Code

c9231d2aae6f531453385fcbf73e36b1b29149d6
[gosa.git] / gosa-si / modules / SIPackages.pm
1 package SIPackages;
3 use Exporter;
4 @ISA = ("Exporter");
6 # Each module has to have a function 'process_incoming_msg'. This function works as a interface to gosa-sd and receives the msg hash from gosa-sd. 'process_incoming_function checks, wether it has a function to process the incoming msg and forward the msg to it. 
9 use strict;
10 use warnings;
11 use GOSA::GosaSupportDaemon;
12 use IO::Socket::INET;
13 use XML::Simple;
14 use Data::Dumper;
15 use NetAddr::IP;
16 use Net::LDAP;
17 use Socket;
18 use Net::hostent;
19 use Net::DNS;
21 my $event_dir = "/usr/lib/gosa-si/server/events";
22 use lib "/usr/lib/gosa-si/server/events";
24 BEGIN{}
25 END {}
27 my ($server_ip, $server_mac_address, $server_port, $SIPackages_key, $max_clients, $ldap_uri, $ldap_base, $ldap_admin_dn, $ldap_admin_password, $server_interface);
28 my ($bus_activ, $bus_key, $bus_ip, $bus_port);
29 my $server;
30 my $event_hash;
31 my $network_interface;
32 my $no_bus;
33 my (@ldap_cfg, @pam_cfg, @nss_cfg, $goto_admin, $goto_secret);
35 my %cfg_defaults = (
36 "bus" => {
37     "activ" => [\$bus_activ, "on"],
38     "key" => [\$bus_key, ""],
39     "ip" => [\$bus_ip, ""],
40     "port" => [\$bus_port, "20080"],
41     },
42 "server" => {
43     "ip" => [\$server_ip, "0.0.0.0"],
44     "mac-address" => [\$server_mac_address, "00:00:00:00:00"],
45     "port" => [\$server_port, "20081"],
46     "ldap-uri" => [\$ldap_uri, ""],
47     "ldap-base" => [\$ldap_base, ""],
48     "ldap-admin-dn" => [\$ldap_admin_dn, ""],
49     "ldap-admin-password" => [\$ldap_admin_password, ""],
50     "max-clients" => [\$max_clients, 100],
51     },
52 "SIPackages" => {
53     "key" => [\$SIPackages_key, ""],
54     },
55 );
57 ### START #####################################################################
59 # read configfile and import variables
60 &read_configfile();
62 $network_interface= &get_interface_for_ip($server_ip);
63 $server_mac_address= &get_mac($network_interface);
65 &import_events();
67 # Unit tag can be defined in config
68 if((not defined($main::gosa_unit_tag)) || length($main::gosa_unit_tag) == 0) {
69         # Read gosaUnitTag from LDAP
70         my $tmp_ldap= Net::LDAP->new($ldap_uri);
71         if(defined($tmp_ldap)) {
72                 &main::daemon_log("Searching for servers gosaUnitTag with mac address $server_mac_address",6);
73                 my $mesg= $tmp_ldap->bind($ldap_admin_dn, password => $ldap_admin_password);
74                 # Perform search for Unit Tag
75                 $mesg = $tmp_ldap->search(
76                         base   => $ldap_base,
77                         scope  => 'sub',
78                         attrs  => ['gosaUnitTag'],
79                         filter => "(macaddress=$server_mac_address)"
80                 );
82                 if ($mesg->count == 1) {
83                         my $entry= $mesg->entry(0);
84                         my $unit_tag= $entry->get_value("gosaUnitTag");
85                         if(defined($unit_tag) && length($unit_tag) > 0) {
86                                 &main::daemon_log("Detected gosaUnitTag $unit_tag for creating entries", 4);
87                                 $main::gosa_unit_tag= $unit_tag;
88                         }
89                 } else {
90                         # Perform another search for Unit Tag
91                         my $hostname= `hostname -f`;
92                         chomp($hostname);
93                         &main::daemon_log("Searching for servers gosaUnitTag with hostname $hostname",6);
94                         $mesg = $tmp_ldap->search(
95                                 base   => $ldap_base,
96                                 scope  => 'sub',
97                                 attrs  => ['gosaUnitTag'],
98                                 filter => "(&(cn=$hostname)(objectClass=goServer))"
99                         );
100                         if ($mesg->count == 1) {
101                                 my $entry= $mesg->entry(0);
102                                 my $unit_tag= $entry->get_value("gosaUnitTag");
103                                 if(defined($unit_tag) && length($unit_tag) > 0) {
104                                         &main::daemon_log("Detected gosaUnitTag $unit_tag for creating entries", 4);
105                                         $main::gosa_unit_tag= $unit_tag;
106                                 }
107                         } else {
108                                 # Perform another search for Unit Tag
109                                 $hostname= `hostname -s`;
110                                 chomp($hostname);
111                                 &main::daemon_log("Searching for servers gosaUnitTag with hostname $hostname",6);
112                                 $mesg = $tmp_ldap->search(
113                                         base   => $ldap_base,
114                                         scope  => 'sub',
115                                         attrs  => ['gosaUnitTag'],
116                                         filter => "(&(cn=$hostname)(objectClass=goServer))"
117                                 );
118                                 if ($mesg->count == 1) {
119                                         my $entry= $mesg->entry(0);
120                                         my $unit_tag= $entry->get_value("gosaUnitTag");
121                                         if(defined($unit_tag) && length($unit_tag) > 0) {
122                                                 &main::daemon_log("Detected gosaUnitTag $unit_tag for creating entries", 4);
123                                                 $main::gosa_unit_tag= $unit_tag;
124                                         }
125                                 } else {
126                                         &main::daemon_log("Not using gosaUnitTag", 6);
127                                 }
128                         }
129                 }
130         } else {
131                 &main::daemon_log("Using gosaUnitTag from config-file: $main::gosa_unit_tag",6);
132         }
133         $tmp_ldap->unbind;
136 # complete addresses
137 #if( $server_ip eq "0.0.0.0" ) {
138 #    $server_ip = "127.0.0.1";
139 #}
140 my $server_address = "$server_ip:$server_port";
141 $main::server_address = $server_address;
142 my $bus_address = "$bus_ip:$bus_port";
143 $main::bus_address = $bus_address;
145 # create general settings for this module
146 my $xml = new XML::Simple();
148 # register at bus
149 if ($main::no_bus > 0) {
150     $bus_activ = "off"
152 if($bus_activ eq "on") {
153     &register_at_bus();
156 # add myself to known_server_db
157 my $res = $main::known_server_db->add_dbentry( {table=>'known_server',
158         primkey=>'hostname',
159         hostname=>$server_address,
160         status=>'myself',
161         hostkey=>$SIPackages_key,
162         timestamp=>&get_time,
163         } );
167 ### functions #################################################################
170 sub get_module_info {
171     my @info = ($server_address,
172                 $SIPackages_key,
173                 );
174     return \@info;
178 #sub daemon_log {
179 #    my ($msg, $level) = @_ ;
180 #    &main::daemon_log($msg, $level);
181 #    return;
182 #}
185 #sub do_wake {
186 #        my $host    = shift;
187 #        my $ipaddr  = shift || '255.255.255.255';
188 #        my $port    = getservbyname('discard', 'udp');
190 #        my ($raddr, $them, $proto);
191 #        my ($hwaddr, $hwaddr_re, $pkt);
193 #        # get the hardware address (ethernet address)
195 #        $hwaddr_re = join(':', ('[0-9A-Fa-f]{1,2}') x 6);
196 #        if ($host =~ m/^$hwaddr_re$/) {
197 #                $hwaddr = $host;
198 #        } else {
199 #                # $host is not a hardware address, try to resolve it
200 #                my $ip_re = join('\.', ('([0-9]|[1-9][0-9]|1[0-9]{2}|2([0-4][0-9]|5[0-5]))') x 4);
201 #                my $ip_addr;
202 #                if ($host =~ m/^$ip_re$/) {
203 #                        $ip_addr = $host;
204 #                } else {
205 #                        my $h;
206 #                        unless ($h = gethost($host)) {
207 #                                return undef;
208 #                        }
209 #                        $ip_addr = inet_ntoa($h->addr);
210 #                }
211 #        }
213 #        # Generate magic sequence
214 #        foreach (split /:/, $hwaddr) {
215 #                $pkt .= chr(hex($_));
216 #        }
217 #        $pkt = chr(0xFF) x 6 . $pkt x 16;
219 #        # Allocate socket and send packet
221 #        $raddr = gethostbyname($ipaddr)->addr;
222 #        $them = pack_sockaddr_in($port, $raddr);
223 #        $proto = getprotobyname('udp');
225 #        socket(S, AF_INET, SOCK_DGRAM, $proto) or die "socket : $!";
226 #        setsockopt(S, SOL_SOCKET, SO_BROADCAST, 1) or die "setsockopt : $!";
228 #        send(S, $pkt, 0, $them) or die "send : $!";
229 #        close S;
230 #}
233 #===  FUNCTION  ================================================================
234 #         NAME:  read_configfile
235 #   PARAMETERS:  cfg_file - string -
236 #      RETURNS:  nothing
237 #  DESCRIPTION:  read cfg_file and set variables
238 #===============================================================================
239 sub read_configfile {
240     my $cfg;
241     if( defined( $main::cfg_file) && ( length($main::cfg_file) > 0 )) {
242         if( -r $main::cfg_file ) {
243             $cfg = Config::IniFiles->new( -file => $main::cfg_file );
244         } else {
245             print STDERR "Couldn't read config file!";
246         }
247     } else {
248         $cfg = Config::IniFiles->new() ;
249     }
250     foreach my $section (keys %cfg_defaults) {
251         foreach my $param (keys %{$cfg_defaults{ $section }}) {
252             my $pinfo = $cfg_defaults{ $section }{ $param };
253             ${@$pinfo[0]} = $cfg->val( $section, $param, @$pinfo[1] );
254         }
255     }
257     # Read non predefined sections
258     my $param;
259     if ($cfg->SectionExists('ldap')){
260                 foreach $param ($cfg->Parameters('ldap')){
261                         push (@ldap_cfg, "$param ".$cfg->val('ldap', $param));
262                 }
263     }
264     if ($cfg->SectionExists('pam_ldap')){
265                 foreach $param ($cfg->Parameters('pam_ldap')){
266                         push (@pam_cfg, "$param ".$cfg->val('pam_ldap', $param));
267                 }
268     }
269     if ($cfg->SectionExists('nss_ldap')){
270                 foreach $param ($cfg->Parameters('nss_ldap')){
271                         push (@nss_cfg, "$param ".$cfg->val('nss_ldap', $param));
272                 }
273     }
274     if ($cfg->SectionExists('goto')){
275         $goto_admin= $cfg->val('goto', 'terminal_admin');
276         $goto_secret= $cfg->val('goto', 'terminal_secret');
277     } else {
278         $goto_admin= undef;
279         $goto_secret= undef;
280     }
284 #===  FUNCTION  ================================================================
285 #         NAME:  get_interface_for_ip
286 #   PARAMETERS:  ip address (i.e. 192.168.0.1)
287 #      RETURNS:  array: list of interfaces if ip=0.0.0.0, matching interface if found, undef else
288 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
289 #===============================================================================
290 sub get_interface_for_ip {
291         my $result;
292         my $ip= shift;
293         if ($ip && length($ip) > 0) {
294                 my @ifs= &get_interfaces();
295                 if($ip eq "0.0.0.0") {
296                         $result = "all";
297                 } else {
298                         foreach (@ifs) {
299                                 my $if=$_;
300                                 if(get_ip($if) eq $ip) {
301                                         $result = $if;
302                                 }
303                         }       
304                 }
305         }       
306         return $result;
309 #===  FUNCTION  ================================================================
310 #         NAME:  get_interfaces 
311 #   PARAMETERS:  none
312 #      RETURNS:  (list of interfaces) 
313 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
314 #===============================================================================
315 sub get_interfaces {
316         my @result;
317         my $PROC_NET_DEV= ('/proc/net/dev');
319         open(PROC_NET_DEV, "<$PROC_NET_DEV")
320                 or die "Could not open $PROC_NET_DEV";
322         my @ifs = <PROC_NET_DEV>;
324         close(PROC_NET_DEV);
326         # Eat first two line
327         shift @ifs;
328         shift @ifs;
330         chomp @ifs;
331         foreach my $line(@ifs) {
332                 my $if= (split /:/, $line)[0];
333                 $if =~ s/^\s+//;
334                 push @result, $if;
335         }
337         return @result;
340 #===  FUNCTION  ================================================================
341 #         NAME:  get_mac 
342 #   PARAMETERS:  interface name (i.e. eth0)
343 #      RETURNS:  (mac address) 
344 #  DESCRIPTION:  Uses ioctl to get mac address directly from system.
345 #===============================================================================
346 sub get_mac {
347         my $ifreq= shift;
348         my $result;
349         if ($ifreq && length($ifreq) > 0) { 
350                 if($ifreq eq "all") {
351                         $result = "00:00:00:00:00:00";
352                 } else {
353                         my $SIOCGIFHWADDR= 0x8927;     # man 2 ioctl_list
355                         # A configured MAC Address should always override a guessed value
356                         if ($server_mac_address and length($server_mac_address) > 0) {
357                                 $result= $server_mac_address;
358                         }
360                         socket SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('ip')
361                                 or die "socket: $!";
363                         if(ioctl SOCKET, $SIOCGIFHWADDR, $ifreq) {
364                                 my ($if, $mac)= unpack 'h36 H12', $ifreq;
366                                 if (length($mac) > 0) {
367                                         $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])$/;
368                                         $mac= sprintf("%s:%s:%s:%s:%s:%s", $1, $2, $3, $4, $5, $6);
369                                         $result = $mac;
370                                 }
371                         }
372                 }
373         }
374         return $result;
378 #===  FUNCTION  ================================================================
379 #         NAME:  register_at_bus
380 #   PARAMETERS:  nothing
381 #      RETURNS:  nothing
382 #  DESCRIPTION:  creates an entry in known_daemons and send a 'here_i_am' msg to bus
383 #===============================================================================
384 sub register_at_bus {
386     # add bus to known_server_db
387     my $res = $main::known_server_db->add_dbentry( {table=>'known_server',
388                                                     primkey=>'hostname',
389                                                     hostname=>$bus_address,
390                                                     status=>'bus',
391                                                     hostkey=>$bus_key,
392                                                     timestamp=>&get_time,
393                                                 } );
394     my $msg_hash = &create_xml_hash("here_i_am", $server_address, $bus_address);
395     my $msg = &create_xml_string($msg_hash);
397     &main::send_msg_to_target($msg, $bus_address, $bus_key, "here_i_am");
398     return $msg;
402 sub import_events {
403     if (not -e $event_dir) {
404         &main::daemon_log("ERROR: cannot find directory or directory is not readable: $event_dir", 1);   
405     }
406     opendir (DIR, $event_dir) or die "ERROR while loading gosa-si-events from directory $event_dir : $!\n";
408     while (defined (my $event = readdir (DIR))) {
409         if( $event eq "." || $event eq ".." ) { next; }  
410         if( $event eq "gosaTriggered.pm" ) { next; }    # only GOsa specific events
412         eval{ require $event; };
413         if( $@ ) {
414             &main::daemon_log("import of event module '$event' failed", 1);
415             &main::daemon_log("$@", 8);
416             next;
417         }
419         $event =~ /(\S*?).pm$/;
420         my $event_module = $1;
421         my $events_l = eval( $1."::get_events()") ;
422         foreach my $event_name (@{$events_l}) {
423             $event_hash->{$event_name} = $event_module;
424         }
425         my $events_string = join( ", ", @{$events_l});
426         &main::daemon_log("INFO: SIPackages imported events $events_string", 5);
427     }
431 #===  FUNCTION  ================================================================
432 #         NAME:  process_incoming_msg
433 #   PARAMETERS:  crypted_msg - string - incoming crypted message
434 #      RETURNS:  nothing
435 #  DESCRIPTION:  handels the proceeded distribution to the appropriated functions
436 #===============================================================================
437 sub process_incoming_msg {
438     my ($msg, $msg_hash, $session_id) = @_ ;
439     my $error = 0;
440     my $host_name;
441     my $host_key;
442     my @out_msg_l = ();
444     # process incoming msg
445     my $header = @{$msg_hash->{header}}[0]; 
446     my @target_l = @{$msg_hash->{target}};
448     # skip PREFIX
449     $header =~ s/^CLMSG_//;
451     &main::daemon_log("SIPackages: msg to process: $header", 3);
452     &main::daemon_log("$msg", 8);
454     if( 0 == length @target_l){     
455         &main::daemon_log("ERROR: no target specified for msg $header", 1);
456         $error++;
457     }
459     if( 1 == length @target_l) {
460         my $target = $target_l[0];
461                 if(&server_matches($target)) {
464             if ($header eq 'new_key') {
465                 @out_msg_l = &new_key($msg_hash)
466             } elsif ($header eq 'here_i_am') {
467                 @out_msg_l = &here_i_am($msg_hash)
468             } else {
469                 if( exists $event_hash->{$header} ) {
470                     # a event exists with the header as name
471                     &main::daemon_log("found event '$header' at event-module '".$event_hash->{$header}."'", 5);
472                     no strict 'refs';
473                     @out_msg_l = &{$event_hash->{$header}."::$header"}($msg, $msg_hash, $session_id);
474                 }
475             }
477             # if delivery not possible raise error and return 
478             if( not @out_msg_l ) {
479                 &main::daemon_log("WARNING: SIPackages got not answer from event handler '$header'", 3);
480             } elsif( 0 == @out_msg_l) {
481                 &main::daemon_log("ERROR: SIPackages: no event handler or core function defined for '$header'", 1);
482             } 
483         }
484                 else {
485                         &main::daemon_log("msg is not for gosa-si-server '$server_address', deliver it to target '$target'", 5);
486                         push(@out_msg_l, $msg);
487                 }
488     }
490     return \@out_msg_l;
494 #===  FUNCTION  ================================================================
495 #         NAME:  got_ping
496 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
497 #      RETURNS:  nothing
498 #  DESCRIPTION:  process this incoming message
499 #===============================================================================
500 #sub got_ping {
501 #    my ($msg_hash) = @_;
503 #    my $source = @{$msg_hash->{source}}[0];
504 #    my $target = @{$msg_hash->{target}}[0];
505 #    my $header = @{$msg_hash->{header}}[0];
506 #    my $session_id = @{$msg_hash->{'session_id'}}[0];
507 #    my $act_time = &get_time;
508 #    my @out_msg_l;
509 #    my $out_msg;
511 #    # check known_clients_db
512 #    my $sql_statement = "SELECT * FROM known_clients WHERE hostname='$source'";
513 #    my $query_res = $main::known_clients_db->select_dbentry( $sql_statement );
514 #    if( 1 == keys %{$query_res} ) {
515 #         my $sql_statement= "UPDATE known_clients ".
516 #            "SET status='$header', timestamp='$act_time' ".
517 #            "WHERE hostname='$source'";
518 #         my $res = $main::known_clients_db->update_dbentry( $sql_statement );
519 #    } 
520 #    
521 #    # check known_server_db
522 #    $sql_statement = "SELECT * FROM known_server WHERE hostname='$source'";
523 #    $query_res = $main::known_server_db->select_dbentry( $sql_statement );
524 #    if( 1 == keys %{$query_res} ) {
525 #         my $sql_statement= "UPDATE known_server ".
526 #            "SET status='$header', timestamp='$act_time' ".
527 #            "WHERE hostname='$source'";
528 #         my $res = $main::known_server_db->update_dbentry( $sql_statement );
529 #    } 
531 #    # create out_msg
532 #    my $out_hash = &create_xml_hash($header, $source, "GOSA");
533 #    &add_content2xml_hash($out_hash, "session_id", $session_id);
534 #    $out_msg = &create_xml_string($out_hash);
535 #    push(@out_msg_l, $out_msg);
536 #    
537 #    return @out_msg_l;
538 #}
540 #===  FUNCTION  ================================================================
541 #         NAME:  new_passwd
542 #   PARAMETERS:  msg_hash - ref - hash from function create_xml_hash
543 #      RETURNS:  nothing
544 #  DESCRIPTION:  process this incoming message
545 #===============================================================================
546 sub new_key {
547     my ($msg_hash) = @_;
548     my @out_msg_l;
549     
550     my $header = @{$msg_hash->{header}}[0];
551     my $source_name = @{$msg_hash->{source}}[0];
552     my $source_key = @{$msg_hash->{new_key}}[0];
553     my $query_res;
555     # check known_clients_db
556     my $sql_statement = "SELECT * FROM known_clients WHERE hostname='$source_name'";
557     $query_res = $main::known_clients_db->select_dbentry( $sql_statement );
558     if( 1 == keys %{$query_res} ) {
559         my $act_time = &get_time;
560         my $sql_statement= "UPDATE known_clients ".
561             "SET hostkey='$source_key', timestamp='$act_time' ".
562             "WHERE hostname='$source_name'";
563         my $res = $main::known_clients_db->update_dbentry( $sql_statement );
564         my $hash = &create_xml_hash("confirm_new_key", $server_address, $source_name);
565         my $out_msg = &create_xml_string($hash);
566         push(@out_msg_l, $out_msg);
567     }
569     # only do if host still not found
570     if( 0 == @out_msg_l ) {
571         # check known_server_db
572         $sql_statement = "SELECT * FROM known_server WHERE hostname='$source_name'";
573         $query_res = $main::known_server_db->select_dbentry( $sql_statement );
574         if( 1 == keys %{$query_res} ) {
575             my $act_time = &get_time;
576             my $sql_statement= "UPDATE known_server ".
577                 "SET hostkey='$source_key', timestamp='$act_time' ".
578                 "WHERE hostname='$source_name'";
579             my $res = $main::known_server_db->update_dbentry( $sql_statement );
581             my $hash = &create_xml_hash("confirm_new_key", $server_address, $source_name);
582             my $out_msg = &create_xml_string($hash);
583             push(@out_msg_l, $out_msg);
584         }
585     }
587     return @out_msg_l;
591 #===  FUNCTION  ================================================================
592 #         NAME:  here_i_am
593 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
594 #      RETURNS:  nothing
595 #  DESCRIPTION:  process this incoming message
596 #===============================================================================
597 sub here_i_am {
598     my ($msg_hash) = @_;
599     my @out_msg_l;
600     my $out_hash;
602     my $source = @{$msg_hash->{source}}[0];
603     my $mac_address = @{$msg_hash->{mac_address}}[0];
604         my $gotoHardwareChecksum = @{$msg_hash->{gotoHardwareChecksum}}[0];
606     # number of known clients
607     my $nu_clients= $main::known_clients_db->count_dbentries('known_clients');
609     # check wether client address or mac address is already known
610     my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$source'";
611     my $db_res= $main::known_clients_db->select_dbentry( $sql_statement );
612     
613     if ( 1 == keys %{$db_res} ) {
614         &main::daemon_log("WARNING: $source is already known as a client", 1);
615         &main::daemon_log("WARNING: values for $source are being overwritten", 1);   
616         $nu_clients --;
617     }
619     # number of actual activ clients
620     my $act_nu_clients = $nu_clients;
622     &main::daemon_log("number of actual activ clients: $act_nu_clients", 5);
623     &main::daemon_log("number of maximal allowed clients: $max_clients", 5);
625     if($max_clients <= $act_nu_clients) {
626         my $out_hash = &create_xml_hash("denied", $server_address, $source);
627         &add_content2xml_hash($out_hash, "denied", "I_cannot_take_any_more_clients!");
628         my $passwd = @{$msg_hash->{new_passwd}}[0]; 
629         &send_msg_hash2address($out_hash, $source, $passwd);
630         return;
631     }
632     
633     # new client accepted
634     my $new_passwd = @{$msg_hash->{new_passwd}}[0];
636     # create entry in known_clients
637     my $events = @{$msg_hash->{events}}[0];
638     
640     # add entry to known_clients_db
641     my $act_timestamp = &get_time;
642     my $res = $main::known_clients_db->add_dbentry( {table=>'known_clients', 
643                                                 primkey=>'hostname',
644                                                 hostname=>$source,
645                                                 events=>$events,
646                                                 macaddress=>$mac_address,
647                                                 status=>'registered',
648                                                 hostkey=>$new_passwd,
649                                                 timestamp=>$act_timestamp,
650                                                 } );
652     if ($res != 0)  {
653         &main::daemon_log("ERROR: cannot add entry to known_clients: $res");
654         return;
655     }
656     
657     # return acknowledgement to client
658     $out_hash = &create_xml_hash("registered", $server_address, $source);
659     my $register_out = &create_xml_string($out_hash);
660     push(@out_msg_l, $register_out);
662     # notify registered client to bus
663     if( $bus_activ eq "on") {
664         # fetch actual bus key
665         my $sql_statement= "SELECT * FROM known_server WHERE status='bus'";
666         my $query_res = $main::known_server_db->select_dbentry( $sql_statement );
667         my $hostkey = $query_res->{1}->{'hostkey'};
669         # send update msg to bus
670         $out_hash = &create_xml_hash("new_client", $server_address, $bus_address, $source);
671         &add_content2xml_hash($out_hash, "macaddress", $mac_address);
672         &add_content2xml_hash($out_hash, "timestamp", $act_timestamp);
673         my $new_client_out = &create_xml_string($out_hash);
674         push(@out_msg_l, $new_client_out);
675         &main::daemon_log("send bus msg that client '$source' has registerd at server '$server_address'", 3);
676     }
678     # give the new client his ldap config
679     my $new_ldap_config_out = &new_ldap_config($source);
680     if( $new_ldap_config_out ) {
681         push(@out_msg_l, $new_ldap_config_out);
682     }
684         my $hardware_config_out = &hardware_config($source, $gotoHardwareChecksum);
685         if( $hardware_config_out ) {
686                 push(@out_msg_l, $hardware_config_out);
687         }
689     return @out_msg_l;
693 #===  FUNCTION  ================================================================
694 #         NAME:  who_has
695 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
696 #      RETURNS:  nothing 
697 #  DESCRIPTION:  process this incoming message
698 #===============================================================================
699 sub who_has {
700     my ($msg_hash) = @_ ;
701     my @out_msg_l;
702     
703     # what is your search pattern
704     my $search_pattern = @{$msg_hash->{who_has}}[0];
705     my $search_element = @{$msg_hash->{$search_pattern}}[0];
706     &main::daemon_log("who_has-msg looking for $search_pattern $search_element", 7);
708     # scanning known_clients for search_pattern
709     my @host_addresses = keys %$main::known_clients;
710     my $known_clients_entries = length @host_addresses;
711     my $host_address;
712     foreach my $host (@host_addresses) {
713         my $client_element = $main::known_clients->{$host}->{$search_pattern};
714         if ($search_element eq $client_element) {
715             $host_address = $host;
716             last;
717         }
718     }
719         
720     # search was successful
721     if (defined $host_address) {
722         my $source = @{$msg_hash->{source}}[0];
723         my $out_hash = &create_xml_hash("who_has_i_do", $server_address, $source, "mac_address");
724         &add_content2xml_hash($out_hash, "mac_address", $search_element);
725         my $out_msg = &create_xml_string($out_hash);
726         push(@out_msg_l, $out_msg);
727     }
728     return @out_msg_l;
732 sub who_has_i_do {
733     my ($msg_hash) = @_ ;
734     my $header = @{$msg_hash->{header}}[0];
735     my $source = @{$msg_hash->{source}}[0];
736     my $search_param = @{$msg_hash->{$header}}[0];
737     my $search_value = @{$msg_hash->{$search_param}}[0];
738     print "\ngot msg $header:\nserver $source has client with $search_param $search_value\n";
741 #===  FUNCTION  ================================================================
742 #         NAME:  new_ldap_config
743 #   PARAMETERS:  address - string - ip address and port of a host
744 #      RETURNS:  nothing
745 #  DESCRIPTION:  send to address the ldap configuration found for dn gotoLdapServer
746 #===============================================================================
747 sub new_ldap_config {
748         my ($address) = @_ ;
750         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address'";
751         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
753         # check hit
754         my $hit_counter = keys %{$res};
755         if( not $hit_counter == 1 ) {
756                 &main::daemon_log("ERROR: more or no hit found in known_clients_db by query by '$address'", 1);
757         }
759         my $macaddress = $res->{1}->{macaddress};
760         my $hostkey = $res->{1}->{hostkey};
762         if (not defined $macaddress) {
763                 &main::daemon_log("ERROR: no mac address found for client $address", 1);
764                 return;
765         }
767         # Build LDAP connection
768         my $ldap = Net::LDAP->new($ldap_uri);
769         if( not defined $ldap ) {
770                 &main::daemon_log("ERROR: cannot connect to ldap: $ldap_uri", 1);
771                 return;
772         } 
775         # Bind to a directory with dn and password
776         my $mesg= $ldap->bind($ldap_admin_dn, password => $ldap_admin_password);
778         # Perform search
779         $mesg = $ldap->search( base   => $ldap_base,
780                 scope  => 'sub',
781                 attrs => ['dn', 'gotoLdapServer', 'gosaUnitTag'],
782                 filter => "(&(objectClass=GOhard)(macaddress=$macaddress))");
783         #$mesg->code && die $mesg->error;
784         if($mesg->code) {
785                 &main::daemon_log($mesg->error, 1);
786                 return;
787         }
789         # Sanity check
790         if ($mesg->count != 1) {
791                 &main::daemon_log("WARNING: client mac address $macaddress not found/not unique in ldap search", 1);
792                 &main::daemon_log("\tbase: $ldap_base", 1);
793                 &main::daemon_log("\tscope: sub", 1);
794                 &main::daemon_log("\tattrs: dn, gotoLdapServer", 1);
795                 &main::daemon_log("\tfilter: (&(objectClass=GOhard)(macaddress=$macaddress))", 1);
796                 return;
797         }
799         my $entry= $mesg->entry(0);
800         my $dn= $entry->dn;
801         my @servers= $entry->get_value("gotoLdapServer");
802         my $unit_tag= $entry->get_value("gosaUnitTag");
803         my @ldap_uris;
804         my $server;
805         my $base;
807         # Do we need to look at an object class?
808         if (length(@servers) < 1){
809                 $mesg = $ldap->search( base   => $ldap_base,
810                         scope  => 'sub',
811                         attrs => ['dn', 'gotoLdapServer'],
812                         filter => "(&(objectClass=gosaGroupOfNames)(member=$dn))");
813                 #$mesg->code && die $mesg->error;
814                 if($mesg->code) {
815                         &main::daemon_log($mesg->error, 1);
816                         return;
817                 }
819                 # Sanity check
820                 if ($mesg->count != 1) {
821                         &main::daemon_log("WARNING: no LDAP information found for client mac $macaddress", 1);
822                         return;
823                 }
825                 $entry= $mesg->entry(0);
826                 $dn= $entry->dn;
827                 @servers= $entry->get_value("gotoLdapServer");
828         }
830         @servers= sort (@servers);
832         foreach $server (@servers){
833         # Conversation for backward compatibility
834         if ($server !=~ /^ldap[^:]+:\/\// ) {
835             if ($server =~ /^([^:]+):(.*)$/ ) {
836                 $server= "1:dummy:ldap://$1/$2";
837             }
838         }
840                 $base= $server;
841                 $server =~ s%^[^:]+:[^:]+:(ldap.*://[^/]+)/.*$%$1%;
842                 $base =~ s%^[^:]+:[^:]+:ldap.*://[^/]+/(.*)$%$1%;
843                 push (@ldap_uris, $server);
844         }
846         # Assemble data package
847         my %data = ( 'ldap_uri'  => \@ldap_uris, 'ldap_base' => $base,
848                 'ldap_cfg' => \@ldap_cfg, 'pam_cfg' => \@pam_cfg,'nss_cfg' => \@nss_cfg );
850         # Need to append GOto settings?
851         if (defined $goto_admin and defined $goto_secret){
852                 $data{'goto_admin'}= $goto_admin;
853                 $data{'goto_secret'}= $goto_secret;
854         }
856         # Append unit tag if needed
857         if (defined $unit_tag){
859                 # Find admin base and department name
860                 $mesg = $ldap->search( base   => $ldap_base,
861                         scope  => 'sub',
862                         attrs => ['dn', 'ou', 'FAIclass'],
863                         filter => "(&(objectClass=gosaAdministrativeUnit)(gosaUnitTag=$unit_tag))");
864                 #$mesg->code && die $mesg->error;
865                 if($mesg->code) {
866                         &main::daemon_log($mesg->error, 1);
867                         return;
868                 }
870                 # Sanity check
871                 if ($mesg->count != 1) {
872                         &main::daemon_log("WARNING: cannot find administrative unit for client with tag $unit_tag", 1);
873                         return;
874                 }
876                 $entry= $mesg->entry(0);
877                 $data{'admin_base'}= $entry->dn;
878                 $data{'department'}= $entry->get_value("ou");
880                 # Append unit Tag
881                 $data{'unit_tag'}= $unit_tag;
882         }
884         # Fill release if available
885         my $FAIclass= $entry->get_value("FAIclass");
886         if (defined $FAIclass && $FAIclass =~ /^.* :([A-Za-z0-9\/.]+).*$/) {
887                 $data{'release'}= $1;
888         }
891         # Unbind
892         $mesg = $ldap->unbind;
894         # Send information
895         return &build_msg("new_ldap_config", $server_address, $address, \%data);
898 #sub process_detected_hardware {
899 #       my $msg_hash = shift;
900 #       my $address = $msg_hash->{source}[0];
901 #       my $gotoHardwareChecksum= $msg_hash->{detected_hardware}[0]->{gotoHardwareChecksum};
903 #    my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address'";
904 #    my $res = $main::known_clients_db->select_dbentry( $sql_statement );
906 #    # check hit
907 #    my $hit_counter = keys %{$res};
908 #    if( not $hit_counter == 1 ) {
909 #        &main::daemon_log("ERROR: more or no hit found in known_clients_db by query by '$address'", 1);
910 #               return;
911 #    }
913 #    my $macaddress = $res->{1}->{macaddress};
914 #    my $hostkey = $res->{1}->{hostkey};
916 #    if (not defined $macaddress) {
917 #        &main::daemon_log("ERROR: no mac address found for client $address", 1);
918 #        return;
919 #    }
920 #    # Build LDAP connection
921 #    my $ldap = Net::LDAP->new($ldap_uri);
922 #    if( not defined $ldap ) {
923 #        &main::daemon_log("ERROR: cannot connect to ldap: $ldap_uri", 1);
924 #        return;
925 #    } 
927 #    # Bind to a directory with dn and password
928 #    my $mesg= $ldap->bind($ldap_admin_dn, password => $ldap_admin_password);
930 #    # Perform search
931 #       $mesg = $ldap->search(
932 #               base   => $ldap_base,
933 #               scope  => 'sub',
934 #               filter => "(&(objectClass=GOhard)(|(macAddress=$macaddress)(dhcpHWaddress=ethernet $macaddress)))"
935 #       );
937 #       # We need to create a base entry first (if not done from ArpHandler)
938 #       if($mesg->count == 0) {
939 #               &main::daemon_log("Need to create a new LDAP Entry for client $address", 1);
940 #               my $resolver=Net::DNS::Resolver->new;
941 #               my $ipaddress= $1 if $address =~ /^([0-9\.]*?):.*$/;
942 #               my $dnsresult= $resolver->search($ipaddress);
943 #               my $dnsname= (defined($dnsresult))?$dnsresult->{answer}[0]->{ptrdname}:$ipaddress;
944 #               my $cn = (($dnsname =~ /^(\d){1,3}\.(\d){1,3}\.(\d){1,3}\.(\d){1,3}/) ? $dnsname : sprintf "%s", $dnsname =~ /([^\.]+)\.?/);
945 #               my $dn = "cn=$cn,ou=incoming,$ldap_base";
946 #               &main::daemon_log("Creating entry for $dn",6);
947 #               my $entry= Net::LDAP::Entry->new( $dn );
948 #               $entry->dn($dn);
949 #               $entry->add("objectClass" => "goHard");
950 #               $entry->add("cn" => $cn);
951 #               $entry->add("macAddress" => $macaddress);
952 #               $entry->add("gotomode" => "locked");
953 #               $entry->add("gotoSysStatus" => "new-system");
954 #               $entry->add("ipHostNumber" => $ipaddress);
955 #               if(defined($main::gosa_unit_tag) && length($main::gosa_unit_tag) > 0) {
956 #                       $entry->add("objectClass" => "gosaAdministrativeUnit");
957 #                       $entry->add("gosaUnitTag" => $main::gosa_unit_tag);
958 #               }
959 #               my $res=$entry->update($ldap);
960 #               if(defined($res->{'errorMessage'}) &&
961 #                       length($res->{'errorMessage'}) >0) {
962 #                       &main::daemon_log("There was a problem adding the entries to LDAP:", 1);
963 #                       &main::daemon_log($res->{'errorMessage'}, 1);
964 #                       return;
965 #               } else {
966 #                       # Fill $mesg again
967 #                       $mesg = $ldap->search(
968 #                               base   => $ldap_base,
969 #                               scope  => 'sub',
970 #                               filter => "(&(objectClass=GOhard)(|(macAddress=$macaddress)(dhcpHWaddress=ethernet $macaddress)))"
971 #                       );
972 #               }
973 #       }
974 #       
975 #       if($mesg->count == 1) {
976 #               my $entry= $mesg->entry(0);
977 #               $entry->changetype("modify");
978 #               foreach my $attribute (
979 #                       "gotoSndModule", "ghNetNic", "gotoXResolution", "ghSoundAdapter", "ghCpuType", "gotoXkbModel", 
980 #                       "ghGfxAdapter", "gotoXMousePort", "ghMemSize", "gotoXMouseType", "ghUsbSupport", "gotoXHsync", 
981 #                       "gotoXDriver", "gotoXVsync", "gotoXMonitor", "gotoHardwareChecksum") {
982 #                       if(defined($msg_hash->{detected_hardware}[0]->{$attribute}) &&
983 #                               length($msg_hash->{detected_hardware}[0]->{$attribute}) >0 ) {
984 #                               if(defined($entry->get_value($attribute))) {
985 #                                       $entry->delete($attribute);
986 #                               }
987 #                               &main::daemon_log("Adding attribute $attribute with value ".$msg_hash->{detected_hardware}[0]->{$attribute},1);
988 #                               $entry->add($attribute => $msg_hash->{detected_hardware}[0]->{$attribute});     
989 #                       }
990 #               }
991 #               foreach my $attribute (
992 #                       "gotoModules", "ghScsiDev", "ghIdeDev") {
993 #                       if(defined($msg_hash->{detected_hardware}[0]->{$attribute}) &&
994 #                               length($msg_hash->{detected_hardware}[0]->{$attribute}) >0 ) {
995 #                               if(defined($entry->get_value($attribute))) {
996 #                                       $entry->delete($attribute);
997 #                               }
998 #                               foreach my $array_entry (@{$msg_hash->{detected_hardware}[0]->{$attribute}}) {
999 #                                       $entry->add($attribute => $array_entry);
1000 #                               }
1001 #                       }
1002 #               }
1004 #               my $res=$entry->update($ldap);
1005 #               if(defined($res->{'errorMessage'}) &&
1006 #                       length($res->{'errorMessage'}) >0) {
1007 #                       &main::daemon_log("There was a problem adding the entries to LDAP:", 1);
1008 #                       &main::daemon_log($res->{'errorMessage'}, 1);
1009 #               } else {
1010 #                       &main::daemon_log("Added Hardware configuration to LDAP", 4);
1011 #               }
1013 #       }
1014 #       return;
1015 #}
1016 #===  FUNCTION  ================================================================
1017 #         NAME:  hardware_config
1018 #   PARAMETERS:  address - string - ip address and port of a host
1019 #      RETURNS:  
1020 #  DESCRIPTION:  
1021 #===============================================================================
1022 sub hardware_config {
1023         my ($address, $gotoHardwareChecksum) = @_ ;
1025         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address'";
1026         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
1028         # check hit
1029         my $hit_counter = keys %{$res};
1030         if( not $hit_counter == 1 ) {
1031                 &main::daemon_log("ERROR: more or no hit found in known_clients_db by query by '$address'", 1);
1032         }
1034         my $macaddress = $res->{1}->{macaddress};
1035         my $hostkey = $res->{1}->{hostkey};
1037         if (not defined $macaddress) {
1038                 &main::daemon_log("ERROR: no mac address found for client $address", 1);
1039                 return;
1040         }
1042         # Build LDAP connection
1043         my $ldap = Net::LDAP->new($ldap_uri);
1044         if( not defined $ldap ) {
1045                 &main::daemon_log("ERROR: cannot connect to ldap: $ldap_uri", 1);
1046                 return;
1047         } 
1049         # Bind to a directory with dn and password
1050         my $mesg= $ldap->bind($ldap_admin_dn, password => $ldap_admin_password);
1052         # Perform search
1053         $mesg = $ldap->search(
1054                 base   => $ldap_base,
1055                 scope  => 'sub',
1056                 filter => "(&(objectClass=GOhard)(|(macAddress=$macaddress)(dhcpHWaddress=ethernet $macaddress)))"
1057         );
1059         if($mesg->count() == 0) {
1060                 &main::daemon_log("Host was not found in LDAP!", 1);
1061         } else {
1062                 my $entry= $mesg->entry(0);
1063                 my $dn= $entry->dn;
1064                 if(defined($entry->get_value("gotoHardwareChecksum"))) {
1065                         if(! $entry->get_value("gotoHardwareChecksum") eq $gotoHardwareChecksum) {
1066                                 $entry->replace(gotoHardwareChecksum => $gotoHardwareChecksum);
1067                                 if($entry->update($ldap)) {
1068                                         &main::daemon_log("Hardware changed! Detection triggered.", 4);
1069                                 }
1070                         } else {
1071                                 # Nothing to do
1072                                 return;
1073                         }
1074                 }
1075         } 
1076         # need to fill it to LDAP
1077         #$entry->add(gotoHardwareChecksum => $gotoHardwareChecksum);
1078         #if($entry->update($ldap)) {
1079         #               &main::daemon_log("gotoHardwareChecksum $gotoHardwareChecksum was added to LDAP", 4);
1080         #}
1082         ## Look if there another host with this checksum to use the hardware config
1083         #$mesg = $ldap->search(
1084         #       base   => $ldap_base,
1085         #       scope  => 'sub',
1086         #       filter => "(&(objectClass=GOhard)(gotoHardwareChecksum=$gotoHardwareChecksum))"
1087         #);
1089         #if($mesg->count>1) {
1090         #       my $clone_entry= $mesg->entry(0);
1091         #       $entry->changetype("modify");
1092         #       foreach my $attribute (
1093         #               "gotoSndModule", "ghNetNic", "gotoXResolution", "ghSoundAdapter", "ghCpuType", "gotoXkbModel", 
1094         #               "ghGfxAdapter", "gotoXMousePort", "ghMemSize", "gotoXMouseType", "ghUsbSupport", "gotoXHsync", 
1095         #               "gotoXDriver", "gotoXVsync", "gotoXMonitor") {
1096         #               my $value= $clone_entry->get_value($attribute);
1097         #               if(defined($value)) {
1098         #                       if(defined($entry->get_value($attribute))) {
1099         #                               $entry->delete($attribute);
1100         #                       }
1101         #                       &main::daemon_log("Adding attribute $attribute with value $value",1);
1102         #                       $entry->add($attribute => $value);
1103         #               }
1104         #       }
1105         #       foreach my $attribute (
1106         #               "gotoModules", "ghScsiDev", "ghIdeDev") {
1107         #               my $array= $clone_entry->get_value($attribute, 'as_ref' => 1);
1108         #               if(defined($array))     {
1109         #                       if(defined($entry->get_value($attribute))) {
1110         #                               $entry->delete($attribute);
1111         #                       }
1112         #                       foreach my $array_entry (@{$array}) {
1113         #                               $entry->add($attribute => $array_entry);
1114         #                       }
1115         #               }
1117         #       }
1118         #       if($entry->update($ldap)) {
1119         #               &main::daemon_log("Added Hardware configuration to LDAP", 4);
1120         #       }
1122         #}
1125         # Assemble data package
1126         my %data = ();
1128         # Need to append GOto settings?
1129         if (defined $goto_admin and defined $goto_secret){
1130                 $data{'goto_admin'}= $goto_admin;
1131                 $data{'goto_secret'}= $goto_secret;
1132         }
1134         # Unbind
1135         $mesg = $ldap->unbind;
1137         &main::daemon_log("Send detect_hardware message to $address", 4);
1139         # Send information
1140         return &build_msg("detect_hardware", $server_address, $address, \%data);
1143 sub server_matches {
1144         my $target = shift;
1145         my $target_ip = sprintf("%s", $target =~ /^([0-9\.]*?):.*$/);
1146         my $result = 0;
1148         if($server_ip eq $target_ip) {
1149                 $result= 1;
1150         } elsif ($server_ip eq "0.0.0.0") {     
1151                 if ($target_ip eq "127.0.0.1") {
1152                         $result= 1;
1153                 } else {
1154                         my $PROC_NET_ROUTE= ('/proc/net/route');
1156                         open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
1157                                 or die "Could not open $PROC_NET_ROUTE";
1159                         my @ifs = <PROC_NET_ROUTE>;
1161                         close(PROC_NET_ROUTE);
1163                         # Eat header line
1164                         shift @ifs;
1165                         chomp @ifs;
1166                         foreach my $line(@ifs) {
1167                                 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
1168                                 my $destination;
1169                                 my $mask;
1170                                 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
1171                                 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
1172                                 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
1173                                 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
1174                                 if(new NetAddr::IP($target_ip)->within(new NetAddr::IP($destination, $mask))) {
1175                                         # destination matches route, save mac and exit
1176                                         $result= 1;
1177                                         last;
1178                                 }
1179                         }
1180                 }
1181         } else {
1182                 &main::daemon_log("Target ip $target_ip does not match Server ip $server_ip",1);
1183         }
1185         return $result;
1189 ##===  FUNCTION  ================================================================
1190 ##         NAME:  execute_actions
1191 ##   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
1192 ##      RETURNS:  nothing
1193 ##  DESCRIPTION:  invokes the script specified in msg_hash which is located under
1194 ##                /etc/gosad/actions
1195 ##===============================================================================
1196 #sub execute_actions {
1197 #    my ($msg_hash) = @_ ;
1198 #    my $configdir= '/etc/gosad/actions/';
1199 #    my $result;
1201 #    my $header = @{$msg_hash->{header}}[0];
1202 #    my $source = @{$msg_hash->{source}}[0];
1203 #    my $target = @{$msg_hash->{target}}[0];
1204
1205 #    if((not defined $source)
1206 #            && (not defined $target)
1207 #            && (not defined $header)) {
1208 #        &main::daemon_log("ERROR: Entries missing in XML msg for gosad actions under /etc/gosad/actions");
1209 #    } else {
1210 #        my $parameters="";
1211 #        my @params = @{$msg_hash->{$header}};
1212 #        my $params = join(", ", @params);
1213 #        &main::daemon_log("execute_actions: got parameters: $params", 5);
1215 #        if (@params) {
1216 #            foreach my $param (@params) {
1217 #                my $param_value = (&get_content_from_xml_hash($msg_hash, $param))[0];
1218 #                &main::daemon_log("execute_actions: parameter -> value: $param -> $param_value", 7);
1219 #                $parameters.= " ".$param_value;
1220 #            }
1221 #        }
1223 #        my $cmd= $configdir.$header."$parameters";
1224 #        &main::daemon_log("execute_actions: executing cmd: $cmd", 7);
1225 #        $result= "";
1226 #        open(PIPE, "$cmd 2>&1 |");
1227 #        while(<PIPE>) {
1228 #            $result.=$_;
1229 #        }
1230 #        close(PIPE);
1231 #    }
1233 #    # process the event result
1236 #    return;
1237 #}
1240 1;