Code

454b1b765996b4ee94a73cdd8e317d7b1b17d6dc
[gosa.git] / gosa-si / gosa-si-client
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);
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 Net::DNS;
39 my $event_dir = "/usr/lib/gosa-si/client/events";
40 use lib "/usr/lib/gosa-si/client/events";
42 my ($cfg_file, %cfg_defaults, $foreground, $verbose, $pid_file, $opts_file, $procid, $pid, $log_file, $fai_logpath);
43 my ($server_ip, $server_port, $server_key, $server_timeout, $server_domain, $server_key_lifetime);
44 my ($client_ip, $client_port, $client_mac_address, $ldap_enabled, $ldap_config, $pam_config, $nss_config);
45 my $xml;
46 my $default_server_key;
47 my $event_hash;
48 my @servers;
49 my $gotoHardwareChecksum;
50 $verbose= 1;
52 # globalise variables which are used in imported events
53 our $cfg_file;
54 our $server_address;
55 our $client_address;
56 our $server_key;
58 # default variables
59 our $REGISTERED = 0;
61 # in function register_at_gosa_si_server, after which period of seconds a new registration should be tried if a registration was 
62 # not successful until now
63 my $delay_set_time = 5;
65 %cfg_defaults = (
66 "general" =>
67     {"log-file"           => [\$log_file, "/var/run/".$0.".log"],
68     "pid-file"            => [\$pid_file, "/var/run/".$0.".pid"],
69     "opts-file"            => [\$opts_file, "/var/run/".$0.".opts"],
70     },
71 "client" => 
72     {"port"        => [\$client_port, "20083"],
73      "ip"          => [\$client_ip, "0.0.0.0"],
74      "mac-address" => [\$client_mac_address, "00:00:00:00:00:00"],
75      "server-domain"       => [\$server_domain, ""],
76      "ldap"               => [\$ldap_enabled, 1],
77      "ldap-config"        => [\$ldap_config, "/etc/ldap/ldap.conf"],
78      "pam-config"         => [\$pam_config, "/etc/pam_ldap.conf"],
79      "nss-config"         => [\$nss_config, "/etc/libnss_ldap.conf"],
80      "fai-logpath"         => [\$fai_logpath, "/var/log/fai/fai.log"],
81     },
82 "server" => {
83     "ip"          => [\$server_ip, "127.0.0.1"],
84     "port"         => [\$server_port, "20081"],
85     "key"          => [\$server_key, ""],
86     "timeout"      => [\$server_timeout, 10],
87     "key-lifetime" => [\$server_key_lifetime, 600], 
88     },
90 );
93 #=== FUNCTIONS = functions =====================================================
95 #===  FUNCTION  ================================================================
96 #         NAME: check_cmdline_param
97 #   PARAMETERS: 
98 #      RETURNS:  
99 #  DESCRIPTION: 
100 #===============================================================================
101 sub check_cmdline_param () {
102     my $err_config;
103     my $err_counter = 0;
104         if(not defined($cfg_file)) {
105                 $cfg_file = "/etc/gosa-si/client.conf";
106                 if(! -r $cfg_file) {
107                         $err_config = "please specify a config file";
108                         $err_counter += 1;
109                 }
110     }
111     if( $err_counter > 0 ) {
112         &usage( "", 1 );
113         if( defined( $err_config)) { print STDERR "$err_config\n"}
114         print STDERR "\n";
115         exit( -1 );
116     }
120 #===  FUNCTION  ================================================================
121 #         NAME:  read_configfile
122 #   PARAMETERS:  cfg_file - string - 
123 #      RETURNS:  
124 #  DESCRIPTION: 
125 #===============================================================================
126 sub read_configfile {
127     my ($cfg_file, %cfg_defaults) = @_ ;
128     my $cfg;
129     if( defined( $cfg_file) && ( length($cfg_file) > 0 )) {
130         if( -r $cfg_file ) {
131             $cfg = Config::IniFiles->new( -file => $cfg_file );
132         } else {
133             print STDERR "Couldn't read config file!";
134         }
135     } else {
136         $cfg = Config::IniFiles->new() ;
137     }
138     foreach my $section (keys %cfg_defaults) {
139         foreach my $param (keys %{$cfg_defaults{ $section }}) {
140             my $pinfo = $cfg_defaults{ $section }{ $param };
141             ${@$pinfo[ 0 ]} = $cfg->val( $section, $param, @$pinfo[ 1 ] );
142         }
143     }
147 #===  FUNCTION  ================================================================
148 #         NAME: check_pid
149 #   PARAMETERS:
150 #      RETURNS:
151 #  DESCRIPTION:
152 #===============================================================================
153 sub check_pid {
154     $pid = -1;
155     # Check, if we are already running
156     if( open(LOCK_FILE, "<$pid_file") ) {
157         $pid = <LOCK_FILE>;
158         if( defined $pid ) {
159             chomp( $pid );
160             if( -f "/proc/$pid/stat" ) {
161                 my($stat) = `cat /proc/$pid/stat` =~ m/$pid \((.+)\).*/;
162                 if( $0 eq $stat ) {
163                     close( LOCK_FILE );
164                     exit -1;
165                 }
166             }
167         }
168         close( LOCK_FILE );
169         unlink( $pid_file );
170     }
172     # create a syslog msg if it is not to possible to open PID file
173     if (not sysopen(LOCK_FILE, $pid_file, O_WRONLY|O_CREAT|O_EXCL, 0644)) {
174         my($msg) = "Couldn't obtain lockfile '$pid_file' ";
175         if (open(LOCK_FILE, '<', $pid_file)
176                 && ($pid = <LOCK_FILE>))
177         {
178             chomp($pid);
179             $msg .= "(PID $pid)\n";
180         } else {
181             $msg .= "(unable to read PID)\n";
182         }
183         if( ! ($foreground) ) {
184             openlog( $0, "cons,pid", "daemon" );
185             syslog( "warning", $msg );
186             closelog();
187         }
188         else {
189             print( STDERR " $msg " );
190         }
191         exit( -1 );
192     }
196 #===  FUNCTION  ================================================================
197 #         NAME:  logging
198 #   PARAMETERS:  level - string - default 'info' 
199 #                msg - string - 
200 #                facility - string - default 'LOG_DAEMON' 
201 #      RETURNS:  
202 #  DESCRIPTION: 
203 #===============================================================================
204 sub daemon_log {
205     # log into log_file
206     my( $msg, $level ) = @_;
207     if(not defined $msg) { return }
208     if(not defined $level) { $level = 1 }
209     if(defined $log_file){
210         open(LOG_HANDLE, ">>$log_file");
211         if(not defined open( LOG_HANDLE, ">>$log_file" )) {
212             print STDERR "cannot open $log_file: $!";
213             return }
214             chomp($msg);
215             if($level <= $verbose){
216                 my ($seconds, $minutes, $hours, $monthday, $month,
217                         $year, $weekday, $yearday, $sommertime) = localtime(time);
218                 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
219                 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
220                 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
221                 my @monthnames = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
222                 $month = $monthnames[$month];
223                 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
224                 $year+=1900;
225                 my $name = $0;
226                 $name =~ s/\.\///;
228                 my $log_msg = "$month $monthday $hours:$minutes:$seconds $name $msg\n";
229                 print LOG_HANDLE $log_msg;
230                 if( $foreground ) { 
231                     print STDERR $log_msg;
232                 }
233             }
234         close( LOG_HANDLE );
235     }
236 #log into syslog
237 #    my ($msg, $level, $facility) = @_;
238 #    if(not defined $msg) {return}
239 #    if(not defined $level) {$level = "info"}
240 #    if(not defined $facility) {$facility = "LOG_DAEMON"}
241 #    openlog($0, "pid,cons,", $facility);
242 #    syslog($level, $msg);
243 #    closelog;
244 #    return;
248 #===  FUNCTION  ================================================================
249 #         NAME:  get_interfaces 
250 #   PARAMETERS:  none
251 #      RETURNS:  (list of interfaces) 
252 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
253 #===============================================================================
254 sub get_interfaces {
255     my @result;
256     my $PROC_NET_DEV= ('/proc/net/dev');
258     open(PROC_NET_DEV, "<$PROC_NET_DEV")
259         or die "Could not open $PROC_NET_DEV";
261     my @ifs = <PROC_NET_DEV>;
263     close(PROC_NET_DEV);
265     # Eat first two line
266     shift @ifs;
267     shift @ifs;
269     chomp @ifs;
270     foreach my $line(@ifs) {
271         my $if= (split /:/, $line)[0];
272         $if =~ s/^\s+//;
273         push @result, $if;
274     }
276     return @result;
279 #===  FUNCTION  ================================================================
280 #         NAME:  get_mac 
281 #   PARAMETERS:  interface name (i.e. eth0)
282 #      RETURNS:  (mac address) 
283 #  DESCRIPTION:  Uses ioctl to get mac address directly from system.
284 #===============================================================================
285 sub get_mac {
286         my $ifreq= shift;
287         my $result;
288         if ($ifreq && length($ifreq) > 0) { 
289                 if($ifreq eq "all") {
290                         if(defined($server_ip)) {
291                                 $result = &get_local_mac_for_remote_ip($server_ip);
292                         } 
293                         elsif ($client_mac_address && length($client_mac_address) > 0 && !($client_mac_address eq "00:00:00:00:00:00")){
294                                 $result = &client_mac_address;
295                         } 
296                         else {
297                                 $result = "00:00:00:00:00:00";
298                         }
299                 } else {
300                         my $SIOCGIFHWADDR= 0x8927;     # man 2 ioctl_list
302                         # A configured MAC Address should always override a guessed value
303                         if ($client_mac_address and length($client_mac_address) > 0 and not($client_mac_address eq "00:00:00:00:00:00")) {
304                                 $result= $client_mac_address;
305                         }
306                         else {
307                                 socket SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('ip')
308                                         or die "socket: $!";
310                                 if(ioctl SOCKET, $SIOCGIFHWADDR, $ifreq) {
311                                         my ($if, $mac)= unpack 'h36 H12', $ifreq;
313                                         if (length($mac) > 0) {
314                                                 $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])$/;
315                                                 $mac= sprintf("%s:%s:%s:%s:%s:%s", $1, $2, $3, $4, $5, $6);
316                                                 $result = $mac;
317                                         }
318                                 }
319                         }
320                 }
321         }
322         return $result;
326 #===  FUNCTION  ================================================================
327 #         NAME:  get_interface_for_ip
328 #   PARAMETERS:  ip address (i.e. 192.168.0.1)
329 #      RETURNS:  array: list of interfaces if ip=0.0.0.0, matching interface if found, undef else
330 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
331 #===============================================================================
332 sub get_interface_for_ip {
333     my $result;
334     my $ip= shift;
335     if ($ip && length($ip) > 0) {
336         my @ifs= &get_interfaces();
337         if($ip eq "0.0.0.0") {
338             $result = "all";
339         } else {
340             foreach (@ifs) {
341                 my $if=$_;
342                 if(get_ip($if) eq $ip) {
343                     $result = $if;
344                     last;
345                 }
346             }       
347         }
348     }       
349     return $result;
353 #===  FUNCTION  ================================================================
354 #         NAME:  get_ip 
355 #   PARAMETERS:  interface name (i.e. eth0)
356 #      RETURNS:  (ip address) 
357 #  DESCRIPTION:  Uses ioctl to get ip address directly from system.
358 #===============================================================================
359 sub get_ip {
360     my $ifreq= shift;
361     my $result= "";
362     my $SIOCGIFADDR= 0x8915;       # man 2 ioctl_list
363         my $proto= getprotobyname('ip');
365     socket SOCKET, PF_INET, SOCK_DGRAM, $proto
366         or die "socket: $!";
368     if(ioctl SOCKET, $SIOCGIFADDR, $ifreq) {
369         my ($if, $sin)    = unpack 'a16 a16', $ifreq;
370         my ($port, $addr) = sockaddr_in $sin;
371         my $ip            = inet_ntoa $addr;
373         if ($ip && length($ip) > 0) {
374             $result = $ip;
375         }
376     }
378     return $result;
382 #===  FUNCTION  ================================================================
383 #         NAME:  get_local_mac_for_remote_ip
384 #   PARAMETERS:  none (takes server_ip from global variable)
385 #      RETURNS:  (ip address from interface that is used for communication) 
386 #  DESCRIPTION:  Uses ioctl to get routing table from system, checks which entry
387 #                matches (defaultroute last).
388 #===============================================================================
389 sub get_local_mac_for_remote_ip {
390         my $server_ip= shift;
391         my $result= "00:00:00:00:00:00";
393         if($server_ip =~ /^(\d\d?\d?\.){3}\d\d?\d?$/) {
394                 my $PROC_NET_ROUTE= ('/proc/net/route');
396                 open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
397                         or die "Could not open $PROC_NET_ROUTE";
399                 my @ifs = <PROC_NET_ROUTE>;
401                 close(PROC_NET_ROUTE);
403                 # Eat header line
404                 shift @ifs;
405                 chomp @ifs;
406                 foreach my $line(@ifs) {
407                         my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
408                         my $destination;
409                         my $mask;
410                         my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
411                         $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
412                         ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
413                         $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
414                         if(new NetAddr::IP($server_ip)->within(new NetAddr::IP($destination, $mask))) {
415                                 # destination matches route, save mac and exit
416                                 $result= &get_mac($Iface);
417                                 last;
418                         }
419                 }
420         } else {
421                 daemon_log("get_local_mac_for_remote_ip was called with a non-ip parameter: $server_ip", 1);
422         }
423         return $result;
426 sub get_local_ip_for_remote_ip {
427         my $server_ip= shift;
428         my $result="0.0.0.0";
430         if($server_ip =~ /^(\d\d?\d?\.){3}\d\d?\d?$/) {
431                 if($server_ip eq "127.0.0.1") {
432                         $result="127.0.0.1";
433                 } else {
434                         my $PROC_NET_ROUTE= ('/proc/net/route');
436                         open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
437                                 or die "Could not open $PROC_NET_ROUTE";
439                         my @ifs = <PROC_NET_ROUTE>;
441                         close(PROC_NET_ROUTE);
443                         # Eat header line
444                         shift @ifs;
445                         chomp @ifs;
446                         foreach my $line(@ifs) {
447                                 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
448                                 my $destination;
449                                 my $mask;
450                                 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
451                                 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
452                                 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
453                                 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
454                                 if(new NetAddr::IP($server_ip)->within(new NetAddr::IP($destination, $mask))) {
455                                         # destination matches route, save mac and exit
456                                         $result= &get_ip($Iface);
457                                         last;
458                                 }
459                         }
460                 }
461         } else {
462                 daemon_log("get_local_ip_for_remote_ip was called with a non-ip parameter: $server_ip", 1);
463         }
464         return $result;
467 sub new_ldap_config {
468     my ($msg_hash) = @_ ;
469     my $element;
470     my @ldap_uris;
471     my $ldap_base;
472     my @ldap_options;
473     my @pam_options;
474     my @nss_options;
475     my $goto_admin;
476     my $goto_secret;
477     my $admin_base= "";
478     my $department= "";
479     my $release= "";
480     my $unit_tag;
482     # Transform input into array
483     while ( my ($key, $value) = each(%$msg_hash) ) {
484         if ($key =~ /^(source|target|header)$/) {
485                 next;
486         }
488         foreach $element (@$value) {
489                 if ($key =~ /^ldap_uri$/) {
490                         push (@ldap_uris, $element);
491                         next;
492                 }
493                 if ($key =~ /^ldap_base$/) {
494                         $ldap_base= $element;
495                         next;
496                 }
497                 if ($key =~ /^goto_admin$/) {
498                         $goto_admin= $element;
499                         next;
500                 }
501                 if ($key =~ /^goto_secret$/) {
502                         $goto_secret= $element;
503                         next;
504                 }
505                 if ($key =~ /^ldap_cfg$/) {
506                         push (@ldap_options, "$element");
507                         next;
508                 }
509                 if ($key =~ /^pam_cfg$/) {
510                         push (@pam_options, "$element");
511                         next;
512                 }
513                 if ($key =~ /^nss_cfg$/) {
514                         push (@nss_options, "$element");
515                         next;
516                 }
517                 if ($key =~ /^admin_base$/) {
518                         $admin_base= $element;
519                         next;
520                 }
521                 if ($key =~ /^department$/) {
522                         $department= $element;
523                         next;
524                 }
525                 if ($key =~ /^unit_tag$/) {
526                         $unit_tag= $element;
527                         next;
528                 }
529                 if ($key =~ /^release$/) {
530                         $release= $element;
531                         next;
532                 }
533         }
534     }
536     # Unit tagging enabled?
537     if (defined $unit_tag){
538             push (@pam_options, "pam_filter gosaUnitTag=$unit_tag");
539             push (@nss_options, "nss_base_passwd  $admin_base?sub?gosaUnitTag=$unit_tag");
540             push (@nss_options, "nss_base_group   $admin_base?sub?gosaUnitTag=$unit_tag");
541     }
543     # Setup ldap.conf
544     my $file1;
545     my $file2;
546     open(file1, "> $ldap_config");
547     print file1 "# This file was automatically generated by gosa-si-client. Do not change.\n";
548     print file1 "URI";
549     foreach $element (@ldap_uris) {
550         print file1 " $element";
551     }
552     print file1 "\nBASE $ldap_base\n";
553     foreach $element (@ldap_options) {
554         print file1 "$element\n";
555     }
556     close (file1);
557     daemon_log("wrote $ldap_config", 5);
559     # Setup pam_ldap.conf / libnss_ldap.conf
560     open(file1, "> $pam_config");
561     open(file2, "> $nss_config");
562     print file1 "# This file was automatically generated by gosa-si-client. Do not change.\n";
563     print file2 "# This file was automatically generated by gosa-si-client. Do not change.\n";
564     print file1 "uri";
565     print file2 "uri";
566     foreach $element (@ldap_uris) {
567         print file1 " $element";
568         print file2 " $element";
569     }
570     print file1 "\nbase $ldap_base\n";
571     print file2 "\nbase $ldap_base\n";
572     foreach $element (@pam_options) {
573         print file1 "$element\n";
574     }
575     foreach $element (@nss_options) {
576         print file2 "$element\n";
577     }
578     close (file2);
579     daemon_log("wrote $nss_config", 5);
580     close (file1);
581     daemon_log("wrote $pam_config", 5);
583     # Create goto.secrets if told so - for compatibility reasons
584     if (defined $goto_admin){
585             open(file1, "> /etc/goto/secret");
586             close(file1);
587             chown(0,0, "/etc/goto/secret");
588             chmod(0600, "/etc/goto/secret");
589             open(file1, "> /etc/goto/secret");
590             print file1 "GOTOADMIN=\"$goto_admin\"\nGOTOSECRET=\"$goto_secret\"\n";
591             close(file1);
592             daemon_log("wrote /etc/goto/secret", 5);
593     }
595     
597     # Write shell based config
598     my $cfg_name= dirname($ldap_config)."/ldap-shell.conf";
599     open(file1, "> $cfg_name");
600     print file1 "LDAP_BASE=\"$ldap_base\"\n";
601     print file1 "ADMIN_BASE=\"$admin_base\"\n";
602     print file1 "DEPARTMENT=\"$department\"\n";
603     print file1 "RELEASE=\"$release\"\n";
604     print file1 "UNIT_TAG=\"".(defined $unit_tag ? "$unit_tag" : "")."\"\n";
605     print file1 "UNIT_TAG_FILTER=\"".(defined $unit_tag ? "(gosaUnitTag=$unit_tag)" : "")."\"\n";
606     close(file1);
607     daemon_log("wrote $cfg_name", 5);
609     return;
614 sub generate_hw_digest {
615         my $hw_data;
616         foreach my $line (split /\n/, `cat /proc/bus/pci/devices`) {
617                 $hw_data.= sprintf "%s", $line =~ /[^\s]+\s([^\s]+)\s.*/;
618         }
619         return(md5_base64($hw_data));
623 sub create_passwd {
624     my $new_passwd = "";
625     for(my $i=0; $i<31; $i++) {
626         $new_passwd .= ("a".."z","A".."Z",0..9)[int(rand(62))]
627     }
629     return $new_passwd;
633 sub get_server_addresses {
634     my $domain= shift;
635     my @result;
636  
637     my $error = 0;
638     my $res   = Net::DNS::Resolver->new;
639     my $query = $res->send("_gosad._tcp.".$domain, "SRV");
640     my @hits;
642     if ($query) {
643         foreach my $rr ($query->answer) {
644             push(@hits, $rr->target.":".$rr->port);
645         }
646     }
647     else {
648         #warn "query failed: ", $res->errorstring, "\n";
649         $error++;
650     }
652     if( $error == 0 ) {
653         foreach my $hit (@hits) {
654             my ($hit_name, $hit_port) = split(/:/, $hit);
656             my $address_query = $res->send($hit_name);
657             if( 1 == length($address_query->answer) ) {
658                 foreach my $rr ($address_query->answer) {
659                     push(@result, $rr->address.":".$hit_port);
660                 }
661             }
662         }
663     }
665 #    my $dig_cmd= 'dig +nocomments srv _gosad._tcp.'.$domain;
667 #    my $output= `$dig_cmd 2>&1`;
668 #    open (PIPE, "$dig_cmd 2>&1 |");
669 #    while(<PIPE>) {
670 #        chomp $_;
671 #        # If it's not a comment
672 #        if($_ =~ m/^[^;]/) {
673 #            my @matches= split /\s+/;
675 #            # Push hostname with port
676 #            if($matches[3] eq 'SRV') {
677 #                push @result, $matches[7].':'.$matches[6];
678 #            } elsif ($matches[3] eq 'A') {
679 #                my $i=0;
681 #                # Substitute the hostname with the ip address of the matching A record
682 #                foreach my $host (@result) {
683 #                    if ((split /\:/, $host)[0] eq $matches[0]) {
684 #                        $result[$i]= $matches[4].':'.(split /\:/, $host)[1];
685 #                    }
686 #                    $i++;
687 #                }
688 #            }
689 #        }
690 #    }
691 #    close(PIPE);
692     return @result;
696 ##===  FUNCTION  ================================================================
697 ##         NAME:  create_ciphering
698 ##   PARAMETERS:  passwd - string - used to create ciphering
699 ##      RETURNS:  cipher - object
700 ##  DESCRIPTION:  creates a Crypt::Rijndael::MODE_CBC object with passwd as key
701 ##===============================================================================
702 #sub create_ciphering {
703 #    my ($passwd) = @_;
704 #    $passwd = substr(md5_hex("$passwd") x 32, 0, 32);
705 #    my $iv = substr(md5_hex('GONICUS GmbH'),0, 16);
707 #    #daemon_log("iv: $iv", 7);
708 #    #daemon_log("key: $passwd", 7);
709 #    my $my_cipher = Crypt::Rijndael->new($passwd , Crypt::Rijndael::MODE_CBC());
710 #    $my_cipher->set_iv($iv);
711 #    return $my_cipher;
712 #}
715 #sub create_ciphering {
716 #    my ($passwd) = @_;
717 #    $passwd = substr(md5_hex("$passwd") x 32, 0, 32);
718 #    my $iv = substr(md5_hex('GONICUS GmbH'),0, 16);
719 #    my $my_cipher = Crypt::Rijndael->new($passwd , Crypt::Rijndael::MODE_CBC());
720 #    $my_cipher->set_iv($iv);
721 #    return $my_cipher;
722 #}
725 #sub encrypt_msg {
726 #    my ($msg, $key) = @_;
727 #    my $my_cipher = &create_ciphering($key);
728 #    {
729 #      use bytes;
730 #      $msg = "\0"x(16-length($msg)%16).$msg;
731 #    }
732 #    $msg = $my_cipher->encrypt($msg);
733 #    chomp($msg = &encode_base64($msg));
734 #    # there are no newlines allowed inside msg
735 #    $msg=~ s/\n//g;
736 #    return $msg;
737 #}
740 #sub decrypt_msg {
741 #    my ($msg, $key) = @_ ;
742 #    $msg = &decode_base64($msg);
743 #    my $my_cipher = &create_ciphering($key);
744 #    $msg = $my_cipher->decrypt($msg); 
745 #    $msg =~ s/\0*//g;
746 #    return $msg;
747 #}
750 #===  FUNCTION  ================================================================
751 #         NAME:  send_msg_hash_to_target
752 #   PARAMETERS:  msg_hash - hash - xml_hash created with function create_xml_hash
753 #                PeerAddr string - socket address to send msg
754 #                PeerPort string - socket port, if not included in socket address
755 #      RETURNS:  nothing
756 #  DESCRIPTION:  ????
757 #===============================================================================
758 sub send_msg_hash_to_target {
759     my ($msg_hash, $address, $encrypt_key) = @_ ;
760     my $msg = &create_xml_string($msg_hash);
761     my $header = @{$msg_hash->{'header'}}[0];
762     my $error = &send_msg_to_target($msg, $address, $encrypt_key, $header);
763     
764     return $error;
768 sub send_msg_to_target {
769     my ($msg, $address, $encrypt_key, $msg_header) = @_ ;
770     my $error = 0;
772     if( $msg_header ) {
773         $msg_header = "'$msg_header'-";
774     }
775     else {
776         $msg_header = "";
777     }
779     # encrypt xml msg
780     my $crypted_msg = &encrypt_msg($msg, $encrypt_key);
782     # opensocket
783     my $socket = &open_socket($address);
784     if( !$socket ) {
785         daemon_log("cannot send ".$msg_header."msg to $address , host not reachable", 1);
786         $error++;
787     }
788     
789     if( $error == 0 ) {
790         # send xml msg
791         print $socket $crypted_msg."\n";
793         daemon_log("send ".$msg_header."msg to $address", 1);
794         daemon_log("message:\n$msg", 8);
796     }
798     # close socket in any case
799     if( $socket ) {
800         close $socket;
801     }
803     return $error;
807 sub write_to_file {
808     my ($string, $file) = @_;
809     my $error = 0;
811     if( not defined $file || not -f $file ) {
812         &main::daemon_log("ERROR: $0: check '-f file' failed: $file", 1);
813         $error++;
814     }
815     if( not defined $string || 0 == length($string)) {
816         &main::daemon_log("ERROR: $0: empty string to write to file '$file'", 1);
817         $error++;
818     }
819     
820     if( $error == 0 ) {
822         chomp($string);
823     
824         open(FILE, ">> $file");
825         print FILE $string."\n";
826         close(FILE);
827     }
829     return;    
833 sub open_socket {
834     my ($PeerAddr, $PeerPort) = @_ ;
835     if(defined($PeerPort)){
836         $PeerAddr = $PeerAddr.":".$PeerPort;
837     }
838     my $socket;
839     $socket = new IO::Socket::INET(PeerAddr => $PeerAddr,
840             Porto => "tcp",
841             Type => SOCK_STREAM,
842             Timeout => 5,
843             );
844     if(not defined $socket) {
845         return;
846     }
847     &daemon_log("open_socket: $PeerAddr", 7);
848     return $socket;
852 #===  FUNCTION  ================================================================
853 #         NAME:  register_at_server
854 #   PARAMETERS:  
855 #      RETURNS:  
856 #  DESCRIPTION:  
857 #===============================================================================
858 sub register_at_gosa_si_server {
859     my ($kernel) = $_[KERNEL];
860     my $try_to_register = 0;
862     if( not $REGISTERED ) {
863         # create new passwd and ciphering object for client-server communication
864         $server_key = &create_passwd();
866         my $events = join( ", ", keys %{$event_hash} );
867         while(1) {
869             if( $try_to_register >= @servers )  {
870                 last;
871             }
873             # fetch first gosa-si-server from @servers
874             my $server = shift(@servers);
876             # append shifted gosa-si-server at the end of @servers, so looking for servers never stop if
877             # a registration never occured
878             push( @servers, $server );
879                 
880                         # Check if our ip is resolvable - if not: don't try to register
881                         my $ip= &get_local_ip_for_remote_ip(sprintf("%s", $server =~ /^([0-9\.]*?):.*$/));
882                         my $resolver= Net::DNS::Resolver->new;
883                         my $dnsresult= $resolver->search($ip);
884                         my $dnsname="";
885                         if(!defined($dnsresult)) {
886                                 &write_to_file("goto-error-dns:$ip", $fai_logpath);
887                                 exit(1);
888                         } else {
889                                 $dnsname=$dnsresult->{answer}[0]->{ptrdname};
890                         }
892             # create registration msg
893             my $local_ip = &get_local_ip_for_remote_ip(sprintf("%s", $server =~ /^([0-9\.]*?):.*$/));
894             my $local_mac = &get_local_mac_for_remote_ip(sprintf("%s", $server =~ /^([0-9\.]*?):.*$/));
895             my $register_hash = &create_xml_hash("here_i_am", $local_ip.":".$client_port, $server);
896             &add_content2xml_hash($register_hash, "new_passwd", $server_key);
897                         &add_content2xml_hash($register_hash, "mac_address", $local_mac);
898             &add_content2xml_hash($register_hash, "events", $events);
899             &add_content2xml_hash($register_hash, "gotoHardwareChecksum", $gotoHardwareChecksum);
901             # send xml hash to server with general server passwd
902             my $res = &send_msg_hash_to_target($register_hash, $server, $default_server_key);
903                         if($res == 0) {
904                 # reset try_to_register
905                 $try_to_register = 0;
906     
907                                 # Set fixed client address
908                                 $client_ip= &get_local_ip_for_remote_ip(sprintf("%s", $server =~ /^([0-9\.]*?):.*$/));
909                                 $client_address= "$client_ip:$client_port";
911                                 # Write the MAC address to file
912                                 if(stat($opts_file)) {
913                                         unlink($opts_file);
914                                 }
915                                 my $opts_file_FH;
916                                 open($opts_file_FH, ">$opts_file");
917                                 print $opts_file_FH "MAC=\"$local_mac\"\n";
918                                 print $opts_file_FH "IPADDRESS=\"$client_ip\"\n";
919                                 print $opts_file_FH "HOSTNAME=\"$dnsname\"\n";
920                                 close($opts_file_FH);
921                                 last;
922                         } else {
923                 $try_to_register++;
924                 # wait 1 sec until trying to register again
925                 sleep(1);
926                                 next;
927                         }
928         }
930         if( $try_to_register >= @servers )  {
931             &write_to_file("gosa-si-no-server-available", $fai_logpath);
932              $kernel->delay_set('register_at_gosa_si_server', $delay_set_time);
933         } 
934         else {
935             daemon_log("waiting for msg 'register_at_gosa_si_server'",1);
936             $kernel->delay_set('register_at_gosa_si_server', $delay_set_time);
937             # clear old settings and set it again
938             $kernel->delay_set('trigger_new_key', $server_key_lifetime);
939         }
940     }
941     return;
943     
945 sub check_key_and_xml_validity {
946     my ($crypted_msg, $module_key) = @_;
947 #print STDERR "crypted_msg:$crypted_msg\n";
948 #print STDERR "modul_key:$module_key\n";
950     my $msg;
951     my $msg_hash;
952     eval{
953         $msg = &decrypt_msg($crypted_msg, $module_key);
954         &main::daemon_log("decrypted_msg: \n$msg", 8);
956         $msg_hash = $xml->XMLin($msg, ForceArray=>1);
958         # check header
959         my $header_l = $msg_hash->{'header'};
960         if( 1 != @{$header_l} ) {
961             die 'no or more headers specified';
962         }
963         my $header = @{$header_l}[0];
964         if( 0 == length $header) {
965             die 'header has length 0';
966         }
968         # check source
969         my $source_l = $msg_hash->{'source'};
970         if( 1 != @{$source_l} ) {
971             die 'no or more sources specified';
972         }
973         my $source = @{$source_l}[0];
974         if( 0 == length $source) {
975             die 'source has length 0';
976         }
978         # check target
979         my $target_l = $msg_hash->{'target'};
980         if( 1 != @{$target_l} ) {
981             die 'no or more targets specified ';
982         }
983         my $target = @{$target_l}[0];
984         if( 0 == length $target) {
985             die 'target has length 0 ';
986         }
988     };
989     if($@) {
990         &main::daemon_log("WARNING: do not understand the message or msg is not gosa-si envelope conform:", 5);
991         &main::daemon_log("$@", 8);
992     }
994     return ($msg, $msg_hash);
998 sub import_events {
1000     if (not -e $event_dir) {
1001         daemon_log("ERROR: cannot find directory or directory is not readable: $event_dir", 1);   
1002     }
1003     opendir (DIR, $event_dir) or die "ERROR while loading gosa-si-events from directory $event_dir : $!\n";
1005     while (defined (my $event = readdir (DIR))) {
1006         if( $event eq "." || $event eq ".." ) { next; }    
1008         eval{ require $event; };
1009         if( $@ ) {
1010             daemon_log("ERROR: import of event module '$event' failed", 1);
1011             daemon_log("$@", 8);
1012             next;
1013         }
1015         $event =~ /(\S*?).pm$/;
1016         my $event_module = $1;
1017         my $events_l = eval( $1."::get_events()") ;
1018         foreach my $event_name (@{$events_l}) {
1019             $event_hash->{$event_name} = $event_module;
1020         }
1022     }
1025 sub trigger_new_key {
1026     my ($kernel) = $_[KERNEL] ;   
1028     my $msg = "<xml><header>new_key</header><source>$client_address</source><target>$client_address</target></xml>";
1029     &send_msg_to_target($msg, $client_address, $server_key, 'new_key');
1031     $kernel->delay_set('trigger_new_key', $server_key_lifetime);
1036 sub _start {
1037     my ($kernel) = $_[KERNEL];
1038     $kernel->alias_set('client_session');
1039     $kernel->yield('register_at_gosa_si_server');
1043 sub server_input {
1044     my ($kernel, $heap, $input, $wheel) = @_[KERNEL, HEAP, ARG0, ARG1];
1045     my $error = 0;
1046     my $answer;
1047     
1048     daemon_log("Incoming msg:\n$input\n", 8);
1050     my ($msg, $msg_hash) = &check_key_and_xml_validity($input, $server_key);
1051     if( (!$msg) || (!$msg_hash) ) {
1052         daemon_log("Deciphering of incoming msg failed", 5);
1053         $error++;
1054     }
1057     ######################
1058     # process incoming msg
1059     if( $error == 0 ) {
1060         my $header = @{$msg_hash->{header}}[0];
1061         my $source = @{$msg_hash->{source}}[0];
1063         if( exists $event_hash->{$header} ) {
1064             # a event exists with the header as name
1065             daemon_log("found event '$header' at event-module '".$event_hash->{$header}."'", 5);
1066             no strict 'refs';
1067             $answer = &{$event_hash->{$header}."::$header"}($msg, $msg_hash);
1068         }
1069         else {
1070             daemon_log("WARNING: no event '$header' found in event modules under $event_dir", 1);
1071         }
1072     }
1074     ########
1075     # answer
1076     if( $answer ) {
1077         # preprocessing
1078         if( $answer =~ "<header>registered</header>") {
1079             # set registered flag to true to stop sending further registered msgs
1080             $REGISTERED = 1;
1081         } 
1082         else {
1083             &send_msg_to_target($answer, $server_address, $server_key);
1084         }
1085         # postprocessing
1086         if( $answer =~ "<header>new_key</header>") {
1087             # set new key to global variable
1088             $answer =~ /<new_key>(\S*?)<\/new_key>/;
1089             my $new_key = $1;
1090             $server_key = $new_key;
1091         }
1092     }
1094     return;
1097 #==== MAIN = main ==============================================================
1098 #  parse commandline options
1099 Getopt::Long::Configure( "bundling" );
1100 GetOptions("h|help" => \&usage,
1101            "c|config=s" => \$cfg_file,
1102            "f|foreground" => \$foreground,
1103            "v|verbose+" => \$verbose,
1104            );
1106 #  read and set config parameters
1107 &check_cmdline_param ;
1108 &read_configfile($cfg_file, %cfg_defaults);
1109 &check_pid;
1112 # forward error messages to logfile
1113 if ( ! $foreground ) {
1114         open STDIN, '/dev/null' or die "Can’t read /dev/null: $!";
1115         open STDOUT, '>>/dev/null' or die "Can't write to /dev/null: $!";
1116         open STDERR, '>>/dev/null' or die "Can't write to /dev/null: $!";
1119 # Just fork, if we are not in foreground mode
1120 if( ! $foreground ) { 
1121     chdir '/'                 or die "Can't chdir to /: $!";
1122     $pid = fork;
1123     setsid                    or die "Can't start a new session: $!";
1124     umask 0;
1125
1126 else { 
1127     $pid = $$; 
1130 # Do something useful - put our PID into the pid_file
1131 if( 0 != $pid ) {
1132     open( LOCK_FILE, ">$pid_file" );
1133     print LOCK_FILE "$pid\n";
1134     close( LOCK_FILE );
1135     if( !$foreground ) { 
1136         exit( 0 ) 
1137     };
1140 daemon_log(" ", 1);
1141 daemon_log("$0 started!", 1);
1143 # delete old DBsqlite lock files
1144 system('rm -f /tmp/gosa_si_lock*gosa-si-client*');
1146 # detect ip and mac address and complete host address
1147 $client_address = $client_ip.":".$client_port;
1148 my $network_interface= &get_interface_for_ip($client_ip);
1149 $client_mac_address= &get_mac($network_interface);
1150 daemon_log("gosa-si-client ip address detected: $client_ip", 1);
1151 daemon_log("gosa-si-client mac address detected: $client_mac_address", 1);
1154 # import events
1155 &import_events();
1158 # compute hardware checksum
1159 $gotoHardwareChecksum= &generate_hw_digest();
1160 daemon_log("gosa-si-client gotoHardwareChecksum detected: $gotoHardwareChecksum", 1);
1163 # create socket for incoming xml messages
1164 POE::Component::Server::TCP->new(
1165     Alias => 'gosa-si-client',
1166         Port => $client_port,
1167         ClientInput => \&server_input,
1168 );
1169 daemon_log("start socket for incoming xml messages at port '$client_port' ", 1);
1172 # prepare variables
1173 if (defined $server_ip && defined $server_port) {
1174     $server_address = $server_ip.":".$server_port;
1176 $xml = new XML::Simple();
1177 $default_server_key = $server_key;
1180 # add gosa-si-server address from config file at first position of server list
1181 if (defined $server_address) {
1182     unshift(@servers, $server_address);
1183     my $servers_string = join(", ", @servers);
1184     daemon_log("found servers in configuration file: $servers_string", 5);
1185
1186 else {
1187     if ( !$server_domain) {
1188         daemon_log("ERROR: please specify a gosa-si-server address or a domain in config file", 1);
1189         exit( 1 );
1190     }
1191     my @tmp_servers = &get_server_addresses($server_domain);
1192     foreach my $server (@tmp_servers) { 
1193         unshift(@servers, $server); 
1194     }
1195     my $servers_string = join(", ", @servers);
1196     daemon_log("found servers in DNS: $servers_string", 5);
1202 POE::Session->create(
1203         inline_states => {
1204                 _start => \&_start, 
1205         register_at_gosa_si_server => \&register_at_gosa_si_server,
1206         trigger_new_key => \&trigger_new_key,
1207         }
1208 );
1210 POE::Kernel->run();
1211 exit;