Code

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