Code

Events should get the right use statement too.
[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 Fcntl;
29 use IO::Socket::INET;
30 use Crypt::Rijndael;
31 use MIME::Base64;
32 use Digest::MD5  qw(md5 md5_hex md5_base64);
33 use XML::Simple;
34 use Data::Dumper;
35 use Sys::Syslog qw( :DEFAULT setlogsock);
36 use File::Spec;
37 use Cwd;
38 use NetAddr::IP;
39 use GOSA::GosaSupportDaemon;
42 my ($cfg_file, %cfg_defaults, $foreground, $verbose, $pid_file, $procid, $pid, $log_file);
43 my ($server_address, $server_ip, $server_port, $server_domain, $server_passwd, $server_cipher, $server_timeout);
44 my ($client_address, $client_ip, $client_port, $client_mac_address, $network_interface, $ldap_config, $pam_config, $nss_config);
45 my ($input_socket, $rbits, $wbits, $ebits, $xml, $known_hosts, $ldap_enabled);
46 my (@events);
48 # default variables
49 my $event_dir = "/etc/gosa-si/client/events";
50 $known_hosts = {};
51 $foreground = 0 ;
52 %cfg_defaults =
53 ("general" =>
54     {"log_file" => [\$log_file, "/var/run/".$0.".log"],
55     "pid_file" => [\$pid_file, "/var/run/".$0.".pid"],
56     },
57 "client" => 
58     {"client_port" => [\$client_port, "20083"],
59      "client_ip" => [\$client_ip, "0.0.0.0"],
60      "ldap" => [\$ldap_enabled, 1],
61      "ldap_config" => [\$ldap_config, "/etc/ldap/ldap.conf"],
62      "pam_config" => [\$pam_config, "/etc/pam_ldap.conf"],
63      "nss_config" => [\$nss_config, "/etc/libnss_ldap.conf"],
64     },
65 "server" =>
66     {"server_ip" => [\$server_ip, ""],
67     "server_port" => [\$server_port, "20081"],
68     "server_passwd" => [\$server_passwd, ""],
69     "server_timeout" => [\$server_timeout, 10],
70     "server_domain" => [\$server_domain, ""],
71     },
72     );
75 #===  FUNCTION  ================================================================
76 #         NAME:  read_configfile
77 #   PARAMETERS:  cfg_file - string - 
78 #      RETURNS:  
79 #  DESCRIPTION: 
80 #===============================================================================
81 sub read_configfile {
82     my $cfg;
83     if( defined( $cfg_file) && ( length($cfg_file) > 0 )) {
84         if( -r $cfg_file ) {
85             $cfg = Config::IniFiles->new( -file => $cfg_file );
86         } else {
87             print STDERR "Couldn't read config file!";
88         }
89     } else {
90         $cfg = Config::IniFiles->new() ;
91     }
92     foreach my $section (keys %cfg_defaults) {
93         foreach my $param (keys %{$cfg_defaults{ $section }}) {
94             my $pinfo = $cfg_defaults{ $section }{ $param };
95             ${@$pinfo[ 0 ]} = $cfg->val( $section, $param, @$pinfo[ 1 ] );
96         }
97     }
98 }
101 #===  FUNCTION  ================================================================
102 #         NAME:  logging
103 #   PARAMETERS:  level - string - default 'info' 
104 #                msg - string - 
105 #                facility - string - default 'LOG_DAEMON' 
106 #      RETURNS:  
107 #  DESCRIPTION: 
108 #===============================================================================
109 sub daemon_log {
110     my( $msg, $level ) = @_;
111     if(not defined $msg) { return }
112     if(not defined $level) { $level = 1 }
113     if(defined $log_file){
114         open(LOG_HANDLE, ">>$log_file");
115         if(not defined open( LOG_HANDLE, ">>$log_file" )) { 
116             print STDERR "cannot open $log_file: $!";
117             return }
118         chomp($msg);
119         if($level <= $verbose){
120             print LOG_HANDLE $msg."\n";
121             if(defined $foreground) { print $msg."\n" }
122         }
123     }
124     close( LOG_HANDLE );
125 #    my ($msg, $level, $facility) = @_;
126 #    if(not defined $msg) {return}
127 #    if(not defined $level) {$level = "info"}
128 #    if(not defined $facility) {$facility = "LOG_DAEMON"}
129 #    openlog($0, "pid,cons,", $facility);
130 #    syslog($level, $msg);
131 #    closelog;
132 #    return;
136 #===  FUNCTION  ================================================================
137 #         NAME: check_cmdline_param
138 #   PARAMETERS: 
139 #      RETURNS:  
140 #  DESCRIPTION: 
141 #===============================================================================
142 sub check_cmdline_param () {
143     my $err_config;
144     my $err_counter = 0;
145     if( not defined( $cfg_file)) {
146         #$err_config = "please specify a config file";
147         #$err_counter += 1;
148         my $cwd = getcwd;
149         my $name = "/etc/gosa-si/client.conf";
150         $cfg_file = File::Spec->catfile( $cwd, $name );
151         print STDERR "no conf file specified\n   try to use default: $cfg_file\n";        
152     }
153     if( $err_counter > 0 ) {
154         &usage( "", 1 );
155         if( defined( $err_config)) { print STDERR "$err_config\n"}
156         print STDERR "\n";
157         exit( -1 );
158     }
162 #===  FUNCTION  ================================================================
163 #         NAME: check_pid
164 #   PARAMETERS:
165 #      RETURNS:
166 #  DESCRIPTION:
167 #===============================================================================
168 sub check_pid {
169     $pid = -1;
170     # Check, if we are already running
171     if( open(LOCK_FILE, "<$pid_file") ) {
172         $pid = <LOCK_FILE>;
173         if( defined $pid ) {
174             chomp( $pid );
175             if( -f "/proc/$pid/stat" ) {
176                 my($stat) = `cat /proc/$pid/stat` =~ m/$pid \((.+)\).*/;
177                 if( $0 eq $stat ) {
178                     close( LOCK_FILE );
179                     exit -1;
180                 }
181             }
182         }
183         close( LOCK_FILE );
184         unlink( $pid_file );
185     }
187     # create a syslog msg if it is not to possible to open PID file
188     if (not sysopen(LOCK_FILE, $pid_file, O_WRONLY|O_CREAT|O_EXCL, 0644)) {
189         my($msg) = "Couldn't obtain lockfile '$pid_file' ";
190         if (open(LOCK_FILE, '<', $pid_file)
191                 && ($pid = <LOCK_FILE>))
192         {
193             chomp($pid);
194             $msg .= "(PID $pid)\n";
195         } else {
196             $msg .= "(unable to read PID)\n";
197         }
198         if( ! ($foreground) ) {
199             openlog( $0, "cons,pid", "daemon" );
200             syslog( "warning", $msg );
201             closelog();
202         }
203         else {
204             print( STDERR " $msg " );
205         }
206         exit( -1 );
207     }
210 #===  FUNCTION  ================================================================
211 #         NAME:  get_interface_for_ip
212 #   PARAMETERS:  ip address (i.e. 192.168.0.1)
213 #      RETURNS:  array: list of interfaces if ip=0.0.0.0, matching interface if found, undef else
214 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
215 #===============================================================================
216 sub get_interface_for_ip {
217         my $result;
218         my $ip= shift;
219         if ($ip && length($ip) > 0) {
220                 my @ifs= &get_interfaces();
221                 if($ip eq "0.0.0.0") {
222                         $result = "all";
223                 } else {
224                         foreach (@ifs) {
225                                 my $if=$_;
226                                 if(get_ip($if) eq $ip) {
227                                         $result = $if;
228                                         last;
229                                 }
230                         }       
231                 }
232         }       
233         return $result;
236 #===  FUNCTION  ================================================================
237 #         NAME:  get_interfaces 
238 #   PARAMETERS:  none
239 #      RETURNS:  (list of interfaces) 
240 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
241 #===============================================================================
242 sub get_interfaces {
243         my @result;
244         my $PROC_NET_DEV= ('/proc/net/dev');
246         open(PROC_NET_DEV, "<$PROC_NET_DEV")
247                 or die "Could not open $PROC_NET_DEV";
249         my @ifs = <PROC_NET_DEV>;
251         close(PROC_NET_DEV);
253         # Eat first two line
254         shift @ifs;
255         shift @ifs;
257         chomp @ifs;
258         foreach my $line(@ifs) {
259                 my $if= (split /:/, $line)[0];
260                 $if =~ s/^\s+//;
261                 push @result, $if;
262         }
264         return @result;
267 #===  FUNCTION  ================================================================
268 #         NAME:  get_mac 
269 #   PARAMETERS:  interface name (i.e. eth0)
270 #      RETURNS:  (mac address) 
271 #  DESCRIPTION:  Uses ioctl to get mac address directly from system.
272 #===============================================================================
273 sub get_mac {
274         my $ifreq= shift;
275         my $result;
276         if ($ifreq && length($ifreq) > 0) { 
277                 if($ifreq eq "all") {
278                         if(defined($server_ip)) {
279                                 $result = &get_local_mac_for_remote_ip($server_ip);
280                         } else {
281                                 $result = "00:00:00:00:00:00";
282                         }
283                 } else {
284                         my $SIOCGIFHWADDR= 0x8927;     # man 2 ioctl_list
286                         # A configured MAC Address should always override a guessed value
287                         if ($client_mac_address and length($client_mac_address) > 0) {
288                                 $result= $client_mac_address;
289                         }
291                         socket SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('ip')
292                                 or die "socket: $!";
294                         if(ioctl SOCKET, $SIOCGIFHWADDR, $ifreq) {
295                                 my ($if, $mac)= unpack 'h36 H12', $ifreq;
297                                 if (length($mac) > 0) {
298                                         $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])$/;
299                                         $mac= sprintf("%s:%s:%s:%s:%s:%s", $1, $2, $3, $4, $5, $6);
300                                         $result = $mac;
301                                 }
302                         }
303                 }
304         }
305         return $result;
308 #===  FUNCTION  ================================================================
309 #         NAME:  get_ip 
310 #   PARAMETERS:  interface name (i.e. eth0)
311 #      RETURNS:  (ip address) 
312 #  DESCRIPTION:  Uses ioctl to get ip address directly from system.
313 #===============================================================================
314 sub get_ip {
315         my $ifreq= shift;
316         my $result= "";
317         my $SIOCGIFADDR= 0x8915;       # man 2 ioctl_list
318         my $proto= getprotobyname('ip');
320         socket SOCKET, PF_INET, SOCK_DGRAM, $proto
321                 or die "socket: $!";
323         if(ioctl SOCKET, $SIOCGIFADDR, $ifreq) {
324                 my ($if, $sin)    = unpack 'a16 a16', $ifreq;
325                 my ($port, $addr) = sockaddr_in $sin;
326                 my $ip            = inet_ntoa $addr;
328                 if ($ip && length($ip) > 0) {
329                         $result = $ip;
330                 }
331         }
333         return $result;
336 #===  FUNCTION  ================================================================
337 #         NAME:  get_local_mac_for_remote_ip
338 #   PARAMETERS:  none (takes server_ip from global variable)
339 #      RETURNS:  (ip address from interface that is used for communication) 
340 #  DESCRIPTION:  Uses ioctl to get routing table from system, checks which entry
341 #                matches (defaultroute last).
342 #===============================================================================
343 sub get_local_mac_for_remote_ip {
344         my $ifreq= shift;
345         my $result= "00:00:00:00:00:00";
346         my $PROC_NET_ROUTE= ('/proc/net/route');
348         open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
349                 or die "Could not open $PROC_NET_ROUTE";
351         my @ifs = <PROC_NET_ROUTE>;
353         close(PROC_NET_ROUTE);
355         # Eat header line
356         shift @ifs;
357         chomp @ifs;
358         foreach my $line(@ifs) {
359                 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
360                 my $destination;
361                 my $mask;
362                 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
363                 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
364                 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
365                 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
366                 if(new NetAddr::IP($server_ip)->within(new NetAddr::IP($destination, $mask))) {
367                         # destination matches route, save mac and exit
368                         $result= &get_mac($Iface);
369                         last;
370                 }
371         }
374         return $result;
377 #===  FUNCTION  ================================================================
378 #         NAME:  usage
379 #   PARAMETERS: 
380 #      RETURNS:  
381 #  DESCRIPTION: 
382 #===============================================================================
383 sub usage {
384         my( $text, $help ) = @_;
385         $text = undef if( "h" eq $text );
386         (defined $text) && print STDERR "\n$text\n";
387         if( (defined $help && $help) || (!defined $help && !defined $text) ) {
388                 print STDERR << "EOF" ;
389 usage: $0 [-hvf] [-c config]
391     -h        : this (help) message
392     -c <file> : config file
393     -f        : foreground, process will not be forked to background
394     -v        : be verbose (multiple to increase verbosity)
395 EOF
396         }
397         print "\n" ;
400 #===  FUNCTION  ================================================================
401 #         NAME:  get_server_addresses
402 #   PARAMETERS:  
403 #      RETURNS:  
404 #  DESCRIPTION:  
405 #===============================================================================
406 sub get_server_addresses {
407     my $domain= shift;
408     my @result;
409     my $dig_cmd= 'dig +nocomments srv _gosad._tcp.'.$domain;
411     my $output= `$dig_cmd 2>&1`;
412     open (PIPE, "$dig_cmd 2>&1 |");
413     while(<PIPE>) {
414         chomp $_;
415         # If it's not a comment
416         if($_ =~ m/^[^;]/) {
417             my @matches= split /\s+/;
419             # Push hostname with port
420             if($matches[3] eq 'SRV') {
421                 push @result, $matches[7].':'.$matches[6];
422             } elsif ($matches[3] eq 'A') {
423                 my $i=0;
425                 # Substitute the hostname with the ip address of the matching A record
426                 foreach my $host (@result) {
427                     if ((split /\:/, $host)[0] eq $matches[0]) {
428                         $result[$i]= $matches[4].':'.(split /\:/, $host)[1];
429                     }
430                     $i++;
431                 }
432             }
433         }
434     }
435     close(PIPE);
436     return @result;
440 #===  FUNCTION  ================================================================
441 #         NAME:  register_at_server
442 #   PARAMETERS:  
443 #      RETURNS:  
444 #  DESCRIPTION:  
445 #===============================================================================
446 sub register_at_server {
447     my ($tmp) = @_;
449     # create new passwd and ciphering object for client-server communication
450     my $new_server_passwd = &create_passwd();
451     my $new_server_cipher;
453     # detect all client accepted events
454     opendir(DIR, $event_dir) 
455         or daemon_log("cannot find directory $event_dir!\ngosa-si-client starts without any accepting events!", 1);
456     my $file_name;
457     @events = ();
458     while(defined($file_name = readdir(DIR))){
459         if ($file_name eq "." || $file_name eq "..") {
460             next;
461         }
462         push(@events, $file_name);
463     }
464     my $events = join(",", @events);
465     daemon_log("found events: $events", 1);
467     # fill in all possible servers
468     my @servers;
469     if (defined $server_domain) {
470         my @tmp_servers = &get_server_addresses($server_domain);
471         foreach my $server (@tmp_servers) { unshift(@servers, $server); }
472     }
473     # add server address from config file at first position of server list
474     if (defined $server_address) {
475         unshift(@servers, $server_address);
476     }
477     daemon_log("found servers in configuration file and via DNS:", 5);
478     foreach my $server (@servers) {
479         daemon_log("\t$server", 5);
480     }
482     my ($rout, $wout, $reg_server);
483     foreach my $server (@servers) {
485 # TODO : server abhängige macadress und ipadresse eintragen
487         # create msg hash
488         my $register_hash = &create_xml_hash("here_i_am", $client_address, $server);
489         &add_content2xml_hash($register_hash, "new_passwd", $new_server_passwd);
490         &add_content2xml_hash($register_hash, "mac_address", $client_mac_address);
491         &add_content2xml_hash($register_hash, "events", $events);
493         # send xml hash to server with general server passwd
494         my $answer = &send_msg_hash2address($register_hash, $server, $server_passwd);
495  
496         if ($answer != 0) { next; }
497        
498         # waiting for response
499         daemon_log("waiting for response...\n", 5);
500         my $nf = select($rout=$rbits, $wout=$wbits, undef, $server_timeout);
502         # something is coming in
503         if(vec $rout, fileno $input_socket, 1) {
504             my $crypted_msg;
505             my $client = $input_socket->accept();
506             my $other_end = getpeername($client);
507             if(not defined $other_end) {
508                 daemon_log("client cannot be identified: $!\n");
509             } else {
510                 my ($port, $iaddr) = unpack_sockaddr_in($other_end);
511                 my $actual_ip = inet_ntoa($iaddr);
512                 daemon_log("\naccept client from $actual_ip\n", 5);
513                 my $in_msg = &read_from_socket($client);
514                 if(defined $in_msg){
515                     chomp($in_msg);
516                     $crypted_msg = $in_msg;
517                 } else {
518                     daemon_log("cannot read from $actual_ip\n", 5);
519                 }
520             }
521             close($client);
522             
523             # validate acknowledge msg from server
524             $new_server_cipher = &create_ciphering($new_server_passwd);
525             my $msg_hash;
526             eval {
527                 my $decrypted_msg = &decrypt_msg($crypted_msg, $new_server_cipher);
528                 daemon_log("decrypted register msg: $decrypted_msg", 5);
529                 $msg_hash = $xml->XMLin($decrypted_msg, ForceArray=>1);
530             };
531             if($@) {
532                 daemon_log("ERROR: do not understand the incoming message:" , 5);  
533                 daemon_log("$@", 7); 
534             } else {
535                 my $header = @{$msg_hash->{header}}[0];
536                 if($header eq "registered") {
537                     $reg_server = $server;
538                     last;
539                 } elsif($header eq "denied") {
540                     my $reason = (&get_content_from_xml_hash($msg_hash, "denied"))[0];
541                     daemon_log("registration at $server denied: $reason", 1);
542                 } else {
543                     daemon_log("cannot register at $server", 1);
544                 }
545             }
546         }
547         # if no answer arrive, try next server in list
549     }
550     
551     if(defined $reg_server) {
552         daemon_log("registered at $reg_server", 1);
553     } else {
554         daemon_log("cannot register at any server", 1);
555         daemon_log("exiting!!!", 1);
556         exit(1);
557     }
559     # update the global available variables
560     $server_address = $reg_server;
561     $server_passwd = $new_server_passwd;
562     $server_cipher = $new_server_cipher;
563     return;
567 #===  FUNCTION  ================================================================
568 #         NAME:  create_xml_hash
569 #   PARAMETERS:  
570 #      RETURNS:
571 #  DESCRIPTION:
572 #===============================================================================
573 #sub create_xml_hash {
574 #    my ($header, $source, $target, $header_value) = @_;
575 #    my $hash = {
576 #            header => [$header],
577 #            source => [$source],
578 #            target => [$target],
579 #            $header => [$header_value],
580 #    };
581 #    daemon_log("create_xml_hash:", 7),
582 #    chomp(my $tmp = Dumper $hash);
583 #    daemon_log("\t$tmp\n", 7);
584 #    return $hash
585 #}
588 #===  FUNCTION  ================================================================
589 #         NAME:  create_xml_string
590 #   PARAMETERS:  
591 #      RETURNS:
592 #  DESCRIPTION:
593 #===============================================================================
594 #sub create_xml_string {
595 #    my ($xml_hash) = @_ ;
596 #    my $xml_string = $xml->XMLout($xml_hash, RootName => 'xml');
597 #    $xml_string =~ s/[\n]+//g;
598 #    daemon_log("create_xml_string:\n\t$xml_string\n", 7);
599 #    return $xml_string;
600 #}
603 #===  FUNCTION  ================================================================
604 #         NAME:  add_content2xml_hash
605 #   PARAMETERS:  
606 #      RETURNS:
607 #  DESCRIPTION:
608 #===============================================================================
609 #sub add_content2xml_hash {
610 #    my ($xml_ref, $element, $content) = @_;
611 #    if(not exists $$xml_ref{$element} ) {
612 #        $$xml_ref{$element} = [];
613 #    }
614 #    my $tmp = $$xml_ref{$element};
615 #    push(@$tmp, $content);
616 #    return;
617 #}
620 #===  FUNCTION  ================================================================
621 #         NAME:  get_content_from_xml_hash
622 #   PARAMETERS:  ref : reference to the xml hash
623 #                string: key of the value you want
624 #      RETURNS:  STRING AND ARRAY
625 #  DESCRIPTION:  if key of the hash is either 'header', 'target' or 'source' the 
626 #                function returns a string cause it is expected that these keys
627 #                do just have one value, all other keys returns an array!!!
628 #===============================================================================
629 #sub get_content_from_xml_hash {
630 #    my ($xml_ref, $element) = @_;
631 #    my $result = $xml_ref->{$element};
632 #    if( $element eq "header" || $element eq "target" || $element eq "source") {
633 #        return @$result[0];
634 #    }
635 #    return @$result;
636 #}
638 #    my ($xml_ref, $element) = @_;
639 #    if (exists $xml_ref->{$element}) {
640 #        my $result = $xml_ref->{$element};
641 #        if( $element eq "header" || $element eq "target" || $element eq "source") {
642 #            return @$result[0];
643 #        } else {
644 #            return @$result;
645 #        }
646 #        
647 #    } else {
648 #        my $result = ();
649 #        return @$result;
650 #    }
651 #}
654 #===  FUNCTION  ================================================================
655 #         NAME:  encrypt_msg
656 #   PARAMETERS:
657 #      RETURNS:
658 #  DESCRIPTION:
659 #===============================================================================
660 #sub encrypt_msg {
661 #    my ($msg, $my_cipher) = @_;
662 #    if(not defined $my_cipher) { print "no cipher object\n"; }
663 #    $msg = "\0"x(16-length($msg)%16).$msg;
664 #    my $crypted_msg = $my_cipher->encrypt($msg);
665 #    chomp($crypted_msg = &encode_base64($crypted_msg));
666 #    return $crypted_msg;
667 #}
670 #===  FUNCTION  ================================================================
671 #         NAME:  decrypt_msg
672 #   PARAMETERS:
673 #      RETURNS:
674 #  DESCRIPTION:
675 #===============================================================================
676 #sub decrypt_msg {
677 #    my ($crypted_msg, $my_cipher) = @_ ;
678 #    $crypted_msg = &decode_base64($crypted_msg);
679 #    my $msg = $my_cipher->decrypt($crypted_msg); 
680 #    $msg =~ s/\0*//g;
681 #    return $msg;
682 #}
685 #===  FUNCTION  ================================================================
686 #         NAME:  create_ciphering
687 #   PARAMETERS:  
688 #      RETURNS:  cipher object
689 #  DESCRIPTION:  
690 #===============================================================================
691 #sub create_ciphering {
692 #    my ($passwd) = @_;
693 #    $passwd = substr(md5_hex("$passwd") x 32, 0, 32);
694 #    my $iv = substr(md5_hex('GONICUS GmbH'),0, 16);
696 #    #daemon_log("iv: $iv", 7);
697 #    #daemon_log("key: $passwd", 7);
698 #    my $my_cipher = Crypt::Rijndael->new($passwd , Crypt::Rijndael::MODE_CBC());
699 #    $my_cipher->set_iv($iv);
700 #    return $my_cipher;
701 #}
704 #===  FUNCTION  ================================================================
705 #         NAME:  create_passwd
706 #   PARAMETERS:
707 #      RETURNS:  cipher object
708 #  DESCRIPTION:
709 #===============================================================================
710 sub create_passwd {
711     my $new_passwd = "";
712     for(my $i=0; $i<31; $i++) {
713         $new_passwd .= ("a".."z","A".."Z",0..9)[int(rand(62))]
714     }
716     return $new_passwd;
720 #===  FUNCTION  ================================================================
721 #         NAME:  send_msg_hash2address
722 #   PARAMETERS:  msg string - xml message
723 #                PeerAddr string - socket address to send msg
724 #                PeerPort string - socket port, if not included in socket address
725 #      RETURNS:  nothing
726 #  DESCRIPTION:  ????
727 #===============================================================================
728 #sub send_msg_hash2address {
729 #    my ($msg_hash, $address, $passwd) = @_ ;
731 #    # fetch header for logging
732 #    my $header = @{$msg_hash->{header}}[0];
734 #    # generiere xml string
735 #    my $msg_xml = &create_xml_string($msg_hash);
737 #    # hole das entsprechende passwd aus dem hash
738 #    if(not defined $passwd) {
739 #        if(exists $known_hosts->{$address}) {
740 #            $passwd = $known_hosts->{$address}->{passwd};
741 #        } elsif ($address eq $server_address) {
742 #            $passwd = $server_passwd;
743 #        } else {
744 #            daemon_log("$address not known, neither as server nor as client", 1);
745 #            return "failed";
746 #        }
747 #    }
749 #    # erzeuge ein ciphering object
750 #    my $act_cipher = &create_ciphering($passwd);
752 #    # encrypt xml msg
753 #    my $crypted_msg = &encrypt_msg($msg_xml, $act_cipher);
755 #    # Ă¶ffne socket
756 #    my $socket = &open_socket($address);
757 #    if(not defined $socket){
758 #        daemon_log("cannot open socket to $address, server not reachable", 1);
759 #        daemon_log("cannot send '$header'-msg", 1);
760 #        return "failed";
761 #    }
763 #    # versende xml msg
764 #    print $socket $crypted_msg."\n";
766 #    # schlieĂźe socket
767 #    close $socket;
769 #    daemon_log("send '$header'-msg to $address", 5);
770 #    daemon_log("crypted_msg:\n\t$crypted_msg", 7);
772 #    return "done";
773 #}
776 #===  FUNCTION  ================================================================
777 #         NAME:  open_socket
778 #   PARAMETERS:  PeerAddr string something like 192.168.1.1 or 192.168.1.1:10000
779 #                [PeerPort] string necessary if port not appended by PeerAddr
780 #      RETURNS:  socket IO::Socket::INET
781 #  DESCRIPTION:
782 #===============================================================================
783 sub open_socket {
784     my ($PeerAddr, $PeerPort) = @_ ;
785     if(defined($PeerPort)){
786         $PeerAddr = $PeerAddr.":".$PeerPort;
787     }
788     my $socket;
789     $socket = new IO::Socket::INET(PeerAddr => $PeerAddr ,
790             Porto => "tcp" ,
791             Type => SOCK_STREAM,
792             Timeout => 5,
793             );
794     if(not defined $socket) {
795         #daemon_log("cannot connect to socket at $PeerAddr, $@\n");
796         return;
797     }
798     daemon_log("open_socket:\n\t$PeerAddr", 7);
799     return $socket;
803 #===  FUNCTION  ================================================================
804 #         NAME:  read_from_socket
805 #   PARAMETERS:  socket fh - 
806 #      RETURNS:  result string - readed characters from socket
807 #  DESCRIPTION:  reads data from socket in 16 byte steps
808 #===============================================================================
809 sub read_from_socket {
810     my ($socket) = @_;
811     my $result = "";
813     $socket->blocking(1);
814     $result = <$socket>;
816     $socket->blocking(0);
817     while ( my $char = <$socket> ) {
818         if (not defined $char) { last }
819         $result .= $char;
820     }
821     return $result;
825 #    my ($socket) = @_;
826 #    my $result = "";
827 #    my $len = 16;
828 #    while($len == 16){
829 #        my $char;
830 #        $len = sysread($socket, $char, 16);
831 #        if($len != 16) { last }
832 #        if($len != 16) { last }
833 #        $result .= $char;
834 #    }
835 #    return $result;
839 #===  FUNCTION  ================================================================
840 #         NAME:  print_known_hosts_hash
841 #   PARAMETERS:
842 #      RETURNS: 
843 #  DESCRIPTION: 
844 #===============================================================================
845 sub print_known_hosts_hash {
846     my ($tmp) = @_;
847     print "####################################\n";
848     print "# status of known_hosts\n";
849     my $hosts;
850     my $host_hash;
851     my @hosts = keys %$known_hosts;
852     foreach my $host (@hosts) {
853         #my @elements = keys %$known_hosts->{$host};
854         my $status = $known_hosts->{$host}->{status} ;
855         my $passwd = $known_hosts->{$host}->{passwd};
856         my $timestamp = $known_hosts->{$host}->{timestamp};
857         print "$host\n";
858         print "\t$status\n";
859         print "\t$passwd\n";
860         print "\t$timestamp\n";
861     }
862     print "####################################\n";
863     return;
866 #===  FUNCTION  ================================================================
867 #         NAME:  
868 #   PARAMETERS:
869 #      RETURNS: 
870 #  DESCRIPTION: 
871 #===============================================================================
872 sub create_known_hosts_entry {
873     my ($hostname) = @_;
874     $known_hosts->{$hostname} = {};
875     $known_hosts->{$hostname}->{status} = "none";
876     $known_hosts->{$hostname}->{passwd} = "none";
877     $known_hosts->{$hostname}->{timestamp} = "none";
878     return;  
882 #===  FUNCTION  ================================================================
883 #         NAME:  
884 #   PARAMETERS:
885 #      RETURNS: 
886 #  DESCRIPTION: 
887 #===============================================================================
888 sub update_known_hosts_entry {
889     my ($hostname, $status, $passwd, $timestamp) = @_;
890     my ($seconds, $minutes, $hours, $monthday, $month,
891     $year, $weekday, $yearday, $sommertime) = localtime(time);
892     $hours = $hours < 10 ? $hours = "0".$hours : $hours;
893     $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
894     $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
895     $month+=1;
896     $month = $month < 10 ? $month = "0".$month : $month;
897     $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
898     $year+=1900;
899     my $t = "$year$month$monthday$hours$minutes$seconds";
901     if($status) {
902         $known_hosts->{$hostname}->{status} = $status;
903     }
904     if($passwd) {
905         $known_hosts->{$hostname}->{passwd} = $passwd;
906     }
907     if($timestamp) {
908         $t = $timestamp;
909     }
910     $known_hosts->{$hostname}->{timestamp} = $t;
911     return;  
915 #===  FUNCTION  ================================================================
916 #         NAME:  
917 #   PARAMETERS:
918 #      RETURNS: 
919 #  DESCRIPTION: 
920 #===============================================================================
921 sub add_content2known_hosts {
922     my ($hostname, $element, $content) = @_;
923     my ($seconds, $minutes, $hours, $monthday, $month,
924     $year, $weekday, $yearday, $sommertime) = localtime(time);
925     $hours = $hours < 10 ? $hours = "0".$hours : $hours;
926     $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
927     $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
928     $month+=1;
929     $month = $month < 10 ? $month = "0".$month : $month;
930     $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
931     $year+=1900;
932     my $t = "$year$month$monthday$hours$minutes$seconds";
933     
934     $known_hosts->{$hostname}->{$element} = $content;
935     $known_hosts->{$hostname}->{timestamp} = $t;
936     return;
940 #===  FUNCTION  ================================================================
941 #         NAME:  
942 #   PARAMETERS:
943 #      RETURNS: 
944 #  DESCRIPTION: 
945 #===============================================================================
946 sub process_incoming_msg {
947     my ($crypted_msg) = @_;
948     if(not defined $crypted_msg) {
949         daemon_log("function 'process_incoming_msg': got no msg", 7);
950     }
951     $crypted_msg =~ /^([\s\S]*?)\.(\d{1,3}?)\.(\d{1,3}?)\.(\d{1,3}?)\.(\d{1,3}?)$/;
952     $crypted_msg = $1;
953     my $host = sprintf("%s.%s.%s.%s", $2, $3, $4, $5);
954     daemon_log("msg from host:", 1);
955     daemon_log("\t$host", 1);
956     daemon_log("crypted msg:", 7);
957     daemon_log("\t$crypted_msg", 7);
959     my $act_cipher = &create_ciphering($server_passwd);
961     # try to decrypt incoming msg
962     my ($msg, $msg_hash);
963     eval{
964         $msg = &decrypt_msg($crypted_msg, $act_cipher);
965         $msg_hash = $xml->XMLin($msg, ForceArray=>1);
966     };
967     if($@) {
968         daemon_log("ERROR: incoming msg cannot be decrypted with server passwd", 1);
969         return;
970     } 
972     my $header = @{$msg_hash->{header}}[0];
973     
974     daemon_log("receive '$header' from $host", 1);
975 #    daemon_log("header from msg:", 1);
976 #    daemon_log("\t$header", 1);
977 #    daemon_log("msg to process:", 7);
978 #    daemon_log("\t$msg", 7);
980     #check whether msg to process is a event 
981     opendir(DIR, $event_dir) 
982         or daemon_log("cannot find directory $event_dir, no events specified", 5);
983     my $file_name;
984     while(defined($file_name = readdir(DIR))){
985         if ($file_name eq "." || $file_name eq "..") {
986             next;
987         }
988         if ($file_name eq $header) {
989             my $cmd = "$event_dir/$file_name '$msg'";
990             my $result_xml = "";
991             open(PIPE, "$cmd 2>&1 |");
992             while(<PIPE>) {
993                 $result_xml.=$_;
994                 last;
995             }
996             close(PIPE);
997             my $res_hash = &transform_msg2hash($result_xml);
998             my $res_target = @{$res_hash->{target}}[0];
999             &send_msg_hash2address($res_hash, $server_address);
1000             
1001             return;
1002         }
1003     }
1004     close(DIR);
1005     daemon_log("could not assign the msg $header to an event", 5);
1006     
1007     if ($header eq 'new_ldap_config') { if ($ldap_enabled == 1) {&new_ldap_config($msg_hash)}}
1008     elsif ($header eq 'ping') { &got_ping($msg_hash) }
1009     elsif ($header eq 'wake_up') { &execute_event($msg_hash)}
1010     elsif ($header eq 'new_passwd') { &new_passwd()}
1011     else { daemon_log("ERROR: no function assigned to msg $header", 5) }
1013     return;
1017 #===  FUNCTION  ================================================================
1018 #         NAME:  
1019 #   PARAMETERS:
1020 #      RETURNS: 
1021 #  DESCRIPTION: 
1022 #===============================================================================
1023 sub update_status { 
1024     my ($new_status) = @_ ;
1025     my $out_hash = &create_xml_hash("update_status", $client_address, $server_address);      
1026     &add_content2xml_hash($out_hash, "update_status", $new_status);
1027     &send_msg_hash2address($out_hash, $server_address);
1028     return;
1032 #===  FUNCTION  ================================================================
1033 #         NAME:  
1034 #   PARAMETERS:
1035 #      RETURNS: 
1036 #  DESCRIPTION: 
1037 #===============================================================================
1038 sub server_leaving {
1039     my ($msg_hash) = @_ ;
1040     my $source = &get_content_from_xml_hash("source");
1041     my $header = &get_content_from_xml_hash("header");
1042     
1043     daemon_log("gosa daemon $source is going down, cause registration procedure", 1);
1044     my $server_address = "none";
1045     my $server_passwd = "none";
1046     my $server_cipher = "none";
1048     # reinitialization of default values in config file
1049     &read_configfile;
1050     
1051     # registrated at new daemon
1052     &register_at_server();
1053        
1054     return;   
1058 sub got_ping {
1059     my ($msg_hash) = @_ ;
1061     my $source = &get_content_from_xml_hash($msg_hash, 'source');
1062     my $target = &get_content_from_xml_hash($msg_hash, 'target');
1063     my $header = &get_content_from_xml_hash($msg_hash, 'header');    
1064     
1065     &add_content2known_hosts(hostname=>$target, status=>$header);
1066     
1067     my $out_hash = &create_xml_hash("got_ping", $target, $source);
1068     &send_msg_hash2address($out_hash, $source, $server_passwd);
1070     return;
1074 sub new_ldap_config {
1075     my ($msg_hash) = @_ ;
1076     my $element;
1077     my @ldap_uris;
1078     my $ldap_base;
1079     my @ldap_options;
1080     my @pam_options;
1081     my @nss_options;
1082     my $goto_admin;
1083     my $goto_secret;
1085     # Transform input into array
1086     while ( my ($key, $value) = each(%$msg_hash) ) {
1087         if ($key =~ /^(source|target|header)$/) {
1088                 next;
1089         }
1091         foreach $element (@$value) {
1092                 if ($key =~ /^ldap_uri$/) {
1093                         push (@ldap_uris, $element);
1094                         next;
1095                 }
1096                 if ($key =~ /^ldap_base$/) {
1097                         $ldap_base= $element;
1098                         next;
1099                 }
1100                 if ($key =~ /^goto_admin$/) {
1101                         $goto_admin= $element;
1102                         next;
1103                 }
1104                 if ($key =~ /^goto_secret$/) {
1105                         $goto_secret= $element;
1106                         next;
1107                 }
1108                 if ($key =~ /^ldap_cfg$/) {
1109                         push (@ldap_options, "$element");
1110                         next;
1111                 }
1112                 if ($key =~ /^pam_cfg$/) {
1113                         push (@pam_options, "$element");
1114                         next;
1115                 }
1116                 if ($key =~ /^nss_cfg$/) {
1117                         push (@nss_options, "$element");
1118                         next;
1119                 }
1120         }
1121     }
1123     # Setup ldap.conf
1124     my $file1;
1125     my $file2;
1126     open(file1, "> $ldap_config");
1127     print file1 "# This file was automatically generated by gosa-si-client. Do not change.\n";
1128     print file1 "URI";
1129     foreach $element (@ldap_uris) {
1130         print file1 " $element";
1131     }
1132     print file1 "\nBASE $ldap_base\n";
1133     foreach $element (@ldap_options) {
1134         print file1 "$element\n";
1135     }
1136     close (file1);
1137     daemon_log("wrote $ldap_config", 5);
1139     # Setup pam_ldap.conf / libnss_ldap.conf
1140     open(file1, "> $pam_config");
1141     open(file2, "> $nss_config");
1142     print file1 "# This file was automatically generated by gosa-si-client. Do not change.\n";
1143     print file2 "# This file was automatically generated by gosa-si-client. Do not change.\n";
1144     print file1 "uri";
1145     print file2 "uri";
1146     foreach $element (@ldap_uris) {
1147         print file1 " $element";
1148         print file2 " $element";
1149     }
1150     print file1 "\nbase $ldap_base\n";
1151     print file2 "\nbase $ldap_base\n";
1152     foreach $element (@pam_options) {
1153         print file1 "$element\n";
1154     }
1155     foreach $element (@nss_options) {
1156         print file2 "$element\n";
1157     }
1158     close (file2);
1159     daemon_log("wrote $nss_config", 5);
1160     close (file1);
1161     daemon_log("wrote $pam_config", 5);
1163     # Create goto.secrets if told so
1164     if (defined $goto_admin){
1165             open(file1, "> /etc/goto/secret");
1166             close(file1);
1167             chown(0,0, "/etc/goto/secret");
1168             chmod(0600, "/etc/goto/secret");
1169             open(file1, "> /etc/goto/secret");
1170             print file1 $goto_admin.":".$goto_secret."\n";
1171             close(file1);
1172             daemon_log("wrote /etc/goto/secret", 5);
1173     }
1175     return;
1180 sub execute_event {
1181     my ($msg_hash)= @_;
1182     my $configdir= '/etc/gosa-si/client/events/';
1183     my $result;
1185     my $header = &get_content_from_xml_hash($msg_hash, 'header');
1186     my $source = &get_content_from_xml_hash($msg_hash, 'source');
1187     my $target = &get_content_from_xml_hash($msg_hash, 'target');
1190     if((not defined $source)
1191             && (not defined $target)
1192             && (not defined $header)) {
1193         daemon_log("ERROR: Entries missing in XML msg for gosa events under $configdir");
1194     } else {
1195         my $parameters="";
1196         my @params = &get_content_from_xml_hash($msg_hash, $header);
1197         my $params = join(", ", @params);
1198         daemon_log("execute_event: got parameters: $params", 5);
1200         if (@params) {
1201             foreach my $param (@params) {
1202                 my $param_value = (&get_content_from_xml_hash($msg_hash, $param))[0];
1203                 daemon_log("execute_event: parameter -> value: $param -> $param_value", 7);
1204                 $parameters.= " ".$param_value;
1205             }
1206         }
1208         my $cmd= $configdir.$header."$parameters";
1209         daemon_log("execute_event: executing cmd: $cmd", 7);
1210         $result= "";
1211         open(PIPE, "$cmd 2>&1 |");
1212         while(<PIPE>) {
1213             $result.=$_;
1214         }
1215         close(PIPE);
1216     }
1218     # process the event result
1221     return;
1225 sub new_passwd {
1226     # my ($msg_hash) = @_ ;
1227     my $new_server_passwd = &create_passwd();
1228     my $new_server_cipher = &create_ciphering($new_server_passwd);
1230     my $out_hash = &create_xml_hash("new_passwd", $client_address, $server_address, $new_server_passwd);
1231     
1232     &send_msg_hash2address($out_hash, $server_address, $server_passwd);
1234     $server_passwd = $new_server_passwd;
1235     $server_cipher = $new_server_cipher;
1236     return; 
1242 #==== MAIN = main ==============================================================
1244 #  parse commandline options
1245 Getopt::Long::Configure( "bundling" );
1246 GetOptions("h|help" => \&usage,
1247            "c|config=s" => \$cfg_file,
1248            "f|foreground" => \$foreground,
1249            "v|verbose+" => \$verbose,
1250            );
1252 #  read and set config parameters
1253 &check_cmdline_param ;
1254 &read_configfile;
1255 &check_pid;
1257 if ( ! $foreground ) {
1258         open STDIN, '/dev/null' or die "Can’t read /dev/null: $!";
1259         open STDOUT, '>>/dev/null' or die "Can't write to /dev/null: $!";
1260         open STDERR, '>>/dev/null' or die "Can't write to /dev/null: $!";
1264 # restart daemon log file
1265 if(-e $log_file ) { unlink $log_file }
1266 daemon_log(" ", 1);
1267 daemon_log("$0 started!", 1);
1269 # Just fork, if we"re not in foreground mode
1270 if( ! $foreground ) { $pid = fork(); }
1271 else { $pid = $$; }
1273 # Do something useful - put our PID into the pid_file
1274 if( 0 != $pid ) {
1275     open( LOCK_FILE, ">$pid_file" );
1276     print LOCK_FILE "$pid\n";
1277     close( LOCK_FILE );
1278     if( !$foreground ) { exit( 0 ) };
1281 # detect own ip and mac address
1282 $network_interface= &get_interface_for_ip($client_ip);
1283 $client_mac_address= &get_mac($network_interface);
1285 # ($client_ip, $client_mac_address) = &get_ip_and_mac(); 
1286 #if (not defined $client_ip) {
1287 #    die "EXIT: ip address of $0 could not be detected";
1288 #}
1289 daemon_log("client ip address detected: $client_ip", 1);
1290 daemon_log("client mac address detected: $client_mac_address", 1);
1292 # prepare variables
1293 if (defined $server_ip && defined $server_port) {
1294     $server_address = $server_ip.":".$server_port;
1296 $client_address = $client_ip.":".$client_port;
1298 # setup xml parser
1299 $xml = new XML::Simple();
1301 # create input socket
1302 daemon_log(" ", 1);
1303 $rbits = $wbits = $ebits = "";
1304 $input_socket = IO::Socket::INET->new(LocalPort => $client_port,
1305         Type => SOCK_STREAM,
1306         Reuse => 1,
1307         Listen => 20,
1308         ); 
1309 if(not defined $input_socket){
1310     daemon_log("cannot be a tcp server at $client_port : $@\n");
1311 } else {
1312     daemon_log("start client at $client_address",1) ;
1313     vec($rbits, fileno $input_socket, 1) = 1;
1314     vec($wbits, fileno $input_socket, 1) = 1;
1317 # register at server
1318 daemon_log(" ", 1);
1319 &register_at_server();
1322 ##############
1323 # Debugging
1324 #############
1325 #sleep(2);
1326 #&update_status("ich_bin_ein_neuer_status");
1328 ###################################
1329 #everything ready, okay, lets start
1330 ###################################
1331 while(1) {
1332     my ($rout, $wout);
1333     my $nf = select($rout=$rbits, $wout=$wbits, undef, undef);
1335     # error handling
1336     if($nf < 0 ) {
1337     }
1339     # something is coming in
1340     if(vec $rout, fileno $input_socket, 1) {
1341         my $client = $input_socket->accept();
1342         my $other_end = getpeername($client);
1343         
1344         if(not defined $other_end) {
1345             daemon_log("client cannot be identified: $!");
1346         } else {
1347             my ($port, $iaddr) = unpack_sockaddr_in($other_end);
1348             my $actual_ip = inet_ntoa($iaddr);
1349             daemon_log("accept client from $actual_ip", 5);
1350             my $in_msg = &read_from_socket($client);
1351             if(defined $in_msg){
1352                 chomp($in_msg);
1353                 $in_msg = $in_msg.".".$actual_ip;
1354                 &process_incoming_msg($in_msg);
1356             }
1357         }
1358     }
1360