Code

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