Code

492b109a006bb5294b4c51e0050bf481fe1fc573
[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 Net::DNS;
20 use utf8;
22 my $event_dir = "/usr/lib/gosa-si/server/events";
23 use lib "/usr/lib/gosa-si/server/events";
25 BEGIN{}
26 END {}
28 my ($server_ip, $server_mac_address, $server_port, $SIPackages_key, $max_clients, $ldap_uri, $ldap_base, $ldap_admin_dn, $ldap_admin_password, $server_interface);
29 my ($bus_activ, $bus_key, $bus_ip, $bus_port);
30 my $server;
31 my $event_hash;
32 my $network_interface;
33 my $no_bus;
34 my (@ldap_cfg, @pam_cfg, @nss_cfg, $goto_admin, $goto_secret);
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         my $tmp_ldap= Net::LDAP->new($ldap_uri);
75         if( defined($tmp_ldap) ) {
76                 &main::daemon_log("INFO: Searching for servers gosaUnitTag with mac address $server_mac_address",5);
77                 my $mesg= $tmp_ldap->bind($ldap_admin_dn, password => $ldap_admin_password);
78                 # Perform search for Unit Tag
79                 $mesg = $tmp_ldap->search(
80                         base   => $ldap_base,
81                         scope  => 'sub',
82                         attrs  => ['gosaUnitTag'],
83                         filter => "(macaddress=$server_mac_address)"
84                 );
86                 if ($mesg->count == 1) {
87                         my $entry= $mesg->entry(0);
88                         my $unit_tag= $entry->get_value("gosaUnitTag");
89                         if(defined($unit_tag) && length($unit_tag) > 0) {
90                                 &main::daemon_log("INFO: Detected gosaUnitTag $unit_tag for creating entries", 5);
91                                 $main::gosa_unit_tag= $unit_tag;
92                         }
93                 } else {
94                         # Perform another search for Unit Tag
95                         my $hostname= `hostname -f`;
96                         chomp($hostname);
97                         &main::daemon_log("INFO: Searching for servers gosaUnitTag with hostname $hostname",5);
98                         $mesg = $tmp_ldap->search(
99                                 base   => $ldap_base,
100                                 scope  => 'sub',
101                                 attrs  => ['gosaUnitTag'],
102                                 filter => "(&(cn=$hostname)(objectClass=goServer))"
103                         );
104                         if ($mesg->count == 1) {
105                                 my $entry= $mesg->entry(0);
106                                 my $unit_tag= $entry->get_value("gosaUnitTag");
107                                 if(defined($unit_tag) && length($unit_tag) > 0) {
108                                         &main::daemon_log("INFO: Detected gosaUnitTag $unit_tag for creating entries", 5);
109                                         $main::gosa_unit_tag= $unit_tag;
110                                 }
111                         } else {
112                                 # Perform another search for Unit Tag
113                                 $hostname= `hostname -s`;
114                                 chomp($hostname);
115                                 &main::daemon_log("INFO: Searching for servers gosaUnitTag with hostname $hostname",5);
116                                 $mesg = $tmp_ldap->search(
117                                         base   => $ldap_base,
118                                         scope  => 'sub',
119                                         attrs  => ['gosaUnitTag'],
120                                         filter => "(&(cn=$hostname)(objectClass=goServer))"
121                                 );
122                                 if ($mesg->count == 1) {
123                                         my $entry= $mesg->entry(0);
124                                         my $unit_tag= $entry->get_value("gosaUnitTag");
125                                         if(defined($unit_tag) && length($unit_tag) > 0) {
126                                                 &main::daemon_log("INFO: Detected gosaUnitTag $unit_tag for creating entries", 5);
127                                                 $main::gosa_unit_tag= $unit_tag;
128                                         }
129                                 } else {
130                                         &main::daemon_log("WARNING: No gosaUnitTag detected. Not using gosaUnitTag", 3);
131                                 }
132                         }
133                 }
134         $tmp_ldap->unbind;
135         } else {
136                 &main::daemon_log("INFO: Using gosaUnitTag from config-file: $main::gosa_unit_tag",5);
137         }
141 my $server_address = "$server_ip:$server_port";
142 $main::server_address = $server_address;
145 if( inet_aton($bus_ip) ){ $bus_ip = inet_ntoa(inet_aton($bus_ip)); } 
146 ######################################################
147 # to change
148 if( $bus_ip eq "127.0.1.1" ) { $bus_ip = "127.0.0.1" }
149 ######################################################
150 my $bus_address = "$bus_ip:$bus_port";
151 $main::bus_address = $bus_address;
153 # create general settings for this module
154 my $xml = new XML::Simple();
156 # register at bus
157 if ($main::no_bus > 0) {
158     $bus_activ = "off"
160 if($bus_activ eq "on") {
161     &register_at_bus();
164 # add myself to known_server_db
165 my $res = $main::known_server_db->add_dbentry( {table=>'known_server',
166         primkey=>'hostname',
167         hostname=>$server_address,
168         status=>'myself',
169         hostkey=>$SIPackages_key,
170         timestamp=>&get_time,
171         } );
175 ### functions #################################################################
178 sub get_module_info {
179     my @info = ($server_address,
180                 $SIPackages_key,
181                 );
182     return \@info;
186 #===  FUNCTION  ================================================================
187 #         NAME:  read_configfile
188 #   PARAMETERS:  cfg_file - string -
189 #      RETURNS:  nothing
190 #  DESCRIPTION:  read cfg_file and set variables
191 #===============================================================================
192 sub read_configfile {
193     my $cfg;
194     if( defined( $main::cfg_file) && ( length($main::cfg_file) > 0 )) {
195         if( -r $main::cfg_file ) {
196             $cfg = Config::IniFiles->new( -file => $main::cfg_file );
197         } else {
198             print STDERR "Couldn't read config file!";
199         }
200     } else {
201         $cfg = Config::IniFiles->new() ;
202     }
203     foreach my $section (keys %cfg_defaults) {
204         foreach my $param (keys %{$cfg_defaults{ $section }}) {
205             my $pinfo = $cfg_defaults{ $section }{ $param };
206             ${@$pinfo[0]} = $cfg->val( $section, $param, @$pinfo[1] );
207         }
208     }
210     # Read non predefined sections
211     my $param;
212     if ($cfg->SectionExists('ldap')){
213                 foreach $param ($cfg->Parameters('ldap')){
214                         push (@ldap_cfg, "$param ".$cfg->val('ldap', $param));
215                 }
216     }
217     if ($cfg->SectionExists('pam_ldap')){
218                 foreach $param ($cfg->Parameters('pam_ldap')){
219                         push (@pam_cfg, "$param ".$cfg->val('pam_ldap', $param));
220                 }
221     }
222     if ($cfg->SectionExists('nss_ldap')){
223                 foreach $param ($cfg->Parameters('nss_ldap')){
224                         push (@nss_cfg, "$param ".$cfg->val('nss_ldap', $param));
225                 }
226     }
227     if ($cfg->SectionExists('goto')){
228         $goto_admin= $cfg->val('goto', 'terminal_admin');
229         $goto_secret= $cfg->val('goto', 'terminal_secret');
230     } else {
231         $goto_admin= undef;
232         $goto_secret= undef;
233     }
237 #===  FUNCTION  ================================================================
238 #         NAME:  get_interface_for_ip
239 #   PARAMETERS:  ip address (i.e. 192.168.0.1)
240 #      RETURNS:  array: list of interfaces if ip=0.0.0.0, matching interface if found, undef else
241 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
242 #===============================================================================
243 sub get_interface_for_ip {
244         my $result;
245         my $ip= shift;
246         if ($ip && length($ip) > 0) {
247                 my @ifs= &get_interfaces();
248                 if($ip eq "0.0.0.0") {
249                         $result = "all";
250                 } else {
251                         foreach (@ifs) {
252                                 my $if=$_;
253                                 if(get_ip($if) eq $ip) {
254                                         $result = $if;
255                                 }
256                         }       
257                 }
258         }       
259         return $result;
262 #===  FUNCTION  ================================================================
263 #         NAME:  get_interfaces 
264 #   PARAMETERS:  none
265 #      RETURNS:  (list of interfaces) 
266 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
267 #===============================================================================
268 sub get_interfaces {
269         my @result;
270         my $PROC_NET_DEV= ('/proc/net/dev');
272         open(PROC_NET_DEV, "<$PROC_NET_DEV")
273                 or die "Could not open $PROC_NET_DEV";
275         my @ifs = <PROC_NET_DEV>;
277         close(PROC_NET_DEV);
279         # Eat first two line
280         shift @ifs;
281         shift @ifs;
283         chomp @ifs;
284         foreach my $line(@ifs) {
285                 my $if= (split /:/, $line)[0];
286                 $if =~ s/^\s+//;
287                 push @result, $if;
288         }
290         return @result;
293 #===  FUNCTION  ================================================================
294 #         NAME:  get_mac 
295 #   PARAMETERS:  interface name (i.e. eth0)
296 #      RETURNS:  (mac address) 
297 #  DESCRIPTION:  Uses ioctl to get mac address directly from system.
298 #===============================================================================
299 sub get_mac {
300         my $ifreq= shift;
301         my $result;
302         if ($ifreq && length($ifreq) > 0) { 
303                 if($ifreq eq "all") {
304                         $result = "00:00:00:00:00:00";
305                 } else {
306                         my $SIOCGIFHWADDR= 0x8927;     # man 2 ioctl_list
308                         # A configured MAC Address should always override a guessed value
309                         if ($server_mac_address and length($server_mac_address) > 0) {
310                                 $result= $server_mac_address;
311                         }
313                         socket SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('ip')
314                                 or die "socket: $!";
316                         if(ioctl SOCKET, $SIOCGIFHWADDR, $ifreq) {
317                                 my ($if, $mac)= unpack 'h36 H12', $ifreq;
319                                 if (length($mac) > 0) {
320                                         $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])$/;
321                                         $mac= sprintf("%s:%s:%s:%s:%s:%s", $1, $2, $3, $4, $5, $6);
322                                         $result = $mac;
323                                 }
324                         }
325                 }
326         }
327         return $result;
331 #===  FUNCTION  ================================================================
332 #         NAME:  register_at_bus
333 #   PARAMETERS:  nothing
334 #      RETURNS:  nothing
335 #  DESCRIPTION:  creates an entry in known_daemons and send a 'here_i_am' msg to bus
336 #===============================================================================
337 sub register_at_bus {
339     # add bus to known_server_db
340     my $res = $main::known_server_db->add_dbentry( {table=>'known_server',
341                                                     primkey=>'hostname',
342                                                     hostname=>$bus_address,
343                                                     status=>'bus',
344                                                     hostkey=>$bus_key,
345                                                     timestamp=>&get_time,
346                                                 } );
347     my $msg_hash = &create_xml_hash("here_i_am", $server_address, $bus_address);
348     my $msg = &create_xml_string($msg_hash);
350     &main::send_msg_to_target($msg, $bus_address, $bus_key, "here_i_am");
351     return $msg;
355 sub import_events {
356     if (not -e $event_dir) {
357         &main::daemon_log("ERROR: cannot find directory or directory is not readable: $event_dir", 1);   
358     }
359     opendir (DIR, $event_dir) or die "ERROR while loading gosa-si-events from directory $event_dir : $!\n";
361     while (defined (my $event = readdir (DIR))) {
362         if( $event eq "." || $event eq ".." ) { next; }  
363         if( $event eq "gosaTriggered.pm" ) { next; }    # only GOsa specific events
365         eval{ require $event; };
366         if( $@ ) {
367             &main::daemon_log("import of event module '$event' failed", 1);
368             &main::daemon_log("$@", 8);
369             next;
370         }
372         $event =~ /(\S*?).pm$/;
373         my $event_module = $1;
374         my $events_l = eval( $1."::get_events()") ;
375         foreach my $event_name (@{$events_l}) {
376             $event_hash->{$event_name} = $event_module;
377         }
378         my $events_string = join( ", ", @{$events_l});
379         &main::daemon_log("INFO: SIPackages imported events $events_string", 5);
380     }
384 #===  FUNCTION  ================================================================
385 #         NAME:  process_incoming_msg
386 #   PARAMETERS:  crypted_msg - string - incoming crypted message
387 #      RETURNS:  nothing
388 #  DESCRIPTION:  handels the proceeded distribution to the appropriated functions
389 #===============================================================================
390 sub process_incoming_msg {
391     my ($msg, $msg_hash, $session_id) = @_ ;
392     my $error = 0;
393     my $host_name;
394     my $host_key;
395     my @out_msg_l = ();
397     # process incoming msg
398     my $header = @{$msg_hash->{header}}[0]; 
399     my @target_l = @{$msg_hash->{target}};
401     # skip PREFIX
402     $header =~ s/^CLMSG_//;
404     &main::daemon_log("DEBUG: SIPackages: msg to process: $header", 7);
405     &main::daemon_log("$msg", 8);
407     if( 0 == length @target_l){     
408         &main::daemon_log("ERROR: no target specified for msg $header", 1);
409         $error++;
410     }
412     if( 1 == length @target_l) {
413         my $target = $target_l[0];
414                 if(&server_matches($target)) {
417             if ($header eq 'new_key') {
418                 @out_msg_l = &new_key($msg_hash)
419             } elsif ($header eq 'here_i_am') {
420                 @out_msg_l = &here_i_am($msg_hash)
421             } else {
422                 if( exists $event_hash->{$header} ) {
423                     # a event exists with the header as name
424                     &main::daemon_log("INFO: found event '$header' at event-module '".$event_hash->{$header}."'", 5);
425                     no strict 'refs';
426                     @out_msg_l = &{$event_hash->{$header}."::$header"}($msg, $msg_hash, $session_id);
427                 }
428             }
430             # if delivery not possible raise error and return 
431             if( not @out_msg_l ) {
432                 &main::daemon_log("WARNING: SIPackages got not answer from event handler '$header'", 3);
433             } elsif( 0 == @out_msg_l) {
434                 &main::daemon_log("ERROR: SIPackages: no event handler or core function defined for '$header'", 1);
435             } 
436         }
437                 else {
438                         &main::daemon_log("INFO: msg is not for gosa-si-server '$server_address', deliver it to target '$target'", 5);
439                         push(@out_msg_l, $msg);
440                 }
441     }
443     return \@out_msg_l;
447 #===  FUNCTION  ================================================================
448 #         NAME:  new_passwd
449 #   PARAMETERS:  msg_hash - ref - hash from function create_xml_hash
450 #      RETURNS:  nothing
451 #  DESCRIPTION:  process this incoming message
452 #===============================================================================
453 sub new_key {
454     my ($msg_hash) = @_;
455     my @out_msg_l;
456     
457     my $header = @{$msg_hash->{header}}[0];
458     my $source_name = @{$msg_hash->{source}}[0];
459     my $source_key = @{$msg_hash->{new_key}}[0];
460     my $query_res;
462     # check known_clients_db
463     my $sql_statement = "SELECT * FROM known_clients WHERE hostname='$source_name'";
464     $query_res = $main::known_clients_db->select_dbentry( $sql_statement );
465     if( 1 == keys %{$query_res} ) {
466         my $act_time = &get_time;
467         my $sql_statement= "UPDATE known_clients ".
468             "SET hostkey='$source_key', timestamp='$act_time' ".
469             "WHERE hostname='$source_name'";
470         my $res = $main::known_clients_db->update_dbentry( $sql_statement );
471         my $hash = &create_xml_hash("confirm_new_key", $server_address, $source_name);
472         my $out_msg = &create_xml_string($hash);
473         push(@out_msg_l, $out_msg);
474     }
476     # only do if host still not found
477     if( 0 == @out_msg_l ) {
478         # check known_server_db
479         $sql_statement = "SELECT * FROM known_server WHERE hostname='$source_name'";
480         $query_res = $main::known_server_db->select_dbentry( $sql_statement );
481         if( 1 == keys %{$query_res} ) {
482             my $act_time = &get_time;
483             my $sql_statement= "UPDATE known_server ".
484                 "SET hostkey='$source_key', timestamp='$act_time' ".
485                 "WHERE hostname='$source_name'";
486             my $res = $main::known_server_db->update_dbentry( $sql_statement );
488             my $hash = &create_xml_hash("confirm_new_key", $server_address, $source_name);
489             my $out_msg = &create_xml_string($hash);
490             push(@out_msg_l, $out_msg);
491         }
492     }
494     return @out_msg_l;
498 #===  FUNCTION  ================================================================
499 #         NAME:  here_i_am
500 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
501 #      RETURNS:  nothing
502 #  DESCRIPTION:  process this incoming message
503 #===============================================================================
504 sub here_i_am {
505     my ($msg_hash) = @_;
506     my @out_msg_l;
507     my $out_hash;
509     my $source = @{$msg_hash->{source}}[0];
510     my $mac_address = @{$msg_hash->{mac_address}}[0];
511         my $gotoHardwareChecksum = @{$msg_hash->{gotoHardwareChecksum}}[0];
513     # number of known clients
514     my $nu_clients= $main::known_clients_db->count_dbentries('known_clients');
516     # check wether client address or mac address is already known
517     my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$source'";
518     my $db_res= $main::known_clients_db->select_dbentry( $sql_statement );
519     
520     if ( 1 == keys %{$db_res} ) {
521         &main::daemon_log("WARNING: $source is already known as a client", 1);
522         &main::daemon_log("WARNING: values for $source are being overwritten", 1);   
523         $nu_clients --;
524     }
526     # number of actual activ clients
527     my $act_nu_clients = $nu_clients;
529     &main::daemon_log("INFO: number of actual activ clients: $act_nu_clients", 5);
530     &main::daemon_log("INFO: number of maximal allowed clients: $max_clients", 5);
532     if($max_clients <= $act_nu_clients) {
533         my $out_hash = &create_xml_hash("denied", $server_address, $source);
534         &add_content2xml_hash($out_hash, "denied", "I_cannot_take_any_more_clients!");
535         my $passwd = @{$msg_hash->{new_passwd}}[0]; 
536         &send_msg_hash2address($out_hash, $source, $passwd);
537         return;
538     }
539     
540     # new client accepted
541     my $new_passwd = @{$msg_hash->{new_passwd}}[0];
543     # create entry in known_clients
544     my $events = @{$msg_hash->{events}}[0];
545     
547     # add entry to known_clients_db
548     my $act_timestamp = &get_time;
549     my $res = $main::known_clients_db->add_dbentry( {table=>'known_clients', 
550                                                 primkey=>'hostname',
551                                                 hostname=>$source,
552                                                 events=>$events,
553                                                 macaddress=>$mac_address,
554                                                 status=>'registered',
555                                                 hostkey=>$new_passwd,
556                                                 timestamp=>$act_timestamp,
557                                                 login=>"nobody",
558                                                 } );
560     if ($res != 0)  {
561         &main::daemon_log("ERROR: cannot add entry to known_clients: $res");
562         return;
563     }
564     
565     # return acknowledgement to client
566     $out_hash = &create_xml_hash("registered", $server_address, $source);
567     my $register_out = &create_xml_string($out_hash);
568     push(@out_msg_l, $register_out);
570     # notify registered client to bus
571     if( $bus_activ eq "on") {
572         # fetch actual bus key
573         my $sql_statement= "SELECT * FROM known_server WHERE status='bus'";
574         my $query_res = $main::known_server_db->select_dbentry( $sql_statement );
575         my $hostkey = $query_res->{1}->{'hostkey'};
577         # send update msg to bus
578         $out_hash = &create_xml_hash("new_client", $server_address, $bus_address, $source);
579         &add_content2xml_hash($out_hash, "macaddress", $mac_address);
580         &add_content2xml_hash($out_hash, "timestamp", $act_timestamp);
581         my $new_client_out = &create_xml_string($out_hash);
582         push(@out_msg_l, $new_client_out);
583         &main::daemon_log("INFO: send bus msg that client '$source' has registerd at server '$server_address'", 5);
584     }
586     # give the new client his ldap config
587     my $new_ldap_config_out = &new_ldap_config($source);
588     if( $new_ldap_config_out ) {
589         push(@out_msg_l, $new_ldap_config_out);
590     }
592         my $hardware_config_out = &hardware_config($source, $gotoHardwareChecksum);
593         if( $hardware_config_out ) {
594                 push(@out_msg_l, $hardware_config_out);
595         }
597     return @out_msg_l;
601 #===  FUNCTION  ================================================================
602 #         NAME:  who_has
603 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
604 #      RETURNS:  nothing 
605 #  DESCRIPTION:  process this incoming message
606 #===============================================================================
607 sub who_has {
608     my ($msg_hash) = @_ ;
609     my @out_msg_l;
610     
611     # what is your search pattern
612     my $search_pattern = @{$msg_hash->{who_has}}[0];
613     my $search_element = @{$msg_hash->{$search_pattern}}[0];
614     &main::daemon_log("who_has-msg looking for $search_pattern $search_element", 7);
616     # scanning known_clients for search_pattern
617     my @host_addresses = keys %$main::known_clients;
618     my $known_clients_entries = length @host_addresses;
619     my $host_address;
620     foreach my $host (@host_addresses) {
621         my $client_element = $main::known_clients->{$host}->{$search_pattern};
622         if ($search_element eq $client_element) {
623             $host_address = $host;
624             last;
625         }
626     }
627         
628     # search was successful
629     if (defined $host_address) {
630         my $source = @{$msg_hash->{source}}[0];
631         my $out_hash = &create_xml_hash("who_has_i_do", $server_address, $source, "mac_address");
632         &add_content2xml_hash($out_hash, "mac_address", $search_element);
633         my $out_msg = &create_xml_string($out_hash);
634         push(@out_msg_l, $out_msg);
635     }
636     return @out_msg_l;
640 sub who_has_i_do {
641     my ($msg_hash) = @_ ;
642     my $header = @{$msg_hash->{header}}[0];
643     my $source = @{$msg_hash->{source}}[0];
644     my $search_param = @{$msg_hash->{$header}}[0];
645     my $search_value = @{$msg_hash->{$search_param}}[0];
646     print "\ngot msg $header:\nserver $source has client with $search_param $search_value\n";
649 #===  FUNCTION  ================================================================
650 #         NAME:  new_ldap_config
651 #   PARAMETERS:  address - string - ip address and port of a host
652 #      RETURNS:  nothing
653 #  DESCRIPTION:  send to address the ldap configuration found for dn gotoLdapServer
654 #===============================================================================
655 sub new_ldap_config {
656         my ($address) = @_ ;
658         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address' OR macaddress='$address'";
659         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
661         # check hit
662         my $hit_counter = keys %{$res};
663         if( not $hit_counter == 1 ) {
664                 &main::daemon_log("ERROR: more or no hit found in known_clients_db by query by '$address'", 1);
665         }
667     $address = $res->{1}->{hostname};
668         my $macaddress = $res->{1}->{macaddress};
669         my $hostkey = $res->{1}->{hostkey};
671         if (not defined $macaddress) {
672                 &main::daemon_log("ERROR: no mac address found for client $address", 1);
673                 return;
674         }
676         # Build LDAP connection
677         my $ldap = Net::LDAP->new($ldap_uri);
678         if( not defined $ldap ) {
679                 &main::daemon_log("ERROR: cannot connect to ldap: $ldap_uri", 1);
680                 return;
681         } 
684         # Bind to a directory with dn and password
685         my $mesg= $ldap->bind($ldap_admin_dn, password => $ldap_admin_password);
687         # Perform search
688         $mesg = $ldap->search( base   => $ldap_base,
689                 scope  => 'sub',
690                 attrs => ['dn', 'gotoLdapServer', 'gosaUnitTag', 'FAIclass'],
691                 filter => "(&(objectClass=GOhard)(macaddress=$macaddress))");
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 mac address $macaddress not found/not unique in ldap search", 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))", 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 = $ldap->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 =~ /^ldap[^:]+:\/\// ) {
758                     if ($server =~ /^([^:]+):(.*)$/ ) {
759                 $server= "1:dummy:ldap://$1/$2";
760                     }
761                 }
763                 $base= $server;
764                 $server =~ s%^[^:]+:[^:]+:(ldap.*://[^/]+)/.*$%$1%;
765                 $base =~ s%^[^:]+:[^:]+:ldap.*://[^/]+/(.*)$%$1%;
766                 push (@ldap_uris, $server);
767         }
769         # Assemble data package
770         my %data = ( 'ldap_uri'  => \@ldap_uris, 'ldap_base' => $base,
771                 'ldap_cfg' => \@ldap_cfg, 'pam_cfg' => \@pam_cfg,'nss_cfg' => \@nss_cfg );
772         if (defined $release){
773                 $data{'release'}= $release;
774         }
776         # Need to append GOto settings?
777         if (defined $goto_admin and defined $goto_secret){
778                 $data{'goto_admin'}= $goto_admin;
779                 $data{'goto_secret'}= $goto_secret;
780         }
782         # Append unit tag if needed
783         if (defined $unit_tag){
785                 # Find admin base and department name
786                 $mesg = $ldap->search( base   => $ldap_base,
787                         scope  => 'sub',
788                         attrs => ['dn', 'ou'],
789                         filter => "(&(objectClass=gosaAdministrativeUnit)(gosaUnitTag=$unit_tag))");
790                 #$mesg->code && die $mesg->error;
791                 if($mesg->code) {
792                         &main::daemon_log($mesg->error, 1);
793                         return;
794                 }
796                 # Sanity check
797                 if ($mesg->count != 1) {
798                         &main::daemon_log("WARNING: cannot find administrative unit for client with tag $unit_tag", 1);
799                         return;
800                 }
802                 $entry= $mesg->entry(0);
803                 $data{'admin_base'}= $entry->dn;
804                 $data{'department'}= $entry->get_value("ou");
806                 # Append unit Tag
807                 $data{'unit_tag'}= $unit_tag;
808         }
811         # Unbind
812         $mesg = $ldap->unbind;
813         if($mesg->code) {
814                 &main::daemon_log($mesg->error, 1);
815                 return;
816         }
818         # Send information
819         return &build_msg("new_ldap_config", $server_address, $address, \%data);
823 #===  FUNCTION  ================================================================
824 #         NAME:  hardware_config
825 #   PARAMETERS:  address - string - ip address and port of a host
826 #      RETURNS:  
827 #  DESCRIPTION:  
828 #===============================================================================
829 sub hardware_config {
830         my ($address, $gotoHardwareChecksum) = @_ ;
832         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address'";
833         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
835         # check hit
836         my $hit_counter = keys %{$res};
837         if( not $hit_counter == 1 ) {
838                 &main::daemon_log("ERROR: more or no hit found in known_clients_db by query by '$address'", 1);
839         }
841         my $macaddress = $res->{1}->{macaddress};
842         my $hostkey = $res->{1}->{hostkey};
844         if (not defined $macaddress) {
845                 &main::daemon_log("ERROR: no mac address found for client $address", 1);
846                 return;
847         }
849         # Build LDAP connection
850         my $ldap = Net::LDAP->new($ldap_uri);
851         if( not defined $ldap ) {
852                 &main::daemon_log("ERROR: cannot connect to ldap: $ldap_uri", 1);
853                 return;
854         } 
856         # Bind to a directory with dn and password
857         my $mesg= $ldap->bind($ldap_admin_dn, password => $ldap_admin_password);
859         # Perform search
860         $mesg = $ldap->search(
861                 base   => $ldap_base,
862                 scope  => 'sub',
863                 filter => "(&(objectClass=GOhard)(|(macAddress=$macaddress)(dhcpHWaddress=ethernet $macaddress)))"
864         );
866         if($mesg->count() == 0) {
867                 &main::daemon_log("Host was not found in LDAP!", 1);
868         } else {
869                 my $entry= $mesg->entry(0);
870                 my $dn= $entry->dn;
871                 if(defined($entry->get_value("gotoHardwareChecksum"))) {
872                         if(! $entry->get_value("gotoHardwareChecksum") eq $gotoHardwareChecksum) {
873                                 $entry->replace(gotoHardwareChecksum => $gotoHardwareChecksum);
874                                 if($entry->update($ldap)) {
875                                         &main::daemon_log("Hardware changed! Detection triggered.", 4);
876                                 }
877                         } else {
878                                 # Nothing to do
879                                 return;
880                         }
881                 }
882         } 
884         # Assemble data package
885         my %data = ();
887         # Need to append GOto settings?
888         if (defined $goto_admin and defined $goto_secret){
889                 $data{'goto_admin'}= $goto_admin;
890                 $data{'goto_secret'}= $goto_secret;
891         }
893         # Unbind
894         $mesg = $ldap->unbind;
896         &main::daemon_log("Send detect_hardware message to $address", 4);
898         # Send information
899         return &build_msg("detect_hardware", $server_address, $address, \%data);
902 sub server_matches {
903         my $target = shift;
904         my $target_ip = sprintf("%s", $target =~ /^([0-9\.]*?):.*$/);
905         my $result = 0;
907         if($server_ip eq $target_ip) {
908                 $result= 1;
909         } elsif ($server_ip eq "0.0.0.0") {     
910                 if ($target_ip eq "127.0.0.1") {
911                         $result= 1;
912                 } else {
913                         my $PROC_NET_ROUTE= ('/proc/net/route');
915                         open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
916                                 or die "Could not open $PROC_NET_ROUTE";
918                         my @ifs = <PROC_NET_ROUTE>;
920                         close(PROC_NET_ROUTE);
922                         # Eat header line
923                         shift @ifs;
924                         chomp @ifs;
925                         foreach my $line(@ifs) {
926                                 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
927                                 my $destination;
928                                 my $mask;
929                                 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
930                                 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
931                                 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
932                                 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
933                                 if(new NetAddr::IP($target_ip)->within(new NetAddr::IP($destination, $mask))) {
934                                         # destination matches route, save mac and exit
935                                         $result= 1;
936                                         last;
937                                 }
938                         }
939                 }
940         } else {
941                 &main::daemon_log("Target ip $target_ip does not match Server ip $server_ip",1);
942         }
944         return $result;
947 1;