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 utf8;
24 use Getopt::Long;
25 use Config::IniFiles;
26 use POSIX;
27 use Time::HiRes qw( gettimeofday );
29 use POE qw(Component::Server::TCP Wheel::FollowTail);
30 use IO::Socket::INET;
31 use NetAddr::IP;
32 use Data::Dumper;
33 use Crypt::Rijndael;
34 use GOSA::GosaSupportDaemon;
35 use Digest::MD5 qw(md5_hex md5 md5_base64);
36 use MIME::Base64;
37 use XML::Simple;
38 use Net::DNS;
39 use File::Basename;
41 my $event_dir = "/usr/lib/gosa-si/client/events";
42 use lib "/usr/lib/gosa-si/client/events";
44 my (%cfg_defaults, $foreground, $verbose, $pid_file, $procid, $pid, $log_file, $fai_logpath);
45 my ($server_ip, $server_port, $server_key, $server_timeout, $server_domain, $server_key_lifetime);
46 my ($client_ip, $client_port, $client_mac_address, $ldap_enabled, $ldap_config, $pam_config, $nss_config);
47 my $xml;
48 my $default_server_key;
49 my $event_hash;
50 my @servers;
51 my $gotoHardwareChecksum;
52 my $gosa_si_client_fifo;
53 my %files_to_watch;
54 $verbose= 1;
56 # globalise variables which are used in imported events
57 our $cfg_file;
58 our $opts_file;
59 our $server_address;
60 our $client_address;
61 our $client_ip;
62 our $client_mac_address;
63 our $client_dnsname;
64 our $client_force_hostname;
65 our $server_key;
67 # default variables
68 our $REGISTERED = 0;
70 # path to fifo for non-gosa-si-client messages to gosa-si-server
71 $gosa_si_client_fifo = "/var/run/gosa-si-client.socket";
72 %files_to_watch = (fifo => $gosa_si_client_fifo);
74 # in function register_at_gosa_si_server, after which period of seconds a new registration should be tried if a registration was
75 # not successful until now
76 my $delay_set_time = 5;
77 our $prg= basename($0);
79 # all x seconds the client reports logged_in users to gosa-si-server
80 my $trigger_logged_in_users_report_delay = 600;
82 %cfg_defaults = (
83 "general" =>
84 {"log-file" => [\$log_file, "/var/run/".$prg.".log"],
85 "pid-file" => [\$pid_file, "/var/run/".$prg.".pid"],
86 "opts-file" => [\$opts_file, "/var/run/".$prg.".opts"],
87 },
88 "client" =>
89 {"port" => [\$client_port, "20083"],
90 "ip" => [\$client_ip, "0.0.0.0"],
91 "mac-address" => [\$client_mac_address, "00:00:00:00:00:00"],
92 "server-domain" => [\$server_domain, ""],
93 "ldap" => [\$ldap_enabled, 1],
94 "ldap-config" => [\$ldap_config, "/etc/ldap/ldap.conf"],
95 "pam-config" => [\$pam_config, "/etc/pam_ldap.conf"],
96 "nss-config" => [\$nss_config, "/etc/libnss_ldap.conf"],
97 "fai-logpath" => [\$fai_logpath, "/var/log/fai/fai.log"],
98 "force-hostname" => [\$client_force_hostname, "false"],
99 },
100 "server" => {
101 "ip" => [\$server_ip, "127.0.0.1"],
102 "port" => [\$server_port, "20081"],
103 "key" => [\$server_key, ""],
104 "timeout" => [\$server_timeout, 10],
105 "key-lifetime" => [\$server_key_lifetime, 600],
106 },
108 );
111 #=== FUNCTIONS = functions =====================================================
113 #=== FUNCTION ================================================================
114 # NAME: check_cmdline_param
115 # PARAMETERS:
116 # RETURNS:
117 # DESCRIPTION:
118 #===============================================================================
119 sub check_cmdline_param () {
120 my $err_config;
121 my $err_counter = 0;
122 if(not defined($cfg_file)) {
123 $cfg_file = "/etc/gosa-si/client.conf";
124 if(! -r $cfg_file) {
125 $err_config = "please specify a config file";
126 $err_counter += 1;
127 }
128 }
129 if( $err_counter > 0 ) {
130 &usage( "", 1 );
131 if( defined( $err_config)) { print STDERR "$err_config\n"}
132 print STDERR "\n";
133 exit( -1 );
134 }
135 }
138 #=== FUNCTION ================================================================
139 # NAME: read_configfile
140 # PARAMETERS: cfg_file - string -
141 # RETURNS:
142 # DESCRIPTION:
143 #===============================================================================
144 sub read_configfile {
145 my ($cfg_file, %cfg_defaults) = @_ ;
146 my $cfg;
147 if( defined( $cfg_file) && ( length($cfg_file) > 0 )) {
148 if( -r $cfg_file ) {
149 $cfg = Config::IniFiles->new( -file => $cfg_file );
150 } else {
151 print STDERR "Couldn't read config file!";
152 }
153 } else {
154 $cfg = Config::IniFiles->new() ;
155 }
156 foreach my $section (keys %cfg_defaults) {
157 foreach my $param (keys %{$cfg_defaults{ $section }}) {
158 my $pinfo = $cfg_defaults{ $section }{ $param };
159 ${@$pinfo[ 0 ]} = $cfg->val( $section, $param, @$pinfo[ 1 ] );
160 }
161 }
162 }
165 #=== FUNCTION ================================================================
166 # NAME: check_pid
167 # PARAMETERS:
168 # RETURNS:
169 # DESCRIPTION:
170 #===============================================================================
171 sub check_pid {
172 $pid = -1;
173 # Check, if we are already running
174 if( open(LOCK_FILE, "<$pid_file") ) {
175 $pid = <LOCK_FILE>;
176 if( defined $pid ) {
177 chomp( $pid );
178 if( -f "/proc/$pid/stat" ) {
179 my($stat) = `cat /proc/$pid/stat` =~ m/$pid \((.+)\).*/;
180 if( $0 eq $stat ) {
181 close( LOCK_FILE );
182 exit -1;
183 }
184 }
185 }
186 close( LOCK_FILE );
187 unlink( $pid_file );
188 }
190 # create a syslog msg if it is not to possible to open PID file
191 if (not sysopen(LOCK_FILE, $pid_file, O_WRONLY|O_CREAT|O_EXCL, 0644)) {
192 my($msg) = "Couldn't obtain lockfile '$pid_file' ";
193 if (open(LOCK_FILE, '<', $pid_file)
194 && ($pid = <LOCK_FILE>))
195 {
196 chomp($pid);
197 $msg .= "(PID $pid)\n";
198 } else {
199 $msg .= "(unable to read PID)\n";
200 }
201 if( ! ($foreground) ) {
202 openlog( $0, "cons,pid", "daemon" );
203 syslog( "warning", $msg );
204 closelog();
205 }
206 else {
207 print( STDERR " $msg " );
208 }
209 exit( -1 );
210 }
211 }
214 sub sig_int_handler {
215 my ($signal) = @_;
217 daemon_log("shutting down gosa-si-server", 1);
218 exit(1);
219 }
220 $SIG{INT} = \&sig_int_handler;
223 #=== FUNCTION ================================================================
224 # NAME: logging
225 # PARAMETERS: level - string - default 'info'
226 # msg - string -
227 # facility - string - default 'LOG_DAEMON'
228 # RETURNS:
229 # DESCRIPTION:
230 #===============================================================================
231 sub daemon_log {
232 # log into log_file
233 my( $msg, $level ) = @_;
234 if(not defined $msg) { return }
235 if(not defined $level) { $level = 1 }
236 if(defined $log_file){
237 open(LOG_HANDLE, ">>$log_file");
238 if(not defined open( LOG_HANDLE, ">>$log_file" )) {
239 print STDERR "cannot open $log_file: $!";
240 return }
241 chomp($msg);
242 if($level <= $verbose){
243 my ($seconds, $minutes, $hours, $monthday, $month,
244 $year, $weekday, $yearday, $sommertime) = localtime(time);
245 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
246 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
247 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
248 my @monthnames = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
249 $month = $monthnames[$month];
250 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
251 $year+=1900;
253 my $log_msg = "$month $monthday $hours:$minutes:$seconds $prg $msg\n";
254 print LOG_HANDLE $log_msg;
255 if( $foreground ) {
256 print STDERR $log_msg;
257 }
258 }
259 close( LOG_HANDLE );
260 }
261 }
264 #=== FUNCTION ================================================================
265 # NAME: get_interfaces
266 # PARAMETERS: none
267 # RETURNS: (list of interfaces)
268 # DESCRIPTION: Uses proc fs (/proc/net/dev) to get list of interfaces.
269 #===============================================================================
270 sub get_interfaces {
271 my @result;
272 my $PROC_NET_DEV= ('/proc/net/dev');
274 open(PROC_NET_DEV, "<$PROC_NET_DEV")
275 or die "Could not open $PROC_NET_DEV";
277 my @ifs = <PROC_NET_DEV>;
279 close(PROC_NET_DEV);
281 # Eat first two line
282 shift @ifs;
283 shift @ifs;
285 chomp @ifs;
286 foreach my $line(@ifs) {
287 my $if= (split /:/, $line)[0];
288 $if =~ s/^\s+//;
289 push @result, $if;
290 }
292 return @result;
293 }
295 #=== FUNCTION ================================================================
296 # NAME: get_mac
297 # PARAMETERS: interface name (i.e. eth0)
298 # RETURNS: (mac address)
299 # DESCRIPTION: Uses ioctl to get mac address directly from system.
300 #===============================================================================
301 sub get_mac {
302 my $ifreq= shift;
303 my $result;
304 if ($ifreq && length($ifreq) > 0) {
305 if($ifreq eq "all") {
306 if(defined($server_ip)) {
307 $result = &get_local_mac_for_remote_ip($server_ip);
308 }
309 elsif ($client_mac_address && length($client_mac_address) > 0 && !($client_mac_address eq "00:00:00:00:00:00")){
310 $result = &client_mac_address;
311 }
312 else {
313 $result = "00:00:00:00:00:00";
314 }
315 } else {
316 my $SIOCGIFHWADDR= 0x8927; # man 2 ioctl_list
318 # A configured MAC Address should always override a guessed value
319 if ($client_mac_address and length($client_mac_address) > 0 and not($client_mac_address eq "00:00:00:00:00:00")) {
320 $result= $client_mac_address;
321 }
322 else {
323 socket SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('ip')
324 or die "socket: $!";
326 if(ioctl SOCKET, $SIOCGIFHWADDR, $ifreq) {
327 my ($if, $mac)= unpack 'h36 H12', $ifreq;
329 if (length($mac) > 0) {
330 $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])$/;
331 $mac= sprintf("%s:%s:%s:%s:%s:%s", $1, $2, $3, $4, $5, $6);
332 $result = $mac;
333 }
334 }
335 }
336 }
337 }
338 return $result;
339 }
342 #=== FUNCTION ================================================================
343 # NAME: get_interface_for_ip
344 # PARAMETERS: ip address (i.e. 192.168.0.1)
345 # RETURNS: array: list of interfaces if ip=0.0.0.0, matching interface if found, undef else
346 # DESCRIPTION: Uses proc fs (/proc/net/dev) to get list of interfaces.
347 #===============================================================================
348 sub get_interface_for_ip {
349 my $result;
350 my $ip= shift;
351 if ($ip && length($ip) > 0) {
352 my @ifs= &get_interfaces();
353 if($ip eq "0.0.0.0") {
354 $result = "all";
355 } else {
356 foreach (@ifs) {
357 my $if=$_;
358 if(get_ip($if) eq $ip) {
359 $result = $if;
360 last;
361 }
362 }
363 }
364 }
365 return $result;
366 }
369 #=== FUNCTION ================================================================
370 # NAME: get_ip
371 # PARAMETERS: interface name (i.e. eth0)
372 # RETURNS: (ip address)
373 # DESCRIPTION: Uses ioctl to get ip address directly from system.
374 #===============================================================================
375 sub get_ip {
376 my $ifreq= shift;
377 my $result= "";
378 my $SIOCGIFADDR= 0x8915; # man 2 ioctl_list
379 my $proto= getprotobyname('ip');
381 socket SOCKET, PF_INET, SOCK_DGRAM, $proto
382 or die "socket: $!";
384 if(ioctl SOCKET, $SIOCGIFADDR, $ifreq) {
385 my ($if, $sin) = unpack 'a16 a16', $ifreq;
386 my ($port, $addr) = sockaddr_in $sin;
387 my $ip = inet_ntoa $addr;
389 if ($ip && length($ip) > 0) {
390 $result = $ip;
391 }
392 }
394 return $result;
395 }
398 #=== FUNCTION ================================================================
399 # NAME: get_local_mac_for_remote_ip
400 # PARAMETERS: none (takes server_ip from global variable)
401 # RETURNS: (ip address from interface that is used for communication)
402 # DESCRIPTION: Uses ioctl to get routing table from system, checks which entry
403 # matches (defaultroute last).
404 #===============================================================================
405 sub get_local_mac_for_remote_ip {
406 my $server_ip= shift;
407 my $result= "00:00:00:00:00:00";
409 if($server_ip =~ /^(\d\d?\d?\.){3}\d\d?\d?$/) {
410 my $PROC_NET_ROUTE= ('/proc/net/route');
412 open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
413 or die "Could not open $PROC_NET_ROUTE";
415 my @ifs = <PROC_NET_ROUTE>;
417 close(PROC_NET_ROUTE);
419 # Eat header line
420 shift @ifs;
421 chomp @ifs;
422 foreach my $line(@ifs) {
423 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
424 my $destination;
425 my $mask;
426 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
427 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
428 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
429 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
430 if(new NetAddr::IP($server_ip)->within(new NetAddr::IP($destination, $mask))) {
431 # destination matches route, save mac and exit
432 $result= &get_mac($Iface);
433 last;
434 }
435 }
436 } else {
437 daemon_log("get_local_mac_for_remote_ip was called with a non-ip parameter: $server_ip", 1);
438 }
439 return $result;
440 }
442 sub get_local_ip_for_remote_ip {
443 my $server_ip= shift;
444 my $result="0.0.0.0";
446 if($server_ip =~ /^(\d\d?\d?\.){3}\d\d?\d?$/) {
447 if($server_ip eq "127.0.0.1") {
448 $result="127.0.0.1";
449 } else {
450 my $PROC_NET_ROUTE= ('/proc/net/route');
452 open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
453 or die "Could not open $PROC_NET_ROUTE";
455 my @ifs = <PROC_NET_ROUTE>;
457 close(PROC_NET_ROUTE);
459 # Eat header line
460 shift @ifs;
461 chomp @ifs;
462 foreach my $line(@ifs) {
463 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
464 my $destination;
465 my $mask;
466 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
467 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
468 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
469 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
470 if(new NetAddr::IP($server_ip)->within(new NetAddr::IP($destination, $mask))) {
471 # destination matches route, save mac and exit
472 $result= &get_ip($Iface);
473 last;
474 }
475 }
476 }
477 } else {
478 daemon_log("get_local_ip_for_remote_ip was called with a non-ip parameter: $server_ip", 1);
479 }
480 return $result;
481 }
484 sub generate_hw_digest {
485 my $hw_data;
486 foreach my $line (split /\n/, `cat /proc/bus/pci/devices`) {
487 $hw_data.= sprintf "%s", $line =~ /[^\s]+\s([^\s]+)\s.*/;
488 }
489 return(md5_base64($hw_data));
490 }
493 sub create_passwd {
494 my $new_passwd = "";
495 for(my $i=0; $i<31; $i++) {
496 $new_passwd .= ("a".."z","A".."Z",0..9)[int(rand(62))]
497 }
499 return $new_passwd;
500 }
503 sub create_ciphering {
504 my ($passwd) = @_;
505 if((!defined($passwd)) || length($passwd)==0) {
506 $passwd = "";
507 }
508 $passwd = substr(md5_hex("$passwd") x 32, 0, 32);
509 my $iv = substr(md5_hex('GONICUS GmbH'),0, 16);
510 my $my_cipher = Crypt::Rijndael->new($passwd , Crypt::Rijndael::MODE_CBC());
511 $my_cipher->set_iv($iv);
512 return $my_cipher;
513 }
516 sub encrypt_msg {
517 my ($msg, $key) = @_;
518 my $my_cipher = &create_ciphering($key);
519 my $len;
520 {
521 use bytes;
522 $len= 16-length($msg)%16;
523 }
524 $msg = "\0"x($len).$msg;
525 $msg = $my_cipher->encrypt($msg);
526 chomp($msg = &encode_base64($msg));
527 # there are no newlines allowed inside msg
528 $msg=~ s/\n//g;
529 return $msg;
530 }
533 sub decrypt_msg {
535 my ($msg, $key) = @_ ;
536 $msg = &decode_base64($msg);
537 my $my_cipher = &create_ciphering($key);
538 $msg = $my_cipher->decrypt($msg);
539 $msg =~ s/\0*//g;
540 return $msg;
541 }
544 sub get_server_addresses {
545 my $domain= shift;
546 my @result;
548 my $error = 0;
549 my $res = Net::DNS::Resolver->new;
550 my $query = $res->send("_gosa-si._tcp.".$domain, "SRV");
551 my @hits;
553 if ($query) {
554 foreach my $rr ($query->answer) {
555 push(@hits, $rr->target.":".$rr->port);
556 }
557 }
558 else {
559 #warn "query failed: ", $res->errorstring, "\n";
560 $error++;
561 }
563 if( $error == 0 ) {
564 foreach my $hit (@hits) {
565 my ($hit_name, $hit_port) = split(/:/, $hit);
566 chomp($hit_name);
567 chomp($hit_port);
569 my $address_query = $res->send($hit_name);
570 if( 1 == length($address_query->answer) ) {
571 foreach my $rr ($address_query->answer) {
572 push(@result, $rr->address.":".$hit_port);
573 }
574 }
575 }
576 }
578 return @result;
579 }
582 #=== FUNCTION ================================================================
583 # NAME: send_msg_hash_to_target
584 # PARAMETERS: msg_hash - hash - xml_hash created with function create_xml_hash
585 # PeerAddr string - socket address to send msg
586 # PeerPort string - socket port, if not included in socket address
587 # RETURNS: nothing
588 # DESCRIPTION: ????
589 #===============================================================================
590 sub send_msg_hash_to_target {
591 my ($msg_hash, $address, $encrypt_key) = @_ ;
592 my $msg = &create_xml_string($msg_hash);
593 my $header = @{$msg_hash->{'header'}}[0];
594 my $error = &send_msg_to_target($msg, $address, $encrypt_key, $header);
596 return $error;
597 }
600 sub send_msg_to_target {
601 my ($msg, $address, $encrypt_key, $msg_header) = @_ ;
602 my $error = 0;
604 if( $msg_header ) {
605 $msg_header = "'$msg_header'-";
606 }
607 else {
608 $msg_header = "";
609 }
611 # encrypt xml msg
612 my $crypted_msg = &encrypt_msg($msg, $encrypt_key);
614 # opensocket
615 my $socket = &open_socket($address);
616 if( !$socket ) {
617 daemon_log("cannot send ".$msg_header."msg to $address , host not reachable", 1);
618 $error++;
619 }
621 if( $error == 0 ) {
622 # send xml msg
623 print $socket $crypted_msg."\n";
625 daemon_log("send ".$msg_header."msg to $address", 1);
626 daemon_log("message:\n$msg", 8);
628 }
630 # close socket in any case
631 if( $socket ) {
632 close $socket;
633 }
635 return $error;
636 }
639 sub write_to_file {
640 my ($string, $file) = @_;
641 my $error = 0;
643 if( not defined $file || not -f $file ) {
644 &main::daemon_log("ERROR: $prg: check '-f file' failed: $file", 1);
645 $error++;
646 }
647 if( not defined $string || 0 == length($string)) {
648 &main::daemon_log("ERROR: $prg: empty string to write to file '$file'", 1);
649 $error++;
650 }
652 if( $error == 0 ) {
654 chomp($string);
656 open(FILE, ">> $file");
657 print FILE $string."\n";
658 close(FILE);
659 }
661 return;
662 }
665 sub open_socket {
666 my ($PeerAddr, $PeerPort) = @_ ;
667 if(defined($PeerPort)){
668 $PeerAddr = $PeerAddr.":".$PeerPort;
669 }
670 my $socket;
671 $socket = new IO::Socket::INET(PeerAddr => $PeerAddr,
672 Porto => "tcp",
673 Type => SOCK_STREAM,
674 Timeout => 5,
675 );
676 if(not defined $socket) {
677 return;
678 }
679 &daemon_log("open_socket: $PeerAddr", 7);
680 return $socket;
681 }
684 #=== FUNCTION ================================================================
685 # NAME: register_at_server
686 # PARAMETERS:
687 # RETURNS:
688 # DESCRIPTION:
689 #===============================================================================
690 sub register_at_gosa_si_server {
691 my ($kernel) = $_[KERNEL];
692 my $try_to_register = 0;
694 if( not $REGISTERED ) {
695 # create new passwd and ciphering object for client-server communication
696 $server_key = &create_passwd();
698 my $events = join( ",", keys %{$event_hash} );
699 while(1) {
701 if( $try_to_register >= @servers ) {
702 last;
703 }
705 # fetch first gosa-si-server from @servers
706 my $server = shift(@servers);
708 # append shifted gosa-si-server at the end of @servers, so looking for servers never stop if
709 # a registration never occured
710 push( @servers, $server );
712 # Check if our ip is resolvable - if not: don't try to register
713 my $ip= &get_local_ip_for_remote_ip(sprintf("%s", $server =~ /^([0-9\.]*?):.*$/));
714 my $dnsname= gethostbyaddr(inet_aton($ip), AF_INET);
715 if(!defined($dnsname)) {
716 &write_to_file("goto-error-dns:$ip", $fai_logpath);
717 exit(1);
718 }
720 # create registration msg
721 my $local_ip = &get_local_ip_for_remote_ip(sprintf("%s", $server =~ /^([0-9\.]*?):.*$/));
722 my $local_mac = &get_local_mac_for_remote_ip(sprintf("%s", $server =~ /^([0-9\.]*?):.*$/));
723 my $register_hash = &create_xml_hash("here_i_am", $local_ip.":".$client_port, $server);
724 &add_content2xml_hash($register_hash, "new_passwd", $server_key);
725 &add_content2xml_hash($register_hash, "mac_address", $local_mac);
726 &add_content2xml_hash($register_hash, "events", $events);
727 &add_content2xml_hash($register_hash, "gotoHardwareChecksum", $gotoHardwareChecksum);
729 # Add $HOSTNAME from ENV if force-hostname is set
730 if( defined($client_force_hostname) &&
731 $client_force_hostname eq "true") {
732 if(defined($ENV{HOSTNAME}) &&
733 length($ENV{HOSTNAME}) >0 ) {
734 &add_content2xml_hash($register_hash, "force-hostname", $ENV{HOSTNAME});
735 } else {
736 &main::daemon_log("force-hostname was set to true, but no \$HOSTNAME was found in Environment!",0);
737 }
738 }
740 # send xml hash to server with general server passwd
741 my $res = &send_msg_hash_to_target($register_hash, $server, $default_server_key);
742 if($res == 0) {
743 # reset try_to_register
744 $try_to_register = 0;
746 # Set fixed client address and mac address
747 $client_ip= &get_local_ip_for_remote_ip(sprintf("%s", $server =~ /^([0-9\.]*?):.*$/));
748 $client_address= "$client_ip:$client_port";
749 $client_mac_address = $local_mac;
750 $client_dnsname = $dnsname;
752 last;
753 } else {
754 $try_to_register++;
756 # wait 1 sec until trying to register again
757 sleep(1);
758 next;
759 }
760 }
762 if( $try_to_register >= @servers ) {
763 &write_to_file("gosa-si-no-server-available", $fai_logpath);
764 $kernel->delay_set('register_at_gosa_si_server', $delay_set_time);
765 }
766 else {
767 daemon_log("INFO: waiting for msg 'register_at_gosa_si_server'",5);
768 $kernel->delay_set('register_at_gosa_si_server', $delay_set_time);
769 # clear old settings and set it again
770 $kernel->delay_set('trigger_new_key', $server_key_lifetime);
771 }
772 }
773 return;
774 }
777 sub check_key_and_xml_validity {
778 my ($crypted_msg, $module_key) = @_;
780 my $msg;
781 my $msg_hash;
782 eval{
783 $msg = &decrypt_msg($crypted_msg, $module_key);
784 &main::daemon_log("decrypted_msg: \n$msg", 8);
786 $msg_hash = $xml->XMLin($msg, ForceArray=>1);
788 ##############
789 # check header
790 my $header_l = $msg_hash->{'header'};
791 if( 1 != @{$header_l} ) {
792 die 'no or more headers specified';
793 }
794 my $header = @{$header_l}[0];
795 if( 0 == length $header) {
796 die 'header has length 0';
797 }
799 ##############
800 # check source
801 my $source_l = $msg_hash->{'source'};
802 if( 1 != @{$source_l} ) {
803 die 'no or more than 1 sources specified';
804 }
805 my $source = @{$source_l}[0];
806 if( 0 == length $source) {
807 die 'source has length 0';
808 }
809 unless( $source =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d+$/ ) {
810 die "source '$source' is neither a complete ip-address with port nor 'GOSA'";
811 }
813 ##############
814 # check target
815 my $target_l = $msg_hash->{'target'};
816 if( 1 != @{$target_l} ) {
817 die 'no or more than 1 targets specified ';
818 }
819 my $target = @{$target_l}[0];
820 if( 0 == length $target) {
821 die 'target has length 0 ';
822 }
823 unless( $target =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d+$/ ){
824 die "source is neither a complete ip-address with port nor 'GOSA'";
825 }
826 };
827 if($@) {
828 &main::daemon_log("WARNING: do not understand the message or msg is not gosa-si envelope conform:", 5);
829 &main::daemon_log("$@", 8);
830 $msg = undef;
831 $msg_hash = undef;
832 }
834 return ($msg, $msg_hash);
835 }
838 sub check_outgoing_xml_validity {
839 my ($msg) = @_;
841 my $msg_hash;
842 eval{
843 $msg_hash = $xml->XMLin($msg, ForceArray=>1);
845 ##############
846 # check header
847 my $header_l = $msg_hash->{'header'};
848 if( 1 != @{$header_l} ) {
849 die 'no or more than one headers specified';
850 }
851 my $header = @{$header_l}[0];
852 if( 0 == length $header) {
853 die 'header has length 0';
854 }
856 ##############
857 # check source
858 my $source_l = $msg_hash->{'source'};
859 if( 1 != @{$source_l} ) {
860 die 'no or more than 1 sources specified';
861 }
862 my $source = @{$source_l}[0];
863 if( 0 == length $source) {
864 die 'source has length 0';
865 }
866 unless( $source =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d+$/ ||
867 $source =~ /^GOSA$/i ) {
868 die "source '$source' is neither a complete ip-address with port";
869 }
871 ##############
872 # check target
873 my $target_l = $msg_hash->{'target'};
874 if( 1 != @{$target_l} ) {
875 die "no or more than one targets specified";
876 }
877 foreach my $target (@$target_l) {
878 if( 0 == length $target) {
879 die "target has length 0";
880 }
881 unless( $target =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d+$/ ) {
882 die "target '$target' is not a complete ip-address with port or a valid target name";
883 }
884 }
885 };
886 if($@) {
887 daemon_log("WARNING: outgoing msg is not gosa-si envelope conform", 5);
888 daemon_log("$@ $msg", 8);
889 $msg_hash = undef;
890 }
891 return ($msg_hash);
892 }
895 sub import_events {
897 if (not -e $event_dir) {
898 daemon_log("ERROR: cannot find directory or directory is not readable: $event_dir", 1);
899 }
900 opendir (DIR, $event_dir) or die "ERROR while loading gosa-si-events from directory $event_dir : $!\n";
902 while (defined (my $event = readdir (DIR))) {
903 if( $event eq "." || $event eq ".." ) { next; }
905 eval{ require $event; };
906 if( $@ ) {
907 daemon_log("ERROR: import of event module '$event' failed", 1);
908 daemon_log("$@", 8);
909 next;
910 }
912 $event =~ /(\S*?).pm$/;
913 my $event_module = $1;
914 my $events_l = eval( $1."::get_events()") ;
915 foreach my $event_name (@{$events_l}) {
916 $event_hash->{$event_name} = $event_module;
917 }
919 }
921 my @all_events = keys %$event_hash;
922 my $all_events_string = join(", ", @all_events);
924 daemon_log("INFO: imported events: $all_events_string", 5);
925 }
927 sub trigger_new_key {
928 my ($kernel) = $_[KERNEL] ;
930 my $msg = "<xml><header>new_key</header><source>$client_address</source><target>$client_address</target></xml>";
931 &send_msg_to_target($msg, $client_address, $server_key, 'new_key');
933 $kernel->delay_set('trigger_new_key', $server_key_lifetime);
934 }
937 sub trigger_logged_in_users_report {
938 my ($kernel) = $_[KERNEL] ;
940 # just do if client is registered already
941 if( $REGISTERED ) {
942 my $result = qx(/usr/bin/w -hs);
943 my @res_lines;
945 if( defined $result ) {
946 chomp($result);
947 @res_lines = split("\n", $result);
948 }
950 my @logged_in_user_list;
951 foreach my $line (@res_lines) {
952 chomp($line);
953 my @line_parts = split(/\s+/, $line);
954 push(@logged_in_user_list, $line_parts[0]);
955 }
956 system("echo 'CURRENTLY_LOGGED_IN ".join(" ", @logged_in_user_list)."' > /var/run/gosa-si-client.socket");
957 $kernel->delay_set('trigger_logged_in_users_report', $trigger_logged_in_users_report_delay);
958 } else {
959 # try it in 1 sec again
960 $kernel->delay_set('trigger_logged_in_users_report', 1);
961 }
962 }
965 sub generic_file_reset {
966 my ( $heap, $wheel_id ) = @_[ HEAP, ARG0 ];
968 my $service = $heap->{services}->{$wheel_id};
969 daemon_log("INFO: '$service' watching reset", 5);
970 return;
971 }
973 sub generic_file_error {
974 my ( $heap, $operation, $errno, $error_string, $wheel_id ) =
975 @_[ HEAP, ARG0, ARG1, ARG2, ARG3 ];
977 my $service = $heap->{services}->{$wheel_id};
978 daemon_log("ERROR: '$service' watcher $operation error $errno: $error_string", 1);
979 daemon_log("ERROR: shutting down '$service' file watcher", 1);
981 delete $heap->{services}->{$wheel_id};
982 delete $heap->{watchers}->{$wheel_id};
983 return;
984 }
986 sub fifo_got_record {
987 my $file_record = $_[ARG0];
988 my $header;
989 my $content = "";
991 $file_record =~ /^(\S+)[ ]?([\s\S]+)?$/;
992 if( defined $1 ) {
993 $header = $1;
994 } else {
995 return;
996 }
998 if( defined $2 ) {
999 $content = $2;
1000 }
1002 my $clmsg_hash = &create_xml_hash("CLMSG_$header", $client_address, $server_address, $content);
1003 &add_content2xml_hash($clmsg_hash, "macaddress", $client_mac_address);
1004 my $clmsg = &create_xml_string($clmsg_hash);
1005 &send_msg_to_target($clmsg, $server_address, $server_key, "CLMSG_$header");
1006 return;
1007 }
1010 sub _start {
1011 my ($kernel, $heap) = @_[KERNEL, HEAP];
1012 $kernel->alias_set('client_session');
1014 # force a registration at a gosa-si-server
1015 $kernel->yield('register_at_gosa_si_server');
1017 # install all file watcher defined
1018 while( my($file_name, $file) = each %files_to_watch ) {
1019 my $file_watcher = POE::Wheel::FollowTail->new(
1020 Filename => $file,
1021 InputEvent => $file_name."_record",
1022 ResetEvent => "file_reset",
1023 ErrorEvent => "file_error",
1024 );
1025 $heap->{services}->{ $file_watcher->ID } = $file_name;
1026 $heap->{watchers}->{ $file_watcher->ID } = $file_watcher;
1027 }
1028 $kernel->yield('trigger_logged_in_users_report');
1029 }
1032 sub _default {
1033 daemon_log("ERROR: can not handle incoming msg with header '$_[ARG0]'", 1);
1034 return;
1035 }
1038 sub server_input {
1039 my ($kernel, $heap, $input, $wheel) = @_[KERNEL, HEAP, ARG0, ARG1];
1040 my $error = 0;
1041 my $answer;
1043 daemon_log("Incoming msg:\n$input\n", 8);
1045 my ($msg, $msg_hash) = &check_key_and_xml_validity($input, $server_key);
1046 if( (!$msg) || (!$msg_hash) ) {
1047 daemon_log("Deciphering of incoming msg failed", 5);
1048 $error++;
1049 }
1052 ######################
1053 # process incoming msg
1054 if( $error == 0 ) {
1055 my $header = @{$msg_hash->{header}}[0];
1056 my $source = @{$msg_hash->{source}}[0];
1058 if( exists $event_hash->{$header} ) {
1059 # a event exists with the header as name
1060 daemon_log("found event '$header' at event-module '".$event_hash->{$header}."'", 5);
1061 no strict 'refs';
1062 $answer = &{$event_hash->{$header}."::$header"}($msg, $msg_hash);
1063 }
1064 else {
1065 daemon_log("WARNING: no event '$header' found in event modules under $event_dir", 1);
1066 }
1067 }
1069 ########
1070 # answer
1071 if( $answer ) {
1073 #check gosa-si envelope validity
1074 my $answer_hash = &check_outgoing_xml_validity($answer);
1076 if( $answer_hash ) {
1077 # answer is valid
1079 # preprocessing
1080 if( $answer =~ "<header>registered</header>") {
1081 # set registered flag to true to stop sending further registered msgs
1082 $REGISTERED = 1;
1083 }
1084 else {
1085 &send_msg_to_target($answer, $server_address, $server_key);
1086 }
1088 # postprocessing
1089 if( $answer =~ "<header>new_key</header>") {
1090 # set new key to global variable
1091 $answer =~ /<new_key>(\S*?)<\/new_key>/;
1092 my $new_key = $1;
1093 $server_key = $new_key;
1094 }
1095 }
1097 }
1099 return;
1100 }
1103 #==== MAIN = main ==============================================================
1104 # parse commandline options
1105 Getopt::Long::Configure( "bundling" );
1106 GetOptions("h|help" => \&usage,
1107 "c|config=s" => \$cfg_file,
1108 "f|foreground" => \$foreground,
1109 "v|verbose+" => \$verbose,
1110 );
1112 # read and set config parameters
1113 &check_cmdline_param ;
1114 &read_configfile($cfg_file, %cfg_defaults);
1115 &check_pid;
1118 # forward error messages to logfile
1119 if ( ! $foreground ) {
1120 open STDIN, '/dev/null' or die "Can’t read /dev/null: $!";
1121 open STDOUT, '>>/dev/null' or die "Can't write to /dev/null: $!";
1122 open STDERR, '>>/dev/null' or die "Can't write to /dev/null: $!";
1123 }
1125 # Just fork, if we are not in foreground mode
1126 if( ! $foreground ) {
1127 chdir '/' or die "Can't chdir to /: $!";
1128 $pid = fork;
1129 setsid or die "Can't start a new session: $!";
1130 umask 0;
1131 }
1132 else {
1133 $pid = $$;
1134 }
1136 # Do something useful - put our PID into the pid_file
1137 if( 0 != $pid ) {
1138 open( LOCK_FILE, ">$pid_file" );
1139 print LOCK_FILE "$pid\n";
1140 close( LOCK_FILE );
1141 if( !$foreground ) {
1142 exit( 0 )
1143 };
1144 }
1146 daemon_log(" ", 1);
1147 daemon_log("$prg started!", 1);
1149 # delete old DBsqlite lock files
1150 system('rm -f /tmp/gosa_si_lock*gosa-si-client*');
1152 # detect ip and mac address and complete host address
1153 $client_address = $client_ip.":".$client_port;
1154 my $network_interface= &get_interface_for_ip($client_ip);
1155 $client_mac_address= &get_mac($network_interface);
1156 daemon_log("gosa-si-client ip address detected: $client_ip", 1);
1157 daemon_log("gosa-si-client mac address detected: $client_mac_address", 1);
1160 # import events
1161 &import_events();
1164 # compute hardware checksum
1165 $gotoHardwareChecksum= &generate_hw_digest();
1166 daemon_log("gosa-si-client gotoHardwareChecksum detected: $gotoHardwareChecksum", 1);
1169 # create socket for incoming xml messages
1170 POE::Component::Server::TCP->new(
1171 Alias => 'gosa-si-client',
1172 Port => $client_port,
1173 ClientInput => \&server_input,
1174 );
1175 daemon_log("start socket for incoming xml messages at port '$client_port' ", 1);
1178 # prepare variables
1179 if( inet_aton($server_ip) ){ $server_ip = inet_ntoa(inet_aton($server_ip)); }
1180 ############################################################
1181 # to change
1182 if( $server_ip eq "127.0.1.1" ) { $server_ip = "127.0.0.1" }
1183 ############################################################
1184 if (defined $server_ip && defined $server_port) {
1185 $server_address = $server_ip.":".$server_port;
1186 }
1187 $xml = new XML::Simple();
1188 $default_server_key = $server_key;
1191 # add gosa-si-server address from config file at first position of server list
1192 my $server_check_cfg = Config::IniFiles->new( -file => $cfg_file );
1193 my $server_check = $server_check_cfg->val( "server", "ip");
1194 if( defined $server_check ) {
1195 unshift(@servers, $server_address);
1196 my $servers_string = join(", ", @servers);
1197 daemon_log("INFO: found servers in configuration file: $servers_string", 5);
1198 } else {
1199 my @tmp_servers;
1200 if ( !$server_domain) {
1201 # Try our DNS Searchlist
1202 for my $domain(get_dns_domains()) {
1203 chomp($domain);
1204 my @tmp_domains= &get_server_addresses($domain);
1205 if(@tmp_domains) {
1206 for my $tmp_server(@tmp_domains) {
1207 push @tmp_servers, $tmp_server;
1208 }
1209 }
1210 }
1211 if(@tmp_servers && length(@tmp_servers)==0) {
1212 daemon_log("ERROR: please specify a gosa-si-server address or a domain in config file", 1);
1213 kill 2, $$;
1214 }
1215 } else {
1216 @tmp_servers = &get_server_addresses($server_domain);
1217 if( 0 == @tmp_servers ) {
1218 daemon_log("ERROR: no gosa-si-server found in DNS for domain '$server_domain'",1);
1219 daemon_log("ERROR: please specify a gosa-si-server address or a domain in config file", 1);
1220 kill 2, $$;
1221 }
1222 }
1224 foreach my $server (@tmp_servers) {
1225 unshift(@servers, $server);
1226 }
1227 my $servers_string = join(", ", @servers);
1228 daemon_log("INFO: found servers in DNS: $servers_string", 5);
1229 }
1232 # open fifo for non-gosa-si-client-msgs to gosa-si-server
1233 POSIX::mkfifo("$gosa_si_client_fifo", "0600");
1236 POE::Session->create(
1237 inline_states => {
1238 _start => \&_start,
1239 _default => \&_default,
1240 register_at_gosa_si_server => \®ister_at_gosa_si_server,
1242 # trigger periodical tasks
1243 trigger_new_key => \&trigger_new_key,
1244 trigger_logged_in_users_report => \&trigger_logged_in_users_report,
1246 # handle records from each defined file differently
1247 fifo_record => \&fifo_got_record,
1249 # handle file resets and errors the same way for each file
1250 file_reset => \&generic_file_reset,
1251 file_error => \&generic_file_error,
1252 }
1253 );
1255 POE::Kernel->run();
1256 exit;