1 #!/usr/bin/perl
2 #===============================================================================
3 #
4 # FILE: gosa-si-client
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 Crypt::Rijndael;
32 use GOSA::GosaSupportDaemon;
33 use Digest::MD5 qw(md5_hex md5 md5_base64);
34 use MIME::Base64;
35 use XML::Simple;
36 use File::Basename;
37 use File::Spec;
38 use Net::ARP;
39 use Fcntl;
41 # Workaround: need pure perl to make it work with UTF-8 :-(
42 $XML::Simple::PREFERRED_PARSER= "XML::SAX::PurePerl";
44 my $client_version = '$HeadURL$:$Rev$';
46 my $client_headURL;
47 my $client_revision;
48 my $client_status;
49 my $event_dir = "/usr/lib/gosa-si/client/events";
50 use lib "/usr/lib/gosa-si/client/events";
52 my (%cfg_defaults, $foreground, $verbose, $pid_file, $procid, $pid, $log_file, $fai_logpath);
53 my ($server_ip, $server_port, $server_timeout, $server_domain, $server_key_lifetime);
54 my ($client_port, $ldap_enabled, $ldap_config, $pam_config, $nss_config);
55 my ($root_uid, $adm_gid);
56 my $xml;
57 my $event_hash;
58 my $default_server_key;
59 my @servers;
60 my $gotoHardwareChecksum;
61 my $system_com;
62 my $servers_string;
63 $verbose= 1;
65 # globalise variables which are used in imported events
66 our $global_kernel;
67 our $cfg_file;
68 our $opts_file;
69 our $server_address;
70 our $client_address;
71 our $client_ip;
72 our $client_mac_address;
73 our $client_dnsname;
74 our $client_force_hostname;
75 our $server_key;
76 our $terminal_server_hash;
77 our $opts_dnslookup;
80 # default variables
81 my $REGISTERED = 0;
83 # path to fifo for non-gosa-si-client messages to gosa-si-server
84 my $fai_com_fifo = "/var/run/gosa-si-client.socket";
85 my $system_com_fifo = "/var/run/gosa-si-client-system-com.socket";
86 my %files_to_watch = (fai_fifo => $fai_com_fifo, system_fifo => $system_com_fifo);
88 # in function register_at_gosa_si_server, after which period of seconds a new registration should be tried if a registration was
89 # not successful until now
90 my $delay_set_time = 10;
91 our $prg= basename($0);
93 # all n seconds the client reports logged_in users to gosa-si-server
94 my $trigger_logged_in_users_report_delay = 600;
96 # all n seconds the client reports messages seen by user
97 my $trigger_seen_messages_delay = 30;
99 # directory where all log files from installation are stored
100 my $fai_log_dir = "/var/log/fai";
102 %cfg_defaults = (
103 "general" =>
104 {"log-file" => [\$log_file, "/var/run/".$prg.".log"],
105 "pid-file" => [\$pid_file, "/var/run/".$prg.".pid"],
106 "opts-file" => [\$opts_file, "/var/run/".$prg.".opts"],
107 },
108 "client" =>
109 {"port" => [\$client_port, "20083"],
110 "ip" => [\$client_ip, "0.0.0.0"],
111 "mac-address" => [\$client_mac_address, "00:00:00:00:00:00"],
112 "server-domain" => [\$server_domain, ""],
113 "ldap" => [\$ldap_enabled, 1],
114 "ldap-config" => [\$ldap_config, "/etc/ldap/ldap.conf"],
115 "pam-config" => [\$pam_config, "/etc/pam_ldap.conf"],
116 "nss-config" => [\$nss_config, "/etc/libnss-ldap.conf"],
117 "fai-logpath" => [\$fai_logpath, "/var/log/fai/fai.log"],
118 "force-hostname" => [\$client_force_hostname, "false"],
119 "system-com" => [\$system_com, "disabled"],
120 },
121 "server" => {
122 "ip" => [\$servers_string, "127.0.0.1"],
123 "port" => [\$server_port, "20081"],
124 "key" => [\$server_key, ""],
125 "timeout" => [\$server_timeout, 10],
126 "key-lifetime" => [\$server_key_lifetime, 600],
127 "dns-lookup" => [\$opts_dnslookup, "true"],
128 },
130 );
133 #=== FUNCTIONS = functions =====================================================
135 sub usage {
136 print STDERR << "EOF" ;
137 usage: $prg [-hvf] [-c config]
139 -h : this (help) message
140 -c <file> : config file
141 -f : foreground, process will not be forked to background
142 -v : be verbose (multiple to increase verbosity)
144 EOF
145 print "\n" ;
146 }
148 #=== FUNCTION ================================================================
149 # NAME: check_cmdline_param
150 # PARAMETERS:
151 # RETURNS:
152 # DESCRIPTION:
153 #===============================================================================
154 sub check_cmdline_param () {
155 my $err_config;
156 my $err_counter = 0;
157 if(not defined($cfg_file)) {
158 $cfg_file = "/etc/gosa-si/client.conf";
159 if(! -r $cfg_file) {
160 $err_config = "please specify a config file";
161 $err_counter += 1;
162 }
163 }
164 if( $err_counter > 0 ) {
165 &usage( "", 1 );
166 if( defined( $err_config)) { print STDERR "$err_config\n"}
167 print STDERR "\n";
168 exit( -1 );
169 }
170 }
173 #=== FUNCTION ================================================================
174 # NAME: check_pid
175 # PARAMETERS:
176 # RETURNS:
177 # DESCRIPTION:
178 #===============================================================================
179 sub check_pid {
180 $pid = -1;
181 # Check, if we are already running
182 if( open(my $LOCK_FILE, "<","$pid_file") ) {
183 $pid = <$LOCK_FILE>;
184 if( defined $pid ) {
185 chomp( $pid );
186 if( -f "/proc/$pid/stat" ) {
187 my($stat) = `cat /proc/$pid/stat` =~ m/$pid \((.+)\).*/;
188 if( $0 eq $stat ) {
189 close($LOCK_FILE);
190 exit -1;
191 }
192 }
193 }
194 close( $LOCK_FILE );
195 unlink( $pid_file );
196 }
198 # create a syslog msg if it is not to possible to open PID file
199 if (not sysopen(LOCK_FILE, $pid_file, O_WRONLY|O_CREAT|O_EXCL, 0644)) {
200 my($msg) = "Couldn't obtain lockfile '$pid_file' ";
201 if (open(my $LOCK_FILE, '<', $pid_file)
202 && ($pid = <$LOCK_FILE>))
203 {
204 chomp($pid);
205 $msg .= "(PID $pid)\n";
206 } else {
207 $msg .= "(unable to read PID)\n";
208 }
209 if( ! ($foreground) ) {
210 openlog( $0, "cons,pid", "daemon" );
211 syslog( "warning", $msg );
212 closelog();
213 }
214 else {
215 print( STDERR " $msg " );
216 }
217 exit( -1 );
218 }
219 }
222 sub sig_int_handler {
223 my ($signal) = @_;
225 daemon_log("shutting down gosa-si-client", 1);
226 system("kill `ps -C gosa-si-client -o pid=`");
227 }
228 $SIG{INT} = \&sig_int_handler;
231 #=== FUNCTION ================================================================
232 # NAME: logging
233 # PARAMETERS: level - string - default 'info'
234 # msg - string -
235 # facility - string - default 'LOG_DAEMON'
236 # RETURNS:
237 # DESCRIPTION:
238 #===============================================================================
239 sub daemon_log {
240 # log into log_file
241 my( $msg, $level ) = @_;
242 if(not defined $msg) { return }
243 if(not defined $level) { $level = 1 }
244 if(defined $log_file){
245 my $open_log_fh = sysopen(LOG_HANDLE, $log_file, O_WRONLY | O_CREAT | O_APPEND , 0440);
246 if(not $open_log_fh) {
247 print STDERR "cannot open $log_file: $!";
248 return;
249 }
250 # check owner and group of log_file and update settings if necessary
251 my ($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size, $atime, $mtime, $ctime, $blksize, $blocks) = stat($log_file);
252 if((not $uid eq $root_uid) || (not $gid eq $adm_gid)) {
253 chown($root_uid, $adm_gid, $log_file);
254 }
256 chomp($msg);
257 if($level <= $verbose){
258 my ($seconds, $minutes, $hours, $monthday, $month,
259 $year, $weekday, $yearday, $sommertime) = localtime(time);
260 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
261 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
262 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
263 my @monthnames = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
264 $month = $monthnames[$month];
265 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
266 $year+=1900;
268 # Microseconds since epoch
269 my $microSeconds = sprintf("%.2f", &Time::HiRes::clock_gettime());
270 $microSeconds =~ s/^\d*(.\d\d)$/$1/;
273 my $log_msg = "$month $monthday $hours:$minutes:$seconds$microSeconds $prg $msg\n";
274 print LOG_HANDLE $log_msg;
275 if( $foreground ) {
276 print STDERR $log_msg;
277 }
278 }
279 close( LOG_HANDLE );
280 }
281 }
284 #=== FUNCTION ================================================================
285 # NAME: get_mac
286 # PARAMETERS: interface name (i.e. eth0)
287 # RETURNS: (mac address)
288 # DESCRIPTION: Uses ioctl to get mac address directly from system.
289 #===============================================================================
290 sub get_mac {
291 my $ifreq= shift;
292 my $result;
293 if ($ifreq && length($ifreq) > 0) {
294 if($ifreq eq "all") {
295 if(defined($server_ip)) {
296 $result = &get_local_mac_for_remote_ip($server_ip);
297 }
298 elsif ($client_mac_address && length($client_mac_address) > 0 && !($client_mac_address eq "00:00:00:00:00:00")){
299 $result = &client_mac_address;
300 }
301 else {
302 $result = "00:00:00:00:00:00";
303 }
304 } else {
305 # A configured MAC Address should always override a guessed value
306 if ($client_mac_address and length($client_mac_address) > 0 and not($client_mac_address eq "00:00:00:00:00:00")) {
307 $result= $client_mac_address;
308 }
309 else {
310 $result = Net::ARP::get_mac($ifreq);
311 }
312 }
313 }
314 return $result;
315 }
319 #=== FUNCTION ================================================================
320 # NAME: get_local_mac_for_remote_ip
321 # PARAMETERS: none (takes server_ip from global variable)
322 # RETURNS: (ip address from interface that is used for communication)
323 # DESCRIPTION: Uses ioctl to get routing table from system, checks which entry
324 # matches (defaultroute last).
325 #===============================================================================
326 sub get_local_mac_for_remote_ip {
327 my $server_ip= shift;
328 my $result= "00:00:00:00:00:00";
330 if($server_ip =~ /^[a-z][a-z0-9\.]+/i) {
331 my $ip_address = inet_ntoa(scalar gethostbyname($server_ip));
332 if(defined($ip_address) && $ip_address =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/) {
333 # Write ip address to $server_ip variable
334 $server_ip = $ip_address;
335 }
336 }
338 if($server_ip =~ /^(\d\d?\d?\.){3}\d\d?\d?$/) {
339 my $PROC_NET_ROUTE= ('/proc/net/route');
341 open(my $PROC_NET_ROUTE, "<","$PROC_NET_ROUTE")
342 or die "Could not open $PROC_NET_ROUTE";
344 my @ifs = <$PROC_NET_ROUTE>;
346 close($PROC_NET_ROUTE);
348 # Eat header line
349 shift @ifs;
350 chomp @ifs;
351 foreach my $line(@ifs) {
352 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
353 my $destination;
354 my $mask;
355 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
356 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
357 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
358 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
359 if(new NetAddr::IP($server_ip)->within(new NetAddr::IP($destination, $mask))) {
360 # destination matches route, save mac and exit
361 $result= &get_mac($Iface);
362 last;
363 }
364 }
365 } else {
366 daemon_log("get_local_mac_for_remote_ip was called with a non-ip parameter: $server_ip", 1);
367 }
368 return $result;
369 }
372 sub generate_hw_digest {
373 my $hw_data;
374 foreach my $line (split /\n/, `cat /proc/bus/pci/devices`) {
375 $hw_data.= sprintf "%s", $line =~ /[^\s]+\s([^\s]+)\s.*/;
376 }
377 # linux-vserver has no /proc/bus/pci/devices
378 if ( !$hw_data ) {
379 foreach my $line (split /\n/, `ifconfig | grep HWaddr`) {
380 $hw_data.= sprintf "%s", $line =~ /[^\s]+\s([^\s]+)\s.*/;
381 }
382 }
383 return(md5_base64($hw_data));
384 }
387 sub create_ciphering {
388 my ($passwd) = @_;
389 if((!defined($passwd)) || length($passwd)==0) {
390 $passwd = "";
391 }
392 $passwd = substr(md5_hex("$passwd") x 32, 0, 32);
393 my $iv = substr(md5_hex('GONICUS GmbH'),0, 16);
394 my $my_cipher = Crypt::Rijndael->new($passwd , Crypt::Rijndael::MODE_CBC());
395 $my_cipher->set_iv($iv);
396 return $my_cipher;
397 }
400 sub encrypt_msg {
401 my ($msg, $key) = @_;
402 my $my_cipher = &create_ciphering($key);
403 my $len;
404 {
405 use bytes;
406 $len= 16-length($msg)%16;
407 }
408 $msg = "\0"x($len).$msg;
409 $msg = $my_cipher->encrypt($msg);
410 chomp($msg = &encode_base64($msg));
411 # there are no newlines allowed inside msg
412 $msg=~ s/\n//g;
413 return $msg;
414 }
417 sub decrypt_msg {
419 my ($msg, $key) = @_ ;
420 $msg = &decode_base64($msg);
421 my $my_cipher = &create_ciphering($key);
422 $msg = $my_cipher->decrypt($msg);
423 $msg =~ s/\0*//g;
424 return $msg;
425 }
428 #=== FUNCTION ================================================================
429 # NAME: send_msg_hash_to_target
430 # PARAMETERS: msg_hash - hash - xml_hash created with function create_xml_hash
431 # PeerAddr string - socket address to send msg
432 # PeerPort string - socket port, if not included in socket address
433 # RETURNS: nothing
434 # DESCRIPTION: ????
435 #===============================================================================
436 sub send_msg_hash_to_target {
437 my ($msg_hash, $address, $encrypt_key) = @_ ;
438 my $msg = &create_xml_string($msg_hash);
439 my $header = @{$msg_hash->{'header'}}[0];
440 my $error = &send_msg_to_target($msg, $address, $encrypt_key, $header);
442 return $error;
443 }
445 sub _setREGISTERED {
446 my $newStatus = shift;
447 &daemon_log("DEBUG: set REGISTERED flag from '$REGISTERED' to '$newStatus'", 7);
448 $REGISTERED = $newStatus;
449 return;
450 }
452 sub send_msg_to_target {
453 my ($msg, $address, $encrypt_key, $msg_header) = @_ ;
454 my $error = 0;
456 if( $msg_header ) { $msg_header = "'$msg_header'-"; }
457 else { $msg_header = ""; }
459 # Memorize own source address
460 $msg =~ /<source>(\S+)<\/source>/;
461 my $own_source_address = $1;
463 # encrypt xml msg
464 my $crypted_msg = &encrypt_msg($msg, $encrypt_key);
466 # opensocket
467 my $socket = &open_socket($address);
468 if( !$socket ) {
469 daemon_log("WARNING: cannot send ".$msg_header."msg to '$address', host not reachable", 3);
470 if ($REGISTERED == 1) {
471 &_setREGISTERED(0); # if server is not available, cause reregistering
472 daemon_log("INFO: cause reregistering at gosa-si-server", 5);
473 $global_kernel->post('client_session', 'register_at_gosa_si_server');
475 }
476 $error++;
477 }
479 # send xml msg
480 if( $error == 0 ) {
481 print $socket $crypted_msg.";$own_source_address\n";
482 daemon_log("INFO: send ".$msg_header."msg to $address", 5);
483 daemon_log("DEBUG: message:\n$msg", 9);
484 }
486 # close socket in any case
487 if( $socket ) {
488 close $socket;
489 }
491 return $error;
492 }
495 sub write_to_file {
496 my ($string, $file) = @_;
497 my $error = 0;
499 if( not defined $file || not -f $file ) {
500 &main::daemon_log("ERROR: $prg: check '-f file' failed: $file", 1);
501 $error++;
502 }
503 if( not defined $string || 0 == length($string)) {
504 &main::daemon_log("ERROR: $prg: empty string to write to file '$file'", 1);
505 $error++;
506 }
508 if( $error == 0 ) {
510 chomp($string);
512 if (open(my $FILE, ">>", "$file")){
513 print $FILE $string."\n";
514 close($FILE);
515 }
516 }
518 return;
519 }
522 sub open_socket {
523 my ($PeerAddr, $PeerPort) = @_ ;
524 if(defined($PeerPort)){
525 $PeerAddr = $PeerAddr.":".$PeerPort;
526 }
527 my $socket;
528 $socket = new IO::Socket::INET(PeerAddr => $PeerAddr,
529 Porto => "tcp",
530 Type => SOCK_STREAM,
531 Timeout => 5,
532 );
533 if(not defined $socket) {
534 return;
535 }
536 &daemon_log("DEBUG: open_socket: $PeerAddr", 7);
537 return $socket;
538 }
541 #=== FUNCTION ================================================================
542 # NAME: register_at_server
543 # PARAMETERS:
544 # RETURNS:
545 # DESCRIPTION:
546 #===============================================================================
547 sub register_at_gosa_si_server {
548 my ($kernel) = $_[KERNEL];
549 my $try_to_register = 0;
551 if ($REGISTERED) {
552 # Client is already registered, clear all other registration events
553 $kernel->delay('register_at_gosa_si_server');
554 } else {
555 # Client is not registered, start registration process
556 # Clear all other events and wait till registration was successful
557 $kernel->delay('register_at_gosa_si_server');
558 $kernel->delay('trigger_new_key');
560 # Create new passwd and ciphering object for client-server communication
561 $server_key = &create_passwd();
563 my $events = join( ",", keys %{$event_hash} );
564 while(1) {
565 $try_to_register++;
567 # after one complete round through all server, stop trying to register
568 if( $try_to_register > @servers ) { last; }
570 # fetch first gosa-si-server from @servers
571 # append shifted gosa-si-server at the end of @servers, so looking for servers never stop if
572 # a registration never occured
573 my $server = shift(@servers);
574 push( @servers, $server );
576 # Check if $server is a valid server address
577 if(!(defined($server) && $server =~ m/^[0-9\.]*?:.*$/)) {
578 &main::daemon_log("ERROR: Server with address '".defined($server)?$server:""."' is invalid!", 1);
579 if (length(@servers) == 1) {
580 &main::daemon_log("ERROR: No valid servers found!", 1);
581 exit(1);
582 }
583 }
585 # Check if our ip is resolvable - if not: don't try to register
586 my $ip= &get_local_ip_for_remote_ip(sprintf("%s", $server =~ /^([0-9\.]*?):.*$/));
587 my $dnsname= gethostbyaddr(inet_aton($ip), AF_INET);
588 if(!defined($dnsname)) {
589 if( defined($client_force_hostname) && $client_force_hostname eq "true") {
590 $dnsname = `hostname`;
591 } else {
592 &write_to_file("goto-error-dns:$ip", $fai_logpath);
593 &main::daemon_log("ERROR: ip is not resolvable, no registration possible. Write 'goto-error-dns:$ip' to $fai_logpath", 1);
594 exit(1);
595 }
596 }
598 # create registration msg
599 my $local_ip = &get_local_ip_for_remote_ip(sprintf("%s", $server =~ /^([0-9\.]*?):.*$/));
600 my $local_mac = &get_local_mac_for_remote_ip(sprintf("%s", $server =~ /^([0-9\.]*?):.*$/));
601 my $register_hash = &create_xml_hash("here_i_am", $local_ip.":".$client_port, $server);
602 &add_content2xml_hash($register_hash, "new_passwd", $server_key);
603 &add_content2xml_hash($register_hash, "mac_address", $local_mac);
604 &add_content2xml_hash($register_hash, "events", $events);
605 &add_content2xml_hash($register_hash, "client_status", $client_status);
606 &add_content2xml_hash($register_hash, "client_revision", $client_revision);
607 &add_content2xml_hash($register_hash, "gotoHardwareChecksum", $gotoHardwareChecksum);
608 &add_content2xml_hash($register_hash, "key_lifetime", $server_key_lifetime);
610 # Add $HOSTNAME from ENV if force-hostname is set
611 if( defined($client_force_hostname) && $client_force_hostname eq "true") {
612 if(defined($ENV{HOSTNAME}) && length($ENV{HOSTNAME}) >0 ) {
613 &add_content2xml_hash($register_hash, "force-hostname", $ENV{HOSTNAME});
614 } else {
615 &main::daemon_log("force-hostname was set to true, but no \$HOSTNAME was found in Environment!",0);
616 }
617 }
619 # send xml hash to server with general server passwd
620 my $res = &send_msg_hash_to_target($register_hash, $server, $default_server_key);
622 # if delivery of registration msg succeed
623 if($res eq "0") {
624 # reset try_to_register
625 $try_to_register = 0;
627 # Set fixed client address and mac address
628 $client_ip= &get_local_ip_for_remote_ip(sprintf("%s", $server =~ /^([0-9\.]*?):.*$/));
629 $client_address= "$client_ip:$client_port";
630 $client_mac_address = $local_mac;
631 $client_dnsname = $dnsname;
632 last;
634 # delivery of registration msg failed
635 } else {
636 # wait 1 sec until trying to register again
637 sleep(1);
638 next;
639 }
641 } # end of while
643 if ( $try_to_register >= @servers ) {
644 # One circle through all servers finished and no registration succeed
645 &write_to_file("gosa-si-no-server-available", $fai_logpath);
646 } else {
647 # Delivery of registraion msg succeed, waiting for server response
648 daemon_log("INFO: waiting for msg 'register_at_gosa_si_server'",5);
649 # Clear old settings and set it again
650 $kernel->delay('trigger_new_key');
651 $kernel->delay_set('trigger_new_key', $server_key_lifetime);
652 }
654 # Set waiting time for 'register_at_gosa_si_server'-event
655 $kernel->delay_set('register_at_gosa_si_server', $delay_set_time);
656 }
657 return;
658 }
661 sub check_key_and_xml_validity {
662 my ($crypted_msg, $module_key) = @_;
664 my $msg;
665 my $msg_hash;
666 eval{
667 $msg = &decrypt_msg($crypted_msg, $module_key);
668 &main::daemon_log("decrypted_msg: \n$msg", 9);
670 $msg_hash = $xml->XMLin($msg, ForceArray=>1);
672 ##############
673 # check header
674 my $header_l = $msg_hash->{'header'};
675 if( 1 != @{$header_l} ) {
676 die 'no or more headers specified';
677 }
678 my $header = @{$header_l}[0];
679 if( 0 == length $header) {
680 die 'header has length 0';
681 }
683 ##############
684 # check source
685 my $source_l = $msg_hash->{'source'};
686 if( 1 != @{$source_l} ) {
687 die 'no or more than 1 sources specified';
688 }
689 my $source = @{$source_l}[0];
690 if( 0 == length $source) {
691 die 'source has length 0';
692 }
693 unless( $source =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d+$/ ) {
694 die "source '$source' is neither a complete ip-address with port nor 'GOSA'";
695 }
697 ##############
698 # check target
699 my $target_l = $msg_hash->{'target'};
700 if( 1 != @{$target_l} ) {
701 die 'no or more than 1 targets specified ';
702 }
703 my $target = @{$target_l}[0];
704 if( 0 == length $target) {
705 die 'target has length 0 ';
706 }
707 unless( $target =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d+$/ ){
708 die "source is neither a complete ip-address with port nor 'GOSA'";
709 }
710 };
711 if($@) {
712 &main::daemon_log("WARNING: do not understand the message or msg is not gosa-si envelope conform:", 5);
713 &main::daemon_log("$@", 8);
714 $msg = undef;
715 $msg_hash = undef;
716 }
718 return ($msg, $msg_hash);
719 }
722 sub check_outgoing_xml_validity {
723 my ($msg) = @_;
725 my $msg_hash;
726 eval{
727 $msg_hash = $xml->XMLin($msg, ForceArray=>1);
729 ##############
730 # check header
731 my $header_l = $msg_hash->{'header'};
732 if( 1 != @{$header_l} ) {
733 die 'no or more than one headers specified';
734 }
735 my $header = @{$header_l}[0];
736 if( 0 == length $header) {
737 die 'header has length 0';
738 }
740 ##############
741 # check source
742 my $source_l = $msg_hash->{'source'};
743 if( 1 != @{$source_l} ) {
744 die 'no or more than 1 sources specified';
745 }
746 my $source = @{$source_l}[0];
747 if( 0 == length $source) {
748 die 'source has length 0';
749 }
750 unless( $source =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d+$/ ||
751 $source =~ /^GOSA$/i ) {
752 die "source '$source' is neither a complete ip-address with port";
753 }
755 ##############
756 # check target
757 my $target_l = $msg_hash->{'target'};
758 if( 1 != @{$target_l} ) {
759 die "no or more than one targets specified";
760 }
761 foreach my $target (@$target_l) {
762 if( 0 == length $target) {
763 die "target has length 0";
764 }
765 unless( $target =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d+$/ ) {
766 die "target '$target' is not a complete ip-address with port or a valid target name";
767 }
768 }
769 };
770 if($@) {
771 daemon_log("WARNING: outgoing msg is not gosa-si envelope conform", 5);
772 daemon_log("$@ $msg", 8);
773 $msg_hash = undef;
774 }
775 return ($msg_hash);
776 }
779 sub trigger_new_key {
780 my ($kernel) = $_[KERNEL] ;
782 my $msg = "<xml><header>new_key</header><source>$client_address</source><target>$client_address</target></xml>";
783 &send_msg_to_target($msg, $client_address, $server_key, 'new_key');
785 $kernel->delay_set('trigger_new_key', $server_key_lifetime);
786 }
789 sub trigger_logged_in_users_report {
790 my ($kernel) = $_[KERNEL] ;
792 # just do if client is registered already
793 if( $REGISTERED ) {
794 my $result = qx(/usr/bin/users);
795 my @logged_in_user_list;
796 if( defined $result ) {
797 chomp($result);
798 @logged_in_user_list = split(/\s/, $result);
799 }
801 system("echo 'CURRENTLY_LOGGED_IN ".join(" ", @logged_in_user_list)."' > /var/run/gosa-si-client.socket");
802 $kernel->delay_set('trigger_logged_in_users_report', $trigger_logged_in_users_report_delay);
803 } else {
804 # try it in 10 sec again
805 $kernel->delay_set('trigger_logged_in_users_report', 10);
806 }
807 }
809 sub trigger_set_terminal_server
810 {
811 # Function is defined in load_reporter.pm
812 if (exists $event_hash->{set_terminal_server})
813 {
814 no strict 'refs';
815 &{$event_hash->{set_terminal_server}."::set_terminal_server"};
816 }
817 else
818 {
819 &daemon_log("0 ERROR: load_reporter.pm needs function set_terminal_server to write terminal server load information to client. Processing aborted!", 1);
820 }
821 return;
822 }
824 sub trigger_seen_messages {
825 my ($kernel) = $_[KERNEL] ;
827 # Select all files under /tmp with prefix 'goto_notify'
828 my $goto_dir = "/tmp";
829 opendir(DIR, $goto_dir);
830 my @goto_files = grep { /.+\.goto_notify$/ && -f "$goto_dir/$_" } readdir(DIR);
831 closedir DIR;
833 # Check if file has 'seen' tag
834 foreach my $goto_file (@goto_files) {
835 open(my $FILE, "$goto_dir/$goto_file");
836 my @lines = <$FILE>;
837 close($FILE);
839 my $source;
840 my $target;
841 my $usr;
842 my $subject;
843 my $message;
844 my $seen = 0;
845 chomp(@lines);
846 foreach my $line (@lines) {
847 if ($line =~ /^source:([\S\s]*)$/) {
848 $source = $1
849 }
850 if ($line =~ /^target:([\S\s]*)$/) {
851 $target = $1;
852 }
853 if ($line =~ /^usr:([\S\s]*)$/) {
854 $usr = $1;
855 }
856 if ($line =~ /^subject:([\S\s]*)$/) {
857 $subject = $1;
858 }
859 if ($line =~ /^message:([\S\s]*)$/) {
860 $message = $1;
861 }
862 if ($line =~ /^seen$/) {
863 $seen++;
864 }
865 }
867 # Send 'confirm_usr_msg' back to msg-hosting server
868 if ($seen) {
869 my %data = ('usr'=>$usr, 'subject'=>$subject, 'message'=>$message);
870 my $confirm_msg = &build_msg("confirm_usr_msg", $target, $source, \%data);
871 my $send_error = &send_msg_to_target($confirm_msg, $server_address, $server_key);
873 # Delete file
874 if (not $send_error) {
875 system("rm $goto_dir/$goto_file");
876 }
877 }
878 }
880 $kernel->delay_set('trigger_seen_messages', $trigger_seen_messages_delay);
882 return;
883 }
886 sub generic_file_error {
887 my ( $heap, $operation, $errno, $error_string, $wheel_id ) =
888 @_[ HEAP, ARG0, ARG1, ARG2, ARG3 ];
890 my $service = $heap->{services}->{$wheel_id};
891 daemon_log("ERROR: '$service' watcher $operation error $errno: $error_string", 1);
892 daemon_log("ERROR: shutting down '$service' file watcher", 1);
894 delete $heap->{services}->{$wheel_id};
895 delete $heap->{watchers}->{$wheel_id};
896 return;
897 }
900 sub fai_fifo_got_record {
901 my $file_record = $_[ARG0];
902 my $header;
903 my $content = "";
904 daemon_log("DEBUG: fifo got record: $file_record", 7);
906 $file_record =~ /^(\S+)[ ]?([\s\S]+)?$/;
907 if( defined $1 ) {
908 $header = $1;
909 } else {
910 return;
911 }
913 if( defined $2 ) {
914 $content = $2;
915 }
917 my $clmsg_hash = &create_xml_hash("CLMSG_$header", $client_address, $server_address, $content);
918 &add_content2xml_hash($clmsg_hash, "macaddress", $client_mac_address);
919 my $utc_ts = &main::get_utc_time();
920 &add_content2xml_hash($clmsg_hash, "timestamp", $utc_ts);
921 my $clmsg = &create_xml_string($clmsg_hash);
922 &send_msg_to_target($clmsg, $server_address, $server_key, "CLMSG_$header");
924 # if installation finished, save all log files
925 if ($file_record eq "TASKBEGIN finish") {
926 &save_fai_log($fai_log_dir);
927 }
929 return;
930 }
933 sub system_fifo_got_record {
934 my ($kernel, $socket_com_record) = @_[KERNEL, ARG0];
935 $socket_com_record =~ /^(\S+)\s?([\s\S]*)$/;
936 my $function = $1;
937 my $content = $2;
939 if( exists $event_hash->{$function} )
940 {
941 # a event exists with the header as name
942 daemon_log("INFO: found event '$function' at event-module '".$event_hash->{$function}."'", 5);
943 no strict 'refs';
944 my $answer = &{$event_hash->{$function}."::$function"}($content, $kernel);
945 &post_processing_and_sending($answer)
946 }
947 else
948 {
949 daemon_log("ERROR: Got input '$socket_com_record' from socket '$system_com_fifo'", 1);
950 daemon_log("ERROR: No event '$function' found in event modules under '$event_dir'.", 1);
951 }
953 # # Sanity check of fifo record
954 #
955 # # Create record message
956 # my $lr_msg_hash = &create_xml_hash("load_report", $client_address, $server_address, $file_record);
957 # &add_content2xml_hash($lr_msg_hash, "macaddress", $client_mac_address);
958 # my $utc_ts = &main::get_utc_time();
959 # &add_content2xml_hash($lr_msg_hash, "timestamp", $utc_ts);
960 # my $lr_msg = &create_xml_string($lr_msg_hash);
961 #
962 # # Report message to si-server
963 # &send_msg_to_target($lr_msg, $server_address, $server_key, "load_report");
965 return;
966 }
969 sub save_fai_log {
970 my ($fai_log_dir) = @_ ;
971 my $FAI_DIR;
973 # Directory for log files after a softupdate
974 my $log_dir = File::Spec->catdir($fai_log_dir, "localhost/last");
976 if (not -d $log_dir) {
977 # Directory for log files after a new installation
978 $log_dir = "/tmp/fai";
979 if (not -d $log_dir) {
980 daemon_log("ERROR: cannot open directory $log_dir", 1);
981 return;
982 }
983 }
985 opendir($FAI_DIR, "$log_dir");
986 my @log_files = readdir($FAI_DIR);
987 closedir($FAI_DIR);
989 my @log_list;
990 foreach my $log_file (@log_files) {
991 if( $log_file eq "." || $log_file eq ".." ) { next; }
993 my $log = "log_file:$log_file:";
994 $log_file = File::Spec->catfile( $log_dir, $log_file );
996 if (not -f $log_file) {
997 daemon_log("ERROR: cannot read $log_file", 1);
998 next;
999 }
1001 open(my $FILE, "<","$log_file");
1002 my @lines = <$FILE> ;
1003 close ($FILE);
1004 my $log_string = join("", @lines);
1005 $log .= &encode_base64($log_string);
1006 push(@log_list, $log);
1007 }
1009 my $all_log_string = join("\n", @log_list);
1010 my $msg_hash = &create_xml_hash("CLMSG_save_fai_log", $client_address, $server_address, $all_log_string);
1011 &add_content2xml_hash($msg_hash, "macaddress", $client_mac_address);
1012 my $msg = &create_xml_string($msg_hash);
1013 &send_msg_to_target($msg, $server_address, $server_key, "CLMSG_save_fai_log");
1015 }
1018 sub sig_handler {
1019 my ($kernel, $signal) = @_[KERNEL, ARG0] ;
1020 daemon_log("0 INFO got signal '$signal'", 1);
1021 $kernel->sig_handled();
1022 return;
1023 }
1026 sub _start {
1027 my ($kernel, $heap) = @_[KERNEL, HEAP];
1028 $kernel->alias_set('client_session');
1029 $global_kernel = $kernel; # this is used to throw events at each point of the skript
1031 $kernel->sig(USR1 => "sig_handler");
1033 # force a registration at a gosa-si-server
1034 $kernel->yield('register_at_gosa_si_server');
1036 # install all file watcher defined
1037 while( my($name, $file) = each %files_to_watch ) {
1038 my $watcher = POE::Wheel::FollowTail->new(
1039 Filename => $file,
1040 InputEvent => $name."_record",
1041 ErrorEvent => "file_error",
1042 );
1043 $heap->{services}->{ $watcher->ID } = $name;
1044 $heap->{watchers}->{ $watcher->ID } = $watcher;
1045 }
1046 $kernel->yield('trigger_logged_in_users_report');
1047 $kernel->yield('trigger_seen_messages');
1048 }
1051 sub _default {
1052 daemon_log("ERROR: can not handle incoming msg with header '$_[ARG0]'", 1);
1053 return;
1054 }
1057 sub server_input {
1058 my ($kernel, $heap, $input, $wheel) = @_[KERNEL, HEAP, ARG0, ARG1];
1059 my $remote_ip = $heap->{'remote_ip'},
1060 my $error = 0;
1061 my $answer;
1063 daemon_log("INFO: Incoming msg from '$remote_ip'", 5);
1064 daemon_log("DEBUG: Incoming msg:\n$input\n", 9);
1066 # Cut of ip and port from msgs tail
1067 my ($encrypted_msg, $msg_source) = split(/;/, $input);
1069 my ($msg, $msg_hash) = &check_key_and_xml_validity($encrypted_msg, $server_key);
1070 if( (!$msg) || (!$msg_hash) ) {
1071 daemon_log("WARNING: Deciphering of incoming msg failed", 3);
1072 if($server_address =~ /$remote_ip/) {
1073 # Got a msg from gosa-si-server which can not be decrypted, the secrete is not up-to-date
1074 # cause a reregistering with a new secrete handshake
1075 daemon_log("ERROR: Message from gosa-si-server could not be understood, cause reregistering at server", 1);
1076 if ($REGISTERED) {
1077 daemon_log("INFO: Client has currently status registered so throw new registering event", 5);
1078 &_setREGISTERED(0);
1079 $kernel->post('client_session', 'register_at_gosa_si_server');
1080 } else {
1081 daemon_log("INFO: Client is currently within a registration process so wait for the next registration itteration", 5);
1082 }
1083 }
1084 $error++;
1085 }
1088 ######################
1089 # process incoming msg
1090 if( $error == 0 ) {
1091 my $header = @{$msg_hash->{header}}[0];
1092 my $source = @{$msg_hash->{source}}[0];
1094 if( exists $event_hash->{$header} ) {
1096 # a event exists with the header as name
1097 daemon_log("INFO: found event '$header' at event-module '".$event_hash->{$header}."'", 5);
1098 no strict 'refs';
1099 $answer = &{$event_hash->{$header}."::$header"}($msg, $msg_hash);
1100 }
1101 else {
1102 daemon_log("WARNING: no event '$header' found in event modules under $event_dir", 3);
1103 }
1104 }
1106 ########
1107 # answer
1108 &post_processing_and_sending($answer);
1110 return;
1111 }
1113 sub post_processing_and_sending
1114 {
1115 my ($answer) = @_ ;
1117 # Do nothing if answer does not exists
1118 if (not defined $answer) { return; }
1120 # Check gosa-si envelope validity
1121 my $answer_hash = &check_outgoing_xml_validity($answer);
1123 # If answer is valid go ahead
1124 if( not defined $answer_hash ) { return; }
1126 # Sending
1127 $answer =~ /<header>(\S+)<\/header>/;
1128 &send_msg_to_target($answer, $server_address, $server_key, $1);
1130 return;
1131 }
1133 sub find_servers {
1134 # add gosa-si-server address from config file at first position of server list
1135 my $server_check_cfg = Config::IniFiles->new( -file => $cfg_file );
1137 # Parse servers string
1138 my @conf_servers = split(',', $servers_string);
1140 # Now search for fallback servers in the configuration
1141 foreach my $cur_server (@conf_servers) {
1142 # Remove spaces from the IP
1143 $cur_server =~ s/\s//g;
1145 my $ip = $cur_server;
1146 if(not $cur_server =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/) {
1147 my $ip_address = inet_ntoa(scalar gethostbyname($ip));
1148 if(defined($ip_address) && $ip_address =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/) {
1149 # Write ip address to $server_ip variable
1150 $ip = $ip_address;
1151 }
1152 }
1154 my $server_addr = sprintf("%s:%s", $ip, $server_port);
1155 if (not grep { $_ eq $server_addr } @servers) {
1156 push(@servers, $server_addr);
1157 }
1158 }
1160 my $servers_string = join(", ", @servers);
1161 daemon_log("INFO: found servers in configuration file: $servers_string", 1);
1163 # Last but not least search for fallback servers in the DNS
1164 if (defined($opts_dnslookup) and $opts_dnslookup eq "true") {
1165 my @tmp_servers;
1166 if ( !$server_domain) {
1167 # Try our DNS Searchlist
1168 my @domain_list = &get_dns_domains();
1169 my $tmp_domains;
1170 my $error_string;
1171 for my $domain (@domain_list) {
1172 chomp($domain);
1173 ($tmp_domains, $error_string) = &get_server_addresses($domain);
1174 if(@$tmp_domains) {
1175 for my $tmp_server(@$tmp_domains) {
1176 push @tmp_servers, $tmp_server;
1177 }
1178 }
1179 }
1181 if (0 == @tmp_servers) {
1182 daemon_log("INFO: No servers found in DNS.", 1);
1183 }
1184 else {
1185 my $servers_string = join(", ", @tmp_servers);
1186 daemon_log("INFO: found servers in DNS: $servers_string", 1);
1187 }
1188 } else {
1189 @tmp_servers = &get_server_addresses($server_domain);
1190 if( 0 == @tmp_servers ) {
1191 daemon_log("INFO: No servers found in DNS for domain '$server_domain'",1);
1192 }
1193 }
1195 if ( 0 != @tmp_servers ) {
1196 foreach my $server_addr (@tmp_servers) {
1197 if (not grep { $_ eq $server_addr } @servers) {
1198 push(@servers, $server_addr);
1199 }
1200 }
1201 }
1202 }
1204 if (0 == scalar(@servers)) {
1205 daemon_log("ERROR: No servers found in the configuration or DNS.", 1);
1206 exit(1);
1207 }
1209 # Define first server as server_ip
1210 $server_ip = $servers[0];
1212 # prepare variables
1213 if( inet_aton($server_ip) ){ $server_ip = inet_ntoa(inet_aton($server_ip)); }
1214 if (defined $server_ip && defined $server_port) {
1215 $server_address = $server_ip.":".$server_port;
1216 }
1217 }
1219 #==== MAIN = main ==============================================================
1220 # parse commandline options
1221 Getopt::Long::Configure( "bundling" );
1222 GetOptions("h|help" => \&usage,
1223 "c|config=s" => \$cfg_file,
1224 "f|foreground" => \$foreground,
1225 "v|verbose+" => \$verbose,
1226 );
1228 # read and set config parameters
1229 &check_cmdline_param ;
1230 &read_configfile($cfg_file, %cfg_defaults);
1231 &check_pid;
1234 # forward error messages to logfile
1235 if ( ! $foreground ) {
1236 open( STDIN, '+>/dev/null' );
1237 open( STDOUT, '+>&STDIN' );
1238 open( STDERR, '+>&STDIN' );
1239 }
1241 # Just fork, if we are not in foreground mode
1242 if( ! $foreground ) {
1243 chdir '/' or die "Can't chdir to /: $!";
1244 $pid = fork;
1245 setsid or die "Can't start a new session: $!";
1246 umask 0;
1247 } else {
1248 $pid = $$;
1249 }
1251 # Do something useful - put our PID into the pid_file
1252 if( 0 != $pid ) {
1253 open( my $LOCK_FILE, ">", "$pid_file" );
1254 print $LOCK_FILE "$pid\n";
1255 close( $LOCK_FILE );
1256 if( !$foreground ) {
1257 exit( 0 )
1258 };
1259 }
1261 # parse head url and revision from svn
1262 my $client_status_hash = { 'developmental'=>'revision', 'stable'=>'release'};
1263 $client_version =~ /^\$HeadURL: (\S+) \$:\$Rev: (\d+) \$$/;
1264 $client_headURL = defined $1 ? $1 : 'unknown' ;
1265 $client_revision = defined $2 ? $2 : 'unknown' ;
1266 if ($client_headURL =~ /\/tag\// ||
1267 $client_headURL =~ /\/branches\// ) {
1268 $client_status = "stable";
1269 } else {
1270 $client_status = "developmental" ;
1271 }
1273 # Determine root uid and adm gid, used for creating log files
1274 $root_uid = getpwnam('root');
1275 $adm_gid = getgrnam('adm');
1276 if(not defined $adm_gid){
1277 $adm_gid = getgrnam('root');
1278 }
1280 daemon_log(" ", 1);
1281 daemon_log("$prg started!", 1);
1282 daemon_log("INFO: status: $client_status", 1);
1283 daemon_log("INFO: ".$client_status_hash->{$client_status}.": $client_revision", 1);
1285 # delete old DBsqlite lock files
1286 system('rm -f /tmp/gosa_si_lock*gosa-si-client*');
1288 # detect ip and mac address and complete host address
1289 $client_address = $client_ip.":".$client_port;
1290 my $network_interface= &get_interface_for_ip($client_ip);
1291 $client_mac_address= &get_mac($network_interface);
1292 daemon_log("INFO: ip address detected: $client_ip", 1);
1293 daemon_log("INFO: gosa-si-client mac address detected: $client_mac_address", 1);
1296 # import events
1297 my ($error, $result, $tmp_hash) = &import_events($event_dir);
1298 while (my ($module, $mod_event_hash) = each %$tmp_hash) {
1299 while (my ($event_name, $nothing) = each %$mod_event_hash) {
1300 $event_hash->{$event_name} = $module;
1301 }
1302 }
1304 foreach my $log_line (@$result) {
1305 if ($log_line =~ / succeed: /) {
1306 &main::daemon_log("0 DEBUG: $log_line", 7);
1307 } else {
1308 &main::daemon_log("0 ERROR: $log_line", 1);
1309 }
1310 }
1313 # compute hardware checksum
1314 $gotoHardwareChecksum= &generate_hw_digest();
1315 daemon_log("INFO: gotoHardwareChecksum detected: $gotoHardwareChecksum", 1);
1317 # create socket for incoming xml messages
1318 POE::Component::Server::TCP->new(
1319 Alias => 'gosa-si-client',
1320 Port => $client_port,
1321 ClientInput => \&server_input,
1322 );
1323 daemon_log("INFO: start socket for incoming xml messages at port '$client_port' ", 1);
1325 $xml = new XML::Simple();
1326 $default_server_key = $server_key;
1328 # Open a new fifo for FAI messages to gosa-si-server
1329 if (-p $fai_com_fifo) { unlink $fai_com_fifo }
1330 POSIX::mkfifo("$fai_com_fifo", 0600);
1332 # Find servers from config and DNS
1333 &find_servers;
1335 # Open a new fifo for system communication,
1336 if (-p $system_com_fifo) { unlink $system_com_fifo }
1337 if ($system_com eq "enabled")
1338 {
1339 POSIX::mkfifo("$system_com_fifo", 0600);
1340 }
1342 POE::Session->create(
1343 inline_states => {
1344 _start => \&_start,
1345 _default => \&_default,
1346 sig_handler => \&sig_handler,
1347 register_at_gosa_si_server => \®ister_at_gosa_si_server,
1349 # trigger periodical tasks
1350 trigger_new_key => \&trigger_new_key,
1351 trigger_logged_in_users_report => \&trigger_logged_in_users_report,
1352 trigger_seen_messages => \&trigger_seen_messages,
1354 # trigger non periodical tasks
1355 trigger_set_terminal_server => \&trigger_set_terminal_server,
1357 # handle records from each defined file differently
1358 fai_fifo_record => \&fai_fifo_got_record,
1359 system_fifo_record => \&system_fifo_got_record,
1361 # handle file resets and errors the same way for each file
1362 file_reset => \&generic_file_reset,
1363 file_error => \&generic_file_error,
1364 }
1365 );
1367 POE::Kernel->run();
1368 exit;