Code

622c8e4279077cba5d1969943cd3732397557b02
[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     }
539     # notify registered client to all other server
540     my %mydata = ( 'client' => $source, 'macaddress' => $mac_address);
541     my $mymsg = &build_msg('new_foreign_client', $main::server_address, "KNOWN_SERVER", \%mydata);
542     push(@out_msg_l, $mymsg);
544     &main::daemon_log("$session_id INFO: register client $source ($mac_address)", 5);
545     &main::daemon_log("$session_id INFO: client version: $client_status - $client_revision", 5); 
546     return @out_msg_l;
550 #===  FUNCTION  ================================================================
551 #         NAME:  who_has
552 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
553 #      RETURNS:  nothing 
554 #  DESCRIPTION:  process this incoming message
555 #===============================================================================
556 sub who_has {
557     my ($msg_hash) = @_ ;
558     my @out_msg_l;
559     
560     # what is your search pattern
561     my $search_pattern = @{$msg_hash->{who_has}}[0];
562     my $search_element = @{$msg_hash->{$search_pattern}}[0];
563     &main::daemon_log("who_has-msg looking for $search_pattern $search_element", 7);
565     # scanning known_clients for search_pattern
566     my @host_addresses = keys %$main::known_clients;
567     my $known_clients_entries = length @host_addresses;
568     my $host_address;
569     foreach my $host (@host_addresses) {
570         my $client_element = $main::known_clients->{$host}->{$search_pattern};
571         if ($search_element eq $client_element) {
572             $host_address = $host;
573             last;
574         }
575     }
576         
577     # search was successful
578     if (defined $host_address) {
579         my $source = @{$msg_hash->{source}}[0];
580         my $out_hash = &create_xml_hash("who_has_i_do", $server_address, $source, "mac_address");
581         &add_content2xml_hash($out_hash, "mac_address", $search_element);
582         my $out_msg = &create_xml_string($out_hash);
583         push(@out_msg_l, $out_msg);
584     }
585     return @out_msg_l;
589 sub who_has_i_do {
590     my ($msg_hash) = @_ ;
591     my $header = @{$msg_hash->{header}}[0];
592     my $source = @{$msg_hash->{source}}[0];
593     my $search_param = @{$msg_hash->{$header}}[0];
594     my $search_value = @{$msg_hash->{$search_param}}[0];
595     print "\ngot msg $header:\nserver $source has client with $search_param $search_value\n";
599 sub new_syslog_config {
600     my ($mac_address, $session_id) = @_;
601     my $syslog_msg;
603         # Build LDAP connection
604     my $ldap_handle = &main::get_ldap_handle($session_id);
605         if( not defined $ldap_handle ) {
606                 &main::daemon_log("$session_id ERROR: cannot connect to ldap: $ldap_uri", 1);
607                 return;
608         }
610         # Perform search
611     my $ldap_res = $ldap_handle->search( base   => $ldap_base,
612                 scope  => 'sub',
613                 attrs => ['gotoSyslogServer'],
614                 filter => "(&(objectClass=GOhard)(macaddress=$mac_address))");
615         if($ldap_res->code) {
616                 &main::daemon_log("$session_id ".$ldap_res->error, 1);
617                 return;
618         }
620         # Sanity check
621         if ($ldap_res->count != 1) {
622                 &main::daemon_log("$session_id ERROR: client with mac address $mac_address not found/unique/active - not sending syslog config".
623                 "\n\tbase: $ldap_base".
624                 "\n\tscope: sub".
625                 "\n\tattrs: gotoSyslogServer".
626                 "\n\tfilter: (&(objectClass=GOhard)(macaddress=$mac_address))", 1);
627                 return;
628         }
630         my $entry= $ldap_res->entry(0);
631     my $filter_dn = &Net::LDAP::Util::escape_filter_value($entry->dn);
632         my $syslog_server = $entry->get_value("gotoSyslogServer");
634     # If no syslog server is specified at host, just have a look at the object group of the host
635     # Perform object group search
636     if (not defined $syslog_server) {
637         my $ldap_res = $ldap_handle->search( base   => $ldap_base,
638                 scope  => 'sub',
639                 attrs => ['gotoSyslogServer'],
640                 filter => "(&(objectClass=gosaGroupOfNames)(member=$filter_dn))");
641         if($ldap_res->code) {
642             &main::daemon_log("$session_id ".$ldap_res->error, 1);
643             return;
644         }
646         # Sanity check
647         if ($ldap_res->count != 1) {
648             &main::daemon_log("$session_id ERROR: client with mac address $mac_address not found/unique/active - not sending syslog config".
649                     "\n\tbase: $ldap_base".
650                     "\n\tscope: sub".
651                     "\n\tattrs: gotoSyslogServer".
652                     "\n\tfilter: (&(objectClass=gosaGroupOfNames)(member=$filter_dn))", 1);
653             return;
654         }
656         my $entry= $ldap_res->entry(0);
657         $syslog_server= $entry->get_value("gotoSyslogServer");
658     }
660     # Return if no syslog server specified
661     if (not defined $syslog_server) {
662         &main::daemon_log("$session_id WARNING: no syslog server specified for this host '$mac_address'", 3);
663         return;
664     }
666  
667     # Add syslog server to 'syslog_config' message
668     my $syslog_msg_hash = &create_xml_hash("new_syslog_config", $server_address, $mac_address);
669     &add_content2xml_hash($syslog_msg_hash, "server", $syslog_server);
671     return &create_xml_string($syslog_msg_hash);
675 sub new_ntp_config {
676     my ($address, $session_id) = @_;
677     my $ntp_msg;
679         # Build LDAP connection
680     my $ldap_handle = &main::get_ldap_handle($session_id);
681         if( not defined $ldap_handle ) {
682                 &main::daemon_log("$session_id ERROR: cannot connect to ldap: $ldap_uri", 1);
683                 return;
684         }
686         # Perform search
687     my $ldap_res = $ldap_handle->search( base   => $ldap_base,
688                 scope  => 'sub',
689                 attrs => ['gotoNtpServer'],
690                 filter => "(&(objectClass=GOhard)(macaddress=$address))");
691         if($ldap_res->code) {
692                 &main::daemon_log("$session_id ".$ldap_res->error, 1);
693                 return;
694         }
696         # Sanity check
697         if ($ldap_res->count != 1) {
698                 &main::daemon_log("$session_id ERROR: client with mac address $address not found/unique/active - not sending ntp config".
699                 "\n\tbase: $ldap_base".
700                 "\n\tscope: sub".
701                 "\n\tattrs: gotoNtpServer".
702                 "\n\tfilter: (&(objectClass=GOhard)(macaddress=$address))", 1);
703                 return;
704         }
706         my $entry= $ldap_res->entry(0);
707     my $filter_dn = &Net::LDAP::Util::escape_filter_value($entry->dn);
708         my @ntp_servers= $entry->get_value("gotoNtpServer");
710     # If no ntp server is specified at host, just have a look at the object group of the host
711     # Perform object group search
712     if ((not @ntp_servers) || (@ntp_servers == 0)) {
713         my $ldap_res = $ldap_handle->search( base   => $ldap_base,
714                 scope  => 'sub',
715                 attrs => ['gotoNtpServer'],
716                 filter => "(&(objectClass=gosaGroupOfNames)(member=$filter_dn))");
717         if($ldap_res->code) {
718             &main::daemon_log("$session_id ".$ldap_res->error, 1);
719             return;
720         }
722         # Sanity check
723         if ($ldap_res->count != 1) {
724             &main::daemon_log("$session_id ERROR: client with mac address $address not found/unique/active - not sending ntp config".
725                     "\n\tbase: $ldap_base".
726                     "\n\tscope: sub".
727                     "\n\tattrs: gotoNtpServer".
728                     "\n\tfilter: (&(objectClass=gosaGroupOfNames)(member=$filter_dn))", 1);
729             return;
730         }
732         my $entry= $ldap_res->entry(0);
733         @ntp_servers= $entry->get_value("gotoNtpServer");
734     }
736     # Return if no ntp server specified
737     if ((not @ntp_servers) || (@ntp_servers == 0)) {
738         &main::daemon_log("$session_id WARNING: no ntp server specified for this host '$address'", 3);
739         return;
740     }
741  
742     # Add each ntp server to 'ntp_config' message
743     my $ntp_msg_hash = &create_xml_hash("new_ntp_config", $server_address, $address);
744     foreach my $ntp_server (@ntp_servers) {
745         &add_content2xml_hash($ntp_msg_hash, "server", $ntp_server);
746     }
748     return &create_xml_string($ntp_msg_hash);
752 #===  FUNCTION  ================================================================
753 #         NAME:  new_ldap_config
754 #   PARAMETERS:  address - string - ip address and port of a host
755 #      RETURNS:  gosa-si conform message
756 #  DESCRIPTION:  send to address the ldap configuration found for dn gotoLdapServer
757 #===============================================================================
758 sub new_ldap_config {
759         my ($address, $session_id) = @_ ;
761         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address' OR macaddress LIKE '$address'";
762         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
764         # check hit
765         my $hit_counter = keys %{$res};
766         if( not $hit_counter == 1 ) {
767                 &main::daemon_log("$session_id ERROR: more or no hit found in known_clients_db by query '$sql_statement'", 1);
768                 return;
769         }
771     $address = $res->{1}->{hostname};
772         my $macaddress = $res->{1}->{macaddress};
773         my $hostkey = $res->{1}->{hostkey};
775         if (not defined $macaddress) {
776                 &main::daemon_log("$session_id ERROR: no mac address found for client $address", 1);
777                 return;
778         }
780         # Build LDAP connection
781     my $ldap_handle = &main::get_ldap_handle($session_id);
782         if( not defined $ldap_handle ) {
783                 &main::daemon_log("$session_id ERROR: cannot connect to ldap: $ldap_uri", 1);
784                 return;
785         } 
787         # Perform search
788     $mesg = $ldap_handle->search( base   => $ldap_base,
789                 scope  => 'sub',
790                 attrs => ['dn', 'gotoLdapServer', 'gosaUnitTag', 'FAIclass'],
791                 filter => "(&(objectClass=GOhard)(macaddress=$macaddress))");
792         if($mesg->code) {
793                 &main::daemon_log("$session_id ".$mesg->error, 1);
794                 return;
795         }
797         # Sanity check
798         if ($mesg->count != 1) {
799                 &main::daemon_log("$session_id ERROR: client with mac address $macaddress not found/unique/active - not sending ldap config".
800                 "\n\tbase: $ldap_base".
801                 "\n\tscope: sub".
802                 "\n\tattrs: dn, gotoLdapServer".
803                 "\n\tfilter: (&(objectClass=GOhard)(macaddress=$macaddress))", 1);
804                 return;
805         }
807         my $entry= $mesg->entry(0);
808         my $filter_dn= &Net::LDAP::Util::escape_filter_value($entry->dn);
809         my @servers= $entry->get_value("gotoLdapServer");
810         my $unit_tag= $entry->get_value("gosaUnitTag");
811         my @ldap_uris;
812         my $server;
813         my $base;
814         my $release;
815     my $dn= $entry->dn;
817         # Fill release if available
818         my $FAIclass= $entry->get_value("FAIclass");
819         if (defined $FAIclass && $FAIclass =~ /^.* :([A-Za-z0-9\/.]+).*$/) {
820                 $release= $1;
821         }
823         # Do we need to look at an object class?
824         if (not @servers){
825                 $mesg = $ldap_handle->search( base   => $ldap_base,
826                         scope  => 'sub',
827                         attrs => ['dn', 'gotoLdapServer', 'FAIclass'],
828                         filter => "(&(objectClass=gosaGroupOfNames)(member=$filter_dn))");
829                 if($mesg->code) {
830                         &main::daemon_log("$session_id ERROR: unable to search for '(&(objectClass=gosaGroupOfNames)(member=$filter_dn))': ".$mesg->error, 1);
831                         return;
832                 }
834                 # Sanity check
835         if ($mesg->count != 1) {
836             &main::daemon_log("$session_id ERROR: client with mac address $macaddress not found/unique/active - not sending ldap config".
837                     "\n\tbase: $ldap_base".
838                     "\n\tscope: sub".
839                     "\n\tattrs: dn, gotoLdapServer, FAIclass".
840                     "\n\tfilter: (&(objectClass=gosaGroupOfNames)(member=$filter_dn))", 1);
841             return;
842         }
844                 $entry= $mesg->entry(0);
845                 $dn= $entry->dn;
846                 @servers= $entry->get_value("gotoLdapServer");
848                 if (not defined $release){
849                         $FAIclass= $entry->get_value("FAIclass");
850                         if (defined $FAIclass && $FAIclass =~ /^.* :([A-Za-z0-9\/.]+).*$/) {
851                                 $release= $1;
852                         }
853                 }
854         }
856         @servers= sort (@servers);
858     # complain if no ldap information found
859     if (@servers == 0) {
860         &main::daemon_log("$session_id ERROR: no gotoLdapServer information for LDAP entry '$dn'", 1);
861     }
863         foreach $server (@servers){
864                 # Conversation for backward compatibility
865                 if (not $server =~ /^\d+:[^:]+:ldap[^:]*:\/\// ) {
866                     if ($server =~ /^([^:]+):([^:]+)$/ ) {
867                       $server= "1:dummy:ldap://$1/$2";
868                     } elsif ($server =~ /^(\d+):([^:]+):(.*)$/ ) {
869                       $server= "$1:dummy:ldap://$2/$3";
870                     }
871                 }
873                 $base= $server;
874                 $server =~ s%^[^:]+:[^:]+:(ldap.*://[^/]+)/.*$%$1%;
875                 $base =~ s%^[^:]+:[^:]+:ldap.*://[^/]+/(.*)$%$1%;
876                 push (@ldap_uris, $server);
877         }
879         # Assemble data package
880         my %data = ( 'ldap_uri'  => \@ldap_uris, 'ldap_base' => $base,
881                 'ldap_cfg' => \@ldap_cfg, 'pam_cfg' => \@pam_cfg,'nss_cfg' => \@nss_cfg );
882         if (defined $release){
883                 $data{'release'}= $release;
884         }
886         # Need to append GOto settings?
887         if (defined $goto_admin and defined $goto_secret){
888                 $data{'goto_admin'}= $goto_admin;
889                 $data{'goto_secret'}= $goto_secret;
890         }
892         # Append unit tag if needed
893         if (defined $unit_tag){
895                 # Find admin base and department name
896                 $mesg = $ldap_handle->search( base   => $ldap_base,
897                         scope  => 'sub',
898                         attrs => ['dn', 'ou'],
899                         filter => "(&(objectClass=gosaAdministrativeUnit)(gosaUnitTag=$unit_tag))");
900                 #$mesg->code && die $mesg->error;
901                 if($mesg->code) {
902                         &main::daemon_log($mesg->error, 1);
903                         return "error-unit-tag-count-0";
904                 }
906                 # Sanity check
907                 if ($mesg->count != 1) {
908                         &main::daemon_log("WARNING: cannot find administrative unit for client with tag $unit_tag", 1);
909                         return "error-unit-tag-count-".$mesg->count;
910                 }
912                 $entry= $mesg->entry(0);
913                 $data{'admin_base'}= $entry->dn;
914                 $data{'department'}= $entry->get_value("ou");
916                 # Append unit Tag
917                 $data{'unit_tag'}= $unit_tag;
918         }
920         # Send information
921         return &build_msg("new_ldap_config", $server_address, $address, \%data);
925 #===  FUNCTION  ================================================================
926 #         NAME:  hardware_config
927 #   PARAMETERS:  address - string - ip address and port of a host
928 #      RETURNS:  
929 #  DESCRIPTION:  
930 #===============================================================================
931 sub hardware_config {
932         my ($msg, $msg_hash, $session_id) = @_ ;
933         my $address = @{$msg_hash->{source}}[0];
934         my $header = @{$msg_hash->{header}}[0];
935         my $gotoHardwareChecksum = @{$msg_hash->{gotoHardwareChecksum}}[0];
937         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address'";
938         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
940         # check hit
941         my $hit_counter = keys %{$res};
942         if( not $hit_counter == 1 ) {
943                 &main::daemon_log("$session_id ERROR: more or no hit found in known_clients_db by query by '$address'", 1);
944         }
945         my $macaddress = $res->{1}->{macaddress};
946         my $hostkey = $res->{1}->{hostkey};
948         if (not defined $macaddress) {
949                 &main::daemon_log("$session_id ERROR: no mac address found for client $address", 1);
950                 return;
951         }
953         # Build LDAP connection
954     my $ldap_handle = &main::get_ldap_handle($session_id);
955         if( not defined $ldap_handle ) {
956                 &main::daemon_log("$session_id ERROR: cannot connect to ldap: $ldap_uri", 1);
957                 return;
958         } 
960         # Perform search
961         $mesg = $ldap_handle->search(
962                 base   => $ldap_base,
963                 scope  => 'sub',
964                 filter => "(&(objectClass=GOhard)(|(macAddress=$macaddress)(dhcpHWaddress=ethernet $macaddress)))"
965         );
967         if($mesg->count() == 0) {
968                 &main::daemon_log("Host was not found in LDAP!", 1);
970                 # set status = hardware_detection at jobqueue if entry exists
971                 # TODO
972                 # resolve plain name for host
973                 my $func_dic = {table=>$main::job_queue_tn,
974                                 primkey=>['macaddress', 'headertag'],
975                                 timestamp=>&get_time,
976                                 status=>'processing',
977                                 result=>'none',
978                                 progress=>'hardware-detection',
979                                 headertag=>'trigger_action_reinstall',
980                                 targettag=>$address,
981                                 xmlmessage=>'none',
982                                 macaddress=>$macaddress,
983                                 plainname=>'none',
984                 siserver=>'localhost',
985                 modified=>'1',
986                 };
987                 my $hd_res = $main::job_db->add_dbentry($func_dic);
988                 &main::daemon_log("$session_id INFO: add '$macaddress' to job queue as an installing job", 5);
989         
990         } else {
991                 my $entry= $mesg->entry(0);
992                 if (defined($entry->get_value("gotoHardwareChecksum"))) {
993                         if (! $entry->get_value("gotoHardwareChecksum") eq $gotoHardwareChecksum) {
994                                 $entry->replace(gotoHardwareChecksum => $gotoHardwareChecksum);
995                                 if($entry->update($ldap_handle)) {
996                                         &main::daemon_log("$session_id INFO: Hardware changed! Detection triggered.", 5);
997                                 }
998                         } else {
999                                 # Nothing to do
1000                                 return;
1001                         }
1002                 } 
1003         } 
1005         # Assemble data package
1006         my %data = ();
1008         # Need to append GOto settings?
1009         if (defined $goto_admin and defined $goto_secret){
1010                 $data{'goto_admin'}= $goto_admin;
1011                 $data{'goto_secret'}= $goto_secret;
1012         }
1014         # Send information
1015         return &build_msg("detect_hardware", $server_address, $address, \%data);
1018 sub server_matches {
1019         my $target = shift;
1020         my $target_ip = ($1) if $target =~ /^([0-9\.]*?):.*$/;
1021         if(!defined($target_ip) or length($target_ip) == 0) {
1022                 return;
1023         }
1025         my $result = 0;
1027         if($server_ip eq $target_ip) {
1028                 $result= 1;
1029         } elsif ($target_ip eq "0.0.0.0") {
1030                 $result= 1;
1031         } elsif ($server_ip eq "0.0.0.0") {     
1032                 if ($target_ip eq "127.0.0.1") {
1033                         $result= 1;
1034                 } else {
1035                         my $PROC_NET_ROUTE= ('/proc/net/route');
1037                         open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
1038                                 or die "Could not open $PROC_NET_ROUTE";
1040                         my @ifs = <PROC_NET_ROUTE>;
1042                         close(PROC_NET_ROUTE);
1044                         # Eat header line
1045                         shift @ifs;
1046                         chomp @ifs;
1047                         foreach my $line(@ifs) {
1048                                 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
1049                                 my $destination;
1050                                 my $mask;
1051                                 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
1052                                 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
1053                                 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
1054                                 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
1055                                 if(new NetAddr::IP($target_ip)->within(new NetAddr::IP($destination, $mask))) {
1056                                         # destination matches route, save mac and exit
1057                                         $result= 1;
1058                                         last;
1059                                 }
1060                         }
1061                 }
1062         } else {
1063                 &main::daemon_log("Target ip $target_ip does not match Server ip $server_ip",1);
1064         }
1066         return $result;
1069 # vim:ts=4:shiftwidth:expandtab
1070 1;