Code

1f0ae9b9ba4115943da54a9f2c4dc06a8e45f668
[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;
39 #use Fcntl;
40 #use Sys::Syslog qw( :DEFAULT setlogsock);
41 #use File::Spec;
42 #use Cwd;
46 my $event_dir = "/usr/lib/gosa-si/client/events";
47 use lib "/usr/lib/gosa-si/client/events";
49 my ($cfg_file, %cfg_defaults, $foreground, $verbose, $pid_file, $procid, $pid, $log_file);
50 my ($server_ip, $server_port, $server_key, $server_timeout, $server_domain);
51 my ($client_ip, $client_port, $client_mac_address, $ldap_enabled, $ldap_config, $pam_config, $nss_config);
52 my $xml;
53 my $default_server_key;
54 my $event_hash;
55 my @servers;
56 my $gotoHardwareChecksum;
58 # globalise variables which are used in imported events
59 our $cfg_file;
60 our $server_address;
61 our $client_address;
62 our $server_key;
64 # default variables
65 our $REGISTERED_FLAG = 1;
67 %cfg_defaults = (
68 "general" =>
69     {"log_file" => [\$log_file, "/var/run/".$0.".log"],
70     "pid_file" => [\$pid_file, "/var/run/".$0.".pid"],
71     },
72 "client" => 
73     {"client_port" => [\$client_port, "20083"],
74      "client_ip" => [\$client_ip, "0.0.0.0"],
75      "client_mac_address" => [\$client_mac_address, "00:00:00:00:00:00:00"],
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     },
81 "server" =>
82     {"server_ip" => [\$server_ip, "127.0.0.1"],
83     "server_port" => [\$server_port, "20081"],
84     "server_key" => [\$server_key, ""],
85     "server_timeout" => [\$server_timeout, 10],
86     "server_domain" => [\$server_domain, ""],
87     },
89 );
92 #=== FUNCTIONS = functions =====================================================
94 #===  FUNCTION  ================================================================
95 #         NAME: check_cmdline_param
96 #   PARAMETERS: 
97 #      RETURNS:  
98 #  DESCRIPTION: 
99 #===============================================================================
100 sub check_cmdline_param () {
101     my $err_config;
102     my $err_counter = 0;
103         if(not defined($cfg_file)) {
104                 $cfg_file = "/etc/gosa-si/client.conf";
105                 if(! -r $cfg_file) {
106                         $err_config = "please specify a config file";
107                         $err_counter += 1;
108                 }
109     }
110     if( $err_counter > 0 ) {
111         &usage( "", 1 );
112         if( defined( $err_config)) { print STDERR "$err_config\n"}
113         print STDERR "\n";
114         exit( -1 );
115     }
119 #===  FUNCTION  ================================================================
120 #         NAME:  read_configfile
121 #   PARAMETERS:  cfg_file - string - 
122 #      RETURNS:  
123 #  DESCRIPTION: 
124 #===============================================================================
125 sub read_configfile {
126     my ($cfg_file, %cfg_defaults) = @_ ;
127     my $cfg;
128     if( defined( $cfg_file) && ( length($cfg_file) > 0 )) {
129         if( -r $cfg_file ) {
130             $cfg = Config::IniFiles->new( -file => $cfg_file );
131         } else {
132             print STDERR "Couldn't read config file!";
133         }
134     } else {
135         $cfg = Config::IniFiles->new() ;
136     }
137     foreach my $section (keys %cfg_defaults) {
138         foreach my $param (keys %{$cfg_defaults{ $section }}) {
139             my $pinfo = $cfg_defaults{ $section }{ $param };
140             ${@$pinfo[ 0 ]} = $cfg->val( $section, $param, @$pinfo[ 1 ] );
141         }
142     }
146 #===  FUNCTION  ================================================================
147 #         NAME: check_pid
148 #   PARAMETERS:
149 #      RETURNS:
150 #  DESCRIPTION:
151 #===============================================================================
152 sub check_pid {
153     $pid = -1;
154     # Check, if we are already running
155     if( open(LOCK_FILE, "<$pid_file") ) {
156         $pid = <LOCK_FILE>;
157         if( defined $pid ) {
158             chomp( $pid );
159             if( -f "/proc/$pid/stat" ) {
160                 my($stat) = `cat /proc/$pid/stat` =~ m/$pid \((.+)\).*/;
161                 if( $0 eq $stat ) {
162                     close( LOCK_FILE );
163                     exit -1;
164                 }
165             }
166         }
167         close( LOCK_FILE );
168         unlink( $pid_file );
169     }
171     # create a syslog msg if it is not to possible to open PID file
172     if (not sysopen(LOCK_FILE, $pid_file, O_WRONLY|O_CREAT|O_EXCL, 0644)) {
173         my($msg) = "Couldn't obtain lockfile '$pid_file' ";
174         if (open(LOCK_FILE, '<', $pid_file)
175                 && ($pid = <LOCK_FILE>))
176         {
177             chomp($pid);
178             $msg .= "(PID $pid)\n";
179         } else {
180             $msg .= "(unable to read PID)\n";
181         }
182         if( ! ($foreground) ) {
183             openlog( $0, "cons,pid", "daemon" );
184             syslog( "warning", $msg );
185             closelog();
186         }
187         else {
188             print( STDERR " $msg " );
189         }
190         exit( -1 );
191     }
195 #===  FUNCTION  ================================================================
196 #         NAME:  logging
197 #   PARAMETERS:  level - string - default 'info' 
198 #                msg - string - 
199 #                facility - string - default 'LOG_DAEMON' 
200 #      RETURNS:  
201 #  DESCRIPTION: 
202 #===============================================================================
203 sub daemon_log {
204     # log into log_file
205     my( $msg, $level ) = @_;
206     if(not defined $msg) { return }
207     if(not defined $level) { $level = 1 }
208     if(defined $log_file){
209         open(LOG_HANDLE, ">>$log_file");
210         if(not defined open( LOG_HANDLE, ">>$log_file" )) {
211             print STDERR "cannot open $log_file: $!";
212             return }
213             chomp($msg);
214             if($level <= $verbose){
215                 my ($seconds, $minutes, $hours, $monthday, $month,
216                         $year, $weekday, $yearday, $sommertime) = localtime(time);
217                 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
218                 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
219                 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
220                 my @monthnames = ("Jan", "Feb", "Mar", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
221                 $month = $monthnames[$month];
222                 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
223                 $year+=1900;
224                 my $name = $0;
225                 $name =~ s/\.\///;
227                 my $log_msg = "$month $monthday $hours:$minutes:$seconds $name $msg\n";
228                 print LOG_HANDLE $log_msg;
229                 if( $foreground ) { 
230                     print STDERR $log_msg;
231                 }
232             }
233         close( LOG_HANDLE );
234     }
235 #log into syslog
236 #    my ($msg, $level, $facility) = @_;
237 #    if(not defined $msg) {return}
238 #    if(not defined $level) {$level = "info"}
239 #    if(not defined $facility) {$facility = "LOG_DAEMON"}
240 #    openlog($0, "pid,cons,", $facility);
241 #    syslog($level, $msg);
242 #    closelog;
243 #    return;
247 #===  FUNCTION  ================================================================
248 #         NAME:  get_interfaces 
249 #   PARAMETERS:  none
250 #      RETURNS:  (list of interfaces) 
251 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
252 #===============================================================================
253 sub get_interfaces {
254     my @result;
255     my $PROC_NET_DEV= ('/proc/net/dev');
257     open(PROC_NET_DEV, "<$PROC_NET_DEV")
258         or die "Could not open $PROC_NET_DEV";
260     my @ifs = <PROC_NET_DEV>;
262     close(PROC_NET_DEV);
264     # Eat first two line
265     shift @ifs;
266     shift @ifs;
268     chomp @ifs;
269     foreach my $line(@ifs) {
270         my $if= (split /:/, $line)[0];
271         $if =~ s/^\s+//;
272         push @result, $if;
273     }
275     return @result;
278 #===  FUNCTION  ================================================================
279 #         NAME:  get_mac 
280 #   PARAMETERS:  interface name (i.e. eth0)
281 #      RETURNS:  (mac address) 
282 #  DESCRIPTION:  Uses ioctl to get mac address directly from system.
283 #===============================================================================
284 sub get_mac {
285         my $ifreq= shift;
286         my $result;
287         if ($ifreq && length($ifreq) > 0) { 
288                 if($ifreq eq "all") {
289                         if(defined($server_ip)) {
290                                 $result = &get_local_mac_for_remote_ip($server_ip);
291                         } 
292                         elsif ($client_mac_address && length($client_mac_address) > 0){
293                                 $result = &client_mac_address;
294                         } 
295                         else {
296                                 $result = "00:00:00:00:00:00";
297                         }
298                 } else {
299                         my $SIOCGIFHWADDR= 0x8927;     # man 2 ioctl_list
301                         # A configured MAC Address should always override a guessed value
302                         if ($client_mac_address and length($client_mac_address) > 0) {
303                                 $result= $client_mac_address;
304                         }
305                         else {
306                                 socket SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('ip')
307                                         or die "socket: $!";
309                                 if(ioctl SOCKET, $SIOCGIFHWADDR, $ifreq) {
310                                         my ($if, $mac)= unpack 'h36 H12', $ifreq;
312                                         if (length($mac) > 0) {
313                                                 $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])$/;
314                                                 $mac= sprintf("%s:%s:%s:%s:%s:%s", $1, $2, $3, $4, $5, $6);
315                                                 $result = $mac;
316                                         }
317                                 }
318                         }
319                 }
320         }
321         return $result;
325 #===  FUNCTION  ================================================================
326 #         NAME:  get_interface_for_ip
327 #   PARAMETERS:  ip address (i.e. 192.168.0.1)
328 #      RETURNS:  array: list of interfaces if ip=0.0.0.0, matching interface if found, undef else
329 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
330 #===============================================================================
331 sub get_interface_for_ip {
332     my $result;
333     my $ip= shift;
334     if ($ip && length($ip) > 0) {
335         my @ifs= &get_interfaces();
336         if($ip eq "0.0.0.0") {
337             $result = "all";
338         } else {
339             foreach (@ifs) {
340                 my $if=$_;
341                 if(get_ip($if) eq $ip) {
342                     $result = $if;
343                     last;
344                 }
345             }       
346         }
347     }       
348     return $result;
352 #===  FUNCTION  ================================================================
353 #         NAME:  get_ip 
354 #   PARAMETERS:  interface name (i.e. eth0)
355 #      RETURNS:  (ip address) 
356 #  DESCRIPTION:  Uses ioctl to get ip address directly from system.
357 #===============================================================================
358 sub get_ip {
359     my $ifreq= shift;
360     my $result= "";
361     my $SIOCGIFADDR= 0x8915;       # man 2 ioctl_list
362         my $proto= getprotobyname('ip');
364     socket SOCKET, PF_INET, SOCK_DGRAM, $proto
365         or die "socket: $!";
367     if(ioctl SOCKET, $SIOCGIFADDR, $ifreq) {
368         my ($if, $sin)    = unpack 'a16 a16', $ifreq;
369         my ($port, $addr) = sockaddr_in $sin;
370         my $ip            = inet_ntoa $addr;
372         if ($ip && length($ip) > 0) {
373             $result = $ip;
374         }
375     }
377     return $result;
381 #===  FUNCTION  ================================================================
382 #         NAME:  get_local_mac_for_remote_ip
383 #   PARAMETERS:  none (takes server_ip from global variable)
384 #      RETURNS:  (ip address from interface that is used for communication) 
385 #  DESCRIPTION:  Uses ioctl to get routing table from system, checks which entry
386 #                matches (defaultroute last).
387 #===============================================================================
388 sub get_local_mac_for_remote_ip {
389     my $ifreq= shift;
390     my $result= "00:00:00:00:00:00";
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     }
419     return $result;
423 sub new_ldap_config {
424     my ($msg_hash) = @_ ;
425     my $element;
426     my @ldap_uris;
427     my $ldap_base;
428     my @ldap_options;
429     my @pam_options;
430     my @nss_options;
431     my $goto_admin;
432     my $goto_secret;
433     my $admin_base= "";
434     my $department= "";
435     my $unit_tag;
437     # Transform input into array
438     while ( my ($key, $value) = each(%$msg_hash) ) {
439         if ($key =~ /^(source|target|header)$/) {
440                 next;
441         }
443         foreach $element (@$value) {
444                 if ($key =~ /^ldap_uri$/) {
445                         push (@ldap_uris, $element);
446                         next;
447                 }
448                 if ($key =~ /^ldap_base$/) {
449                         $ldap_base= $element;
450                         next;
451                 }
452                 if ($key =~ /^goto_admin$/) {
453                         $goto_admin= $element;
454                         next;
455                 }
456                 if ($key =~ /^goto_secret$/) {
457                         $goto_secret= $element;
458                         next;
459                 }
460                 if ($key =~ /^ldap_cfg$/) {
461                         push (@ldap_options, "$element");
462                         next;
463                 }
464                 if ($key =~ /^pam_cfg$/) {
465                         push (@pam_options, "$element");
466                         next;
467                 }
468                 if ($key =~ /^nss_cfg$/) {
469                         push (@nss_options, "$element");
470                         next;
471                 }
472                 if ($key =~ /^admin_base$/) {
473                         $admin_base= $element;
474                         next;
475                 }
476                 if ($key =~ /^department$/) {
477                         $department= $element;
478                         next;
479                 }
480                 if ($key =~ /^unit_tag$/) {
481                         $unit_tag= $element;
482                         next;
483                 }
484         }
485     }
487     # Unit tagging enabled?
488     if (defined $unit_tag){
489             push (@pam_options, "pam_filter gosaUnitTag=$unit_tag");
490             push (@nss_options, "nss_base_passwd  $admin_base?sub?gosaUnitTag=$unit_tag");
491             push (@nss_options, "nss_base_group   $admin_base?sub?gosaUnitTag=$unit_tag");
492     }
494     # Setup ldap.conf
495     my $file1;
496     my $file2;
497     open(file1, "> $ldap_config");
498     print file1 "# This file was automatically generated by gosa-si-client. Do not change.\n";
499     print file1 "URI";
500     foreach $element (@ldap_uris) {
501         print file1 " $element";
502     }
503     print file1 "\nBASE $ldap_base\n";
504     foreach $element (@ldap_options) {
505         print file1 "$element\n";
506     }
507     close (file1);
508     daemon_log("wrote $ldap_config", 5);
510     # Setup pam_ldap.conf / libnss_ldap.conf
511     open(file1, "> $pam_config");
512     open(file2, "> $nss_config");
513     print file1 "# This file was automatically generated by gosa-si-client. Do not change.\n";
514     print file2 "# This file was automatically generated by gosa-si-client. Do not change.\n";
515     print file1 "uri";
516     print file2 "uri";
517     foreach $element (@ldap_uris) {
518         print file1 " $element";
519         print file2 " $element";
520     }
521     print file1 "\nbase $ldap_base\n";
522     print file2 "\nbase $ldap_base\n";
523     foreach $element (@pam_options) {
524         print file1 "$element\n";
525     }
526     foreach $element (@nss_options) {
527         print file2 "$element\n";
528     }
529     close (file2);
530     daemon_log("wrote $nss_config", 5);
531     close (file1);
532     daemon_log("wrote $pam_config", 5);
534     # Create goto.secrets if told so - for compatibility reasons
535     if (defined $goto_admin){
536             open(file1, "> /etc/goto/secret");
537             close(file1);
538             chown(0,0, "/etc/goto/secret");
539             chmod(0600, "/etc/goto/secret");
540             open(file1, "> /etc/goto/secret");
541             print file1 "GOTOADMIN=\"$goto_admin\"\nGOTOSECRET=\"$goto_secret\"\n";
542             close(file1);
543             daemon_log("wrote /etc/goto/secret", 5);
544     }
546     
548     # Write shell based config
549     my $cfg_name= dirname($ldap_config)."/ldap-shell.conf";
550     open(file1, "> $cfg_name");
551     print file1 "LDAP_BASE=\"$ldap_base\"\n";
552     print file1 "ADMIN_BASE=\"$admin_base\"\n";
553     print file1 "DEPARTMENT=\"$department\"\n";
554     print file1 "UNIT_TAG=\"".(defined $unit_tag ? "$unit_tag" : "")."\"\n";
555     print file1 "UNIT_TAG_FILTER=\"".(defined $unit_tag ? "(gosaUnitTag=$unit_tag)" : "")."\"\n";
556     close(file1);
557     daemon_log("wrote $cfg_name", 5);
559     return;
564 sub generate_hw_digest {
565         my $hw_data;
566         foreach my $line (split /\n/, `cat /proc/bus/pci/devices`) {
567                 $hw_data.= sprintf "%s", $line =~ /[^\s]+\s([^\s]+)\s.*/;
568         }
569         return(md5_base64($hw_data));
573 sub create_passwd {
574     my $new_passwd = "";
575     for(my $i=0; $i<31; $i++) {
576         $new_passwd .= ("a".."z","A".."Z",0..9)[int(rand(62))]
577     }
579     return $new_passwd;
583 sub get_server_addresses {
584     my $domain= shift;
585     my @result;
586     my $dig_cmd= 'dig +nocomments srv _gosad._tcp.'.$domain;
588     my $output= `$dig_cmd 2>&1`;
589     open (PIPE, "$dig_cmd 2>&1 |");
590     while(<PIPE>) {
591         chomp $_;
592         # If it's not a comment
593         if($_ =~ m/^[^;]/) {
594             my @matches= split /\s+/;
596             # Push hostname with port
597             if($matches[3] eq 'SRV') {
598                 push @result, $matches[7].':'.$matches[6];
599             } elsif ($matches[3] eq 'A') {
600                 my $i=0;
602                 # Substitute the hostname with the ip address of the matching A record
603                 foreach my $host (@result) {
604                     if ((split /\:/, $host)[0] eq $matches[0]) {
605                         $result[$i]= $matches[4].':'.(split /\:/, $host)[1];
606                     }
607                     $i++;
608                 }
609             }
610         }
611     }
612     close(PIPE);
613     return @result;
617 ##===  FUNCTION  ================================================================
618 ##         NAME:  create_ciphering
619 ##   PARAMETERS:  passwd - string - used to create ciphering
620 ##      RETURNS:  cipher - object
621 ##  DESCRIPTION:  creates a Crypt::Rijndael::MODE_CBC object with passwd as key
622 ##===============================================================================
623 #sub create_ciphering {
624 #    my ($passwd) = @_;
625 #    $passwd = substr(md5_hex("$passwd") x 32, 0, 32);
626 #    my $iv = substr(md5_hex('GONICUS GmbH'),0, 16);
628 #    #daemon_log("iv: $iv", 7);
629 #    #daemon_log("key: $passwd", 7);
630 #    my $my_cipher = Crypt::Rijndael->new($passwd , Crypt::Rijndael::MODE_CBC());
631 #    $my_cipher->set_iv($iv);
632 #    return $my_cipher;
633 #}
636 #sub create_ciphering {
637 #    my ($passwd) = @_;
638 #    $passwd = substr(md5_hex("$passwd") x 32, 0, 32);
639 #    my $iv = substr(md5_hex('GONICUS GmbH'),0, 16);
640 #    my $my_cipher = Crypt::Rijndael->new($passwd , Crypt::Rijndael::MODE_CBC());
641 #    $my_cipher->set_iv($iv);
642 #    return $my_cipher;
643 #}
646 #sub encrypt_msg {
647 #    my ($msg, $key) = @_;
648 #    my $my_cipher = &create_ciphering($key);
649 #    {
650 #      use bytes;
651 #      $msg = "\0"x(16-length($msg)%16).$msg;
652 #    }
653 #    $msg = $my_cipher->encrypt($msg);
654 #    chomp($msg = &encode_base64($msg));
655 #    # there are no newlines allowed inside msg
656 #    $msg=~ s/\n//g;
657 #    return $msg;
658 #}
661 #sub decrypt_msg {
662 #    my ($msg, $key) = @_ ;
663 #    $msg = &decode_base64($msg);
664 #    my $my_cipher = &create_ciphering($key);
665 #    $msg = $my_cipher->decrypt($msg); 
666 #    $msg =~ s/\0*//g;
667 #    return $msg;
668 #}
671 #===  FUNCTION  ================================================================
672 #         NAME:  send_msg_hash2address
673 #   PARAMETERS:  msg_hash - hash - xml_hash created with function create_xml_hash
674 #                PeerAddr string - socket address to send msg
675 #                PeerPort string - socket port, if not included in socket address
676 #      RETURNS:  nothing
677 #  DESCRIPTION:  ????
678 #===============================================================================
679 sub send_msg_hash2address {
680     my ($msg_hash, $address, $passwd) = @_ ;
682     # fetch header for logging
683     my $header = @{$msg_hash->{header}}[0];  
685     # generate xml string
686     my $msg_xml = &create_xml_string($msg_hash);
687     
688     # encrypt xml msg
689     my $crypted_msg = &encrypt_msg($msg_xml, $passwd);
691     # opensocket
692     my $socket = &open_socket($address);
693     if(not defined $socket){
694         daemon_log("cannot send '$header'-msg to $address , server not reachable", 5);
695         return 1;
696     }
697     
698     # send xml msg
699     print $socket $crypted_msg."\n";
700     
701     close $socket;
703     daemon_log("send '$header'-msg to $address", 1);
704     daemon_log("message:\n$msg_xml", 8);
705     return 0;
709 sub send_msg_to_target {
710     my ($msg, $address, $encrypt_key, $msg_header) = @_ ;
711     my $error = 0;
713     if( $msg_header ) {
714         $msg_header = "'$msg_header'-";
715     }
716     else {
717         $msg_header = "";
718     }
720     # encrypt xml msg
721     my $crypted_msg = &encrypt_msg($msg, $encrypt_key);
723     # opensocket
724     my $socket = &open_socket($address);
725     if( !$socket ) {
726         daemon_log("cannot send ".$msg_header."msg to $address , host not reachable", 1);
727         $error++;
728     }
729     
730     if( $error == 0 ) {
731         # send xml msg
732         print $socket $crypted_msg."\n";
734         daemon_log("send ".$msg_header."msg to $address", 1);
735         daemon_log("message:\n$msg", 8);
737     }
739     # close socket in any case
740     if( $socket ) {
741         close $socket;
742     }
744     return;
748 sub open_socket {
749     my ($PeerAddr, $PeerPort) = @_ ;
750     if(defined($PeerPort)){
751         $PeerAddr = $PeerAddr.":".$PeerPort;
752     }
753     my $socket;
754     $socket = new IO::Socket::INET(PeerAddr => $PeerAddr,
755             Porto => "tcp",
756             Type => SOCK_STREAM,
757             Timeout => 5,
758             );
759     if(not defined $socket) {
760         return;
761     }
762     &daemon_log("open_socket: $PeerAddr", 7);
763     return $socket;
767 #===  FUNCTION  ================================================================
768 #         NAME:  register_at_server
769 #   PARAMETERS:  
770 #      RETURNS:  
771 #  DESCRIPTION:  
772 #===============================================================================
773 sub register_at_gosa_si_server {
774     my ($kernel) = $_[KERNEL];
776     if( $REGISTERED_FLAG == 1 ) {
778         # create new passwd and ciphering object for client-server communication
779         $server_key = &create_passwd();
781         my $events = join( ", ", keys %{$event_hash} );
783         while(1) {
785             # fetch first gosa-si-server from @servers
786             my $server = shift(@servers);
788             if( !$server ) {
789                 daemon_log("no gosa-si-server left in list of servers", 1);
790                 daemon_log("unable to register at a gosa-si-server, force shutdown", 1);
791                 exit(1);
792             }
794             # create registration msg
795             my $register_hash = &create_xml_hash("here_i_am", $client_address, $server);
796             &add_content2xml_hash($register_hash, "new_passwd", $server_key);
797             &add_content2xml_hash($register_hash, "mac_address", $client_mac_address);
798             &add_content2xml_hash($register_hash, "events", $events);
799             &add_content2xml_hash($register_hash, "gotoHardwareChecksum", $gotoHardwareChecksum);
801             # send xml hash to server with general server passwd
802             my $res = &send_msg_hash2address($register_hash, $server, $default_server_key);
803             last;
804         }
805         daemon_log("waiting for msg 'register_at_gosa_si_server'",1);
806         $kernel->delay_set('register_at_gosa_si_server',2);
807     }
808     return;
810     
812 sub check_key_and_xml_validity {
813     my ($crypted_msg, $module_key) = @_;
814 #print STDERR "crypted_msg:$crypted_msg\n";
815 #print STDERR "modul_key:$module_key\n";
817     my $msg;
818     my $msg_hash;
819     eval{
820         $msg = &decrypt_msg($crypted_msg, $module_key);
821         &main::daemon_log("decrypted_msg: \n$msg", 8);
823         $msg_hash = $xml->XMLin($msg, ForceArray=>1);
825         # check header
826         my $header_l = $msg_hash->{'header'};
827         if( 1 != @{$header_l} ) {
828             die 'no or more headers specified';
829         }
830         my $header = @{$header_l}[0];
831         if( 0 == length $header) {
832             die 'header has length 0';
833         }
835         # check source
836         my $source_l = $msg_hash->{'source'};
837         if( 1 != @{$source_l} ) {
838             die 'no or more sources specified';
839         }
840         my $source = @{$source_l}[0];
841         if( 0 == length $source) {
842             die 'source has length 0';
843         }
845         # check target
846         my $target_l = $msg_hash->{'target'};
847         if( 1 != @{$target_l} ) {
848             die 'no or more targets specified ';
849         }
850         my $target = @{$target_l}[0];
851         if( 0 == length $target) {
852             die 'target has length 0 ';
853         }
855     };
856     if($@) {
857         &main::daemon_log("WARNING: do not understand the message or msg is not gosa-si envelope conform:", 5);
858         &main::daemon_log("$@", 8);
859     }
861     return ($msg, $msg_hash);
865 sub import_events {
867     if (not -e $event_dir) {
868         daemon_log("ERROR: cannot find directory or directory is not readable: $event_dir", 1);   
869     }
870     opendir (DIR, $event_dir) or die "ERROR while loading gosa-si-events from directory $event_dir : $!\n";
872     while (defined (my $event = readdir (DIR))) {
873         if( $event eq "." || $event eq ".." ) { next; }    
875         eval{ require $event; };
876         if( $@ ) {
877             daemon_log("import of event module '$event' failed", 1);
878             daemon_log("$@", 8);
879             next;
880         }
882         $event =~ /(\S*?).pm$/;
883         my $event_module = $1;
884         my $events_l = eval( $1."::get_events()") ;
885         foreach my $event_name (@{$events_l}) {
886             $event_hash->{$event_name} = $event_module;
887         }
889     }
893 sub server_input {
894     my ($heap,$input,$wheel) = @_[HEAP, ARG0, ARG1];
895     my $error = 0;
896     my $answer;
897     
898     daemon_log("Incoming msg:\n$input\n", 8);
900     my ($msg, $msg_hash) = &check_key_and_xml_validity($input, $server_key);
901     if( (!$msg) || (!$msg_hash) ) {
902         daemon_log("Deciphering of incoming msg failed", 5);
903         $error++;
904     }
906     ######################
907     # process incoming msg
908     if( $error == 0 ) {
909         my $header = @{$msg_hash->{header}}[0];
910         my $source = @{$msg_hash->{source}}[0];
912         if( exists $event_hash->{$header} ) {
913             # a event exists with the header as name
914             daemon_log("found event '$header' at event-module '".$event_hash->{$header}."'", 5);
915             no strict 'refs';
916             $answer = &{$event_hash->{$header}."::$header"}($msg, $msg_hash);
917          }
918     }
920     ########
921     # answer
922     if( $answer ) {
923         if( $answer =~ "<header>registered</header>") {
924             $REGISTERED_FLAG = 0;
925         } 
926         else {
927         &send_msg_to_address($answer, $server_address, $server_key);
928         }
929     }
931     return;
934 #==== MAIN = main ==============================================================
935 #  parse commandline options
936 Getopt::Long::Configure( "bundling" );
937 GetOptions("h|help" => \&usage,
938            "c|config=s" => \$cfg_file,
939            "f|foreground" => \$foreground,
940            "v|verbose+" => \$verbose,
941            );
943 #  read and set config parameters
944 &check_cmdline_param ;
945 &read_configfile($cfg_file, %cfg_defaults);
946 &check_pid;
949 # forward error messages to logfile
950 if ( ! $foreground ) {
951         open STDIN, '/dev/null' or die "Can’t read /dev/null: $!";
952         open STDOUT, '>>/dev/null' or die "Can't write to /dev/null: $!";
953         open STDERR, '>>/dev/null' or die "Can't write to /dev/null: $!";
956 # Just fork, if we are not in foreground mode
957 if( ! $foreground ) { 
958     chdir '/'                 or die "Can't chdir to /: $!";
959     $pid = fork;
960     setsid                    or die "Can't start a new session: $!";
961     umask 0;
962
963 else { 
964     $pid = $$; 
967 # Do something useful - put our PID into the pid_file
968 if( 0 != $pid ) {
969     open( LOCK_FILE, ">$pid_file" );
970     print LOCK_FILE "$pid\n";
971     close( LOCK_FILE );
972     if( !$foreground ) { 
973         exit( 0 ) 
974     };
977 daemon_log(" ", 1);
978 daemon_log("$0 started!", 1);
980 # delete old DBsqlite lock files
981 system('rm -f /tmp/gosa_si_lock*gosa-si-client*');
984 # complete client_address
985 $client_address = $client_ip.":".$client_port;
988 # detect own ip and mac address
989 my $network_interface= &get_interface_for_ip($client_ip);
990 $client_mac_address= &get_mac($network_interface);
991 daemon_log("gosa-si-client ip address detected: $client_ip", 1);
992 daemon_log("gosa-si-client mac address detected: $client_mac_address", 1);
995 # import events
996 &import_events();
999 # compute hardware checksum
1000 $gotoHardwareChecksum= &generate_hw_digest();
1001 daemon_log("gosa-si-client gotoHardwareChecksum detected: $gotoHardwareChecksum", 1);
1004 # create socket for incoming xml messages
1005 POE::Component::Server::TCP->new(
1006     Alias => 'gosa-si-client',
1007         Port => $client_port,
1008         ClientInput => \&server_input,
1009 );
1010 daemon_log("start socket for incoming xml messages at port '$client_port' ", 1);
1013 # prepare variables
1014 if (defined $server_ip && defined $server_port) {
1015     $server_address = $server_ip.":".$server_port;
1017 $xml = new XML::Simple();
1018 $default_server_key = $server_key;
1021 # find all possible gosa-si-servers in DNS
1022 if (defined $server_domain) {
1023     my @tmp_servers = &get_server_addresses($server_domain);
1024     foreach my $server (@tmp_servers) { 
1025         unshift(@servers, $server); 
1026     }
1028 # add gosa-si-server address from config file at first position of server list
1029 if (defined $server_address) {
1030     unshift(@servers, $server_address);
1032 my $servers_string = join(", ", @servers);
1033 daemon_log("found servers in configuration file and via DNS: $servers_string", 5);
1036 POE::Session->create(
1037         inline_states => {
1038                 _start => \&register_at_gosa_si_server ,
1039         register_at_gosa_si_server => \&register_at_gosa_si_server,
1040         }
1041 );
1043 POE::Kernel->run();
1044 exit;