Code

new ldap handling, a handle is taken out of a pool of ldap handles and given back...
[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 Net::LDAP::Util;
17 use Socket;
18 use Net::hostent;
20 my $event_dir = "/usr/lib/gosa-si/server/ClientPackages";
21 use lib "/usr/lib/gosa-si/server/ClientPackages";
23 BEGIN{}
24 END {}
26 my ($server_ip, $server_port, $ClientPackages_key, $max_clients, $ldap_uri, $ldap_base, $ldap_admin_dn, $ldap_admin_password, $server_interface);
27 my $server;
28 my $network_interface;
29 my (@ldap_cfg, @pam_cfg, @nss_cfg, $goto_admin, $goto_secret);
30 my $mesg;
32 my %cfg_defaults = (
33 "server" => {
34     "ip" => [\$server_ip, "0.0.0.0"],
35     "mac-address" => [\$main::server_mac_address, "00:00:00:00:00"],
36     "port" => [\$server_port, "20081"],
37     "ldap-uri" => [\$ldap_uri, ""],
38     "ldap-base" => [\$ldap_base, ""],
39     "ldap-admin-dn" => [\$ldap_admin_dn, ""],
40     "ldap-admin-password" => [\$ldap_admin_password, ""],
41     "max-clients" => [\$max_clients, 100],
42     },
43 "ClientPackages" => {
44     "key" => [\$ClientPackages_key, ""],
45     },
46 );
48 ### START #####################################################################
50 # read configfile and import variables
51 &local_read_configfile();
54 # if server_ip is not an ip address but a name
55 if( inet_aton($server_ip) ){ $server_ip = inet_ntoa(inet_aton($server_ip)); } 
56 $network_interface= &get_interface_for_ip($server_ip);
57 $main::server_mac_address= &get_mac($network_interface);
60 # import local events
61 my ($error, $result, $event_hash) = &import_events($event_dir);
63 foreach my $log_line (@$result) {
64     if ($log_line =~ / succeed: /) {
65         &main::daemon_log("0 DEBUG: ClientPackages - $log_line", 7);
66     } else {
67         &main::daemon_log("0 ERROR: ClientPackages - $log_line", 1);
68     }
69 }
70 # build vice versa event_hash, event_name => module
71 my $event2module_hash = {};
72 while (my ($module, $mod_events) = each %$event_hash) {
73     while (my ($event_name, $nothing) = each %$mod_events) {
74         $event2module_hash->{$event_name} = $module;
75     }
77 }
79 # Unit tag can be defined in config
80 if((not defined($main::gosa_unit_tag)) || length($main::gosa_unit_tag) == 0) {
81         # Read gosaUnitTag from LDAP
82         
83     my $ldap_handle = &main::get_ldap_handle(); 
84     if( defined($ldap_handle) ) {
85                 &main::daemon_log("0 INFO: Searching for servers gosaUnitTag with mac address $main::server_mac_address",5);
86                 # Perform search for Unit Tag
87                 $mesg = $ldap_handle->search(
88                         base   => $ldap_base,
89                         scope  => 'sub',
90                         attrs  => ['gosaUnitTag'],
91                         filter => "(macaddress=$main::server_mac_address)"
92                 );
94                 if ((! $main::server_mac_address eq "00:00:00:00:00:00") and $mesg->count == 1) {
95                         my $entry= $mesg->entry(0);
96                         my $unit_tag= $entry->get_value("gosaUnitTag");
97                         $main::ldap_server_dn= $mesg->entry(0)->dn;
98                         if(defined($unit_tag) && length($unit_tag) > 0) {
99                                 &main::daemon_log("0 INFO: Detected gosaUnitTag $unit_tag for creating entries", 5);
100                                 $main::gosa_unit_tag= $unit_tag;
101                         }
102                 } else {
103                         # Perform another search for Unit Tag
104                         my $hostname= `hostname -f`;
105                         chomp($hostname);
106                         &main::daemon_log("0 INFO: Searching for servers gosaUnitTag with hostname $hostname",5);
107                         $mesg = $ldap_handle->search(
108                                 base   => $ldap_base,
109                                 scope  => 'sub',
110                                 attrs  => ['gosaUnitTag'],
111                                 filter => "(&(cn=$hostname)(objectClass=goServer))"
112                         );
113                         if ($mesg->count == 1) {
114                                 my $entry= $mesg->entry(0);
115                                 my $unit_tag= $entry->get_value("gosaUnitTag");
116                                 $main::ldap_server_dn= $mesg->entry(0)->dn;
117                                 if(defined($unit_tag) && length($unit_tag) > 0) {
118                                         &main::daemon_log("0 INFO: Detected gosaUnitTag $unit_tag for creating entries", 5);
119                                         $main::gosa_unit_tag= $unit_tag;
120                                 }
121                         } else {
122                                 # Perform another search for Unit Tag
123                                 $hostname= `hostname -s`;
124                                 chomp($hostname);
125                                 &main::daemon_log("0 INFO: Searching for servers gosaUnitTag with hostname $hostname",5);
126                                 $mesg = $ldap_handle->search(
127                                         base   => $ldap_base,
128                                         scope  => 'sub',
129                                         attrs  => ['gosaUnitTag'],
130                                         filter => "(&(cn=$hostname)(objectClass=goServer))"
131                                 );
132                                 if ($mesg->count == 1) {
133                                         my $entry= $mesg->entry(0);
134                                         my $unit_tag= $entry->get_value("gosaUnitTag");
135                                         $main::ldap_server_dn= $mesg->entry(0)->dn;
136                                         if(defined($unit_tag) && length($unit_tag) > 0) {
137                                                 &main::daemon_log("INFO: Detected gosaUnitTag $unit_tag for creating entries", 5);
138                                                 $main::gosa_unit_tag= $unit_tag;
139                                         }
140                                 } else {
141                                         &main::daemon_log("0 WARNING: No gosaUnitTag detected. Not using gosaUnitTag", 3);
142                                 }
143                         }
144                 }
145         } else {
146                 &main::daemon_log("0 INFO: Using gosaUnitTag from config-file: $main::gosa_unit_tag",5);
147         }
148     &main::release_ldap_handle($ldap_handle);
152 my $server_address = "$server_ip:$server_port";
153 $main::server_address = $server_address;
156 ### functions #################################################################
159 sub get_module_info {
160     my @info = ($server_address,
161                 $ClientPackages_key,
162                 $event_hash,
163                 );
164     return \@info;
168 #===  FUNCTION  ================================================================
169 #         NAME:  local_read_configfile
170 #   PARAMETERS:  cfg_file - string -
171 #      RETURNS:  nothing
172 #  DESCRIPTION:  read cfg_file and set variables
173 #===============================================================================
174 sub local_read_configfile {
175     my $cfg;
176     if( defined( $main::cfg_file) && ( (-s $main::cfg_file) > 0 )) {
177         if( -r $main::cfg_file ) {
178             $cfg = Config::IniFiles->new( -file => $main::cfg_file );
179         } else {
180             print STDERR "Couldn't read config file!";
181         }
182     } else {
183         $cfg = Config::IniFiles->new() ;
184     }
185     foreach my $section (keys %cfg_defaults) {
186         foreach my $param (keys %{$cfg_defaults{ $section }}) {
187             my $pinfo = $cfg_defaults{ $section }{ $param };
188             ${@$pinfo[0]} = $cfg->val( $section, $param, @$pinfo[1] );
189         }
190     }
192     # Read non predefined sections
193     my $param;
194     if ($cfg->SectionExists('ldap')){
195                 foreach $param ($cfg->Parameters('ldap')){
196                         push (@ldap_cfg, "$param ".$cfg->val('ldap', $param));
197                 }
198     }
199     if ($cfg->SectionExists('pam_ldap')){
200                 foreach $param ($cfg->Parameters('pam_ldap')){
201                         push (@pam_cfg, "$param ".$cfg->val('pam_ldap', $param));
202                 }
203     }
204     if ($cfg->SectionExists('nss_ldap')){
205                 foreach $param ($cfg->Parameters('nss_ldap')){
206                         push (@nss_cfg, "$param ".$cfg->val('nss_ldap', $param));
207                 }
208     }
209     if ($cfg->SectionExists('goto')){
210         $goto_admin= $cfg->val('goto', 'terminal_admin');
211         $goto_secret= $cfg->val('goto', 'terminal_secret');
212     } else {
213         $goto_admin= undef;
214         $goto_secret= undef;
215     }
220 #===  FUNCTION  ================================================================
221 #         NAME:  get_mac 
222 #   PARAMETERS:  interface name (i.e. eth0)
223 #      RETURNS:  (mac address) 
224 #  DESCRIPTION:  Uses ioctl to get mac address directly from system.
225 #===============================================================================
226 sub get_mac {
227         my $ifreq= shift;
228         my $result;
229         if ($ifreq && length($ifreq) > 0) { 
230                 if($ifreq eq "all") {
231                         $result = "00:00:00:00:00:00";
232                 } else {
233                         my $SIOCGIFHWADDR= 0x8927;     # man 2 ioctl_list
235                         # A configured MAC Address should always override a guessed value
236                         if ($main::server_mac_address and length($main::server_mac_address) > 0) {
237                                 $result= $main::server_mac_address;
238                         }
240                         socket SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('ip')
241                                 or die "socket: $!";
243                         if(ioctl SOCKET, $SIOCGIFHWADDR, $ifreq) {
244                                 my ($if, $mac)= unpack 'h36 H12', $ifreq;
246                                 if (length($mac) > 0) {
247                                         $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])$/;
248                                         $mac= sprintf("%s:%s:%s:%s:%s:%s", $1, $2, $3, $4, $5, $6);
249                                         $result = $mac;
250                                 }
251                         }
252                 }
253         }
254         return $result;
258 #===  FUNCTION  ================================================================
259 #         NAME:  process_incoming_msg
260 #   PARAMETERS:  crypted_msg - string - incoming crypted message
261 #      RETURNS:  nothing
262 #  DESCRIPTION:  handels the proceeded distribution to the appropriated functions
263 #===============================================================================
264 sub process_incoming_msg {
265     my ($msg, $msg_hash, $session_id, $ldap_handle) = @_ ;
266     my $error = 0;
267     my $host_name;
268     my $host_key;
269     my @out_msg_l = ("nohandler");
270     my $sql_events;
272     # process incoming msg
273     my $header = @{$msg_hash->{header}}[0]; 
274     my $source = @{$msg_hash->{source}}[0]; 
275     my @target_l = @{$msg_hash->{target}};
277     # skip PREFIX
278     $header =~ s/^CLMSG_//;
280     &main::daemon_log("$session_id DEBUG: ClientPackages: msg to process: $header", 7);
282     if( 0 == length @target_l){     
283         &main::daemon_log("$session_id ERROR: no target specified for msg $header", 1);
284         $error++;
285     }
287     if( 1 == length @target_l) {
288         my $target = $target_l[0];
289                 if(&server_matches($target)) {
290             if ($header eq 'new_key') {
291                 @out_msg_l = &new_key($msg_hash)
292             } elsif ($header eq 'here_i_am') {
293                 @out_msg_l = &here_i_am($msg, $msg_hash, $session_id, $ldap_handle)
294             } else {
295                 # a event exists with the header as name
296                 if( exists $event2module_hash->{$header} ) {
297                     &main::daemon_log("$session_id INFO: found event '$header' at event-module '".$event2module_hash->{$header}."'", 5);
298                     no strict 'refs';
299                     @out_msg_l = &{$event2module_hash->{$header}."::$header"}($msg, $msg_hash, $session_id, $ldap_handle);
301                 # if no event handler is implemented   
302                 } else {
303                     $sql_events = "SELECT * FROM $main::known_clients_tn WHERE ( (macaddress LIKE '$source') OR (hostname='$source') )"; 
304                     my $res = $main::known_clients_db->select_dbentry( $sql_events );
305                     my $l = keys(%$res);
307                     # set error if no or more than 1 hits are found for sql query
308                     if ( $l != 1) {
309                         @out_msg_l = ('knownclienterror');
311                     # found exact 1 hit in db
312                     } else {
313                         my $client_events = $res->{'1'}->{'events'};
315                         # client is registered for this event, deliver this message to client
316                         $header =~ s/^answer_//;
317                         if ($client_events =~ /,$header,/) {
318                             # answer message finally arrived destination server, so forward messages to GOsa
319                             if ($target eq $main::server_address) {        
320                                 $msg =~ s/<header>answer_/<header>/;
321                                 $msg =~ s/<target>\S+<\/target>/<target>GOSA<\/target>/;
322                             }
323                             @out_msg_l = ( $msg );
325                         # client is not registered for this event, set error
326                         } else {
327                             @out_msg_l = ('noeventerror');
328                         }
329                     }
330                 }
331             }
333             # if delivery not possible raise error and return 
334             if( not defined $out_msg_l[0] ) {
335                 @out_msg_l = ();
336             } elsif( $out_msg_l[0] eq 'nohandler') {
337                 &main::daemon_log("$session_id ERROR: ClientPackages: no event handler or core function defined for '$header'", 1);
338                 @out_msg_l = ();
339             }  elsif ($out_msg_l[0] eq 'knownclienterror') {
340                 &main::daemon_log("$session_id ERROR: no or more than 1 hits are found at known_clients_db with sql query: '$sql_events'", 1);
341                 &main::daemon_log("$session_id ERROR: processing is aborted and message will not be forwarded", 1);
342                 @out_msg_l = ();
343             } elsif ($out_msg_l[0] eq 'noeventerror') {
344                 &main::daemon_log("$session_id ERROR: client '$target' is not registered for event '$header', processing is aborted", 1); 
345                 @out_msg_l = ();
346             }
351         }
352                 else {
353                         &main::daemon_log("INFO: msg is not for gosa-si-server '$server_address', deliver it to target '$target'", 5);
354                         push(@out_msg_l, $msg);
355                 }
356     }
358     return \@out_msg_l;
362 #===  FUNCTION  ================================================================
363 #         NAME:  new_passwd
364 #   PARAMETERS:  msg_hash - ref - hash from function create_xml_hash
365 #      RETURNS:  nothing
366 #  DESCRIPTION:  process this incoming message
367 #===============================================================================
368 sub new_key {
369     my ($msg_hash) = @_;
370     my @out_msg_l;
371     
372     my $header = @{$msg_hash->{header}}[0];
373     my $source_name = @{$msg_hash->{source}}[0];
374     my $source_key = @{$msg_hash->{new_key}}[0];
375     my $query_res;
377     # check known_clients_db
378     my $sql_statement = "SELECT * FROM known_clients WHERE hostname='$source_name'";
379     $query_res = $main::known_clients_db->select_dbentry( $sql_statement );
380     if( 1 == keys %{$query_res} ) {
381         my $act_time = &get_time;
382         my $sql_statement= "UPDATE known_clients ".
383             "SET hostkey='$source_key', timestamp='$act_time' ".
384             "WHERE hostname='$source_name'";
385         my $res = $main::known_clients_db->update_dbentry( $sql_statement );
386         my $hash = &create_xml_hash("confirm_new_key", $server_address, $source_name);
387         my $out_msg = &create_xml_string($hash);
388         push(@out_msg_l, $out_msg);
389     }
391     # only do if host still not found
392     if( 0 == @out_msg_l ) {
393         # check known_server_db
394         $sql_statement = "SELECT * FROM known_server WHERE hostname='$source_name'";
395         $query_res = $main::known_server_db->select_dbentry( $sql_statement );
396         if( 1 == keys %{$query_res} ) {
397             my $act_time = &get_time;
398             my $sql_statement= "UPDATE known_server ".
399                 "SET hostkey='$source_key', timestamp='$act_time' ".
400                 "WHERE hostname='$source_name'";
401             my $res = $main::known_server_db->update_dbentry( $sql_statement );
403             my $hash = &create_xml_hash("confirm_new_key", $server_address, $source_name);
404             my $out_msg = &create_xml_string($hash);
405             push(@out_msg_l, $out_msg);
406         }
407     }
409     return @out_msg_l;
413 #===  FUNCTION  ================================================================
414 #         NAME:  here_i_am
415 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
416 #      RETURNS:  nothing
417 #  DESCRIPTION:  process this incoming message
418 #===============================================================================
419 sub here_i_am {
420     my ($msg, $msg_hash, $session_id, $ldap_handle) = @_;
421     my @out_msg_l;
422     my $out_hash;
423     my $source = @{$msg_hash->{source}}[0];
424     my $mac_address = @{$msg_hash->{mac_address}}[0];
425         my $gotoHardwareChecksum = @{$msg_hash->{gotoHardwareChecksum}}[0];
426     my $client_status = @{$msg_hash->{client_status}}[0];
427     my $client_revision = @{$msg_hash->{client_revision}}[0];
428     my $key_lifetime = @{$msg_hash->{key_lifetime}}[0];
430     # Move forced hostname to heap - if used
431     #FIXME: move to some global POE namespace - please
432     if ( defined($msg_hash->{'force-hostname'}[0]) &&
433        length($msg_hash->{'force-hostname'}[0]) > 0){
434     #      $heap->{force-hostname}->{$mac_address}= $msg_hash->{'force-hostname'}[0];
435             open (TFILE, ">/var/tmp/$mac_address");
436             print TFILE $msg_hash->{'force-hostname'}[0];
437             close (TFILE); 
438     } else {
439     #      $heap->{force-hostname}->{$mac_address}= undef;
440         if ( -e "/var/tmp/$mac_address") {
441                 unlink("/var/tmp/$mac_address")
442         }; 
443     }
445     # number of known clients
446     my $nu_clients= $main::known_clients_db->count_dbentries('known_clients');
448     # check wether client address or mac address is already known
449     my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$source'";
450     my $db_res= $main::known_clients_db->select_dbentry( $sql_statement );
451     
452     if ( 1 == keys %{$db_res} ) {
453         &main::daemon_log("$session_id WARNING: $source is already known as a client", 1);
454         &main::daemon_log("$session_id WARNING: values for $source are being overwritten", 1);   
455         $nu_clients --;
456     }
458     # number of current active clients
459     my $act_nu_clients = $nu_clients;
461     &main::daemon_log("$session_id INFO: number of current active clients: $act_nu_clients", 5);
462     &main::daemon_log("$session_id INFO: number of maximal allowed clients: $max_clients", 5);
464     if($max_clients <= $act_nu_clients) {
465         my $out_hash = &create_xml_hash("denied", $server_address, $source);
466         &add_content2xml_hash($out_hash, "denied", "I_cannot_take_any_more_clients!");
467         my $passwd = @{$msg_hash->{new_passwd}}[0]; 
468         &send_msg_hash2address($out_hash, $source, $passwd);
469         return;
470     }
471     
472     # new client accepted
473     my $new_passwd = @{$msg_hash->{new_passwd}}[0];
475     # add entry to known_clients_db
476     my $events = @{$msg_hash->{events}}[0];
477     my $act_timestamp = &get_time;
478     my $res = $main::known_clients_db->add_dbentry( {table=>'known_clients', 
479                                                 primkey=>['hostname'],
480                                                 hostname=>$source,
481                                                 events=>$events,
482                                                 macaddress=>$mac_address,
483                                                 status=>'registered',
484                                                 hostkey=>$new_passwd,
485                                                 timestamp=>$act_timestamp,
486                                                 keylifetime=>$key_lifetime,
487                                                 } );
489     if ($res != 0)  {
490         &main::daemon_log("$session_id ERROR: cannot add entry to known_clients: $res");
491         return;
492     }
493     
494     # return acknowledgement to client
495     $out_hash = &create_xml_hash("registered", $server_address, $source);
498     # give the new client his ldap config
499     # Workaround: Send within the registration response, if the client will get an ldap config later
500         my $new_ldap_config_out = &new_ldap_config($source, $session_id, $ldap_handle);
501         if($new_ldap_config_out && (!($new_ldap_config_out =~ /error/))) {
502                 &add_content2xml_hash($out_hash, "ldap_available", "true");
503         } elsif($new_ldap_config_out && $new_ldap_config_out =~ /error/){
504                 &add_content2xml_hash($out_hash, "error", $new_ldap_config_out);
506                 my $sql_statement = "UPDATE $main::job_queue_tn ".
507                 "SET status='error', result='$new_ldap_config_out' ".
508                 "WHERE status='processing' AND macaddress LIKE '$mac_address'";
509                 my $res = $main::job_db->update_dbentry($sql_statement);
510                 &main::daemon_log("$session_id DEBUG: $sql_statement RESULT: $res", 7);         
511         }
512     my $register_out = &create_xml_string($out_hash);
513     push(@out_msg_l, $register_out);
515     # Really send the ldap config
516     if( $new_ldap_config_out && (!($new_ldap_config_out =~ /error/))) {
517             push(@out_msg_l, $new_ldap_config_out);
518     }
520     # Send client hardware configuration
521         my $hardware_config_out = &hardware_config($msg, $msg_hash, $session_id, $ldap_handle);
522         if( $hardware_config_out ) {
523                 push(@out_msg_l, $hardware_config_out);
524         }
526     # Send client ntp server
527     my $ntp_config_out = &new_ntp_config($mac_address, $session_id, $ldap_handle);
528     if ($ntp_config_out) {
529         push(@out_msg_l, $ntp_config_out);
530     }
532     # Send client syslog server
533     my $syslog_config_out = &new_syslog_config($mac_address, $session_id, $ldap_handle);
534     if ($syslog_config_out) {
535         push(@out_msg_l, $syslog_config_out);
536     }
538     # notify registered client to all other server
539     my %mydata = ( 'client' => $source, 'macaddress' => $mac_address);
540     my $mymsg = &build_msg('new_foreign_client', $main::server_address, "KNOWN_SERVER", \%mydata);
541     push(@out_msg_l, $mymsg);
543     &main::daemon_log("$session_id INFO: register client $source ($mac_address)", 5);
544     &main::daemon_log("$session_id INFO: client version: $client_status - $client_revision", 5); 
545     return @out_msg_l;
549 #===  FUNCTION  ================================================================
550 #         NAME:  who_has
551 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
552 #      RETURNS:  nothing 
553 #  DESCRIPTION:  process this incoming message
554 #===============================================================================
555 sub who_has {
556     my ($msg_hash) = @_ ;
557     my @out_msg_l;
558     
559     # what is your search pattern
560     my $search_pattern = @{$msg_hash->{who_has}}[0];
561     my $search_element = @{$msg_hash->{$search_pattern}}[0];
562     &main::daemon_log("who_has-msg looking for $search_pattern $search_element", 7);
564     # scanning known_clients for search_pattern
565     my @host_addresses = keys %$main::known_clients;
566     my $known_clients_entries = length @host_addresses;
567     my $host_address;
568     foreach my $host (@host_addresses) {
569         my $client_element = $main::known_clients->{$host}->{$search_pattern};
570         if ($search_element eq $client_element) {
571             $host_address = $host;
572             last;
573         }
574     }
575         
576     # search was successful
577     if (defined $host_address) {
578         my $source = @{$msg_hash->{source}}[0];
579         my $out_hash = &create_xml_hash("who_has_i_do", $server_address, $source, "mac_address");
580         &add_content2xml_hash($out_hash, "mac_address", $search_element);
581         my $out_msg = &create_xml_string($out_hash);
582         push(@out_msg_l, $out_msg);
583     }
584     return @out_msg_l;
588 sub who_has_i_do {
589     my ($msg_hash) = @_ ;
590     my $header = @{$msg_hash->{header}}[0];
591     my $source = @{$msg_hash->{source}}[0];
592     my $search_param = @{$msg_hash->{$header}}[0];
593     my $search_value = @{$msg_hash->{$search_param}}[0];
594     print "\ngot msg $header:\nserver $source has client with $search_param $search_value\n";
598 sub new_syslog_config {
599     my ($mac_address, $session_id, $ldap_handle) = @_;
600     my $syslog_msg;
602         # Perform search
603     my $ldap_res = $ldap_handle->search( base   => $ldap_base,
604                 scope  => 'sub',
605                 attrs => ['gotoSyslogServer'],
606                 filter => "(&(objectClass=GOhard)(macaddress=$mac_address))");
607         if($ldap_res->code) {
608                 &main::daemon_log("$session_id ".$ldap_res->error, 1);
609                 return;
610         }
612         # Sanity check
613         if ($ldap_res->count != 1) {
614                 &main::daemon_log("$session_id ERROR: client with mac address $mac_address not found/unique/active - not sending syslog config".
615                 "\n\tbase: $ldap_base".
616                 "\n\tscope: sub".
617                 "\n\tattrs: gotoSyslogServer".
618                 "\n\tfilter: (&(objectClass=GOhard)(macaddress=$mac_address))", 1);
619                 return;
620         }
622         my $entry= $ldap_res->entry(0);
623     my $filter_dn = &Net::LDAP::Util::escape_filter_value($entry->dn);
624         my $syslog_server = $entry->get_value("gotoSyslogServer");
626     # If no syslog server is specified at host, just have a look at the object group of the host
627     # Perform object group search
628     if (not defined $syslog_server) {
629         my $ldap_res = $ldap_handle->search( base   => $ldap_base,
630                 scope  => 'sub',
631                 attrs => ['gotoSyslogServer'],
632                 filter => "(&(objectClass=gosaGroupOfNames)(member=$filter_dn))");
633         if($ldap_res->code) {
634             &main::daemon_log("$session_id ".$ldap_res->error, 1);
635             return;
636         }
638         # Sanity check
639         if ($ldap_res->count != 1) {
640             &main::daemon_log("$session_id ERROR: client with mac address $mac_address not found/unique/active - not sending syslog config".
641                     "\n\tbase: $ldap_base".
642                     "\n\tscope: sub".
643                     "\n\tattrs: gotoSyslogServer".
644                     "\n\tfilter: (&(objectClass=gosaGroupOfNames)(member=$filter_dn))", 1);
645             return;
646         }
648         my $entry= $ldap_res->entry(0);
649         $syslog_server= $entry->get_value("gotoSyslogServer");
650     }
652     # Return if no syslog server specified
653     if (not defined $syslog_server) {
654         &main::daemon_log("$session_id WARNING: no syslog server specified for this host '$mac_address'", 3);
655         return;
656     }
658  
659     # Add syslog server to 'syslog_config' message
660     my $syslog_msg_hash = &create_xml_hash("new_syslog_config", $server_address, $mac_address);
661     &add_content2xml_hash($syslog_msg_hash, "server", $syslog_server);
663     return &create_xml_string($syslog_msg_hash);
667 sub new_ntp_config {
668     my ($address, $session_id, $ldap_handle) = @_;
669     my $ntp_msg;
671         # Perform search
672     my $ldap_res = $ldap_handle->search( base   => $ldap_base,
673                 scope  => 'sub',
674                 attrs => ['gotoNtpServer'],
675                 filter => "(&(objectClass=GOhard)(macaddress=$address))");
676         if($ldap_res->code) {
677                 &main::daemon_log("$session_id ".$ldap_res->error, 1);
678                 return;
679         }
681         # Sanity check
682         if ($ldap_res->count != 1) {
683                 &main::daemon_log("$session_id ERROR: client with mac address $address not found/unique/active - not sending ntp config".
684                 "\n\tbase: $ldap_base".
685                 "\n\tscope: sub".
686                 "\n\tattrs: gotoNtpServer".
687                 "\n\tfilter: (&(objectClass=GOhard)(macaddress=$address))", 1);
688                 return;
689         }
691         my $entry= $ldap_res->entry(0);
692     my $filter_dn = &Net::LDAP::Util::escape_filter_value($entry->dn);
693         my @ntp_servers= $entry->get_value("gotoNtpServer");
695     # If no ntp server is specified at host, just have a look at the object group of the host
696     # Perform object group search
697     if ((not @ntp_servers) || (@ntp_servers == 0)) {
698         my $ldap_res = $ldap_handle->search( base   => $ldap_base,
699                 scope  => 'sub',
700                 attrs => ['gotoNtpServer'],
701                 filter => "(&(objectClass=gosaGroupOfNames)(member=$filter_dn))");
702         if($ldap_res->code) {
703             &main::daemon_log("$session_id ".$ldap_res->error, 1);
704             return;
705         }
707         # Sanity check
708         if ($ldap_res->count != 1) {
709             &main::daemon_log("$session_id ERROR: client with mac address $address not found/unique/active - not sending ntp config".
710                     "\n\tbase: $ldap_base".
711                     "\n\tscope: sub".
712                     "\n\tattrs: gotoNtpServer".
713                     "\n\tfilter: (&(objectClass=gosaGroupOfNames)(member=$filter_dn))", 1);
714             return;
715         }
717         my $entry= $ldap_res->entry(0);
718         @ntp_servers= $entry->get_value("gotoNtpServer");
719     }
721     # Return if no ntp server specified
722     if ((not @ntp_servers) || (@ntp_servers == 0)) {
723         &main::daemon_log("$session_id WARNING: no ntp server specified for this host '$address'", 3);
724         return;
725     }
726  
727     # Add each ntp server to 'ntp_config' message
728     my $ntp_msg_hash = &create_xml_hash("new_ntp_config", $server_address, $address);
729     foreach my $ntp_server (@ntp_servers) {
730         &add_content2xml_hash($ntp_msg_hash, "server", $ntp_server);
731     }
733     return &create_xml_string($ntp_msg_hash);
737 #===  FUNCTION  ================================================================
738 #         NAME:  new_ldap_config
739 #   PARAMETERS:  address - string - ip address and port of a host
740 #      RETURNS:  gosa-si conform message
741 #  DESCRIPTION:  send to address the ldap configuration found for dn gotoLdapServer
742 #===============================================================================
743 sub new_ldap_config {
744         my ($address, $session_id, $ldap_handle) = @_ ;
746         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address' OR macaddress LIKE '$address'";
747         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
749         # check hit
750         my $hit_counter = keys %{$res};
751         if( not $hit_counter == 1 ) {
752                 &main::daemon_log("$session_id ERROR: more or no hit found in known_clients_db by query '$sql_statement'", 1);
753         }
755     $address = $res->{1}->{hostname};
756         my $macaddress = $res->{1}->{macaddress};
757         my $hostkey = $res->{1}->{hostkey};
759         if (not defined $macaddress) {
760                 &main::daemon_log("$session_id ERROR: no mac address found for client $address", 1);
761                 return;
762         }
764         # Perform search
765     $mesg = $ldap_handle->search( base   => $ldap_base,
766                 scope  => 'sub',
767                 attrs => ['dn', 'gotoLdapServer', 'gosaUnitTag', 'FAIclass'],
768                 filter => "(&(objectClass=GOhard)(macaddress=$macaddress))");
769         if($mesg->code) {
770                 &main::daemon_log("$session_id ".$mesg->error, 1);
771                 return;
772         }
774         # Sanity check
775         if ($mesg->count != 1) {
776                 &main::daemon_log("$session_id ERROR: client with mac address $macaddress not found/unique/active - not sending ldap config".
777                 "\n\tbase: $ldap_base".
778                 "\n\tscope: sub".
779                 "\n\tattrs: dn, gotoLdapServer".
780                 "\n\tfilter: (&(objectClass=GOhard)(macaddress=$macaddress))", 1);
781                 return;
782         }
784         my $entry= $mesg->entry(0);
785         my $filter_dn= &Net::LDAP::Util::escape_filter_value($entry->dn);
786         my @servers= $entry->get_value("gotoLdapServer");
787         my $unit_tag= $entry->get_value("gosaUnitTag");
788         my @ldap_uris;
789         my $server;
790         my $base;
791         my $release;
792     my $dn= $entry->dn;
794         # Fill release if available
795         my $FAIclass= $entry->get_value("FAIclass");
796         if (defined $FAIclass && $FAIclass =~ /^.* :([A-Za-z0-9\/.]+).*$/) {
797                 $release= $1;
798         }
800         # Do we need to look at an object class?
801         if (not @servers){
802                 $mesg = $ldap_handle->search( base   => $ldap_base,
803                         scope  => 'sub',
804                         attrs => ['dn', 'gotoLdapServer', 'FAIclass'],
805                         filter => "(&(objectClass=gosaGroupOfNames)(member=$filter_dn))");
806                 if($mesg->code) {
807                         &main::daemon_log("$session_id ERROR: unable to search for '(&(objectClass=gosaGroupOfNames)(member=$filter_dn))': ".$mesg->error, 1);
808                         return;
809                 }
811                 # Sanity check
812         if ($mesg->count != 1) {
813             &main::daemon_log("$session_id ERROR: client with mac address $macaddress not found/unique/active - not sending ldap config".
814                     "\n\tbase: $ldap_base".
815                     "\n\tscope: sub".
816                     "\n\tattrs: dn, gotoLdapServer, FAIclass".
817                     "\n\tfilter: (&(objectClass=gosaGroupOfNames)(member=$filter_dn))", 1);
818             return;
819         }
821                 $entry= $mesg->entry(0);
822                 $dn= $entry->dn;
823                 @servers= $entry->get_value("gotoLdapServer");
825                 if (not defined $release){
826                         $FAIclass= $entry->get_value("FAIclass");
827                         if (defined $FAIclass && $FAIclass =~ /^.* :([A-Za-z0-9\/.]+).*$/) {
828                                 $release= $1;
829                         }
830                 }
831         }
833         @servers= sort (@servers);
835     # complain if no ldap information found
836     if (@servers == 0) {
837         &main::daemon_log("$session_id ERROR: no gotoLdapServer information for LDAP entry '$dn'", 1);
838     }
840         foreach $server (@servers){
841                 # Conversation for backward compatibility
842                 if (not $server =~ /^\d+:[^:]+:ldap[^:]*:\/\// ) {
843                     if ($server =~ /^([^:]+):([^:]+)$/ ) {
844                       $server= "1:dummy:ldap://$1/$2";
845                     } elsif ($server =~ /^(\d+):([^:]+):(.*)$/ ) {
846                       $server= "$1:dummy:ldap://$2/$3";
847                     }
848                 }
850                 $base= $server;
851                 $server =~ s%^[^:]+:[^:]+:(ldap.*://[^/]+)/.*$%$1%;
852                 $base =~ s%^[^:]+:[^:]+:ldap.*://[^/]+/(.*)$%$1%;
853                 push (@ldap_uris, $server);
854         }
856         # Assemble data package
857         my %data = ( 'ldap_uri'  => \@ldap_uris, 'ldap_base' => $base,
858                 'ldap_cfg' => \@ldap_cfg, 'pam_cfg' => \@pam_cfg,'nss_cfg' => \@nss_cfg );
859         if (defined $release){
860                 $data{'release'}= $release;
861         }
863         # Need to append GOto settings?
864         if (defined $goto_admin and defined $goto_secret){
865                 $data{'goto_admin'}= $goto_admin;
866                 $data{'goto_secret'}= $goto_secret;
867         }
869         # Append unit tag if needed
870         if (defined $unit_tag){
872                 # Find admin base and department name
873                 $mesg = $ldap_handle->search( base   => $ldap_base,
874                         scope  => 'sub',
875                         attrs => ['dn', 'ou'],
876                         filter => "(&(objectClass=gosaAdministrativeUnit)(gosaUnitTag=$unit_tag))");
877                 #$mesg->code && die $mesg->error;
878                 if($mesg->code) {
879                         &main::daemon_log($mesg->error, 1);
880                         return "error-unit-tag-count-0";
881                 }
883                 # Sanity check
884                 if ($mesg->count != 1) {
885                         &main::daemon_log("WARNING: cannot find administrative unit for client with tag $unit_tag", 1);
886                         return "error-unit-tag-count-".$mesg->count;
887                 }
889                 $entry= $mesg->entry(0);
890                 $data{'admin_base'}= $entry->dn;
891                 $data{'department'}= $entry->get_value("ou");
893                 # Append unit Tag
894                 $data{'unit_tag'}= $unit_tag;
895         }
897         # Send information
898         return &build_msg("new_ldap_config", $server_address, $address, \%data);
902 #===  FUNCTION  ================================================================
903 #         NAME:  hardware_config
904 #   PARAMETERS:  address - string - ip address and port of a host
905 #      RETURNS:  
906 #  DESCRIPTION:  
907 #===============================================================================
908 sub hardware_config {
909         my ($msg, $msg_hash, $session_id, $ldap_handle) = @_ ;
910         my $address = @{$msg_hash->{source}}[0];
911         my $header = @{$msg_hash->{header}}[0];
912         my $gotoHardwareChecksum = @{$msg_hash->{gotoHardwareChecksum}}[0];
914         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address'";
915         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
917         # check hit
918         my $hit_counter = keys %{$res};
919         if( not $hit_counter == 1 ) {
920                 &main::daemon_log("$session_id ERROR: more or no hit found in known_clients_db by query by '$address'", 1);
921         }
922         my $macaddress = $res->{1}->{macaddress};
923         my $hostkey = $res->{1}->{hostkey};
925         if (not defined $macaddress) {
926                 &main::daemon_log("$session_id ERROR: no mac address found for client $address", 1);
927                 return;
928         }
930         # Perform search
931         $mesg = $ldap_handle->search(
932                 base   => $ldap_base,
933                 scope  => 'sub',
934                 filter => "(&(objectClass=GOhard)(|(macAddress=$macaddress)(dhcpHWaddress=ethernet $macaddress)))"
935         );
937         if($mesg->count() == 0) {
938                 &main::daemon_log("Host was not found in LDAP!", 1);
940                 # set status = hardware_detection at jobqueue if entry exists
941                 # TODO
942                 # resolve plain name for host
943                 my $func_dic = {table=>$main::job_queue_tn,
944                                 primkey=>['macaddress', 'headertag'],
945                                 timestamp=>&get_time,
946                                 status=>'processing',
947                                 result=>'none',
948                                 progress=>'hardware-detection',
949                                 headertag=>'trigger_action_reinstall',
950                                 targettag=>$address,
951                                 xmlmessage=>'none',
952                                 macaddress=>$macaddress,
953                                 plainname=>'none',
954                 siserver=>'localhost',
955                 modified=>'1',
956                 };
957                 my $hd_res = $main::job_db->add_dbentry($func_dic);
958                 &main::daemon_log("$session_id INFO: add '$macaddress' to job queue as an installing job", 5);
959         
960         } else {
961                 my $entry= $mesg->entry(0);
962                 if (defined($entry->get_value("gotoHardwareChecksum"))) {
963                         if (! $entry->get_value("gotoHardwareChecksum") eq $gotoHardwareChecksum) {
964                                 $entry->replace(gotoHardwareChecksum => $gotoHardwareChecksum);
965                                 if($entry->update($ldap_handle)) {
966                                         &main::daemon_log("$session_id INFO: Hardware changed! Detection triggered.", 5);
967                                 }
968                         } else {
969                                 # Nothing to do
970                                 return;
971                         }
972                 } 
973         } 
975         # Assemble data package
976         my %data = ();
978         # Need to append GOto settings?
979         if (defined $goto_admin and defined $goto_secret){
980                 $data{'goto_admin'}= $goto_admin;
981                 $data{'goto_secret'}= $goto_secret;
982         }
984         # Send information
985         return &build_msg("detect_hardware", $server_address, $address, \%data);
988 sub server_matches {
989         my $target = shift;
990         my $target_ip = ($1) if $target =~ /^([0-9\.]*?):.*$/;
991         if(!defined($target_ip) or length($target_ip) == 0) {
992                 return;
993         }
995         my $result = 0;
997         if($server_ip eq $target_ip) {
998                 $result= 1;
999         } elsif ($target_ip eq "0.0.0.0") {
1000                 $result= 1;
1001         } elsif ($server_ip eq "0.0.0.0") {     
1002                 if ($target_ip eq "127.0.0.1") {
1003                         $result= 1;
1004                 } else {
1005                         my $PROC_NET_ROUTE= ('/proc/net/route');
1007                         open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
1008                                 or die "Could not open $PROC_NET_ROUTE";
1010                         my @ifs = <PROC_NET_ROUTE>;
1012                         close(PROC_NET_ROUTE);
1014                         # Eat header line
1015                         shift @ifs;
1016                         chomp @ifs;
1017                         foreach my $line(@ifs) {
1018                                 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
1019                                 my $destination;
1020                                 my $mask;
1021                                 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
1022                                 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
1023                                 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
1024                                 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
1025                                 if(new NetAddr::IP($target_ip)->within(new NetAddr::IP($destination, $mask))) {
1026                                         # destination matches route, save mac and exit
1027                                         $result= 1;
1028                                         last;
1029                                 }
1030                         }
1031                 }
1032         } else {
1033                 &main::daemon_log("Target ip $target_ip does not match Server ip $server_ip",1);
1034         }
1036         return $result;
1039 # vim:ts=4:shiftwidth:expandtab
1040 1;