Code

65be05af8d3515da1ff044029b9703d45efb6716
[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);
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     },
49 "SIPackages" => {
50     "key" => [\$SIPackages_key, ""],
51     },
52 );
54 ### START #####################################################################
56 # read configfile and import variables
57 &read_configfile();
59 $network_interface= &get_interface_for_ip($server_ip);
60 $server_mac_address= &get_mac($network_interface);
62 # complete addresses
63 #if( $server_ip eq "0.0.0.0" ) {
64 #    $server_ip = "127.0.0.1";
65 #}
66 my $server_address = "$server_ip:$server_port";
67 $main::server_address = $server_address;
68 my $bus_address = "$bus_ip:$bus_port";
69 $main::bus_address = $bus_address;
71 # create general settings for this module
72 my $xml = new XML::Simple();
74 # register at bus
75 if ($main::no_bus > 0) {
76     $bus_activ = "off"
77 }
78 if($bus_activ eq "on") {
79     &register_at_bus();
80 }
82 # add myself to known_server_db
83 my $res = $main::known_server_db->add_dbentry( {table=>'known_server',
84         primkey=>'hostname',
85         hostname=>$server_address,
86         status=>'myself',
87         hostkey=>$SIPackages_key,
88         timestamp=>&get_time,
89         } );
93 ### functions #################################################################
96 sub get_module_info {
97     my @info = ($server_address,
98                 $SIPackages_key,
99                 );
100     return \@info;
104 sub do_wake {
105         my $host    = shift;
106         my $ipaddr  = shift || '255.255.255.255';
107         my $port    = getservbyname('discard', 'udp');
109         my ($raddr, $them, $proto);
110         my ($hwaddr, $hwaddr_re, $pkt);
112         # get the hardware address (ethernet address)
114         $hwaddr_re = join(':', ('[0-9A-Fa-f]{1,2}') x 6);
115         if ($host =~ m/^$hwaddr_re$/) {
116                 $hwaddr = $host;
117         } else {
118                 # $host is not a hardware address, try to resolve it
119                 my $ip_re = join('\.', ('([0-9]|[1-9][0-9]|1[0-9]{2}|2([0-4][0-9]|5[0-5]))') x 4);
120                 my $ip_addr;
121                 if ($host =~ m/^$ip_re$/) {
122                         $ip_addr = $host;
123                 } else {
124                         my $h;
125                         unless ($h = gethost($host)) {
126                                 return undef;
127                         }
128                         $ip_addr = inet_ntoa($h->addr);
129                 }
130         }
132         # Generate magic sequence
133         foreach (split /:/, $hwaddr) {
134                 $pkt .= chr(hex($_));
135         }
136         $pkt = chr(0xFF) x 6 . $pkt x 16;
138         # Allocate socket and send packet
140         $raddr = gethostbyname($ipaddr)->addr;
141         $them = pack_sockaddr_in($port, $raddr);
142         $proto = getprotobyname('udp');
144         socket(S, AF_INET, SOCK_DGRAM, $proto) or die "socket : $!";
145         setsockopt(S, SOL_SOCKET, SO_BROADCAST, 1) or die "setsockopt : $!";
147         send(S, $pkt, 0, $them) or die "send : $!";
148         close S;
152 #===  FUNCTION  ================================================================
153 #         NAME:  read_configfile
154 #   PARAMETERS:  cfg_file - string -
155 #      RETURNS:  nothing
156 #  DESCRIPTION:  read cfg_file and set variables
157 #===============================================================================
158 sub read_configfile {
159     my $cfg;
160     if( defined( $main::cfg_file) && ( length($main::cfg_file) > 0 )) {
161         if( -r $main::cfg_file ) {
162             $cfg = Config::IniFiles->new( -file => $main::cfg_file );
163         } else {
164             print STDERR "Couldn't read config file!";
165         }
166     } else {
167         $cfg = Config::IniFiles->new() ;
168     }
169     foreach my $section (keys %cfg_defaults) {
170         foreach my $param (keys %{$cfg_defaults{ $section }}) {
171             my $pinfo = $cfg_defaults{ $section }{ $param };
172             ${@$pinfo[0]} = $cfg->val( $section, $param, @$pinfo[1] );
173         }
174     }
176     # Read non predefined sections
177     my $param;
178     if ($cfg->SectionExists('ldap')){
179                 foreach $param ($cfg->Parameters('ldap')){
180                         push (@ldap_cfg, "$param ".$cfg->val('ldap', $param));
181                 }
182     }
183     if ($cfg->SectionExists('pam_ldap')){
184                 foreach $param ($cfg->Parameters('pam_ldap')){
185                         push (@pam_cfg, "$param ".$cfg->val('pam_ldap', $param));
186                 }
187     }
188     if ($cfg->SectionExists('nss_ldap')){
189                 foreach $param ($cfg->Parameters('nss_ldap')){
190                         push (@nss_cfg, "$param ".$cfg->val('nss_ldap', $param));
191                 }
192     }
193     if ($cfg->SectionExists('goto')){
194         $goto_admin= $cfg->val('goto', 'terminal_admin');
195         $goto_secret= $cfg->val('goto', 'terminal_secret');
196     } else {
197         $goto_admin= undef;
198         $goto_secret= undef;
199     }
203 #===  FUNCTION  ================================================================
204 #         NAME:  get_interface_for_ip
205 #   PARAMETERS:  ip address (i.e. 192.168.0.1)
206 #      RETURNS:  array: list of interfaces if ip=0.0.0.0, matching interface if found, undef else
207 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
208 #===============================================================================
209 sub get_interface_for_ip {
210         my $result;
211         my $ip= shift;
212         if ($ip && length($ip) > 0) {
213                 my @ifs= &get_interfaces();
214                 if($ip eq "0.0.0.0") {
215                         $result = "all";
216                 } else {
217                         foreach (@ifs) {
218                                 my $if=$_;
219                                 if(get_ip($if) eq $ip) {
220                                         $result = $if;
221                                 }
222                         }       
223                 }
224         }       
225         return $result;
228 #===  FUNCTION  ================================================================
229 #         NAME:  get_interfaces 
230 #   PARAMETERS:  none
231 #      RETURNS:  (list of interfaces) 
232 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
233 #===============================================================================
234 sub get_interfaces {
235         my @result;
236         my $PROC_NET_DEV= ('/proc/net/dev');
238         open(PROC_NET_DEV, "<$PROC_NET_DEV")
239                 or die "Could not open $PROC_NET_DEV";
241         my @ifs = <PROC_NET_DEV>;
243         close(PROC_NET_DEV);
245         # Eat first two line
246         shift @ifs;
247         shift @ifs;
249         chomp @ifs;
250         foreach my $line(@ifs) {
251                 my $if= (split /:/, $line)[0];
252                 $if =~ s/^\s+//;
253                 push @result, $if;
254         }
256         return @result;
259 #===  FUNCTION  ================================================================
260 #         NAME:  get_mac 
261 #   PARAMETERS:  interface name (i.e. eth0)
262 #      RETURNS:  (mac address) 
263 #  DESCRIPTION:  Uses ioctl to get mac address directly from system.
264 #===============================================================================
265 sub get_mac {
266         my $ifreq= shift;
267         my $result;
268         if ($ifreq && length($ifreq) > 0) { 
269                 if($ifreq eq "all") {
270                         $result = "00:00:00:00:00:00";
271                 } else {
272                         my $SIOCGIFHWADDR= 0x8927;     # man 2 ioctl_list
274                         # A configured MAC Address should always override a guessed value
275                         if ($server_mac_address and length($server_mac_address) > 0) {
276                                 $result= $server_mac_address;
277                         }
279                         socket SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('ip')
280                                 or die "socket: $!";
282                         if(ioctl SOCKET, $SIOCGIFHWADDR, $ifreq) {
283                                 my ($if, $mac)= unpack 'h36 H12', $ifreq;
285                                 if (length($mac) > 0) {
286                                         $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])$/;
287                                         $mac= sprintf("%s:%s:%s:%s:%s:%s", $1, $2, $3, $4, $5, $6);
288                                         $result = $mac;
289                                 }
290                         }
291                 }
292         }
293         return $result;
297 #===  FUNCTION  ================================================================
298 #         NAME:  register_at_bus
299 #   PARAMETERS:  nothing
300 #      RETURNS:  nothing
301 #  DESCRIPTION:  creates an entry in known_daemons and send a 'here_i_am' msg to bus
302 #===============================================================================
303 sub register_at_bus {
305     # add bus to known_server_db
306     my $res = $main::known_server_db->add_dbentry( {table=>'known_server',
307                                                     primkey=>'hostname',
308                                                     hostname=>$bus_address,
309                                                     status=>'bus',
310                                                     hostkey=>$bus_key,
311                                                     timestamp=>&get_time,
312                                                 } );
313     my $msg_hash = &create_xml_hash("here_i_am", $server_address, $bus_address);
314     my $msg = &create_xml_string($msg_hash);
316     &main::send_msg_to_target($msg, $bus_address, $bus_key, "here_i_am");
317     return $msg;
321 #===  FUNCTION  ================================================================
322 #         NAME:  process_incoming_msg
323 #   PARAMETERS:  crypted_msg - string - incoming crypted message
324 #      RETURNS:  nothing
325 #  DESCRIPTION:  handels the proceeded distribution to the appropriated functions
326 #===============================================================================
327 sub process_incoming_msg {
328     my ($msg, $msg_hash, $remote_ip) = @_ ;
329     my $error = 0;
330     my $host_name;
331     my $host_key;
332     my @out_msg_l;
334     # process incoming msg
335     my $header = @{$msg_hash->{header}}[0]; 
336     my @target_l = @{$msg_hash->{target}};
338     &main::daemon_log("SIPackages: msg to process: $header", 3);
339     &main::daemon_log("$msg", 8);
341     if( 0 == length @target_l){     
342         &main::daemon_log("ERROR: no target specified for msg $header", 1);
343         $error++;
344     }
346     if( 1 == length @target_l) {
347         my $target = $target_l[0];
348                 if(&server_matches($target)) {
349             if ($header eq 'new_key') {
350                 @out_msg_l = &new_key($msg_hash)
351             } elsif ($header eq 'here_i_am') {
352                 @out_msg_l = &here_i_am($msg_hash)
353             } elsif ($header eq 'who_has') {
354                 @out_msg_l = &who_has($msg_hash)
355             } elsif ($header eq 'who_has_i_do') {
356                 @out_msg_l = &who_has_i_do($msg_hash)
357             } elsif ($header eq 'got_ping') {
358                 @out_msg_l = &got_ping($msg_hash)
359             } elsif ($header eq 'get_load') {
360                 @out_msg_l = &execute_actions($msg_hash)
361             } elsif ($header eq 'detected_hardware') {
362                 @out_msg_l = &process_detected_hardware($msg_hash)
363             } elsif ($header eq 'trigger_wake') {
364                 foreach (@{$msg_hash->{macAddress}}){
365                     &main::daemon_log("SIPackages: trigger wake for $_", 1);
366                     do_wake($_);
367                 }
369             } else {
370                 &main::daemon_log("ERROR: $header is an unknown core function", 1);
371                 $error++;
372             }
373         }
374                 else {
375                         &main::daemon_log("msg is not for gosa-si-server '$server_address', deliver it to target '$target'", 5);
376                         push(@out_msg_l, $msg);
377                 }
378     }
380 #    if( $error == 0) {
381 #        if( 0 == @out_msg_l ) {
382 #                       push(@out_msg_l, $msg);
383 #        }
384 #    }
385     
386     return \@out_msg_l;
390 #===  FUNCTION  ================================================================
391 #         NAME:  got_ping
392 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
393 #      RETURNS:  nothing
394 #  DESCRIPTION:  process this incoming message
395 #===============================================================================
396 sub got_ping {
397     my ($msg_hash) = @_;
398     
399     my $source = @{$msg_hash->{source}}[0];
400     my $target = @{$msg_hash->{target}}[0];
401     my $header = @{$msg_hash->{header}}[0];
402     
403     if(exists $main::known_daemons->{$source}) {
404         &main::add_content2known_daemons(hostname=>$source, status=>$header);
405     } else {
406         &main::add_content2known_clients(hostname=>$source, status=>$header);
407     }
408     
409     return;
413 #===  FUNCTION  ================================================================
414 #         NAME:  new_passwd
415 #   PARAMETERS:  msg_hash - ref - hash from function create_xml_hash
416 #      RETURNS:  nothing
417 #  DESCRIPTION:  process this incoming message
418 #===============================================================================
419 sub new_key {
420     my ($msg_hash) = @_;
421     my @out_msg_l;
422     
423     my $header = @{$msg_hash->{header}}[0];
424     my $source_name = @{$msg_hash->{source}}[0];
425     my $source_key = @{$msg_hash->{new_key}}[0];
426     my $query_res;
428     # check known_clients_db
429     my $sql_statement = "SELECT * FROM known_clients WHERE hostname='$source_name'";
430     $query_res = $main::known_clients_db->select_dbentry( $sql_statement );
431     if( 1 == keys %{$query_res} ) {
432         my $act_time = &get_time;
433         my $sql_statement= "UPDATE known_clients ".
434             "SET hostkey='$source_key', timestamp='$act_time' ".
435             "WHERE hostname='$source_name'";
436         my $res = $main::known_clients_db->update_dbentry( $sql_statement );
437         my $hash = &create_xml_hash("confirm_new_key", $server_address, $source_name);
438         my $out_msg = &create_xml_string($hash);
439         push(@out_msg_l, $out_msg);
440     }
442     # only do if host still not found
443     if( 0 == @out_msg_l ) {
444         # check known_server_db
445         $sql_statement = "SELECT * FROM known_server WHERE hostname='$source_name'";
446         $query_res = $main::known_server_db->select_dbentry( $sql_statement );
447         if( 1 == keys %{$query_res} ) {
448             my $act_time = &get_time;
449             my $sql_statement= "UPDATE known_server ".
450                 "SET hostkey='$source_key', timestamp='$act_time' ".
451                 "WHERE hostname='$source_name'";
452             my $res = $main::known_server_db->update_dbentry( $sql_statement );
454             my $hash = &create_xml_hash("confirm_new_key", $server_address, $source_name);
455             my $out_msg = &create_xml_string($hash);
456             push(@out_msg_l, $out_msg);
457         }
458     }
460     return @out_msg_l;
464 #===  FUNCTION  ================================================================
465 #         NAME:  here_i_am
466 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
467 #      RETURNS:  nothing
468 #  DESCRIPTION:  process this incoming message
469 #===============================================================================
470 sub here_i_am {
471     my ($msg_hash) = @_;
472     my @out_msg_l;
473     my $out_hash;
475     my $source = @{$msg_hash->{source}}[0];
476     my $mac_address = @{$msg_hash->{mac_address}}[0];
477         my $gotoHardwareChecksum = @{$msg_hash->{gotoHardwareChecksum}}[0];
479     # number of known clients
480     my $nu_clients= $main::known_clients_db->count_dbentries('known_clients');
482     # check wether client address or mac address is already known
483     my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$source'";
484     my $db_res= $main::known_clients_db->select_dbentry( $sql_statement );
485     
486     if ( 1 == keys %{$db_res} ) {
487         &main::daemon_log("WARNING: $source is already known as a client", 1);
488         &main::daemon_log("WARNING: values for $source are being overwritten", 1);   
489         $nu_clients --;
490     }
492     # number of actual activ clients
493     my $act_nu_clients = $nu_clients;
495     &main::daemon_log("number of actual activ clients: $act_nu_clients", 5);
496     &main::daemon_log("number of maximal allowed clients: $max_clients", 5);
498     if($max_clients <= $act_nu_clients) {
499         my $out_hash = &create_xml_hash("denied", $server_address, $source);
500         &add_content2xml_hash($out_hash, "denied", "I_cannot_take_any_more_clients!");
501         my $passwd = @{$msg_hash->{new_passwd}}[0]; 
502         &send_msg_hash2address($out_hash, $source, $passwd);
503         return;
504     }
505     
506     # new client accepted
507     my $new_passwd = @{$msg_hash->{new_passwd}}[0];
509     # create entry in known_clients
510     my $events = @{$msg_hash->{events}}[0];
511     
513     # add entry to known_clients_db
514     my $act_timestamp = &get_time;
515     my $res = $main::known_clients_db->add_dbentry( {table=>'known_clients', 
516                                                 primkey=>'hostname',
517                                                 hostname=>$source,
518                                                 events=>$events,
519                                                 macaddress=>$mac_address,
520                                                 status=>'registered',
521                                                 hostkey=>$new_passwd,
522                                                 timestamp=>$act_timestamp,
523                                                 } );
525     if ($res != 0)  {
526         &main::daemon_log("ERROR: cannot add entry to known_clients: $res");
527         return;
528     }
529     
530     # return acknowledgement to client
531     $out_hash = &create_xml_hash("registered", $server_address, $source);
532     my $register_out = &create_xml_string($out_hash);
533     push(@out_msg_l, $register_out);
535     # notify registered client to bus
536     if( $bus_activ eq "on") {
537         # fetch actual bus key
538         my $sql_statement= "SELECT * FROM known_server WHERE status='bus'";
539         my $query_res = $main::known_server_db->select_dbentry( $sql_statement );
540         my $hostkey = $query_res->{1}->{'hostkey'};
542         # send update msg to bus
543         $out_hash = &create_xml_hash("new_client", $server_address, $bus_address, $source);
544         &add_content2xml_hash($out_hash, "macaddress", $mac_address);
545         &add_content2xml_hash($out_hash, "timestamp", $act_timestamp);
546         my $new_client_out = &create_xml_string($out_hash);
547         push(@out_msg_l, $new_client_out);
548         &main::daemon_log("send bus msg that client '$source' has registerd at server '$server_address'", 3);
549     }
551     # give the new client his ldap config
552     my $new_ldap_config_out = &new_ldap_config($source);
553     if( $new_ldap_config_out ) {
554         push(@out_msg_l, $new_ldap_config_out);
555     }
557         my $hardware_config_out = &hardware_config($source, $gotoHardwareChecksum);
558         if( $hardware_config_out ) {
559                 push(@out_msg_l, $hardware_config_out);
560         }
562     return @out_msg_l;
566 #===  FUNCTION  ================================================================
567 #         NAME:  who_has
568 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
569 #      RETURNS:  nothing 
570 #  DESCRIPTION:  process this incoming message
571 #===============================================================================
572 sub who_has {
573     my ($msg_hash) = @_ ;
574     my @out_msg_l;
575     
576     # what is your search pattern
577     my $search_pattern = @{$msg_hash->{who_has}}[0];
578     my $search_element = @{$msg_hash->{$search_pattern}}[0];
579     &main::daemon_log("who_has-msg looking for $search_pattern $search_element", 7);
581     # scanning known_clients for search_pattern
582     my @host_addresses = keys %$main::known_clients;
583     my $known_clients_entries = length @host_addresses;
584     my $host_address;
585     foreach my $host (@host_addresses) {
586         my $client_element = $main::known_clients->{$host}->{$search_pattern};
587         if ($search_element eq $client_element) {
588             $host_address = $host;
589             last;
590         }
591     }
592         
593     # search was successful
594     if (defined $host_address) {
595         my $source = @{$msg_hash->{source}}[0];
596         my $out_hash = &create_xml_hash("who_has_i_do", $server_address, $source, "mac_address");
597         &add_content2xml_hash($out_hash, "mac_address", $search_element);
598         my $out_msg = &create_xml_string($out_hash);
599         push(@out_msg_l, $out_msg);
600     }
601     return @out_msg_l;
605 sub who_has_i_do {
606     my ($msg_hash) = @_ ;
607     my $header = @{$msg_hash->{header}}[0];
608     my $source = @{$msg_hash->{source}}[0];
609     my $search_param = @{$msg_hash->{$header}}[0];
610     my $search_value = @{$msg_hash->{$search_param}}[0];
611     print "\ngot msg $header:\nserver $source has client with $search_param $search_value\n";
614 #===  FUNCTION  ================================================================
615 #         NAME:  new_ldap_config
616 #   PARAMETERS:  address - string - ip address and port of a host
617 #      RETURNS:  nothing
618 #  DESCRIPTION:  send to address the ldap configuration found for dn gotoLdapServer
619 #===============================================================================
620 sub new_ldap_config {
621         my ($address) = @_ ;
623         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address'";
624         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
626         # check hit
627         my $hit_counter = keys %{$res};
628         if( not $hit_counter == 1 ) {
629                 &main::daemon_log("ERROR: more or no hit found in known_clients_db by query by '$address'", 1);
630         }
632         my $macaddress = $res->{1}->{macaddress};
633         my $hostkey = $res->{1}->{hostkey};
635         if (not defined $macaddress) {
636                 &main::daemon_log("ERROR: no mac address found for client $address", 1);
637                 return;
638         }
640         # Build LDAP connection
641         my $ldap = Net::LDAP->new($ldap_uri);
642         if( not defined $ldap ) {
643                 &main::daemon_log("ERROR: cannot connect to ldap: $ldap_uri", 1);
644                 return;
645         } 
648         # Bind to a directory with dn and password
649         my $mesg= $ldap->bind($ldap_admin_dn, password => $ldap_admin_password);
651         # Perform search
652         $mesg = $ldap->search( base   => $ldap_base,
653                 scope  => 'sub',
654                 attrs => ['dn', 'gotoLdapServer', 'gosaUnitTag'],
655                 filter => "(&(objectClass=GOhard)(macaddress=$macaddress))");
656         #$mesg->code && die $mesg->error;
657         if($mesg->code) {
658                 &main::daemon_log($mesg->error, 1);
659                 return;
660         }
662         # Sanity check
663         if ($mesg->count != 1) {
664                 &main::daemon_log("WARNING: client mac address $macaddress not found/not unique in ldap search", 1);
665                 &main::daemon_log("\tbase: $ldap_base", 1);
666                 &main::daemon_log("\tscope: sub", 1);
667                 &main::daemon_log("\tattrs: dn, gotoLdapServer", 1);
668                 &main::daemon_log("\tfilter: (&(objectClass=GOhard)(macaddress=$macaddress))", 1);
669                 return;
670         }
672         my $entry= $mesg->entry(0);
673         my $dn= $entry->dn;
674         my @servers= $entry->get_value("gotoLdapServer");
675         my $unit_tag= $entry->get_value("gosaUnitTag");
676         my @ldap_uris;
677         my $server;
678         my $base;
680         # Do we need to look at an object class?
681         if (length(@servers) < 1){
682                 $mesg = $ldap->search( base   => $ldap_base,
683                         scope  => 'sub',
684                         attrs => ['dn', 'gotoLdapServer'],
685                         filter => "(&(objectClass=gosaGroupOfNames)(member=$dn))");
686                 #$mesg->code && die $mesg->error;
687                 if($mesg->code) {
688                         &main::daemon_log($mesg->error, 1);
689                         return;
690                 }
692                 # Sanity check
693                 if ($mesg->count != 1) {
694                         &main::daemon_log("WARNING: no LDAP information found for client mac $macaddress", 1);
695                         return;
696                 }
698                 $entry= $mesg->entry(0);
699                 $dn= $entry->dn;
700                 @servers= $entry->get_value("gotoLdapServer");
701         }
703         @servers= sort (@servers);
705         foreach $server (@servers){
706                 $base= $server;
707                 $server =~ s%^[^:]+:[^:]+:(ldap.*://[^/]+)/.*$%$1%;
708                 $base =~ s%^[^:]+:[^:]+:ldap.*://[^/]+/(.*)$%$1%;
709                 push (@ldap_uris, $server);
710         }
712         # Assemble data package
713         my %data = ( 'ldap_uri'  => \@ldap_uris, 'ldap_base' => $base,
714                 'ldap_cfg' => \@ldap_cfg, 'pam_cfg' => \@pam_cfg,'nss_cfg' => \@nss_cfg );
716         # Need to append GOto settings?
717         if (defined $goto_admin and defined $goto_secret){
718                 $data{'goto_admin'}= $goto_admin;
719                 $data{'goto_secret'}= $goto_secret;
720         }
722         # Append unit tag if needed
723         if (defined $unit_tag){
725                 # Find admin base and department name
726                 $mesg = $ldap->search( base   => $ldap_base,
727                         scope  => 'sub',
728                         attrs => ['dn', 'ou', 'FAIclass'],
729                         filter => "(&(objectClass=gosaAdministrativeUnit)(gosaUnitTag=$unit_tag))");
730                 #$mesg->code && die $mesg->error;
731                 if($mesg->code) {
732                         &main::daemon_log($mesg->error, 1);
733                         return;
734                 }
736                 # Sanity check
737                 if ($mesg->count != 1) {
738                         &main::daemon_log("WARNING: cannot find administrative unit for client with tag $unit_tag", 1);
739                         return;
740                 }
742                 $entry= $mesg->entry(0);
743                 $data{'admin_base'}= $entry->dn;
744                 $data{'department'}= $entry->get_value("ou");
746                 # Append unit Tag
747                 $data{'unit_tag'}= $unit_tag;
748         }
750         # Fill release if available
751         my $FAIclass= $entry->get_value("FAIclass");
752         if (defined $FAIclass && $FAIclass =~ /^.* :([A-Za-z0-9\/.]+).*$/) {
753                 $data{'release'}= $1;
754         }
757         # Unbind
758         $mesg = $ldap->unbind;
760         # Send information
761         return send_msg("new_ldap_config", $server_address, $address, \%data);
764 sub process_detected_hardware {
765         my $msg_hash = shift;
766         my $address = $msg_hash->{source}[0];
767         my $gotoHardwareChecksum= $msg_hash->{detected_hardware}[0]->{gotoHardwareChecksum};
769     my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address'";
770     my $res = $main::known_clients_db->select_dbentry( $sql_statement );
772     # check hit
773     my $hit_counter = keys %{$res};
774     if( not $hit_counter == 1 ) {
775         &main::daemon_log("ERROR: more or no hit found in known_clients_db by query by '$address'", 1);
776                 return;
777     }
779     my $macaddress = $res->{1}->{macaddress};
780     my $hostkey = $res->{1}->{hostkey};
782     if (not defined $macaddress) {
783         &main::daemon_log("ERROR: no mac address found for client $address", 1);
784         return;
785     }
786     # Build LDAP connection
787     my $ldap = Net::LDAP->new($ldap_uri);
788     if( not defined $ldap ) {
789         &main::daemon_log("ERROR: cannot connect to ldap: $ldap_uri", 1);
790         return;
791     } 
793     # Bind to a directory with dn and password
794     my $mesg= $ldap->bind($ldap_admin_dn, password => $ldap_admin_password);
796     # Perform search
797         $mesg = $ldap->search(
798                 base   => $ldap_base,
799                 scope  => 'sub',
800                 filter => "(&(objectClass=GOhard)(|(macAddress=$macaddress)(dhcpHWaddress=ethernet $macaddress)))"
801         );
803         # We need to create a base entry first (if not done from ArpHandler)
804         if($mesg->count == 0) {
805                 &main::daemon_log("Need to create a new LDAP Entry for client $address", 1);
806                 my $resolver=Net::DNS::Resolver->new;
807                 my $ipaddress= $1 if $address =~ /^([0-9\.]*?):.*$/;
808                 my $dnsresult= $resolver->search($ipaddress);
809                 my $dnsname= (defined($dnsresult))?$dnsresult->{answer}[0]->{ptrdname}:$ipaddress;
810                 my $cn = (($dnsname =~ /^(\d){1,3}\.(\d){1,3}\.(\d){1,3}\.(\d){1,3}/) ? $dnsname : sprintf "%s", $dnsname =~ /([^\.]+)\.?/);
811                 my $dn = "cn=$cn,ou=incoming,$ldap_base";
812                 &main::daemon_log("Creating entry for $dn",6);
813                 my $entry= Net::LDAP::Entry->new( $dn );
814                 $entry->dn($dn);
815                 $entry->add("objectClass" => "goHard");
816                 $entry->add("cn" => $cn);
817                 $entry->add("macAddress" => $macaddress);
818                 $entry->add("gotomode" => "locked");
819                 $entry->add("gotoSysStatus" => "new-system");
820                 $entry->add("ipHostNumber" => $ipaddress);
821                 if(my $res=$entry->update($ldap)) {
822                         # Fill $mesg again
823                         $mesg = $ldap->search(
824                                 base   => $ldap_base,
825                                 scope  => 'sub',
826                                 filter => "(&(objectClass=GOhard)(|(macAddress=$macaddress)(dhcpHWaddress=ethernet $macaddress)))"
827                         );
828                 } else {
829                         &main::daemon_log("ERROR: There was a problem adding the entry", 1);
830                 }
832         }
833         
834         if($mesg->count == 1) {
835                 my $entry= $mesg->entry(0);
836                 $entry->changetype("modify");
837                 foreach my $attribute (
838                         "gotoSndModule", "ghNetNic", "gotoXResolution", "ghSoundAdapter", "ghCpuType", "gotoXkbModel", 
839                         "ghGfxAdapter", "gotoXMousePort", "ghMemSize", "gotoXMouseType", "ghUsbSupport", "gotoXHsync", 
840                         "gotoXDriver", "gotoXVsync", "gotoXMonitor", "gotoHardwareChecksum") {
841                         if(defined($msg_hash->{detected_hardware}[0]->{$attribute})) {
842                                 if(defined($entry->get_value($attribute))) {
843                                         $entry->delete($attribute);
844                                 }
845                                 &main::daemon_log("Adding attribute $attribute with value ".$msg_hash->{detected_hardware}[0]->{$attribute},1);
846                                 $entry->add($attribute => $msg_hash->{detected_hardware}[0]->{$attribute});     
847                         }
848                 }
849                 foreach my $attribute (
850                         "gotoModules", "ghScsiDev", "ghIdeDev") {
851                         if(defined($msg_hash->{detected_hardware}[0]->{$attribute})) {
852                                 if(defined($entry->get_value($attribute))) {
853                                         $entry->delete($attribute);
854                                 }
855                                 foreach my $array_entry (@{$msg_hash->{detected_hardware}[0]->{$attribute}}) {
856                                         $entry->add($attribute => $array_entry);
857                                 }
858                         }
860                 }
862                 if($entry->update($ldap)) {
863                         &main::daemon_log("Added Hardware configuration to LDAP", 4);
864                 }
866         }
867         return;
869 #===  FUNCTION  ================================================================
870 #         NAME:  hardware_config
871 #   PARAMETERS:  address - string - ip address and port of a host
872 #      RETURNS:  
873 #  DESCRIPTION:  
874 #===============================================================================
875 sub hardware_config {
876         my ($address, $gotoHardwareChecksum) = @_ ;
878         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address'";
879         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
881         # check hit
882         my $hit_counter = keys %{$res};
883         if( not $hit_counter == 1 ) {
884                 &main::daemon_log("ERROR: more or no hit found in known_clients_db by query by '$address'", 1);
885         }
887         my $macaddress = $res->{1}->{macaddress};
888         my $hostkey = $res->{1}->{hostkey};
890         if (not defined $macaddress) {
891                 &main::daemon_log("ERROR: no mac address found for client $address", 1);
892                 return;
893         }
895         # Build LDAP connection
896         my $ldap = Net::LDAP->new($ldap_uri);
897         if( not defined $ldap ) {
898                 &main::daemon_log("ERROR: cannot connect to ldap: $ldap_uri", 1);
899                 return;
900         } 
902         # Bind to a directory with dn and password
903         my $mesg= $ldap->bind($ldap_admin_dn, password => $ldap_admin_password);
905         # Perform search
906         $mesg = $ldap->search(
907                 base   => $ldap_base,
908                 scope  => 'sub',
909                 filter => "(&(objectClass=GOhard)(|(macAddress=$macaddress)(dhcpHWaddress=ethernet $macaddress)))"
910         );
912         if($mesg->count() == 0) {
913                 &main::daemon_log("Host was not found in LDAP!", 1);
914         } else {
915                 my $entry= $mesg->entry(0);
916                 my $dn= $entry->dn;
917                 if(defined($entry->get_value("gotoHardwareChecksum"))) {
918                         if(! $entry->get_value("gotoHardwareChecksum") eq $gotoHardwareChecksum) {
919                                 $entry->replace(gotoHardwareChecksum => $gotoHardwareChecksum);
920                                 if($entry->update($ldap)) {
921                                         &main::daemon_log("Hardware changed! Detection triggered.", 4);
922                                 }
923                         } else {
924                                 # Nothing to do
925                                 return;
926                         }
927                 }
928         } 
929         # need to fill it to LDAP
930         #$entry->add(gotoHardwareChecksum => $gotoHardwareChecksum);
931         #if($entry->update($ldap)) {
932         #               &main::daemon_log("gotoHardwareChecksum $gotoHardwareChecksum was added to LDAP", 4);
933         #}
935         ## Look if there another host with this checksum to use the hardware config
936         #$mesg = $ldap->search(
937         #       base   => $ldap_base,
938         #       scope  => 'sub',
939         #       filter => "(&(objectClass=GOhard)(gotoHardwareChecksum=$gotoHardwareChecksum))"
940         #);
942         #if($mesg->count>1) {
943         #       my $clone_entry= $mesg->entry(0);
944         #       $entry->changetype("modify");
945         #       foreach my $attribute (
946         #               "gotoSndModule", "ghNetNic", "gotoXResolution", "ghSoundAdapter", "ghCpuType", "gotoXkbModel", 
947         #               "ghGfxAdapter", "gotoXMousePort", "ghMemSize", "gotoXMouseType", "ghUsbSupport", "gotoXHsync", 
948         #               "gotoXDriver", "gotoXVsync", "gotoXMonitor") {
949         #               my $value= $clone_entry->get_value($attribute);
950         #               if(defined($value)) {
951         #                       if(defined($entry->get_value($attribute))) {
952         #                               $entry->delete($attribute);
953         #                       }
954         #                       &main::daemon_log("Adding attribute $attribute with value $value",1);
955         #                       $entry->add($attribute => $value);
956         #               }
957         #       }
958         #       foreach my $attribute (
959         #               "gotoModules", "ghScsiDev", "ghIdeDev") {
960         #               my $array= $clone_entry->get_value($attribute, 'as_ref' => 1);
961         #               if(defined($array))     {
962         #                       if(defined($entry->get_value($attribute))) {
963         #                               $entry->delete($attribute);
964         #                       }
965         #                       foreach my $array_entry (@{$array}) {
966         #                               $entry->add($attribute => $array_entry);
967         #                       }
968         #               }
970         #       }
971         #       if($entry->update($ldap)) {
972         #               &main::daemon_log("Added Hardware configuration to LDAP", 4);
973         #       }
975         #}
978         # Assemble data package
979         my %data = ();
981         # Need to append GOto settings?
982         if (defined $goto_admin and defined $goto_secret){
983                 $data{'goto_admin'}= $goto_admin;
984                 $data{'goto_secret'}= $goto_secret;
985         }
987         # Unbind
988         $mesg = $ldap->unbind;
990         &main::daemon_log("Send detect_hardware message to $address", 4);
992         # Send information
993         return send_msg("detect_hardware", $server_address, $address, \%data);
996 sub server_matches {
997         my $target = shift;
998         my $target_ip = sprintf("%s", $target =~ /^([0-9\.]*?):.*$/);
999         my $result = 0;
1001         if($server_ip eq $target_ip) {
1002                 $result= 1;
1003         } elsif ($server_ip eq "0.0.0.0") {     
1004                 if ($target_ip eq "127.0.0.1") {
1005                         $result= 1;
1006                 } else {
1007                         my $PROC_NET_ROUTE= ('/proc/net/route');
1009                         open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
1010                                 or die "Could not open $PROC_NET_ROUTE";
1012                         my @ifs = <PROC_NET_ROUTE>;
1014                         close(PROC_NET_ROUTE);
1016                         # Eat header line
1017                         shift @ifs;
1018                         chomp @ifs;
1019                         foreach my $line(@ifs) {
1020                                 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
1021                                 my $destination;
1022                                 my $mask;
1023                                 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
1024                                 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
1025                                 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
1026                                 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
1027                                 if(new NetAddr::IP($target_ip)->within(new NetAddr::IP($destination, $mask))) {
1028                                         # destination matches route, save mac and exit
1029                                         $result= 1;
1030                                         last;
1031                                 }
1032                         }
1033                 }
1034         } else {
1035                 &main::daemon_log("Target ip $target_ip does not match Server ip $server_ip",1);
1036         }
1038         return $result;
1042 #===  FUNCTION  ================================================================
1043 #         NAME:  execute_actions
1044 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
1045 #      RETURNS:  nothing
1046 #  DESCRIPTION:  invokes the script specified in msg_hash which is located under
1047 #                /etc/gosad/actions
1048 #===============================================================================
1049 sub execute_actions {
1050     my ($msg_hash) = @_ ;
1051     my $configdir= '/etc/gosad/actions/';
1052     my $result;
1054     my $header = @{$msg_hash->{header}}[0];
1055     my $source = @{$msg_hash->{source}}[0];
1056     my $target = @{$msg_hash->{target}}[0];
1057  
1058     if((not defined $source)
1059             && (not defined $target)
1060             && (not defined $header)) {
1061         &main::daemon_log("ERROR: Entries missing in XML msg for gosad actions under /etc/gosad/actions");
1062     } else {
1063         my $parameters="";
1064         my @params = @{$msg_hash->{$header}};
1065         my $params = join(", ", @params);
1066         &main::daemon_log("execute_actions: got parameters: $params", 5);
1068         if (@params) {
1069             foreach my $param (@params) {
1070                 my $param_value = (&get_content_from_xml_hash($msg_hash, $param))[0];
1071                 &main::daemon_log("execute_actions: parameter -> value: $param -> $param_value", 7);
1072                 $parameters.= " ".$param_value;
1073             }
1074         }
1076         my $cmd= $configdir.$header."$parameters";
1077         &main::daemon_log("execute_actions: executing cmd: $cmd", 7);
1078         $result= "";
1079         open(PIPE, "$cmd 2>&1 |");
1080         while(<PIPE>) {
1081             $result.=$_;
1082         }
1083         close(PIPE);
1084     }
1086     # process the event result
1089     return;
1093 1;