Code

f8c56e6bf88b4517a087db15677ec31ee466807b
[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                 $base= $server;
734                 $server =~ s%^[^:]+:[^:]+:(ldap.*://[^/]+)/.*$%$1%;
735                 $base =~ s%^[^:]+:[^:]+:ldap.*://[^/]+/(.*)$%$1%;
736                 push (@ldap_uris, $server);
737         }
739         # Assemble data package
740         my %data = ( 'ldap_uri'  => \@ldap_uris, 'ldap_base' => $base,
741                 'ldap_cfg' => \@ldap_cfg, 'pam_cfg' => \@pam_cfg,'nss_cfg' => \@nss_cfg );
743         # Need to append GOto settings?
744         if (defined $goto_admin and defined $goto_secret){
745                 $data{'goto_admin'}= $goto_admin;
746                 $data{'goto_secret'}= $goto_secret;
747         }
749         # Append unit tag if needed
750         if (defined $unit_tag){
752                 # Find admin base and department name
753                 $mesg = $ldap->search( base   => $ldap_base,
754                         scope  => 'sub',
755                         attrs => ['dn', 'ou', 'FAIclass'],
756                         filter => "(&(objectClass=gosaAdministrativeUnit)(gosaUnitTag=$unit_tag))");
757                 #$mesg->code && die $mesg->error;
758                 if($mesg->code) {
759                         &main::daemon_log($mesg->error, 1);
760                         return;
761                 }
763                 # Sanity check
764                 if ($mesg->count != 1) {
765                         &main::daemon_log("WARNING: cannot find administrative unit for client with tag $unit_tag", 1);
766                         return;
767                 }
769                 $entry= $mesg->entry(0);
770                 $data{'admin_base'}= $entry->dn;
771                 $data{'department'}= $entry->get_value("ou");
773                 # Append unit Tag
774                 $data{'unit_tag'}= $unit_tag;
775         }
777         # Fill release if available
778         my $FAIclass= $entry->get_value("FAIclass");
779         if (defined $FAIclass && $FAIclass =~ /^.* :([A-Za-z0-9\/.]+).*$/) {
780                 $data{'release'}= $1;
781         }
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];
794         my $gotoHardwareChecksum= $msg_hash->{detected_hardware}[0]->{gotoHardwareChecksum};
796     my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address'";
797     my $res = $main::known_clients_db->select_dbentry( $sql_statement );
799     # check hit
800     my $hit_counter = keys %{$res};
801     if( not $hit_counter == 1 ) {
802         &main::daemon_log("ERROR: more or no hit found in known_clients_db by query by '$address'", 1);
803                 return;
804     }
806     my $macaddress = $res->{1}->{macaddress};
807     my $hostkey = $res->{1}->{hostkey};
809     if (not defined $macaddress) {
810         &main::daemon_log("ERROR: no mac address found for client $address", 1);
811         return;
812     }
813     # Build LDAP connection
814     my $ldap = Net::LDAP->new($ldap_uri);
815     if( not defined $ldap ) {
816         &main::daemon_log("ERROR: cannot connect to ldap: $ldap_uri", 1);
817         return;
818     } 
820     # Bind to a directory with dn and password
821     my $mesg= $ldap->bind($ldap_admin_dn, password => $ldap_admin_password);
823     # Perform search
824         $mesg = $ldap->search(
825                 base   => $ldap_base,
826                 scope  => 'sub',
827                 filter => "(&(objectClass=GOhard)(|(macAddress=$macaddress)(dhcpHWaddress=ethernet $macaddress)))"
828         );
830         # We need to create a base entry first (if not done from ArpHandler)
831         if($mesg->count == 0) {
832                 &main::daemon_log("Need to create a new LDAP Entry for client $address", 1);
833                 my $resolver=Net::DNS::Resolver->new;
834                 my $ipaddress= $1 if $address =~ /^([0-9\.]*?):.*$/;
835                 my $dnsresult= $resolver->search($ipaddress);
836                 my $dnsname= (defined($dnsresult))?$dnsresult->{answer}[0]->{ptrdname}:$ipaddress;
837                 my $cn = (($dnsname =~ /^(\d){1,3}\.(\d){1,3}\.(\d){1,3}\.(\d){1,3}/) ? $dnsname : sprintf "%s", $dnsname =~ /([^\.]+)\.?/);
838                 my $dn = "cn=$cn,ou=incoming,$ldap_base";
839                 &main::daemon_log("Creating entry for $dn",6);
840                 my $entry= Net::LDAP::Entry->new( $dn );
841                 $entry->dn($dn);
842                 $entry->add("objectClass" => "goHard");
843                 $entry->add("cn" => $cn);
844                 $entry->add("macAddress" => $macaddress);
845                 $entry->add("gotomode" => "locked");
846                 $entry->add("gotoSysStatus" => "new-system");
847                 $entry->add("ipHostNumber" => $ipaddress);
848                 if(defined($gosa_unit_tag) && length($gosa_unit_tag) > 0) {
849                         $entry->add("objectClass" => "gosaAdministrativeUnit");
850                         $entry->add("gosaUnitTag" => $gosa_unit_tag);
851                 }
852                 if(my $res=$entry->update($ldap)) {
853                         # Fill $mesg again
854                         $mesg = $ldap->search(
855                                 base   => $ldap_base,
856                                 scope  => 'sub',
857                                 filter => "(&(objectClass=GOhard)(|(macAddress=$macaddress)(dhcpHWaddress=ethernet $macaddress)))"
858                         );
859                 } else {
860                         &main::daemon_log("ERROR: There was a problem adding the entry", 1);
861                 }
863         }
864         
865         if($mesg->count == 1) {
866                 my $entry= $mesg->entry(0);
867                 $entry->changetype("modify");
868                 foreach my $attribute (
869                         "gotoSndModule", "ghNetNic", "gotoXResolution", "ghSoundAdapter", "ghCpuType", "gotoXkbModel", 
870                         "ghGfxAdapter", "gotoXMousePort", "ghMemSize", "gotoXMouseType", "ghUsbSupport", "gotoXHsync", 
871                         "gotoXDriver", "gotoXVsync", "gotoXMonitor", "gotoHardwareChecksum") {
872                         if(defined($msg_hash->{detected_hardware}[0]->{$attribute})) {
873                                 if(defined($entry->get_value($attribute))) {
874                                         $entry->delete($attribute);
875                                 }
876                                 &main::daemon_log("Adding attribute $attribute with value ".$msg_hash->{detected_hardware}[0]->{$attribute},1);
877                                 $entry->add($attribute => $msg_hash->{detected_hardware}[0]->{$attribute});     
878                         }
879                 }
880                 foreach my $attribute (
881                         "gotoModules", "ghScsiDev", "ghIdeDev") {
882                         if(defined($msg_hash->{detected_hardware}[0]->{$attribute})) {
883                                 if(defined($entry->get_value($attribute))) {
884                                         $entry->delete($attribute);
885                                 }
886                                 foreach my $array_entry (@{$msg_hash->{detected_hardware}[0]->{$attribute}}) {
887                                         $entry->add($attribute => $array_entry);
888                                 }
889                         }
891                 }
893                 if($entry->update($ldap)) {
894                         &main::daemon_log("Added Hardware configuration to LDAP", 4);
895                 }
897         }
898         return;
900 #===  FUNCTION  ================================================================
901 #         NAME:  hardware_config
902 #   PARAMETERS:  address - string - ip address and port of a host
903 #      RETURNS:  
904 #  DESCRIPTION:  
905 #===============================================================================
906 sub hardware_config {
907         my ($address, $gotoHardwareChecksum) = @_ ;
909         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address'";
910         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
912         # check hit
913         my $hit_counter = keys %{$res};
914         if( not $hit_counter == 1 ) {
915                 &main::daemon_log("ERROR: more or no hit found in known_clients_db by query by '$address'", 1);
916         }
918         my $macaddress = $res->{1}->{macaddress};
919         my $hostkey = $res->{1}->{hostkey};
921         if (not defined $macaddress) {
922                 &main::daemon_log("ERROR: no mac address found for client $address", 1);
923                 return;
924         }
926         # Build LDAP connection
927         my $ldap = Net::LDAP->new($ldap_uri);
928         if( not defined $ldap ) {
929                 &main::daemon_log("ERROR: cannot connect to ldap: $ldap_uri", 1);
930                 return;
931         } 
933         # Bind to a directory with dn and password
934         my $mesg= $ldap->bind($ldap_admin_dn, password => $ldap_admin_password);
936         # Perform search
937         $mesg = $ldap->search(
938                 base   => $ldap_base,
939                 scope  => 'sub',
940                 filter => "(&(objectClass=GOhard)(|(macAddress=$macaddress)(dhcpHWaddress=ethernet $macaddress)))"
941         );
943         if($mesg->count() == 0) {
944                 &main::daemon_log("Host was not found in LDAP!", 1);
945         } else {
946                 my $entry= $mesg->entry(0);
947                 my $dn= $entry->dn;
948                 if(defined($entry->get_value("gotoHardwareChecksum"))) {
949                         if(! $entry->get_value("gotoHardwareChecksum") eq $gotoHardwareChecksum) {
950                                 $entry->replace(gotoHardwareChecksum => $gotoHardwareChecksum);
951                                 if($entry->update($ldap)) {
952                                         &main::daemon_log("Hardware changed! Detection triggered.", 4);
953                                 }
954                         } else {
955                                 # Nothing to do
956                                 return;
957                         }
958                 }
959         } 
960         # need to fill it to LDAP
961         #$entry->add(gotoHardwareChecksum => $gotoHardwareChecksum);
962         #if($entry->update($ldap)) {
963         #               &main::daemon_log("gotoHardwareChecksum $gotoHardwareChecksum was added to LDAP", 4);
964         #}
966         ## Look if there another host with this checksum to use the hardware config
967         #$mesg = $ldap->search(
968         #       base   => $ldap_base,
969         #       scope  => 'sub',
970         #       filter => "(&(objectClass=GOhard)(gotoHardwareChecksum=$gotoHardwareChecksum))"
971         #);
973         #if($mesg->count>1) {
974         #       my $clone_entry= $mesg->entry(0);
975         #       $entry->changetype("modify");
976         #       foreach my $attribute (
977         #               "gotoSndModule", "ghNetNic", "gotoXResolution", "ghSoundAdapter", "ghCpuType", "gotoXkbModel", 
978         #               "ghGfxAdapter", "gotoXMousePort", "ghMemSize", "gotoXMouseType", "ghUsbSupport", "gotoXHsync", 
979         #               "gotoXDriver", "gotoXVsync", "gotoXMonitor") {
980         #               my $value= $clone_entry->get_value($attribute);
981         #               if(defined($value)) {
982         #                       if(defined($entry->get_value($attribute))) {
983         #                               $entry->delete($attribute);
984         #                       }
985         #                       &main::daemon_log("Adding attribute $attribute with value $value",1);
986         #                       $entry->add($attribute => $value);
987         #               }
988         #       }
989         #       foreach my $attribute (
990         #               "gotoModules", "ghScsiDev", "ghIdeDev") {
991         #               my $array= $clone_entry->get_value($attribute, 'as_ref' => 1);
992         #               if(defined($array))     {
993         #                       if(defined($entry->get_value($attribute))) {
994         #                               $entry->delete($attribute);
995         #                       }
996         #                       foreach my $array_entry (@{$array}) {
997         #                               $entry->add($attribute => $array_entry);
998         #                       }
999         #               }
1001         #       }
1002         #       if($entry->update($ldap)) {
1003         #               &main::daemon_log("Added Hardware configuration to LDAP", 4);
1004         #       }
1006         #}
1009         # Assemble data package
1010         my %data = ();
1012         # Need to append GOto settings?
1013         if (defined $goto_admin and defined $goto_secret){
1014                 $data{'goto_admin'}= $goto_admin;
1015                 $data{'goto_secret'}= $goto_secret;
1016         }
1018         # Unbind
1019         $mesg = $ldap->unbind;
1021         &main::daemon_log("Send detect_hardware message to $address", 4);
1023         # Send information
1024         return send_msg("detect_hardware", $server_address, $address, \%data);
1027 sub server_matches {
1028         my $target = shift;
1029         my $target_ip = sprintf("%s", $target =~ /^([0-9\.]*?):.*$/);
1030         my $result = 0;
1032         if($server_ip eq $target_ip) {
1033                 $result= 1;
1034         } elsif ($server_ip eq "0.0.0.0") {     
1035                 if ($target_ip eq "127.0.0.1") {
1036                         $result= 1;
1037                 } else {
1038                         my $PROC_NET_ROUTE= ('/proc/net/route');
1040                         open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
1041                                 or die "Could not open $PROC_NET_ROUTE";
1043                         my @ifs = <PROC_NET_ROUTE>;
1045                         close(PROC_NET_ROUTE);
1047                         # Eat header line
1048                         shift @ifs;
1049                         chomp @ifs;
1050                         foreach my $line(@ifs) {
1051                                 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
1052                                 my $destination;
1053                                 my $mask;
1054                                 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
1055                                 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
1056                                 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
1057                                 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
1058                                 if(new NetAddr::IP($target_ip)->within(new NetAddr::IP($destination, $mask))) {
1059                                         # destination matches route, save mac and exit
1060                                         $result= 1;
1061                                         last;
1062                                 }
1063                         }
1064                 }
1065         } else {
1066                 &main::daemon_log("Target ip $target_ip does not match Server ip $server_ip",1);
1067         }
1069         return $result;
1073 #===  FUNCTION  ================================================================
1074 #         NAME:  execute_actions
1075 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
1076 #      RETURNS:  nothing
1077 #  DESCRIPTION:  invokes the script specified in msg_hash which is located under
1078 #                /etc/gosad/actions
1079 #===============================================================================
1080 sub execute_actions {
1081     my ($msg_hash) = @_ ;
1082     my $configdir= '/etc/gosad/actions/';
1083     my $result;
1085     my $header = @{$msg_hash->{header}}[0];
1086     my $source = @{$msg_hash->{source}}[0];
1087     my $target = @{$msg_hash->{target}}[0];
1088  
1089     if((not defined $source)
1090             && (not defined $target)
1091             && (not defined $header)) {
1092         &main::daemon_log("ERROR: Entries missing in XML msg for gosad actions under /etc/gosad/actions");
1093     } else {
1094         my $parameters="";
1095         my @params = @{$msg_hash->{$header}};
1096         my $params = join(", ", @params);
1097         &main::daemon_log("execute_actions: got parameters: $params", 5);
1099         if (@params) {
1100             foreach my $param (@params) {
1101                 my $param_value = (&get_content_from_xml_hash($msg_hash, $param))[0];
1102                 &main::daemon_log("execute_actions: parameter -> value: $param -> $param_value", 7);
1103                 $parameters.= " ".$param_value;
1104             }
1105         }
1107         my $cmd= $configdir.$header."$parameters";
1108         &main::daemon_log("execute_actions: executing cmd: $cmd", 7);
1109         $result= "";
1110         open(PIPE, "$cmd 2>&1 |");
1111         while(<PIPE>) {
1112             $result.=$_;
1113         }
1114         close(PIPE);
1115     }
1117     # process the event result
1120     return;
1124 1;