Code

22e052455cc08decb1db929d8e637f3e7c64b5ba
[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;
18 use Net::DNS;
20 BEGIN{}
21 END {}
23 my ($known_clients_file_name);
24 my ($server_activ, $server_ip, $server_mac_address, $server_port, $SIPackages_key, $max_clients, $ldap_uri, $ldap_base, $ldap_admin_dn, $ldap_admin_password);
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 (
34 "server" =>
35     {"server_activ" => [\$server_activ, "on"],
36     "server_ip" => [\$server_ip, "0.0.0.0"],
37     "server_mac_address" => [\$server_mac_address, ""],
38     "server_port" => [\$server_port, "20081"],
39     "SIPackages_key" => [\$SIPackages_key, ""],
40     "max_clients" => [\$max_clients, 100],
41     "ldap_uri" => [\$ldap_uri, ""],
42     "ldap_base" => [\$ldap_base, ""],
43     "ldap_admin_dn" => [\$ldap_admin_dn, ""],
44     "ldap_admin_password" => [\$ldap_admin_password, ""],
45     },
46 "bus" =>
47     {"bus_activ" => [\$bus_activ, "on"],
48     "bus_passwd" => [\$bus_key, ""],
49     "bus_ip" => [\$bus_ip, ""],
50     "bus_port" => [\$bus_port, "20080"],
51     },
52 );
54 ### START #####################################################################
56 # read configfile and import variables
57 &read_configfile();
59 # detect interfaces and mac address
60 $network_interface= &get_interface_for_ip($server_ip);
61 $server_mac_address= &get_mac($network_interface); 
63 # complete addresses
64 if( $server_ip eq "0.0.0.0" ) {
65     $server_ip = "127.0.0.1";
66 }
67 my $server_address = "$server_ip:$server_port";
68 my $bus_address = "$bus_ip:$bus_port";
70 # create general settings for this module
71 my $xml = new XML::Simple();
73 # register at bus
74 if ($main::no_bus > 0) {
75     $bus_activ = "off"
76 }
77 if($bus_activ eq "on") {
78     &register_at_bus();
79 }
81 # add myself to known_server_db
82 my $res = $main::known_server_db->add_dbentry( {table=>'known_server',
83         primkey=>'hostname',
84         hostname=>$server_address,
85         status=>'myself',
86         hostkey=>$SIPackages_key,
87         timestamp=>&get_time,
88         } );
92 ### functions #################################################################
95 sub get_module_info {
96     my @info = ($server_address,
97                 $SIPackages_key,
98                 $server,
99                 $server_activ,
100                 "socket",
101                 );
102     return \@info;
107 sub do_wake {
108         my $host    = shift;
109         my $ipaddr  = shift || '255.255.255.255';
110         my $port    = getservbyname('discard', 'udp');
112         my ($raddr, $them, $proto);
113         my ($hwaddr, $hwaddr_re, $pkt);
115         # get the hardware address (ethernet address)
117         $hwaddr_re = join(':', ('[0-9A-Fa-f]{1,2}') x 6);
118         if ($host =~ m/^$hwaddr_re$/) {
119                 $hwaddr = $host;
120         } else {
121                 # $host is not a hardware address, try to resolve it
122                 my $ip_re = join('\.', ('([0-9]|[1-9][0-9]|1[0-9]{2}|2([0-4][0-9]|5[0-5]))') x 4);
123                 my $ip_addr;
124                 if ($host =~ m/^$ip_re$/) {
125                         $ip_addr = $host;
126                 } else {
127                         my $h;
128                         unless ($h = gethost($host)) {
129                                 return undef;
130                         }
131                         $ip_addr = inet_ntoa($h->addr);
132                 }
133         }
135         # Generate magic sequence
136         foreach (split /:/, $hwaddr) {
137                 $pkt .= chr(hex($_));
138         }
139         $pkt = chr(0xFF) x 6 . $pkt x 16;
141         # Allocate socket and send packet
143         $raddr = gethostbyname($ipaddr)->addr;
144         $them = pack_sockaddr_in($port, $raddr);
145         $proto = getprotobyname('udp');
147         socket(S, AF_INET, SOCK_DGRAM, $proto) or die "socket : $!";
148         setsockopt(S, SOL_SOCKET, SO_BROADCAST, 1) or die "setsockopt : $!";
150         send(S, $pkt, 0, $them) or die "send : $!";
151         close S;
155 #===  FUNCTION  ================================================================
156 #         NAME:  read_configfile
157 #   PARAMETERS:  cfg_file - string -
158 #      RETURNS:  nothing
159 #  DESCRIPTION:  read cfg_file and set variables
160 #===============================================================================
161 sub read_configfile {
162     my $cfg;
163     if( defined( $main::cfg_file) && ( length($main::cfg_file) > 0 )) {
164         if( -r $main::cfg_file ) {
165             $cfg = Config::IniFiles->new( -file => $main::cfg_file );
166         } else {
167             print STDERR "Couldn't read config file!";
168         }
169     } else {
170         $cfg = Config::IniFiles->new() ;
171     }
172     foreach my $section (keys %cfg_defaults) {
173         foreach my $param (keys %{$cfg_defaults{ $section }}) {
174             my $pinfo = $cfg_defaults{ $section }{ $param };
175             ${@$pinfo[0]} = $cfg->val( $section, $param, @$pinfo[1] );
176         }
177     }
179     # Read non predefined sections
180     my $param;
181     if ($cfg->SectionExists('ldap')){
182                 foreach $param ($cfg->Parameters('ldap')){
183                         push (@ldap_cfg, "$param ".$cfg->val('ldap', $param));
184                 }
185     }
186     if ($cfg->SectionExists('pam_ldap')){
187                 foreach $param ($cfg->Parameters('pam_ldap')){
188                         push (@pam_cfg, "$param ".$cfg->val('pam_ldap', $param));
189                 }
190     }
191     if ($cfg->SectionExists('nss_ldap')){
192                 foreach $param ($cfg->Parameters('nss_ldap')){
193                         push (@nss_cfg, "$param ".$cfg->val('nss_ldap', $param));
194                 }
195     }
196     if ($cfg->SectionExists('goto')){
197         $goto_admin= $cfg->val('goto', 'terminal_admin');
198         $goto_secret= $cfg->val('goto', 'terminal_secret');
199     } else {
200         $goto_admin= undef;
201         $goto_secret= undef;
202     }
206 #===  FUNCTION  ================================================================
207 #         NAME:  get_interface_for_ip
208 #   PARAMETERS:  ip address (i.e. 192.168.0.1)
209 #      RETURNS:  array: list of interfaces if ip=0.0.0.0, matching interface if found, undef else
210 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
211 #===============================================================================
212 sub get_interface_for_ip {
213         my $result;
214         my $ip= shift;
215         if ($ip && length($ip) > 0) {
216                 my @ifs= &get_interfaces();
217                 if($ip eq "0.0.0.0") {
218                         $result = "all";
219                 } else {
220                         foreach (@ifs) {
221                                 my $if=$_;
222                                 if(get_ip($if) eq $ip) {
223                                         $result = $if;
224                                 }
225                         }       
226                 }
227         }       
228         return $result;
231 #===  FUNCTION  ================================================================
232 #         NAME:  get_interfaces 
233 #   PARAMETERS:  none
234 #      RETURNS:  (list of interfaces) 
235 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
236 #===============================================================================
237 sub get_interfaces {
238         my @result;
239         my $PROC_NET_DEV= ('/proc/net/dev');
241         open(PROC_NET_DEV, "<$PROC_NET_DEV")
242                 or die "Could not open $PROC_NET_DEV";
244         my @ifs = <PROC_NET_DEV>;
246         close(PROC_NET_DEV);
248         # Eat first two line
249         shift @ifs;
250         shift @ifs;
252         chomp @ifs;
253         foreach my $line(@ifs) {
254                 my $if= (split /:/, $line)[0];
255                 $if =~ s/^\s+//;
256                 push @result, $if;
257         }
259         return @result;
262 #===  FUNCTION  ================================================================
263 #         NAME:  get_mac 
264 #   PARAMETERS:  interface name (i.e. eth0)
265 #      RETURNS:  (mac address) 
266 #  DESCRIPTION:  Uses ioctl to get mac address directly from system.
267 #===============================================================================
268 sub get_mac {
269         my $ifreq= shift;
270         my $result;
271         if ($ifreq && length($ifreq) > 0) { 
272                 if($ifreq eq "all") {
273                         $result = "00:00:00:00:00:00";
274                 } else {
275                         my $SIOCGIFHWADDR= 0x8927;     # man 2 ioctl_list
277                         # A configured MAC Address should always override a guessed value
278                         if ($server_mac_address and length($server_mac_address) > 0) {
279                                 $result= $server_mac_address;
280                         }
282                         socket SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('ip')
283                                 or die "socket: $!";
285                         if(ioctl SOCKET, $SIOCGIFHWADDR, $ifreq) {
286                                 my ($if, $mac)= unpack 'h36 H12', $ifreq;
288                                 if (length($mac) > 0) {
289                                         $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])$/;
290                                         $mac= sprintf("%s:%s:%s:%s:%s:%s", $1, $2, $3, $4, $5, $6);
291                                         $result = $mac;
292                                 }
293                         }
294                 }
295         }
296         return $result;
299 #===  FUNCTION  ================================================================
300 #         NAME:  get_ip 
301 #   PARAMETERS:  interface name (i.e. eth0)
302 #      RETURNS:  (ip address) 
303 #  DESCRIPTION:  Uses ioctl to get ip address directly from system.
304 #===============================================================================
305 sub get_ip {
306         my $ifreq= shift;
307         my $result= "";
308         my $SIOCGIFADDR= 0x8915;       # man 2 ioctl_list
309         my $proto= getprotobyname('ip');
311         socket SOCKET, PF_INET, SOCK_DGRAM, $proto
312                 or die "socket: $!";
314         if(ioctl SOCKET, $SIOCGIFADDR, $ifreq) {
315                 my ($if, $sin)    = unpack 'a16 a16', $ifreq;
316                 my ($port, $addr) = sockaddr_in $sin;
317                 my $ip            = inet_ntoa $addr;
319                 if ($ip && length($ip) > 0) {
320                         $result = $ip;
321                 }
322         }
324         return $result;
328 #===  FUNCTION  ================================================================
329 #         NAME:  register_at_bus
330 #   PARAMETERS:  nothing
331 #      RETURNS:  nothing
332 #  DESCRIPTION:  creates an entry in known_daemons and send a 'here_i_am' msg to bus
333 #===============================================================================
334 sub register_at_bus {
336     # add bus to known_server_db
337     my $res = $main::known_server_db->add_dbentry( {table=>'known_server',
338                                                     primkey=>'hostname',
339                                                     hostname=>$bus_address,
340                                                     status=>'bus',
341                                                     hostkey=>$bus_key,
342                                                     timestamp=>&get_time,
343                                                 } );
344     my $msg_hash = &create_xml_hash("here_i_am", $server_address, $bus_address);
345     my $msg = &create_xml_string($msg_hash);
347     &main::send_msg_to_target($msg, $bus_address, $bus_key, "here_i_am");
348     return $msg;
349 #    my $answer = "";
350 #    $answer = &send_msg_hash2address($msg_hash, $bus_address, $bus_passwd);
351 #    if ($answer == 0) {
352 #        &main::daemon_log("register at bus: $bus_address", 1);
353 #    } else {
354 #        &main::daemon_log("unable to send 'register'-msg to bus '$bus_address': $answer", 1);
355 #    }
356 #    return;
360 #===  FUNCTION  ================================================================
361 #         NAME:  process_incoming_msg
362 #   PARAMETERS:  crypted_msg - string - incoming crypted message
363 #      RETURNS:  nothing
364 #  DESCRIPTION:  handels the proceeded distribution to the appropriated functions
365 #===============================================================================
366 sub process_incoming_msg {
367     my ($msg, $msg_hash, $remote_ip) = @_ ;
368     my $error = 0;
369     my $host_name;
370     my $host_key;
371     my @out_msg_l;
373     # process incoming msg
374     my $header = @{$msg_hash->{header}}[0]; 
375     my @target_l = @{$msg_hash->{target}};
377     &main::daemon_log("SIPackages: msg to process: $header", 3);
378     &main::daemon_log("$msg", 8);
380     if( 0 == length @target_l){     
381         &main::daemon_log("ERROR: no target specified for msg $header", 1);
382         $error++;
383     }
385     if( 1 == length @target_l) {
386         my $target = $target_l[0];
387         if( $target eq $server_address ) {  
388             if ($header eq 'new_key') {
389                 @out_msg_l = &new_key($msg_hash)
390             } elsif ($header eq 'here_i_am') {
391                 @out_msg_l = &here_i_am($msg_hash)
392             } elsif ($header eq 'who_has') {
393                 @out_msg_l = &who_has($msg_hash)
394             } elsif ($header eq 'who_has_i_do') {
395                 @out_msg_l = &who_has_i_do($msg_hash)
396             } elsif ($header eq 'got_ping') {
397                 @out_msg_l = &got_ping($msg_hash)
398             } elsif ($header eq 'get_load') {
399                 @out_msg_l = &execute_actions($msg_hash)
400             } elsif ($header eq 'detected_hardware') {
401                 @out_msg_l = &process_detected_hardware($msg_hash)
402             } elsif ($header eq 'trigger_wake') {
403                 foreach (@{$msg_hash->{macAddress}}){
404                     &main::daemon_log("SIPackages: trigger wake for $_", 1);
405                     do_wake($_);
406                 }
408             } else {
409                 &main::daemon_log("ERROR: $header is an unknown core function", 1);
410                 $error++;
411             }
412         }
413                 else {
414                         &main::daemon_log("msg is not for gosa-si-server '$server_address', deliver it to target '$target'", 5);
415                         push(@out_msg_l, $msg);
416                 }
417     }
419 #    if( $error == 0) {
420 #        if( 0 == @out_msg_l ) {
421 #                       push(@out_msg_l, $msg);
422 #        }
423 #    }
424     
425     return \@out_msg_l;
429 #===  FUNCTION  ================================================================
430 #         NAME:  got_ping
431 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
432 #      RETURNS:  nothing
433 #  DESCRIPTION:  process this incoming message
434 #===============================================================================
435 sub got_ping {
436     my ($msg_hash) = @_;
437     
438     my $source = @{$msg_hash->{source}}[0];
439     my $target = @{$msg_hash->{target}}[0];
440     my $header = @{$msg_hash->{header}}[0];
441     
442     if(exists $main::known_daemons->{$source}) {
443         &main::add_content2known_daemons(hostname=>$source, status=>$header);
444     } else {
445         &main::add_content2known_clients(hostname=>$source, status=>$header);
446     }
447     
448     return;
452 #===  FUNCTION  ================================================================
453 #         NAME:  new_passwd
454 #   PARAMETERS:  msg_hash - ref - hash from function create_xml_hash
455 #      RETURNS:  nothing
456 #  DESCRIPTION:  process this incoming message
457 #===============================================================================
458 sub new_key {
459     my ($msg_hash) = @_;
460     my @out_msg_l;
461     
462     my $header = @{$msg_hash->{header}}[0];
463     my $source_name = @{$msg_hash->{source}}[0];
464     my $source_key = @{$msg_hash->{new_key}}[0];
465     my $query_res;
467     # check known_clients_db
468     my $sql_statement = "SELECT * FROM known_clients WHERE hostname='$source_name'";
469     $query_res = $main::known_clients_db->select_dbentry( $sql_statement );
470     if( 1 == keys %{$query_res} ) {
471         my $act_time = &get_time;
472         my $sql_statement= "UPDATE known_clients ".
473             "SET hostkey='$source_key', timestamp='$act_time' ".
474             "WHERE hostname='$source_name'";
475         my $res = $main::known_clients_db->update_dbentry( $sql_statement );
476         my $hash = &create_xml_hash("confirm_new_passwd", $server_address, $source_name);
477         my $out_msg = &create_xml_string($hash);
478         push(@out_msg_l, $out_msg);
479     }
481     # only do if host still not found
482     if( 0 == @out_msg_l ) {
483         # check known_server_db
484         $sql_statement = "SELECT * FROM known_server WHERE hostname='$source_name'";
485         $query_res = $main::known_server_db->select_dbentry( $sql_statement );
486         if( 1 == keys %{$query_res} ) {
487             my $act_time = &get_time;
488             my $sql_statement= "UPDATE known_server ".
489                 "SET hostkey='$source_key', timestamp='$act_time' ".
490                 "WHERE hostname='$source_name'";
491             my $res = $main::known_server_db->update_dbentry( $sql_statement );
493             my $hash = &create_xml_hash("confirm_new_passwd", $server_address, $source_name);
494             my $out_msg = &create_xml_string($hash);
495             push(@out_msg_l, $out_msg);
496         }
497     }
499     return @out_msg_l;
503 #===  FUNCTION  ================================================================
504 #         NAME:  here_i_am
505 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
506 #      RETURNS:  nothing
507 #  DESCRIPTION:  process this incoming message
508 #===============================================================================
509 sub here_i_am {
510     my ($msg_hash) = @_;
511     my @out_msg_l;
512     my $out_hash;
514     my $source = @{$msg_hash->{source}}[0];
515     my $mac_address = @{$msg_hash->{mac_address}}[0];
516         my $gotoHardwareChecksum = @{$msg_hash->{gotoHardwareChecksum}}[0];
518     # number of known clients
519     my $nu_clients= $main::known_clients_db->count_dbentries('known_clients');
521     # check wether client address or mac address is already known
522     my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$source'";
523     my $db_res= $main::known_clients_db->select_dbentry( $sql_statement );
524     
525     if ( 1 == keys %{$db_res} ) {
526         &main::daemon_log("WARNING: $source is already known as a client", 1);
527         &main::daemon_log("WARNING: values for $source are being overwritten", 1);   
528         $nu_clients --;
529     }
531     # number of actual activ clients
532     my $act_nu_clients = $nu_clients;
534     &main::daemon_log("number of actual activ clients: $act_nu_clients", 5);
535     &main::daemon_log("number of maximal allowed clients: $max_clients", 5);
537     if($max_clients <= $act_nu_clients) {
538         my $out_hash = &create_xml_hash("denied", $server_address, $source);
539         &add_content2xml_hash($out_hash, "denied", "I_cannot_take_any_more_clients!");
540         my $passwd = @{$msg_hash->{new_passwd}}[0]; 
541         &send_msg_hash2address($out_hash, $source, $passwd);
542         return;
543     }
544     
545     # new client accepted
546     my $new_passwd = @{$msg_hash->{new_passwd}}[0];
548     # create entry in known_clients
549     my $events = @{$msg_hash->{events}}[0];
550     
552     # add entry to known_clients_db
553     my $act_timestamp = &get_time;
554     my $res = $main::known_clients_db->add_dbentry( {table=>'known_clients', 
555                                                 primkey=>'hostname',
556                                                 hostname=>$source,
557                                                 events=>$events,
558                                                 macaddress=>$mac_address,
559                                                 status=>'registered',
560                                                 hostkey=>$new_passwd,
561                                                 timestamp=>$act_timestamp,
562                                                 } );
564     if ($res != 0)  {
565         &main::daemon_log("ERROR: cannot add entry to known_clients: $res");
566         return;
567     }
568     
569     # return acknowledgement to client
570     $out_hash = &create_xml_hash("registered", $server_address, $source);
571     my $register_out = &create_xml_string($out_hash);
572     push(@out_msg_l, $register_out);
574     # notify registered client to bus
575     if( $bus_activ eq "on") {
576         # fetch actual bus key
577         my $sql_statement= "SELECT * FROM known_server WHERE status='bus'";
578         my $query_res = $main::known_server_db->select_dbentry( $sql_statement );
579         my $hostkey = $query_res->{1}->{'hostkey'};
581         # send update msg to bus
582         $out_hash = &create_xml_hash("new_client", $server_address, $bus_address, $source);
583         &add_content2xml_hash($out_hash, "macaddress", $mac_address);
584         &add_content2xml_hash($out_hash, "timestamp", $act_timestamp);
585         my $new_client_out = &create_xml_string($out_hash);
586         push(@out_msg_l, $new_client_out);
587         &main::daemon_log("send bus msg that client '$source' has registerd at server '$server_address'", 3);
588     }
590     # give the new client his ldap config
591     my $new_ldap_config_out = &new_ldap_config($source);
592     if( $new_ldap_config_out ) {
593         push(@out_msg_l, $new_ldap_config_out);
594     }
596         my $hardware_config_out = &hardware_config($source, $gotoHardwareChecksum);
597         if( $hardware_config_out ) {
598                 push(@out_msg_l, $hardware_config_out);
599         }
601     return @out_msg_l;
605 #===  FUNCTION  ================================================================
606 #         NAME:  who_has
607 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
608 #      RETURNS:  nothing 
609 #  DESCRIPTION:  process this incoming message
610 #===============================================================================
611 sub who_has {
612     my ($msg_hash) = @_ ;
613     my @out_msg_l;
614     
615     # what is your search pattern
616     my $search_pattern = @{$msg_hash->{who_has}}[0];
617     my $search_element = @{$msg_hash->{$search_pattern}}[0];
618     &main::daemon_log("who_has-msg looking for $search_pattern $search_element", 7);
620     # scanning known_clients for search_pattern
621     my @host_addresses = keys %$main::known_clients;
622     my $known_clients_entries = length @host_addresses;
623     my $host_address;
624     foreach my $host (@host_addresses) {
625         my $client_element = $main::known_clients->{$host}->{$search_pattern};
626         if ($search_element eq $client_element) {
627             $host_address = $host;
628             last;
629         }
630     }
631         
632     # search was successful
633     if (defined $host_address) {
634         my $source = @{$msg_hash->{source}}[0];
635         my $out_hash = &create_xml_hash("who_has_i_do", $server_address, $source, "mac_address");
636         &add_content2xml_hash($out_hash, "mac_address", $search_element);
637         my $out_msg = &create_xml_string($out_hash);
638         push(@out_msg_l, $out_msg);
639     }
640     return @out_msg_l;
644 sub who_has_i_do {
645     my ($msg_hash) = @_ ;
646     my $header = @{$msg_hash->{header}}[0];
647     my $source = @{$msg_hash->{source}}[0];
648     my $search_param = @{$msg_hash->{$header}}[0];
649     my $search_value = @{$msg_hash->{$search_param}}[0];
650     print "\ngot msg $header:\nserver $source has client with $search_param $search_value\n";
653 #===  FUNCTION  ================================================================
654 #         NAME:  new_ldap_config
655 #   PARAMETERS:  address - string - ip address and port of a host
656 #      RETURNS:  nothing
657 #  DESCRIPTION:  send to address the ldap configuration found for dn gotoLdapServer
658 #===============================================================================
659 sub new_ldap_config {
660         my ($address) = @_ ;
662         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address'";
663         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
665         # check hit
666         my $hit_counter = keys %{$res};
667         if( not $hit_counter == 1 ) {
668                 &main::daemon_log("ERROR: more or no hit found in known_clients_db by query by '$address'", 1);
669         }
671         my $macaddress = $res->{1}->{macaddress};
672         my $hostkey = $res->{1}->{hostkey};
674         if (not defined $macaddress) {
675                 &main::daemon_log("ERROR: no mac address found for client $address", 1);
676                 return;
677         }
679         # Build LDAP connection
680         my $ldap = Net::LDAP->new($ldap_uri);
681         if( not defined $ldap ) {
682                 &main::daemon_log("ERROR: cannot connect to ldap: $ldap_uri", 1);
683                 return;
684         } 
687         # Bind to a directory with dn and password
688         my $mesg= $ldap->bind($ldap_admin_dn, password => $ldap_admin_password);
690         # Perform search
691         $mesg = $ldap->search( base   => $ldap_base,
692                 scope  => 'sub',
693                 attrs => ['dn', 'gotoLdapServer', 'gosaUnitTag'],
694                 filter => "(&(objectClass=GOhard)(macaddress=$macaddress))");
695         #$mesg->code && die $mesg->error;
696         if($mesg->code) {
697                 &main::daemon_log($mesg->error, 1);
698                 return;
699         }
701         # Sanity check
702         if ($mesg->count != 1) {
703                 &main::daemon_log("WARNING: client mac address $macaddress not found/not unique in ldap search", 1);
704                 &main::daemon_log("\tbase: $ldap_base", 1);
705                 &main::daemon_log("\tscope: sub", 1);
706                 &main::daemon_log("\tattrs: dn, gotoLdapServer", 1);
707                 &main::daemon_log("\tfilter: (&(objectClass=GOhard)(macaddress=$macaddress))", 1);
708                 return;
709         }
711         my $entry= $mesg->entry(0);
712         my $dn= $entry->dn;
713         my @servers= $entry->get_value("gotoLdapServer");
714         my $unit_tag= $entry->get_value("gosaUnitTag");
715         my @ldap_uris;
716         my $server;
717         my $base;
719         # Do we need to look at an object class?
720         if (length(@servers) < 1){
721                 $mesg = $ldap->search( base   => $ldap_base,
722                         scope  => 'sub',
723                         attrs => ['dn', 'gotoLdapServer'],
724                         filter => "(&(objectClass=gosaGroupOfNames)(member=$dn))");
725                 #$mesg->code && die $mesg->error;
726                 if($mesg->code) {
727                         &main::daemon_log($mesg->error, 1);
728                         return;
729                 }
731                 # Sanity check
732                 if ($mesg->count != 1) {
733                         &main::daemon_log("WARNING: no LDAP information found for client mac $macaddress", 1);
734                         return;
735                 }
737                 $entry= $mesg->entry(0);
738                 $dn= $entry->dn;
739                 @servers= $entry->get_value("gotoLdapServer");
740         }
742         @servers= sort (@servers);
744         foreach $server (@servers){
745                 $base= $server;
746                 $server =~ s%^[^:]+:[^:]+:(ldap.*://[^/]+)/.*$%$1%;
747                 $base =~ s%^[^:]+:[^:]+:ldap.*://[^/]+/(.*)$%$1%;
748                 push (@ldap_uris, $server);
749         }
751         # Assemble data package
752         my %data = ( 'ldap_uri'  => \@ldap_uris, 'ldap_base' => $base,
753                 'ldap_cfg' => \@ldap_cfg, 'pam_cfg' => \@pam_cfg,'nss_cfg' => \@nss_cfg );
755         # Need to append GOto settings?
756         if (defined $goto_admin and defined $goto_secret){
757                 $data{'goto_admin'}= $goto_admin;
758                 $data{'goto_secret'}= $goto_secret;
759         }
761         # Append unit tag if needed
762         if (defined $unit_tag){
764                 # Find admin base and department name
765                 $mesg = $ldap->search( base   => $ldap_base,
766                         scope  => 'sub',
767                         attrs => ['dn', 'ou', 'FAIclass'],
768                         filter => "(&(objectClass=gosaAdministrativeUnit)(gosaUnitTag=$unit_tag))");
769                 #$mesg->code && die $mesg->error;
770                 if($mesg->code) {
771                         &main::daemon_log($mesg->error, 1);
772                         return;
773                 }
775                 # Sanity check
776                 if ($mesg->count != 1) {
777                         &main::daemon_log("WARNING: cannot find administrative unit for client with tag $unit_tag", 1);
778                         return;
779                 }
781                 $entry= $mesg->entry(0);
782                 $data{'admin_base'}= $entry->dn;
783                 $data{'department'}= $entry->get_value("ou");
785                 # Fill release if available
786                 my $ou= $entry->get_value("ou");
787                 if (defined $ou && $ou ~= /^.* :([A-Za-z0-9/.]+).*$/){
788                         $data{'release'}= $1;
789                 }
791                 # Append unit Tag
792                 $data{'unit_tag'}= $unit_tag;
793         }
795         # Unbind
796         $mesg = $ldap->unbind;
798         # Send information
799         return send_msg("new_ldap_config", $server_address, $address, \%data);
802 sub process_detected_hardware {
803         my $msg_hash = shift;
804         my $address = $msg_hash->{source}[0];
805         my $gotoHardwareChecksum= $msg_hash->{detected_hardware}[0]->{gotoHardwareChecksum};
807     my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address'";
808     my $res = $main::known_clients_db->select_dbentry( $sql_statement );
810     # check hit
811     my $hit_counter = keys %{$res};
812     if( not $hit_counter == 1 ) {
813         &main::daemon_log("ERROR: more or no hit found in known_clients_db by query by '$address'", 1);
814                 return;
815     }
817     my $macaddress = $res->{1}->{macaddress};
818     my $hostkey = $res->{1}->{hostkey};
820     if (not defined $macaddress) {
821         &main::daemon_log("ERROR: no mac address found for client $address", 1);
822         return;
823     }
824     # Build LDAP connection
825     my $ldap = Net::LDAP->new($ldap_uri);
826     if( not defined $ldap ) {
827         &main::daemon_log("ERROR: cannot connect to ldap: $ldap_uri", 1);
828         return;
829     } 
831     # Bind to a directory with dn and password
832     my $mesg= $ldap->bind($ldap_admin_dn, password => $ldap_admin_password);
834     # Perform search
835         $mesg = $ldap->search(
836                 base   => $ldap_base,
837                 scope  => 'sub',
838                 filter => "(&(objectClass=GOhard)(|(macAddress=$macaddress)(dhcpHWaddress=ethernet $macaddress)))"
839         );
841         # We need to create a base entry first (if not done from ArpHandler)
842         if($mesg->count == 0) {
843                 &main::daemon_log("Need to create a new LDAP Entry for client $address", 1);
844                 my $resolver=Net::DNS::Resolver->new;
845                 my $ipaddress= $1 if $address =~ /^([0-9\.]*?):.*$/;
846                 my $dnsresult= $resolver->search($ipaddress);
847                 my $dnsname= (defined($dnsresult))?$dnsresult->{answer}[0]->{ptrdname}:$ipaddress;
848                 my $cn = (($dnsname =~ /^(\d){1,3}\.(\d){1,3}\.(\d){1,3}\.(\d){1,3}/) ? $dnsname : sprintf "%s", $dnsname =~ /([^\.]+)\.?/);
849                 my $dn = "cn=$cn,ou=incoming,$ldap_base";
850                 &main::daemon_log("Creating entry for $dn",6);
851                 my $entry= Net::LDAP::Entry->new( $dn );
852                 $entry->dn($dn);
853                 $entry->add("objectClass" => "goHard");
854                 $entry->add("cn" => $cn);
855                 $entry->add("macAddress" => $macaddress);
856                 $entry->add("gotomode" => "locked");
857                 $entry->add("gotoSysStatus" => "new-system");
858                 $entry->add("ipHostNumber" => $ipaddress);
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("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);
1035 #===  FUNCTION  ================================================================
1036 #         NAME:  execute_actions
1037 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
1038 #      RETURNS:  nothing
1039 #  DESCRIPTION:  invokes the script specified in msg_hash which is located under
1040 #                /etc/gosad/actions
1041 #===============================================================================
1042 sub execute_actions {
1043     my ($msg_hash) = @_ ;
1044     my $configdir= '/etc/gosad/actions/';
1045     my $result;
1047     my $header = @{$msg_hash->{header}}[0];
1048     my $source = @{$msg_hash->{source}}[0];
1049     my $target = @{$msg_hash->{target}}[0];
1050  
1051     if((not defined $source)
1052             && (not defined $target)
1053             && (not defined $header)) {
1054         &main::daemon_log("ERROR: Entries missing in XML msg for gosad actions under /etc/gosad/actions");
1055     } else {
1056         my $parameters="";
1057         my @params = @{$msg_hash->{$header}};
1058         my $params = join(", ", @params);
1059         &main::daemon_log("execute_actions: got parameters: $params", 5);
1061         if (@params) {
1062             foreach my $param (@params) {
1063                 my $param_value = (&get_content_from_xml_hash($msg_hash, $param))[0];
1064                 &main::daemon_log("execute_actions: parameter -> value: $param -> $param_value", 7);
1065                 $parameters.= " ".$param_value;
1066             }
1067         }
1069         my $cmd= $configdir.$header."$parameters";
1070         &main::daemon_log("execute_actions: executing cmd: $cmd", 7);
1071         $result= "";
1072         open(PIPE, "$cmd 2>&1 |");
1073         while(<PIPE>) {
1074             $result.=$_;
1075         }
1076         close(PIPE);
1077     }
1079     # process the event result
1082     return;
1086 1;