Code

Added additional searches if mac address search is not successfull
[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;
21 BEGIN{}
22 END {}
24 my ($server_ip, $server_mac_address, $server_port, $SIPackages_key, $max_clients, $ldap_uri, $ldap_base, $ldap_admin_dn, $ldap_admin_password, $server_interface);
25 my ($bus_activ, $bus_key, $bus_ip, $bus_port);
26 my $server;
27 my $network_interface;
28 my $no_bus;
29 my (@ldap_cfg, @pam_cfg, @nss_cfg, $goto_admin, $goto_secret, $gosa_unit_tag);
32 my %cfg_defaults = (
33 "bus" => {
34     "activ" => [\$bus_activ, "on"],
35     "key" => [\$bus_key, ""],
36     "ip" => [\$bus_ip, ""],
37     "port" => [\$bus_port, "20080"],
38     },
39 "server" => {
40     "ip" => [\$server_ip, "0.0.0.0"],
41     "mac-address" => [\$server_mac_address, "00:00:00:00:00"],
42     "port" => [\$server_port, "20081"],
43     "ldap-uri" => [\$ldap_uri, ""],
44     "ldap-base" => [\$ldap_base, ""],
45     "ldap-admin-dn" => [\$ldap_admin_dn, ""],
46     "ldap-admin-password" => [\$ldap_admin_password, ""],
47     "max-clients" => [\$max_clients, 100],
48         "gosa-unit-tag" => [\$gosa_unit_tag, ""],
49     },
50 "SIPackages" => {
51     "key" => [\$SIPackages_key, ""],
52     },
53 );
55 ### START #####################################################################
57 # read configfile and import variables
58 &read_configfile();
60 $network_interface= &get_interface_for_ip($server_ip);
61 $server_mac_address= &get_mac($network_interface);
63 # Unit tag can be defined in config
64 if((not defined($gosa_unit_tag)) || length($gosa_unit_tag) == 0) {
65         # Read gosaUnitTag from LDAP
66         my $tmp_ldap= Net::LDAP->new($ldap_uri);
67         if(defined($tmp_ldap)) {
68                 &main::daemon_log("Searching for servers gosaUnitTag with mac address $server_mac_address",6);
69                 my $mesg= $tmp_ldap->bind($ldap_admin_dn, password => $ldap_admin_password);
70                 # Perform search for Unit Tag
71                 $mesg = $tmp_ldap->search(
72                         base   => $ldap_base,
73                         scope  => 'sub',
74                         attrs  => ['gosaUnitTag'],
75                         filter => "(macaddress=$server_mac_address)"
76                 );
78                 if ($mesg->count == 1) {
79                         my $entry= $mesg->entry(0);
80                         my $unit_tag= $entry->get_value("gosaUnitTag");
81                         if(defined($unit_tag) && length($unit_tag) > 0) {
82                                 &main::daemon_log("Detected gosaUnitTag $unit_tag for creating entries", 4);
83                                 $gosa_unit_tag= $unit_tag;
84                         }
85                 } else {
86                         # Perform another search for Unit Tag
87                         my $hostname= `hostname -f`;
88                         $mesg = $tmp_ldap->search(
89                                 base   => $ldap_base,
90                                 scope  => 'sub',
91                                 attrs  => ['gosaUnitTag'],
92                                 filter => "(&(cn=$hostname)(objectClass=goServer))"
93                         );
94                         if ($mesg->count == 1) {
95                                 my $entry= $mesg->entry(0);
96                                 my $unit_tag= $entry->get_value("gosaUnitTag");
97                                 if(defined($unit_tag) && length($unit_tag) > 0) {
98                                         &main::daemon_log("Detected gosaUnitTag $unit_tag for creating entries", 4);
99                                         $gosa_unit_tag= $unit_tag;
100                                 }
101                         } else {
102                                 # Perform another search for Unit Tag
103                                 $hostname= `hostname -s`;
104                                 $mesg = $tmp_ldap->search(
105                                         base   => $ldap_base,
106                                         scope  => 'sub',
107                                         attrs  => ['gosaUnitTag'],
108                                         filter => "(&(cn=$hostname)(objectClass=goServer))"
109                                 );
110                                 if ($mesg->count == 1) {
111                                         my $entry= $mesg->entry(0);
112                                         my $unit_tag= $entry->get_value("gosaUnitTag");
113                                         if(defined($unit_tag) && length($unit_tag) > 0) {
114                                                 &main::daemon_log("Detected gosaUnitTag $unit_tag for creating entries", 4);
115                                                 $gosa_unit_tag= $unit_tag;
116                                         }
117                                 } else {
118                                         &main::daemon_log("Not using gosaUnitTag", 6);
119                                 }
120                         }
121                 }
122         } else {
123                 &main::daemon_log("Using gosaUnitTag from config-file: $gosa_unit_tag",6);
124         }
125         $tmp_ldap->unbind;
128 # complete addresses
129 #if( $server_ip eq "0.0.0.0" ) {
130 #    $server_ip = "127.0.0.1";
131 #}
132 my $server_address = "$server_ip:$server_port";
133 $main::server_address = $server_address;
134 my $bus_address = "$bus_ip:$bus_port";
135 $main::bus_address = $bus_address;
137 # create general settings for this module
138 my $xml = new XML::Simple();
140 # register at bus
141 if ($main::no_bus > 0) {
142     $bus_activ = "off"
144 if($bus_activ eq "on") {
145     &register_at_bus();
148 # add myself to known_server_db
149 my $res = $main::known_server_db->add_dbentry( {table=>'known_server',
150         primkey=>'hostname',
151         hostname=>$server_address,
152         status=>'myself',
153         hostkey=>$SIPackages_key,
154         timestamp=>&get_time,
155         } );
159 ### functions #################################################################
162 sub get_module_info {
163     my @info = ($server_address,
164                 $SIPackages_key,
165                 );
166     return \@info;
170 sub do_wake {
171         my $host    = shift;
172         my $ipaddr  = shift || '255.255.255.255';
173         my $port    = getservbyname('discard', 'udp');
175         my ($raddr, $them, $proto);
176         my ($hwaddr, $hwaddr_re, $pkt);
178         # get the hardware address (ethernet address)
180         $hwaddr_re = join(':', ('[0-9A-Fa-f]{1,2}') x 6);
181         if ($host =~ m/^$hwaddr_re$/) {
182                 $hwaddr = $host;
183         } else {
184                 # $host is not a hardware address, try to resolve it
185                 my $ip_re = join('\.', ('([0-9]|[1-9][0-9]|1[0-9]{2}|2([0-4][0-9]|5[0-5]))') x 4);
186                 my $ip_addr;
187                 if ($host =~ m/^$ip_re$/) {
188                         $ip_addr = $host;
189                 } else {
190                         my $h;
191                         unless ($h = gethost($host)) {
192                                 return undef;
193                         }
194                         $ip_addr = inet_ntoa($h->addr);
195                 }
196         }
198         # Generate magic sequence
199         foreach (split /:/, $hwaddr) {
200                 $pkt .= chr(hex($_));
201         }
202         $pkt = chr(0xFF) x 6 . $pkt x 16;
204         # Allocate socket and send packet
206         $raddr = gethostbyname($ipaddr)->addr;
207         $them = pack_sockaddr_in($port, $raddr);
208         $proto = getprotobyname('udp');
210         socket(S, AF_INET, SOCK_DGRAM, $proto) or die "socket : $!";
211         setsockopt(S, SOL_SOCKET, SO_BROADCAST, 1) or die "setsockopt : $!";
213         send(S, $pkt, 0, $them) or die "send : $!";
214         close S;
218 #===  FUNCTION  ================================================================
219 #         NAME:  read_configfile
220 #   PARAMETERS:  cfg_file - string -
221 #      RETURNS:  nothing
222 #  DESCRIPTION:  read cfg_file and set variables
223 #===============================================================================
224 sub read_configfile {
225     my $cfg;
226     if( defined( $main::cfg_file) && ( length($main::cfg_file) > 0 )) {
227         if( -r $main::cfg_file ) {
228             $cfg = Config::IniFiles->new( -file => $main::cfg_file );
229         } else {
230             print STDERR "Couldn't read config file!";
231         }
232     } else {
233         $cfg = Config::IniFiles->new() ;
234     }
235     foreach my $section (keys %cfg_defaults) {
236         foreach my $param (keys %{$cfg_defaults{ $section }}) {
237             my $pinfo = $cfg_defaults{ $section }{ $param };
238             ${@$pinfo[0]} = $cfg->val( $section, $param, @$pinfo[1] );
239         }
240     }
242     # Read non predefined sections
243     my $param;
244     if ($cfg->SectionExists('ldap')){
245                 foreach $param ($cfg->Parameters('ldap')){
246                         push (@ldap_cfg, "$param ".$cfg->val('ldap', $param));
247                 }
248     }
249     if ($cfg->SectionExists('pam_ldap')){
250                 foreach $param ($cfg->Parameters('pam_ldap')){
251                         push (@pam_cfg, "$param ".$cfg->val('pam_ldap', $param));
252                 }
253     }
254     if ($cfg->SectionExists('nss_ldap')){
255                 foreach $param ($cfg->Parameters('nss_ldap')){
256                         push (@nss_cfg, "$param ".$cfg->val('nss_ldap', $param));
257                 }
258     }
259     if ($cfg->SectionExists('goto')){
260         $goto_admin= $cfg->val('goto', 'terminal_admin');
261         $goto_secret= $cfg->val('goto', 'terminal_secret');
262     } else {
263         $goto_admin= undef;
264         $goto_secret= undef;
265     }
269 #===  FUNCTION  ================================================================
270 #         NAME:  get_interface_for_ip
271 #   PARAMETERS:  ip address (i.e. 192.168.0.1)
272 #      RETURNS:  array: list of interfaces if ip=0.0.0.0, matching interface if found, undef else
273 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
274 #===============================================================================
275 sub get_interface_for_ip {
276         my $result;
277         my $ip= shift;
278         if ($ip && length($ip) > 0) {
279                 my @ifs= &get_interfaces();
280                 if($ip eq "0.0.0.0") {
281                         $result = "all";
282                 } else {
283                         foreach (@ifs) {
284                                 my $if=$_;
285                                 if(get_ip($if) eq $ip) {
286                                         $result = $if;
287                                 }
288                         }       
289                 }
290         }       
291         return $result;
294 #===  FUNCTION  ================================================================
295 #         NAME:  get_interfaces 
296 #   PARAMETERS:  none
297 #      RETURNS:  (list of interfaces) 
298 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
299 #===============================================================================
300 sub get_interfaces {
301         my @result;
302         my $PROC_NET_DEV= ('/proc/net/dev');
304         open(PROC_NET_DEV, "<$PROC_NET_DEV")
305                 or die "Could not open $PROC_NET_DEV";
307         my @ifs = <PROC_NET_DEV>;
309         close(PROC_NET_DEV);
311         # Eat first two line
312         shift @ifs;
313         shift @ifs;
315         chomp @ifs;
316         foreach my $line(@ifs) {
317                 my $if= (split /:/, $line)[0];
318                 $if =~ s/^\s+//;
319                 push @result, $if;
320         }
322         return @result;
325 #===  FUNCTION  ================================================================
326 #         NAME:  get_mac 
327 #   PARAMETERS:  interface name (i.e. eth0)
328 #      RETURNS:  (mac address) 
329 #  DESCRIPTION:  Uses ioctl to get mac address directly from system.
330 #===============================================================================
331 sub get_mac {
332         my $ifreq= shift;
333         my $result;
334         if ($ifreq && length($ifreq) > 0) { 
335                 if($ifreq eq "all") {
336                         $result = "00:00:00:00:00:00";
337                 } else {
338                         my $SIOCGIFHWADDR= 0x8927;     # man 2 ioctl_list
340                         # A configured MAC Address should always override a guessed value
341                         if ($server_mac_address and length($server_mac_address) > 0) {
342                                 $result= $server_mac_address;
343                         }
345                         socket SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('ip')
346                                 or die "socket: $!";
348                         if(ioctl SOCKET, $SIOCGIFHWADDR, $ifreq) {
349                                 my ($if, $mac)= unpack 'h36 H12', $ifreq;
351                                 if (length($mac) > 0) {
352                                         $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])$/;
353                                         $mac= sprintf("%s:%s:%s:%s:%s:%s", $1, $2, $3, $4, $5, $6);
354                                         $result = $mac;
355                                 }
356                         }
357                 }
358         }
359         return $result;
363 #===  FUNCTION  ================================================================
364 #         NAME:  register_at_bus
365 #   PARAMETERS:  nothing
366 #      RETURNS:  nothing
367 #  DESCRIPTION:  creates an entry in known_daemons and send a 'here_i_am' msg to bus
368 #===============================================================================
369 sub register_at_bus {
371     # add bus to known_server_db
372     my $res = $main::known_server_db->add_dbentry( {table=>'known_server',
373                                                     primkey=>'hostname',
374                                                     hostname=>$bus_address,
375                                                     status=>'bus',
376                                                     hostkey=>$bus_key,
377                                                     timestamp=>&get_time,
378                                                 } );
379     my $msg_hash = &create_xml_hash("here_i_am", $server_address, $bus_address);
380     my $msg = &create_xml_string($msg_hash);
382     &main::send_msg_to_target($msg, $bus_address, $bus_key, "here_i_am");
383     return $msg;
387 #===  FUNCTION  ================================================================
388 #         NAME:  process_incoming_msg
389 #   PARAMETERS:  crypted_msg - string - incoming crypted message
390 #      RETURNS:  nothing
391 #  DESCRIPTION:  handels the proceeded distribution to the appropriated functions
392 #===============================================================================
393 sub process_incoming_msg {
394     my ($msg, $msg_hash, $remote_ip) = @_ ;
395     my $error = 0;
396     my $host_name;
397     my $host_key;
398     my @out_msg_l;
400     # process incoming msg
401     my $header = @{$msg_hash->{header}}[0]; 
402     my @target_l = @{$msg_hash->{target}};
404     &main::daemon_log("SIPackages: msg to process: $header", 3);
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)) {
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             } elsif ($header eq 'who_has') {
420                 @out_msg_l = &who_has($msg_hash)
421             } elsif ($header eq 'who_has_i_do') {
422                 @out_msg_l = &who_has_i_do($msg_hash)
423             } elsif ($header eq 'got_ping') {
424                 @out_msg_l = &got_ping($msg_hash)
425             } elsif ($header eq 'get_load') {
426                 @out_msg_l = &execute_actions($msg_hash)
427             } elsif ($header eq 'detected_hardware') {
428                 @out_msg_l = &process_detected_hardware($msg_hash)
429             } elsif ($header eq 'trigger_wake') {
430                 foreach (@{$msg_hash->{macAddress}}){
431                     &main::daemon_log("SIPackages: trigger wake for $_", 1);
432                     do_wake($_);
433                 }
435             } else {
436                 &main::daemon_log("ERROR: $header is an unknown core function", 1);
437                 $error++;
438             }
439         }
440                 else {
441                         &main::daemon_log("msg is not for gosa-si-server '$server_address', deliver it to target '$target'", 5);
442                         push(@out_msg_l, $msg);
443                 }
444     }
446 #    if( $error == 0) {
447 #        if( 0 == @out_msg_l ) {
448 #                       push(@out_msg_l, $msg);
449 #        }
450 #    }
451     
452     return \@out_msg_l;
456 #===  FUNCTION  ================================================================
457 #         NAME:  got_ping
458 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
459 #      RETURNS:  nothing
460 #  DESCRIPTION:  process this incoming message
461 #===============================================================================
462 sub got_ping {
463     my ($msg_hash) = @_;
464     
465     my $source = @{$msg_hash->{source}}[0];
466     my $target = @{$msg_hash->{target}}[0];
467     my $header = @{$msg_hash->{header}}[0];
468     
469     if(exists $main::known_daemons->{$source}) {
470         &main::add_content2known_daemons(hostname=>$source, status=>$header);
471     } else {
472         &main::add_content2known_clients(hostname=>$source, status=>$header);
473     }
474     
475     return;
479 #===  FUNCTION  ================================================================
480 #         NAME:  new_passwd
481 #   PARAMETERS:  msg_hash - ref - hash from function create_xml_hash
482 #      RETURNS:  nothing
483 #  DESCRIPTION:  process this incoming message
484 #===============================================================================
485 sub new_key {
486     my ($msg_hash) = @_;
487     my @out_msg_l;
488     
489     my $header = @{$msg_hash->{header}}[0];
490     my $source_name = @{$msg_hash->{source}}[0];
491     my $source_key = @{$msg_hash->{new_key}}[0];
492     my $query_res;
494     # check known_clients_db
495     my $sql_statement = "SELECT * FROM known_clients WHERE hostname='$source_name'";
496     $query_res = $main::known_clients_db->select_dbentry( $sql_statement );
497     if( 1 == keys %{$query_res} ) {
498         my $act_time = &get_time;
499         my $sql_statement= "UPDATE known_clients ".
500             "SET hostkey='$source_key', timestamp='$act_time' ".
501             "WHERE hostname='$source_name'";
502         my $res = $main::known_clients_db->update_dbentry( $sql_statement );
503         my $hash = &create_xml_hash("confirm_new_key", $server_address, $source_name);
504         my $out_msg = &create_xml_string($hash);
505         push(@out_msg_l, $out_msg);
506     }
508     # only do if host still not found
509     if( 0 == @out_msg_l ) {
510         # check known_server_db
511         $sql_statement = "SELECT * FROM known_server WHERE hostname='$source_name'";
512         $query_res = $main::known_server_db->select_dbentry( $sql_statement );
513         if( 1 == keys %{$query_res} ) {
514             my $act_time = &get_time;
515             my $sql_statement= "UPDATE known_server ".
516                 "SET hostkey='$source_key', timestamp='$act_time' ".
517                 "WHERE hostname='$source_name'";
518             my $res = $main::known_server_db->update_dbentry( $sql_statement );
520             my $hash = &create_xml_hash("confirm_new_key", $server_address, $source_name);
521             my $out_msg = &create_xml_string($hash);
522             push(@out_msg_l, $out_msg);
523         }
524     }
526     return @out_msg_l;
530 #===  FUNCTION  ================================================================
531 #         NAME:  here_i_am
532 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
533 #      RETURNS:  nothing
534 #  DESCRIPTION:  process this incoming message
535 #===============================================================================
536 sub here_i_am {
537     my ($msg_hash) = @_;
538     my @out_msg_l;
539     my $out_hash;
541     my $source = @{$msg_hash->{source}}[0];
542     my $mac_address = @{$msg_hash->{mac_address}}[0];
543         my $gotoHardwareChecksum = @{$msg_hash->{gotoHardwareChecksum}}[0];
545     # number of known clients
546     my $nu_clients= $main::known_clients_db->count_dbentries('known_clients');
548     # check wether client address or mac address is already known
549     my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$source'";
550     my $db_res= $main::known_clients_db->select_dbentry( $sql_statement );
551     
552     if ( 1 == keys %{$db_res} ) {
553         &main::daemon_log("WARNING: $source is already known as a client", 1);
554         &main::daemon_log("WARNING: values for $source are being overwritten", 1);   
555         $nu_clients --;
556     }
558     # number of actual activ clients
559     my $act_nu_clients = $nu_clients;
561     &main::daemon_log("number of actual activ clients: $act_nu_clients", 5);
562     &main::daemon_log("number of maximal allowed clients: $max_clients", 5);
564     if($max_clients <= $act_nu_clients) {
565         my $out_hash = &create_xml_hash("denied", $server_address, $source);
566         &add_content2xml_hash($out_hash, "denied", "I_cannot_take_any_more_clients!");
567         my $passwd = @{$msg_hash->{new_passwd}}[0]; 
568         &send_msg_hash2address($out_hash, $source, $passwd);
569         return;
570     }
571     
572     # new client accepted
573     my $new_passwd = @{$msg_hash->{new_passwd}}[0];
575     # create entry in known_clients
576     my $events = @{$msg_hash->{events}}[0];
577     
579     # add entry to known_clients_db
580     my $act_timestamp = &get_time;
581     my $res = $main::known_clients_db->add_dbentry( {table=>'known_clients', 
582                                                 primkey=>'hostname',
583                                                 hostname=>$source,
584                                                 events=>$events,
585                                                 macaddress=>$mac_address,
586                                                 status=>'registered',
587                                                 hostkey=>$new_passwd,
588                                                 timestamp=>$act_timestamp,
589                                                 } );
591     if ($res != 0)  {
592         &main::daemon_log("ERROR: cannot add entry to known_clients: $res");
593         return;
594     }
595     
596     # return acknowledgement to client
597     $out_hash = &create_xml_hash("registered", $server_address, $source);
598     my $register_out = &create_xml_string($out_hash);
599     push(@out_msg_l, $register_out);
601     # notify registered client to bus
602     if( $bus_activ eq "on") {
603         # fetch actual bus key
604         my $sql_statement= "SELECT * FROM known_server WHERE status='bus'";
605         my $query_res = $main::known_server_db->select_dbentry( $sql_statement );
606         my $hostkey = $query_res->{1}->{'hostkey'};
608         # send update msg to bus
609         $out_hash = &create_xml_hash("new_client", $server_address, $bus_address, $source);
610         &add_content2xml_hash($out_hash, "macaddress", $mac_address);
611         &add_content2xml_hash($out_hash, "timestamp", $act_timestamp);
612         my $new_client_out = &create_xml_string($out_hash);
613         push(@out_msg_l, $new_client_out);
614         &main::daemon_log("send bus msg that client '$source' has registerd at server '$server_address'", 3);
615     }
617     # give the new client his ldap config
618     my $new_ldap_config_out = &new_ldap_config($source);
619     if( $new_ldap_config_out ) {
620         push(@out_msg_l, $new_ldap_config_out);
621     }
623         my $hardware_config_out = &hardware_config($source, $gotoHardwareChecksum);
624         if( $hardware_config_out ) {
625                 push(@out_msg_l, $hardware_config_out);
626         }
628     return @out_msg_l;
632 #===  FUNCTION  ================================================================
633 #         NAME:  who_has
634 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
635 #      RETURNS:  nothing 
636 #  DESCRIPTION:  process this incoming message
637 #===============================================================================
638 sub who_has {
639     my ($msg_hash) = @_ ;
640     my @out_msg_l;
641     
642     # what is your search pattern
643     my $search_pattern = @{$msg_hash->{who_has}}[0];
644     my $search_element = @{$msg_hash->{$search_pattern}}[0];
645     &main::daemon_log("who_has-msg looking for $search_pattern $search_element", 7);
647     # scanning known_clients for search_pattern
648     my @host_addresses = keys %$main::known_clients;
649     my $known_clients_entries = length @host_addresses;
650     my $host_address;
651     foreach my $host (@host_addresses) {
652         my $client_element = $main::known_clients->{$host}->{$search_pattern};
653         if ($search_element eq $client_element) {
654             $host_address = $host;
655             last;
656         }
657     }
658         
659     # search was successful
660     if (defined $host_address) {
661         my $source = @{$msg_hash->{source}}[0];
662         my $out_hash = &create_xml_hash("who_has_i_do", $server_address, $source, "mac_address");
663         &add_content2xml_hash($out_hash, "mac_address", $search_element);
664         my $out_msg = &create_xml_string($out_hash);
665         push(@out_msg_l, $out_msg);
666     }
667     return @out_msg_l;
671 sub who_has_i_do {
672     my ($msg_hash) = @_ ;
673     my $header = @{$msg_hash->{header}}[0];
674     my $source = @{$msg_hash->{source}}[0];
675     my $search_param = @{$msg_hash->{$header}}[0];
676     my $search_value = @{$msg_hash->{$search_param}}[0];
677     print "\ngot msg $header:\nserver $source has client with $search_param $search_value\n";
680 #===  FUNCTION  ================================================================
681 #         NAME:  new_ldap_config
682 #   PARAMETERS:  address - string - ip address and port of a host
683 #      RETURNS:  nothing
684 #  DESCRIPTION:  send to address the ldap configuration found for dn gotoLdapServer
685 #===============================================================================
686 sub new_ldap_config {
687         my ($address) = @_ ;
689         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address'";
690         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
692         # check hit
693         my $hit_counter = keys %{$res};
694         if( not $hit_counter == 1 ) {
695                 &main::daemon_log("ERROR: more or no hit found in known_clients_db by query by '$address'", 1);
696         }
698         my $macaddress = $res->{1}->{macaddress};
699         my $hostkey = $res->{1}->{hostkey};
701         if (not defined $macaddress) {
702                 &main::daemon_log("ERROR: no mac address found for client $address", 1);
703                 return;
704         }
706         # Build LDAP connection
707         my $ldap = Net::LDAP->new($ldap_uri);
708         if( not defined $ldap ) {
709                 &main::daemon_log("ERROR: cannot connect to ldap: $ldap_uri", 1);
710                 return;
711         } 
714         # Bind to a directory with dn and password
715         my $mesg= $ldap->bind($ldap_admin_dn, password => $ldap_admin_password);
717         # Perform search
718         $mesg = $ldap->search( base   => $ldap_base,
719                 scope  => 'sub',
720                 attrs => ['dn', 'gotoLdapServer', 'gosaUnitTag'],
721                 filter => "(&(objectClass=GOhard)(macaddress=$macaddress))");
722         #$mesg->code && die $mesg->error;
723         if($mesg->code) {
724                 &main::daemon_log($mesg->error, 1);
725                 return;
726         }
728         # Sanity check
729         if ($mesg->count != 1) {
730                 &main::daemon_log("WARNING: client mac address $macaddress not found/not unique in ldap search", 1);
731                 &main::daemon_log("\tbase: $ldap_base", 1);
732                 &main::daemon_log("\tscope: sub", 1);
733                 &main::daemon_log("\tattrs: dn, gotoLdapServer", 1);
734                 &main::daemon_log("\tfilter: (&(objectClass=GOhard)(macaddress=$macaddress))", 1);
735                 return;
736         }
738         my $entry= $mesg->entry(0);
739         my $dn= $entry->dn;
740         my @servers= $entry->get_value("gotoLdapServer");
741         my $unit_tag= $entry->get_value("gosaUnitTag");
742         my @ldap_uris;
743         my $server;
744         my $base;
746         # Do we need to look at an object class?
747         if (length(@servers) < 1){
748                 $mesg = $ldap->search( base   => $ldap_base,
749                         scope  => 'sub',
750                         attrs => ['dn', 'gotoLdapServer'],
751                         filter => "(&(objectClass=gosaGroupOfNames)(member=$dn))");
752                 #$mesg->code && die $mesg->error;
753                 if($mesg->code) {
754                         &main::daemon_log($mesg->error, 1);
755                         return;
756                 }
758                 # Sanity check
759                 if ($mesg->count != 1) {
760                         &main::daemon_log("WARNING: no LDAP information found for client mac $macaddress", 1);
761                         return;
762                 }
764                 $entry= $mesg->entry(0);
765                 $dn= $entry->dn;
766                 @servers= $entry->get_value("gotoLdapServer");
767         }
769         @servers= sort (@servers);
771         foreach $server (@servers){
772                 # Conversation for backward compatibility
773                 if ($server !=~ /^ldap[^:]+:\/\// ) {
774                         if ($server =~ /^([^:]+):(.*)$/ ) {
775                                 $server= "1:dummy:ldap://$1/$2";
776                         }
777                 }
779                 $base= $server;
780                 $server =~ s%^[^:]+:[^:]+:(ldap.*://[^/]+)/.*$%$1%;
781                 $base =~ s%^[^:]+:[^:]+:ldap.*://[^/]+/(.*)$%$1%;
782                 push (@ldap_uris, $server);
783         }
785         # Assemble data package
786         my %data = ( 'ldap_uri'  => \@ldap_uris, 'ldap_base' => $base,
787                 'ldap_cfg' => \@ldap_cfg, 'pam_cfg' => \@pam_cfg,'nss_cfg' => \@nss_cfg );
789         # Need to append GOto settings?
790         if (defined $goto_admin and defined $goto_secret){
791                 $data{'goto_admin'}= $goto_admin;
792                 $data{'goto_secret'}= $goto_secret;
793         }
795         # Append unit tag if needed
796         if (defined $unit_tag){
798                 # Find admin base and department name
799                 $mesg = $ldap->search( base   => $ldap_base,
800                         scope  => 'sub',
801                         attrs => ['dn', 'ou', 'FAIclass'],
802                         filter => "(&(objectClass=gosaAdministrativeUnit)(gosaUnitTag=$unit_tag))");
803                 #$mesg->code && die $mesg->error;
804                 if($mesg->code) {
805                         &main::daemon_log($mesg->error, 1);
806                         return;
807                 }
809                 # Sanity check
810                 if ($mesg->count != 1) {
811                         &main::daemon_log("WARNING: cannot find administrative unit for client with tag $unit_tag", 1);
812                         return;
813                 }
815                 $entry= $mesg->entry(0);
816                 $data{'admin_base'}= $entry->dn;
817                 $data{'department'}= $entry->get_value("ou");
819                 # Append unit Tag
820                 $data{'unit_tag'}= $unit_tag;
821         }
823         # Fill release if available
824         my $FAIclass= $entry->get_value("FAIclass");
825         if (defined $FAIclass && $FAIclass =~ /^.* :([A-Za-z0-9\/.]+).*$/) {
826                 $data{'release'}= $1;
827         }
830         # Unbind
831         $mesg = $ldap->unbind;
833         # Send information
834         return send_msg("new_ldap_config", $server_address, $address, \%data);
837 sub process_detected_hardware {
838         my $msg_hash = shift;
839         my $address = $msg_hash->{source}[0];
840         my $gotoHardwareChecksum= $msg_hash->{detected_hardware}[0]->{gotoHardwareChecksum};
842     my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address'";
843     my $res = $main::known_clients_db->select_dbentry( $sql_statement );
845     # check hit
846     my $hit_counter = keys %{$res};
847     if( not $hit_counter == 1 ) {
848         &main::daemon_log("ERROR: more or no hit found in known_clients_db by query by '$address'", 1);
849                 return;
850     }
852     my $macaddress = $res->{1}->{macaddress};
853     my $hostkey = $res->{1}->{hostkey};
855     if (not defined $macaddress) {
856         &main::daemon_log("ERROR: no mac address found for client $address", 1);
857         return;
858     }
859     # Build LDAP connection
860     my $ldap = Net::LDAP->new($ldap_uri);
861     if( not defined $ldap ) {
862         &main::daemon_log("ERROR: cannot connect to ldap: $ldap_uri", 1);
863         return;
864     } 
866     # Bind to a directory with dn and password
867     my $mesg= $ldap->bind($ldap_admin_dn, password => $ldap_admin_password);
869     # Perform search
870         $mesg = $ldap->search(
871                 base   => $ldap_base,
872                 scope  => 'sub',
873                 filter => "(&(objectClass=GOhard)(|(macAddress=$macaddress)(dhcpHWaddress=ethernet $macaddress)))"
874         );
876         # We need to create a base entry first (if not done from ArpHandler)
877         if($mesg->count == 0) {
878                 &main::daemon_log("Need to create a new LDAP Entry for client $address", 1);
879                 my $resolver=Net::DNS::Resolver->new;
880                 my $ipaddress= $1 if $address =~ /^([0-9\.]*?):.*$/;
881                 my $dnsresult= $resolver->search($ipaddress);
882                 my $dnsname= (defined($dnsresult))?$dnsresult->{answer}[0]->{ptrdname}:$ipaddress;
883                 my $cn = (($dnsname =~ /^(\d){1,3}\.(\d){1,3}\.(\d){1,3}\.(\d){1,3}/) ? $dnsname : sprintf "%s", $dnsname =~ /([^\.]+)\.?/);
884                 my $dn = "cn=$cn,ou=incoming,$ldap_base";
885                 &main::daemon_log("Creating entry for $dn",6);
886                 my $entry= Net::LDAP::Entry->new( $dn );
887                 $entry->dn($dn);
888                 $entry->add("objectClass" => "goHard");
889                 $entry->add("cn" => $cn);
890                 $entry->add("macAddress" => $macaddress);
891                 $entry->add("gotomode" => "locked");
892                 $entry->add("gotoSysStatus" => "new-system");
893                 $entry->add("ipHostNumber" => $ipaddress);
894                 if(defined($gosa_unit_tag) && length($gosa_unit_tag) > 0) {
895                         $entry->add("objectClass" => "gosaAdministrativeUnit");
896                         $entry->add("gosaUnitTag" => $gosa_unit_tag);
897                 }
898                 if(my $res=$entry->update($ldap)) {
899                         # Fill $mesg again
900                         $mesg = $ldap->search(
901                                 base   => $ldap_base,
902                                 scope  => 'sub',
903                                 filter => "(&(objectClass=GOhard)(|(macAddress=$macaddress)(dhcpHWaddress=ethernet $macaddress)))"
904                         );
905                 } else {
906                         &main::daemon_log("ERROR: There was a problem adding the entry", 1);
907                 }
909         }
910         
911         if($mesg->count == 1) {
912                 my $entry= $mesg->entry(0);
913                 $entry->changetype("modify");
914                 foreach my $attribute (
915                         "gotoSndModule", "ghNetNic", "gotoXResolution", "ghSoundAdapter", "ghCpuType", "gotoXkbModel", 
916                         "ghGfxAdapter", "gotoXMousePort", "ghMemSize", "gotoXMouseType", "ghUsbSupport", "gotoXHsync", 
917                         "gotoXDriver", "gotoXVsync", "gotoXMonitor", "gotoHardwareChecksum") {
918                         if(defined($msg_hash->{detected_hardware}[0]->{$attribute})) {
919                                 if(defined($entry->get_value($attribute))) {
920                                         $entry->delete($attribute);
921                                 }
922                                 &main::daemon_log("Adding attribute $attribute with value ".$msg_hash->{detected_hardware}[0]->{$attribute},1);
923                                 $entry->add($attribute => $msg_hash->{detected_hardware}[0]->{$attribute});     
924                         }
925                 }
926                 foreach my $attribute (
927                         "gotoModules", "ghScsiDev", "ghIdeDev") {
928                         if(defined($msg_hash->{detected_hardware}[0]->{$attribute})) {
929                                 if(defined($entry->get_value($attribute))) {
930                                         $entry->delete($attribute);
931                                 }
932                                 foreach my $array_entry (@{$msg_hash->{detected_hardware}[0]->{$attribute}}) {
933                                         $entry->add($attribute => $array_entry);
934                                 }
935                         }
937                 }
939                 if($entry->update($ldap)) {
940                         &main::daemon_log("Added Hardware configuration to LDAP", 4);
941                 }
943         }
944         return;
946 #===  FUNCTION  ================================================================
947 #         NAME:  hardware_config
948 #   PARAMETERS:  address - string - ip address and port of a host
949 #      RETURNS:  
950 #  DESCRIPTION:  
951 #===============================================================================
952 sub hardware_config {
953         my ($address, $gotoHardwareChecksum) = @_ ;
955         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address'";
956         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
958         # check hit
959         my $hit_counter = keys %{$res};
960         if( not $hit_counter == 1 ) {
961                 &main::daemon_log("ERROR: more or no hit found in known_clients_db by query by '$address'", 1);
962         }
964         my $macaddress = $res->{1}->{macaddress};
965         my $hostkey = $res->{1}->{hostkey};
967         if (not defined $macaddress) {
968                 &main::daemon_log("ERROR: no mac address found for client $address", 1);
969                 return;
970         }
972         # Build LDAP connection
973         my $ldap = Net::LDAP->new($ldap_uri);
974         if( not defined $ldap ) {
975                 &main::daemon_log("ERROR: cannot connect to ldap: $ldap_uri", 1);
976                 return;
977         } 
979         # Bind to a directory with dn and password
980         my $mesg= $ldap->bind($ldap_admin_dn, password => $ldap_admin_password);
982         # Perform search
983         $mesg = $ldap->search(
984                 base   => $ldap_base,
985                 scope  => 'sub',
986                 filter => "(&(objectClass=GOhard)(|(macAddress=$macaddress)(dhcpHWaddress=ethernet $macaddress)))"
987         );
989         if($mesg->count() == 0) {
990                 &main::daemon_log("Host was not found in LDAP!", 1);
991         } else {
992                 my $entry= $mesg->entry(0);
993                 my $dn= $entry->dn;
994                 if(defined($entry->get_value("gotoHardwareChecksum"))) {
995                         if(! $entry->get_value("gotoHardwareChecksum") eq $gotoHardwareChecksum) {
996                                 $entry->replace(gotoHardwareChecksum => $gotoHardwareChecksum);
997                                 if($entry->update($ldap)) {
998                                         &main::daemon_log("Hardware changed! Detection triggered.", 4);
999                                 }
1000                         } else {
1001                                 # Nothing to do
1002                                 return;
1003                         }
1004                 }
1005         } 
1006         # need to fill it to LDAP
1007         #$entry->add(gotoHardwareChecksum => $gotoHardwareChecksum);
1008         #if($entry->update($ldap)) {
1009         #               &main::daemon_log("gotoHardwareChecksum $gotoHardwareChecksum was added to LDAP", 4);
1010         #}
1012         ## Look if there another host with this checksum to use the hardware config
1013         #$mesg = $ldap->search(
1014         #       base   => $ldap_base,
1015         #       scope  => 'sub',
1016         #       filter => "(&(objectClass=GOhard)(gotoHardwareChecksum=$gotoHardwareChecksum))"
1017         #);
1019         #if($mesg->count>1) {
1020         #       my $clone_entry= $mesg->entry(0);
1021         #       $entry->changetype("modify");
1022         #       foreach my $attribute (
1023         #               "gotoSndModule", "ghNetNic", "gotoXResolution", "ghSoundAdapter", "ghCpuType", "gotoXkbModel", 
1024         #               "ghGfxAdapter", "gotoXMousePort", "ghMemSize", "gotoXMouseType", "ghUsbSupport", "gotoXHsync", 
1025         #               "gotoXDriver", "gotoXVsync", "gotoXMonitor") {
1026         #               my $value= $clone_entry->get_value($attribute);
1027         #               if(defined($value)) {
1028         #                       if(defined($entry->get_value($attribute))) {
1029         #                               $entry->delete($attribute);
1030         #                       }
1031         #                       &main::daemon_log("Adding attribute $attribute with value $value",1);
1032         #                       $entry->add($attribute => $value);
1033         #               }
1034         #       }
1035         #       foreach my $attribute (
1036         #               "gotoModules", "ghScsiDev", "ghIdeDev") {
1037         #               my $array= $clone_entry->get_value($attribute, 'as_ref' => 1);
1038         #               if(defined($array))     {
1039         #                       if(defined($entry->get_value($attribute))) {
1040         #                               $entry->delete($attribute);
1041         #                       }
1042         #                       foreach my $array_entry (@{$array}) {
1043         #                               $entry->add($attribute => $array_entry);
1044         #                       }
1045         #               }
1047         #       }
1048         #       if($entry->update($ldap)) {
1049         #               &main::daemon_log("Added Hardware configuration to LDAP", 4);
1050         #       }
1052         #}
1055         # Assemble data package
1056         my %data = ();
1058         # Need to append GOto settings?
1059         if (defined $goto_admin and defined $goto_secret){
1060                 $data{'goto_admin'}= $goto_admin;
1061                 $data{'goto_secret'}= $goto_secret;
1062         }
1064         # Unbind
1065         $mesg = $ldap->unbind;
1067         &main::daemon_log("Send detect_hardware message to $address", 4);
1069         # Send information
1070         return send_msg("detect_hardware", $server_address, $address, \%data);
1073 sub server_matches {
1074         my $target = shift;
1075         my $target_ip = sprintf("%s", $target =~ /^([0-9\.]*?):.*$/);
1076         my $result = 0;
1078         if($server_ip eq $target_ip) {
1079                 $result= 1;
1080         } elsif ($server_ip eq "0.0.0.0") {     
1081                 if ($target_ip eq "127.0.0.1") {
1082                         $result= 1;
1083                 } else {
1084                         my $PROC_NET_ROUTE= ('/proc/net/route');
1086                         open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
1087                                 or die "Could not open $PROC_NET_ROUTE";
1089                         my @ifs = <PROC_NET_ROUTE>;
1091                         close(PROC_NET_ROUTE);
1093                         # Eat header line
1094                         shift @ifs;
1095                         chomp @ifs;
1096                         foreach my $line(@ifs) {
1097                                 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
1098                                 my $destination;
1099                                 my $mask;
1100                                 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
1101                                 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
1102                                 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
1103                                 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
1104                                 if(new NetAddr::IP($target_ip)->within(new NetAddr::IP($destination, $mask))) {
1105                                         # destination matches route, save mac and exit
1106                                         $result= 1;
1107                                         last;
1108                                 }
1109                         }
1110                 }
1111         } else {
1112                 &main::daemon_log("Target ip $target_ip does not match Server ip $server_ip",1);
1113         }
1115         return $result;
1119 #===  FUNCTION  ================================================================
1120 #         NAME:  execute_actions
1121 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
1122 #      RETURNS:  nothing
1123 #  DESCRIPTION:  invokes the script specified in msg_hash which is located under
1124 #                /etc/gosad/actions
1125 #===============================================================================
1126 sub execute_actions {
1127     my ($msg_hash) = @_ ;
1128     my $configdir= '/etc/gosad/actions/';
1129     my $result;
1131     my $header = @{$msg_hash->{header}}[0];
1132     my $source = @{$msg_hash->{source}}[0];
1133     my $target = @{$msg_hash->{target}}[0];
1134  
1135     if((not defined $source)
1136             && (not defined $target)
1137             && (not defined $header)) {
1138         &main::daemon_log("ERROR: Entries missing in XML msg for gosad actions under /etc/gosad/actions");
1139     } else {
1140         my $parameters="";
1141         my @params = @{$msg_hash->{$header}};
1142         my $params = join(", ", @params);
1143         &main::daemon_log("execute_actions: got parameters: $params", 5);
1145         if (@params) {
1146             foreach my $param (@params) {
1147                 my $param_value = (&get_content_from_xml_hash($msg_hash, $param))[0];
1148                 &main::daemon_log("execute_actions: parameter -> value: $param -> $param_value", 7);
1149                 $parameters.= " ".$param_value;
1150             }
1151         }
1153         my $cmd= $configdir.$header."$parameters";
1154         &main::daemon_log("execute_actions: executing cmd: $cmd", 7);
1155         $result= "";
1156         open(PIPE, "$cmd 2>&1 |");
1157         while(<PIPE>) {
1158             $result.=$_;
1159         }
1160         close(PIPE);
1161     }
1163     # process the event result
1166     return;
1170 1;