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