Code

b25c44d95f4c1282f7f2f8f8857a6b9ee6d9f95d
[gosa.git] / gosa-si / modules / ClientPackages.pm
1 package ClientPackages;
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. 
8 use strict;
9 use warnings;
10 use GOSA::GosaSupportDaemon;
11 use IO::Socket::INET;
12 use XML::Simple;
13 use Data::Dumper;
14 use NetAddr::IP;
15 use Net::LDAP;
16 use Socket;
17 use Net::hostent;
19 my $event_dir = "/usr/lib/gosa-si/server/ClientPackages";
20 use lib "/usr/lib/gosa-si/server/ClientPackages";
22 BEGIN{}
23 END {}
25 my ($server_ip, $server_port, $ClientPackages_key, $max_clients, $ldap_uri, $ldap_base, $ldap_admin_dn, $ldap_admin_password, $server_interface);
26 my ($bus_activ, $bus_key, $bus_ip, $bus_port);
27 my $server;
28 my $network_interface;
29 my $no_bus;
30 my (@ldap_cfg, @pam_cfg, @nss_cfg, $goto_admin, $goto_secret);
31 my $mesg;
33 my %cfg_defaults = (
34 "bus" => {
35     "activ" => [\$bus_activ, "on"],
36     "key" => [\$bus_key, ""],
37     "ip" => [\$bus_ip, ""],
38     "port" => [\$bus_port, "20080"],
39     },
40 "server" => {
41     "ip" => [\$server_ip, "0.0.0.0"],
42     "mac-address" => [\$main::server_mac_address, "00:00:00:00:00"],
43     "port" => [\$server_port, "20081"],
44     "ldap-uri" => [\$ldap_uri, ""],
45     "ldap-base" => [\$ldap_base, ""],
46     "ldap-admin-dn" => [\$ldap_admin_dn, ""],
47     "ldap-admin-password" => [\$ldap_admin_password, ""],
48     "max-clients" => [\$max_clients, 100],
49     },
50 "ClientPackages" => {
51     "key" => [\$ClientPackages_key, ""],
52     },
53 );
55 ### START #####################################################################
57 # read configfile and import variables
58 &read_configfile();
61 # if server_ip is not an ip address but a name
62 if( inet_aton($server_ip) ){ $server_ip = inet_ntoa(inet_aton($server_ip)); } 
63 $network_interface= &get_interface_for_ip($server_ip);
64 $main::server_mac_address= &get_mac($network_interface);
67 # import local events
68 my ($error, $result, $event_hash) = &import_events($event_dir);
69 if ($error == 0) {
70     foreach my $log_line (@$result) {
71         &main::daemon_log("0 DEBUG: ClientPackages - $log_line", 7);
72     }
73 } else {
74     foreach my $log_line (@$result) {
75         &main::daemon_log("0 ERROR: ClientPackages - $log_line", 1);
76     }
78 }
80 # Unit tag can be defined in config
81 if((not defined($main::gosa_unit_tag)) || length($main::gosa_unit_tag) == 0) {
82         # Read gosaUnitTag from LDAP
83         
84     my $ldap_handle = &main::get_ldap_handle(); 
85     if( defined($ldap_handle) ) {
86                 &main::daemon_log("0 INFO: Searching for servers gosaUnitTag with mac address $main::server_mac_address",5);
87                 # Perform search for Unit Tag
88                 $mesg = $ldap_handle->search(
89                         base   => $ldap_base,
90                         scope  => 'sub',
91                         attrs  => ['gosaUnitTag'],
92                         filter => "(macaddress=$main::server_mac_address)"
93                 );
95                 if ((! $main::server_mac_address eq "00:00:00:00:00:00") and $mesg->count == 1) {
96                         my $entry= $mesg->entry(0);
97                         my $unit_tag= $entry->get_value("gosaUnitTag");
98                         $main::ldap_server_dn= $mesg->entry(0)->dn;
99                         if(defined($unit_tag) && length($unit_tag) > 0) {
100                                 &main::daemon_log("0 INFO: Detected gosaUnitTag $unit_tag for creating entries", 5);
101                                 $main::gosa_unit_tag= $unit_tag;
102                         }
103                 } else {
104                         # Perform another search for Unit Tag
105                         my $hostname= `hostname -f`;
106                         chomp($hostname);
107                         &main::daemon_log("0 INFO: Searching for servers gosaUnitTag with hostname $hostname",5);
108                         $mesg = $ldap_handle->search(
109                                 base   => $ldap_base,
110                                 scope  => 'sub',
111                                 attrs  => ['gosaUnitTag'],
112                                 filter => "(&(cn=$hostname)(objectClass=goServer))"
113                         );
114                         if ($mesg->count == 1) {
115                                 my $entry= $mesg->entry(0);
116                                 my $unit_tag= $entry->get_value("gosaUnitTag");
117                                 $main::ldap_server_dn= $mesg->entry(0)->dn;
118                                 if(defined($unit_tag) && length($unit_tag) > 0) {
119                                         &main::daemon_log("0 INFO: Detected gosaUnitTag $unit_tag for creating entries", 5);
120                                         $main::gosa_unit_tag= $unit_tag;
121                                 }
122                         } else {
123                                 # Perform another search for Unit Tag
124                                 $hostname= `hostname -s`;
125                                 chomp($hostname);
126                                 &main::daemon_log("0 INFO: Searching for servers gosaUnitTag with hostname $hostname",5);
127                                 $mesg = $ldap_handle->search(
128                                         base   => $ldap_base,
129                                         scope  => 'sub',
130                                         attrs  => ['gosaUnitTag'],
131                                         filter => "(&(cn=$hostname)(objectClass=goServer))"
132                                 );
133                                 if ($mesg->count == 1) {
134                                         my $entry= $mesg->entry(0);
135                                         my $unit_tag= $entry->get_value("gosaUnitTag");
136                                         $main::ldap_server_dn= $mesg->entry(0)->dn;
137                                         if(defined($unit_tag) && length($unit_tag) > 0) {
138                                                 &main::daemon_log("INFO: Detected gosaUnitTag $unit_tag for creating entries", 5);
139                                                 $main::gosa_unit_tag= $unit_tag;
140                                         }
141                                 } else {
142                                         &main::daemon_log("0 WARNING: No gosaUnitTag detected. Not using gosaUnitTag", 3);
143                                 }
144                         }
145                 }
146         } else {
147                 &main::daemon_log("0 INFO: Using gosaUnitTag from config-file: $main::gosa_unit_tag",5);
148         }
152 my $server_address = "$server_ip:$server_port";
153 $main::server_address = $server_address;
156 if( inet_aton($bus_ip) ){ $bus_ip = inet_ntoa(inet_aton($bus_ip)); } 
157 ######################################################
158 # to change
159 if( $bus_ip eq "127.0.1.1" ) { $bus_ip = "127.0.0.1" }
160 ######################################################
161 my $bus_address = "$bus_ip:$bus_port";
162 $main::bus_address = $bus_address;
164 # create general settings for this module
165 my $xml = new XML::Simple();
167 # register at bus
168 if ($main::no_bus > 0) {
169     $bus_activ = "off"
171 if($bus_activ eq "on") {
172     &register_at_bus();
175 # add myself to known_server_db
176 my $res = $main::known_server_db->add_dbentry( {table=>'known_server',
177         primkey=>['hostname'],
178         hostname=>$server_address,
179         status=>'myself',
180         hostkey=>$ClientPackages_key,
181         timestamp=>&get_time,
182         } );
186 ### functions #################################################################
189 sub get_module_info {
190     my @info = ($server_address,
191                 $ClientPackages_key,
192                 );
193     return \@info;
197 #===  FUNCTION  ================================================================
198 #         NAME:  read_configfile
199 #   PARAMETERS:  cfg_file - string -
200 #      RETURNS:  nothing
201 #  DESCRIPTION:  read cfg_file and set variables
202 #===============================================================================
203 sub read_configfile {
204     my $cfg;
205     if( defined( $main::cfg_file) && ( (-s $main::cfg_file) > 0 )) {
206         if( -r $main::cfg_file ) {
207             $cfg = Config::IniFiles->new( -file => $main::cfg_file );
208         } else {
209             print STDERR "Couldn't read config file!";
210         }
211     } else {
212         $cfg = Config::IniFiles->new() ;
213     }
214     foreach my $section (keys %cfg_defaults) {
215         foreach my $param (keys %{$cfg_defaults{ $section }}) {
216             my $pinfo = $cfg_defaults{ $section }{ $param };
217             ${@$pinfo[0]} = $cfg->val( $section, $param, @$pinfo[1] );
218         }
219     }
221     # Read non predefined sections
222     my $param;
223     if ($cfg->SectionExists('ldap')){
224                 foreach $param ($cfg->Parameters('ldap')){
225                         push (@ldap_cfg, "$param ".$cfg->val('ldap', $param));
226                 }
227     }
228     if ($cfg->SectionExists('pam_ldap')){
229                 foreach $param ($cfg->Parameters('pam_ldap')){
230                         push (@pam_cfg, "$param ".$cfg->val('pam_ldap', $param));
231                 }
232     }
233     if ($cfg->SectionExists('nss_ldap')){
234                 foreach $param ($cfg->Parameters('nss_ldap')){
235                         push (@nss_cfg, "$param ".$cfg->val('nss_ldap', $param));
236                 }
237     }
238     if ($cfg->SectionExists('goto')){
239         $goto_admin= $cfg->val('goto', 'terminal_admin');
240         $goto_secret= $cfg->val('goto', 'terminal_secret');
241     } else {
242         $goto_admin= undef;
243         $goto_secret= undef;
244     }
248 #===  FUNCTION  ================================================================
249 #         NAME:  get_interface_for_ip
250 #   PARAMETERS:  ip address (i.e. 192.168.0.1)
251 #      RETURNS:  array: list of interfaces if ip=0.0.0.0, matching interface if found, undef else
252 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
253 #===============================================================================
254 sub get_interface_for_ip {
255         my $result;
256         my $ip= shift;
257         if ($ip && length($ip) > 0) {
258                 my @ifs= &get_interfaces();
259                 if($ip eq "0.0.0.0") {
260                         $result = "all";
261                 } else {
262                         foreach (@ifs) {
263                                 my $if=$_;
264                                 if(&main::get_ip($if) eq $ip) {
265                                         $result = $if;
266                                 }
267                         }       
268                 }
269         }       
270         return $result;
273 #===  FUNCTION  ================================================================
274 #         NAME:  get_interfaces 
275 #   PARAMETERS:  none
276 #      RETURNS:  (list of interfaces) 
277 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
278 #===============================================================================
279 sub get_interfaces {
280         my @result;
281         my $PROC_NET_DEV= ('/proc/net/dev');
283         open(PROC_NET_DEV, "<$PROC_NET_DEV")
284                 or die "Could not open $PROC_NET_DEV";
286         my @ifs = <PROC_NET_DEV>;
288         close(PROC_NET_DEV);
290         # Eat first two line
291         shift @ifs;
292         shift @ifs;
294         chomp @ifs;
295         foreach my $line(@ifs) {
296                 my $if= (split /:/, $line)[0];
297                 $if =~ s/^\s+//;
298                 push @result, $if;
299         }
301         return @result;
304 #===  FUNCTION  ================================================================
305 #         NAME:  get_mac 
306 #   PARAMETERS:  interface name (i.e. eth0)
307 #      RETURNS:  (mac address) 
308 #  DESCRIPTION:  Uses ioctl to get mac address directly from system.
309 #===============================================================================
310 sub get_mac {
311         my $ifreq= shift;
312         my $result;
313         if ($ifreq && length($ifreq) > 0) { 
314                 if($ifreq eq "all") {
315                         $result = "00:00:00:00:00:00";
316                 } else {
317                         my $SIOCGIFHWADDR= 0x8927;     # man 2 ioctl_list
319                         # A configured MAC Address should always override a guessed value
320                         if ($main::server_mac_address and length($main::server_mac_address) > 0) {
321                                 $result= $main::server_mac_address;
322                         }
324                         socket SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('ip')
325                                 or die "socket: $!";
327                         if(ioctl SOCKET, $SIOCGIFHWADDR, $ifreq) {
328                                 my ($if, $mac)= unpack 'h36 H12', $ifreq;
330                                 if (length($mac) > 0) {
331                                         $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])$/;
332                                         $mac= sprintf("%s:%s:%s:%s:%s:%s", $1, $2, $3, $4, $5, $6);
333                                         $result = $mac;
334                                 }
335                         }
336                 }
337         }
338         return $result;
342 #===  FUNCTION  ================================================================
343 #         NAME:  register_at_bus
344 #   PARAMETERS:  nothing
345 #      RETURNS:  nothing
346 #  DESCRIPTION:  creates an entry in known_daemons and send a 'here_i_am' msg to bus
347 #===============================================================================
348 sub register_at_bus {
350     # add bus to known_server_db
351     my $res = $main::known_server_db->add_dbentry( {table=>'known_server',
352                                                     primkey=>['hostname'],
353                                                     hostname=>$bus_address,
354                                                     status=>'bus',
355                                                     hostkey=>$bus_key,
356                                                     timestamp=>&get_time,
357                                                 } );
358     my $msg_hash = &create_xml_hash("here_i_am", $server_address, $bus_address);
359     my $msg = &create_xml_string($msg_hash);
361     &main::send_msg_to_target($msg, $bus_address, $bus_key, "here_i_am");
362     return $msg;
367 # outcommented from rettenbe: moved to GosaSupportDaemon.pm
368 #sub import_events {
369 #    if (not -e $event_dir) {
370 #        &main::daemon_log("S ERROR: cannot find directory or directory is not readable: $event_dir", 1);   
371 #    }
372 #    opendir (DIR, $event_dir) or die "ERROR while loading gosa-si-events from directory $event_dir : $!\n";
374 #    while (defined (my $event = readdir (DIR))) {
375 #        if( $event eq "." || $event eq ".." ) { next; }  
376 #        if( $event eq "gosaTriggered.pm" ) { next; }    # only GOsa specific events
378 #        eval{ require $event; };
379 #        if( $@ ) {
380 #            &main::daemon_log("S ERROR: import of event module '$event' failed", 1);
381 #            &main::daemon_log("$@", 8);
382 #            next;
383 #        }
385 #        $event =~ /(\S*?).pm$/;
386 #        my $event_module = $1;
387 #        my $events_l = eval( $1."::get_events()") ;
388 #        foreach my $event_name (@{$events_l}) {
389 #            $event_hash->{$event_name} = $event_module;
390 #        }
391 #        my $events_string = join( ", ", @{$events_l});
392 #        &main::daemon_log("S DEBUG: ClientPackages imported events $events_string", 8);
393 #    }
394 #}
397 #===  FUNCTION  ================================================================
398 #         NAME:  process_incoming_msg
399 #   PARAMETERS:  crypted_msg - string - incoming crypted message
400 #      RETURNS:  nothing
401 #  DESCRIPTION:  handels the proceeded distribution to the appropriated functions
402 #===============================================================================
403 sub process_incoming_msg {
404     my ($msg, $msg_hash, $session_id) = @_ ;
405     my $error = 0;
406     my $host_name;
407     my $host_key;
408     my @out_msg_l = ("nohandler");
409     my $sql_events;
411     # process incoming msg
412     my $header = @{$msg_hash->{header}}[0]; 
413     my $source = @{$msg_hash->{source}}[0]; 
414     my @target_l = @{$msg_hash->{target}};
416     # skip PREFIX
417     $header =~ s/^CLMSG_//;
419     &main::daemon_log("$session_id DEBUG: ClientPackages: msg to process: $header", 7);
421     if( 0 == length @target_l){     
422         &main::daemon_log("$session_id ERROR: no target specified for msg $header", 1);
423         $error++;
424     }
426     if( 1 == length @target_l) {
427         my $target = $target_l[0];
428                 if(&server_matches($target)) {
429             if ($header eq 'new_key') {
430                 @out_msg_l = &new_key($msg_hash)
431             } elsif ($header eq 'here_i_am') {
432                 @out_msg_l = &here_i_am($msg, $msg_hash, $session_id)
433             } else {
434                 # a event exists with the header as name
435                 if( exists $event_hash->{$header} ) {
436                     &main::daemon_log("$session_id INFO: found event '$header' at event-module '".$event_hash->{$header}."'", 5);
437                     no strict 'refs';
438                     @out_msg_l = &{$event_hash->{$header}."::$header"}($msg, $msg_hash, $session_id);
440                 # if no event handler is implemented   
441                 } else {
442                     $sql_events = "SELECT * FROM $main::known_clients_tn WHERE ( (macaddress LIKE '$source') OR (hostname='$source') )"; 
443                     my $res = $main::known_clients_db->select_dbentry( $sql_events );
444                     my $l = keys(%$res);
446                     # set error if no or more than 1 hits are found for sql query
447                     if ( $l != 1) {
448                         @out_msg_l = ('knownclienterror');
450                     # found exact 1 hit in db
451                     } else {
452                         my $client_events = $res->{'1'}->{'events'};
454                         # client is registered for this event, deliver this message to client
455                         $header =~ s/^answer_//;
456                         if ($client_events =~ /,$header,/) {
457                             # answer message finally arrived destination server, so forward messages to GOsa
458                             if ($target eq $main::server_address) {        
459                                 $msg =~ s/<header>answer_/<header>/;
460                                 $msg =~ s/<target>\S+<\/target>/<target>GOSA<\/target>/;
461                             }
462                             @out_msg_l = ( $msg );
464                         # client is not registered for this event, set error
465                         } else {
466                             @out_msg_l = ('noeventerror');
467                         }
468                     }
469                 }
470             }
472             # if delivery not possible raise error and return 
473             if( not defined $out_msg_l[0] ) {
474                 @out_msg_l = ();
475             } elsif( $out_msg_l[0] eq 'nohandler') {
476                 &main::daemon_log("$session_id ERROR: ClientPackages: no event handler or core function defined for '$header'", 1);
477                 @out_msg_l = ();
478             }  elsif ($out_msg_l[0] eq 'knownclienterror') {
479                 &main::daemon_log("$session_id ERROR: no or more than 1 hits are found at known_clients_db with sql query: '$sql_events'", 1);
480                 &main::daemon_log("$session_id WARNING: processing is aborted and message will not be forwarded");
481                 @out_msg_l = ();
482             } elsif ($out_msg_l[0] eq 'noeventerror') {
483                 &main::daemon_log("$session_id WARNING: client '$target' is not registered for event '$header', processing is aborted", 1); 
484                 @out_msg_l = ();
485             }
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:  new_passwd
503 #   PARAMETERS:  msg_hash - ref - hash from function create_xml_hash
504 #      RETURNS:  nothing
505 #  DESCRIPTION:  process this incoming message
506 #===============================================================================
507 sub new_key {
508     my ($msg_hash) = @_;
509     my @out_msg_l;
510     
511     my $header = @{$msg_hash->{header}}[0];
512     my $source_name = @{$msg_hash->{source}}[0];
513     my $source_key = @{$msg_hash->{new_key}}[0];
514     my $query_res;
516     # check known_clients_db
517     my $sql_statement = "SELECT * FROM known_clients WHERE hostname='$source_name'";
518     $query_res = $main::known_clients_db->select_dbentry( $sql_statement );
519     if( 1 == keys %{$query_res} ) {
520         my $act_time = &get_time;
521         my $sql_statement= "UPDATE known_clients ".
522             "SET hostkey='$source_key', timestamp='$act_time' ".
523             "WHERE hostname='$source_name'";
524         my $res = $main::known_clients_db->update_dbentry( $sql_statement );
525         my $hash = &create_xml_hash("confirm_new_key", $server_address, $source_name);
526         my $out_msg = &create_xml_string($hash);
527         push(@out_msg_l, $out_msg);
528     }
530     # only do if host still not found
531     if( 0 == @out_msg_l ) {
532         # check known_server_db
533         $sql_statement = "SELECT * FROM known_server WHERE hostname='$source_name'";
534         $query_res = $main::known_server_db->select_dbentry( $sql_statement );
535         if( 1 == keys %{$query_res} ) {
536             my $act_time = &get_time;
537             my $sql_statement= "UPDATE known_server ".
538                 "SET hostkey='$source_key', timestamp='$act_time' ".
539                 "WHERE hostname='$source_name'";
540             my $res = $main::known_server_db->update_dbentry( $sql_statement );
542             my $hash = &create_xml_hash("confirm_new_key", $server_address, $source_name);
543             my $out_msg = &create_xml_string($hash);
544             push(@out_msg_l, $out_msg);
545         }
546     }
548     return @out_msg_l;
552 #===  FUNCTION  ================================================================
553 #         NAME:  here_i_am
554 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
555 #      RETURNS:  nothing
556 #  DESCRIPTION:  process this incoming message
557 #===============================================================================
558 sub here_i_am {
559     my ($msg, $msg_hash, $session_id) = @_;
560     my @out_msg_l;
561     my $out_hash;
562     my $source = @{$msg_hash->{source}}[0];
563     my $mac_address = @{$msg_hash->{mac_address}}[0];
564         my $gotoHardwareChecksum = @{$msg_hash->{gotoHardwareChecksum}}[0];
565     my $client_status = @{$msg_hash->{client_status}}[0];
566     my $client_revision = @{$msg_hash->{client_revision}}[0];
568     # number of known clients
569     my $nu_clients= $main::known_clients_db->count_dbentries('known_clients');
571     # check wether client address or mac address is already known
572     my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$source'";
573     my $db_res= $main::known_clients_db->select_dbentry( $sql_statement );
574     
575     if ( 1 == keys %{$db_res} ) {
576         &main::daemon_log("$session_id WARNING: $source is already known as a client", 1);
577         &main::daemon_log("$session_id WARNING: values for $source are being overwritten", 1);   
578         $nu_clients --;
579     }
581     # number of actual activ clients
582     my $act_nu_clients = $nu_clients;
584     &main::daemon_log("$session_id INFO: number of actual activ clients: $act_nu_clients", 5);
585     &main::daemon_log("$session_id INFO: number of maximal allowed clients: $max_clients", 5);
587     if($max_clients <= $act_nu_clients) {
588         my $out_hash = &create_xml_hash("denied", $server_address, $source);
589         &add_content2xml_hash($out_hash, "denied", "I_cannot_take_any_more_clients!");
590         my $passwd = @{$msg_hash->{new_passwd}}[0]; 
591         &send_msg_hash2address($out_hash, $source, $passwd);
592         return;
593     }
594     
595     # new client accepted
596     my $new_passwd = @{$msg_hash->{new_passwd}}[0];
598     # add entry to known_clients_db
599     my $events = @{$msg_hash->{events}}[0];
600     my $act_timestamp = &get_time;
601     my $res = $main::known_clients_db->add_dbentry( {table=>'known_clients', 
602                                                 primkey=>['hostname'],
603                                                 hostname=>$source,
604                                                 events=>$events,
605                                                 macaddress=>$mac_address,
606                                                 status=>'registered',
607                                                 hostkey=>$new_passwd,
608                                                 timestamp=>$act_timestamp,
609                                                 } );
611     if ($res != 0)  {
612         &main::daemon_log("$session_id ERROR: cannot add entry to known_clients: $res");
613         return;
614     }
615     
616     # return acknowledgement to client
617     $out_hash = &create_xml_hash("registered", $server_address, $source);
622 #    # notify registered client to all other server
623 #    if( $bus_activ eq "on") {
624 #        # fetch actual bus key
625 #        my $sql_statement= "SELECT * FROM known_server WHERE status='bus'";
626 #        my $query_res = $main::known_server_db->select_dbentry( $sql_statement );
627 #        my $hostkey = $query_res->{1}->{'hostkey'};
629 #        # send update msg to bus
630 #        $out_hash = &create_xml_hash("new_client", $server_address, $bus_address, $source);
631 #        &add_content2xml_hash($out_hash, "macaddress", $mac_address);
632 #        &add_content2xml_hash($out_hash, "timestamp", $act_timestamp);
633 #        my $new_client_out = &create_xml_string($out_hash);
634 #        push(@out_msg_l, $new_client_out);
635 #        &main::daemon_log("$session_id INFO: send bus msg that client '$source' has registered at server '$server_address'", 5);
636 #    }
638     # give the new client his ldap config
639     # Workaround: Send within the registration response, if the client will get an ldap config later
640         my $new_ldap_config_out = &new_ldap_config($source, $session_id);
641         if($new_ldap_config_out && (!($new_ldap_config_out =~ /error/))) {
642                 &add_content2xml_hash($out_hash, "ldap_available", "true");
643         } elsif($new_ldap_config_out && $new_ldap_config_out =~ /error/){
644                 &add_content2xml_hash($out_hash, "error", $new_ldap_config_out);
646                 my $sql_statement = "UPDATE $main::job_queue_tn ".
647                 "SET status='error', result='$new_ldap_config_out' ".
648                 "WHERE status='processing' AND macaddress LIKE '$mac_address'";
649                 my $res = $main::job_db->update_dbentry($sql_statement);
650                 &main::daemon_log("$session_id DEBUG: $sql_statement RESULT: $res", 7);         
651         }
652     my $register_out = &create_xml_string($out_hash);
653     push(@out_msg_l, $register_out);
655     # Really send the ldap config
656     if( $new_ldap_config_out && (!($new_ldap_config_out =~ /error/))) {
657             push(@out_msg_l, $new_ldap_config_out);
658     }
660         my $hardware_config_out = &hardware_config($msg, $msg_hash, $session_id);
661         if( $hardware_config_out ) {
662                 push(@out_msg_l, $hardware_config_out);
663         }
665     # notify registered client to all other server
666     my %mydata = ( 'client' => $source, 'macaddress' => $mac_address);
667     my $mymsg = &build_msg('new_foreign_client', $main::server_address, "KNOWN_SERVER", \%mydata);
668     push(@out_msg_l, $mymsg);
670     &main::daemon_log("$session_id INFO: register client $source ($mac_address)", 5);
671     &main::daemon_log("$session_id INFO: client version: $client_status - $client_revision", 5); 
672     return @out_msg_l;
676 #===  FUNCTION  ================================================================
677 #         NAME:  who_has
678 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
679 #      RETURNS:  nothing 
680 #  DESCRIPTION:  process this incoming message
681 #===============================================================================
682 sub who_has {
683     my ($msg_hash) = @_ ;
684     my @out_msg_l;
685     
686     # what is your search pattern
687     my $search_pattern = @{$msg_hash->{who_has}}[0];
688     my $search_element = @{$msg_hash->{$search_pattern}}[0];
689     &main::daemon_log("who_has-msg looking for $search_pattern $search_element", 7);
691     # scanning known_clients for search_pattern
692     my @host_addresses = keys %$main::known_clients;
693     my $known_clients_entries = length @host_addresses;
694     my $host_address;
695     foreach my $host (@host_addresses) {
696         my $client_element = $main::known_clients->{$host}->{$search_pattern};
697         if ($search_element eq $client_element) {
698             $host_address = $host;
699             last;
700         }
701     }
702         
703     # search was successful
704     if (defined $host_address) {
705         my $source = @{$msg_hash->{source}}[0];
706         my $out_hash = &create_xml_hash("who_has_i_do", $server_address, $source, "mac_address");
707         &add_content2xml_hash($out_hash, "mac_address", $search_element);
708         my $out_msg = &create_xml_string($out_hash);
709         push(@out_msg_l, $out_msg);
710     }
711     return @out_msg_l;
715 sub who_has_i_do {
716     my ($msg_hash) = @_ ;
717     my $header = @{$msg_hash->{header}}[0];
718     my $source = @{$msg_hash->{source}}[0];
719     my $search_param = @{$msg_hash->{$header}}[0];
720     my $search_value = @{$msg_hash->{$search_param}}[0];
721     print "\ngot msg $header:\nserver $source has client with $search_param $search_value\n";
725 #===  FUNCTION  ================================================================
726 #         NAME:  new_ldap_config
727 #   PARAMETERS:  address - string - ip address and port of a host
728 #      RETURNS:  gosa-si conform message
729 #  DESCRIPTION:  send to address the ldap configuration found for dn gotoLdapServer
730 #===============================================================================
731 sub new_ldap_config {
732         my ($address, $session_id) = @_ ;
734         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address' OR macaddress LIKE '$address'";
735         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
737         # check hit
738         my $hit_counter = keys %{$res};
739         if( not $hit_counter == 1 ) {
740                 &main::daemon_log("$session_id ERROR: more or no hit found in known_clients_db by query '$sql_statement'", 1);
741         }
743     $address = $res->{1}->{hostname};
744         my $macaddress = $res->{1}->{macaddress};
745         my $hostkey = $res->{1}->{hostkey};
747         if (not defined $macaddress) {
748                 &main::daemon_log("$session_id ERROR: no mac address found for client $address", 1);
749                 return;
750         }
752         # Build LDAP connection
753     my $ldap_handle = &main::get_ldap_handle($session_id);
754         if( not defined $ldap_handle ) {
755                 &main::daemon_log("$session_id ERROR: cannot connect to ldap: $ldap_uri", 1);
756                 return;
757         } 
759         # Perform search
760     $mesg = $ldap_handle->search( base   => $ldap_base,
761                 scope  => 'sub',
762                 attrs => ['dn', 'gotoLdapServer', 'gosaUnitTag', 'FAIclass'],
763                 filter => "(&(objectClass=GOhard)(macaddress=$macaddress))");
764         if($mesg->code) {
765                 &main::daemon_log("$session_id ".$mesg->error, 1);
766                 return;
767         }
769         # Sanity check
770         if ($mesg->count != 1) {
771                 &main::daemon_log("$session_id WARNING: client with mac address $macaddress not found/unique/active - not sending ldap config".
772                 "\n\tbase: $ldap_base".
773                 "\n\tscope: sub".
774                 "\n\tattrs: dn, gotoLdapServer".
775                 "\n\tfilter: (&(objectClass=GOhard)(macaddress=$macaddress))", 1);
776                 return;
777         }
779         my $entry= $mesg->entry(0);
780         my $dn= $entry->dn;
781         my @servers= $entry->get_value("gotoLdapServer");
782         my $unit_tag= $entry->get_value("gosaUnitTag");
783         my @ldap_uris;
784         my $server;
785         my $base;
786         my $release;
788         # Fill release if available
789         my $FAIclass= $entry->get_value("FAIclass");
790         if (defined $FAIclass && $FAIclass =~ /^.* :([A-Za-z0-9\/.]+).*$/) {
791                 $release= $1;
792         }
794         # Do we need to look at an object class?
795         if (not @servers){
796                 $mesg = $ldap_handle->search( base   => $ldap_base,
797                         scope  => 'sub',
798                         attrs => ['dn', 'gotoLdapServer', 'FAIclass'],
799                         filter => "(&(objectClass=gosaGroupOfNames)(member=$dn))");
800                 #$mesg->code && die $mesg->error;
801                 if($mesg->code) {
802                         &main::daemon_log("$session_id ".$mesg->error, 1);
803                         return;
804                 }
806                 # Sanity check
807                 if ($mesg->count != 1) {
808                         &main::daemon_log("$session_id WARNING: no LDAP information found for client mac $macaddress", 1);
809                         return;
810                 }
812                 $entry= $mesg->entry(0);
813                 $dn= $entry->dn;
814                 @servers= $entry->get_value("gotoLdapServer");
816                 if (not defined $release){
817                         $FAIclass= $entry->get_value("FAIclass");
818                         if (defined $FAIclass && $FAIclass =~ /^.* :([A-Za-z0-9\/.]+).*$/) {
819                                 $release= $1;
820                         }
821                 }
822         }
824         @servers= sort (@servers);
826         foreach $server (@servers){
827                 # Conversation for backward compatibility
828                 if (not $server =~ /^\d+:[^:]+:ldap[^:]*:\/\// ) {
829                     if ($server =~ /^([^:]+):([^:]+)$/ ) {
830                       $server= "1:dummy:ldap://$1/$2";
831                     } elsif ($server =~ /^(\d+):([^:]+):(.*)$/ ) {
832                       $server= "$1:dummy:ldap://$2/$3";
833                     }
834                 }
836                 $base= $server;
837                 $server =~ s%^[^:]+:[^:]+:(ldap.*://[^/]+)/.*$%$1%;
838                 $base =~ s%^[^:]+:[^:]+:ldap.*://[^/]+/(.*)$%$1%;
839                 push (@ldap_uris, $server);
840         }
842         # Assemble data package
843         my %data = ( 'ldap_uri'  => \@ldap_uris, 'ldap_base' => $base,
844                 'ldap_cfg' => \@ldap_cfg, 'pam_cfg' => \@pam_cfg,'nss_cfg' => \@nss_cfg );
845         if (defined $release){
846                 $data{'release'}= $release;
847         }
849         # Need to append GOto settings?
850         if (defined $goto_admin and defined $goto_secret){
851                 $data{'goto_admin'}= $goto_admin;
852                 $data{'goto_secret'}= $goto_secret;
853         }
855         # Append unit tag if needed
856         if (defined $unit_tag){
858                 # Find admin base and department name
859                 $mesg = $ldap_handle->search( base   => $ldap_base,
860                         scope  => 'sub',
861                         attrs => ['dn', 'ou'],
862                         filter => "(&(objectClass=gosaAdministrativeUnit)(gosaUnitTag=$unit_tag))");
863                 #$mesg->code && die $mesg->error;
864                 if($mesg->code) {
865                         &main::daemon_log($mesg->error, 1);
866                         return "error-unit-tag-count-0";
867                 }
869                 # Sanity check
870                 if ($mesg->count != 1) {
871                         &main::daemon_log("WARNING: cannot find administrative unit for client with tag $unit_tag", 1);
872                         return "error-unit-tag-count-".$mesg->count;
873                 }
875                 $entry= $mesg->entry(0);
876                 $data{'admin_base'}= $entry->dn;
877                 $data{'department'}= $entry->get_value("ou");
879                 # Append unit Tag
880                 $data{'unit_tag'}= $unit_tag;
881         }
883         # Send information
884         return &build_msg("new_ldap_config", $server_address, $address, \%data);
888 #===  FUNCTION  ================================================================
889 #         NAME:  hardware_config
890 #   PARAMETERS:  address - string - ip address and port of a host
891 #      RETURNS:  
892 #  DESCRIPTION:  
893 #===============================================================================
894 sub hardware_config {
895         my ($msg, $msg_hash, $session_id) = @_ ;
896         my $address = @{$msg_hash->{source}}[0];
897         my $header = @{$msg_hash->{header}}[0];
898         my $gotoHardwareChecksum = @{$msg_hash->{gotoHardwareChecksum}}[0];
900         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address'";
901         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
903         # check hit
904         my $hit_counter = keys %{$res};
905         if( not $hit_counter == 1 ) {
906                 &main::daemon_log("$session_id ERROR: more or no hit found in known_clients_db by query by '$address'", 1);
907         }
908         my $macaddress = $res->{1}->{macaddress};
909         my $hostkey = $res->{1}->{hostkey};
911         if (not defined $macaddress) {
912                 &main::daemon_log("$session_id ERROR: no mac address found for client $address", 1);
913                 return;
914         }
916         # Build LDAP connection
917     my $ldap_handle = &main::get_ldap_handle($session_id);
918         if( not defined $ldap_handle ) {
919                 &main::daemon_log("$session_id ERROR: cannot connect to ldap: $ldap_uri", 1);
920                 return;
921         } 
923         # Perform search
924         $mesg = $ldap_handle->search(
925                 base   => $ldap_base,
926                 scope  => 'sub',
927                 filter => "(&(objectClass=GOhard)(|(macAddress=$macaddress)(dhcpHWaddress=ethernet $macaddress)))"
928         );
930         if($mesg->count() == 0) {
931                 &main::daemon_log("Host was not found in LDAP!", 1);
933                 # set status = hardware_detection at jobqueue if entry exists
934                 # TODO
935                 # resolve plain name for host
936                 my $func_dic = {table=>$main::job_queue_tn,
937                                 primkey=>[],
938                                 timestamp=>&get_time,
939                                 status=>'processing',
940                                 result=>'none',
941                                 progress=>'hardware-detection',
942                                 headertag=>'trigger_action_reinstall',
943                                 targettag=>$address,
944                                 xmlmessage=>'none',
945                                 macaddress=>$macaddress,
946                                 plainname=>'none',
947                 };
948                 my $hd_res = $main::job_db->add_dbentry($func_dic);
949                 &main::daemon_log("$session_id INFO: add '$macaddress' to job queue as an installing job", 5);
950         
951         } else {
952                 my $entry= $mesg->entry(0);
953                 my $dn= $entry->dn;
954                 if (defined($entry->get_value("gotoHardwareChecksum"))) {
955                         if (! $entry->get_value("gotoHardwareChecksum") eq $gotoHardwareChecksum) {
956                                 $entry->replace(gotoHardwareChecksum => $gotoHardwareChecksum);
957                                 if($entry->update($ldap_handle)) {
958                                         &main::daemon_log("$session_id INFO: Hardware changed! Detection triggered.", 5);
959                                 }
960                         } else {
961                                 # Nothing to do
962                                 return;
963                         }
964                 } 
965         } 
967         # Assemble data package
968         my %data = ();
970         # Need to append GOto settings?
971         if (defined $goto_admin and defined $goto_secret){
972                 $data{'goto_admin'}= $goto_admin;
973                 $data{'goto_secret'}= $goto_secret;
974         }
976         # Send information
977         return &build_msg("detect_hardware", $server_address, $address, \%data);
980 sub server_matches {
981         my $target = shift;
982         my $target_ip = ($1) if $target =~ /^([0-9\.]*?):.*$/;
983         if(!defined($target_ip) or length($target_ip) == 0) {
984                 return;
985         }
987         my $result = 0;
989         if($server_ip eq $target_ip) {
990                 $result= 1;
991         } elsif ($target_ip eq "0.0.0.0") {
992                 $result= 1;
993         } elsif ($server_ip eq "0.0.0.0") {     
994                 if ($target_ip eq "127.0.0.1") {
995                         $result= 1;
996                 } else {
997                         my $PROC_NET_ROUTE= ('/proc/net/route');
999                         open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
1000                                 or die "Could not open $PROC_NET_ROUTE";
1002                         my @ifs = <PROC_NET_ROUTE>;
1004                         close(PROC_NET_ROUTE);
1006                         # Eat header line
1007                         shift @ifs;
1008                         chomp @ifs;
1009                         foreach my $line(@ifs) {
1010                                 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
1011                                 my $destination;
1012                                 my $mask;
1013                                 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
1014                                 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
1015                                 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
1016                                 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
1017                                 if(new NetAddr::IP($target_ip)->within(new NetAddr::IP($destination, $mask))) {
1018                                         # destination matches route, save mac and exit
1019                                         $result= 1;
1020                                         last;
1021                                 }
1022                         }
1023                 }
1024         } else {
1025                 &main::daemon_log("Target ip $target_ip does not match Server ip $server_ip",1);
1026         }
1028         return $result;
1031 1;