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 #=== FUNCTION ================================================================
124 # NAME: check_cmdline_param
125 # PARAMETERS:
126 # RETURNS:
127 # DESCRIPTION:
128 #===============================================================================
129 sub check_cmdline_param () {
130 my $err_config;
131 my $err_counter = 0;
132 if(not defined($cfg_file)) {
133 $cfg_file = "/etc/gosa-si/client.conf";
134 if(! -r $cfg_file) {
135 $err_config = "please specify a config file";
136 $err_counter += 1;
137 }
138 }
139 if( $err_counter > 0 ) {
140 &usage( "", 1 );
141 if( defined( $err_config)) { print STDERR "$err_config\n"}
142 print STDERR "\n";
143 exit( -1 );
144 }
145 }
148 #=== FUNCTION ================================================================
149 # NAME: check_pid
150 # PARAMETERS:
151 # RETURNS:
152 # DESCRIPTION:
153 #===============================================================================
154 sub check_pid {
155 $pid = -1;
156 # Check, if we are already running
157 if( open(LOCK_FILE, "<$pid_file") ) {
158 $pid = <LOCK_FILE>;
159 if( defined $pid ) {
160 chomp( $pid );
161 if( -f "/proc/$pid/stat" ) {
162 my($stat) = `cat /proc/$pid/stat` =~ m/$pid \((.+)\).*/;
163 if( $0 eq $stat ) {
164 close( LOCK_FILE );
165 exit -1;
166 }
167 }
168 }
169 close( LOCK_FILE );
170 unlink( $pid_file );
171 }
173 # create a syslog msg if it is not to possible to open PID file
174 if (not sysopen(LOCK_FILE, $pid_file, O_WRONLY|O_CREAT|O_EXCL, 0644)) {
175 my($msg) = "Couldn't obtain lockfile '$pid_file' ";
176 if (open(LOCK_FILE, '<', $pid_file)
177 && ($pid = <LOCK_FILE>))
178 {
179 chomp($pid);
180 $msg .= "(PID $pid)\n";
181 } else {
182 $msg .= "(unable to read PID)\n";
183 }
184 if( ! ($foreground) ) {
185 openlog( $0, "cons,pid", "daemon" );
186 syslog( "warning", $msg );
187 closelog();
188 }
189 else {
190 print( STDERR " $msg " );
191 }
192 exit( -1 );
193 }
194 }
197 sub sig_int_handler {
198 my ($signal) = @_;
200 daemon_log("shutting down gosa-si-client", 1);
201 system("kill `ps -C gosa-si-client -o pid=`");
202 }
203 $SIG{INT} = \&sig_int_handler;
206 #=== FUNCTION ================================================================
207 # NAME: logging
208 # PARAMETERS: level - string - default 'info'
209 # msg - string -
210 # facility - string - default 'LOG_DAEMON'
211 # RETURNS:
212 # DESCRIPTION:
213 #===============================================================================
214 sub daemon_log {
215 # log into log_file
216 my( $msg, $level ) = @_;
217 if(not defined $msg) { return }
218 if(not defined $level) { $level = 1 }
219 if(defined $log_file){
220 open(LOG_HANDLE, ">>$log_file");
221 chmod 0600, $log_file;
222 if(not defined open( LOG_HANDLE, ">>$log_file" )) {
223 print STDERR "cannot open $log_file: $!";
224 return
225 }
226 chomp($msg);
227 if($level <= $verbose){
228 my ($seconds, $minutes, $hours, $monthday, $month,
229 $year, $weekday, $yearday, $sommertime) = localtime(time);
230 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
231 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
232 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
233 my @monthnames = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
234 $month = $monthnames[$month];
235 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
236 $year+=1900;
238 my $log_msg = "$month $monthday $hours:$minutes:$seconds $prg $msg\n";
239 print LOG_HANDLE $log_msg;
240 if( $foreground ) {
241 print STDERR $log_msg;
242 }
243 }
244 close( LOG_HANDLE );
245 }
246 }
249 #=== FUNCTION ================================================================
250 # NAME: get_mac
251 # PARAMETERS: interface name (i.e. eth0)
252 # RETURNS: (mac address)
253 # DESCRIPTION: Uses ioctl to get mac address directly from system.
254 #===============================================================================
255 sub get_mac {
256 my $ifreq= shift;
257 my $result;
258 if ($ifreq && length($ifreq) > 0) {
259 if($ifreq eq "all") {
260 if(defined($server_ip)) {
261 $result = &get_local_mac_for_remote_ip($server_ip);
262 }
263 elsif ($client_mac_address && length($client_mac_address) > 0 && !($client_mac_address eq "00:00:00:00:00:00")){
264 $result = &client_mac_address;
265 }
266 else {
267 $result = "00:00:00:00:00:00";
268 }
269 } else {
270 my $SIOCGIFHWADDR= 0x8927; # man 2 ioctl_list
272 # A configured MAC Address should always override a guessed value
273 if ($client_mac_address and length($client_mac_address) > 0 and not($client_mac_address eq "00:00:00:00:00:00")) {
274 $result= $client_mac_address;
275 }
276 else {
277 socket SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('ip')
278 or die "socket: $!";
280 if(ioctl SOCKET, $SIOCGIFHWADDR, $ifreq) {
281 my ($if, $mac)= unpack 'h36 H12', $ifreq;
283 if (length($mac) > 0) {
284 $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])$/;
285 $mac= sprintf("%s:%s:%s:%s:%s:%s", $1, $2, $3, $4, $5, $6);
286 $result = $mac;
287 }
288 }
289 }
290 }
291 }
292 return $result;
293 }
297 #=== FUNCTION ================================================================
298 # NAME: get_local_mac_for_remote_ip
299 # PARAMETERS: none (takes server_ip from global variable)
300 # RETURNS: (ip address from interface that is used for communication)
301 # DESCRIPTION: Uses ioctl to get routing table from system, checks which entry
302 # matches (defaultroute last).
303 #===============================================================================
304 sub get_local_mac_for_remote_ip {
305 my $server_ip= shift;
306 my $result= "00:00:00:00:00:00";
308 if($server_ip =~ /^(\d\d?\d?\.){3}\d\d?\d?$/) {
309 my $PROC_NET_ROUTE= ('/proc/net/route');
311 open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
312 or die "Could not open $PROC_NET_ROUTE";
314 my @ifs = <PROC_NET_ROUTE>;
316 close(PROC_NET_ROUTE);
318 # Eat header line
319 shift @ifs;
320 chomp @ifs;
321 foreach my $line(@ifs) {
322 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
323 my $destination;
324 my $mask;
325 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
326 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
327 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
328 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
329 if(new NetAddr::IP($server_ip)->within(new NetAddr::IP($destination, $mask))) {
330 # destination matches route, save mac and exit
331 $result= &get_mac($Iface);
332 last;
333 }
334 }
335 } else {
336 daemon_log("get_local_mac_for_remote_ip was called with a non-ip parameter: $server_ip", 1);
337 }
338 return $result;
339 }
341 sub get_local_ip_for_remote_ip {
342 my $server_ip= shift;
343 my $result="0.0.0.0";
345 if($server_ip =~ /^(\d\d?\d?\.){3}\d\d?\d?$/) {
346 # client should always have a 'valid' ip-address, which is available from other hosts too,
347 # 127.0.0.1 says nothing to foreign host
348 #if($server_ip eq "127.0.0.1") {
349 # $result="127.0.0.1";
350 #} else {
351 my $PROC_NET_ROUTE= ('/proc/net/route');
353 open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
354 or die "Could not open $PROC_NET_ROUTE";
356 my @ifs = <PROC_NET_ROUTE>;
358 close(PROC_NET_ROUTE);
360 # Eat header line
361 shift @ifs;
362 chomp @ifs;
363 foreach my $line(@ifs) {
364 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
365 my $destination;
366 my $mask;
367 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
368 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
369 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
370 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
371 if(new NetAddr::IP($server_ip)->within(new NetAddr::IP($destination, $mask))) {
372 # destination matches route, save mac and exit
373 $result= &get_ip($Iface);
374 last;
375 }
376 }
377 #}
378 } else {
379 daemon_log("get_local_ip_for_remote_ip was called with a non-ip parameter: $server_ip", 1);
380 }
381 return $result;
382 }
385 sub generate_hw_digest {
386 my $hw_data;
387 foreach my $line (split /\n/, `cat /proc/bus/pci/devices`) {
388 $hw_data.= sprintf "%s", $line =~ /[^\s]+\s([^\s]+)\s.*/;
389 }
390 return(md5_base64($hw_data));
391 }
394 sub create_ciphering {
395 my ($passwd) = @_;
396 if((!defined($passwd)) || length($passwd)==0) {
397 $passwd = "";
398 }
399 $passwd = substr(md5_hex("$passwd") x 32, 0, 32);
400 my $iv = substr(md5_hex('GONICUS GmbH'),0, 16);
401 my $my_cipher = Crypt::Rijndael->new($passwd , Crypt::Rijndael::MODE_CBC());
402 $my_cipher->set_iv($iv);
403 return $my_cipher;
404 }
407 sub encrypt_msg {
408 my ($msg, $key) = @_;
409 my $my_cipher = &create_ciphering($key);
410 my $len;
411 {
412 use bytes;
413 $len= 16-length($msg)%16;
414 }
415 $msg = "\0"x($len).$msg;
416 $msg = $my_cipher->encrypt($msg);
417 chomp($msg = &encode_base64($msg));
418 # there are no newlines allowed inside msg
419 $msg=~ s/\n//g;
420 return $msg;
421 }
424 sub decrypt_msg {
426 my ($msg, $key) = @_ ;
427 $msg = &decode_base64($msg);
428 my $my_cipher = &create_ciphering($key);
429 $msg = $my_cipher->decrypt($msg);
430 $msg =~ s/\0*//g;
431 return $msg;
432 }
435 #=== FUNCTION ================================================================
436 # NAME: send_msg_hash_to_target
437 # PARAMETERS: msg_hash - hash - xml_hash created with function create_xml_hash
438 # PeerAddr string - socket address to send msg
439 # PeerPort string - socket port, if not included in socket address
440 # RETURNS: nothing
441 # DESCRIPTION: ????
442 #===============================================================================
443 sub send_msg_hash_to_target {
444 my ($msg_hash, $address, $encrypt_key) = @_ ;
445 my $msg = &create_xml_string($msg_hash);
446 my $header = @{$msg_hash->{'header'}}[0];
447 my $error = &send_msg_to_target($msg, $address, $encrypt_key, $header);
449 return $error;
450 }
453 sub send_msg_to_target {
454 my ($msg, $address, $encrypt_key, $msg_header) = @_ ;
455 my $error = 0;
457 if( $msg_header ) { $msg_header = "'$msg_header'-"; }
458 else { $msg_header = ""; }
460 # encrypt xml msg
461 my $crypted_msg = &encrypt_msg($msg, $encrypt_key);
463 # opensocket
464 my $socket = &open_socket($address);
465 if( !$socket ) {
466 daemon_log("WARNING: cannot send ".$msg_header."msg to $address , host not reachable", 3);
467 if ($REGISTERED == 1) {
468 $REGISTERED = 0; # if server is not available, cause reregistering
469 daemon_log("INFO: cause reregistering at gosa-si-server", 5);
470 $global_kernel->yield('register_at_gosa_si_server');
472 }
473 $error++;
474 }
476 # send xml msg
477 if( $error == 0 ) {
478 print $socket $crypted_msg."\n";
479 daemon_log("INFO: send ".$msg_header."msg to $address", 5);
480 daemon_log("DEBUG: message:\n$msg", 9);
481 }
483 # close socket in any case
484 if( $socket ) {
485 close $socket;
486 }
488 return $error;
489 }
492 sub write_to_file {
493 my ($string, $file) = @_;
494 my $error = 0;
496 if( not defined $file || not -f $file ) {
497 &main::daemon_log("ERROR: $prg: check '-f file' failed: $file", 1);
498 $error++;
499 }
500 if( not defined $string || 0 == length($string)) {
501 &main::daemon_log("ERROR: $prg: empty string to write to file '$file'", 1);
502 $error++;
503 }
505 if( $error == 0 ) {
507 chomp($string);
509 if (open(FILE, ">> $file")){
510 print FILE $string."\n";
511 close(FILE);
512 }
513 }
515 return;
516 }
519 sub open_socket {
520 my ($PeerAddr, $PeerPort) = @_ ;
521 if(defined($PeerPort)){
522 $PeerAddr = $PeerAddr.":".$PeerPort;
523 }
524 my $socket;
525 $socket = new IO::Socket::INET(PeerAddr => $PeerAddr,
526 Porto => "tcp",
527 Type => SOCK_STREAM,
528 Timeout => 5,
529 );
530 if(not defined $socket) {
531 return;
532 }
533 &daemon_log("DEBUG: open_socket: $PeerAddr", 7);
534 return $socket;
535 }
538 #=== FUNCTION ================================================================
539 # NAME: register_at_server
540 # PARAMETERS:
541 # RETURNS:
542 # DESCRIPTION:
543 #===============================================================================
544 sub register_at_gosa_si_server {
545 my ($kernel) = $_[KERNEL];
546 my $try_to_register = 0;
548 # if client is already registered, stop registration process
549 if ($REGISTERED) {
550 $kernel->delay('register_at_gosa_si_server');
552 # client is not registered, start registration process
553 } else {
554 # clear all other triggered events and wait till registration was successful
555 $kernel->delay('trigger_new_key');
557 # create new passwd and ciphering object for client-server communication
558 $server_key = &create_passwd();
560 my $events = join( ",", keys %{$event_hash} );
561 while(1) {
562 $try_to_register++;
564 # after one complete round through all server, stop trying to register
565 if( $try_to_register > @servers ) { last; }
567 # fetch first gosa-si-server from @servers
568 # append shifted gosa-si-server at the end of @servers, so looking for servers never stop if
569 # a registration never occured
570 my $server = shift(@servers);
571 push( @servers, $server );
573 # Check if our ip is resolvable - if not: don't try to register
574 if(!(defined($server) && $server =~ m/^[0-9\.]*?:.*$/)) {
575 &main::daemon_log("ERROR: Server with address '".defined($server)?$server:""."' is invalid!", 1);
576 if (length(@servers) == 1) {
577 &main::daemon_log("ERROR: No valid servers found!", 1);
578 exit(1);
579 }
580 }
582 # Check if our ip is resolvable - if not: don't try to register
583 my $ip= &get_local_ip_for_remote_ip(sprintf("%s", $server =~ /^([0-9\.]*?):.*$/));
584 my $dnsname= gethostbyaddr(inet_aton($ip), AF_INET);
585 if(!defined($dnsname)) {
586 if( defined($client_force_hostname) && $client_force_hostname eq "true") {
587 $dnsname = `hostname`;
588 } else {
589 &write_to_file("goto-error-dns:$ip", $fai_logpath);
590 exit(1);
591 }
592 }
594 # create registration msg
595 my $local_ip = &get_local_ip_for_remote_ip(sprintf("%s", $server =~ /^([0-9\.]*?):.*$/));
596 my $local_mac = &get_local_mac_for_remote_ip(sprintf("%s", $server =~ /^([0-9\.]*?):.*$/));
597 my $register_hash = &create_xml_hash("here_i_am", $local_ip.":".$client_port, $server);
598 &add_content2xml_hash($register_hash, "new_passwd", $server_key);
599 &add_content2xml_hash($register_hash, "mac_address", $local_mac);
600 &add_content2xml_hash($register_hash, "events", $events);
601 &add_content2xml_hash($register_hash, "client_status", $client_status);
602 &add_content2xml_hash($register_hash, "client_revision", $client_revision);
603 &add_content2xml_hash($register_hash, "gotoHardwareChecksum", $gotoHardwareChecksum);
604 &add_content2xml_hash($register_hash, "key_lifetime", $server_key_lifetime);
606 # Add $HOSTNAME from ENV if force-hostname is set
607 if( defined($client_force_hostname) && $client_force_hostname eq "true") {
608 if(defined($ENV{HOSTNAME}) && length($ENV{HOSTNAME}) >0 ) {
609 &add_content2xml_hash($register_hash, "force-hostname", $ENV{HOSTNAME});
610 } else {
611 &main::daemon_log("force-hostname was set to true, but no \$HOSTNAME was found in Environment!",0);
612 }
613 }
615 # send xml hash to server with general server passwd
616 my $res = &send_msg_hash_to_target($register_hash, $server, $default_server_key);
618 # if delivery of registration msg succeed
619 if($res eq "0") {
620 # reset try_to_register
621 $try_to_register = 0;
623 # Set fixed client address and mac address
624 $client_ip= &get_local_ip_for_remote_ip(sprintf("%s", $server =~ /^([0-9\.]*?):.*$/));
625 $client_address= "$client_ip:$client_port";
626 $client_mac_address = $local_mac;
627 $client_dnsname = $dnsname;
628 last;
630 # delivery of registration msg failed
631 } else {
632 # wait 1 sec until trying to register again
633 sleep(1);
634 next;
635 }
637 } # end of while
638 # one circle through all servers finished and no registration succeed
639 if ( $try_to_register >= @servers ) {
640 &write_to_file("gosa-si-no-server-available", $fai_logpath);
641 $kernel->delay_set('register_at_gosa_si_server', $delay_set_time);
643 # delivery of registraion msg succeed, waiting for server response
644 } else {
645 daemon_log("INFO: waiting for msg 'register_at_gosa_si_server'",5);
646 $kernel->delay_set('register_at_gosa_si_server', $delay_set_time);
647 # clear old settings and set it again
648 $kernel->delay('trigger_new_key');
649 $kernel->delay_set('trigger_new_key', $server_key_lifetime);
650 }
652 }
653 return;
654 }
657 sub check_key_and_xml_validity {
658 my ($crypted_msg, $module_key) = @_;
660 my $msg;
661 my $msg_hash;
662 eval{
663 $msg = &decrypt_msg($crypted_msg, $module_key);
664 &main::daemon_log("decrypted_msg: \n$msg", 9);
666 $msg_hash = $xml->XMLin($msg, ForceArray=>1);
668 ##############
669 # check header
670 my $header_l = $msg_hash->{'header'};
671 if( 1 != @{$header_l} ) {
672 die 'no or more headers specified';
673 }
674 my $header = @{$header_l}[0];
675 if( 0 == length $header) {
676 die 'header has length 0';
677 }
679 ##############
680 # check source
681 my $source_l = $msg_hash->{'source'};
682 if( 1 != @{$source_l} ) {
683 die 'no or more than 1 sources specified';
684 }
685 my $source = @{$source_l}[0];
686 if( 0 == length $source) {
687 die 'source has length 0';
688 }
689 unless( $source =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d+$/ ) {
690 die "source '$source' is neither a complete ip-address with port nor 'GOSA'";
691 }
693 ##############
694 # check target
695 my $target_l = $msg_hash->{'target'};
696 if( 1 != @{$target_l} ) {
697 die 'no or more than 1 targets specified ';
698 }
699 my $target = @{$target_l}[0];
700 if( 0 == length $target) {
701 die 'target has length 0 ';
702 }
703 unless( $target =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d+$/ ){
704 die "source is neither a complete ip-address with port nor 'GOSA'";
705 }
706 };
707 if($@) {
708 &main::daemon_log("WARNING: do not understand the message or msg is not gosa-si envelope conform:", 5);
709 &main::daemon_log("$@", 8);
710 $msg = undef;
711 $msg_hash = undef;
712 }
714 return ($msg, $msg_hash);
715 }
718 sub check_outgoing_xml_validity {
719 my ($msg) = @_;
721 my $msg_hash;
722 eval{
723 $msg_hash = $xml->XMLin($msg, ForceArray=>1);
725 ##############
726 # check header
727 my $header_l = $msg_hash->{'header'};
728 if( 1 != @{$header_l} ) {
729 die 'no or more than one headers specified';
730 }
731 my $header = @{$header_l}[0];
732 if( 0 == length $header) {
733 die 'header has length 0';
734 }
736 ##############
737 # check source
738 my $source_l = $msg_hash->{'source'};
739 if( 1 != @{$source_l} ) {
740 die 'no or more than 1 sources specified';
741 }
742 my $source = @{$source_l}[0];
743 if( 0 == length $source) {
744 die 'source has length 0';
745 }
746 unless( $source =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d+$/ ||
747 $source =~ /^GOSA$/i ) {
748 die "source '$source' is neither a complete ip-address with port";
749 }
751 ##############
752 # check target
753 my $target_l = $msg_hash->{'target'};
754 if( 1 != @{$target_l} ) {
755 die "no or more than one targets specified";
756 }
757 foreach my $target (@$target_l) {
758 if( 0 == length $target) {
759 die "target has length 0";
760 }
761 unless( $target =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d+$/ ) {
762 die "target '$target' is not a complete ip-address with port or a valid target name";
763 }
764 }
765 };
766 if($@) {
767 daemon_log("WARNING: outgoing msg is not gosa-si envelope conform", 5);
768 daemon_log("$@ $msg", 8);
769 $msg_hash = undef;
770 }
771 return ($msg_hash);
772 }
775 sub trigger_new_key {
776 my ($kernel) = $_[KERNEL] ;
778 my $msg = "<xml><header>new_key</header><source>$client_address</source><target>$client_address</target></xml>";
779 &send_msg_to_target($msg, $client_address, $server_key, 'new_key');
781 $kernel->delay_set('trigger_new_key', $server_key_lifetime);
782 }
785 sub trigger_logged_in_users_report {
786 my ($kernel) = $_[KERNEL] ;
788 # just do if client is registered already
789 if( $REGISTERED ) {
790 my $result = qx(/usr/bin/users);
791 my @logged_in_user_list;
792 if( defined $result ) {
793 chomp($result);
794 @logged_in_user_list = split(/\s/, $result);
795 }
797 system("echo 'CURRENTLY_LOGGED_IN ".join(" ", @logged_in_user_list)."' > /var/run/gosa-si-client.socket");
798 $kernel->delay_set('trigger_logged_in_users_report', $trigger_logged_in_users_report_delay);
799 } else {
800 # try it in 10 sec again
801 $kernel->delay_set('trigger_logged_in_users_report', 10);
802 }
803 }
806 sub generic_file_error {
807 my ( $heap, $operation, $errno, $error_string, $wheel_id ) =
808 @_[ HEAP, ARG0, ARG1, ARG2, ARG3 ];
810 my $service = $heap->{services}->{$wheel_id};
811 daemon_log("ERROR: '$service' watcher $operation error $errno: $error_string", 1);
812 daemon_log("ERROR: shutting down '$service' file watcher", 1);
814 delete $heap->{services}->{$wheel_id};
815 delete $heap->{watchers}->{$wheel_id};
816 return;
817 }
820 sub fifo_got_record {
821 my $file_record = $_[ARG0];
822 my $header;
823 my $content = "";
824 daemon_log("DEBUG: fifo got record: $file_record", 7);
826 $file_record =~ /^(\S+)[ ]?([\s\S]+)?$/;
827 if( defined $1 ) {
828 $header = $1;
829 } else {
830 return;
831 }
833 if( defined $2 ) {
834 $content = $2;
835 }
837 my $clmsg_hash = &create_xml_hash("CLMSG_$header", $client_address, $server_address, $content);
838 &add_content2xml_hash($clmsg_hash, "macaddress", $client_mac_address);
839 my $clmsg = &create_xml_string($clmsg_hash);
840 &send_msg_to_target($clmsg, $server_address, $server_key, "CLMSG_$header");
842 # if installation finished, save all log files
843 if ($file_record eq "TASKBEGIN finish") {
844 &save_fai_log($fai_log_dir);
845 }
847 return;
848 }
851 sub save_fai_log {
852 my ($fai_log_dir) = @_ ;
853 my $FAI_DIR;
855 opendir($FAI_DIR, $fai_log_dir);
856 if (not defined $FAI_DIR) {
857 daemon_log("ERROR: can not open directory $fai_log_dir: $!", 1);
858 return;
859 }
861 my @log_files = readdir($FAI_DIR);
862 closedir($FAI_DIR);
863 my @log_list;
865 foreach my $log_file (@log_files) {
866 if( $log_file eq "." || $log_file eq ".." ) { next; }
867 my $log = "log_file:$log_file:";
868 $log_file = File::Spec->catfile( $fai_log_dir, $log_file );
869 open(my $FILE, "<$log_file");
870 if (not defined $FILE ) {
871 daemon_log("ERROR: can not open '$log_file': $!", 1);
872 next;
873 }
874 my @lines = <$FILE>;
875 my $log_string = join("", @lines);
876 $log .= &encode_base64($log_string);
877 push(@log_list, $log);
878 close ($FILE);
879 }
881 my $all_log_string = join("\n", @log_list);
882 my $msg_hash = &create_xml_hash("CLMSG_save_fai_log", $client_address, $server_address, $all_log_string);
883 &add_content2xml_hash($msg_hash, "macaddress", $client_mac_address);
884 my $msg = &create_xml_string($msg_hash);
885 &send_msg_to_target($msg, $server_address, $server_key, "CLMSG_save_fai_log");
887 }
890 sub sig_handler {
891 my ($kernel, $signal) = @_[KERNEL, ARG0] ;
892 daemon_log("0 INFO got signal '$signal'", 1);
893 $kernel->sig_handled();
894 return;
895 }
898 sub _start {
899 my ($kernel, $heap) = @_[KERNEL, HEAP];
900 $kernel->alias_set('client_session');
901 $global_kernel = $kernel; # this is used to throw events at each point of the skript
903 $kernel->sig(USR1 => "sig_handler");
905 # force a registration at a gosa-si-server
906 $kernel->yield('register_at_gosa_si_server');
908 # install all file watcher defined
909 while( my($name, $file) = each %files_to_watch ) {
910 my $watcher = POE::Wheel::FollowTail->new(
911 Filename => $file,
912 InputEvent => $name."_record",
913 # ResetEvent => "file_reset",
914 ErrorEvent => "file_error",
915 );
916 # $heap->{tail} = POE::Wheel::Run->new(
917 # Program => [ "/usr/bin/tail", "-f", $file ],
918 # StdoutEvent => $file_name."_record",
919 # );
920 $heap->{services}->{ $watcher->ID } = $name;
921 $heap->{watchers}->{ $watcher->ID } = $watcher;
922 }
923 $kernel->yield('trigger_logged_in_users_report');
924 }
927 sub _default {
928 daemon_log("ERROR: can not handle incoming msg with header '$_[ARG0]'", 1);
929 return;
930 }
933 sub server_input {
934 my ($kernel, $heap, $input, $wheel) = @_[KERNEL, HEAP, ARG0, ARG1];
935 my $remote_ip = $heap->{'remote_ip'},
936 my $error = 0;
937 my $answer;
940 daemon_log("INFO: Incoming msg from '$remote_ip'", 5);
941 daemon_log("DEBUG: Incoming msg:\n$input\n", 9);
943 my ($msg, $msg_hash) = &check_key_and_xml_validity($input, $server_key);
944 if( (!$msg) || (!$msg_hash) ) {
945 daemon_log("WARNING: Deciphering of incoming msg failed", 3);
946 if($server_address =~ /$remote_ip/) {
947 # got a msg from gosa-si-server which can not be decrypted, may the secrete not up-to-date
948 # cause a reregistering with a new secrete handshake
949 daemon_log("WARNING: Message from gosa-si-server could not be understood, cause reregistering at server", 3);
951 # if client is alread in a registration process, that means not registered, do nothing
952 # if not, cause re-registration
953 if (not $REGISTERED) {
954 &daemon_log("WARNING: gosa-si-client is already in a registration process so ignore this message", 3);
955 } else {
956 $REGISTERED = 0;
957 $kernel->post('client_session', 'register_at_gosa_si_server');
958 }
959 }
960 $error++;
961 }
964 ######################
965 # process incoming msg
966 if( $error == 0 ) {
967 my $header = @{$msg_hash->{header}}[0];
968 my $source = @{$msg_hash->{source}}[0];
970 if( exists $event_hash->{$header} ) {
972 # a event exists with the header as name
973 daemon_log("INFO: found event '$header' at event-module '".$event_hash->{$header}."'", 5);
974 no strict 'refs';
975 $answer = &{$event_hash->{$header}."::$header"}($msg, $msg_hash);
976 }
977 else {
978 daemon_log("WARNING: no event '$header' found in event modules under $event_dir", 3);
979 }
980 }
982 ########
983 # answer
984 if( $answer ) {
986 #check gosa-si envelope validity
987 my $answer_hash = &check_outgoing_xml_validity($answer);
989 if( $answer_hash ) {
990 # answer is valid
992 # preprocessing
993 if( $answer =~ "<header>registered</header>") {
994 # set registered flag to true to stop sending further registered msgs
995 $REGISTERED = 1;
996 }
997 else {
998 $answer =~ /<header>(\S+)<\/header>/;
999 &send_msg_to_target($answer, $server_address, $server_key, $1);
1000 }
1002 # postprocessing
1003 if( $answer =~ "<header>new_key</header>") {
1004 # set new key to global variable
1005 $answer =~ /<new_key>(\S*?)<\/new_key>/;
1006 my $new_key = $1;
1007 $server_key = $new_key;
1008 }
1009 }
1011 }
1013 return;
1014 }
1017 #==== MAIN = main ==============================================================
1018 # parse commandline options
1019 Getopt::Long::Configure( "bundling" );
1020 GetOptions("h|help" => \&usage,
1021 "c|config=s" => \$cfg_file,
1022 "f|foreground" => \$foreground,
1023 "v|verbose+" => \$verbose,
1024 );
1026 # read and set config parameters
1027 &check_cmdline_param ;
1028 &read_configfile($cfg_file, %cfg_defaults);
1029 &check_pid;
1032 # forward error messages to logfile
1033 if ( ! $foreground ) {
1034 open( STDIN, '+>/dev/null' );
1035 open( STDOUT, '+>&STDIN' );
1036 open( STDERR, '+>&STDIN' );
1037 }
1039 # Just fork, if we are not in foreground mode
1040 if( ! $foreground ) {
1041 chdir '/' or die "Can't chdir to /: $!";
1042 $pid = fork;
1043 setsid or die "Can't start a new session: $!";
1044 umask 0;
1045 } else {
1046 $pid = $$;
1047 }
1049 # Do something useful - put our PID into the pid_file
1050 if( 0 != $pid ) {
1051 open( LOCK_FILE, ">$pid_file" );
1052 print LOCK_FILE "$pid\n";
1053 close( LOCK_FILE );
1054 if( !$foreground ) {
1055 exit( 0 )
1056 };
1057 }
1059 # parse head url and revision from svn
1060 my $client_status_hash = { 'developmental'=>'revision', 'stable'=>'release'};
1061 $client_version =~ /^\$HeadURL: (\S+) \$:\$Rev: (\d+) \$$/;
1062 $client_headURL = defined $1 ? $1 : 'unknown' ;
1063 $client_revision = defined $2 ? $2 : 'unknown' ;
1064 if ($client_headURL =~ /\/tag\// ||
1065 $client_headURL =~ /\/branches\// ) {
1066 $client_status = "stable";
1067 } else {
1068 $client_status = "developmental" ;
1069 }
1071 daemon_log(" ", 1);
1072 daemon_log("$prg started!", 1);
1073 daemon_log("INFO: status: $client_status", 1);
1074 daemon_log("INFO: ".$client_status_hash->{$client_status}.": $client_revision", 1);
1076 # delete old DBsqlite lock files
1077 system('rm -f /tmp/gosa_si_lock*gosa-si-client*');
1079 # detect ip and mac address and complete host address
1080 $client_address = $client_ip.":".$client_port;
1081 my $network_interface= &get_interface_for_ip($client_ip);
1082 $client_mac_address= &get_mac($network_interface);
1083 daemon_log("INFO: ip address detected: $client_ip", 1);
1084 daemon_log("INFO: gosa-si-client mac address detected: $client_mac_address", 1);
1087 # import events
1088 my ($error, $result, $tmp_hash) = &import_events($event_dir);
1089 $event_hash = $tmp_hash;
1091 foreach my $log_line (@$result) {
1092 if ($log_line =~ / succeed: /) {
1093 &main::daemon_log("0 DEBUG: $log_line", 7);
1094 } else {
1095 &main::daemon_log("0 ERROR: $log_line", 1);
1096 }
1097 }
1100 # compute hardware checksum
1101 $gotoHardwareChecksum= &generate_hw_digest();
1102 daemon_log("INFO: gotoHardwareChecksum detected: $gotoHardwareChecksum", 1);
1105 # create socket for incoming xml messages
1106 POE::Component::Server::TCP->new(
1107 Alias => 'gosa-si-client',
1108 Port => $client_port,
1109 ClientInput => \&server_input,
1110 );
1111 daemon_log("INFO: start socket for incoming xml messages at port '$client_port' ", 1);
1114 # prepare variables
1115 if( inet_aton($server_ip) ){ $server_ip = inet_ntoa(inet_aton($server_ip)); }
1116 if (defined $server_ip && defined $server_port) {
1117 $server_address = $server_ip.":".$server_port;
1118 }
1119 $xml = new XML::Simple();
1120 $default_server_key = $server_key;
1123 # add gosa-si-server address from config file at first position of server list
1124 my $server_check_cfg = Config::IniFiles->new( -file => $cfg_file );
1125 my $server_check = (defined($server_check_cfg))?$server_check_cfg->val( "server", "ip"):undef;
1126 if( defined $server_check ) {
1127 unshift(@servers, $server_address);
1128 my $servers_string = join(", ", @servers);
1129 daemon_log("INFO: found servers in configuration file: $servers_string", 5);
1130 } else {
1131 my @tmp_servers;
1132 if ( !$server_domain) {
1133 # Try our DNS Searchlist
1134 for my $domain(get_dns_domains()) {
1135 chomp($domain);
1136 my @tmp_domains= &get_server_addresses($domain);
1137 if(@tmp_domains) {
1138 for my $tmp_server(@tmp_domains) {
1139 push @tmp_servers, $tmp_server;
1140 }
1141 }
1142 }
1143 if(@tmp_servers && length(@tmp_servers)==0) {
1144 daemon_log("ERROR: please specify a gosa-si-server address or a domain in config file", 1);
1145 kill 2, $$;
1146 }
1147 } else {
1148 @tmp_servers = &get_server_addresses($server_domain);
1149 if( 0 == @tmp_servers ) {
1150 daemon_log("ERROR: no gosa-si-server found in DNS for domain '$server_domain'",1);
1151 daemon_log("ERROR: please specify a gosa-si-server address or a domain in config file", 1);
1152 kill 2, $$;
1153 }
1154 }
1156 foreach my $server (@tmp_servers) {
1157 unshift(@servers, $server);
1158 }
1159 my $servers_string = join(", ", @servers);
1160 daemon_log("INFO: found servers in DNS: $servers_string", 5);
1161 }
1164 # open fifo for non-gosa-si-client-msgs to gosa-si-server
1165 POSIX::mkfifo("$gosa_si_client_fifo", "0600");
1168 POE::Session->create(
1169 inline_states => {
1170 _start => \&_start,
1171 _default => \&_default,
1172 sig_handler => \&sig_handler,
1173 register_at_gosa_si_server => \®ister_at_gosa_si_server,
1175 # trigger periodical tasks
1176 trigger_new_key => \&trigger_new_key,
1177 trigger_logged_in_users_report => \&trigger_logged_in_users_report,
1179 # handle records from each defined file differently
1180 fifo_record => \&fifo_got_record,
1182 # handle file resets and errors the same way for each file
1183 file_reset => \&generic_file_reset,
1184 file_error => \&generic_file_error,
1185 }
1186 );
1188 POE::Kernel->run();
1189 exit;