Code

Fixed typos.
[gosa.git] / gosa-si / modules / SIPackages.pm
1 package SIPackages;
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. 
9 use strict;
10 use warnings;
11 use GOSA::GosaSupportDaemon;
12 use IO::Socket::INET;
13 use XML::Simple;
14 use Data::Dumper;
15 use NetAddr::IP;
16 use Net::LDAP;
17 use Socket;
18 use Net::hostent;
19 use utf8;
21 my $event_dir = "/usr/lib/gosa-si/server/events";
22 use lib "/usr/lib/gosa-si/server/events";
24 BEGIN{}
25 END {}
27 my ($server_ip, $server_mac_address, $server_port, $SIPackages_key, $max_clients, $ldap_uri, $ldap_base, $ldap_admin_dn, $ldap_admin_password, $server_interface);
28 my ($bus_activ, $bus_key, $bus_ip, $bus_port);
29 my $server;
30 my $event_hash;
31 my $network_interface;
32 my $no_bus;
33 my (@ldap_cfg, @pam_cfg, @nss_cfg, $goto_admin, $goto_secret);
34 my $mesg;
36 my %cfg_defaults = (
37 "bus" => {
38     "activ" => [\$bus_activ, "on"],
39     "key" => [\$bus_key, ""],
40     "ip" => [\$bus_ip, ""],
41     "port" => [\$bus_port, "20080"],
42     },
43 "server" => {
44     "ip" => [\$server_ip, "0.0.0.0"],
45     "mac-address" => [\$server_mac_address, "00:00:00:00:00"],
46     "port" => [\$server_port, "20081"],
47     "ldap-uri" => [\$ldap_uri, ""],
48     "ldap-base" => [\$ldap_base, ""],
49     "ldap-admin-dn" => [\$ldap_admin_dn, ""],
50     "ldap-admin-password" => [\$ldap_admin_password, ""],
51     "max-clients" => [\$max_clients, 100],
52     },
53 "SIPackages" => {
54     "key" => [\$SIPackages_key, ""],
55     },
56 );
58 ### START #####################################################################
60 # read configfile and import variables
61 &read_configfile();
64 # if server_ip is not an ip address but a name
65 if( inet_aton($server_ip) ){ $server_ip = inet_ntoa(inet_aton($server_ip)); } 
66 $network_interface= &get_interface_for_ip($server_ip);
67 $server_mac_address= &get_mac($network_interface);
69 &import_events();
71 # Unit tag can be defined in config
72 if((not defined($main::gosa_unit_tag)) || length($main::gosa_unit_tag) == 0) {
73         # Read gosaUnitTag from LDAP
74   &main::refresh_ldap_handle();
75         if( defined($main::ldap_handle) ) {
76                 &main::daemon_log("INFO: Searching for servers gosaUnitTag with mac address $server_mac_address",5);
77                 # Perform search for Unit Tag
78                 $mesg = $main::ldap_handle->search(
79                         base   => $ldap_base,
80                         scope  => 'sub',
81                         attrs  => ['gosaUnitTag'],
82                         filter => "(macaddress=$server_mac_address)"
83                 );
85                 if ($mesg->count == 1) {
86                         my $entry= $mesg->entry(0);
87                         my $unit_tag= $entry->get_value("gosaUnitTag");
88                         if(defined($unit_tag) && length($unit_tag) > 0) {
89                                 &main::daemon_log("INFO: Detected gosaUnitTag $unit_tag for creating entries", 5);
90                                 $main::gosa_unit_tag= $unit_tag;
91                         }
92                 } else {
93                         # Perform another search for Unit Tag
94                         my $hostname= `hostname -f`;
95                         chomp($hostname);
96                         &main::daemon_log("INFO: Searching for servers gosaUnitTag with hostname $hostname",5);
97                         $mesg = $main::ldap_handle->search(
98                                 base   => $ldap_base,
99                                 scope  => 'sub',
100                                 attrs  => ['gosaUnitTag'],
101                                 filter => "(&(cn=$hostname)(objectClass=goServer))"
102                         );
103                         if ($mesg->count == 1) {
104                                 my $entry= $mesg->entry(0);
105                                 my $unit_tag= $entry->get_value("gosaUnitTag");
106                                 if(defined($unit_tag) && length($unit_tag) > 0) {
107                                         &main::daemon_log("INFO: Detected gosaUnitTag $unit_tag for creating entries", 5);
108                                         $main::gosa_unit_tag= $unit_tag;
109                                 }
110                         } else {
111                                 # Perform another search for Unit Tag
112                                 $hostname= `hostname -s`;
113                                 chomp($hostname);
114                                 &main::daemon_log("INFO: Searching for servers gosaUnitTag with hostname $hostname",5);
115                                 $mesg = $main::ldap_handle->search(
116                                         base   => $ldap_base,
117                                         scope  => 'sub',
118                                         attrs  => ['gosaUnitTag'],
119                                         filter => "(&(cn=$hostname)(objectClass=goServer))"
120                                 );
121                                 if ($mesg->count == 1) {
122                                         my $entry= $mesg->entry(0);
123                                         my $unit_tag= $entry->get_value("gosaUnitTag");
124                                         if(defined($unit_tag) && length($unit_tag) > 0) {
125                                                 &main::daemon_log("INFO: Detected gosaUnitTag $unit_tag for creating entries", 5);
126                                                 $main::gosa_unit_tag= $unit_tag;
127                                         }
128                                 } else {
129                                         &main::daemon_log("WARNING: No gosaUnitTag detected. Not using gosaUnitTag", 3);
130                                 }
131                         }
132                 }
133         } else {
134                 &main::daemon_log("INFO: Using gosaUnitTag from config-file: $main::gosa_unit_tag",5);
135         }
139 my $server_address = "$server_ip:$server_port";
140 $main::server_address = $server_address;
143 if( inet_aton($bus_ip) ){ $bus_ip = inet_ntoa(inet_aton($bus_ip)); } 
144 ######################################################
145 # to change
146 if( $bus_ip eq "127.0.1.1" ) { $bus_ip = "127.0.0.1" }
147 ######################################################
148 my $bus_address = "$bus_ip:$bus_port";
149 $main::bus_address = $bus_address;
151 # create general settings for this module
152 my $xml = new XML::Simple();
154 # register at bus
155 if ($main::no_bus > 0) {
156     $bus_activ = "off"
158 if($bus_activ eq "on") {
159     &register_at_bus();
162 # add myself to known_server_db
163 my $res = $main::known_server_db->add_dbentry( {table=>'known_server',
164         primkey=>['hostname'],
165         hostname=>$server_address,
166         status=>'myself',
167         hostkey=>$SIPackages_key,
168         timestamp=>&get_time,
169         } );
173 ### functions #################################################################
176 sub get_module_info {
177     my @info = ($server_address,
178                 $SIPackages_key,
179                 );
180     return \@info;
184 #===  FUNCTION  ================================================================
185 #         NAME:  read_configfile
186 #   PARAMETERS:  cfg_file - string -
187 #      RETURNS:  nothing
188 #  DESCRIPTION:  read cfg_file and set variables
189 #===============================================================================
190 sub read_configfile {
191     my $cfg;
192     if( defined( $main::cfg_file) && ( length($main::cfg_file) > 0 )) {
193         if( -r $main::cfg_file ) {
194             $cfg = Config::IniFiles->new( -file => $main::cfg_file );
195         } else {
196             print STDERR "Couldn't read config file!";
197         }
198     } else {
199         $cfg = Config::IniFiles->new() ;
200     }
201     foreach my $section (keys %cfg_defaults) {
202         foreach my $param (keys %{$cfg_defaults{ $section }}) {
203             my $pinfo = $cfg_defaults{ $section }{ $param };
204             ${@$pinfo[0]} = $cfg->val( $section, $param, @$pinfo[1] );
205         }
206     }
208     # Read non predefined sections
209     my $param;
210     if ($cfg->SectionExists('ldap')){
211                 foreach $param ($cfg->Parameters('ldap')){
212                         push (@ldap_cfg, "$param ".$cfg->val('ldap', $param));
213                 }
214     }
215     if ($cfg->SectionExists('pam_ldap')){
216                 foreach $param ($cfg->Parameters('pam_ldap')){
217                         push (@pam_cfg, "$param ".$cfg->val('pam_ldap', $param));
218                 }
219     }
220     if ($cfg->SectionExists('nss_ldap')){
221                 foreach $param ($cfg->Parameters('nss_ldap')){
222                         push (@nss_cfg, "$param ".$cfg->val('nss_ldap', $param));
223                 }
224     }
225     if ($cfg->SectionExists('goto')){
226         $goto_admin= $cfg->val('goto', 'terminal_admin');
227         $goto_secret= $cfg->val('goto', 'terminal_secret');
228     } else {
229         $goto_admin= undef;
230         $goto_secret= undef;
231     }
235 #===  FUNCTION  ================================================================
236 #         NAME:  get_interface_for_ip
237 #   PARAMETERS:  ip address (i.e. 192.168.0.1)
238 #      RETURNS:  array: list of interfaces if ip=0.0.0.0, matching interface if found, undef else
239 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
240 #===============================================================================
241 sub get_interface_for_ip {
242         my $result;
243         my $ip= shift;
244         if ($ip && length($ip) > 0) {
245                 my @ifs= &get_interfaces();
246                 if($ip eq "0.0.0.0") {
247                         $result = "all";
248                 } else {
249                         foreach (@ifs) {
250                                 my $if=$_;
251                                 if(get_ip($if) eq $ip) {
252                                         $result = $if;
253                                 }
254                         }       
255                 }
256         }       
257         return $result;
260 #===  FUNCTION  ================================================================
261 #         NAME:  get_interfaces 
262 #   PARAMETERS:  none
263 #      RETURNS:  (list of interfaces) 
264 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
265 #===============================================================================
266 sub get_interfaces {
267         my @result;
268         my $PROC_NET_DEV= ('/proc/net/dev');
270         open(PROC_NET_DEV, "<$PROC_NET_DEV")
271                 or die "Could not open $PROC_NET_DEV";
273         my @ifs = <PROC_NET_DEV>;
275         close(PROC_NET_DEV);
277         # Eat first two line
278         shift @ifs;
279         shift @ifs;
281         chomp @ifs;
282         foreach my $line(@ifs) {
283                 my $if= (split /:/, $line)[0];
284                 $if =~ s/^\s+//;
285                 push @result, $if;
286         }
288         return @result;
291 #===  FUNCTION  ================================================================
292 #         NAME:  get_mac 
293 #   PARAMETERS:  interface name (i.e. eth0)
294 #      RETURNS:  (mac address) 
295 #  DESCRIPTION:  Uses ioctl to get mac address directly from system.
296 #===============================================================================
297 sub get_mac {
298         my $ifreq= shift;
299         my $result;
300         if ($ifreq && length($ifreq) > 0) { 
301                 if($ifreq eq "all") {
302                         $result = "00:00:00:00:00:00";
303                 } else {
304                         my $SIOCGIFHWADDR= 0x8927;     # man 2 ioctl_list
306                         # A configured MAC Address should always override a guessed value
307                         if ($server_mac_address and length($server_mac_address) > 0) {
308                                 $result= $server_mac_address;
309                         }
311                         socket SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('ip')
312                                 or die "socket: $!";
314                         if(ioctl SOCKET, $SIOCGIFHWADDR, $ifreq) {
315                                 my ($if, $mac)= unpack 'h36 H12', $ifreq;
317                                 if (length($mac) > 0) {
318                                         $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])$/;
319                                         $mac= sprintf("%s:%s:%s:%s:%s:%s", $1, $2, $3, $4, $5, $6);
320                                         $result = $mac;
321                                 }
322                         }
323                 }
324         }
325         return $result;
329 #===  FUNCTION  ================================================================
330 #         NAME:  register_at_bus
331 #   PARAMETERS:  nothing
332 #      RETURNS:  nothing
333 #  DESCRIPTION:  creates an entry in known_daemons and send a 'here_i_am' msg to bus
334 #===============================================================================
335 sub register_at_bus {
337     # add bus to known_server_db
338     my $res = $main::known_server_db->add_dbentry( {table=>'known_server',
339                                                     primkey=>['hostname'],
340                                                     hostname=>$bus_address,
341                                                     status=>'bus',
342                                                     hostkey=>$bus_key,
343                                                     timestamp=>&get_time,
344                                                 } );
345     my $msg_hash = &create_xml_hash("here_i_am", $server_address, $bus_address);
346     my $msg = &create_xml_string($msg_hash);
348     &main::send_msg_to_target($msg, $bus_address, $bus_key, "here_i_am");
349     return $msg;
353 sub import_events {
354     if (not -e $event_dir) {
355         &main::daemon_log("ERROR: cannot find directory or directory is not readable: $event_dir", 1);   
356     }
357     opendir (DIR, $event_dir) or die "ERROR while loading gosa-si-events from directory $event_dir : $!\n";
359     while (defined (my $event = readdir (DIR))) {
360         if( $event eq "." || $event eq ".." ) { next; }  
361         if( $event eq "gosaTriggered.pm" ) { next; }    # only GOsa specific events
363         eval{ require $event; };
364         if( $@ ) {
365             &main::daemon_log("import of event module '$event' failed", 1);
366             &main::daemon_log("$@", 8);
367             next;
368         }
370         $event =~ /(\S*?).pm$/;
371         my $event_module = $1;
372         my $events_l = eval( $1."::get_events()") ;
373         foreach my $event_name (@{$events_l}) {
374             $event_hash->{$event_name} = $event_module;
375         }
376         my $events_string = join( ", ", @{$events_l});
377         &main::daemon_log("INFO: SIPackages imported events $events_string", 5);
378     }
382 #===  FUNCTION  ================================================================
383 #         NAME:  process_incoming_msg
384 #   PARAMETERS:  crypted_msg - string - incoming crypted message
385 #      RETURNS:  nothing
386 #  DESCRIPTION:  handels the proceeded distribution to the appropriated functions
387 #===============================================================================
388 sub process_incoming_msg {
389     my ($msg, $msg_hash, $session_id) = @_ ;
390     my $error = 0;
391     my $host_name;
392     my $host_key;
393     my @out_msg_l = ();
395     # process incoming msg
396     my $header = @{$msg_hash->{header}}[0]; 
397     my @target_l = @{$msg_hash->{target}};
399     # skip PREFIX
400     $header =~ s/^CLMSG_//;
402     &main::daemon_log("DEBUG: SIPackages: msg to process: $header", 7);
403     &main::daemon_log("$msg", 8);
405     if( 0 == length @target_l){     
406         &main::daemon_log("ERROR: no target specified for msg $header", 1);
407         $error++;
408     }
410     if( 1 == length @target_l) {
411         my $target = $target_l[0];
412                 if(&server_matches($target)) {
415             if ($header eq 'new_key') {
416                 @out_msg_l = &new_key($msg_hash)
417             } elsif ($header eq 'here_i_am') {
418                 @out_msg_l = &here_i_am($msg_hash)
419             } else {
420                 if( exists $event_hash->{$header} ) {
421                     # a event exists with the header as name
422                     &main::daemon_log("INFO: found event '$header' at event-module '".$event_hash->{$header}."'", 5);
423                     no strict 'refs';
424                     @out_msg_l = &{$event_hash->{$header}."::$header"}($msg, $msg_hash, $session_id);
425                 }
426             }
428             # if delivery not possible raise error and return 
429             if( not @out_msg_l ) {
430                 &main::daemon_log("WARNING: SIPackages got no answer from event handler '$header'", 3);
431             } elsif( 0 == @out_msg_l) {
432                 &main::daemon_log("ERROR: SIPackages: no event handler or core function defined for '$header'", 1);
433             } 
434         }
435                 else {
436                         &main::daemon_log("INFO: msg is not for gosa-si-server '$server_address', deliver it to target '$target'", 5);
437                         push(@out_msg_l, $msg);
438                 }
439     }
441     return \@out_msg_l;
445 #===  FUNCTION  ================================================================
446 #         NAME:  new_passwd
447 #   PARAMETERS:  msg_hash - ref - hash from function create_xml_hash
448 #      RETURNS:  nothing
449 #  DESCRIPTION:  process this incoming message
450 #===============================================================================
451 sub new_key {
452     my ($msg_hash) = @_;
453     my @out_msg_l;
454     
455     my $header = @{$msg_hash->{header}}[0];
456     my $source_name = @{$msg_hash->{source}}[0];
457     my $source_key = @{$msg_hash->{new_key}}[0];
458     my $query_res;
460     # check known_clients_db
461     my $sql_statement = "SELECT * FROM known_clients WHERE hostname='$source_name'";
462     $query_res = $main::known_clients_db->select_dbentry( $sql_statement );
463     if( 1 == keys %{$query_res} ) {
464         my $act_time = &get_time;
465         my $sql_statement= "UPDATE known_clients ".
466             "SET hostkey='$source_key', timestamp='$act_time' ".
467             "WHERE hostname='$source_name'";
468         my $res = $main::known_clients_db->update_dbentry( $sql_statement );
469         my $hash = &create_xml_hash("confirm_new_key", $server_address, $source_name);
470         my $out_msg = &create_xml_string($hash);
471         push(@out_msg_l, $out_msg);
472     }
474     # only do if host still not found
475     if( 0 == @out_msg_l ) {
476         # check known_server_db
477         $sql_statement = "SELECT * FROM known_server WHERE hostname='$source_name'";
478         $query_res = $main::known_server_db->select_dbentry( $sql_statement );
479         if( 1 == keys %{$query_res} ) {
480             my $act_time = &get_time;
481             my $sql_statement= "UPDATE known_server ".
482                 "SET hostkey='$source_key', timestamp='$act_time' ".
483                 "WHERE hostname='$source_name'";
484             my $res = $main::known_server_db->update_dbentry( $sql_statement );
486             my $hash = &create_xml_hash("confirm_new_key", $server_address, $source_name);
487             my $out_msg = &create_xml_string($hash);
488             push(@out_msg_l, $out_msg);
489         }
490     }
492     return @out_msg_l;
496 #===  FUNCTION  ================================================================
497 #         NAME:  here_i_am
498 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
499 #      RETURNS:  nothing
500 #  DESCRIPTION:  process this incoming message
501 #===============================================================================
502 sub here_i_am {
503     my ($msg_hash) = @_;
504     my @out_msg_l;
505     my $out_hash;
507     my $source = @{$msg_hash->{source}}[0];
508     my $mac_address = @{$msg_hash->{mac_address}}[0];
509         my $gotoHardwareChecksum = @{$msg_hash->{gotoHardwareChecksum}}[0];
511     # number of known clients
512     my $nu_clients= $main::known_clients_db->count_dbentries('known_clients');
514     # check wether client address or mac address is already known
515     my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$source'";
516     my $db_res= $main::known_clients_db->select_dbentry( $sql_statement );
517     
518     if ( 1 == keys %{$db_res} ) {
519         &main::daemon_log("WARNING: $source is already known as a client", 1);
520         &main::daemon_log("WARNING: values for $source are being overwritten", 1);   
521         $nu_clients --;
522     }
524     # number of actual activ clients
525     my $act_nu_clients = $nu_clients;
527     &main::daemon_log("INFO: number of actual activ clients: $act_nu_clients", 5);
528     &main::daemon_log("INFO: number of maximal allowed clients: $max_clients", 5);
530     if($max_clients <= $act_nu_clients) {
531         my $out_hash = &create_xml_hash("denied", $server_address, $source);
532         &add_content2xml_hash($out_hash, "denied", "I_cannot_take_any_more_clients!");
533         my $passwd = @{$msg_hash->{new_passwd}}[0]; 
534         &send_msg_hash2address($out_hash, $source, $passwd);
535         return;
536     }
537     
538     # new client accepted
539     my $new_passwd = @{$msg_hash->{new_passwd}}[0];
541     # create entry in known_clients
542     my $events = @{$msg_hash->{events}}[0];
543     
545     # add entry to known_clients_db
546     my $act_timestamp = &get_time;
547     my $res = $main::known_clients_db->add_dbentry( {table=>'known_clients', 
548                                                 primkey=>['hostname'],
549                                                 hostname=>$source,
550                                                 events=>$events,
551                                                 macaddress=>$mac_address,
552                                                 status=>'registered',
553                                                 hostkey=>$new_passwd,
554                                                 timestamp=>$act_timestamp,
555                                                 } );
557     if ($res != 0)  {
558         &main::daemon_log("ERROR: cannot add entry to known_clients: $res");
559         return;
560     }
561     
562     # return acknowledgement to client
563     $out_hash = &create_xml_hash("registered", $server_address, $source);
565     # notify registered client to bus
566     if( $bus_activ eq "on") {
567         # fetch actual bus key
568         my $sql_statement= "SELECT * FROM known_server WHERE status='bus'";
569         my $query_res = $main::known_server_db->select_dbentry( $sql_statement );
570         my $hostkey = $query_res->{1}->{'hostkey'};
572         # send update msg to bus
573         $out_hash = &create_xml_hash("new_client", $server_address, $bus_address, $source);
574         &add_content2xml_hash($out_hash, "macaddress", $mac_address);
575         &add_content2xml_hash($out_hash, "timestamp", $act_timestamp);
576         my $new_client_out = &create_xml_string($out_hash);
577         push(@out_msg_l, $new_client_out);
578         &main::daemon_log("INFO: send bus msg that client '$source' has registerd at server '$server_address'", 5);
579     }
581     # give the new client his ldap config
582     # Workaround: Send within the registration response, if the client will get an ldap config later
583     my $new_ldap_config_out = &new_ldap_config($source);
584     if( $new_ldap_config_out ) {
585             &add_content2xml_hash($out_hash, "ldap_available", "true");
586     }
587     my $register_out = &create_xml_string($out_hash);
588     push(@out_msg_l, $register_out);
590     # Really send the ldap config
591     if( $new_ldap_config_out ) {
592             push(@out_msg_l, $new_ldap_config_out);
593     }
595         my $hardware_config_out = &hardware_config($source, $gotoHardwareChecksum);
596         if( $hardware_config_out ) {
597                 push(@out_msg_l, $hardware_config_out);
598         }
600     return @out_msg_l;
604 #===  FUNCTION  ================================================================
605 #         NAME:  who_has
606 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
607 #      RETURNS:  nothing 
608 #  DESCRIPTION:  process this incoming message
609 #===============================================================================
610 sub who_has {
611     my ($msg_hash) = @_ ;
612     my @out_msg_l;
613     
614     # what is your search pattern
615     my $search_pattern = @{$msg_hash->{who_has}}[0];
616     my $search_element = @{$msg_hash->{$search_pattern}}[0];
617     &main::daemon_log("who_has-msg looking for $search_pattern $search_element", 7);
619     # scanning known_clients for search_pattern
620     my @host_addresses = keys %$main::known_clients;
621     my $known_clients_entries = length @host_addresses;
622     my $host_address;
623     foreach my $host (@host_addresses) {
624         my $client_element = $main::known_clients->{$host}->{$search_pattern};
625         if ($search_element eq $client_element) {
626             $host_address = $host;
627             last;
628         }
629     }
630         
631     # search was successful
632     if (defined $host_address) {
633         my $source = @{$msg_hash->{source}}[0];
634         my $out_hash = &create_xml_hash("who_has_i_do", $server_address, $source, "mac_address");
635         &add_content2xml_hash($out_hash, "mac_address", $search_element);
636         my $out_msg = &create_xml_string($out_hash);
637         push(@out_msg_l, $out_msg);
638     }
639     return @out_msg_l;
643 sub who_has_i_do {
644     my ($msg_hash) = @_ ;
645     my $header = @{$msg_hash->{header}}[0];
646     my $source = @{$msg_hash->{source}}[0];
647     my $search_param = @{$msg_hash->{$header}}[0];
648     my $search_value = @{$msg_hash->{$search_param}}[0];
649     print "\ngot msg $header:\nserver $source has client with $search_param $search_value\n";
653 #===  FUNCTION  ================================================================
654 #         NAME:  new_ldap_config
655 #   PARAMETERS:  address - string - ip address and port of a host
656 #      RETURNS:  gosa-si conform message
657 #  DESCRIPTION:  send to address the ldap configuration found for dn gotoLdapServer
658 #===============================================================================
659 sub new_ldap_config {
660         my ($address) = @_ ;
662         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address' OR macaddress='$address'";
663         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
665         # check hit
666         my $hit_counter = keys %{$res};
667         if( not $hit_counter == 1 ) {
668                 &main::daemon_log("ERROR: more or no hit found in known_clients_db by query by '$address'", 1);
669         }
671     $address = $res->{1}->{hostname};
672         my $macaddress = $res->{1}->{macaddress};
673         my $hostkey = $res->{1}->{hostkey};
675         if (not defined $macaddress) {
676                 &main::daemon_log("ERROR: no mac address found for client $address", 1);
677                 return;
678         }
680         # Build LDAP connection
681   &main::refresh_ldap_handle();
682         if( not defined $main::ldap_handle ) {
683                 &main::daemon_log("ERROR: cannot connect to ldap: $ldap_uri", 1);
684                 return;
685         } 
687         # Perform search
688         $mesg = $main::ldap_handle->search( base   => $ldap_base,
689                 scope  => 'sub',
690                 attrs => ['dn', 'gotoLdapServer', 'gosaUnitTag', 'FAIclass'],
691                 filter => "(&(objectClass=GOhard)(macaddress=$macaddress)(gotoLdapServer=*))");
692         #$mesg->code && die $mesg->error;
693         if($mesg->code) {
694                 &main::daemon_log($mesg->error, 1);
695                 return;
696         }
698         # Sanity check
699         if ($mesg->count != 1) {
700                 &main::daemon_log("WARNING: client with mac address $macaddress not found/unique/active - not sending ldap config", 1);
701                 &main::daemon_log("\tbase: $ldap_base", 1);
702                 &main::daemon_log("\tscope: sub", 1);
703                 &main::daemon_log("\tattrs: dn, gotoLdapServer", 1);
704                 &main::daemon_log("\tfilter: (&(objectClass=GOhard)(macaddress=$macaddress)(gotoLdapServer=*))", 1);
705                 return;
706         }
708         my $entry= $mesg->entry(0);
709         my $dn= $entry->dn;
710         my @servers= $entry->get_value("gotoLdapServer");
711         my $unit_tag= $entry->get_value("gosaUnitTag");
712         my @ldap_uris;
713         my $server;
714         my $base;
715         my $release;
717         # Fill release if available
718         my $FAIclass= $entry->get_value("FAIclass");
719         if (defined $FAIclass && $FAIclass =~ /^.* :([A-Za-z0-9\/.]+).*$/) {
720                 $release= $1;
721         }
723         # Do we need to look at an object class?
724         if (length(@servers) < 1){
725                 $mesg = $main::ldap_handle->search( base   => $ldap_base,
726                         scope  => 'sub',
727                         attrs => ['dn', 'gotoLdapServer', 'FAIclass'],
728                         filter => "(&(objectClass=gosaGroupOfNames)(member=$dn))");
729                 #$mesg->code && die $mesg->error;
730                 if($mesg->code) {
731                         &main::daemon_log($mesg->error, 1);
732                         return;
733                 }
735                 # Sanity check
736                 if ($mesg->count != 1) {
737                         &main::daemon_log("WARNING: no LDAP information found for client mac $macaddress", 1);
738                         return;
739                 }
741                 $entry= $mesg->entry(0);
742                 $dn= $entry->dn;
743                 @servers= $entry->get_value("gotoLdapServer");
745                 if (not defined $release){
746                         $FAIclass= $entry->get_value("FAIclass");
747                         if (defined $FAIclass && $FAIclass =~ /^.* :([A-Za-z0-9\/.]+).*$/) {
748                                 $release= $1;
749                         }
750                 }
751         }
753         @servers= sort (@servers);
755         foreach $server (@servers){
756                 # Conversation for backward compatibility
757                 if (not $server =~ /^\d+:[^:]+:ldap[^:]*:\/\// ) {
758                     if ($server =~ /^([^:]+):([^:]+)$/ ) {
759                       $server= "1:dummy:ldap://$1/$2";
760                     } elsif ($server =~ /^(\d+):([^:]+):(.*)$/ ) {
761                       $server= "$1:dummy:ldap://$2/$3";
762                     }
763                 }
765                 $base= $server;
766                 $server =~ s%^[^:]+:[^:]+:(ldap.*://[^/]+)/.*$%$1%;
767                 $base =~ s%^[^:]+:[^:]+:ldap.*://[^/]+/(.*)$%$1%;
768                 push (@ldap_uris, $server);
769         }
771         # Assemble data package
772         my %data = ( 'ldap_uri'  => \@ldap_uris, 'ldap_base' => $base,
773                 'ldap_cfg' => \@ldap_cfg, 'pam_cfg' => \@pam_cfg,'nss_cfg' => \@nss_cfg );
774         if (defined $release){
775                 $data{'release'}= $release;
776         }
778         # Need to append GOto settings?
779         if (defined $goto_admin and defined $goto_secret){
780                 $data{'goto_admin'}= $goto_admin;
781                 $data{'goto_secret'}= $goto_secret;
782         }
784         # Append unit tag if needed
785         if (defined $unit_tag){
787                 # Find admin base and department name
788                 $mesg = $main::ldap_handle->search( base   => $ldap_base,
789                         scope  => 'sub',
790                         attrs => ['dn', 'ou'],
791                         filter => "(&(objectClass=gosaAdministrativeUnit)(gosaUnitTag=$unit_tag))");
792                 #$mesg->code && die $mesg->error;
793                 if($mesg->code) {
794                         &main::daemon_log($mesg->error, 1);
795                         return;
796                 }
798                 # Sanity check
799                 if ($mesg->count != 1) {
800                         &main::daemon_log("WARNING: cannot find administrative unit for client with tag $unit_tag", 1);
801                         return;
802                 }
804                 $entry= $mesg->entry(0);
805                 $data{'admin_base'}= $entry->dn;
806                 $data{'department'}= $entry->get_value("ou");
808                 # Append unit Tag
809                 $data{'unit_tag'}= $unit_tag;
810         }
812         # Send information
813         return &build_msg("new_ldap_config", $server_address, $address, \%data);
817 #===  FUNCTION  ================================================================
818 #         NAME:  hardware_config
819 #   PARAMETERS:  address - string - ip address and port of a host
820 #      RETURNS:  
821 #  DESCRIPTION:  
822 #===============================================================================
823 sub hardware_config {
824         my ($address, $gotoHardwareChecksum) = @_ ;
826         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address'";
827         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
829         # check hit
830         my $hit_counter = keys %{$res};
831         if( not $hit_counter == 1 ) {
832                 &main::daemon_log("ERROR: more or no hit found in known_clients_db by query by '$address'", 1);
833         }
835         my $macaddress = $res->{1}->{macaddress};
836         my $hostkey = $res->{1}->{hostkey};
838         if (not defined $macaddress) {
839                 &main::daemon_log("ERROR: no mac address found for client $address", 1);
840                 return;
841         }
843         # Build LDAP connection
844   &main::refresh_ldap_handle();
845         if( not defined $main::ldap_handle ) {
846                 &main::daemon_log("ERROR: cannot connect to ldap: $ldap_uri", 1);
847                 return;
848         } 
850         # Perform search
851         $mesg = $main::ldap_handle->search(
852                 base   => $ldap_base,
853                 scope  => 'sub',
854                 filter => "(&(objectClass=GOhard)(|(macAddress=$macaddress)(dhcpHWaddress=ethernet $macaddress)))"
855         );
857         if($mesg->count() == 0) {
858                 &main::daemon_log("Host was not found in LDAP!", 1);
859         } else {
860                 my $entry= $mesg->entry(0);
861                 my $dn= $entry->dn;
862                 if(defined($entry->get_value("gotoHardwareChecksum"))) {
863                         if(! $entry->get_value("gotoHardwareChecksum") eq $gotoHardwareChecksum) {
864                                 $entry->replace(gotoHardwareChecksum => $gotoHardwareChecksum);
865                                 if($entry->update($main::ldap_handle)) {
866                                         &main::daemon_log("Hardware changed! Detection triggered.", 4);
867                                 }
868                         } else {
869                                 # Nothing to do
870                                 return;
871                         }
872                 }
873         } 
875         # Assemble data package
876         my %data = ();
878         # Need to append GOto settings?
879         if (defined $goto_admin and defined $goto_secret){
880                 $data{'goto_admin'}= $goto_admin;
881                 $data{'goto_secret'}= $goto_secret;
882         }
884         &main::daemon_log("Send detect_hardware message to $address", 4);
886         # Send information
887         return &build_msg("detect_hardware", $server_address, $address, \%data);
890 sub server_matches {
891         my $target = shift;
892         my $target_ip = sprintf("%s", $target =~ /^([0-9\.]*?):.*$/);
893         my $result = 0;
895         if($server_ip eq $target_ip) {
896                 $result= 1;
897         } elsif ($server_ip eq "0.0.0.0") {     
898                 if ($target_ip eq "127.0.0.1") {
899                         $result= 1;
900                 } else {
901                         my $PROC_NET_ROUTE= ('/proc/net/route');
903                         open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
904                                 or die "Could not open $PROC_NET_ROUTE";
906                         my @ifs = <PROC_NET_ROUTE>;
908                         close(PROC_NET_ROUTE);
910                         # Eat header line
911                         shift @ifs;
912                         chomp @ifs;
913                         foreach my $line(@ifs) {
914                                 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
915                                 my $destination;
916                                 my $mask;
917                                 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
918                                 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
919                                 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
920                                 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
921                                 if(new NetAddr::IP($target_ip)->within(new NetAddr::IP($destination, $mask))) {
922                                         # destination matches route, save mac and exit
923                                         $result= 1;
924                                         last;
925                                 }
926                         }
927                 }
928         } else {
929                 &main::daemon_log("Target ip $target_ip does not match Server ip $server_ip",1);
930         }
932         return $result;
935 1;