Code

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