Code

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