Code

Revert parts of the change.
[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 "server" => {
35     "ip" => [\$server_ip, "0.0.0.0"],
36     "mac-address" => [\$main::server_mac_address, "00:00:00:00:00"],
37     "port" => [\$server_port, "20081"],
38     "ldap-uri" => [\$ldap_uri, ""],
39     "ldap-base" => [\$ldap_base, ""],
40     "ldap-admin-dn" => [\$ldap_admin_dn, ""],
41     "ldap-admin-password" => [\$ldap_admin_password, ""],
42     "max-clients" => [\$max_clients, 100],
43     },
44 "ClientPackages" => {
45     "key" => [\$ClientPackages_key, ""],
46     },
47 );
49 ### START #####################################################################
51 # read configfile and import variables
52 &read_configfile();
55 # if server_ip is not an ip address but a name
56 if( inet_aton($server_ip) ){ $server_ip = inet_ntoa(inet_aton($server_ip)); } 
57 $network_interface= &get_interface_for_ip($server_ip);
58 $main::server_mac_address= &get_mac($network_interface);
61 # import local events
62 my ($error, $result, $event_hash) = &import_events($event_dir);
63 if ($error == 0) {
64     foreach my $log_line (@$result) {
65         &main::daemon_log("0 DEBUG: ClientPackages - $log_line", 7);
66     }
67 } else {
68     foreach my $log_line (@$result) {
69         &main::daemon_log("0 ERROR: ClientPackages - $log_line", 1);
70     }
72 }
74 # Unit tag can be defined in config
75 if((not defined($main::gosa_unit_tag)) || length($main::gosa_unit_tag) == 0) {
76         # Read gosaUnitTag from LDAP
77         
78     my $ldap_handle = &main::get_ldap_handle(); 
79     if( defined($ldap_handle) ) {
80                 &main::daemon_log("0 INFO: Searching for servers gosaUnitTag with mac address $main::server_mac_address",5);
81                 # Perform search for Unit Tag
82                 $mesg = $ldap_handle->search(
83                         base   => $ldap_base,
84                         scope  => 'sub',
85                         attrs  => ['gosaUnitTag'],
86                         filter => "(macaddress=$main::server_mac_address)"
87                 );
89                 if ((! $main::server_mac_address eq "00:00:00:00:00:00") and $mesg->count == 1) {
90                         my $entry= $mesg->entry(0);
91                         my $unit_tag= $entry->get_value("gosaUnitTag");
92                         $main::ldap_server_dn= $mesg->entry(0)->dn;
93                         if(defined($unit_tag) && length($unit_tag) > 0) {
94                                 &main::daemon_log("0 INFO: Detected gosaUnitTag $unit_tag for creating entries", 5);
95                                 $main::gosa_unit_tag= $unit_tag;
96                         }
97                 } else {
98                         # Perform another search for Unit Tag
99                         my $hostname= `hostname -f`;
100                         chomp($hostname);
101                         &main::daemon_log("0 INFO: Searching for servers gosaUnitTag with hostname $hostname",5);
102                         $mesg = $ldap_handle->search(
103                                 base   => $ldap_base,
104                                 scope  => 'sub',
105                                 attrs  => ['gosaUnitTag'],
106                                 filter => "(&(cn=$hostname)(objectClass=goServer))"
107                         );
108                         if ($mesg->count == 1) {
109                                 my $entry= $mesg->entry(0);
110                                 my $unit_tag= $entry->get_value("gosaUnitTag");
111                                 $main::ldap_server_dn= $mesg->entry(0)->dn;
112                                 if(defined($unit_tag) && length($unit_tag) > 0) {
113                                         &main::daemon_log("0 INFO: Detected gosaUnitTag $unit_tag for creating entries", 5);
114                                         $main::gosa_unit_tag= $unit_tag;
115                                 }
116                         } else {
117                                 # Perform another search for Unit Tag
118                                 $hostname= `hostname -s`;
119                                 chomp($hostname);
120                                 &main::daemon_log("0 INFO: Searching for servers gosaUnitTag with hostname $hostname",5);
121                                 $mesg = $ldap_handle->search(
122                                         base   => $ldap_base,
123                                         scope  => 'sub',
124                                         attrs  => ['gosaUnitTag'],
125                                         filter => "(&(cn=$hostname)(objectClass=goServer))"
126                                 );
127                                 if ($mesg->count == 1) {
128                                         my $entry= $mesg->entry(0);
129                                         my $unit_tag= $entry->get_value("gosaUnitTag");
130                                         $main::ldap_server_dn= $mesg->entry(0)->dn;
131                                         if(defined($unit_tag) && length($unit_tag) > 0) {
132                                                 &main::daemon_log("INFO: Detected gosaUnitTag $unit_tag for creating entries", 5);
133                                                 $main::gosa_unit_tag= $unit_tag;
134                                         }
135                                 } else {
136                                         &main::daemon_log("0 WARNING: No gosaUnitTag detected. Not using gosaUnitTag", 3);
137                                 }
138                         }
139                 }
140         } else {
141                 &main::daemon_log("0 INFO: Using gosaUnitTag from config-file: $main::gosa_unit_tag",5);
142         }
146 my $server_address = "$server_ip:$server_port";
147 $main::server_address = $server_address;
150 ### functions #################################################################
153 sub get_module_info {
154     my @info = ($server_address,
155                 $ClientPackages_key,
156                 );
157     return \@info;
161 #===  FUNCTION  ================================================================
162 #         NAME:  read_configfile
163 #   PARAMETERS:  cfg_file - string -
164 #      RETURNS:  nothing
165 #  DESCRIPTION:  read cfg_file and set variables
166 #===============================================================================
167 sub read_configfile {
168     my $cfg;
169     if( defined( $main::cfg_file) && ( (-s $main::cfg_file) > 0 )) {
170         if( -r $main::cfg_file ) {
171             $cfg = Config::IniFiles->new( -file => $main::cfg_file );
172         } else {
173             print STDERR "Couldn't read config file!";
174         }
175     } else {
176         $cfg = Config::IniFiles->new() ;
177     }
178     foreach my $section (keys %cfg_defaults) {
179         foreach my $param (keys %{$cfg_defaults{ $section }}) {
180             my $pinfo = $cfg_defaults{ $section }{ $param };
181             ${@$pinfo[0]} = $cfg->val( $section, $param, @$pinfo[1] );
182         }
183     }
185     # Read non predefined sections
186     my $param;
187     if ($cfg->SectionExists('ldap')){
188                 foreach $param ($cfg->Parameters('ldap')){
189                         push (@ldap_cfg, "$param ".$cfg->val('ldap', $param));
190                 }
191     }
192     if ($cfg->SectionExists('pam_ldap')){
193                 foreach $param ($cfg->Parameters('pam_ldap')){
194                         push (@pam_cfg, "$param ".$cfg->val('pam_ldap', $param));
195                 }
196     }
197     if ($cfg->SectionExists('nss_ldap')){
198                 foreach $param ($cfg->Parameters('nss_ldap')){
199                         push (@nss_cfg, "$param ".$cfg->val('nss_ldap', $param));
200                 }
201     }
202     if ($cfg->SectionExists('goto')){
203         $goto_admin= $cfg->val('goto', 'terminal_admin');
204         $goto_secret= $cfg->val('goto', 'terminal_secret');
205     } else {
206         $goto_admin= undef;
207         $goto_secret= undef;
208     }
213 #===  FUNCTION  ================================================================
214 #         NAME:  get_mac 
215 #   PARAMETERS:  interface name (i.e. eth0)
216 #      RETURNS:  (mac address) 
217 #  DESCRIPTION:  Uses ioctl to get mac address directly from system.
218 #===============================================================================
219 sub get_mac {
220         my $ifreq= shift;
221         my $result;
222         if ($ifreq && length($ifreq) > 0) { 
223                 if($ifreq eq "all") {
224                         $result = "00:00:00:00:00:00";
225                 } else {
226                         my $SIOCGIFHWADDR= 0x8927;     # man 2 ioctl_list
228                         # A configured MAC Address should always override a guessed value
229                         if ($main::server_mac_address and length($main::server_mac_address) > 0) {
230                                 $result= $main::server_mac_address;
231                         }
233                         socket SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('ip')
234                                 or die "socket: $!";
236                         if(ioctl SOCKET, $SIOCGIFHWADDR, $ifreq) {
237                                 my ($if, $mac)= unpack 'h36 H12', $ifreq;
239                                 if (length($mac) > 0) {
240                                         $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])$/;
241                                         $mac= sprintf("%s:%s:%s:%s:%s:%s", $1, $2, $3, $4, $5, $6);
242                                         $result = $mac;
243                                 }
244                         }
245                 }
246         }
247         return $result;
251 #===  FUNCTION  ================================================================
252 #         NAME:  process_incoming_msg
253 #   PARAMETERS:  crypted_msg - string - incoming crypted message
254 #      RETURNS:  nothing
255 #  DESCRIPTION:  handels the proceeded distribution to the appropriated functions
256 #===============================================================================
257 sub process_incoming_msg {
258     my ($msg, $msg_hash, $session_id) = @_ ;
259     my $error = 0;
260     my $host_name;
261     my $host_key;
262     my @out_msg_l = ("nohandler");
263     my $sql_events;
265     # process incoming msg
266     my $header = @{$msg_hash->{header}}[0]; 
267     my $source = @{$msg_hash->{source}}[0]; 
268     my @target_l = @{$msg_hash->{target}};
270     # skip PREFIX
271     $header =~ s/^CLMSG_//;
273     &main::daemon_log("$session_id DEBUG: ClientPackages: msg to process: $header", 7);
275     if( 0 == length @target_l){     
276         &main::daemon_log("$session_id ERROR: no target specified for msg $header", 1);
277         $error++;
278     }
280     if( 1 == length @target_l) {
281         my $target = $target_l[0];
282                 if(&server_matches($target)) {
283             if ($header eq 'new_key') {
284                 @out_msg_l = &new_key($msg_hash)
285             } elsif ($header eq 'here_i_am') {
286                 @out_msg_l = &here_i_am($msg, $msg_hash, $session_id)
287             } else {
288                 # a event exists with the header as name
289                 if( exists $event_hash->{$header} ) {
290                     &main::daemon_log("$session_id INFO: found event '$header' at event-module '".$event_hash->{$header}."'", 5);
291                     no strict 'refs';
292                     @out_msg_l = &{$event_hash->{$header}."::$header"}($msg, $msg_hash, $session_id);
294                 # if no event handler is implemented   
295                 } else {
296                     $sql_events = "SELECT * FROM $main::known_clients_tn WHERE ( (macaddress LIKE '$source') OR (hostname='$source') )"; 
297                     my $res = $main::known_clients_db->select_dbentry( $sql_events );
298                     my $l = keys(%$res);
300                     # set error if no or more than 1 hits are found for sql query
301                     if ( $l != 1) {
302                         @out_msg_l = ('knownclienterror');
304                     # found exact 1 hit in db
305                     } else {
306                         my $client_events = $res->{'1'}->{'events'};
308                         # client is registered for this event, deliver this message to client
309                         $header =~ s/^answer_//;
310                         if ($client_events =~ /,$header,/) {
311                             # answer message finally arrived destination server, so forward messages to GOsa
312                             if ($target eq $main::server_address) {        
313                                 $msg =~ s/<header>answer_/<header>/;
314                                 $msg =~ s/<target>\S+<\/target>/<target>GOSA<\/target>/;
315                             }
316                             @out_msg_l = ( $msg );
318                         # client is not registered for this event, set error
319                         } else {
320                             @out_msg_l = ('noeventerror');
321                         }
322                     }
323                 }
324             }
326             # if delivery not possible raise error and return 
327             if( not defined $out_msg_l[0] ) {
328                 @out_msg_l = ();
329             } elsif( $out_msg_l[0] eq 'nohandler') {
330                 &main::daemon_log("$session_id ERROR: ClientPackages: no event handler or core function defined for '$header'", 1);
331                 @out_msg_l = ();
332             }  elsif ($out_msg_l[0] eq 'knownclienterror') {
333                 &main::daemon_log("$session_id ERROR: no or more than 1 hits are found at known_clients_db with sql query: '$sql_events'", 1);
334                 &main::daemon_log("$session_id WARNING: processing is aborted and message will not be forwarded");
335                 @out_msg_l = ();
336             } elsif ($out_msg_l[0] eq 'noeventerror') {
337                 &main::daemon_log("$session_id WARNING: client '$target' is not registered for event '$header', processing is aborted", 1); 
338                 @out_msg_l = ();
339             }
344         }
345                 else {
346                         &main::daemon_log("INFO: msg is not for gosa-si-server '$server_address', deliver it to target '$target'", 5);
347                         push(@out_msg_l, $msg);
348                 }
349     }
351     return \@out_msg_l;
355 #===  FUNCTION  ================================================================
356 #         NAME:  new_passwd
357 #   PARAMETERS:  msg_hash - ref - hash from function create_xml_hash
358 #      RETURNS:  nothing
359 #  DESCRIPTION:  process this incoming message
360 #===============================================================================
361 sub new_key {
362     my ($msg_hash) = @_;
363     my @out_msg_l;
364     
365     my $header = @{$msg_hash->{header}}[0];
366     my $source_name = @{$msg_hash->{source}}[0];
367     my $source_key = @{$msg_hash->{new_key}}[0];
368     my $query_res;
370     # check known_clients_db
371     my $sql_statement = "SELECT * FROM known_clients WHERE hostname='$source_name'";
372     $query_res = $main::known_clients_db->select_dbentry( $sql_statement );
373     if( 1 == keys %{$query_res} ) {
374         my $act_time = &get_time;
375         my $sql_statement= "UPDATE known_clients ".
376             "SET hostkey='$source_key', timestamp='$act_time' ".
377             "WHERE hostname='$source_name'";
378         my $res = $main::known_clients_db->update_dbentry( $sql_statement );
379         my $hash = &create_xml_hash("confirm_new_key", $server_address, $source_name);
380         my $out_msg = &create_xml_string($hash);
381         push(@out_msg_l, $out_msg);
382     }
384     # only do if host still not found
385     if( 0 == @out_msg_l ) {
386         # check known_server_db
387         $sql_statement = "SELECT * FROM known_server WHERE hostname='$source_name'";
388         $query_res = $main::known_server_db->select_dbentry( $sql_statement );
389         if( 1 == keys %{$query_res} ) {
390             my $act_time = &get_time;
391             my $sql_statement= "UPDATE known_server ".
392                 "SET hostkey='$source_key', timestamp='$act_time' ".
393                 "WHERE hostname='$source_name'";
394             my $res = $main::known_server_db->update_dbentry( $sql_statement );
396             my $hash = &create_xml_hash("confirm_new_key", $server_address, $source_name);
397             my $out_msg = &create_xml_string($hash);
398             push(@out_msg_l, $out_msg);
399         }
400     }
402     return @out_msg_l;
406 #===  FUNCTION  ================================================================
407 #         NAME:  here_i_am
408 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
409 #      RETURNS:  nothing
410 #  DESCRIPTION:  process this incoming message
411 #===============================================================================
412 sub here_i_am {
413     my ($msg, $msg_hash, $session_id) = @_;
414     my @out_msg_l;
415     my $out_hash;
416     my $source = @{$msg_hash->{source}}[0];
417     my $mac_address = @{$msg_hash->{mac_address}}[0];
418         my $gotoHardwareChecksum = @{$msg_hash->{gotoHardwareChecksum}}[0];
419     my $client_status = @{$msg_hash->{client_status}}[0];
420     my $client_revision = @{$msg_hash->{client_revision}}[0];
421     my $key_lifetime = @{$msg_hash->{key_lifetime}}[0];
423     # Move forced hostname to heap - if used
424     #if ( defined($msg_hash->{'force-hostname'}[0]) &&
425     #   length($msg_hash->{'force-hostname'}[0]) > 0){
426     #      $heap->{force-hostname}->{$mac_address}= $msg_hash->{'force-hostname'}[0];
427     #} else {
428     #      $heap->{force-hostname}->{$mac_address}= undef;
429     #}
431     # number of known clients
432     my $nu_clients= $main::known_clients_db->count_dbentries('known_clients');
434     # check wether client address or mac address is already known
435     my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$source'";
436     my $db_res= $main::known_clients_db->select_dbentry( $sql_statement );
437     
438     if ( 1 == keys %{$db_res} ) {
439         &main::daemon_log("$session_id WARNING: $source is already known as a client", 1);
440         &main::daemon_log("$session_id WARNING: values for $source are being overwritten", 1);   
441         $nu_clients --;
442     }
444     # number of actual activ clients
445     my $act_nu_clients = $nu_clients;
447     &main::daemon_log("$session_id INFO: number of actual activ clients: $act_nu_clients", 5);
448     &main::daemon_log("$session_id INFO: number of maximal allowed clients: $max_clients", 5);
450     if($max_clients <= $act_nu_clients) {
451         my $out_hash = &create_xml_hash("denied", $server_address, $source);
452         &add_content2xml_hash($out_hash, "denied", "I_cannot_take_any_more_clients!");
453         my $passwd = @{$msg_hash->{new_passwd}}[0]; 
454         &send_msg_hash2address($out_hash, $source, $passwd);
455         return;
456     }
457     
458     # new client accepted
459     my $new_passwd = @{$msg_hash->{new_passwd}}[0];
461     # add entry to known_clients_db
462     my $events = @{$msg_hash->{events}}[0];
463     my $act_timestamp = &get_time;
464     my $res = $main::known_clients_db->add_dbentry( {table=>'known_clients', 
465                                                 primkey=>['hostname'],
466                                                 hostname=>$source,
467                                                 events=>$events,
468                                                 macaddress=>$mac_address,
469                                                 status=>'registered',
470                                                 hostkey=>$new_passwd,
471                                                 timestamp=>$act_timestamp,
472                                                 keylifetime=>$key_lifetime,
473                                                 } );
475     if ($res != 0)  {
476         &main::daemon_log("$session_id ERROR: cannot add entry to known_clients: $res");
477         return;
478     }
479     
480     # return acknowledgement to client
481     $out_hash = &create_xml_hash("registered", $server_address, $source);
484     # give the new client his ldap config
485     # Workaround: Send within the registration response, if the client will get an ldap config later
486         my $new_ldap_config_out = &new_ldap_config($source, $session_id);
487         if($new_ldap_config_out && (!($new_ldap_config_out =~ /error/))) {
488                 &add_content2xml_hash($out_hash, "ldap_available", "true");
489         } elsif($new_ldap_config_out && $new_ldap_config_out =~ /error/){
490                 &add_content2xml_hash($out_hash, "error", $new_ldap_config_out);
492                 my $sql_statement = "UPDATE $main::job_queue_tn ".
493                 "SET status='error', result='$new_ldap_config_out' ".
494                 "WHERE status='processing' AND macaddress LIKE '$mac_address'";
495                 my $res = $main::job_db->update_dbentry($sql_statement);
496                 &main::daemon_log("$session_id DEBUG: $sql_statement RESULT: $res", 7);         
497         }
498     my $register_out = &create_xml_string($out_hash);
499     push(@out_msg_l, $register_out);
501     # Really send the ldap config
502     if( $new_ldap_config_out && (!($new_ldap_config_out =~ /error/))) {
503             push(@out_msg_l, $new_ldap_config_out);
504     }
506         my $hardware_config_out = &hardware_config($msg, $msg_hash, $session_id);
507         if( $hardware_config_out ) {
508                 push(@out_msg_l, $hardware_config_out);
509         }
511     # notify registered client to all other server
512     my %mydata = ( 'client' => $source, 'macaddress' => $mac_address);
513     my $mymsg = &build_msg('new_foreign_client', $main::server_address, "KNOWN_SERVER", \%mydata);
514     push(@out_msg_l, $mymsg);
516     &main::daemon_log("$session_id INFO: register client $source ($mac_address)", 5);
517     &main::daemon_log("$session_id INFO: client version: $client_status - $client_revision", 5); 
518     return @out_msg_l;
522 #===  FUNCTION  ================================================================
523 #         NAME:  who_has
524 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
525 #      RETURNS:  nothing 
526 #  DESCRIPTION:  process this incoming message
527 #===============================================================================
528 sub who_has {
529     my ($msg_hash) = @_ ;
530     my @out_msg_l;
531     
532     # what is your search pattern
533     my $search_pattern = @{$msg_hash->{who_has}}[0];
534     my $search_element = @{$msg_hash->{$search_pattern}}[0];
535     &main::daemon_log("who_has-msg looking for $search_pattern $search_element", 7);
537     # scanning known_clients for search_pattern
538     my @host_addresses = keys %$main::known_clients;
539     my $known_clients_entries = length @host_addresses;
540     my $host_address;
541     foreach my $host (@host_addresses) {
542         my $client_element = $main::known_clients->{$host}->{$search_pattern};
543         if ($search_element eq $client_element) {
544             $host_address = $host;
545             last;
546         }
547     }
548         
549     # search was successful
550     if (defined $host_address) {
551         my $source = @{$msg_hash->{source}}[0];
552         my $out_hash = &create_xml_hash("who_has_i_do", $server_address, $source, "mac_address");
553         &add_content2xml_hash($out_hash, "mac_address", $search_element);
554         my $out_msg = &create_xml_string($out_hash);
555         push(@out_msg_l, $out_msg);
556     }
557     return @out_msg_l;
561 sub who_has_i_do {
562     my ($msg_hash) = @_ ;
563     my $header = @{$msg_hash->{header}}[0];
564     my $source = @{$msg_hash->{source}}[0];
565     my $search_param = @{$msg_hash->{$header}}[0];
566     my $search_value = @{$msg_hash->{$search_param}}[0];
567     print "\ngot msg $header:\nserver $source has client with $search_param $search_value\n";
571 #===  FUNCTION  ================================================================
572 #         NAME:  new_ldap_config
573 #   PARAMETERS:  address - string - ip address and port of a host
574 #      RETURNS:  gosa-si conform message
575 #  DESCRIPTION:  send to address the ldap configuration found for dn gotoLdapServer
576 #===============================================================================
577 sub new_ldap_config {
578         my ($address, $session_id) = @_ ;
580         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address' OR macaddress LIKE '$address'";
581         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
583         # check hit
584         my $hit_counter = keys %{$res};
585         if( not $hit_counter == 1 ) {
586                 &main::daemon_log("$session_id ERROR: more or no hit found in known_clients_db by query '$sql_statement'", 1);
587         }
589     $address = $res->{1}->{hostname};
590         my $macaddress = $res->{1}->{macaddress};
591         my $hostkey = $res->{1}->{hostkey};
593         if (not defined $macaddress) {
594                 &main::daemon_log("$session_id ERROR: no mac address found for client $address", 1);
595                 return;
596         }
598         # Build LDAP connection
599     my $ldap_handle = &main::get_ldap_handle($session_id);
600         if( not defined $ldap_handle ) {
601                 &main::daemon_log("$session_id ERROR: cannot connect to ldap: $ldap_uri", 1);
602                 return;
603         } 
605         # Perform search
606     $mesg = $ldap_handle->search( base   => $ldap_base,
607                 scope  => 'sub',
608                 attrs => ['dn', 'gotoLdapServer', 'gosaUnitTag', 'FAIclass'],
609                 filter => "(&(objectClass=GOhard)(macaddress=$macaddress))");
610         if($mesg->code) {
611                 &main::daemon_log("$session_id ".$mesg->error, 1);
612                 return;
613         }
615         # Sanity check
616         if ($mesg->count != 1) {
617                 &main::daemon_log("$session_id WARNING: client with mac address $macaddress not found/unique/active - not sending ldap config".
618                 "\n\tbase: $ldap_base".
619                 "\n\tscope: sub".
620                 "\n\tattrs: dn, gotoLdapServer".
621                 "\n\tfilter: (&(objectClass=GOhard)(macaddress=$macaddress))", 1);
622                 return;
623         }
625         my $entry= $mesg->entry(0);
626         my $dn= $entry->dn;
627         my @servers= $entry->get_value("gotoLdapServer");
628         my $unit_tag= $entry->get_value("gosaUnitTag");
629         my @ldap_uris;
630         my $server;
631         my $base;
632         my $release;
634         # Fill release if available
635         my $FAIclass= $entry->get_value("FAIclass");
636         if (defined $FAIclass && $FAIclass =~ /^.* :([A-Za-z0-9\/.]+).*$/) {
637                 $release= $1;
638         }
640         # Do we need to look at an object class?
641         if (not @servers){
642                 $mesg = $ldap_handle->search( base   => $ldap_base,
643                         scope  => 'sub',
644                         attrs => ['dn', 'gotoLdapServer', 'FAIclass'],
645                         filter => "(&(objectClass=gosaGroupOfNames)(member=$dn))");
646                 if($mesg->code) {
647                         &main::daemon_log("$session_id ERROR: unable to search for '(&(objectClass=gosaGroupOfNames)(member=$dn))': ".$mesg->error, 1);
648                         return;
649                 }
651                 # Sanity check
652                 if ($mesg->count == 0) {
653                         &main::daemon_log("$session_id WARNING: no LDAP informations found for client  with filter '(&(objectClass=gosaGroupOfNames)(member=$dn))'", 3);
654                         return;
655                 } elsif ($mesg->count >= 2) {
656             &main::daemon_log("$session_id ERROR: multiple LDAP informations found for client  with filter '(&(objectClass=gosaGroupOfNames)(member=$dn))'", 1);
657             return;
658         }
660                 $entry= $mesg->entry(0);
661                 $dn= $entry->dn;
662                 @servers= $entry->get_value("gotoLdapServer");
664                 if (not defined $release){
665                         $FAIclass= $entry->get_value("FAIclass");
666                         if (defined $FAIclass && $FAIclass =~ /^.* :([A-Za-z0-9\/.]+).*$/) {
667                                 $release= $1;
668                         }
669                 }
670         }
672         @servers= sort (@servers);
674     # complain if no ldap information found
675     if (@servers == 0) {
676         &main::daemon_log("$session_id ERROR: no gotoLdapServer information for LDAP entry with filter '(&(objectClass=gosaGroupOfNames)(member=$dn))'");
677     }
679         foreach $server (@servers){
680                 # Conversation for backward compatibility
681                 if (not $server =~ /^\d+:[^:]+:ldap[^:]*:\/\// ) {
682                     if ($server =~ /^([^:]+):([^:]+)$/ ) {
683                       $server= "1:dummy:ldap://$1/$2";
684                     } elsif ($server =~ /^(\d+):([^:]+):(.*)$/ ) {
685                       $server= "$1:dummy:ldap://$2/$3";
686                     }
687                 }
689                 $base= $server;
690                 $server =~ s%^[^:]+:[^:]+:(ldap.*://[^/]+)/.*$%$1%;
691                 $base =~ s%^[^:]+:[^:]+:ldap.*://[^/]+/(.*)$%$1%;
692                 push (@ldap_uris, $server);
693         }
695         # Assemble data package
696         my %data = ( 'ldap_uri'  => \@ldap_uris, 'ldap_base' => $base,
697                 'ldap_cfg' => \@ldap_cfg, 'pam_cfg' => \@pam_cfg,'nss_cfg' => \@nss_cfg );
698         if (defined $release){
699                 $data{'release'}= $release;
700         }
702         # Need to append GOto settings?
703         if (defined $goto_admin and defined $goto_secret){
704                 $data{'goto_admin'}= $goto_admin;
705                 $data{'goto_secret'}= $goto_secret;
706         }
708         # Append unit tag if needed
709         if (defined $unit_tag){
711                 # Find admin base and department name
712                 $mesg = $ldap_handle->search( base   => $ldap_base,
713                         scope  => 'sub',
714                         attrs => ['dn', 'ou'],
715                         filter => "(&(objectClass=gosaAdministrativeUnit)(gosaUnitTag=$unit_tag))");
716                 #$mesg->code && die $mesg->error;
717                 if($mesg->code) {
718                         &main::daemon_log($mesg->error, 1);
719                         return "error-unit-tag-count-0";
720                 }
722                 # Sanity check
723                 if ($mesg->count != 1) {
724                         &main::daemon_log("WARNING: cannot find administrative unit for client with tag $unit_tag", 1);
725                         return "error-unit-tag-count-".$mesg->count;
726                 }
728                 $entry= $mesg->entry(0);
729                 $data{'admin_base'}= $entry->dn;
730                 $data{'department'}= $entry->get_value("ou");
732                 # Append unit Tag
733                 $data{'unit_tag'}= $unit_tag;
734         }
736         # Send information
737         return &build_msg("new_ldap_config", $server_address, $address, \%data);
741 #===  FUNCTION  ================================================================
742 #         NAME:  hardware_config
743 #   PARAMETERS:  address - string - ip address and port of a host
744 #      RETURNS:  
745 #  DESCRIPTION:  
746 #===============================================================================
747 sub hardware_config {
748         my ($msg, $msg_hash, $session_id) = @_ ;
749         my $address = @{$msg_hash->{source}}[0];
750         my $header = @{$msg_hash->{header}}[0];
751         my $gotoHardwareChecksum = @{$msg_hash->{gotoHardwareChecksum}}[0];
753         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address'";
754         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
756         # check hit
757         my $hit_counter = keys %{$res};
758         if( not $hit_counter == 1 ) {
759                 &main::daemon_log("$session_id ERROR: more or no hit found in known_clients_db by query by '$address'", 1);
760         }
761         my $macaddress = $res->{1}->{macaddress};
762         my $hostkey = $res->{1}->{hostkey};
764         if (not defined $macaddress) {
765                 &main::daemon_log("$session_id ERROR: no mac address found for client $address", 1);
766                 return;
767         }
769         # Build LDAP connection
770     my $ldap_handle = &main::get_ldap_handle($session_id);
771         if( not defined $ldap_handle ) {
772                 &main::daemon_log("$session_id ERROR: cannot connect to ldap: $ldap_uri", 1);
773                 return;
774         } 
776         # Perform search
777         $mesg = $ldap_handle->search(
778                 base   => $ldap_base,
779                 scope  => 'sub',
780                 filter => "(&(objectClass=GOhard)(|(macAddress=$macaddress)(dhcpHWaddress=ethernet $macaddress)))"
781         );
783         if($mesg->count() == 0) {
784                 &main::daemon_log("Host was not found in LDAP!", 1);
786                 # set status = hardware_detection at jobqueue if entry exists
787                 # TODO
788                 # resolve plain name for host
789                 my $func_dic = {table=>$main::job_queue_tn,
790                                 primkey=>['macaddress', 'headertag'],
791                                 timestamp=>&get_time,
792                                 status=>'processing',
793                                 result=>'none',
794                                 progress=>'hardware-detection',
795                                 headertag=>'trigger_action_reinstall',
796                                 targettag=>$address,
797                                 xmlmessage=>'none',
798                                 macaddress=>$macaddress,
799                                 plainname=>'none',
800                 siserver=>'localhost',
801                 modified=>'1',
802                 };
803                 my $hd_res = $main::job_db->add_dbentry($func_dic);
804                 &main::daemon_log("$session_id INFO: add '$macaddress' to job queue as an installing job", 5);
805         
806         } else {
807                 my $entry= $mesg->entry(0);
808                 my $dn= $entry->dn;
809                 if (defined($entry->get_value("gotoHardwareChecksum"))) {
810                         if (! $entry->get_value("gotoHardwareChecksum") eq $gotoHardwareChecksum) {
811                                 $entry->replace(gotoHardwareChecksum => $gotoHardwareChecksum);
812                                 if($entry->update($ldap_handle)) {
813                                         &main::daemon_log("$session_id INFO: Hardware changed! Detection triggered.", 5);
814                                 }
815                         } else {
816                                 # Nothing to do
817                                 return;
818                         }
819                 } 
820         } 
822         # Assemble data package
823         my %data = ();
825         # Need to append GOto settings?
826         if (defined $goto_admin and defined $goto_secret){
827                 $data{'goto_admin'}= $goto_admin;
828                 $data{'goto_secret'}= $goto_secret;
829         }
831         # Send information
832         return &build_msg("detect_hardware", $server_address, $address, \%data);
835 sub server_matches {
836         my $target = shift;
837         my $target_ip = ($1) if $target =~ /^([0-9\.]*?):.*$/;
838         if(!defined($target_ip) or length($target_ip) == 0) {
839                 return;
840         }
842         my $result = 0;
844         if($server_ip eq $target_ip) {
845                 $result= 1;
846         } elsif ($target_ip eq "0.0.0.0") {
847                 $result= 1;
848         } elsif ($server_ip eq "0.0.0.0") {     
849                 if ($target_ip eq "127.0.0.1") {
850                         $result= 1;
851                 } else {
852                         my $PROC_NET_ROUTE= ('/proc/net/route');
854                         open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
855                                 or die "Could not open $PROC_NET_ROUTE";
857                         my @ifs = <PROC_NET_ROUTE>;
859                         close(PROC_NET_ROUTE);
861                         # Eat header line
862                         shift @ifs;
863                         chomp @ifs;
864                         foreach my $line(@ifs) {
865                                 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
866                                 my $destination;
867                                 my $mask;
868                                 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
869                                 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
870                                 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
871                                 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
872                                 if(new NetAddr::IP($target_ip)->within(new NetAddr::IP($destination, $mask))) {
873                                         # destination matches route, save mac and exit
874                                         $result= 1;
875                                         last;
876                                 }
877                         }
878                 }
879         } else {
880                 &main::daemon_log("Target ip $target_ip does not match Server ip $server_ip",1);
881         }
883         return $result;
886 # vim:ts=4:shiftwidth:expandtab
887 1;