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