Code

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