Code

Updated properties.
[gosa.git] / gosa-si / modules / ClientPackages.pm
1 package ClientPackages;
3 # 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. 
5 use strict;
6 use warnings;
8 use Exporter;
9 use GOSA::GosaSupportDaemon;
10 use IO::Socket::INET;
11 use XML::Simple;
12 use Data::Dumper;
13 use NetAddr::IP;
14 use Net::LDAP;
15 use Net::LDAP::Util;
16 use Socket;
17 use Net::hostent;
19 our @ISA = ("Exporter");
21 my $event_dir = "/usr/lib/gosa-si/server/ClientPackages";
22 use lib "/usr/lib/gosa-si/server/ClientPackages";
24 BEGIN{}
25 END {}
27 my ($server_ip, $server_port, $ClientPackages_key, $max_clients, $ldap_uri, $ldap_base, $ldap_admin_dn, $ldap_admin_password, $server_interface);
28 my $server;
29 my $network_interface;
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 &local_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 INFO: ClientPackages - $log_line", 5);
67     } else {
68         &main::daemon_log("0 ERROR: ClientPackages - $log_line", 1);
69     }
70 }
71 # build vice versa event_hash, event_name => module
72 my $event2module_hash = {};
73 while (my ($module, $mod_events) = each %$event_hash) {
74     while (my ($event_name, $nothing) = each %$mod_events) {
75         $event2module_hash->{$event_name} = $module;
76     }
78 }
80 # Unit tag can be defined in config
81 if((not defined($main::gosa_unit_tag)) || length($main::gosa_unit_tag) == 0) {
82         # Read gosaUnitTag from LDAP
83         
84     my $ldap_handle = &main::get_ldap_handle(); 
85     if( defined($ldap_handle) ) {
86                 &main::daemon_log("0 INFO: Searching for servers gosaUnitTag with mac address $main::server_mac_address",5);
87                 # Perform search for Unit Tag
88                 $mesg = $ldap_handle->search(
89                         base   => $ldap_base,
90                         scope  => 'sub',
91                         attrs  => ['gosaUnitTag'],
92                         filter => "(macaddress=$main::server_mac_address)"
93                 );
95                 if ((! $main::server_mac_address eq "00:00:00:00:00:00") and $mesg->count == 1) {
96                         my $entry= $mesg->entry(0);
97                         my $unit_tag= $entry->get_value("gosaUnitTag");
98                         $main::ldap_server_dn= $mesg->entry(0)->dn;
99                         if(defined($unit_tag) && length($unit_tag) > 0) {
100                                 &main::daemon_log("0 INFO: Detected gosaUnitTag $unit_tag for creating entries", 5);
101                                 $main::gosa_unit_tag= $unit_tag;
102                         }
103                 } else {
104                         # Perform another search for Unit Tag
105                         my $hostname= `hostname -f`;
106                         chomp($hostname);
107                         &main::daemon_log("0 INFO: Searching for servers gosaUnitTag with hostname $hostname",5);
108                         $mesg = $ldap_handle->search(
109                                 base   => $ldap_base,
110                                 scope  => 'sub',
111                                 attrs  => ['gosaUnitTag'],
112                                 filter => "(&(cn=$hostname)(objectClass=goServer))"
113                         );
114                         if ($mesg->count == 1) {
115                                 my $entry= $mesg->entry(0);
116                                 my $unit_tag= $entry->get_value("gosaUnitTag");
117                                 $main::ldap_server_dn= $mesg->entry(0)->dn;
118                                 if(defined($unit_tag) && length($unit_tag) > 0) {
119                                         &main::daemon_log("0 INFO: Detected gosaUnitTag $unit_tag for creating entries", 5);
120                                         $main::gosa_unit_tag= $unit_tag;
121                                 }
122                         } else {
123                                 # Perform another search for Unit Tag
124                                 $hostname= `hostname -s`;
125                                 chomp($hostname);
126                                 &main::daemon_log("0 INFO: Searching for servers gosaUnitTag with hostname $hostname",5);
127                                 $mesg = $ldap_handle->search(
128                                         base   => $ldap_base,
129                                         scope  => 'sub',
130                                         attrs  => ['gosaUnitTag'],
131                                         filter => "(&(cn=$hostname)(objectClass=goServer))"
132                                 );
133                                 if ($mesg->count == 1) {
134                                         my $entry= $mesg->entry(0);
135                                         my $unit_tag= $entry->get_value("gosaUnitTag");
136                                         $main::ldap_server_dn= $mesg->entry(0)->dn;
137                                         if(defined($unit_tag) && length($unit_tag) > 0) {
138                                                 &main::daemon_log("INFO: Detected gosaUnitTag $unit_tag for creating entries", 5);
139                                                 $main::gosa_unit_tag= $unit_tag;
140                                         }
141                                 } else {
142                                         &main::daemon_log("0 WARNING: No gosaUnitTag detected. Not using gosaUnitTag", 3);
143                                 }
144                         }
145                 }
146         } else {
147                 &main::daemon_log("0 INFO: Using gosaUnitTag from config-file: $main::gosa_unit_tag",5);
148         }
149     &main::release_ldap_handle($ldap_handle);
153 my $server_address = "$server_ip:$server_port";
154 $main::server_address = $server_address;
157   # Check if ou=incoming exists
158   # TODO: This should be transferred to a module init-function
159   my $ldap_handle = &main::get_ldap_handle();
160   if( defined($ldap_handle) ) {
161     &main::daemon_log("0 INFO: Searching for ou=incoming container for new clients", 5);
162     # Perform search
163     my $mesg = $ldap_handle->search(
164       base   => $ldap_base,
165       scope  => 'one',
166       filter => "(&(ou=incoming)(objectClass=organizationalUnit))"
167     );
168     if(not defined($mesg->count) or $mesg->count == 0) {
169             my $incomingou = Net::LDAP::Entry->new();
170             $incomingou->dn('ou=incoming,'.$ldap_base);
171             $incomingou->add('objectClass' => 'organizationalUnit');
172             $incomingou->add('ou' => 'incoming');
173             my $result = $incomingou->update($ldap_handle);
174             if($result->code != 0) {
175                 &main::daemon_log("0 ERROR: Problem adding ou=incoming: '".$result->error()."'!", 1);
176             }
177     }
178   }
179   &main::release_ldap_handle($ldap_handle);
183 ### functions #################################################################
186 sub get_module_info {
187     my @info = ($server_address,
188                 $ClientPackages_key,
189                 $event_hash,
190                 );
191     return \@info;
195 #===  FUNCTION  ================================================================
196 #         NAME:  local_read_configfile
197 #   PARAMETERS:  cfg_file - string -
198 #      RETURNS:  nothing
199 #  DESCRIPTION:  read cfg_file and set variables
200 #===============================================================================
201 sub local_read_configfile {
202     my $cfg;
203     if( defined( $main::cfg_file) && ( (-s $main::cfg_file) > 0 )) {
204         if( -r $main::cfg_file ) {
205             $cfg = Config::IniFiles->new( -file => $main::cfg_file );
206         } else {
207             print STDERR "Couldn't read config file!";
208         }
209     } else {
210         $cfg = Config::IniFiles->new() ;
211     }
212     foreach my $section (keys %cfg_defaults) {
213         foreach my $param (keys %{$cfg_defaults{ $section }}) {
214             my $pinfo = $cfg_defaults{ $section }{ $param };
215             ${@$pinfo[0]} = $cfg->val( $section, $param, @$pinfo[1] );
216         }
217     }
219     # Read non predefined sections
220     my $param;
221     if ($cfg->SectionExists('ldap')){
222                 foreach $param ($cfg->Parameters('ldap')){
223                         push (@ldap_cfg, "$param ".$cfg->val('ldap', $param));
224                 }
225     }
226     if ($cfg->SectionExists('pam_ldap')){
227                 foreach $param ($cfg->Parameters('pam_ldap')){
228                         push (@pam_cfg, "$param ".$cfg->val('pam_ldap', $param));
229                 }
230     }
231     if ($cfg->SectionExists('nss_ldap')){
232                 foreach $param ($cfg->Parameters('nss_ldap')){
233                         push (@nss_cfg, "$param ".$cfg->val('nss_ldap', $param));
234                 }
235     }
236     if ($cfg->SectionExists('goto')){
237         $goto_admin= $cfg->val('goto', 'terminal_admin');
238         $goto_secret= $cfg->val('goto', 'terminal_secret');
239     } else {
240         $goto_admin= undef;
241         $goto_secret= undef;
242     }
247 #===  FUNCTION  ================================================================
248 #         NAME:  get_mac 
249 #   PARAMETERS:  interface name (i.e. eth0)
250 #      RETURNS:  (mac address) 
251 #  DESCRIPTION:  Uses ioctl to get mac address directly from system.
252 #===============================================================================
253 sub get_mac {
254         my $ifreq= shift;
255         my $result;
256         if ($ifreq && length($ifreq) > 0) { 
257                 if($ifreq eq "all") {
258                         $result = "00:00:00:00:00:00";
259                 } else {
260                         my $SIOCGIFHWADDR= 0x8927;     # man 2 ioctl_list
262                         # A configured MAC Address should always override a guessed value
263                         if ($main::server_mac_address and length($main::server_mac_address) > 0) {
264                                 $result= $main::server_mac_address;
265                         }
267                         socket SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('ip')
268                                 or die "socket: $!";
270                         if(ioctl SOCKET, $SIOCGIFHWADDR, $ifreq) {
271                                 my ($if, $mac)= unpack 'h36 H12', $ifreq;
273                                 if (length($mac) > 0) {
274                                         $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])$/;
275                                         $mac= sprintf("%s:%s:%s:%s:%s:%s", $1, $2, $3, $4, $5, $6);
276                                         $result = $mac;
277                                 }
278                         }
279                 }
280         }
281         return $result;
285 #===  FUNCTION  ================================================================
286 #         NAME:  process_incoming_msg
287 #   PARAMETERS:  crypted_msg - string - incoming crypted message
288 #      RETURNS:  nothing
289 #  DESCRIPTION:  handels the proceeded distribution to the appropriated functions
290 #===============================================================================
291 sub process_incoming_msg {
292     my ($msg, $msg_hash, $session_id) = @_ ;
293     my $error = 0;
294     my $host_name;
295     my $host_key;
296     my @out_msg_l = ("nohandler");
297     my $sql_events;
299     # process incoming msg
300     my $header = @{$msg_hash->{header}}[0]; 
301     my $source = @{$msg_hash->{source}}[0]; 
302     my @target_l = @{$msg_hash->{target}};
304     # skip PREFIX
305     $header =~ s/^CLMSG_//;
307     &main::daemon_log("$session_id DEBUG: ClientPackages: msg to process: $header", 26);
309     if( 0 == length @target_l){     
310         &main::daemon_log("$session_id ERROR: no target specified for msg $header", 1);
311         $error++;
312     } elsif( 1 == length @target_l) {
313         my $target = $target_l[0];
314                 if(&server_matches($target, $session_id)) {
315             if ($header eq 'new_key') {
316                 @out_msg_l = &new_key($msg_hash)
317             } elsif ($header eq 'here_i_am') {
318                 @out_msg_l = &here_i_am($msg, $msg_hash, $session_id)
319             } else {
320                 # a event exists with the header as name
321                 if( exists $event2module_hash->{$header} ) {
322                     &main::daemon_log("$session_id DEBUG: found event '$header' at event-module '".$event2module_hash->{$header}."'", 26);
323                     no strict 'refs';
324                     @out_msg_l = &{$event2module_hash->{$header}."::$header"}($msg, $msg_hash, $session_id);
326                 # if no event handler is implemented   
327                 } else {
328                     $sql_events = "SELECT * FROM $main::known_clients_tn WHERE ( (macaddress LIKE '$source') OR (hostname='$source') )"; 
329                     my $res = $main::known_clients_db->select_dbentry( $sql_events );
330                     my $l = keys(%$res);
332                     # set error if no or more than 1 hits are found for sql query
333                     if ( $l != 1) {
334                         @out_msg_l = ('knownclienterror');
336                     # found exact 1 hit in db
337                     } else {
338                         my $client_events = $res->{'1'}->{'events'};
340                         # client is registered for this event, deliver this message to client
341                         $header =~ s/^answer_//;
342                         if ($client_events =~ /,$header,/) {
343                             # answer message finally arrived destination server, so forward messages to GOsa
344                             if ($target eq $main::server_address) {        
345                                 $msg =~ s/<header>answer_/<header>/;
346                                 $msg =~ s/<target>\S+<\/target>/<target>GOSA<\/target>/;
347                             }
348                             @out_msg_l = ( $msg );
350                         # client is not registered for this event, set error
351                         } else {
352                             @out_msg_l = ('noeventerror');
353                         }
354                     }
355                 }
356             }
358             # if delivery not possible raise error and return 
359             if( not defined $out_msg_l[0] ) {
360                 @out_msg_l = ();
361             } elsif( $out_msg_l[0] eq 'nohandler') {
362                 &main::daemon_log("$session_id ERROR: ClientPackages: no event handler or core function defined for '$header'", 1);
363                 @out_msg_l = ();
364             }  elsif ($out_msg_l[0] eq 'knownclienterror') {
365                 &main::daemon_log("$session_id ERROR: no or more than 1 hits are found at known_clients_db with sql query: '$sql_events'", 1);
366                 &main::daemon_log("$session_id ERROR: processing is aborted and message will not be forwarded", 1);
367                 @out_msg_l = ();
368             } elsif ($out_msg_l[0] eq 'noeventerror') {
369                 &main::daemon_log("$session_id ERROR: client '$target' is not registered for event '$header', processing is aborted", 1); 
370                 @out_msg_l = ();
371             }
372         } else {
373                         &main::daemon_log("DEBUG: msg is not for gosa-si-server '$server_address', deliver it to target '$target'", 26);
374                         push(@out_msg_l, $msg);
375                 }
376     }
378     return \@out_msg_l;
382 #===  FUNCTION  ================================================================
383 #         NAME:  new_passwd
384 #   PARAMETERS:  msg_hash - ref - hash from function create_xml_hash
385 #      RETURNS:  nothing
386 #  DESCRIPTION:  process this incoming message
387 #===============================================================================
388 sub new_key {
389     my ($msg_hash) = @_;
390     my @out_msg_l;
391     
392     my $header = @{$msg_hash->{header}}[0];
393     my $source_name = @{$msg_hash->{source}}[0];
394     my $source_key = @{$msg_hash->{new_key}}[0];
395     my $query_res;
397     # check known_clients_db
398     my $sql_statement = "SELECT * FROM known_clients WHERE hostname='$source_name'";
399     $query_res = $main::known_clients_db->select_dbentry( $sql_statement );
400     if( 1 == keys %{$query_res} ) {
401         my $act_time = &get_time;
402         my $sql_statement= "UPDATE known_clients ".
403             "SET hostkey='$source_key', timestamp='$act_time' ".
404             "WHERE hostname='$source_name'";
405         my $res = $main::known_clients_db->update_dbentry( $sql_statement );
406         my $hash = &create_xml_hash("confirm_new_key", $server_address, $source_name);
407         my $out_msg = &create_xml_string($hash);
408         push(@out_msg_l, $out_msg);
409     }
411     # only do if host still not found
412     if( 0 == @out_msg_l ) {
413         # check known_server_db
414         $sql_statement = "SELECT * FROM known_server WHERE hostname='$source_name'";
415         $query_res = $main::known_server_db->select_dbentry( $sql_statement );
416         if( 1 == keys %{$query_res} ) {
417             my $act_time = &get_time;
418             my $sql_statement= "UPDATE known_server ".
419                 "SET hostkey='$source_key', timestamp='$act_time' ".
420                 "WHERE hostname='$source_name'";
421             my $res = $main::known_server_db->update_dbentry( $sql_statement );
423             my $hash = &create_xml_hash("confirm_new_key", $server_address, $source_name);
424             my $out_msg = &create_xml_string($hash);
425             push(@out_msg_l, $out_msg);
426         }
427     }
429     return @out_msg_l;
433 #===  FUNCTION  ================================================================
434 #         NAME:  here_i_am
435 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
436 #      RETURNS:  nothing
437 #  DESCRIPTION:  process this incoming message
438 #===============================================================================
439 sub here_i_am {
440     my ($msg, $msg_hash, $session_id) = @_;
441     my @out_msg_l;
442     my $out_hash;
443     my $source = @{$msg_hash->{source}}[0];
444     my $mac_address = @{$msg_hash->{mac_address}}[0];
445         my $gotoHardwareChecksum = @{$msg_hash->{gotoHardwareChecksum}}[0];
446     my $client_status = @{$msg_hash->{client_status}}[0];
447     my $client_revision = @{$msg_hash->{client_revision}}[0];
448     my $key_lifetime = @{$msg_hash->{key_lifetime}}[0];
450     # Move forced hostname to heap - if used
451     #FIXME: move to some global POE namespace - please
452     if ( defined($msg_hash->{'force-hostname'}[0]) &&
453        length($msg_hash->{'force-hostname'}[0]) > 0){
454     #      $heap->{force-hostname}->{$mac_address}= $msg_hash->{'force-hostname'}[0];
455             open (my $TFILE, ">", "/var/tmp/$mac_address");
456             print $TFILE $msg_hash->{'force-hostname'}[0];
457             close ($TFILE); 
458     } else {
459     #      $heap->{force-hostname}->{$mac_address}= undef;
460         if ( -e "/var/tmp/$mac_address") {
461                 unlink("/var/tmp/$mac_address")
462         }; 
463     }
465     # number of known clients
466     my $nu_clients= $main::known_clients_db->count_dbentries('known_clients');
468     # check wether client address or mac address is already known
469     my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$source'";
470     my $db_res= $main::known_clients_db->select_dbentry( $sql_statement );
471     
472     if ( 1 == keys %{$db_res} ) {
473         &main::daemon_log("$session_id WARNING: $source is already known as a client", 3);
474         &main::daemon_log("$session_id WARNING: values for $source are being overwritten", 3);   
475         $nu_clients --;
476     }
478     # number of current active clients
479     my $act_nu_clients = $nu_clients;
481     &main::daemon_log("$session_id DEBUG: number of current active clients: $act_nu_clients", 26);
482     &main::daemon_log("$session_id DEBUG: number of maximal allowed clients: $max_clients", 26);
484     if($max_clients <= $act_nu_clients) {
485         my $out_hash = &create_xml_hash("denied", $server_address, $source);
486         &add_content2xml_hash($out_hash, "denied", "I_cannot_take_any_more_clients!");
487         my $passwd = @{$msg_hash->{new_passwd}}[0]; 
488         &send_msg_hash2address($out_hash, $source, $passwd);
489         return;
490     }
491     
492     # new client accepted
493     my $new_passwd = @{$msg_hash->{new_passwd}}[0];
495     # add entry to known_clients_db
496     my $events = @{$msg_hash->{events}}[0];
497     my $act_timestamp = &get_time;
498     my $res = $main::known_clients_db->add_dbentry( {table=>'known_clients', 
499                                                 primkey=>['hostname'],
500                                                 hostname=>$source,
501                                                 events=>$events,
502                                                 macaddress=>$mac_address,
503                                                 status=>'registered',
504                                                 hostkey=>$new_passwd,
505                                                 timestamp=>$act_timestamp,
506                                                 keylifetime=>$key_lifetime,
507                                                 } );
509     if ($res != 0)  {
510         &main::daemon_log("$session_id ERROR: cannot add entry to known_clients: $res",1);
511         return;
512     }
513     
514     # return acknowledgement to client
515     $out_hash = &create_xml_hash("registered", $server_address, $source);
517     # give the new client his ldap config
518     # Workaround: Send within the registration response, if the client will get an ldap config later
519         my $new_ldap_config_out = &new_ldap_config($source, $session_id);
520         if($new_ldap_config_out && (!($new_ldap_config_out =~ /error/))) {
521                 &add_content2xml_hash($out_hash, "ldap_available", "true");
522         } elsif($new_ldap_config_out && $new_ldap_config_out =~ /error/){
523                 &add_content2xml_hash($out_hash, "error", $new_ldap_config_out);
525                 my $sql_statement = "UPDATE $main::job_queue_tn ".
526                 "SET status='error', result='$new_ldap_config_out' ".
527                 "WHERE status='processing' AND macaddress LIKE '$mac_address'";
528                 my $res = $main::job_db->update_dbentry($sql_statement);
529                 &main::daemon_log("$session_id DEBUG: $sql_statement RESULT: $res", 26);         
530         }
531     my $register_out = &create_xml_string($out_hash);
532     push(@out_msg_l, $register_out);
534     # Really send the ldap config
535     if( $new_ldap_config_out && (!($new_ldap_config_out =~ /error/))) {
536             push(@out_msg_l, $new_ldap_config_out);
537     }
539     # Send client hardware configuration
540         my $hardware_config_out = &hardware_config($msg, $msg_hash, $session_id);
541         if( $hardware_config_out ) {
542                 push(@out_msg_l, $hardware_config_out);
543         }
545     # Send client ntp server
546     my $ntp_config_out = &new_ntp_config($mac_address, $session_id);
547     if ($ntp_config_out) {
548         push(@out_msg_l, $ntp_config_out);
549     }
551     # Send client syslog server
552     my $syslog_config_out = &new_syslog_config($mac_address, $session_id);
553     if ($syslog_config_out) {
554         push(@out_msg_l, $syslog_config_out);
555     }
557     # update ldap entry if exists
558     my $ldap_handle= &main::get_ldap_handle();
559     my $ldap_res= $ldap_handle->search(
560                 base   => $ldap_base,
561                 scope  => 'sub',
562                 #attrs => ['ipHostNumber'],
563                 filter => "(&(objectClass=GOhard)(macAddress=$mac_address))");
564     if($ldap_res->code) {
565             &main::daemon_log("$session_id ERROR: LDAP Entry for client with mac address $mac_address not found: ".$ldap_res->error, 1);
566     } elsif ($ldap_res->count != 1) {
567             &main::daemon_log("$session_id ERROR: client with mac address $mac_address not found/unique/active - not updating ldap entry".
568                             "\n\tbase: $ldap_base".
569                             "\n\tscope: sub".
570                             "\n\tattrs: ipHostNumber".
571                             "\n\tfilter: (&(objectClass=GOhard)(macaddress=$mac_address))", 1);
572     } else {
573             my $entry= $ldap_res->pop_entry();
574             my $ip_address= $entry->get_value('ipHostNumber');
575             my $source_ip= ($1) if $source =~ /^([0-9\.]*?):[0-9]*$/;
576             if(not defined($ip_address) and defined($source_ip)) {
577                 $entry->add( 'ipHostNumber' => $source_ip );
578                 my $mesg= $entry->update($ldap_handle);
579                 $mesg->code && &main::daemon_log("$session_id ERROR: Updating IP Address for client with mac address $mac_address failed with '".$mesg->mesg()."'", 1);
580             } elsif(defined($source_ip) and not ($source_ip eq $ip_address)) {
581                 $entry->replace( 'ipHostNumber' => $source_ip );
582                 my $mesg= $entry->update($ldap_handle);
583                 $mesg->code && &main::daemon_log("$session_id ERROR: Updating IP Address for client with mac address $mac_address failed with '".$mesg->mesg()."'", 1);
584             } elsif (not defined($source_ip)) {
585                 &main::daemon_log("ERROR: Could not parse source value '$source' perhaps not an ip address?", 1);
586             }
587     }
588     &main::release_ldap_handle($ldap_handle);
590     # notify registered client to all other server
591     my %mydata = ( 'client' => $source, 'macaddress' => $mac_address);
592     my $mymsg = &build_msg('new_foreign_client', $main::server_address, "KNOWN_SERVER", \%mydata);
593     push(@out_msg_l, $mymsg);
595     &main::daemon_log("$session_id INFO: register client $source ($mac_address), $client_status - $client_revision", 5);
596     return @out_msg_l;
600 #===  FUNCTION  ================================================================
601 #         NAME:  who_has
602 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
603 #      RETURNS:  nothing 
604 #  DESCRIPTION:  process this incoming message
605 #===============================================================================
606 sub who_has {
607     my ($msg_hash) = @_ ;
608     my @out_msg_l;
609     
610     # what is your search pattern
611     my $search_pattern = @{$msg_hash->{who_has}}[0];
612     my $search_element = @{$msg_hash->{$search_pattern}}[0];
613     #&main::daemon_log("who_has-msg looking for $search_pattern $search_element", 7);
615     # scanning known_clients for search_pattern
616     my @host_addresses = keys %$main::known_clients;
617     my $known_clients_entries = length @host_addresses;
618     my $host_address;
619     foreach my $host (@host_addresses) {
620         my $client_element = $main::known_clients->{$host}->{$search_pattern};
621         if ($search_element eq $client_element) {
622             $host_address = $host;
623             last;
624         }
625     }
626         
627     # search was successful
628     if (defined $host_address) {
629         my $source = @{$msg_hash->{source}}[0];
630         my $out_hash = &create_xml_hash("who_has_i_do", $server_address, $source, "mac_address");
631         &add_content2xml_hash($out_hash, "mac_address", $search_element);
632         my $out_msg = &create_xml_string($out_hash);
633         push(@out_msg_l, $out_msg);
634     }
635     return @out_msg_l;
639 sub who_has_i_do {
640     my ($msg_hash) = @_ ;
641     my $header = @{$msg_hash->{header}}[0];
642     my $source = @{$msg_hash->{source}}[0];
643     my $search_param = @{$msg_hash->{$header}}[0];
644     my $search_value = @{$msg_hash->{$search_param}}[0];
645     print "\ngot msg $header:\nserver $source has client with $search_param $search_value\n";
649 sub new_syslog_config {
650     my ($mac_address, $session_id) = @_;
651     my $syslog_msg;
652     my $ldap_handle=&main::get_ldap_handle();
654         # Perform search
655     my $ldap_res = $ldap_handle->search( base   => $ldap_base,
656                 scope  => 'sub',
657                 attrs => ['gotoSyslogServer'],
658                 filter => "(&(objectClass=GOhard)(macaddress=$mac_address))");
659         if($ldap_res->code) {
660                 &main::daemon_log("$session_id ERROR: new_syslog_config: ldap search: ".$ldap_res->error, 1);
661         &main::release_ldap_handle($ldap_handle);
662                 return;
663         }
665         # Sanity check
666         if ($ldap_res->count != 1) {
667                 &main::daemon_log("$session_id ERROR: client with mac address $mac_address not found/unique/active - not sending syslog config".
668                 "\n\tbase: $ldap_base".
669                 "\n\tscope: sub".
670                 "\n\tattrs: gotoSyslogServer".
671                 "\n\tfilter: (&(objectClass=GOhard)(macaddress=$mac_address))", 1);
672         &main::release_ldap_handle($ldap_handle);
673                 return;
674         }
676         my $entry= $ldap_res->entry(0);
677     my $filter_dn = &Net::LDAP::Util::escape_filter_value($entry->dn);
678         my $syslog_server = $entry->get_value("gotoSyslogServer");
680     # If no syslog server is specified at host, just have a look at the object group of the host
681     # Perform object group search
682     if (not defined $syslog_server) {
683         my $ldap_res = $ldap_handle->search( base   => $ldap_base,
684                 scope  => 'sub',
685                 attrs => ['gotoSyslogServer'],
686                 filter => "(&(gosaGroupObjects=[W])(objectClass=gosaGroupOfNames)(member=$filter_dn))");
687         if($ldap_res->code) {
688             &main::daemon_log("$session_id ERROR: new_syslog_config: ldap search: ".$ldap_res->error, 1);
689             &main::release_ldap_handle($ldap_handle);
690             return;
691         }
693         # Sanity check
694         if ($ldap_res->count != 1) {
695             &main::daemon_log("$session_id ERROR: client with mac address $mac_address not found/unique/active - not sending syslog config".
696                     "\n\tbase: $ldap_base".
697                     "\n\tscope: sub".
698                     "\n\tattrs: gotoSyslogServer".
699                     "\n\tfilter: (&(gosaGroupObjects=[W])(objectClass=gosaGroupOfNames)(member=$filter_dn))", 1);
700             &main::release_ldap_handle($ldap_handle);
701             return;
702         }
704         my $entry= $ldap_res->entry(0);
705         $syslog_server= $entry->get_value("gotoSyslogServer");
706     }
708     # Return if no syslog server specified
709     if (not defined $syslog_server) {
710         &main::daemon_log("$session_id WARNING: no syslog server specified for this host '$mac_address'", 3);
711         &main::release_ldap_handle($ldap_handle);
712         return;
713     }
715  
716     # Add syslog server to 'syslog_config' message
717     my $syslog_msg_hash = &create_xml_hash("new_syslog_config", $server_address, $mac_address);
718     &add_content2xml_hash($syslog_msg_hash, "server", $syslog_server);
720     &main::release_ldap_handle($ldap_handle);
721     return &create_xml_string($syslog_msg_hash);
725 sub new_ntp_config {
726     my ($address, $session_id) = @_;
727     my $ntp_msg;
728     my $ldap_handle=&main::get_ldap_handle();
730         # Perform search
731     my $ldap_res = $ldap_handle->search( base   => $ldap_base,
732                 scope  => 'sub',
733                 attrs => ['gotoNtpServer'],
734                 filter => "(&(objectClass=GOhard)(macaddress=$address))");
735         if($ldap_res->code) {
736                 &main::daemon_log("$session_id ERROR: new_ntp_config: ldap search: ".$ldap_res->error, 1);
737         &main::release_ldap_handle($ldap_handle);
738                 return;
739         }
741         # Sanity check
742         if ($ldap_res->count != 1) {
743                 &main::daemon_log("$session_id ERROR: client with mac address $address not found/unique/active - not sending ntp config".
744                 "\n\tbase: $ldap_base".
745                 "\n\tscope: sub".
746                 "\n\tattrs: gotoNtpServer".
747                 "\n\tfilter: (&(objectClass=GOhard)(macaddress=$address))", 1);
748         &main::release_ldap_handle($ldap_handle);
749                 return;
750         }
752         my $entry= $ldap_res->entry(0);
753     my $filter_dn = &Net::LDAP::Util::escape_filter_value($entry->dn);
754         my @ntp_servers= $entry->get_value("gotoNtpServer");
756     # If no ntp server is specified at host, just have a look at the object group of the host
757     # Perform object group search
758     if ((not @ntp_servers) || (@ntp_servers == 0)) {
759         my $ldap_res = $ldap_handle->search( base   => $ldap_base,
760                 scope  => 'sub',
761                 attrs => ['gotoNtpServer'],
762                 filter => "(&(gosaGroupObjects=[W])(objectClass=gosaGroupOfNames)(member=$filter_dn))");
763         if($ldap_res->code) {
764             &main::daemon_log("$session_id ERROR: new_ntp_config: ldap search: ".$ldap_res->error, 1);
765             &main::release_ldap_handle($ldap_handle);
766             return;
767         }
769         # Sanity check
770         if ($ldap_res->count != 1) {
771             &main::daemon_log("$session_id ERROR: client with mac address $address not found/unique/active - not sending ntp config".
772                     "\n\tbase: $ldap_base".
773                     "\n\tscope: sub".
774                     "\n\tattrs: gotoNtpServer".
775                     "\n\tfilter: (&(gosaGroupObjects=[W])(objectClass=gosaGroupOfNames)(member=$filter_dn))", 1);
776             &main::release_ldap_handle($ldap_handle);
777             return;
778         }
780         my $entry= $ldap_res->entry(0);
781         @ntp_servers= $entry->get_value("gotoNtpServer");
782     }
784     # Return if no ntp server specified
785     if ((not @ntp_servers) || (@ntp_servers == 0)) {
786         &main::daemon_log("$session_id WARNING: no ntp server specified for this host '$address'", 3);
787         &main::release_ldap_handle($ldap_handle);
788         return;
789     }
790  
791     # Add each ntp server to 'ntp_config' message
792     my $ntp_msg_hash = &create_xml_hash("new_ntp_config", $server_address, $address);
793     foreach my $ntp_server (@ntp_servers) {
794         &add_content2xml_hash($ntp_msg_hash, "server", $ntp_server);
795     }
797     &main::release_ldap_handle($ldap_handle);
798     return &create_xml_string($ntp_msg_hash);
802 #===  FUNCTION  ================================================================
803 #         NAME:  new_ldap_config
804 #   PARAMETERS:  address - string - ip address and port of a host
805 #      RETURNS:  gosa-si conform message
806 #  DESCRIPTION:  send to address the ldap configuration found for dn gotoLdapServer
807 #===============================================================================
808 sub new_ldap_config {
809         my ($address, $session_id) = @_ ;
811         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address' OR macaddress LIKE '$address'";
812         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
814         # check hit
815         my $hit_counter = keys %{$res};
816         if( not $hit_counter == 1 ) {
817                 &main::daemon_log("$session_id ERROR: new_ldap_config: more or no hit found in known_clients_db by query '$sql_statement'", 1);
818         return;
819         }
821     $address = $res->{1}->{hostname};
822         my $macaddress = $res->{1}->{macaddress};
823         my $hostkey = $res->{1}->{hostkey};
824         
825         if (not defined $macaddress) {
826                 &main::daemon_log("$session_id ERROR: new_ldap_config: no mac address found for client $address", 1);
827                 return;
828         }
830         # Perform search
831     my $ldap_handle=&main::get_ldap_handle();
832     $mesg = $ldap_handle->search( base   => $ldap_base,
833                 scope  => 'sub',
834                 attrs => ['dn', 'gotoLdapServer', 'gosaUnitTag', 'FAIclass'],
835                 filter => "(&(objectClass=GOhard)(macaddress=$macaddress))");
836         if($mesg->code) {
837                 &main::daemon_log("$session_id ERROR: new_ldap_config: ldap search: ".$mesg->error, 1);
838         &main::release_ldap_handle($ldap_handle);
839                 return;
840         }
842         # Sanity check
843         if ($mesg->count != 1) {
844                 &main::daemon_log("$session_id ERROR: client with mac address $macaddress not found/unique/active - not sending ldap config".
845                 "\n\tbase: $ldap_base".
846                 "\n\tscope: sub".
847                 "\n\tattrs: dn, gotoLdapServer".
848                 "\n\tfilter: (&(objectClass=GOhard)(macaddress=$macaddress))", 1);
849         &main::release_ldap_handle($ldap_handle);
850                 return;
851         }
853         my $entry= $mesg->entry(0);
854         my $filter_dn= &Net::LDAP::Util::escape_filter_value($entry->dn);
855         my @servers= $entry->get_value("gotoLdapServer");
856         my $unit_tag= $entry->get_value("gosaUnitTag");
857         my @ldap_uris;
858         my $server;
859         my $base;
860         my $release;
861     my $dn= $entry->dn;
863         # Fill release if available
864         my $FAIclass= $entry->get_value("FAIclass");
865         if (defined $FAIclass && $FAIclass =~ /^.* :([A-Za-z0-9\/.]+).*$/) {
866                 $release= $1;
867         }
869         # Do we need to look at an object class?
870         if (not @servers){
871                 $mesg = $ldap_handle->search( base   => $ldap_base,
872                         scope  => 'sub',
873                         attrs => ['dn', 'gotoLdapServer', 'FAIclass'],
874                         filter => "(&(gosaGroupObjects=[W])(objectClass=gosaGroupOfNames)(member=$filter_dn))");
875                 if($mesg->code) {
876                         &main::daemon_log("$session_id ERROR: new_ldap_config: unable to search for '(&(objectClass=gosaGroupOfNames)(member=$filter_dn))': ".$mesg->error, 1);
877             &main::release_ldap_handle($ldap_handle);
878                         return;
879                 }
881                 # Sanity check
882         if ($mesg->count != 1) {
883             &main::daemon_log("$session_id ERROR: new_ldap_config: client with mac address $macaddress not found/unique/active - not sending ldap config".
884                     "\n\tbase: $ldap_base".
885                     "\n\tscope: sub".
886                     "\n\tattrs: dn, gotoLdapServer, FAIclass".
887                     "\n\tfilter: (&(gosaGroupObjects=[W])(objectClass=gosaGroupOfNames)(member=$filter_dn))", 1);
888             &main::release_ldap_handle($ldap_handle);
889             return;
890         }
892                 $entry= $mesg->entry(0);
893                 $dn= $entry->dn;
894                 @servers= $entry->get_value("gotoLdapServer");
896                 if (not defined $release){
897                         $FAIclass= $entry->get_value("FAIclass");
898                         if (defined $FAIclass && $FAIclass =~ /^.* :([A-Za-z0-9\/.]+).*$/) {
899                                 $release= $1;
900                         }
901                 }
902         }
904         @servers= sort (@servers);
906     # complain if no ldap information found
907     if (@servers == 0) {
908         &main::daemon_log("$session_id ERROR: no gotoLdapServer information for LDAP entry '$dn'", 1);
909     }
911         foreach $server (@servers){
912                 # Conversation for backward compatibility
913                 if (not $server =~ /^\d+:[^:]+:ldap[^:]*:\/\// ) {
914                     if ($server =~ /^([^:]+):([^:]+)$/ ) {
915                       $server= "1:dummy:ldap://$1/$2";
916                     } elsif ($server =~ /^(\d+):([^:]+):(.*)$/ ) {
917                       $server= "$1:dummy:ldap://$2/$3";
918                     }
919                 }
921                 $base= $server;
922                 $server =~ s%^[^:]+:[^:]+:(ldap.*://[^/]+)/.*$%$1%;
923                 $base =~ s%^[^:]+:[^:]+:ldap.*://[^/]+/(.*)$%$1%;
924                 push (@ldap_uris, $server);
925         }
927         # Assemble data package
928         my %data = ( 'ldap_uri'  => \@ldap_uris, 'ldap_base' => $base,
929                 'ldap_cfg' => \@ldap_cfg, 'pam_cfg' => \@pam_cfg,'nss_cfg' => \@nss_cfg );
930         if (defined $release){
931                 $data{'release'}= $release;
932         }
934         # Need to append GOto settings?
935         if (defined $goto_admin and defined $goto_secret){
936                 $data{'goto_admin'}= $goto_admin;
937                 $data{'goto_secret'}= $goto_secret;
938         }
940         # Append unit tag if needed
941         if (defined $unit_tag){
943                 # Find admin base and department name
944                 $mesg = $ldap_handle->search( base   => $ldap_base,
945                         scope  => 'sub',
946                         attrs => ['dn', 'ou'],
947                         filter => "(&(objectClass=gosaAdministrativeUnit)(gosaUnitTag=$unit_tag))");
948                 #$mesg->code && die $mesg->error;
949                 if($mesg->code) {
950                         &main::daemon_log("$session_id ERROR: new_ldap_config: ldap search: ".$mesg->error, 1);
951             &main::release_ldap_handle($ldap_handle);
952                         return "error-unit-tag-count-0";
953                 }
955                 # Sanity check
956                 if ($mesg->count != 1) {
957                         &main::daemon_log("WARNING: cannot find administrative unit for client with tag $unit_tag", 3);
958             &main::release_ldap_handle($ldap_handle);
959                         return "error-unit-tag-count-".$mesg->count;
960                 }
962                 $entry= $mesg->entry(0);
963                 $data{'admin_base'}= $entry->dn;
964                 $data{'department'}= $entry->get_value("ou");
966                 # Append unit Tag
967                 $data{'unit_tag'}= $unit_tag;
968         }
969     &main::release_ldap_handle($ldap_handle);
971         # Send information
972         return &build_msg("new_ldap_config", $server_address, $address, \%data);
976 #===  FUNCTION  ================================================================
977 #         NAME:  hardware_config
978 #   PARAMETERS:  address - string - ip address and port of a host
979 #      RETURNS:  
980 #  DESCRIPTION:  
981 #===============================================================================
982 sub hardware_config {
983         my ($msg, $msg_hash, $session_id) = @_ ;
984         my $address = @{$msg_hash->{source}}[0];
985         my $header = @{$msg_hash->{header}}[0];
986         my $gotoHardwareChecksum = @{$msg_hash->{gotoHardwareChecksum}}[0];
988         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address'";
989         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
991         # check hit
992         my $hit_counter = keys %{$res};
993         if( not $hit_counter == 1 ) {
994                 &main::daemon_log("$session_id ERROR: hardware_config: more or no hit found in known_clients_db by query by '$address'", 1);
995         }
996         my $macaddress = $res->{1}->{macaddress};
997         my $hostkey = $res->{1}->{hostkey};
999         if (not defined $macaddress) {
1000                 &main::daemon_log("$session_id ERROR: hardware_config: no mac address found for client $address", 1);
1001                 return;
1002         }
1004         # Perform search
1005     my $ldap_handle=&main::get_ldap_handle();
1006         $mesg = $ldap_handle->search(
1007                 base   => $ldap_base,
1008                 scope  => 'sub',
1009                 filter => "(&(objectClass=GOhard)(|(macAddress=$macaddress)(dhcpHWaddress=ethernet $macaddress)))"
1010         );
1012         if($mesg->count() == 0) {
1013                 &main::daemon_log("$session_id INFO: Host was not found in LDAP!", 5);
1015                 # set status = hardware_detection at jobqueue if entry exists
1016                 # TODO
1017                 # resolve plain name for host
1018                 my $func_dic = {table=>$main::job_queue_tn,
1019                                 primkey=>['macaddress', 'headertag'],
1020                                 timestamp=>&get_time,
1021                                 status=>'processing',
1022                                 result=>'none',
1023                                 progress=>'hardware-detection',
1024                                 headertag=>'trigger_action_reinstall',
1025                                 targettag=>$address,
1026                                 xmlmessage=>'none',
1027                                 macaddress=>$macaddress,
1028                                 plainname=>'none',
1029                 siserver=>'localhost',
1030                 modified=>'1',
1031                 };
1032                 my $hd_res = $main::job_db->add_dbentry($func_dic);
1033                 &main::daemon_log("$session_id INFO: add '$macaddress' to job queue as an installing job", 5);
1034         
1035         } else {
1036                 my $entry= $mesg->entry(0);
1037                 if (defined($entry->get_value("gotoHardwareChecksum"))) {
1038                         if (! ($entry->get_value("gotoHardwareChecksum") eq $gotoHardwareChecksum)) {
1039                                 $entry->replace(gotoHardwareChecksum => $gotoHardwareChecksum);
1040                                 if($entry->update($ldap_handle)) {
1041                                         &main::daemon_log("$session_id INFO: Hardware changed! Detection triggered.", 5);
1042                                 }
1043                         } else {
1044                                 # Nothing to do
1045                 &main::release_ldap_handle($ldap_handle);
1046                                 return;
1047                         }
1048                 } 
1049         } 
1051         # Assemble data package
1052         my %data = ();
1054         # Need to append GOto settings?
1055         if (defined $goto_admin and defined $goto_secret){
1056                 $data{'goto_admin'}= $goto_admin;
1057                 $data{'goto_secret'}= $goto_secret;
1058         }
1060     &main::release_ldap_handle($ldap_handle);
1062         # Send information
1063         return &build_msg("detect_hardware", $server_address, $address, \%data);
1066 sub server_matches {
1067     my ($target, $session_id) = @_ ;
1068         my $target_ip = ($1) if $target =~ /^([0-9\.]*?):.*$/;
1069         if(!defined($target_ip) or length($target_ip) == 0) {
1070                 return;
1071         }
1073         my $result = 0;
1075         if($server_ip eq $target_ip) {
1076                 $result= 1;
1077         } elsif ($target_ip eq "0.0.0.0") {
1078                 $result= 1;
1079         } elsif ($server_ip eq "0.0.0.0") {     
1080                 if ($target_ip eq "127.0.0.1") {
1081                         $result= 1;
1082                 } else {
1083                         my $PROC_NET_ROUTE= ('/proc/net/route');
1085                         open(my $FD_PROC_NET_ROUTE, "<", "$PROC_NET_ROUTE")
1086                                 or die "Could not open $PROC_NET_ROUTE";
1088                         my @ifs = <$FD_PROC_NET_ROUTE>;
1090                         close($FD_PROC_NET_ROUTE);
1092                         # Eat header line
1093                         shift @ifs;
1094                         chomp @ifs;
1095                         foreach my $line(@ifs) {
1096                                 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
1097                                 my $destination;
1098                                 my $mask;
1099                                 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
1100                                 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
1101                                 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
1102                                 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
1103                                 if(new NetAddr::IP($target_ip)->within(new NetAddr::IP($destination, $mask))) {
1104                                         # destination matches route, save mac and exit
1105                                         $result= 1;
1106                                         last;
1107                                 }
1108                         }
1109                 }
1110         } else {
1111                 &main::daemon_log("$session_id INFO: Target ip $target_ip does not match Server ip $server_ip",5);
1112         }
1114         return $result;
1117 # vim:ts=4:shiftwidth:expandtab
1118 1;