Code

2dc40fffcda9cd991d534338e31ae4afe8e65098
[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                 my $mesg= $tmp_ldap->bind($ldap_admin_dn, password => $ldap_admin_password);
69                 # Perform search for Unit Tag
70                 $mesg = $tmp_ldap->search(
71                         base   => $ldap_base,
72                         scope  => 'sub',
73                         attrs  => ['gosaUnitTag'],
74                         filter => "(macaddress=$server_mac_address)"
75                 );
77                 if ($mesg->count == 1) {
78                         my $entry= $mesg->entry(0);
79                         my $unit_tag= $entry->get_value("gosaUnitTag");
80                         if(defined($unit_tag) && length($unit_tag) > 0) {
81                                 &main::daemon_log("Detected gosaUnitTag $unit_tag for creating entries", 4);
82                                 $gosa_unit_tag= $unit_tag;
83                         }
84                         $mesg = $tmp_ldap->unbind;
85                 }
86         }
87 }
89 # complete addresses
90 #if( $server_ip eq "0.0.0.0" ) {
91 #    $server_ip = "127.0.0.1";
92 #}
93 my $server_address = "$server_ip:$server_port";
94 $main::server_address = $server_address;
95 my $bus_address = "$bus_ip:$bus_port";
96 $main::bus_address = $bus_address;
98 # create general settings for this module
99 my $xml = new XML::Simple();
101 # register at bus
102 if ($main::no_bus > 0) {
103     $bus_activ = "off"
105 if($bus_activ eq "on") {
106     &register_at_bus();
109 # add myself to known_server_db
110 my $res = $main::known_server_db->add_dbentry( {table=>'known_server',
111         primkey=>'hostname',
112         hostname=>$server_address,
113         status=>'myself',
114         hostkey=>$SIPackages_key,
115         timestamp=>&get_time,
116         } );
120 ### functions #################################################################
123 sub get_module_info {
124     my @info = ($server_address,
125                 $SIPackages_key,
126                 );
127     return \@info;
131 sub do_wake {
132         my $host    = shift;
133         my $ipaddr  = shift || '255.255.255.255';
134         my $port    = getservbyname('discard', 'udp');
136         my ($raddr, $them, $proto);
137         my ($hwaddr, $hwaddr_re, $pkt);
139         # get the hardware address (ethernet address)
141         $hwaddr_re = join(':', ('[0-9A-Fa-f]{1,2}') x 6);
142         if ($host =~ m/^$hwaddr_re$/) {
143                 $hwaddr = $host;
144         } else {
145                 # $host is not a hardware address, try to resolve it
146                 my $ip_re = join('\.', ('([0-9]|[1-9][0-9]|1[0-9]{2}|2([0-4][0-9]|5[0-5]))') x 4);
147                 my $ip_addr;
148                 if ($host =~ m/^$ip_re$/) {
149                         $ip_addr = $host;
150                 } else {
151                         my $h;
152                         unless ($h = gethost($host)) {
153                                 return undef;
154                         }
155                         $ip_addr = inet_ntoa($h->addr);
156                 }
157         }
159         # Generate magic sequence
160         foreach (split /:/, $hwaddr) {
161                 $pkt .= chr(hex($_));
162         }
163         $pkt = chr(0xFF) x 6 . $pkt x 16;
165         # Allocate socket and send packet
167         $raddr = gethostbyname($ipaddr)->addr;
168         $them = pack_sockaddr_in($port, $raddr);
169         $proto = getprotobyname('udp');
171         socket(S, AF_INET, SOCK_DGRAM, $proto) or die "socket : $!";
172         setsockopt(S, SOL_SOCKET, SO_BROADCAST, 1) or die "setsockopt : $!";
174         send(S, $pkt, 0, $them) or die "send : $!";
175         close S;
179 #===  FUNCTION  ================================================================
180 #         NAME:  read_configfile
181 #   PARAMETERS:  cfg_file - string -
182 #      RETURNS:  nothing
183 #  DESCRIPTION:  read cfg_file and set variables
184 #===============================================================================
185 sub read_configfile {
186     my $cfg;
187     if( defined( $main::cfg_file) && ( length($main::cfg_file) > 0 )) {
188         if( -r $main::cfg_file ) {
189             $cfg = Config::IniFiles->new( -file => $main::cfg_file );
190         } else {
191             print STDERR "Couldn't read config file!";
192         }
193     } else {
194         $cfg = Config::IniFiles->new() ;
195     }
196     foreach my $section (keys %cfg_defaults) {
197         foreach my $param (keys %{$cfg_defaults{ $section }}) {
198             my $pinfo = $cfg_defaults{ $section }{ $param };
199             ${@$pinfo[0]} = $cfg->val( $section, $param, @$pinfo[1] );
200         }
201     }
203     # Read non predefined sections
204     my $param;
205     if ($cfg->SectionExists('ldap')){
206                 foreach $param ($cfg->Parameters('ldap')){
207                         push (@ldap_cfg, "$param ".$cfg->val('ldap', $param));
208                 }
209     }
210     if ($cfg->SectionExists('pam_ldap')){
211                 foreach $param ($cfg->Parameters('pam_ldap')){
212                         push (@pam_cfg, "$param ".$cfg->val('pam_ldap', $param));
213                 }
214     }
215     if ($cfg->SectionExists('nss_ldap')){
216                 foreach $param ($cfg->Parameters('nss_ldap')){
217                         push (@nss_cfg, "$param ".$cfg->val('nss_ldap', $param));
218                 }
219     }
220     if ($cfg->SectionExists('goto')){
221         $goto_admin= $cfg->val('goto', 'terminal_admin');
222         $goto_secret= $cfg->val('goto', 'terminal_secret');
223     } else {
224         $goto_admin= undef;
225         $goto_secret= undef;
226     }
230 #===  FUNCTION  ================================================================
231 #         NAME:  get_interface_for_ip
232 #   PARAMETERS:  ip address (i.e. 192.168.0.1)
233 #      RETURNS:  array: list of interfaces if ip=0.0.0.0, matching interface if found, undef else
234 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
235 #===============================================================================
236 sub get_interface_for_ip {
237         my $result;
238         my $ip= shift;
239         if ($ip && length($ip) > 0) {
240                 my @ifs= &get_interfaces();
241                 if($ip eq "0.0.0.0") {
242                         $result = "all";
243                 } else {
244                         foreach (@ifs) {
245                                 my $if=$_;
246                                 if(get_ip($if) eq $ip) {
247                                         $result = $if;
248                                 }
249                         }       
250                 }
251         }       
252         return $result;
255 #===  FUNCTION  ================================================================
256 #         NAME:  get_interfaces 
257 #   PARAMETERS:  none
258 #      RETURNS:  (list of interfaces) 
259 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
260 #===============================================================================
261 sub get_interfaces {
262         my @result;
263         my $PROC_NET_DEV= ('/proc/net/dev');
265         open(PROC_NET_DEV, "<$PROC_NET_DEV")
266                 or die "Could not open $PROC_NET_DEV";
268         my @ifs = <PROC_NET_DEV>;
270         close(PROC_NET_DEV);
272         # Eat first two line
273         shift @ifs;
274         shift @ifs;
276         chomp @ifs;
277         foreach my $line(@ifs) {
278                 my $if= (split /:/, $line)[0];
279                 $if =~ s/^\s+//;
280                 push @result, $if;
281         }
283         return @result;
286 #===  FUNCTION  ================================================================
287 #         NAME:  get_mac 
288 #   PARAMETERS:  interface name (i.e. eth0)
289 #      RETURNS:  (mac address) 
290 #  DESCRIPTION:  Uses ioctl to get mac address directly from system.
291 #===============================================================================
292 sub get_mac {
293         my $ifreq= shift;
294         my $result;
295         if ($ifreq && length($ifreq) > 0) { 
296                 if($ifreq eq "all") {
297                         $result = "00:00:00:00:00:00";
298                 } else {
299                         my $SIOCGIFHWADDR= 0x8927;     # man 2 ioctl_list
301                         # A configured MAC Address should always override a guessed value
302                         if ($server_mac_address and length($server_mac_address) > 0) {
303                                 $result= $server_mac_address;
304                         }
306                         socket SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('ip')
307                                 or die "socket: $!";
309                         if(ioctl SOCKET, $SIOCGIFHWADDR, $ifreq) {
310                                 my ($if, $mac)= unpack 'h36 H12', $ifreq;
312                                 if (length($mac) > 0) {
313                                         $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])$/;
314                                         $mac= sprintf("%s:%s:%s:%s:%s:%s", $1, $2, $3, $4, $5, $6);
315                                         $result = $mac;
316                                 }
317                         }
318                 }
319         }
320         return $result;
324 #===  FUNCTION  ================================================================
325 #         NAME:  register_at_bus
326 #   PARAMETERS:  nothing
327 #      RETURNS:  nothing
328 #  DESCRIPTION:  creates an entry in known_daemons and send a 'here_i_am' msg to bus
329 #===============================================================================
330 sub register_at_bus {
332     # add bus to known_server_db
333     my $res = $main::known_server_db->add_dbentry( {table=>'known_server',
334                                                     primkey=>'hostname',
335                                                     hostname=>$bus_address,
336                                                     status=>'bus',
337                                                     hostkey=>$bus_key,
338                                                     timestamp=>&get_time,
339                                                 } );
340     my $msg_hash = &create_xml_hash("here_i_am", $server_address, $bus_address);
341     my $msg = &create_xml_string($msg_hash);
343     &main::send_msg_to_target($msg, $bus_address, $bus_key, "here_i_am");
344     return $msg;
348 #===  FUNCTION  ================================================================
349 #         NAME:  process_incoming_msg
350 #   PARAMETERS:  crypted_msg - string - incoming crypted message
351 #      RETURNS:  nothing
352 #  DESCRIPTION:  handels the proceeded distribution to the appropriated functions
353 #===============================================================================
354 sub process_incoming_msg {
355     my ($msg, $msg_hash, $remote_ip) = @_ ;
356     my $error = 0;
357     my $host_name;
358     my $host_key;
359     my @out_msg_l;
361     # process incoming msg
362     my $header = @{$msg_hash->{header}}[0]; 
363     my @target_l = @{$msg_hash->{target}};
365     &main::daemon_log("SIPackages: msg to process: $header", 3);
366     &main::daemon_log("$msg", 8);
368     if( 0 == length @target_l){     
369         &main::daemon_log("ERROR: no target specified for msg $header", 1);
370         $error++;
371     }
373     if( 1 == length @target_l) {
374         my $target = $target_l[0];
375                 if(&server_matches($target)) {
376             if ($header eq 'new_key') {
377                 @out_msg_l = &new_key($msg_hash)
378             } elsif ($header eq 'here_i_am') {
379                 @out_msg_l = &here_i_am($msg_hash)
380             } elsif ($header eq 'who_has') {
381                 @out_msg_l = &who_has($msg_hash)
382             } elsif ($header eq 'who_has_i_do') {
383                 @out_msg_l = &who_has_i_do($msg_hash)
384             } elsif ($header eq 'got_ping') {
385                 @out_msg_l = &got_ping($msg_hash)
386             } elsif ($header eq 'get_load') {
387                 @out_msg_l = &execute_actions($msg_hash)
388             } elsif ($header eq 'detected_hardware') {
389                 @out_msg_l = &process_detected_hardware($msg_hash)
390             } elsif ($header eq 'trigger_wake') {
391                 foreach (@{$msg_hash->{macAddress}}){
392                     &main::daemon_log("SIPackages: trigger wake for $_", 1);
393                     do_wake($_);
394                 }
396             } else {
397                 &main::daemon_log("ERROR: $header is an unknown core function", 1);
398                 $error++;
399             }
400         }
401                 else {
402                         &main::daemon_log("msg is not for gosa-si-server '$server_address', deliver it to target '$target'", 5);
403                         push(@out_msg_l, $msg);
404                 }
405     }
407 #    if( $error == 0) {
408 #        if( 0 == @out_msg_l ) {
409 #                       push(@out_msg_l, $msg);
410 #        }
411 #    }
412     
413     return \@out_msg_l;
417 #===  FUNCTION  ================================================================
418 #         NAME:  got_ping
419 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
420 #      RETURNS:  nothing
421 #  DESCRIPTION:  process this incoming message
422 #===============================================================================
423 sub got_ping {
424     my ($msg_hash) = @_;
425     
426     my $source = @{$msg_hash->{source}}[0];
427     my $target = @{$msg_hash->{target}}[0];
428     my $header = @{$msg_hash->{header}}[0];
429     
430     if(exists $main::known_daemons->{$source}) {
431         &main::add_content2known_daemons(hostname=>$source, status=>$header);
432     } else {
433         &main::add_content2known_clients(hostname=>$source, status=>$header);
434     }
435     
436     return;
440 #===  FUNCTION  ================================================================
441 #         NAME:  new_passwd
442 #   PARAMETERS:  msg_hash - ref - hash from function create_xml_hash
443 #      RETURNS:  nothing
444 #  DESCRIPTION:  process this incoming message
445 #===============================================================================
446 sub new_key {
447     my ($msg_hash) = @_;
448     my @out_msg_l;
449     
450     my $header = @{$msg_hash->{header}}[0];
451     my $source_name = @{$msg_hash->{source}}[0];
452     my $source_key = @{$msg_hash->{new_key}}[0];
453     my $query_res;
455     # check known_clients_db
456     my $sql_statement = "SELECT * FROM known_clients WHERE hostname='$source_name'";
457     $query_res = $main::known_clients_db->select_dbentry( $sql_statement );
458     if( 1 == keys %{$query_res} ) {
459         my $act_time = &get_time;
460         my $sql_statement= "UPDATE known_clients ".
461             "SET hostkey='$source_key', timestamp='$act_time' ".
462             "WHERE hostname='$source_name'";
463         my $res = $main::known_clients_db->update_dbentry( $sql_statement );
464         my $hash = &create_xml_hash("confirm_new_key", $server_address, $source_name);
465         my $out_msg = &create_xml_string($hash);
466         push(@out_msg_l, $out_msg);
467     }
469     # only do if host still not found
470     if( 0 == @out_msg_l ) {
471         # check known_server_db
472         $sql_statement = "SELECT * FROM known_server WHERE hostname='$source_name'";
473         $query_res = $main::known_server_db->select_dbentry( $sql_statement );
474         if( 1 == keys %{$query_res} ) {
475             my $act_time = &get_time;
476             my $sql_statement= "UPDATE known_server ".
477                 "SET hostkey='$source_key', timestamp='$act_time' ".
478                 "WHERE hostname='$source_name'";
479             my $res = $main::known_server_db->update_dbentry( $sql_statement );
481             my $hash = &create_xml_hash("confirm_new_key", $server_address, $source_name);
482             my $out_msg = &create_xml_string($hash);
483             push(@out_msg_l, $out_msg);
484         }
485     }
487     return @out_msg_l;
491 #===  FUNCTION  ================================================================
492 #         NAME:  here_i_am
493 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
494 #      RETURNS:  nothing
495 #  DESCRIPTION:  process this incoming message
496 #===============================================================================
497 sub here_i_am {
498     my ($msg_hash) = @_;
499     my @out_msg_l;
500     my $out_hash;
502     my $source = @{$msg_hash->{source}}[0];
503     my $mac_address = @{$msg_hash->{mac_address}}[0];
504         my $gotoHardwareChecksum = @{$msg_hash->{gotoHardwareChecksum}}[0];
506     # number of known clients
507     my $nu_clients= $main::known_clients_db->count_dbentries('known_clients');
509     # check wether client address or mac address is already known
510     my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$source'";
511     my $db_res= $main::known_clients_db->select_dbentry( $sql_statement );
512     
513     if ( 1 == keys %{$db_res} ) {
514         &main::daemon_log("WARNING: $source is already known as a client", 1);
515         &main::daemon_log("WARNING: values for $source are being overwritten", 1);   
516         $nu_clients --;
517     }
519     # number of actual activ clients
520     my $act_nu_clients = $nu_clients;
522     &main::daemon_log("number of actual activ clients: $act_nu_clients", 5);
523     &main::daemon_log("number of maximal allowed clients: $max_clients", 5);
525     if($max_clients <= $act_nu_clients) {
526         my $out_hash = &create_xml_hash("denied", $server_address, $source);
527         &add_content2xml_hash($out_hash, "denied", "I_cannot_take_any_more_clients!");
528         my $passwd = @{$msg_hash->{new_passwd}}[0]; 
529         &send_msg_hash2address($out_hash, $source, $passwd);
530         return;
531     }
532     
533     # new client accepted
534     my $new_passwd = @{$msg_hash->{new_passwd}}[0];
536     # create entry in known_clients
537     my $events = @{$msg_hash->{events}}[0];
538     
540     # add entry to known_clients_db
541     my $act_timestamp = &get_time;
542     my $res = $main::known_clients_db->add_dbentry( {table=>'known_clients', 
543                                                 primkey=>'hostname',
544                                                 hostname=>$source,
545                                                 events=>$events,
546                                                 macaddress=>$mac_address,
547                                                 status=>'registered',
548                                                 hostkey=>$new_passwd,
549                                                 timestamp=>$act_timestamp,
550                                                 } );
552     if ($res != 0)  {
553         &main::daemon_log("ERROR: cannot add entry to known_clients: $res");
554         return;
555     }
556     
557     # return acknowledgement to client
558     $out_hash = &create_xml_hash("registered", $server_address, $source);
559     my $register_out = &create_xml_string($out_hash);
560     push(@out_msg_l, $register_out);
562     # notify registered client to bus
563     if( $bus_activ eq "on") {
564         # fetch actual bus key
565         my $sql_statement= "SELECT * FROM known_server WHERE status='bus'";
566         my $query_res = $main::known_server_db->select_dbentry( $sql_statement );
567         my $hostkey = $query_res->{1}->{'hostkey'};
569         # send update msg to bus
570         $out_hash = &create_xml_hash("new_client", $server_address, $bus_address, $source);
571         &add_content2xml_hash($out_hash, "macaddress", $mac_address);
572         &add_content2xml_hash($out_hash, "timestamp", $act_timestamp);
573         my $new_client_out = &create_xml_string($out_hash);
574         push(@out_msg_l, $new_client_out);
575         &main::daemon_log("send bus msg that client '$source' has registerd at server '$server_address'", 3);
576     }
578     # give the new client his ldap config
579     my $new_ldap_config_out = &new_ldap_config($source);
580     if( $new_ldap_config_out ) {
581         push(@out_msg_l, $new_ldap_config_out);
582     }
584         my $hardware_config_out = &hardware_config($source, $gotoHardwareChecksum);
585         if( $hardware_config_out ) {
586                 push(@out_msg_l, $hardware_config_out);
587         }
589     return @out_msg_l;
593 #===  FUNCTION  ================================================================
594 #         NAME:  who_has
595 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
596 #      RETURNS:  nothing 
597 #  DESCRIPTION:  process this incoming message
598 #===============================================================================
599 sub who_has {
600     my ($msg_hash) = @_ ;
601     my @out_msg_l;
602     
603     # what is your search pattern
604     my $search_pattern = @{$msg_hash->{who_has}}[0];
605     my $search_element = @{$msg_hash->{$search_pattern}}[0];
606     &main::daemon_log("who_has-msg looking for $search_pattern $search_element", 7);
608     # scanning known_clients for search_pattern
609     my @host_addresses = keys %$main::known_clients;
610     my $known_clients_entries = length @host_addresses;
611     my $host_address;
612     foreach my $host (@host_addresses) {
613         my $client_element = $main::known_clients->{$host}->{$search_pattern};
614         if ($search_element eq $client_element) {
615             $host_address = $host;
616             last;
617         }
618     }
619         
620     # search was successful
621     if (defined $host_address) {
622         my $source = @{$msg_hash->{source}}[0];
623         my $out_hash = &create_xml_hash("who_has_i_do", $server_address, $source, "mac_address");
624         &add_content2xml_hash($out_hash, "mac_address", $search_element);
625         my $out_msg = &create_xml_string($out_hash);
626         push(@out_msg_l, $out_msg);
627     }
628     return @out_msg_l;
632 sub who_has_i_do {
633     my ($msg_hash) = @_ ;
634     my $header = @{$msg_hash->{header}}[0];
635     my $source = @{$msg_hash->{source}}[0];
636     my $search_param = @{$msg_hash->{$header}}[0];
637     my $search_value = @{$msg_hash->{$search_param}}[0];
638     print "\ngot msg $header:\nserver $source has client with $search_param $search_value\n";
641 #===  FUNCTION  ================================================================
642 #         NAME:  new_ldap_config
643 #   PARAMETERS:  address - string - ip address and port of a host
644 #      RETURNS:  nothing
645 #  DESCRIPTION:  send to address the ldap configuration found for dn gotoLdapServer
646 #===============================================================================
647 sub new_ldap_config {
648         my ($address) = @_ ;
650         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address'";
651         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
653         # check hit
654         my $hit_counter = keys %{$res};
655         if( not $hit_counter == 1 ) {
656                 &main::daemon_log("ERROR: more or no hit found in known_clients_db by query by '$address'", 1);
657         }
659         my $macaddress = $res->{1}->{macaddress};
660         my $hostkey = $res->{1}->{hostkey};
662         if (not defined $macaddress) {
663                 &main::daemon_log("ERROR: no mac address found for client $address", 1);
664                 return;
665         }
667         # Build LDAP connection
668         my $ldap = Net::LDAP->new($ldap_uri);
669         if( not defined $ldap ) {
670                 &main::daemon_log("ERROR: cannot connect to ldap: $ldap_uri", 1);
671                 return;
672         } 
675         # Bind to a directory with dn and password
676         my $mesg= $ldap->bind($ldap_admin_dn, password => $ldap_admin_password);
678         # Perform search
679         $mesg = $ldap->search( base   => $ldap_base,
680                 scope  => 'sub',
681                 attrs => ['dn', 'gotoLdapServer', 'gosaUnitTag'],
682                 filter => "(&(objectClass=GOhard)(macaddress=$macaddress))");
683         #$mesg->code && die $mesg->error;
684         if($mesg->code) {
685                 &main::daemon_log($mesg->error, 1);
686                 return;
687         }
689         # Sanity check
690         if ($mesg->count != 1) {
691                 &main::daemon_log("WARNING: client mac address $macaddress not found/not unique in ldap search", 1);
692                 &main::daemon_log("\tbase: $ldap_base", 1);
693                 &main::daemon_log("\tscope: sub", 1);
694                 &main::daemon_log("\tattrs: dn, gotoLdapServer", 1);
695                 &main::daemon_log("\tfilter: (&(objectClass=GOhard)(macaddress=$macaddress))", 1);
696                 return;
697         }
699         my $entry= $mesg->entry(0);
700         my $dn= $entry->dn;
701         my @servers= $entry->get_value("gotoLdapServer");
702         my $unit_tag= $entry->get_value("gosaUnitTag");
703         my @ldap_uris;
704         my $server;
705         my $base;
707         # Do we need to look at an object class?
708         if (length(@servers) < 1){
709                 $mesg = $ldap->search( base   => $ldap_base,
710                         scope  => 'sub',
711                         attrs => ['dn', 'gotoLdapServer'],
712                         filter => "(&(objectClass=gosaGroupOfNames)(member=$dn))");
713                 #$mesg->code && die $mesg->error;
714                 if($mesg->code) {
715                         &main::daemon_log($mesg->error, 1);
716                         return;
717                 }
719                 # Sanity check
720                 if ($mesg->count != 1) {
721                         &main::daemon_log("WARNING: no LDAP information found for client mac $macaddress", 1);
722                         return;
723                 }
725                 $entry= $mesg->entry(0);
726                 $dn= $entry->dn;
727                 @servers= $entry->get_value("gotoLdapServer");
728         }
730         @servers= sort (@servers);
732         foreach $server (@servers){
733                 # Conversation for backward compatibility
734                 if ($server !=~ /^ldap[^:]+:\/\// ) {
735                         if ($server =~ /^([^:]+):(.*)$/ ) {
736                                 $server= "1:dummy:ldap://$1/$2";
737                         }
738                 }
740                 $base= $server;
741                 $server =~ s%^[^:]+:[^:]+:(ldap.*://[^/]+)/.*$%$1%;
742                 $base =~ s%^[^:]+:[^:]+:ldap.*://[^/]+/(.*)$%$1%;
743                 push (@ldap_uris, $server);
744         }
746         # Assemble data package
747         my %data = ( 'ldap_uri'  => \@ldap_uris, 'ldap_base' => $base,
748                 'ldap_cfg' => \@ldap_cfg, 'pam_cfg' => \@pam_cfg,'nss_cfg' => \@nss_cfg );
750         # Need to append GOto settings?
751         if (defined $goto_admin and defined $goto_secret){
752                 $data{'goto_admin'}= $goto_admin;
753                 $data{'goto_secret'}= $goto_secret;
754         }
756         # Append unit tag if needed
757         if (defined $unit_tag){
759                 # Find admin base and department name
760                 $mesg = $ldap->search( base   => $ldap_base,
761                         scope  => 'sub',
762                         attrs => ['dn', 'ou', 'FAIclass'],
763                         filter => "(&(objectClass=gosaAdministrativeUnit)(gosaUnitTag=$unit_tag))");
764                 #$mesg->code && die $mesg->error;
765                 if($mesg->code) {
766                         &main::daemon_log($mesg->error, 1);
767                         return;
768                 }
770                 # Sanity check
771                 if ($mesg->count != 1) {
772                         &main::daemon_log("WARNING: cannot find administrative unit for client with tag $unit_tag", 1);
773                         return;
774                 }
776                 $entry= $mesg->entry(0);
777                 $data{'admin_base'}= $entry->dn;
778                 $data{'department'}= $entry->get_value("ou");
780                 # Append unit Tag
781                 $data{'unit_tag'}= $unit_tag;
782         }
784         # Fill release if available
785         my $FAIclass= $entry->get_value("FAIclass");
786         if (defined $FAIclass && $FAIclass =~ /^.* :([A-Za-z0-9\/.]+).*$/) {
787                 $data{'release'}= $1;
788         }
791         # Unbind
792         $mesg = $ldap->unbind;
794         # Send information
795         return send_msg("new_ldap_config", $server_address, $address, \%data);
798 sub process_detected_hardware {
799         my $msg_hash = shift;
800         my $address = $msg_hash->{source}[0];
801         my $gotoHardwareChecksum= $msg_hash->{detected_hardware}[0]->{gotoHardwareChecksum};
803     my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address'";
804     my $res = $main::known_clients_db->select_dbentry( $sql_statement );
806     # check hit
807     my $hit_counter = keys %{$res};
808     if( not $hit_counter == 1 ) {
809         &main::daemon_log("ERROR: more or no hit found in known_clients_db by query by '$address'", 1);
810                 return;
811     }
813     my $macaddress = $res->{1}->{macaddress};
814     my $hostkey = $res->{1}->{hostkey};
816     if (not defined $macaddress) {
817         &main::daemon_log("ERROR: no mac address found for client $address", 1);
818         return;
819     }
820     # Build LDAP connection
821     my $ldap = Net::LDAP->new($ldap_uri);
822     if( not defined $ldap ) {
823         &main::daemon_log("ERROR: cannot connect to ldap: $ldap_uri", 1);
824         return;
825     } 
827     # Bind to a directory with dn and password
828     my $mesg= $ldap->bind($ldap_admin_dn, password => $ldap_admin_password);
830     # Perform search
831         $mesg = $ldap->search(
832                 base   => $ldap_base,
833                 scope  => 'sub',
834                 filter => "(&(objectClass=GOhard)(|(macAddress=$macaddress)(dhcpHWaddress=ethernet $macaddress)))"
835         );
837         # We need to create a base entry first (if not done from ArpHandler)
838         if($mesg->count == 0) {
839                 &main::daemon_log("Need to create a new LDAP Entry for client $address", 1);
840                 my $resolver=Net::DNS::Resolver->new;
841                 my $ipaddress= $1 if $address =~ /^([0-9\.]*?):.*$/;
842                 my $dnsresult= $resolver->search($ipaddress);
843                 my $dnsname= (defined($dnsresult))?$dnsresult->{answer}[0]->{ptrdname}:$ipaddress;
844                 my $cn = (($dnsname =~ /^(\d){1,3}\.(\d){1,3}\.(\d){1,3}\.(\d){1,3}/) ? $dnsname : sprintf "%s", $dnsname =~ /([^\.]+)\.?/);
845                 my $dn = "cn=$cn,ou=incoming,$ldap_base";
846                 &main::daemon_log("Creating entry for $dn",6);
847                 my $entry= Net::LDAP::Entry->new( $dn );
848                 $entry->dn($dn);
849                 $entry->add("objectClass" => "goHard");
850                 $entry->add("cn" => $cn);
851                 $entry->add("macAddress" => $macaddress);
852                 $entry->add("gotomode" => "locked");
853                 $entry->add("gotoSysStatus" => "new-system");
854                 $entry->add("ipHostNumber" => $ipaddress);
855                 if(defined($gosa_unit_tag) && length($gosa_unit_tag) > 0) {
856                         $entry->add("objectClass" => "gosaAdministrativeUnit");
857                         $entry->add("gosaUnitTag" => $gosa_unit_tag);
858                 }
859                 if(my $res=$entry->update($ldap)) {
860                         # Fill $mesg again
861                         $mesg = $ldap->search(
862                                 base   => $ldap_base,
863                                 scope  => 'sub',
864                                 filter => "(&(objectClass=GOhard)(|(macAddress=$macaddress)(dhcpHWaddress=ethernet $macaddress)))"
865                         );
866                 } else {
867                         &main::daemon_log("ERROR: There was a problem adding the entry", 1);
868                 }
870         }
871         
872         if($mesg->count == 1) {
873                 my $entry= $mesg->entry(0);
874                 $entry->changetype("modify");
875                 foreach my $attribute (
876                         "gotoSndModule", "ghNetNic", "gotoXResolution", "ghSoundAdapter", "ghCpuType", "gotoXkbModel", 
877                         "ghGfxAdapter", "gotoXMousePort", "ghMemSize", "gotoXMouseType", "ghUsbSupport", "gotoXHsync", 
878                         "gotoXDriver", "gotoXVsync", "gotoXMonitor", "gotoHardwareChecksum") {
879                         if(defined($msg_hash->{detected_hardware}[0]->{$attribute})) {
880                                 if(defined($entry->get_value($attribute))) {
881                                         $entry->delete($attribute);
882                                 }
883                                 &main::daemon_log("Adding attribute $attribute with value ".$msg_hash->{detected_hardware}[0]->{$attribute},1);
884                                 $entry->add($attribute => $msg_hash->{detected_hardware}[0]->{$attribute});     
885                         }
886                 }
887                 foreach my $attribute (
888                         "gotoModules", "ghScsiDev", "ghIdeDev") {
889                         if(defined($msg_hash->{detected_hardware}[0]->{$attribute})) {
890                                 if(defined($entry->get_value($attribute))) {
891                                         $entry->delete($attribute);
892                                 }
893                                 foreach my $array_entry (@{$msg_hash->{detected_hardware}[0]->{$attribute}}) {
894                                         $entry->add($attribute => $array_entry);
895                                 }
896                         }
898                 }
900                 if($entry->update($ldap)) {
901                         &main::daemon_log("Added Hardware configuration to LDAP", 4);
902                 }
904         }
905         return;
907 #===  FUNCTION  ================================================================
908 #         NAME:  hardware_config
909 #   PARAMETERS:  address - string - ip address and port of a host
910 #      RETURNS:  
911 #  DESCRIPTION:  
912 #===============================================================================
913 sub hardware_config {
914         my ($address, $gotoHardwareChecksum) = @_ ;
916         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address'";
917         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
919         # check hit
920         my $hit_counter = keys %{$res};
921         if( not $hit_counter == 1 ) {
922                 &main::daemon_log("ERROR: more or no hit found in known_clients_db by query by '$address'", 1);
923         }
925         my $macaddress = $res->{1}->{macaddress};
926         my $hostkey = $res->{1}->{hostkey};
928         if (not defined $macaddress) {
929                 &main::daemon_log("ERROR: no mac address found for client $address", 1);
930                 return;
931         }
933         # Build LDAP connection
934         my $ldap = Net::LDAP->new($ldap_uri);
935         if( not defined $ldap ) {
936                 &main::daemon_log("ERROR: cannot connect to ldap: $ldap_uri", 1);
937                 return;
938         } 
940         # Bind to a directory with dn and password
941         my $mesg= $ldap->bind($ldap_admin_dn, password => $ldap_admin_password);
943         # Perform search
944         $mesg = $ldap->search(
945                 base   => $ldap_base,
946                 scope  => 'sub',
947                 filter => "(&(objectClass=GOhard)(|(macAddress=$macaddress)(dhcpHWaddress=ethernet $macaddress)))"
948         );
950         if($mesg->count() == 0) {
951                 &main::daemon_log("Host was not found in LDAP!", 1);
952         } else {
953                 my $entry= $mesg->entry(0);
954                 my $dn= $entry->dn;
955                 if(defined($entry->get_value("gotoHardwareChecksum"))) {
956                         if(! $entry->get_value("gotoHardwareChecksum") eq $gotoHardwareChecksum) {
957                                 $entry->replace(gotoHardwareChecksum => $gotoHardwareChecksum);
958                                 if($entry->update($ldap)) {
959                                         &main::daemon_log("Hardware changed! Detection triggered.", 4);
960                                 }
961                         } else {
962                                 # Nothing to do
963                                 return;
964                         }
965                 }
966         } 
967         # need to fill it to LDAP
968         #$entry->add(gotoHardwareChecksum => $gotoHardwareChecksum);
969         #if($entry->update($ldap)) {
970         #               &main::daemon_log("gotoHardwareChecksum $gotoHardwareChecksum was added to LDAP", 4);
971         #}
973         ## Look if there another host with this checksum to use the hardware config
974         #$mesg = $ldap->search(
975         #       base   => $ldap_base,
976         #       scope  => 'sub',
977         #       filter => "(&(objectClass=GOhard)(gotoHardwareChecksum=$gotoHardwareChecksum))"
978         #);
980         #if($mesg->count>1) {
981         #       my $clone_entry= $mesg->entry(0);
982         #       $entry->changetype("modify");
983         #       foreach my $attribute (
984         #               "gotoSndModule", "ghNetNic", "gotoXResolution", "ghSoundAdapter", "ghCpuType", "gotoXkbModel", 
985         #               "ghGfxAdapter", "gotoXMousePort", "ghMemSize", "gotoXMouseType", "ghUsbSupport", "gotoXHsync", 
986         #               "gotoXDriver", "gotoXVsync", "gotoXMonitor") {
987         #               my $value= $clone_entry->get_value($attribute);
988         #               if(defined($value)) {
989         #                       if(defined($entry->get_value($attribute))) {
990         #                               $entry->delete($attribute);
991         #                       }
992         #                       &main::daemon_log("Adding attribute $attribute with value $value",1);
993         #                       $entry->add($attribute => $value);
994         #               }
995         #       }
996         #       foreach my $attribute (
997         #               "gotoModules", "ghScsiDev", "ghIdeDev") {
998         #               my $array= $clone_entry->get_value($attribute, 'as_ref' => 1);
999         #               if(defined($array))     {
1000         #                       if(defined($entry->get_value($attribute))) {
1001         #                               $entry->delete($attribute);
1002         #                       }
1003         #                       foreach my $array_entry (@{$array}) {
1004         #                               $entry->add($attribute => $array_entry);
1005         #                       }
1006         #               }
1008         #       }
1009         #       if($entry->update($ldap)) {
1010         #               &main::daemon_log("Added Hardware configuration to LDAP", 4);
1011         #       }
1013         #}
1016         # Assemble data package
1017         my %data = ();
1019         # Need to append GOto settings?
1020         if (defined $goto_admin and defined $goto_secret){
1021                 $data{'goto_admin'}= $goto_admin;
1022                 $data{'goto_secret'}= $goto_secret;
1023         }
1025         # Unbind
1026         $mesg = $ldap->unbind;
1028         &main::daemon_log("Send detect_hardware message to $address", 4);
1030         # Send information
1031         return send_msg("detect_hardware", $server_address, $address, \%data);
1034 sub server_matches {
1035         my $target = shift;
1036         my $target_ip = sprintf("%s", $target =~ /^([0-9\.]*?):.*$/);
1037         my $result = 0;
1039         if($server_ip eq $target_ip) {
1040                 $result= 1;
1041         } elsif ($server_ip eq "0.0.0.0") {     
1042                 if ($target_ip eq "127.0.0.1") {
1043                         $result= 1;
1044                 } else {
1045                         my $PROC_NET_ROUTE= ('/proc/net/route');
1047                         open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
1048                                 or die "Could not open $PROC_NET_ROUTE";
1050                         my @ifs = <PROC_NET_ROUTE>;
1052                         close(PROC_NET_ROUTE);
1054                         # Eat header line
1055                         shift @ifs;
1056                         chomp @ifs;
1057                         foreach my $line(@ifs) {
1058                                 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
1059                                 my $destination;
1060                                 my $mask;
1061                                 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
1062                                 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
1063                                 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
1064                                 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
1065                                 if(new NetAddr::IP($target_ip)->within(new NetAddr::IP($destination, $mask))) {
1066                                         # destination matches route, save mac and exit
1067                                         $result= 1;
1068                                         last;
1069                                 }
1070                         }
1071                 }
1072         } else {
1073                 &main::daemon_log("Target ip $target_ip does not match Server ip $server_ip",1);
1074         }
1076         return $result;
1080 #===  FUNCTION  ================================================================
1081 #         NAME:  execute_actions
1082 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
1083 #      RETURNS:  nothing
1084 #  DESCRIPTION:  invokes the script specified in msg_hash which is located under
1085 #                /etc/gosad/actions
1086 #===============================================================================
1087 sub execute_actions {
1088     my ($msg_hash) = @_ ;
1089     my $configdir= '/etc/gosad/actions/';
1090     my $result;
1092     my $header = @{$msg_hash->{header}}[0];
1093     my $source = @{$msg_hash->{source}}[0];
1094     my $target = @{$msg_hash->{target}}[0];
1095  
1096     if((not defined $source)
1097             && (not defined $target)
1098             && (not defined $header)) {
1099         &main::daemon_log("ERROR: Entries missing in XML msg for gosad actions under /etc/gosad/actions");
1100     } else {
1101         my $parameters="";
1102         my @params = @{$msg_hash->{$header}};
1103         my $params = join(", ", @params);
1104         &main::daemon_log("execute_actions: got parameters: $params", 5);
1106         if (@params) {
1107             foreach my $param (@params) {
1108                 my $param_value = (&get_content_from_xml_hash($msg_hash, $param))[0];
1109                 &main::daemon_log("execute_actions: parameter -> value: $param -> $param_value", 7);
1110                 $parameters.= " ".$param_value;
1111             }
1112         }
1114         my $cmd= $configdir.$header."$parameters";
1115         &main::daemon_log("execute_actions: executing cmd: $cmd", 7);
1116         $result= "";
1117         open(PIPE, "$cmd 2>&1 |");
1118         while(<PIPE>) {
1119             $result.=$_;
1120         }
1121         close(PIPE);
1122     }
1124     # process the event result
1127     return;
1131 1;