Code

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