Code

6c44e134aa7c6ae02913d1447a5c374528c37f92
[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 Net::LDAP;
16 use Socket;
17 use Net::hostent;
19 BEGIN{}
20 END {}
22 my ($known_clients_file_name);
23 my ($server_activ, $server_ip, $server_mac_address, $server_port, $SIPackages_key, $max_clients, $ldap_uri, $ldap_base, $ldap_admin_dn, $ldap_admin_password);
24 my ($bus_activ, $bus_passwd, $bus_ip, $bus_port);
25 my $server;
26 my $network_interface;
27 my $no_bus;
28 my (@ldap_cfg, @pam_cfg, @nss_cfg, $goto_admin, $goto_secret);
31 my %cfg_defaults =
32 (
33 "server" =>
34     {"server_activ" => [\$server_activ, "on"],
35     "server_ip" => [\$server_ip, "0.0.0.0"],
36     "server_mac_address" => [\$server_mac_address, ""],
37     "server_port" => [\$server_port, "20081"],
38     "SIPackages_key" => [\$SIPackages_key, ""],
39     "max_clients" => [\$max_clients, 100],
40     "ldap_uri" => [\$ldap_uri, ""],
41     "ldap_base" => [\$ldap_base, ""],
42     "ldap_admin_dn" => [\$ldap_admin_dn, ""],
43     "ldap_admin_password" => [\$ldap_admin_password, ""],
44     },
45 "bus" =>
46     {"bus_activ" => [\$bus_activ, "on"],
47     "bus_passwd" => [\$bus_passwd, ""],
48     "bus_ip" => [\$bus_ip, ""],
49     "bus_port" => [\$bus_port, "20080"],
50     },
51 );
53 ### START #####################################################################
55 # read configfile and import variables
56 &read_configfile();
58 # detect interfaces and mac address
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 my $bus_address = "$bus_ip:$bus_port";
69 # create general settings for this module
70 my $xml = new XML::Simple();
72 # register at bus
73 if ($main::no_bus > 0) {
74     $bus_activ = "off"
75 }
76 if($bus_activ eq "on") {
77     &register_at_bus();
78 }
80 # add myself to known_server_db
81 my $res = $main::known_server_db->add_dbentry( {table=>'known_server',
82         primkey=>'hostname',
83         hostname=>$server_address,
84         status=>'myself',
85         hostkey=>$SIPackages_key,
86         timestamp=>&get_time,
87         } );
91 ### functions #################################################################
94 sub get_module_info {
95     my @info = ($server_address,
96                 $SIPackages_key,
97                 $server,
98                 $server_activ,
99                 "socket",
100                 );
101     return \@info;
106 sub do_wake {
107         my $host    = shift;
108         my $ipaddr  = shift || '255.255.255.255';
109         my $port    = getservbyname('discard', 'udp');
111         my ($raddr, $them, $proto);
112         my ($hwaddr, $hwaddr_re, $pkt);
114         # get the hardware address (ethernet address)
116         $hwaddr_re = join(':', ('[0-9A-Fa-f]{1,2}') x 6);
117         if ($host =~ m/^$hwaddr_re$/) {
118                 $hwaddr = $host;
119         } else {
120                 # $host is not a hardware address, try to resolve it
121                 my $ip_re = join('\.', ('([0-9]|[1-9][0-9]|1[0-9]{2}|2([0-4][0-9]|5[0-5]))') x 4);
122                 my $ip_addr;
123                 if ($host =~ m/^$ip_re$/) {
124                         $ip_addr = $host;
125                 } else {
126                         my $h;
127                         unless ($h = gethost($host)) {
128                                 return undef;
129                         }
130                         $ip_addr = inet_ntoa($h->addr);
131                 }
132         }
134         # Generate magic sequence
135         foreach (split /:/, $hwaddr) {
136                 $pkt .= chr(hex($_));
137         }
138         $pkt = chr(0xFF) x 6 . $pkt x 16;
140         # Allocate socket and send packet
142         $raddr = gethostbyname($ipaddr)->addr;
143         $them = pack_sockaddr_in($port, $raddr);
144         $proto = getprotobyname('udp');
146         socket(S, AF_INET, SOCK_DGRAM, $proto) or die "socket : $!";
147         setsockopt(S, SOL_SOCKET, SO_BROADCAST, 1) or die "setsockopt : $!";
149         send(S, $pkt, 0, $them) or die "send : $!";
150         close S;
154 #===  FUNCTION  ================================================================
155 #         NAME:  read_configfile
156 #   PARAMETERS:  cfg_file - string -
157 #      RETURNS:  nothing
158 #  DESCRIPTION:  read cfg_file and set variables
159 #===============================================================================
160 sub read_configfile {
161     my $cfg;
162     if( defined( $main::cfg_file) && ( length($main::cfg_file) > 0 )) {
163         if( -r $main::cfg_file ) {
164             $cfg = Config::IniFiles->new( -file => $main::cfg_file );
165         } else {
166             print STDERR "Couldn't read config file!";
167         }
168     } else {
169         $cfg = Config::IniFiles->new() ;
170     }
171     foreach my $section (keys %cfg_defaults) {
172         foreach my $param (keys %{$cfg_defaults{ $section }}) {
173             my $pinfo = $cfg_defaults{ $section }{ $param };
174             ${@$pinfo[0]} = $cfg->val( $section, $param, @$pinfo[1] );
175         }
176     }
178     # Read non predefined sections
179     my $param;
180     if ($cfg->SectionExists('ldap')){
181                 foreach $param ($cfg->Parameters('ldap')){
182                         push (@ldap_cfg, "$param ".$cfg->val('ldap', $param));
183                 }
184     }
185     if ($cfg->SectionExists('pam_ldap')){
186                 foreach $param ($cfg->Parameters('pam_ldap')){
187                         push (@pam_cfg, "$param ".$cfg->val('pam_ldap', $param));
188                 }
189     }
190     if ($cfg->SectionExists('nss_ldap')){
191                 foreach $param ($cfg->Parameters('nss_ldap')){
192                         push (@nss_cfg, "$param ".$cfg->val('nss_ldap', $param));
193                 }
194     }
195     if ($cfg->SectionExists('goto')){
196         $goto_admin= $cfg->val('goto', 'terminal_admin');
197         $goto_secret= $cfg->val('goto', 'terminal_secret');
198     } else {
199         $goto_admin= undef;
200         $goto_secret= undef;
201     }
205 #===  FUNCTION  ================================================================
206 #         NAME:  get_interface_for_ip
207 #   PARAMETERS:  ip address (i.e. 192.168.0.1)
208 #      RETURNS:  array: list of interfaces if ip=0.0.0.0, matching interface if found, undef else
209 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
210 #===============================================================================
211 sub get_interface_for_ip {
212         my $result;
213         my $ip= shift;
214         if ($ip && length($ip) > 0) {
215                 my @ifs= &get_interfaces();
216                 if($ip eq "0.0.0.0") {
217                         $result = "all";
218                 } else {
219                         foreach (@ifs) {
220                                 my $if=$_;
221                                 if(get_ip($if) eq $ip) {
222                                         $result = $if;
223                                 }
224                         }       
225                 }
226         }       
227         return $result;
230 #===  FUNCTION  ================================================================
231 #         NAME:  get_interfaces 
232 #   PARAMETERS:  none
233 #      RETURNS:  (list of interfaces) 
234 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
235 #===============================================================================
236 sub get_interfaces {
237         my @result;
238         my $PROC_NET_DEV= ('/proc/net/dev');
240         open(PROC_NET_DEV, "<$PROC_NET_DEV")
241                 or die "Could not open $PROC_NET_DEV";
243         my @ifs = <PROC_NET_DEV>;
245         close(PROC_NET_DEV);
247         # Eat first two line
248         shift @ifs;
249         shift @ifs;
251         chomp @ifs;
252         foreach my $line(@ifs) {
253                 my $if= (split /:/, $line)[0];
254                 $if =~ s/^\s+//;
255                 push @result, $if;
256         }
258         return @result;
261 #===  FUNCTION  ================================================================
262 #         NAME:  get_mac 
263 #   PARAMETERS:  interface name (i.e. eth0)
264 #      RETURNS:  (mac address) 
265 #  DESCRIPTION:  Uses ioctl to get mac address directly from system.
266 #===============================================================================
267 sub get_mac {
268         my $ifreq= shift;
269         my $result;
270         if ($ifreq && length($ifreq) > 0) { 
271                 if($ifreq eq "all") {
272                         $result = "00:00:00:00:00:00";
273                 } else {
274                         my $SIOCGIFHWADDR= 0x8927;     # man 2 ioctl_list
276                         # A configured MAC Address should always override a guessed value
277                         if ($server_mac_address and length($server_mac_address) > 0) {
278                                 $result= $server_mac_address;
279                         }
281                         socket SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('ip')
282                                 or die "socket: $!";
284                         if(ioctl SOCKET, $SIOCGIFHWADDR, $ifreq) {
285                                 my ($if, $mac)= unpack 'h36 H12', $ifreq;
287                                 if (length($mac) > 0) {
288                                         $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])$/;
289                                         $mac= sprintf("%s:%s:%s:%s:%s:%s", $1, $2, $3, $4, $5, $6);
290                                         $result = $mac;
291                                 }
292                         }
293                 }
294         }
295         return $result;
298 #===  FUNCTION  ================================================================
299 #         NAME:  get_ip 
300 #   PARAMETERS:  interface name (i.e. eth0)
301 #      RETURNS:  (ip address) 
302 #  DESCRIPTION:  Uses ioctl to get ip address directly from system.
303 #===============================================================================
304 sub get_ip {
305         my $ifreq= shift;
306         my $result= "";
307         my $SIOCGIFADDR= 0x8915;       # man 2 ioctl_list
308         my $proto= getprotobyname('ip');
310         socket SOCKET, PF_INET, SOCK_DGRAM, $proto
311                 or die "socket: $!";
313         if(ioctl SOCKET, $SIOCGIFADDR, $ifreq) {
314                 my ($if, $sin)    = unpack 'a16 a16', $ifreq;
315                 my ($port, $addr) = sockaddr_in $sin;
316                 my $ip            = inet_ntoa $addr;
318                 if ($ip && length($ip) > 0) {
319                         $result = $ip;
320                 }
321         }
323         return $result;
327 #===  FUNCTION  ================================================================
328 #         NAME:  register_at_bus
329 #   PARAMETERS:  nothing
330 #      RETURNS:  nothing
331 #  DESCRIPTION:  creates an entry in known_daemons and send a 'here_i_am' msg to bus
332 #===============================================================================
333 sub register_at_bus {
335     # add bus to known_server_db
336     my $res = $main::known_server_db->add_dbentry( {table=>'known_server',
337                                                     primkey=>'hostname',
338                                                     hostname=>$bus_address,
339                                                     status=>'bus',
340                                                     hostkey=>$bus_passwd,
341                                                     timestamp=>&get_time,
342                                                 } );
343     my $msg_hash = &create_xml_hash("here_i_am", $server_address, $bus_address);
344     my $msg = &create_xml_string($msg_hash);
345     return $msg;
346 #    my $answer = "";
347 #    $answer = &send_msg_hash2address($msg_hash, $bus_address, $bus_passwd);
348 #    if ($answer == 0) {
349 #        &main::daemon_log("register at bus: $bus_address", 1);
350 #    } else {
351 #        &main::daemon_log("unable to send 'register'-msg to bus '$bus_address': $answer", 1);
352 #    }
353 #    return;
357 #===  FUNCTION  ================================================================
358 #         NAME:  process_incoming_msg
359 #   PARAMETERS:  crypted_msg - string - incoming crypted message
360 #      RETURNS:  nothing
361 #  DESCRIPTION:  handels the proceeded distribution to the appropriated functions
362 #===============================================================================
363 sub process_incoming_msg {
364     my ($msg, $msg_hash, $remote_ip) = @_ ;
365     my $error = 0;
366     my $host_name;
367     my $host_key;
368     my @out_msg_l;
370     # process incoming msg
371     my $header = @{$msg_hash->{header}}[0]; 
372     my @target_l = @{$msg_hash->{target}};
374     &main::daemon_log("SIPackages: msg to process: $header", 3);
375     &main::daemon_log("$msg", 8);
377     if( 0 == length @target_l){     
378         &main::daemon_log("ERROR: no target specified for msg $header", 1);
379         $error++;
380     }
382     if( 1 == length @target_l) {
383         my $target = $target_l[0];
384         if( $target eq $server_address ) {  
385             if ($header eq 'new_key') {
386                 @out_msg_l = &new_key($msg_hash)
387             } elsif ($header eq 'here_i_am') {
388                 @out_msg_l = &here_i_am($msg_hash)
389             } elsif ($header eq 'who_has') {
390                 @out_msg_l = &who_has($msg_hash)
391             } elsif ($header eq 'who_has_i_do') {
392                 @out_msg_l = &who_has_i_do($msg_hash)
393             } elsif ($header eq 'got_ping') {
394                 @out_msg_l = &got_ping($msg_hash)
395             } elsif ($header eq 'get_load') {
396                 @out_msg_l = &execute_actions($msg_hash)
397             } elsif ($header eq 'detected_hardware') {
398                 @out_msg_l = &process_detected_hardware($msg_hash)
399             } elsif ($header eq 'trigger_wake') {
400                 foreach (@{$msg_hash->{macAddress}}){
401                     &main::daemon_log("SIPackages: trigger wake for $_", 1);
402                     do_wake($_);
403                 }
405             } else {
406                 &main::daemon_log("ERROR: $header is an unknown core function", 1);
407                 $error++;
408             }
409         }
410                 else {
411                         &main::daemon_log("msg is not for gosa-si-server '$server_address', deliver it to target '$target'", 5);
412                         push(@out_msg_l, $msg);
413                 }
414     }
416     if( $error == 0) {
417         if( 0 == @out_msg_l ) {
418                         push(@out_msg_l, $msg);
419         }
420     }
421     
422     return \@out_msg_l;
426 #===  FUNCTION  ================================================================
427 #         NAME:  got_ping
428 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
429 #      RETURNS:  nothing
430 #  DESCRIPTION:  process this incoming message
431 #===============================================================================
432 sub got_ping {
433     my ($msg_hash) = @_;
434     
435     my $source = @{$msg_hash->{source}}[0];
436     my $target = @{$msg_hash->{target}}[0];
437     my $header = @{$msg_hash->{header}}[0];
438     
439     if(exists $main::known_daemons->{$source}) {
440         &main::add_content2known_daemons(hostname=>$source, status=>$header);
441     } else {
442         &main::add_content2known_clients(hostname=>$source, status=>$header);
443     }
444     
445     return;
449 #===  FUNCTION  ================================================================
450 #         NAME:  new_passwd
451 #   PARAMETERS:  msg_hash - ref - hash from function create_xml_hash
452 #      RETURNS:  nothing
453 #  DESCRIPTION:  process this incoming message
454 #===============================================================================
455 sub new_key {
456     my ($msg_hash) = @_;
457     my @out_msg_l;
458     
459     my $header = @{$msg_hash->{header}}[0];
460     my $source_name = @{$msg_hash->{source}}[0];
461     my $source_key = @{$msg_hash->{new_key}}[0];
462     my $query_res;
464     # check known_clients_db
465     my $sql_statement = "SELECT * FROM known_clients WHERE hostname='$source_name'";
466     $query_res = $main::known_clients_db->select_dbentry( $sql_statement );
467     if( 1 == keys %{$query_res} ) {
468         my $act_time = &get_time;
469         my $sql_statement= "UPDATE known_clients ".
470             "SET hostkey='$source_key', timestamp='$act_time' ".
471             "WHERE hostname='$source_name'";
472         my $res = $main::known_clients_db->update_dbentry( $sql_statement );
474         my $hash = &create_xml_hash("confirm_new_passwd", $server_address, $source_name);
475         my $out_msg = &create_xml_string($hash);
476         push(@out_msg_l, $out_msg);
477     }
479     # only do if host still not found
480     if( 0 == @out_msg_l ) {
481         # check known_server_db
482         $sql_statement = "SELECT * FROM known_server WHERE hostname='$source_name'";
483         $query_res = $main::known_server_db->select_dbentry( $sql_statement );
484         if( 1 == keys %{$query_res} ) {
485             my $act_time = &get_time;
486             my $sql_statement= "UPDATE known_server ".
487                 "SET hostkey='$source_key', timestamp='$act_time' ".
488                 "WHERE hostname='$source_name'";
489             my $res = $main::known_server_db->update_dbentry( $sql_statement );
491             my $hash = &create_xml_hash("confirm_new_passwd", $server_address, $source_name);
492             my $out_msg = &create_xml_string($hash);
493             push(@out_msg_l, $out_msg);
494         }
495     }
497     return @out_msg_l;
501 #===  FUNCTION  ================================================================
502 #         NAME:  here_i_am
503 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
504 #      RETURNS:  nothing
505 #  DESCRIPTION:  process this incoming message
506 #===============================================================================
507 sub here_i_am {
508     my ($msg_hash) = @_;
509     my @out_msg_l;
510     my $out_hash;
512     my $source = @{$msg_hash->{source}}[0];
513     my $mac_address = @{$msg_hash->{mac_address}}[0];
514         my $gotoHardwareChecksum = @{$msg_hash->{gotoHardwareChecksum}}[0];
516     # number of known clients
517     my $nu_clients= $main::known_clients_db->count_dbentries('known_clients');
519     # check wether client address or mac address is already known
520     my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$source'";
521     my $db_res= $main::known_clients_db->select_dbentry( $sql_statement );
522     
523     if ( 1 == keys %{$db_res} ) {
524         &main::daemon_log("WARNING: $source is already known as a client", 1);
525         &main::daemon_log("WARNING: values for $source are being overwritten", 1);   
526         $nu_clients --;
527     }
529     # number of actual activ clients
530     my $act_nu_clients = $nu_clients;
532     &main::daemon_log("number of actual activ clients: $act_nu_clients", 5);
533     &main::daemon_log("number of maximal allowed clients: $max_clients", 5);
535     if($max_clients <= $act_nu_clients) {
536         my $out_hash = &create_xml_hash("denied", $server_address, $source);
537         &add_content2xml_hash($out_hash, "denied", "I_cannot_take_any_more_clients!");
538         my $passwd = @{$msg_hash->{new_passwd}}[0]; 
539         &send_msg_hash2address($out_hash, $source, $passwd);
540         return;
541     }
542     
543     # new client accepted
544     my $new_passwd = @{$msg_hash->{new_passwd}}[0];
546     # create entry in known_clients
547     my $events = @{$msg_hash->{events}}[0];
548     
550     # add entry to known_clients_db
551     my $res = $main::known_clients_db->add_dbentry( {table=>'known_clients', 
552                                                 primkey=>'hostname',
553                                                 hostname=>$source,
554                                                 events=>$events,
555                                                 macaddress=>$mac_address,
556                                                 status=>'registered',
557                                                 hostkey=>$new_passwd,
558                                                 timestamp=>&get_time,
559                                                 } );
561     if ($res != 0)  {
562         &main::daemon_log("ERROR: cannot add entry to known_clients: $res");
563         return;
564     }
565     
566     # return acknowledgement to client
567     $out_hash = &create_xml_hash("registered", $server_address, $source);
568     my $register_out = &create_xml_string($out_hash);
569     push(@out_msg_l, $register_out);
571     # notify registered client to bus
572     if( $bus_activ eq "on") {
573         # fetch actual bus key
574         my $sql_statement= "SELECT * FROM known_server WHERE status='bus'";
575         my $query_res = $main::known_server_db->select_dbentry( $sql_statement );
576         my $hostkey = $query_res->{1}->{'hostkey'};
578         # send update msg to bus
579         $out_hash = &create_xml_hash("new_client", $server_address, $bus_address, $source);
580         my $new_client_out = &create_xml_string($out_hash);
581         push(@out_msg_l, $new_client_out);
582         &main::daemon_log("send bus msg that client '$source' has registerd at server '$server_address'", 3);
583     }
585     # give the new client his ldap config
586     my $new_ldap_config_out = &new_ldap_config($source);
587     if( $new_ldap_config_out ) {
588         push(@out_msg_l, $new_ldap_config_out);
589     }
591         my $hardware_config_out = &hardware_config($source, $gotoHardwareChecksum);
592         if( $hardware_config_out ) {
593                 push(@out_msg_l, $hardware_config_out);
594         }
596     return @out_msg_l;
600 #===  FUNCTION  ================================================================
601 #         NAME:  who_has
602 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
603 #      RETURNS:  nothing 
604 #  DESCRIPTION:  process this incoming message
605 #===============================================================================
606 sub who_has {
607     my ($msg_hash) = @_ ;
608     my @out_msg_l;
609     
610     # what is your search pattern
611     my $search_pattern = @{$msg_hash->{who_has}}[0];
612     my $search_element = @{$msg_hash->{$search_pattern}}[0];
613     &main::daemon_log("who_has-msg looking for $search_pattern $search_element", 7);
615     # scanning known_clients for search_pattern
616     my @host_addresses = keys %$main::known_clients;
617     my $known_clients_entries = length @host_addresses;
618     my $host_address;
619     foreach my $host (@host_addresses) {
620         my $client_element = $main::known_clients->{$host}->{$search_pattern};
621         if ($search_element eq $client_element) {
622             $host_address = $host;
623             last;
624         }
625     }
626         
627     # search was successful
628     if (defined $host_address) {
629         my $source = @{$msg_hash->{source}}[0];
630         my $out_hash = &create_xml_hash("who_has_i_do", $server_address, $source, "mac_address");
631         &add_content2xml_hash($out_hash, "mac_address", $search_element);
632         my $out_msg = &create_xml_string($out_hash);
633         push(@out_msg_l, $out_msg);
634     }
635     return @out_msg_l;
639 sub who_has_i_do {
640     my ($msg_hash) = @_ ;
641     my $header = @{$msg_hash->{header}}[0];
642     my $source = @{$msg_hash->{source}}[0];
643     my $search_param = @{$msg_hash->{$header}}[0];
644     my $search_value = @{$msg_hash->{$search_param}}[0];
645     print "\ngot msg $header:\nserver $source has client with $search_param $search_value\n";
648 #===  FUNCTION  ================================================================
649 #         NAME:  new_ldap_config
650 #   PARAMETERS:  address - string - ip address and port of a host
651 #      RETURNS:  nothing
652 #  DESCRIPTION:  send to address the ldap configuration found for dn gotoLdapServer
653 #===============================================================================
654 sub new_ldap_config {
655         my ($address) = @_ ;
657         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address'";
658         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
660         # check hit
661         my $hit_counter = keys %{$res};
662         if( not $hit_counter == 1 ) {
663                 &main::daemon_log("ERROR: more or no hit found in known_clients_db by query by '$address'", 1);
664         }
666         my $macaddress = $res->{1}->{macaddress};
667         my $hostkey = $res->{1}->{hostkey};
669         if (not defined $macaddress) {
670                 &main::daemon_log("ERROR: no mac address found for client $address", 1);
671                 return;
672         }
674         # Build LDAP connection
675         my $ldap = Net::LDAP->new($ldap_uri);
676         if( not defined $ldap ) {
677                 &main::daemon_log("ERROR: cannot connect to ldap: $ldap_uri", 1);
678                 return;
679         } 
682         # Bind to a directory with dn and password
683         my $mesg= $ldap->bind($ldap_admin_dn, password => $ldap_admin_password);
685         # Perform search
686         $mesg = $ldap->search( base   => $ldap_base,
687                 scope  => 'sub',
688                 attrs => ['dn', 'gotoLdapServer', 'gosaUnitTag'],
689                 filter => "(&(objectClass=GOhard)(macaddress=$macaddress))");
690         #$mesg->code && die $mesg->error;
691         if($mesg->code) {
692                 &main::daemon_log($mesg->error, 1);
693                 return;
694         }
696         # Sanity check
697         if ($mesg->count != 1) {
698                 &main::daemon_log("WARNING: client mac address $macaddress not found/not unique in ldap search", 1);
699                 &main::daemon_log("\tbase: $ldap_base", 1);
700                 &main::daemon_log("\tscope: sub", 1);
701                 &main::daemon_log("\tattrs: dn, gotoLdapServer", 1);
702                 &main::daemon_log("\tfilter: (&(objectClass=GOhard)(macaddress=$macaddress))", 1);
703                 return;
704         }
706         my $entry= $mesg->entry(0);
707         my $dn= $entry->dn;
708         my @servers= $entry->get_value("gotoLdapServer");
709         my $unit_tag= $entry->get_value("gosaUnitTag");
710         my @ldap_uris;
711         my $server;
712         my $base;
714         # Do we need to look at an object class?
715         if (length(@servers) < 1){
716                 $mesg = $ldap->search( base   => $ldap_base,
717                         scope  => 'sub',
718                         attrs => ['dn', 'gotoLdapServer'],
719                         filter => "(&(objectClass=gosaGroupOfNames)(member=$dn))");
720                 #$mesg->code && die $mesg->error;
721                 if($mesg->code) {
722                         &main::daemon_log($mesg->error, 1);
723                         return;
724                 }
726                 # Sanity check
727                 if ($mesg->count != 1) {
728                         &main::daemon_log("WARNING: no LDAP information found for client mac $macaddress", 1);
729                         return;
730                 }
732                 $entry= $mesg->entry(0);
733                 $dn= $entry->dn;
734                 @servers= $entry->get_value("gotoLdapServer");
735         }
737         @servers= sort (@servers);
739         foreach $server (@servers){
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'],
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         # Unbind
785         $mesg = $ldap->unbind;
787         # Send information
788         return send_msg("new_ldap_config", $server_address, $address, \%data);
791 sub process_detected_hardware {
792         my $msg_hash = shift;
793         my $address = $msg_hash->{source}[0];
795     my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address'";
796     my $res = $main::known_clients_db->select_dbentry( $sql_statement );
798     # check hit
799     my $hit_counter = keys %{$res};
800     if( not $hit_counter == 1 ) {
801         &main::daemon_log("ERROR: more or no hit found in known_clients_db by query by '$address'", 1);
802     }
804     my $macaddress = $res->{1}->{macaddress};
805     my $hostkey = $res->{1}->{hostkey};
807     if (not defined $macaddress) {
808         &main::daemon_log("ERROR: no mac address found for client $address", 1);
809         return;
810     }
811     # Build LDAP connection
812     my $ldap = Net::LDAP->new($ldap_uri);
813     if( not defined $ldap ) {
814         &main::daemon_log("ERROR: cannot connect to ldap: $ldap_uri", 1);
815         return;
816     } 
818     # Bind to a directory with dn and password
819     my $mesg= $ldap->bind($ldap_admin_dn, password => $ldap_admin_password);
821     # Perform search
822         $mesg = $ldap->search(
823                 base   => $ldap_base,
824                 scope  => 'sub',
825                 filter => "(&(objectClass=GOhard)(|(macAddress=$macaddress)(dhcpHWaddress=ethernet $macaddress)))"
826         );
828         if($mesg->count == 1) {
829                 my $entry= $mesg->entry(0);
830                 $entry->changetype("modify");
831                 foreach my $attribute (
832                         "gotoSndModule", "ghNetNic", "gotoXResolution", "ghSoundAdapter", "ghCpuType", "gotoXkbModel", 
833                         "ghGfxAdapter", "gotoXMousePort", "ghMemSize", "gotoXMouseType", "ghUsbSupport", "gotoXHsync", 
834                         "gotoXDriver", "gotoXVsync", "gotoXMonitor") {
835                         if(defined($msg_hash->{detected_hardware}[0]->{$attribute})) {
836                                 if(defined($entry->get_value($attribute))) {
837                                         $entry->delete($attribute);
838                                 }
839                                 &main::daemon_log("Adding attribute $attribute with value ".$msg_hash->{detected_hardware}[0]->{$attribute},1);
840                                 $entry->add($attribute => $msg_hash->{detected_hardware}[0]->{$attribute});     
841                         }
842                 }
843                 foreach my $attribute (
844                         "gotoModules", "ghScsiDev", "ghIdeDev") {
845                         if(defined($msg_hash->{detected_hardware}[0]->{$attribute})) {
846                                 if(defined($entry->get_value($attribute))) {
847                                         $entry->delete($attribute);
848                                 }
849                                 foreach my $array_entry (@{$msg_hash->{detected_hardware}[0]->{$attribute}}) {
850                                         $entry->add($attribute => $array_entry);
851                                 }
852                         }
854                 }
855                 if($entry->update($ldap)) {
856                         &main::daemon_log("Added Hardware configuration to LDAP", 4);
857                 }
859         }
860         return;
862 #===  FUNCTION  ================================================================
863 #         NAME:  hardware_config
864 #   PARAMETERS:  address - string - ip address and port of a host
865 #      RETURNS:  
866 #  DESCRIPTION:  
867 #===============================================================================
868 sub hardware_config {
869         my ($address, $gotoHardwareChecksum) = @_ ;
871         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address'";
872         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
874         # check hit
875         my $hit_counter = keys %{$res};
876         if( not $hit_counter == 1 ) {
877                 &main::daemon_log("ERROR: more or no hit found in known_clients_db by query by '$address'", 1);
878         }
880         my $macaddress = $res->{1}->{macaddress};
881         my $hostkey = $res->{1}->{hostkey};
883         if (not defined $macaddress) {
884                 &main::daemon_log("ERROR: no mac address found for client $address", 1);
885                 return;
886         }
888         # Build LDAP connection
889         my $ldap = Net::LDAP->new($ldap_uri);
890         if( not defined $ldap ) {
891                 &main::daemon_log("ERROR: cannot connect to ldap: $ldap_uri", 1);
892                 return;
893         } 
895         # Bind to a directory with dn and password
896         my $mesg= $ldap->bind($ldap_admin_dn, password => $ldap_admin_password);
898         # Perform search
899         $mesg = $ldap->search(
900                 base   => $ldap_base,
901                 scope  => 'sub',
902                 filter => "(&(objectClass=GOhard)(|(macAddress=$macaddress)(dhcpHWaddress=ethernet $macaddress)))"
903         );
905         if($mesg->count() == 0) {
906                 &main::daemon_log("Host was not found in LDAP!", 1);
907                 return;
908         }
910         my $entry= $mesg->entry(0);
911         my $dn= $entry->dn;
912         if(defined($entry->get_value("gotoHardwareChecksum"))) {
913                 if(! $entry->get_value("gotoHardwareChecksum") eq $gotoHardwareChecksum) {
914                         $entry->replace(gotoHardwareChecksum => $gotoHardwareChecksum);
915                         if($entry->update($ldap)) {
916                                 &main::daemon_log("Hardware changed! Detection triggered.", 4);
917                         }
918                 } else {
919                         # Nothing to do
920                         return;
921                 }
922         } else {
923                 # need to fill it to LDAP
924                 $entry->add(gotoHardwareChecksum => $gotoHardwareChecksum);
925                 if($entry->update($ldap)) {
926                         &main::daemon_log("gotoHardwareChecksum $gotoHardwareChecksum was added to LDAP", 4);
927                 }
929                 ## Look if there another host with this checksum to use the hardware config
930                 #$mesg = $ldap->search(
931                 #       base   => $ldap_base,
932                 #       scope  => 'sub',
933                 #       filter => "(&(objectClass=GOhard)(gotoHardwareChecksum=$gotoHardwareChecksum))"
934                 #);
936                 #if($mesg->count>1) {
937                 #       my $clone_entry= $mesg->entry(0);
938                 #       $entry->changetype("modify");
939                 #       foreach my $attribute (
940                 #               "gotoSndModule", "ghNetNic", "gotoXResolution", "ghSoundAdapter", "ghCpuType", "gotoXkbModel", 
941                 #               "ghGfxAdapter", "gotoXMousePort", "ghMemSize", "gotoXMouseType", "ghUsbSupport", "gotoXHsync", 
942                 #               "gotoXDriver", "gotoXVsync", "gotoXMonitor") {
943                 #               my $value= $clone_entry->get_value($attribute);
944                 #               if(defined($value)) {
945                 #                       if(defined($entry->get_value($attribute))) {
946                 #                               $entry->delete($attribute);
947                 #                       }
948                 #                       &main::daemon_log("Adding attribute $attribute with value $value",1);
949                 #                       $entry->add($attribute => $value);
950                 #               }
951                 #       }
952                 #       foreach my $attribute (
953                 #               "gotoModules", "ghScsiDev", "ghIdeDev") {
954                 #               my $array= $clone_entry->get_value($attribute, 'as_ref' => 1);
955                 #               if(defined($array))     {
956                 #                       if(defined($entry->get_value($attribute))) {
957                 #                               $entry->delete($attribute);
958                 #                       }
959                 #                       foreach my $array_entry (@{$array}) {
960                 #                               $entry->add($attribute => $array_entry);
961                 #                       }
962                 #               }
964                 #       }
965                 #       if($entry->update($ldap)) {
966                 #               &main::daemon_log("Added Hardware configuration to LDAP", 4);
967                 #       }
969                 #}
971         }
973         # Assemble data package
974         my %data = ();
976         # Need to append GOto settings?
977         if (defined $goto_admin and defined $goto_secret){
978                 $data{'goto_admin'}= $goto_admin;
979                 $data{'goto_secret'}= $goto_secret;
980         }
982         # Unbind
983         $mesg = $ldap->unbind;
985         &main::daemon_log("Send detect_hardware message to $address", 4);
986         
987         # Send information
988         return send_msg("detect_hardware", $server_address, $address, \%data);
992 #===  FUNCTION  ================================================================
993 #         NAME:  execute_actions
994 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
995 #      RETURNS:  nothing
996 #  DESCRIPTION:  invokes the script specified in msg_hash which is located under
997 #                /etc/gosad/actions
998 #===============================================================================
999 sub execute_actions {
1000     my ($msg_hash) = @_ ;
1001     my $configdir= '/etc/gosad/actions/';
1002     my $result;
1004     my $header = @{$msg_hash->{header}}[0];
1005     my $source = @{$msg_hash->{source}}[0];
1006     my $target = @{$msg_hash->{target}}[0];
1007  
1008     if((not defined $source)
1009             && (not defined $target)
1010             && (not defined $header)) {
1011         &main::daemon_log("ERROR: Entries missing in XML msg for gosad actions under /etc/gosad/actions");
1012     } else {
1013         my $parameters="";
1014         my @params = @{$msg_hash->{$header}};
1015         my $params = join(", ", @params);
1016         &main::daemon_log("execute_actions: got parameters: $params", 5);
1018         if (@params) {
1019             foreach my $param (@params) {
1020                 my $param_value = (&get_content_from_xml_hash($msg_hash, $param))[0];
1021                 &main::daemon_log("execute_actions: parameter -> value: $param -> $param_value", 7);
1022                 $parameters.= " ".$param_value;
1023             }
1024         }
1026         my $cmd= $configdir.$header."$parameters";
1027         &main::daemon_log("execute_actions: executing cmd: $cmd", 7);
1028         $result= "";
1029         open(PIPE, "$cmd 2>&1 |");
1030         while(<PIPE>) {
1031             $result.=$_;
1032         }
1033         close(PIPE);
1034     }
1036     # process the event result
1039     return;
1043 1;