Code

better log messages
[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();
63 # if server_ip is not an ip address but a name
64 if( inet_aton($server_ip) ){ $server_ip = inet_ntoa(inet_aton($server_ip)); } 
65 $network_interface= &get_interface_for_ip($server_ip);
66 $server_mac_address= &get_mac($network_interface);
68 &import_events();
70 # Unit tag can be defined in config
71 if((not defined($main::gosa_unit_tag)) || length($main::gosa_unit_tag) == 0) {
72         # Read gosaUnitTag from LDAP
73         my $tmp_ldap= Net::LDAP->new($ldap_uri);
74         if( defined($tmp_ldap) ) {
75                 &main::daemon_log("INFO: Searching for servers gosaUnitTag with mac address $server_mac_address",5);
76                 my $mesg= $tmp_ldap->bind($ldap_admin_dn, password => $ldap_admin_password);
77                 # Perform search for Unit Tag
78                 $mesg = $tmp_ldap->search(
79                         base   => $ldap_base,
80                         scope  => 'sub',
81                         attrs  => ['gosaUnitTag'],
82                         filter => "(macaddress=$server_mac_address)"
83                 );
85                 if ($mesg->count == 1) {
86                         my $entry= $mesg->entry(0);
87                         my $unit_tag= $entry->get_value("gosaUnitTag");
88                         if(defined($unit_tag) && length($unit_tag) > 0) {
89                                 &main::daemon_log("INFO: Detected gosaUnitTag $unit_tag for creating entries", 5);
90                                 $main::gosa_unit_tag= $unit_tag;
91                         }
92                 } else {
93                         # Perform another search for Unit Tag
94                         my $hostname= `hostname -f`;
95                         chomp($hostname);
96                         &main::daemon_log("INFO: Searching for servers gosaUnitTag with hostname $hostname",5);
97                         $mesg = $tmp_ldap->search(
98                                 base   => $ldap_base,
99                                 scope  => 'sub',
100                                 attrs  => ['gosaUnitTag'],
101                                 filter => "(&(cn=$hostname)(objectClass=goServer))"
102                         );
103                         if ($mesg->count == 1) {
104                                 my $entry= $mesg->entry(0);
105                                 my $unit_tag= $entry->get_value("gosaUnitTag");
106                                 if(defined($unit_tag) && length($unit_tag) > 0) {
107                                         &main::daemon_log("INFO: Detected gosaUnitTag $unit_tag for creating entries", 5);
108                                         $main::gosa_unit_tag= $unit_tag;
109                                 }
110                         } else {
111                                 # Perform another search for Unit Tag
112                                 $hostname= `hostname -s`;
113                                 chomp($hostname);
114                                 &main::daemon_log("INFO: Searching for servers gosaUnitTag with hostname $hostname",5);
115                                 $mesg = $tmp_ldap->search(
116                                         base   => $ldap_base,
117                                         scope  => 'sub',
118                                         attrs  => ['gosaUnitTag'],
119                                         filter => "(&(cn=$hostname)(objectClass=goServer))"
120                                 );
121                                 if ($mesg->count == 1) {
122                                         my $entry= $mesg->entry(0);
123                                         my $unit_tag= $entry->get_value("gosaUnitTag");
124                                         if(defined($unit_tag) && length($unit_tag) > 0) {
125                                                 &main::daemon_log("INFO: Detected gosaUnitTag $unit_tag for creating entries", 5);
126                                                 $main::gosa_unit_tag= $unit_tag;
127                                         }
128                                 } else {
129                                         &main::daemon_log("WARNING: No gosaUnitTag detected. Not using gosaUnitTag", 3);
130                                 }
131                         }
132                 }
133         $tmp_ldap->unbind;
134         } else {
135                 &main::daemon_log("INFO: Using gosaUnitTag from config-file: $main::gosa_unit_tag",5);
136         }
140 my $server_address = "$server_ip:$server_port";
141 $main::server_address = $server_address;
144 if( inet_aton($bus_ip) ){ $bus_ip = inet_ntoa(inet_aton($bus_ip)); } 
145 ######################################################
146 # to change
147 if( $bus_ip eq "127.0.1.1" ) { $bus_ip = "127.0.0.1" }
148 ######################################################
149 my $bus_address = "$bus_ip:$bus_port";
150 $main::bus_address = $bus_address;
152 # create general settings for this module
153 my $xml = new XML::Simple();
155 # register at bus
156 if ($main::no_bus > 0) {
157     $bus_activ = "off"
159 if($bus_activ eq "on") {
160     &register_at_bus();
163 # add myself to known_server_db
164 my $res = $main::known_server_db->add_dbentry( {table=>'known_server',
165         primkey=>'hostname',
166         hostname=>$server_address,
167         status=>'myself',
168         hostkey=>$SIPackages_key,
169         timestamp=>&get_time,
170         } );
174 ### functions #################################################################
177 sub get_module_info {
178     my @info = ($server_address,
179                 $SIPackages_key,
180                 );
181     return \@info;
185 #sub daemon_log {
186 #    my ($msg, $level) = @_ ;
187 #    &main::daemon_log($msg, $level);
188 #    return;
189 #}
192 #sub do_wake {
193 #        my $host    = shift;
194 #        my $ipaddr  = shift || '255.255.255.255';
195 #        my $port    = getservbyname('discard', 'udp');
197 #        my ($raddr, $them, $proto);
198 #        my ($hwaddr, $hwaddr_re, $pkt);
200 #        # get the hardware address (ethernet address)
202 #        $hwaddr_re = join(':', ('[0-9A-Fa-f]{1,2}') x 6);
203 #        if ($host =~ m/^$hwaddr_re$/) {
204 #                $hwaddr = $host;
205 #        } else {
206 #                # $host is not a hardware address, try to resolve it
207 #                my $ip_re = join('\.', ('([0-9]|[1-9][0-9]|1[0-9]{2}|2([0-4][0-9]|5[0-5]))') x 4);
208 #                my $ip_addr;
209 #                if ($host =~ m/^$ip_re$/) {
210 #                        $ip_addr = $host;
211 #                } else {
212 #                        my $h;
213 #                        unless ($h = gethost($host)) {
214 #                                return undef;
215 #                        }
216 #                        $ip_addr = inet_ntoa($h->addr);
217 #                }
218 #        }
220 #        # Generate magic sequence
221 #        foreach (split /:/, $hwaddr) {
222 #                $pkt .= chr(hex($_));
223 #        }
224 #        $pkt = chr(0xFF) x 6 . $pkt x 16;
226 #        # Allocate socket and send packet
228 #        $raddr = gethostbyname($ipaddr)->addr;
229 #        $them = pack_sockaddr_in($port, $raddr);
230 #        $proto = getprotobyname('udp');
232 #        socket(S, AF_INET, SOCK_DGRAM, $proto) or die "socket : $!";
233 #        setsockopt(S, SOL_SOCKET, SO_BROADCAST, 1) or die "setsockopt : $!";
235 #        send(S, $pkt, 0, $them) or die "send : $!";
236 #        close S;
237 #}
240 #===  FUNCTION  ================================================================
241 #         NAME:  read_configfile
242 #   PARAMETERS:  cfg_file - string -
243 #      RETURNS:  nothing
244 #  DESCRIPTION:  read cfg_file and set variables
245 #===============================================================================
246 sub read_configfile {
247     my $cfg;
248     if( defined( $main::cfg_file) && ( length($main::cfg_file) > 0 )) {
249         if( -r $main::cfg_file ) {
250             $cfg = Config::IniFiles->new( -file => $main::cfg_file );
251         } else {
252             print STDERR "Couldn't read config file!";
253         }
254     } else {
255         $cfg = Config::IniFiles->new() ;
256     }
257     foreach my $section (keys %cfg_defaults) {
258         foreach my $param (keys %{$cfg_defaults{ $section }}) {
259             my $pinfo = $cfg_defaults{ $section }{ $param };
260             ${@$pinfo[0]} = $cfg->val( $section, $param, @$pinfo[1] );
261         }
262     }
264     # Read non predefined sections
265     my $param;
266     if ($cfg->SectionExists('ldap')){
267                 foreach $param ($cfg->Parameters('ldap')){
268                         push (@ldap_cfg, "$param ".$cfg->val('ldap', $param));
269                 }
270     }
271     if ($cfg->SectionExists('pam_ldap')){
272                 foreach $param ($cfg->Parameters('pam_ldap')){
273                         push (@pam_cfg, "$param ".$cfg->val('pam_ldap', $param));
274                 }
275     }
276     if ($cfg->SectionExists('nss_ldap')){
277                 foreach $param ($cfg->Parameters('nss_ldap')){
278                         push (@nss_cfg, "$param ".$cfg->val('nss_ldap', $param));
279                 }
280     }
281     if ($cfg->SectionExists('goto')){
282         $goto_admin= $cfg->val('goto', 'terminal_admin');
283         $goto_secret= $cfg->val('goto', 'terminal_secret');
284     } else {
285         $goto_admin= undef;
286         $goto_secret= undef;
287     }
291 #===  FUNCTION  ================================================================
292 #         NAME:  get_interface_for_ip
293 #   PARAMETERS:  ip address (i.e. 192.168.0.1)
294 #      RETURNS:  array: list of interfaces if ip=0.0.0.0, matching interface if found, undef else
295 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
296 #===============================================================================
297 sub get_interface_for_ip {
298         my $result;
299         my $ip= shift;
300         if ($ip && length($ip) > 0) {
301                 my @ifs= &get_interfaces();
302                 if($ip eq "0.0.0.0") {
303                         $result = "all";
304                 } else {
305                         foreach (@ifs) {
306                                 my $if=$_;
307                                 if(get_ip($if) eq $ip) {
308                                         $result = $if;
309                                 }
310                         }       
311                 }
312         }       
313         return $result;
316 #===  FUNCTION  ================================================================
317 #         NAME:  get_interfaces 
318 #   PARAMETERS:  none
319 #      RETURNS:  (list of interfaces) 
320 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
321 #===============================================================================
322 sub get_interfaces {
323         my @result;
324         my $PROC_NET_DEV= ('/proc/net/dev');
326         open(PROC_NET_DEV, "<$PROC_NET_DEV")
327                 or die "Could not open $PROC_NET_DEV";
329         my @ifs = <PROC_NET_DEV>;
331         close(PROC_NET_DEV);
333         # Eat first two line
334         shift @ifs;
335         shift @ifs;
337         chomp @ifs;
338         foreach my $line(@ifs) {
339                 my $if= (split /:/, $line)[0];
340                 $if =~ s/^\s+//;
341                 push @result, $if;
342         }
344         return @result;
347 #===  FUNCTION  ================================================================
348 #         NAME:  get_mac 
349 #   PARAMETERS:  interface name (i.e. eth0)
350 #      RETURNS:  (mac address) 
351 #  DESCRIPTION:  Uses ioctl to get mac address directly from system.
352 #===============================================================================
353 sub get_mac {
354         my $ifreq= shift;
355         my $result;
356         if ($ifreq && length($ifreq) > 0) { 
357                 if($ifreq eq "all") {
358                         $result = "00:00:00:00:00:00";
359                 } else {
360                         my $SIOCGIFHWADDR= 0x8927;     # man 2 ioctl_list
362                         # A configured MAC Address should always override a guessed value
363                         if ($server_mac_address and length($server_mac_address) > 0) {
364                                 $result= $server_mac_address;
365                         }
367                         socket SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('ip')
368                                 or die "socket: $!";
370                         if(ioctl SOCKET, $SIOCGIFHWADDR, $ifreq) {
371                                 my ($if, $mac)= unpack 'h36 H12', $ifreq;
373                                 if (length($mac) > 0) {
374                                         $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])$/;
375                                         $mac= sprintf("%s:%s:%s:%s:%s:%s", $1, $2, $3, $4, $5, $6);
376                                         $result = $mac;
377                                 }
378                         }
379                 }
380         }
381         return $result;
385 #===  FUNCTION  ================================================================
386 #         NAME:  register_at_bus
387 #   PARAMETERS:  nothing
388 #      RETURNS:  nothing
389 #  DESCRIPTION:  creates an entry in known_daemons and send a 'here_i_am' msg to bus
390 #===============================================================================
391 sub register_at_bus {
393     # add bus to known_server_db
394     my $res = $main::known_server_db->add_dbentry( {table=>'known_server',
395                                                     primkey=>'hostname',
396                                                     hostname=>$bus_address,
397                                                     status=>'bus',
398                                                     hostkey=>$bus_key,
399                                                     timestamp=>&get_time,
400                                                 } );
401     my $msg_hash = &create_xml_hash("here_i_am", $server_address, $bus_address);
402     my $msg = &create_xml_string($msg_hash);
404     &main::send_msg_to_target($msg, $bus_address, $bus_key, "here_i_am");
405     return $msg;
409 sub import_events {
410     if (not -e $event_dir) {
411         &main::daemon_log("ERROR: cannot find directory or directory is not readable: $event_dir", 1);   
412     }
413     opendir (DIR, $event_dir) or die "ERROR while loading gosa-si-events from directory $event_dir : $!\n";
415     while (defined (my $event = readdir (DIR))) {
416         if( $event eq "." || $event eq ".." ) { next; }  
417         if( $event eq "gosaTriggered.pm" ) { next; }    # only GOsa specific events
419         eval{ require $event; };
420         if( $@ ) {
421             &main::daemon_log("import of event module '$event' failed", 1);
422             &main::daemon_log("$@", 8);
423             next;
424         }
426         $event =~ /(\S*?).pm$/;
427         my $event_module = $1;
428         my $events_l = eval( $1."::get_events()") ;
429         foreach my $event_name (@{$events_l}) {
430             $event_hash->{$event_name} = $event_module;
431         }
432         my $events_string = join( ", ", @{$events_l});
433         &main::daemon_log("INFO: SIPackages imported events $events_string", 5);
434     }
438 #===  FUNCTION  ================================================================
439 #         NAME:  process_incoming_msg
440 #   PARAMETERS:  crypted_msg - string - incoming crypted message
441 #      RETURNS:  nothing
442 #  DESCRIPTION:  handels the proceeded distribution to the appropriated functions
443 #===============================================================================
444 sub process_incoming_msg {
445     my ($msg, $msg_hash, $session_id) = @_ ;
446     my $error = 0;
447     my $host_name;
448     my $host_key;
449     my @out_msg_l = ();
451     # process incoming msg
452     my $header = @{$msg_hash->{header}}[0]; 
453     my @target_l = @{$msg_hash->{target}};
455     # skip PREFIX
456     $header =~ s/^CLMSG_//;
458     &main::daemon_log("DEBUG: SIPackages: msg to process: $header", 7);
459     &main::daemon_log("$msg", 8);
461     if( 0 == length @target_l){     
462         &main::daemon_log("ERROR: no target specified for msg $header", 1);
463         $error++;
464     }
466     if( 1 == length @target_l) {
467         my $target = $target_l[0];
468                 if(&server_matches($target)) {
471             if ($header eq 'new_key') {
472                 @out_msg_l = &new_key($msg_hash)
473             } elsif ($header eq 'here_i_am') {
474                 @out_msg_l = &here_i_am($msg_hash)
475             } else {
476                 if( exists $event_hash->{$header} ) {
477                     # a event exists with the header as name
478                     &main::daemon_log("INFO: found event '$header' at event-module '".$event_hash->{$header}."'", 5);
479                     no strict 'refs';
480                     @out_msg_l = &{$event_hash->{$header}."::$header"}($msg, $msg_hash, $session_id);
481                 }
482             }
484             # if delivery not possible raise error and return 
485             if( not @out_msg_l ) {
486                 &main::daemon_log("WARNING: SIPackages got not answer from event handler '$header'", 3);
487             } elsif( 0 == @out_msg_l) {
488                 &main::daemon_log("ERROR: SIPackages: no event handler or core function defined for '$header'", 1);
489             } 
490         }
491                 else {
492                         &main::daemon_log("INFO: msg is not for gosa-si-server '$server_address', deliver it to target '$target'", 5);
493                         push(@out_msg_l, $msg);
494                 }
495     }
497     return \@out_msg_l;
501 #===  FUNCTION  ================================================================
502 #         NAME:  got_ping
503 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
504 #      RETURNS:  nothing
505 #  DESCRIPTION:  process this incoming message
506 #===============================================================================
507 #sub got_ping {
508 #    my ($msg_hash) = @_;
510 #    my $source = @{$msg_hash->{source}}[0];
511 #    my $target = @{$msg_hash->{target}}[0];
512 #    my $header = @{$msg_hash->{header}}[0];
513 #    my $session_id = @{$msg_hash->{'session_id'}}[0];
514 #    my $act_time = &get_time;
515 #    my @out_msg_l;
516 #    my $out_msg;
518 #    # check known_clients_db
519 #    my $sql_statement = "SELECT * FROM known_clients WHERE hostname='$source'";
520 #    my $query_res = $main::known_clients_db->select_dbentry( $sql_statement );
521 #    if( 1 == keys %{$query_res} ) {
522 #         my $sql_statement= "UPDATE known_clients ".
523 #            "SET status='$header', timestamp='$act_time' ".
524 #            "WHERE hostname='$source'";
525 #         my $res = $main::known_clients_db->update_dbentry( $sql_statement );
526 #    } 
527 #    
528 #    # check known_server_db
529 #    $sql_statement = "SELECT * FROM known_server WHERE hostname='$source'";
530 #    $query_res = $main::known_server_db->select_dbentry( $sql_statement );
531 #    if( 1 == keys %{$query_res} ) {
532 #         my $sql_statement= "UPDATE known_server ".
533 #            "SET status='$header', timestamp='$act_time' ".
534 #            "WHERE hostname='$source'";
535 #         my $res = $main::known_server_db->update_dbentry( $sql_statement );
536 #    } 
538 #    # create out_msg
539 #    my $out_hash = &create_xml_hash($header, $source, "GOSA");
540 #    &add_content2xml_hash($out_hash, "session_id", $session_id);
541 #    $out_msg = &create_xml_string($out_hash);
542 #    push(@out_msg_l, $out_msg);
543 #    
544 #    return @out_msg_l;
545 #}
547 #===  FUNCTION  ================================================================
548 #         NAME:  new_passwd
549 #   PARAMETERS:  msg_hash - ref - hash from function create_xml_hash
550 #      RETURNS:  nothing
551 #  DESCRIPTION:  process this incoming message
552 #===============================================================================
553 sub new_key {
554     my ($msg_hash) = @_;
555     my @out_msg_l;
556     
557     my $header = @{$msg_hash->{header}}[0];
558     my $source_name = @{$msg_hash->{source}}[0];
559     my $source_key = @{$msg_hash->{new_key}}[0];
560     my $query_res;
562     # check known_clients_db
563     my $sql_statement = "SELECT * FROM known_clients WHERE hostname='$source_name'";
564     $query_res = $main::known_clients_db->select_dbentry( $sql_statement );
565     if( 1 == keys %{$query_res} ) {
566         my $act_time = &get_time;
567         my $sql_statement= "UPDATE known_clients ".
568             "SET hostkey='$source_key', timestamp='$act_time' ".
569             "WHERE hostname='$source_name'";
570         my $res = $main::known_clients_db->update_dbentry( $sql_statement );
571         my $hash = &create_xml_hash("confirm_new_key", $server_address, $source_name);
572         my $out_msg = &create_xml_string($hash);
573         push(@out_msg_l, $out_msg);
574     }
576     # only do if host still not found
577     if( 0 == @out_msg_l ) {
578         # check known_server_db
579         $sql_statement = "SELECT * FROM known_server WHERE hostname='$source_name'";
580         $query_res = $main::known_server_db->select_dbentry( $sql_statement );
581         if( 1 == keys %{$query_res} ) {
582             my $act_time = &get_time;
583             my $sql_statement= "UPDATE known_server ".
584                 "SET hostkey='$source_key', timestamp='$act_time' ".
585                 "WHERE hostname='$source_name'";
586             my $res = $main::known_server_db->update_dbentry( $sql_statement );
588             my $hash = &create_xml_hash("confirm_new_key", $server_address, $source_name);
589             my $out_msg = &create_xml_string($hash);
590             push(@out_msg_l, $out_msg);
591         }
592     }
594     return @out_msg_l;
598 #===  FUNCTION  ================================================================
599 #         NAME:  here_i_am
600 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
601 #      RETURNS:  nothing
602 #  DESCRIPTION:  process this incoming message
603 #===============================================================================
604 sub here_i_am {
605     my ($msg_hash) = @_;
606     my @out_msg_l;
607     my $out_hash;
609     my $source = @{$msg_hash->{source}}[0];
610     my $mac_address = @{$msg_hash->{mac_address}}[0];
611         my $gotoHardwareChecksum = @{$msg_hash->{gotoHardwareChecksum}}[0];
613     # number of known clients
614     my $nu_clients= $main::known_clients_db->count_dbentries('known_clients');
616     # check wether client address or mac address is already known
617     my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$source'";
618     my $db_res= $main::known_clients_db->select_dbentry( $sql_statement );
619     
620     if ( 1 == keys %{$db_res} ) {
621         &main::daemon_log("WARNING: $source is already known as a client", 1);
622         &main::daemon_log("WARNING: values for $source are being overwritten", 1);   
623         $nu_clients --;
624     }
626     # number of actual activ clients
627     my $act_nu_clients = $nu_clients;
629     &main::daemon_log("INFO: number of actual activ clients: $act_nu_clients", 5);
630     &main::daemon_log("INFO: number of maximal allowed clients: $max_clients", 5);
632     if($max_clients <= $act_nu_clients) {
633         my $out_hash = &create_xml_hash("denied", $server_address, $source);
634         &add_content2xml_hash($out_hash, "denied", "I_cannot_take_any_more_clients!");
635         my $passwd = @{$msg_hash->{new_passwd}}[0]; 
636         &send_msg_hash2address($out_hash, $source, $passwd);
637         return;
638     }
639     
640     # new client accepted
641     my $new_passwd = @{$msg_hash->{new_passwd}}[0];
643     # create entry in known_clients
644     my $events = @{$msg_hash->{events}}[0];
645     
647     # add entry to known_clients_db
648     my $act_timestamp = &get_time;
649     my $res = $main::known_clients_db->add_dbentry( {table=>'known_clients', 
650                                                 primkey=>'hostname',
651                                                 hostname=>$source,
652                                                 events=>$events,
653                                                 macaddress=>$mac_address,
654                                                 status=>'registered',
655                                                 hostkey=>$new_passwd,
656                                                 timestamp=>$act_timestamp,
657                                                 } );
659     if ($res != 0)  {
660         &main::daemon_log("ERROR: cannot add entry to known_clients: $res");
661         return;
662     }
663     
664     # return acknowledgement to client
665     $out_hash = &create_xml_hash("registered", $server_address, $source);
666     my $register_out = &create_xml_string($out_hash);
667     push(@out_msg_l, $register_out);
669     # notify registered client to bus
670     if( $bus_activ eq "on") {
671         # fetch actual bus key
672         my $sql_statement= "SELECT * FROM known_server WHERE status='bus'";
673         my $query_res = $main::known_server_db->select_dbentry( $sql_statement );
674         my $hostkey = $query_res->{1}->{'hostkey'};
676         # send update msg to bus
677         $out_hash = &create_xml_hash("new_client", $server_address, $bus_address, $source);
678         &add_content2xml_hash($out_hash, "macaddress", $mac_address);
679         &add_content2xml_hash($out_hash, "timestamp", $act_timestamp);
680         my $new_client_out = &create_xml_string($out_hash);
681         push(@out_msg_l, $new_client_out);
682         &main::daemon_log("INFO: send bus msg that client '$source' has registerd at server '$server_address'", 5);
683     }
685     # give the new client his ldap config
686     my $new_ldap_config_out = &new_ldap_config($source);
687     if( $new_ldap_config_out ) {
688         push(@out_msg_l, $new_ldap_config_out);
689     }
691         my $hardware_config_out = &hardware_config($source, $gotoHardwareChecksum);
692         if( $hardware_config_out ) {
693                 push(@out_msg_l, $hardware_config_out);
694         }
696     return @out_msg_l;
700 #===  FUNCTION  ================================================================
701 #         NAME:  who_has
702 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
703 #      RETURNS:  nothing 
704 #  DESCRIPTION:  process this incoming message
705 #===============================================================================
706 sub who_has {
707     my ($msg_hash) = @_ ;
708     my @out_msg_l;
709     
710     # what is your search pattern
711     my $search_pattern = @{$msg_hash->{who_has}}[0];
712     my $search_element = @{$msg_hash->{$search_pattern}}[0];
713     &main::daemon_log("who_has-msg looking for $search_pattern $search_element", 7);
715     # scanning known_clients for search_pattern
716     my @host_addresses = keys %$main::known_clients;
717     my $known_clients_entries = length @host_addresses;
718     my $host_address;
719     foreach my $host (@host_addresses) {
720         my $client_element = $main::known_clients->{$host}->{$search_pattern};
721         if ($search_element eq $client_element) {
722             $host_address = $host;
723             last;
724         }
725     }
726         
727     # search was successful
728     if (defined $host_address) {
729         my $source = @{$msg_hash->{source}}[0];
730         my $out_hash = &create_xml_hash("who_has_i_do", $server_address, $source, "mac_address");
731         &add_content2xml_hash($out_hash, "mac_address", $search_element);
732         my $out_msg = &create_xml_string($out_hash);
733         push(@out_msg_l, $out_msg);
734     }
735     return @out_msg_l;
739 sub who_has_i_do {
740     my ($msg_hash) = @_ ;
741     my $header = @{$msg_hash->{header}}[0];
742     my $source = @{$msg_hash->{source}}[0];
743     my $search_param = @{$msg_hash->{$header}}[0];
744     my $search_value = @{$msg_hash->{$search_param}}[0];
745     print "\ngot msg $header:\nserver $source has client with $search_param $search_value\n";
748 #===  FUNCTION  ================================================================
749 #         NAME:  new_ldap_config
750 #   PARAMETERS:  address - string - ip address and port of a host
751 #      RETURNS:  nothing
752 #  DESCRIPTION:  send to address the ldap configuration found for dn gotoLdapServer
753 #===============================================================================
754 sub new_ldap_config {
755         my ($address) = @_ ;
757         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address' OR macaddress='$address'";
758         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
760         # check hit
761         my $hit_counter = keys %{$res};
762         if( not $hit_counter == 1 ) {
763                 &main::daemon_log("ERROR: more or no hit found in known_clients_db by query by '$address'", 1);
764         }
766     $address = $res->{1}->{hostname};
767         my $macaddress = $res->{1}->{macaddress};
768         my $hostkey = $res->{1}->{hostkey};
770         if (not defined $macaddress) {
771                 &main::daemon_log("ERROR: no mac address found for client $address", 1);
772                 return;
773         }
775         # Build LDAP connection
776         my $ldap = Net::LDAP->new($ldap_uri);
777         if( not defined $ldap ) {
778                 &main::daemon_log("ERROR: cannot connect to ldap: $ldap_uri", 1);
779                 return;
780         } 
783         # Bind to a directory with dn and password
784         my $mesg= $ldap->bind($ldap_admin_dn, password => $ldap_admin_password);
786         # Perform search
787         $mesg = $ldap->search( base   => $ldap_base,
788                 scope  => 'sub',
789                 attrs => ['dn', 'gotoLdapServer', 'gosaUnitTag'],
790                 filter => "(&(objectClass=GOhard)(macaddress=$macaddress))");
791         #$mesg->code && die $mesg->error;
792         if($mesg->code) {
793                 &main::daemon_log($mesg->error, 1);
794                 return;
795         }
797         # Sanity check
798         if ($mesg->count != 1) {
799                 &main::daemon_log("WARNING: client mac address $macaddress not found/not unique in ldap search", 1);
800                 &main::daemon_log("\tbase: $ldap_base", 1);
801                 &main::daemon_log("\tscope: sub", 1);
802                 &main::daemon_log("\tattrs: dn, gotoLdapServer", 1);
803                 &main::daemon_log("\tfilter: (&(objectClass=GOhard)(macaddress=$macaddress))", 1);
804                 return;
805         }
807         my $entry= $mesg->entry(0);
808         my $dn= $entry->dn;
809         my @servers= $entry->get_value("gotoLdapServer");
810         my $unit_tag= $entry->get_value("gosaUnitTag");
811         my @ldap_uris;
812         my $server;
813         my $base;
815         # Do we need to look at an object class?
816         if (length(@servers) < 1){
817                 $mesg = $ldap->search( base   => $ldap_base,
818                         scope  => 'sub',
819                         attrs => ['dn', 'gotoLdapServer'],
820                         filter => "(&(objectClass=gosaGroupOfNames)(member=$dn))");
821                 #$mesg->code && die $mesg->error;
822                 if($mesg->code) {
823                         &main::daemon_log($mesg->error, 1);
824                         return;
825                 }
827                 # Sanity check
828                 if ($mesg->count != 1) {
829                         &main::daemon_log("WARNING: no LDAP information found for client mac $macaddress", 1);
830                         return;
831                 }
833                 $entry= $mesg->entry(0);
834                 $dn= $entry->dn;
835                 @servers= $entry->get_value("gotoLdapServer");
836         }
838         @servers= sort (@servers);
840         foreach $server (@servers){
841                 # Conversation for backward compatibility
842                 if (not $server =~ /^ldap[^:]+:\/\// ) {
843                     if ($server =~ /^([^:]+):(.*)$/ ) {
844                 $server= "1:dummy:ldap://$1/$2";
845                     }
846                 }
848                 $base= $server;
849                 $server =~ s%^[^:]+:[^:]+:(ldap.*://[^/]+)/.*$%$1%;
850                 $base =~ s%^[^:]+:[^:]+:ldap.*://[^/]+/(.*)$%$1%;
851                 push (@ldap_uris, $server);
852         }
854         # Assemble data package
855         my %data = ( 'ldap_uri'  => \@ldap_uris, 'ldap_base' => $base,
856                 'ldap_cfg' => \@ldap_cfg, 'pam_cfg' => \@pam_cfg,'nss_cfg' => \@nss_cfg );
858         # Need to append GOto settings?
859         if (defined $goto_admin and defined $goto_secret){
860                 $data{'goto_admin'}= $goto_admin;
861                 $data{'goto_secret'}= $goto_secret;
862         }
864         # Append unit tag if needed
865         if (defined $unit_tag){
867                 # Find admin base and department name
868                 $mesg = $ldap->search( base   => $ldap_base,
869                         scope  => 'sub',
870                         attrs => ['dn', 'ou', 'FAIclass'],
871                         filter => "(&(objectClass=gosaAdministrativeUnit)(gosaUnitTag=$unit_tag))");
872                 #$mesg->code && die $mesg->error;
873                 if($mesg->code) {
874                         &main::daemon_log($mesg->error, 1);
875                         return;
876                 }
878                 # Sanity check
879                 if ($mesg->count != 1) {
880                         &main::daemon_log("WARNING: cannot find administrative unit for client with tag $unit_tag", 1);
881                         return;
882                 }
884                 $entry= $mesg->entry(0);
885                 $data{'admin_base'}= $entry->dn;
886                 $data{'department'}= $entry->get_value("ou");
888                 # Append unit Tag
889                 $data{'unit_tag'}= $unit_tag;
890         }
892         # Fill release if available
893         my $FAIclass= $entry->get_value("FAIclass");
894         if (defined $FAIclass && $FAIclass =~ /^.* :([A-Za-z0-9\/.]+).*$/) {
895                 $data{'release'}= $1;
896         }
899         # Unbind
900         $mesg = $ldap->unbind;
901         if($mesg->code) {
902                 &main::daemon_log($mesg->error, 1);
903                 return;
904         }
906         # Send information
907         return &build_msg("new_ldap_config", $server_address, $address, \%data);
911 #===  FUNCTION  ================================================================
912 #         NAME:  hardware_config
913 #   PARAMETERS:  address - string - ip address and port of a host
914 #      RETURNS:  
915 #  DESCRIPTION:  
916 #===============================================================================
917 sub hardware_config {
918         my ($address, $gotoHardwareChecksum) = @_ ;
920         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address'";
921         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
923         # check hit
924         my $hit_counter = keys %{$res};
925         if( not $hit_counter == 1 ) {
926                 &main::daemon_log("ERROR: more or no hit found in known_clients_db by query by '$address'", 1);
927         }
929         my $macaddress = $res->{1}->{macaddress};
930         my $hostkey = $res->{1}->{hostkey};
932         if (not defined $macaddress) {
933                 &main::daemon_log("ERROR: no mac address found for client $address", 1);
934                 return;
935         }
937         # Build LDAP connection
938         my $ldap = Net::LDAP->new($ldap_uri);
939         if( not defined $ldap ) {
940                 &main::daemon_log("ERROR: cannot connect to ldap: $ldap_uri", 1);
941                 return;
942         } 
944         # Bind to a directory with dn and password
945         my $mesg= $ldap->bind($ldap_admin_dn, password => $ldap_admin_password);
947         # Perform search
948         $mesg = $ldap->search(
949                 base   => $ldap_base,
950                 scope  => 'sub',
951                 filter => "(&(objectClass=GOhard)(|(macAddress=$macaddress)(dhcpHWaddress=ethernet $macaddress)))"
952         );
954         if($mesg->count() == 0) {
955                 &main::daemon_log("Host was not found in LDAP!", 1);
956         } else {
957                 my $entry= $mesg->entry(0);
958                 my $dn= $entry->dn;
959                 if(defined($entry->get_value("gotoHardwareChecksum"))) {
960                         if(! $entry->get_value("gotoHardwareChecksum") eq $gotoHardwareChecksum) {
961                                 $entry->replace(gotoHardwareChecksum => $gotoHardwareChecksum);
962                                 if($entry->update($ldap)) {
963                                         &main::daemon_log("Hardware changed! Detection triggered.", 4);
964                                 }
965                         } else {
966                                 # Nothing to do
967                                 return;
968                         }
969                 }
970         } 
971         # need to fill it to LDAP
972         #$entry->add(gotoHardwareChecksum => $gotoHardwareChecksum);
973         #if($entry->update($ldap)) {
974         #               &main::daemon_log("gotoHardwareChecksum $gotoHardwareChecksum was added to LDAP", 4);
975         #}
977         ## Look if there another host with this checksum to use the hardware config
978         #$mesg = $ldap->search(
979         #       base   => $ldap_base,
980         #       scope  => 'sub',
981         #       filter => "(&(objectClass=GOhard)(gotoHardwareChecksum=$gotoHardwareChecksum))"
982         #);
984         #if($mesg->count>1) {
985         #       my $clone_entry= $mesg->entry(0);
986         #       $entry->changetype("modify");
987         #       foreach my $attribute (
988         #               "gotoSndModule", "ghNetNic", "gotoXResolution", "ghSoundAdapter", "ghCpuType", "gotoXkbModel", 
989         #               "ghGfxAdapter", "gotoXMousePort", "ghMemSize", "gotoXMouseType", "ghUsbSupport", "gotoXHsync", 
990         #               "gotoXDriver", "gotoXVsync", "gotoXMonitor") {
991         #               my $value= $clone_entry->get_value($attribute);
992         #               if(defined($value)) {
993         #                       if(defined($entry->get_value($attribute))) {
994         #                               $entry->delete($attribute);
995         #                       }
996         #                       &main::daemon_log("Adding attribute $attribute with value $value",1);
997         #                       $entry->add($attribute => $value);
998         #               }
999         #       }
1000         #       foreach my $attribute (
1001         #               "gotoModules", "ghScsiDev", "ghIdeDev") {
1002         #               my $array= $clone_entry->get_value($attribute, 'as_ref' => 1);
1003         #               if(defined($array))     {
1004         #                       if(defined($entry->get_value($attribute))) {
1005         #                               $entry->delete($attribute);
1006         #                       }
1007         #                       foreach my $array_entry (@{$array}) {
1008         #                               $entry->add($attribute => $array_entry);
1009         #                       }
1010         #               }
1012         #       }
1013         #       if($entry->update($ldap)) {
1014         #               &main::daemon_log("Added Hardware configuration to LDAP", 4);
1015         #       }
1017         #}
1020         # Assemble data package
1021         my %data = ();
1023         # Need to append GOto settings?
1024         if (defined $goto_admin and defined $goto_secret){
1025                 $data{'goto_admin'}= $goto_admin;
1026                 $data{'goto_secret'}= $goto_secret;
1027         }
1029         # Unbind
1030         $mesg = $ldap->unbind;
1032         &main::daemon_log("Send detect_hardware message to $address", 4);
1034         # Send information
1035         return &build_msg("detect_hardware", $server_address, $address, \%data);
1038 sub server_matches {
1039         my $target = shift;
1040         my $target_ip = sprintf("%s", $target =~ /^([0-9\.]*?):.*$/);
1041         my $result = 0;
1043         if($server_ip eq $target_ip) {
1044                 $result= 1;
1045         } elsif ($server_ip eq "0.0.0.0") {     
1046                 if ($target_ip eq "127.0.0.1") {
1047                         $result= 1;
1048                 } else {
1049                         my $PROC_NET_ROUTE= ('/proc/net/route');
1051                         open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
1052                                 or die "Could not open $PROC_NET_ROUTE";
1054                         my @ifs = <PROC_NET_ROUTE>;
1056                         close(PROC_NET_ROUTE);
1058                         # Eat header line
1059                         shift @ifs;
1060                         chomp @ifs;
1061                         foreach my $line(@ifs) {
1062                                 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
1063                                 my $destination;
1064                                 my $mask;
1065                                 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
1066                                 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
1067                                 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
1068                                 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
1069                                 if(new NetAddr::IP($target_ip)->within(new NetAddr::IP($destination, $mask))) {
1070                                         # destination matches route, save mac and exit
1071                                         $result= 1;
1072                                         last;
1073                                 }
1074                         }
1075                 }
1076         } else {
1077                 &main::daemon_log("Target ip $target_ip does not match Server ip $server_ip",1);
1078         }
1080         return $result;
1084 ##===  FUNCTION  ================================================================
1085 ##         NAME:  execute_actions
1086 ##   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
1087 ##      RETURNS:  nothing
1088 ##  DESCRIPTION:  invokes the script specified in msg_hash which is located under
1089 ##                /etc/gosad/actions
1090 ##===============================================================================
1091 #sub execute_actions {
1092 #    my ($msg_hash) = @_ ;
1093 #    my $configdir= '/etc/gosad/actions/';
1094 #    my $result;
1096 #    my $header = @{$msg_hash->{header}}[0];
1097 #    my $source = @{$msg_hash->{source}}[0];
1098 #    my $target = @{$msg_hash->{target}}[0];
1099
1100 #    if((not defined $source)
1101 #            && (not defined $target)
1102 #            && (not defined $header)) {
1103 #        &main::daemon_log("ERROR: Entries missing in XML msg for gosad actions under /etc/gosad/actions");
1104 #    } else {
1105 #        my $parameters="";
1106 #        my @params = @{$msg_hash->{$header}};
1107 #        my $params = join(", ", @params);
1108 #        &main::daemon_log("execute_actions: got parameters: $params", 5);
1110 #        if (@params) {
1111 #            foreach my $param (@params) {
1112 #                my $param_value = (&get_content_from_xml_hash($msg_hash, $param))[0];
1113 #                &main::daemon_log("execute_actions: parameter -> value: $param -> $param_value", 7);
1114 #                $parameters.= " ".$param_value;
1115 #            }
1116 #        }
1118 #        my $cmd= $configdir.$header."$parameters";
1119 #        &main::daemon_log("execute_actions: executing cmd: $cmd", 7);
1120 #        $result= "";
1121 #        open(PIPE, "$cmd 2>&1 |");
1122 #        while(<PIPE>) {
1123 #            $result.=$_;
1124 #        }
1125 #        close(PIPE);
1126 #    }
1128 #    # process the event result
1131 #    return;
1132 #}
1135 1;