Code

cfea9ed8a87b0d787efdd1b471af111fb5d2837b
[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 ($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 }
73 # Unit tag can be defined in config
74 if((not defined($main::gosa_unit_tag)) || length($main::gosa_unit_tag) == 0) {
75         # Read gosaUnitTag from LDAP
76         
77     my $ldap_handle = &main::get_ldap_handle(); 
78     if( defined($ldap_handle) ) {
79                 &main::daemon_log("0 INFO: Searching for servers gosaUnitTag with mac address $main::server_mac_address",5);
80                 # Perform search for Unit Tag
81                 $mesg = $ldap_handle->search(
82                         base   => $ldap_base,
83                         scope  => 'sub',
84                         attrs  => ['gosaUnitTag'],
85                         filter => "(macaddress=$main::server_mac_address)"
86                 );
88                 if ((! $main::server_mac_address eq "00:00:00:00:00:00") and $mesg->count == 1) {
89                         my $entry= $mesg->entry(0);
90                         my $unit_tag= $entry->get_value("gosaUnitTag");
91                         $main::ldap_server_dn= $mesg->entry(0)->dn;
92                         if(defined($unit_tag) && length($unit_tag) > 0) {
93                                 &main::daemon_log("0 INFO: Detected gosaUnitTag $unit_tag for creating entries", 5);
94                                 $main::gosa_unit_tag= $unit_tag;
95                         }
96                 } else {
97                         # Perform another search for Unit Tag
98                         my $hostname= `hostname -f`;
99                         chomp($hostname);
100                         &main::daemon_log("0 INFO: Searching for servers gosaUnitTag with hostname $hostname",5);
101                         $mesg = $ldap_handle->search(
102                                 base   => $ldap_base,
103                                 scope  => 'sub',
104                                 attrs  => ['gosaUnitTag'],
105                                 filter => "(&(cn=$hostname)(objectClass=goServer))"
106                         );
107                         if ($mesg->count == 1) {
108                                 my $entry= $mesg->entry(0);
109                                 my $unit_tag= $entry->get_value("gosaUnitTag");
110                                 $main::ldap_server_dn= $mesg->entry(0)->dn;
111                                 if(defined($unit_tag) && length($unit_tag) > 0) {
112                                         &main::daemon_log("0 INFO: Detected gosaUnitTag $unit_tag for creating entries", 5);
113                                         $main::gosa_unit_tag= $unit_tag;
114                                 }
115                         } else {
116                                 # Perform another search for Unit Tag
117                                 $hostname= `hostname -s`;
118                                 chomp($hostname);
119                                 &main::daemon_log("0 INFO: Searching for servers gosaUnitTag with hostname $hostname",5);
120                                 $mesg = $ldap_handle->search(
121                                         base   => $ldap_base,
122                                         scope  => 'sub',
123                                         attrs  => ['gosaUnitTag'],
124                                         filter => "(&(cn=$hostname)(objectClass=goServer))"
125                                 );
126                                 if ($mesg->count == 1) {
127                                         my $entry= $mesg->entry(0);
128                                         my $unit_tag= $entry->get_value("gosaUnitTag");
129                                         $main::ldap_server_dn= $mesg->entry(0)->dn;
130                                         if(defined($unit_tag) && length($unit_tag) > 0) {
131                                                 &main::daemon_log("INFO: Detected gosaUnitTag $unit_tag for creating entries", 5);
132                                                 $main::gosa_unit_tag= $unit_tag;
133                                         }
134                                 } else {
135                                         &main::daemon_log("0 WARNING: No gosaUnitTag detected. Not using gosaUnitTag", 3);
136                                 }
137                         }
138                 }
139         } else {
140                 &main::daemon_log("0 INFO: Using gosaUnitTag from config-file: $main::gosa_unit_tag",5);
141         }
145 my $server_address = "$server_ip:$server_port";
146 $main::server_address = $server_address;
149 ### functions #################################################################
152 sub get_module_info {
153     my @info = ($server_address,
154                 $ClientPackages_key,
155                 $event_hash,
156                 );
157     return \@info;
161 #===  FUNCTION  ================================================================
162 #         NAME:  local_read_configfile
163 #   PARAMETERS:  cfg_file - string -
164 #      RETURNS:  nothing
165 #  DESCRIPTION:  read cfg_file and set variables
166 #===============================================================================
167 sub local_read_configfile {
168     my $cfg;
169     if( defined( $main::cfg_file) && ( (-s $main::cfg_file) > 0 )) {
170         if( -r $main::cfg_file ) {
171             $cfg = Config::IniFiles->new( -file => $main::cfg_file );
172         } else {
173             print STDERR "Couldn't read config file!";
174         }
175     } else {
176         $cfg = Config::IniFiles->new() ;
177     }
178     foreach my $section (keys %cfg_defaults) {
179         foreach my $param (keys %{$cfg_defaults{ $section }}) {
180             my $pinfo = $cfg_defaults{ $section }{ $param };
181             ${@$pinfo[0]} = $cfg->val( $section, $param, @$pinfo[1] );
182         }
183     }
185     # Read non predefined sections
186     my $param;
187     if ($cfg->SectionExists('ldap')){
188                 foreach $param ($cfg->Parameters('ldap')){
189                         push (@ldap_cfg, "$param ".$cfg->val('ldap', $param));
190                 }
191     }
192     if ($cfg->SectionExists('pam_ldap')){
193                 foreach $param ($cfg->Parameters('pam_ldap')){
194                         push (@pam_cfg, "$param ".$cfg->val('pam_ldap', $param));
195                 }
196     }
197     if ($cfg->SectionExists('nss_ldap')){
198                 foreach $param ($cfg->Parameters('nss_ldap')){
199                         push (@nss_cfg, "$param ".$cfg->val('nss_ldap', $param));
200                 }
201     }
202     if ($cfg->SectionExists('goto')){
203         $goto_admin= $cfg->val('goto', 'terminal_admin');
204         $goto_secret= $cfg->val('goto', 'terminal_secret');
205     } else {
206         $goto_admin= undef;
207         $goto_secret= undef;
208     }
213 #===  FUNCTION  ================================================================
214 #         NAME:  get_mac 
215 #   PARAMETERS:  interface name (i.e. eth0)
216 #      RETURNS:  (mac address) 
217 #  DESCRIPTION:  Uses ioctl to get mac address directly from system.
218 #===============================================================================
219 sub get_mac {
220         my $ifreq= shift;
221         my $result;
222         if ($ifreq && length($ifreq) > 0) { 
223                 if($ifreq eq "all") {
224                         $result = "00:00:00:00:00:00";
225                 } else {
226                         my $SIOCGIFHWADDR= 0x8927;     # man 2 ioctl_list
228                         # A configured MAC Address should always override a guessed value
229                         if ($main::server_mac_address and length($main::server_mac_address) > 0) {
230                                 $result= $main::server_mac_address;
231                         }
233                         socket SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('ip')
234                                 or die "socket: $!";
236                         if(ioctl SOCKET, $SIOCGIFHWADDR, $ifreq) {
237                                 my ($if, $mac)= unpack 'h36 H12', $ifreq;
239                                 if (length($mac) > 0) {
240                                         $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])$/;
241                                         $mac= sprintf("%s:%s:%s:%s:%s:%s", $1, $2, $3, $4, $5, $6);
242                                         $result = $mac;
243                                 }
244                         }
245                 }
246         }
247         return $result;
251 #===  FUNCTION  ================================================================
252 #         NAME:  process_incoming_msg
253 #   PARAMETERS:  crypted_msg - string - incoming crypted message
254 #      RETURNS:  nothing
255 #  DESCRIPTION:  handels the proceeded distribution to the appropriated functions
256 #===============================================================================
257 sub process_incoming_msg {
258     my ($msg, $msg_hash, $session_id) = @_ ;
259     my $error = 0;
260     my $host_name;
261     my $host_key;
262     my @out_msg_l = ("nohandler");
263     my $sql_events;
265     # process incoming msg
266     my $header = @{$msg_hash->{header}}[0]; 
267     my $source = @{$msg_hash->{source}}[0]; 
268     my @target_l = @{$msg_hash->{target}};
270     # skip PREFIX
271     $header =~ s/^CLMSG_//;
273     &main::daemon_log("$session_id DEBUG: ClientPackages: msg to process: $header", 7);
275     if( 0 == length @target_l){     
276         &main::daemon_log("$session_id ERROR: no target specified for msg $header", 1);
277         $error++;
278     }
280     if( 1 == length @target_l) {
281         my $target = $target_l[0];
282                 if(&server_matches($target)) {
283             if ($header eq 'new_key') {
284                 @out_msg_l = &new_key($msg_hash)
285             } elsif ($header eq 'here_i_am') {
286                 @out_msg_l = &here_i_am($msg, $msg_hash, $session_id)
287             } else {
288                 # a event exists with the header as name
289                 if( exists $event_hash->{$header} ) {
290                     &main::daemon_log("$session_id INFO: found event '$header' at event-module '".$event_hash->{$header}."'", 5);
291                     no strict 'refs';
292                     @out_msg_l = &{$event_hash->{$header}."::$header"}($msg, $msg_hash, $session_id);
294                 # if no event handler is implemented   
295                 } else {
296                     $sql_events = "SELECT * FROM $main::known_clients_tn WHERE ( (macaddress LIKE '$source') OR (hostname='$source') )"; 
297                     my $res = $main::known_clients_db->select_dbentry( $sql_events );
298                     my $l = keys(%$res);
300                     # set error if no or more than 1 hits are found for sql query
301                     if ( $l != 1) {
302                         @out_msg_l = ('knownclienterror');
304                     # found exact 1 hit in db
305                     } else {
306                         my $client_events = $res->{'1'}->{'events'};
308                         # client is registered for this event, deliver this message to client
309                         $header =~ s/^answer_//;
310                         if ($client_events =~ /,$header,/) {
311                             # answer message finally arrived destination server, so forward messages to GOsa
312                             if ($target eq $main::server_address) {        
313                                 $msg =~ s/<header>answer_/<header>/;
314                                 $msg =~ s/<target>\S+<\/target>/<target>GOSA<\/target>/;
315                             }
316                             @out_msg_l = ( $msg );
318                         # client is not registered for this event, set error
319                         } else {
320                             @out_msg_l = ('noeventerror');
321                         }
322                     }
323                 }
324             }
326             # if delivery not possible raise error and return 
327             if( not defined $out_msg_l[0] ) {
328                 @out_msg_l = ();
329             } elsif( $out_msg_l[0] eq 'nohandler') {
330                 &main::daemon_log("$session_id ERROR: ClientPackages: no event handler or core function defined for '$header'", 1);
331                 @out_msg_l = ();
332             }  elsif ($out_msg_l[0] eq 'knownclienterror') {
333                 &main::daemon_log("$session_id ERROR: no or more than 1 hits are found at known_clients_db with sql query: '$sql_events'", 1);
334                 &main::daemon_log("$session_id ERROR: processing is aborted and message will not be forwarded", 1);
335                 @out_msg_l = ();
336             } elsif ($out_msg_l[0] eq 'noeventerror') {
337                 &main::daemon_log("$session_id ERROR: client '$target' is not registered for event '$header', processing is aborted", 1); 
338                 @out_msg_l = ();
339             }
344         }
345                 else {
346                         &main::daemon_log("INFO: msg is not for gosa-si-server '$server_address', deliver it to target '$target'", 5);
347                         push(@out_msg_l, $msg);
348                 }
349     }
351     return \@out_msg_l;
355 #===  FUNCTION  ================================================================
356 #         NAME:  new_passwd
357 #   PARAMETERS:  msg_hash - ref - hash from function create_xml_hash
358 #      RETURNS:  nothing
359 #  DESCRIPTION:  process this incoming message
360 #===============================================================================
361 sub new_key {
362     my ($msg_hash) = @_;
363     my @out_msg_l;
364     
365     my $header = @{$msg_hash->{header}}[0];
366     my $source_name = @{$msg_hash->{source}}[0];
367     my $source_key = @{$msg_hash->{new_key}}[0];
368     my $query_res;
370     # check known_clients_db
371     my $sql_statement = "SELECT * FROM known_clients WHERE hostname='$source_name'";
372     $query_res = $main::known_clients_db->select_dbentry( $sql_statement );
373     if( 1 == keys %{$query_res} ) {
374         my $act_time = &get_time;
375         my $sql_statement= "UPDATE known_clients ".
376             "SET hostkey='$source_key', timestamp='$act_time' ".
377             "WHERE hostname='$source_name'";
378         my $res = $main::known_clients_db->update_dbentry( $sql_statement );
379         my $hash = &create_xml_hash("confirm_new_key", $server_address, $source_name);
380         my $out_msg = &create_xml_string($hash);
381         push(@out_msg_l, $out_msg);
382     }
384     # only do if host still not found
385     if( 0 == @out_msg_l ) {
386         # check known_server_db
387         $sql_statement = "SELECT * FROM known_server WHERE hostname='$source_name'";
388         $query_res = $main::known_server_db->select_dbentry( $sql_statement );
389         if( 1 == keys %{$query_res} ) {
390             my $act_time = &get_time;
391             my $sql_statement= "UPDATE known_server ".
392                 "SET hostkey='$source_key', timestamp='$act_time' ".
393                 "WHERE hostname='$source_name'";
394             my $res = $main::known_server_db->update_dbentry( $sql_statement );
396             my $hash = &create_xml_hash("confirm_new_key", $server_address, $source_name);
397             my $out_msg = &create_xml_string($hash);
398             push(@out_msg_l, $out_msg);
399         }
400     }
402     return @out_msg_l;
406 #===  FUNCTION  ================================================================
407 #         NAME:  here_i_am
408 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
409 #      RETURNS:  nothing
410 #  DESCRIPTION:  process this incoming message
411 #===============================================================================
412 sub here_i_am {
413     my ($msg, $msg_hash, $session_id) = @_;
414     my @out_msg_l;
415     my $out_hash;
416     my $source = @{$msg_hash->{source}}[0];
417     my $mac_address = @{$msg_hash->{mac_address}}[0];
418         my $gotoHardwareChecksum = @{$msg_hash->{gotoHardwareChecksum}}[0];
419     my $client_status = @{$msg_hash->{client_status}}[0];
420     my $client_revision = @{$msg_hash->{client_revision}}[0];
421     my $key_lifetime = @{$msg_hash->{key_lifetime}}[0];
423     # Move forced hostname to heap - if used
424     #FIXME: move to some global POE namespace - please
425     if ( defined($msg_hash->{'force-hostname'}[0]) &&
426        length($msg_hash->{'force-hostname'}[0]) > 0){
427     #      $heap->{force-hostname}->{$mac_address}= $msg_hash->{'force-hostname'}[0];
428             open (TFILE, ">/var/tmp/$mac_address");
429             print TFILE $msg_hash->{'force-hostname'}[0];
430             close (TFILE); 
431     } else {
432     #      $heap->{force-hostname}->{$mac_address}= undef;
433         if ( -e "/var/tmp/$mac_address") {
434                 unlink("/var/tmp/$mac_address")
435         }; 
436     }
438     # number of known clients
439     my $nu_clients= $main::known_clients_db->count_dbentries('known_clients');
441     # check wether client address or mac address is already known
442     my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$source'";
443     my $db_res= $main::known_clients_db->select_dbentry( $sql_statement );
444     
445     if ( 1 == keys %{$db_res} ) {
446         &main::daemon_log("$session_id WARNING: $source is already known as a client", 1);
447         &main::daemon_log("$session_id WARNING: values for $source are being overwritten", 1);   
448         $nu_clients --;
449     }
451     # number of actual activ clients
452     my $act_nu_clients = $nu_clients;
454     &main::daemon_log("$session_id INFO: number of actual activ clients: $act_nu_clients", 5);
455     &main::daemon_log("$session_id INFO: number of maximal allowed clients: $max_clients", 5);
457     if($max_clients <= $act_nu_clients) {
458         my $out_hash = &create_xml_hash("denied", $server_address, $source);
459         &add_content2xml_hash($out_hash, "denied", "I_cannot_take_any_more_clients!");
460         my $passwd = @{$msg_hash->{new_passwd}}[0]; 
461         &send_msg_hash2address($out_hash, $source, $passwd);
462         return;
463     }
464     
465     # new client accepted
466     my $new_passwd = @{$msg_hash->{new_passwd}}[0];
468     # add entry to known_clients_db
469     my $events = @{$msg_hash->{events}}[0];
470     my $act_timestamp = &get_time;
471     my $res = $main::known_clients_db->add_dbentry( {table=>'known_clients', 
472                                                 primkey=>['hostname'],
473                                                 hostname=>$source,
474                                                 events=>$events,
475                                                 macaddress=>$mac_address,
476                                                 status=>'registered',
477                                                 hostkey=>$new_passwd,
478                                                 timestamp=>$act_timestamp,
479                                                 keylifetime=>$key_lifetime,
480                                                 } );
482     if ($res != 0)  {
483         &main::daemon_log("$session_id ERROR: cannot add entry to known_clients: $res");
484         return;
485     }
486     
487     # return acknowledgement to client
488     $out_hash = &create_xml_hash("registered", $server_address, $source);
491     # give the new client his ldap config
492     # Workaround: Send within the registration response, if the client will get an ldap config later
493         my $new_ldap_config_out = &new_ldap_config($source, $session_id);
494         if($new_ldap_config_out && (!($new_ldap_config_out =~ /error/))) {
495                 &add_content2xml_hash($out_hash, "ldap_available", "true");
496         } elsif($new_ldap_config_out && $new_ldap_config_out =~ /error/){
497                 &add_content2xml_hash($out_hash, "error", $new_ldap_config_out);
499                 my $sql_statement = "UPDATE $main::job_queue_tn ".
500                 "SET status='error', result='$new_ldap_config_out' ".
501                 "WHERE status='processing' AND macaddress LIKE '$mac_address'";
502                 my $res = $main::job_db->update_dbentry($sql_statement);
503                 &main::daemon_log("$session_id DEBUG: $sql_statement RESULT: $res", 7);         
504         }
505     my $register_out = &create_xml_string($out_hash);
506     push(@out_msg_l, $register_out);
508     # Really send the ldap config
509     if( $new_ldap_config_out && (!($new_ldap_config_out =~ /error/))) {
510             push(@out_msg_l, $new_ldap_config_out);
511     }
513     # Send client hardware configuration
514         my $hardware_config_out = &hardware_config($msg, $msg_hash, $session_id);
515         if( $hardware_config_out ) {
516                 push(@out_msg_l, $hardware_config_out);
517         }
519     # Send client ntp server
520     my $ntp_config_out = &new_ntp_config($mac_address, $session_id);
521     if ($ntp_config_out) {
522         push(@out_msg_l, $ntp_config_out);
523     }
525     # Send client syslog server
526     my $syslog_config_out = &new_syslog_config($mac_address, $session_id);
527     if ($syslog_config_out) {
528         push(@out_msg_l, $syslog_config_out);
529     }
531     # notify registered client to all other server
532     my %mydata = ( 'client' => $source, 'macaddress' => $mac_address);
533     my $mymsg = &build_msg('new_foreign_client', $main::server_address, "KNOWN_SERVER", \%mydata);
534     push(@out_msg_l, $mymsg);
536     &main::daemon_log("$session_id INFO: register client $source ($mac_address)", 5);
537     &main::daemon_log("$session_id INFO: client version: $client_status - $client_revision", 5); 
538     return @out_msg_l;
542 #===  FUNCTION  ================================================================
543 #         NAME:  who_has
544 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
545 #      RETURNS:  nothing 
546 #  DESCRIPTION:  process this incoming message
547 #===============================================================================
548 sub who_has {
549     my ($msg_hash) = @_ ;
550     my @out_msg_l;
551     
552     # what is your search pattern
553     my $search_pattern = @{$msg_hash->{who_has}}[0];
554     my $search_element = @{$msg_hash->{$search_pattern}}[0];
555     &main::daemon_log("who_has-msg looking for $search_pattern $search_element", 7);
557     # scanning known_clients for search_pattern
558     my @host_addresses = keys %$main::known_clients;
559     my $known_clients_entries = length @host_addresses;
560     my $host_address;
561     foreach my $host (@host_addresses) {
562         my $client_element = $main::known_clients->{$host}->{$search_pattern};
563         if ($search_element eq $client_element) {
564             $host_address = $host;
565             last;
566         }
567     }
568         
569     # search was successful
570     if (defined $host_address) {
571         my $source = @{$msg_hash->{source}}[0];
572         my $out_hash = &create_xml_hash("who_has_i_do", $server_address, $source, "mac_address");
573         &add_content2xml_hash($out_hash, "mac_address", $search_element);
574         my $out_msg = &create_xml_string($out_hash);
575         push(@out_msg_l, $out_msg);
576     }
577     return @out_msg_l;
581 sub who_has_i_do {
582     my ($msg_hash) = @_ ;
583     my $header = @{$msg_hash->{header}}[0];
584     my $source = @{$msg_hash->{source}}[0];
585     my $search_param = @{$msg_hash->{$header}}[0];
586     my $search_value = @{$msg_hash->{$search_param}}[0];
587     print "\ngot msg $header:\nserver $source has client with $search_param $search_value\n";
591 sub new_syslog_config {
592     my ($mac_address, $session_id) = @_;
593     my $syslog_msg;
595         # Build LDAP connection
596     my $ldap_handle = &main::get_ldap_handle($session_id);
597         if( not defined $ldap_handle ) {
598                 &main::daemon_log("$session_id ERROR: cannot connect to ldap: $ldap_uri", 1);
599                 return;
600         }
602         # Perform search
603     my $ldap_res = $ldap_handle->search( base   => $ldap_base,
604                 scope  => 'sub',
605                 attrs => ['gotoSyslogServer'],
606                 filter => "(&(objectClass=GOhard)(macaddress=$mac_address))");
607         if($ldap_res->code) {
608                 &main::daemon_log("$session_id ".$ldap_res->error, 1);
609                 return;
610         }
612         # Sanity check
613         if ($ldap_res->count != 1) {
614                 &main::daemon_log("$session_id ERROR: client with mac address $mac_address not found/unique/active - not sending syslog config".
615                 "\n\tbase: $ldap_base".
616                 "\n\tscope: sub".
617                 "\n\tattrs: gotoSyslogServer".
618                 "\n\tfilter: (&(objectClass=GOhard)(macaddress=$mac_address))", 1);
619                 return;
620         }
622         my $entry= $ldap_res->entry(0);
623     my $dn = &Net::LDAP::Util::escape_dn_value($entry->dn);
624         my $syslog_server = $entry->get_value("gotoSyslogServer");
626     # If no syslog server is specified at host, just have a look at the object group of the host
627     # Perform object group search
628     if (not defined $syslog_server) {
629         my $ldap_res = $ldap_handle->search( base   => $ldap_base,
630                 scope  => 'sub',
631                 attrs => ['gotoSyslogServer'],
632                 filter => "(&(objectClass=gosaGroupOfNames)(member=$dn))");
633         if($ldap_res->code) {
634             &main::daemon_log("$session_id ".$ldap_res->error, 1);
635             return;
636         }
638         # Sanity check
639         if ($ldap_res->count != 1) {
640             &main::daemon_log("$session_id ERROR: client with mac address $mac_address not found/unique/active - not sending syslog config".
641                     "\n\tbase: $ldap_base".
642                     "\n\tscope: sub".
643                     "\n\tattrs: gotoSyslogServer".
644                     "\n\tfilter: (&(objectClass=gosaGroupOfNames)(member=$dn))", 1);
645             return;
646         }
648         my $entry= $ldap_res->entry(0);
649         $syslog_server= $entry->get_value("gotoSyslogServer");
650     }
652     # Return if no syslog server specified
653     if (not defined $syslog_server) {
654         &main::daemon_log("$session_id WARNING: no syslog server specified for this host '$mac_address'", 3);
655         return;
656     }
657  
658     # Add syslog server to 'syslog_config' message
659     my $syslog_msg_hash = &create_xml_hash("new_syslog_config", $server_address, $mac_address);
660     &add_content2xml_hash($syslog_msg_hash, "server", $syslog_server);
662     return &create_xml_string($syslog_msg_hash);
666 sub new_ntp_config {
667     my ($address, $session_id) = @_;
668     my $ntp_msg;
670         # Build LDAP connection
671     my $ldap_handle = &main::get_ldap_handle($session_id);
672         if( not defined $ldap_handle ) {
673                 &main::daemon_log("$session_id ERROR: cannot connect to ldap: $ldap_uri", 1);
674                 return;
675         }
677         # Perform search
678     my $ldap_res = $ldap_handle->search( base   => $ldap_base,
679                 scope  => 'sub',
680                 attrs => ['gotoNtpServer'],
681                 filter => "(&(objectClass=GOhard)(macaddress=$address))");
682         if($ldap_res->code) {
683                 &main::daemon_log("$session_id ".$ldap_res->error, 1);
684                 return;
685         }
687         # Sanity check
688         if ($ldap_res->count != 1) {
689                 &main::daemon_log("$session_id ERROR: client with mac address $address not found/unique/active - not sending ntp config".
690                 "\n\tbase: $ldap_base".
691                 "\n\tscope: sub".
692                 "\n\tattrs: gotoNtpServer".
693                 "\n\tfilter: (&(objectClass=GOhard)(macaddress=$address))", 1);
694                 return;
695         }
697         my $entry= $ldap_res->entry(0);
698     my $dn = &Net::LDAP::Util::escape_dn_value($entry->dn);
699         my @ntp_servers= $entry->get_value("gotoNtpServer");
701     # If no ntp server is specified at host, just have a look at the object group of the host
702     # Perform object group search
703     if ((not @ntp_servers) || (@ntp_servers == 0)) {
704         my $ldap_res = $ldap_handle->search( base   => $ldap_base,
705                 scope  => 'sub',
706                 attrs => ['gotoNtpServer'],
707                 filter => "(&(objectClass=gosaGroupOfNames)(member=$dn))");
708         if($ldap_res->code) {
709             &main::daemon_log("$session_id ".$ldap_res->error, 1);
710             return;
711         }
713         # Sanity check
714         if ($ldap_res->count != 1) {
715             &main::daemon_log("$session_id ERROR: client with mac address $address not found/unique/active - not sending ntp config".
716                     "\n\tbase: $ldap_base".
717                     "\n\tscope: sub".
718                     "\n\tattrs: gotoNtpServer".
719                     "\n\tfilter: (&(objectClass=gosaGroupOfNames)(member=$dn))", 1);
720             return;
721         }
723         my $entry= $ldap_res->entry(0);
724         @ntp_servers= $entry->get_value("gotoNtpServer");
725     }
727     # Return if no ntp server specified
728     if ((not @ntp_servers) || (@ntp_servers == 0)) {
729         &main::daemon_log("$session_id WARNING: no ntp server specified for this host '$address'", 3);
730         return;
731     }
732  
733     # Add each ntp server to 'ntp_config' message
734     my $ntp_msg_hash = &create_xml_hash("new_ntp_config", $server_address, $address);
735     foreach my $ntp_server (@ntp_servers) {
736         &add_content2xml_hash($ntp_msg_hash, "server", $ntp_server);
737     }
739     return &create_xml_string($ntp_msg_hash);
743 #===  FUNCTION  ================================================================
744 #         NAME:  new_ldap_config
745 #   PARAMETERS:  address - string - ip address and port of a host
746 #      RETURNS:  gosa-si conform message
747 #  DESCRIPTION:  send to address the ldap configuration found for dn gotoLdapServer
748 #===============================================================================
749 sub new_ldap_config {
750         my ($address, $session_id) = @_ ;
752         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address' OR macaddress LIKE '$address'";
753         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
755         # check hit
756         my $hit_counter = keys %{$res};
757         if( not $hit_counter == 1 ) {
758                 &main::daemon_log("$session_id ERROR: more or no hit found in known_clients_db by query '$sql_statement'", 1);
759         }
761     $address = $res->{1}->{hostname};
762         my $macaddress = $res->{1}->{macaddress};
763         my $hostkey = $res->{1}->{hostkey};
765         if (not defined $macaddress) {
766                 &main::daemon_log("$session_id ERROR: no mac address found for client $address", 1);
767                 return;
768         }
770         # Build LDAP connection
771     my $ldap_handle = &main::get_ldap_handle($session_id);
772         if( not defined $ldap_handle ) {
773                 &main::daemon_log("$session_id ERROR: cannot connect to ldap: $ldap_uri", 1);
774                 return;
775         } 
777         # Perform search
778     $mesg = $ldap_handle->search( base   => $ldap_base,
779                 scope  => 'sub',
780                 attrs => ['dn', 'gotoLdapServer', 'gosaUnitTag', 'FAIclass'],
781                 filter => "(&(objectClass=GOhard)(macaddress=$macaddress))");
782         if($mesg->code) {
783                 &main::daemon_log("$session_id ".$mesg->error, 1);
784                 return;
785         }
787         # Sanity check
788         if ($mesg->count != 1) {
789                 &main::daemon_log("$session_id WARNING: client with mac address $macaddress not found/unique/active - not sending ldap config".
790                 "\n\tbase: $ldap_base".
791                 "\n\tscope: sub".
792                 "\n\tattrs: dn, gotoLdapServer".
793                 "\n\tfilter: (&(objectClass=GOhard)(macaddress=$macaddress))", 1);
794                 return;
795         }
797         my $entry= $mesg->entry(0);
798         my $dn= $entry->dn;
799         my @servers= $entry->get_value("gotoLdapServer");
800         my $unit_tag= $entry->get_value("gosaUnitTag");
801         my @ldap_uris;
802         my $server;
803         my $base;
804         my $release;
806         # Fill release if available
807         my $FAIclass= $entry->get_value("FAIclass");
808         if (defined $FAIclass && $FAIclass =~ /^.* :([A-Za-z0-9\/.]+).*$/) {
809                 $release= $1;
810         }
812         # Do we need to look at an object class?
813         if (not @servers){
814           my $escaped_dn = &Net::LDAP::Util::escape_dn_value($dn);
815                 $mesg = $ldap_handle->search( base   => $ldap_base,
816                         scope  => 'sub',
817                         attrs => ['dn', 'gotoLdapServer', 'FAIclass'],
818                         filter => "(&(objectClass=gosaGroupOfNames)(member=$escaped_dn))");
819                 if($mesg->code) {
820                         &main::daemon_log("$session_id ERROR: unable to search for '(&(objectClass=gosaGroupOfNames)(member=$dn))': ".$mesg->error, 1);
821                         return;
822                 }
824                 # Sanity check
825         if ($mesg->count != 1) {
826             &main::daemon_log("$session_id ERROR: client with mac address $macaddress not found/unique/active - not sending ldap config".
827                     "\n\tbase: $ldap_base".
828                     "\n\tscope: sub".
829                     "\n\tattrs: dn, gotoLdapServer, FAIclass".
830                     "\n\tfilter: (&(objectClass=gosaGroupOfNames)(member=$escaped_dn))", 1);
831             return;
832         }
834                 $entry= $mesg->entry(0);
835                 $dn= $entry->dn;
836                 @servers= $entry->get_value("gotoLdapServer");
838                 if (not defined $release){
839                         $FAIclass= $entry->get_value("FAIclass");
840                         if (defined $FAIclass && $FAIclass =~ /^.* :([A-Za-z0-9\/.]+).*$/) {
841                                 $release= $1;
842                         }
843                 }
844         }
846         @servers= sort (@servers);
848     # complain if no ldap information found
849     if (@servers == 0) {
850         &main::daemon_log("$session_id ERROR: no gotoLdapServer information for LDAP entry '$dn'", 1);
851     }
853         foreach $server (@servers){
854                 # Conversation for backward compatibility
855                 if (not $server =~ /^\d+:[^:]+:ldap[^:]*:\/\// ) {
856                     if ($server =~ /^([^:]+):([^:]+)$/ ) {
857                       $server= "1:dummy:ldap://$1/$2";
858                     } elsif ($server =~ /^(\d+):([^:]+):(.*)$/ ) {
859                       $server= "$1:dummy:ldap://$2/$3";
860                     }
861                 }
863                 $base= $server;
864                 $server =~ s%^[^:]+:[^:]+:(ldap.*://[^/]+)/.*$%$1%;
865                 $base =~ s%^[^:]+:[^:]+:ldap.*://[^/]+/(.*)$%$1%;
866                 push (@ldap_uris, $server);
867         }
869         # Assemble data package
870         my %data = ( 'ldap_uri'  => \@ldap_uris, 'ldap_base' => $base,
871                 'ldap_cfg' => \@ldap_cfg, 'pam_cfg' => \@pam_cfg,'nss_cfg' => \@nss_cfg );
872         if (defined $release){
873                 $data{'release'}= $release;
874         }
876         # Need to append GOto settings?
877         if (defined $goto_admin and defined $goto_secret){
878                 $data{'goto_admin'}= $goto_admin;
879                 $data{'goto_secret'}= $goto_secret;
880         }
882         # Append unit tag if needed
883         if (defined $unit_tag){
885                 # Find admin base and department name
886                 $mesg = $ldap_handle->search( base   => $ldap_base,
887                         scope  => 'sub',
888                         attrs => ['dn', 'ou'],
889                         filter => "(&(objectClass=gosaAdministrativeUnit)(gosaUnitTag=$unit_tag))");
890                 #$mesg->code && die $mesg->error;
891                 if($mesg->code) {
892                         &main::daemon_log($mesg->error, 1);
893                         return "error-unit-tag-count-0";
894                 }
896                 # Sanity check
897                 if ($mesg->count != 1) {
898                         &main::daemon_log("WARNING: cannot find administrative unit for client with tag $unit_tag", 1);
899                         return "error-unit-tag-count-".$mesg->count;
900                 }
902                 $entry= $mesg->entry(0);
903                 $data{'admin_base'}= $entry->dn;
904                 $data{'department'}= $entry->get_value("ou");
906                 # Append unit Tag
907                 $data{'unit_tag'}= $unit_tag;
908         }
910         # Send information
911         return &build_msg("new_ldap_config", $server_address, $address, \%data);
915 #===  FUNCTION  ================================================================
916 #         NAME:  hardware_config
917 #   PARAMETERS:  address - string - ip address and port of a host
918 #      RETURNS:  
919 #  DESCRIPTION:  
920 #===============================================================================
921 sub hardware_config {
922         my ($msg, $msg_hash, $session_id) = @_ ;
923         my $address = @{$msg_hash->{source}}[0];
924         my $header = @{$msg_hash->{header}}[0];
925         my $gotoHardwareChecksum = @{$msg_hash->{gotoHardwareChecksum}}[0];
927         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address'";
928         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
930         # check hit
931         my $hit_counter = keys %{$res};
932         if( not $hit_counter == 1 ) {
933                 &main::daemon_log("$session_id ERROR: more or no hit found in known_clients_db by query by '$address'", 1);
934         }
935         my $macaddress = $res->{1}->{macaddress};
936         my $hostkey = $res->{1}->{hostkey};
938         if (not defined $macaddress) {
939                 &main::daemon_log("$session_id ERROR: no mac address found for client $address", 1);
940                 return;
941         }
943         # Build LDAP connection
944     my $ldap_handle = &main::get_ldap_handle($session_id);
945         if( not defined $ldap_handle ) {
946                 &main::daemon_log("$session_id ERROR: cannot connect to ldap: $ldap_uri", 1);
947                 return;
948         } 
950         # Perform search
951         $mesg = $ldap_handle->search(
952                 base   => $ldap_base,
953                 scope  => 'sub',
954                 filter => "(&(objectClass=GOhard)(|(macAddress=$macaddress)(dhcpHWaddress=ethernet $macaddress)))"
955         );
957         if($mesg->count() == 0) {
958                 &main::daemon_log("Host was not found in LDAP!", 1);
960                 # set status = hardware_detection at jobqueue if entry exists
961                 # TODO
962                 # resolve plain name for host
963                 my $func_dic = {table=>$main::job_queue_tn,
964                                 primkey=>['macaddress', 'headertag'],
965                                 timestamp=>&get_time,
966                                 status=>'processing',
967                                 result=>'none',
968                                 progress=>'hardware-detection',
969                                 headertag=>'trigger_action_reinstall',
970                                 targettag=>$address,
971                                 xmlmessage=>'none',
972                                 macaddress=>$macaddress,
973                                 plainname=>'none',
974                 siserver=>'localhost',
975                 modified=>'1',
976                 };
977                 my $hd_res = $main::job_db->add_dbentry($func_dic);
978                 &main::daemon_log("$session_id INFO: add '$macaddress' to job queue as an installing job", 5);
979         
980         } else {
981                 my $entry= $mesg->entry(0);
982                 my $dn= $entry->dn;
983                 if (defined($entry->get_value("gotoHardwareChecksum"))) {
984                         if (! $entry->get_value("gotoHardwareChecksum") eq $gotoHardwareChecksum) {
985                                 $entry->replace(gotoHardwareChecksum => $gotoHardwareChecksum);
986                                 if($entry->update($ldap_handle)) {
987                                         &main::daemon_log("$session_id INFO: Hardware changed! Detection triggered.", 5);
988                                 }
989                         } else {
990                                 # Nothing to do
991                                 return;
992                         }
993                 } 
994         } 
996         # Assemble data package
997         my %data = ();
999         # Need to append GOto settings?
1000         if (defined $goto_admin and defined $goto_secret){
1001                 $data{'goto_admin'}= $goto_admin;
1002                 $data{'goto_secret'}= $goto_secret;
1003         }
1005         # Send information
1006         return &build_msg("detect_hardware", $server_address, $address, \%data);
1009 sub server_matches {
1010         my $target = shift;
1011         my $target_ip = ($1) if $target =~ /^([0-9\.]*?):.*$/;
1012         if(!defined($target_ip) or length($target_ip) == 0) {
1013                 return;
1014         }
1016         my $result = 0;
1018         if($server_ip eq $target_ip) {
1019                 $result= 1;
1020         } elsif ($target_ip eq "0.0.0.0") {
1021                 $result= 1;
1022         } elsif ($server_ip eq "0.0.0.0") {     
1023                 if ($target_ip eq "127.0.0.1") {
1024                         $result= 1;
1025                 } else {
1026                         my $PROC_NET_ROUTE= ('/proc/net/route');
1028                         open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
1029                                 or die "Could not open $PROC_NET_ROUTE";
1031                         my @ifs = <PROC_NET_ROUTE>;
1033                         close(PROC_NET_ROUTE);
1035                         # Eat header line
1036                         shift @ifs;
1037                         chomp @ifs;
1038                         foreach my $line(@ifs) {
1039                                 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
1040                                 my $destination;
1041                                 my $mask;
1042                                 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
1043                                 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
1044                                 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
1045                                 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
1046                                 if(new NetAddr::IP($target_ip)->within(new NetAddr::IP($destination, $mask))) {
1047                                         # destination matches route, save mac and exit
1048                                         $result= 1;
1049                                         last;
1050                                 }
1051                         }
1052                 }
1053         } else {
1054                 &main::daemon_log("Target ip $target_ip does not match Server ip $server_ip",1);
1055         }
1057         return $result;
1060 # vim:ts=4:shiftwidth:expandtab
1061 1;