Code

Correct syntax (hope so) - vacumm table has no effect.
[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;
20 my $event_dir = "/usr/lib/gosa-si/server/events";
21 use lib "/usr/lib/gosa-si/server/events";
23 BEGIN{}
24 END {}
26 my ($server_ip, $server_port, $SIPackages_key, $max_clients, $ldap_uri, $ldap_base, $ldap_admin_dn, $ldap_admin_password, $server_interface);
27 my ($bus_activ, $bus_key, $bus_ip, $bus_port);
28 my $server;
29 my $event_hash;
30 my $network_interface;
31 my $no_bus;
32 my (@ldap_cfg, @pam_cfg, @nss_cfg, $goto_admin, $goto_secret);
33 my $mesg;
35 my %cfg_defaults = (
36 "bus" => {
37     "activ" => [\$bus_activ, "on"],
38     "key" => [\$bus_key, ""],
39     "ip" => [\$bus_ip, ""],
40     "port" => [\$bus_port, "20080"],
41     },
42 "server" => {
43     "ip" => [\$server_ip, "0.0.0.0"],
44     "mac-address" => [\$main::server_mac_address, "00:00:00:00:00"],
45     "port" => [\$server_port, "20081"],
46     "ldap-uri" => [\$ldap_uri, ""],
47     "ldap-base" => [\$ldap_base, ""],
48     "ldap-admin-dn" => [\$ldap_admin_dn, ""],
49     "ldap-admin-password" => [\$ldap_admin_password, ""],
50     "max-clients" => [\$max_clients, 100],
51     },
52 "SIPackages" => {
53     "key" => [\$SIPackages_key, ""],
54     },
55 );
57 ### START #####################################################################
59 # read configfile and import variables
60 &read_configfile();
63 # if server_ip is not an ip address but a name
64 if( inet_aton($server_ip) ){ $server_ip = inet_ntoa(inet_aton($server_ip)); } 
65 $network_interface= &get_interface_for_ip($server_ip);
66 $main::server_mac_address= &get_mac($network_interface);
68 &import_events();
70 # Unit tag can be defined in config
71 if((not defined($main::gosa_unit_tag)) || length($main::gosa_unit_tag) == 0) {
72         # Read gosaUnitTag from LDAP
73         
74     my $ldap_handle = &main::get_ldap_handle(); 
75     if( defined($ldap_handle) ) {
76                 &main::daemon_log("INFO: Searching for servers gosaUnitTag with mac address $main::server_mac_address",5);
77                 # Perform search for Unit Tag
78                 $mesg = $ldap_handle->search(
79                         base   => $ldap_base,
80                         scope  => 'sub',
81                         attrs  => ['gosaUnitTag'],
82                         filter => "(macaddress=$main::server_mac_address)"
83                 );
85                 if ($mesg->count == 1) {
86                         my $entry= $mesg->entry(0);
87                         my $unit_tag= $entry->get_value("gosaUnitTag");
88                         $main::ldap_server_dn= $mesg->entry(0)->dn;
89                         if(defined($unit_tag) && length($unit_tag) > 0) {
90                                 &main::daemon_log("INFO: Detected gosaUnitTag $unit_tag for creating entries", 5);
91                                 $main::gosa_unit_tag= $unit_tag;
92                         }
93                 } else {
94                         # Perform another search for Unit Tag
95                         my $hostname= `hostname -f`;
96                         chomp($hostname);
97                         &main::daemon_log("INFO: Searching for servers gosaUnitTag with hostname $hostname",5);
98                         $mesg = $ldap_handle->search(
99                                 base   => $ldap_base,
100                                 scope  => 'sub',
101                                 attrs  => ['gosaUnitTag'],
102                                 filter => "(&(cn=$hostname)(objectClass=goServer))"
103                         );
104                         if ($mesg->count == 1) {
105                                 my $entry= $mesg->entry(0);
106                                 my $unit_tag= $entry->get_value("gosaUnitTag");
107                                 $main::ldap_server_dn= $mesg->entry(0)->dn;
108                                 if(defined($unit_tag) && length($unit_tag) > 0) {
109                                         &main::daemon_log("INFO: Detected gosaUnitTag $unit_tag for creating entries", 5);
110                                         $main::gosa_unit_tag= $unit_tag;
111                                 }
112                         } else {
113                                 # Perform another search for Unit Tag
114                                 $hostname= `hostname -s`;
115                                 chomp($hostname);
116                                 &main::daemon_log("INFO: Searching for servers gosaUnitTag with hostname $hostname",5);
117                                 $mesg = $ldap_handle->search(
118                                         base   => $ldap_base,
119                                         scope  => 'sub',
120                                         attrs  => ['gosaUnitTag'],
121                                         filter => "(&(cn=$hostname)(objectClass=goServer))"
122                                 );
123                                 if ($mesg->count == 1) {
124                                         my $entry= $mesg->entry(0);
125                                         my $unit_tag= $entry->get_value("gosaUnitTag");
126                                         $main::ldap_server_dn= $mesg->entry(0)->dn;
127                                         if(defined($unit_tag) && length($unit_tag) > 0) {
128                                                 &main::daemon_log("INFO: Detected gosaUnitTag $unit_tag for creating entries", 5);
129                                                 $main::gosa_unit_tag= $unit_tag;
130                                         }
131                                 } else {
132                                         &main::daemon_log("WARNING: No gosaUnitTag detected. Not using gosaUnitTag", 3);
133                                 }
134                         }
135                 }
136         } else {
137                 &main::daemon_log("INFO: Using gosaUnitTag from config-file: $main::gosa_unit_tag",5);
138         }
142 my $server_address = "$server_ip:$server_port";
143 $main::server_address = $server_address;
146 if( inet_aton($bus_ip) ){ $bus_ip = inet_ntoa(inet_aton($bus_ip)); } 
147 ######################################################
148 # to change
149 if( $bus_ip eq "127.0.1.1" ) { $bus_ip = "127.0.0.1" }
150 ######################################################
151 my $bus_address = "$bus_ip:$bus_port";
152 $main::bus_address = $bus_address;
154 # create general settings for this module
155 my $xml = new XML::Simple();
157 # register at bus
158 if ($main::no_bus > 0) {
159     $bus_activ = "off"
161 if($bus_activ eq "on") {
162     &register_at_bus();
165 # add myself to known_server_db
166 my $res = $main::known_server_db->add_dbentry( {table=>'known_server',
167         primkey=>['hostname'],
168         hostname=>$server_address,
169         status=>'myself',
170         hostkey=>$SIPackages_key,
171         timestamp=>&get_time,
172         } );
176 ### functions #################################################################
179 sub get_module_info {
180     my @info = ($server_address,
181                 $SIPackages_key,
182                 );
183     return \@info;
187 #===  FUNCTION  ================================================================
188 #         NAME:  read_configfile
189 #   PARAMETERS:  cfg_file - string -
190 #      RETURNS:  nothing
191 #  DESCRIPTION:  read cfg_file and set variables
192 #===============================================================================
193 sub read_configfile {
194     my $cfg;
195     if( defined( $main::cfg_file) && ( (-s $main::cfg_file) > 0 )) {
196         if( -r $main::cfg_file ) {
197             $cfg = Config::IniFiles->new( -file => $main::cfg_file );
198         } else {
199             print STDERR "Couldn't read config file!";
200         }
201     } else {
202         $cfg = Config::IniFiles->new() ;
203     }
204     foreach my $section (keys %cfg_defaults) {
205         foreach my $param (keys %{$cfg_defaults{ $section }}) {
206             my $pinfo = $cfg_defaults{ $section }{ $param };
207             ${@$pinfo[0]} = $cfg->val( $section, $param, @$pinfo[1] );
208         }
209     }
211     # Read non predefined sections
212     my $param;
213     if ($cfg->SectionExists('ldap')){
214                 foreach $param ($cfg->Parameters('ldap')){
215                         push (@ldap_cfg, "$param ".$cfg->val('ldap', $param));
216                 }
217     }
218     if ($cfg->SectionExists('pam_ldap')){
219                 foreach $param ($cfg->Parameters('pam_ldap')){
220                         push (@pam_cfg, "$param ".$cfg->val('pam_ldap', $param));
221                 }
222     }
223     if ($cfg->SectionExists('nss_ldap')){
224                 foreach $param ($cfg->Parameters('nss_ldap')){
225                         push (@nss_cfg, "$param ".$cfg->val('nss_ldap', $param));
226                 }
227     }
228     if ($cfg->SectionExists('goto')){
229         $goto_admin= $cfg->val('goto', 'terminal_admin');
230         $goto_secret= $cfg->val('goto', 'terminal_secret');
231     } else {
232         $goto_admin= undef;
233         $goto_secret= undef;
234     }
238 #===  FUNCTION  ================================================================
239 #         NAME:  get_interface_for_ip
240 #   PARAMETERS:  ip address (i.e. 192.168.0.1)
241 #      RETURNS:  array: list of interfaces if ip=0.0.0.0, matching interface if found, undef else
242 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
243 #===============================================================================
244 sub get_interface_for_ip {
245         my $result;
246         my $ip= shift;
247         if ($ip && length($ip) > 0) {
248                 my @ifs= &get_interfaces();
249                 if($ip eq "0.0.0.0") {
250                         $result = "all";
251                 } else {
252                         foreach (@ifs) {
253                                 my $if=$_;
254                                 if(&main::get_ip($if) eq $ip) {
255                                         $result = $if;
256                                 }
257                         }       
258                 }
259         }       
260         return $result;
263 #===  FUNCTION  ================================================================
264 #         NAME:  get_interfaces 
265 #   PARAMETERS:  none
266 #      RETURNS:  (list of interfaces) 
267 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
268 #===============================================================================
269 sub get_interfaces {
270         my @result;
271         my $PROC_NET_DEV= ('/proc/net/dev');
273         open(PROC_NET_DEV, "<$PROC_NET_DEV")
274                 or die "Could not open $PROC_NET_DEV";
276         my @ifs = <PROC_NET_DEV>;
278         close(PROC_NET_DEV);
280         # Eat first two line
281         shift @ifs;
282         shift @ifs;
284         chomp @ifs;
285         foreach my $line(@ifs) {
286                 my $if= (split /:/, $line)[0];
287                 $if =~ s/^\s+//;
288                 push @result, $if;
289         }
291         return @result;
294 #===  FUNCTION  ================================================================
295 #         NAME:  get_mac 
296 #   PARAMETERS:  interface name (i.e. eth0)
297 #      RETURNS:  (mac address) 
298 #  DESCRIPTION:  Uses ioctl to get mac address directly from system.
299 #===============================================================================
300 sub get_mac {
301         my $ifreq= shift;
302         my $result;
303         if ($ifreq && length($ifreq) > 0) { 
304                 if($ifreq eq "all") {
305                         $result = "00:00:00:00:00:00";
306                 } else {
307                         my $SIOCGIFHWADDR= 0x8927;     # man 2 ioctl_list
309                         # A configured MAC Address should always override a guessed value
310                         if ($main::server_mac_address and length($main::server_mac_address) > 0) {
311                                 $result= $main::server_mac_address;
312                         }
314                         socket SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('ip')
315                                 or die "socket: $!";
317                         if(ioctl SOCKET, $SIOCGIFHWADDR, $ifreq) {
318                                 my ($if, $mac)= unpack 'h36 H12', $ifreq;
320                                 if (length($mac) > 0) {
321                                         $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])$/;
322                                         $mac= sprintf("%s:%s:%s:%s:%s:%s", $1, $2, $3, $4, $5, $6);
323                                         $result = $mac;
324                                 }
325                         }
326                 }
327         }
328         return $result;
332 #===  FUNCTION  ================================================================
333 #         NAME:  register_at_bus
334 #   PARAMETERS:  nothing
335 #      RETURNS:  nothing
336 #  DESCRIPTION:  creates an entry in known_daemons and send a 'here_i_am' msg to bus
337 #===============================================================================
338 sub register_at_bus {
340     # add bus to known_server_db
341     my $res = $main::known_server_db->add_dbentry( {table=>'known_server',
342                                                     primkey=>['hostname'],
343                                                     hostname=>$bus_address,
344                                                     status=>'bus',
345                                                     hostkey=>$bus_key,
346                                                     timestamp=>&get_time,
347                                                 } );
348     my $msg_hash = &create_xml_hash("here_i_am", $server_address, $bus_address);
349     my $msg = &create_xml_string($msg_hash);
351     &main::send_msg_to_target($msg, $bus_address, $bus_key, "here_i_am");
352     return $msg;
356 sub import_events {
357     if (not -e $event_dir) {
358         &main::daemon_log("S ERROR: cannot find directory or directory is not readable: $event_dir", 1);   
359     }
360     opendir (DIR, $event_dir) or die "ERROR while loading gosa-si-events from directory $event_dir : $!\n";
362     while (defined (my $event = readdir (DIR))) {
363         if( $event eq "." || $event eq ".." ) { next; }  
364         if( $event eq "gosaTriggered.pm" ) { next; }    # only GOsa specific events
366         eval{ require $event; };
367         if( $@ ) {
368             &main::daemon_log("S ERROR: import of event module '$event' failed", 1);
369             &main::daemon_log("$@", 8);
370             next;
371         }
373         $event =~ /(\S*?).pm$/;
374         my $event_module = $1;
375         my $events_l = eval( $1."::get_events()") ;
376         foreach my $event_name (@{$events_l}) {
377             $event_hash->{$event_name} = $event_module;
378         }
379         my $events_string = join( ", ", @{$events_l});
380         &main::daemon_log("S DEBUG: SIPackages imported events $events_string", 8);
381     }
385 #===  FUNCTION  ================================================================
386 #         NAME:  process_incoming_msg
387 #   PARAMETERS:  crypted_msg - string - incoming crypted message
388 #      RETURNS:  nothing
389 #  DESCRIPTION:  handels the proceeded distribution to the appropriated functions
390 #===============================================================================
391 sub process_incoming_msg {
392     my ($msg, $msg_hash, $session_id) = @_ ;
393     my $error = 0;
394     my $host_name;
395     my $host_key;
396     my @out_msg_l = ("nohandler");
398     # process incoming msg
399     my $header = @{$msg_hash->{header}}[0]; 
400     my @target_l = @{$msg_hash->{target}};
402     # skip PREFIX
403     $header =~ s/^CLMSG_//;
405     &main::daemon_log("$session_id DEBUG: SIPackages: msg to process: $header", 7);
407     if( 0 == length @target_l){     
408         &main::daemon_log("$session_id ERROR: no target specified for msg $header", 1);
409         $error++;
410     }
412     if( 1 == length @target_l) {
413         my $target = $target_l[0];
414                 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, $msg_hash, $session_id)
421             } else {
422                 if( exists $event_hash->{$header} ) {
423                     # a event exists with the header as name
424                     &main::daemon_log("$session_id INFO: found event '$header' at event-module '".$event_hash->{$header}."'", 5);
425                     no strict 'refs';
426                     @out_msg_l = &{$event_hash->{$header}."::$header"}($msg, $msg_hash, $session_id);
427                 }
428             }
430             # if delivery not possible raise error and return 
431             if( not defined $out_msg_l[0] ) {
432                 @out_msg_l = ();
433             } elsif( $out_msg_l[0] eq 'nohandler') {
434                 &main::daemon_log("$session_id ERROR: SIPackages: no event handler or core function defined for '$header'", 1);
435                 @out_msg_l = ();
436             } 
438         }
439                 else {
440                         &main::daemon_log("INFO: msg is not for gosa-si-server '$server_address', deliver it to target '$target'", 5);
441                         push(@out_msg_l, $msg);
442                 }
443     }
445     return \@out_msg_l;
449 #===  FUNCTION  ================================================================
450 #         NAME:  new_passwd
451 #   PARAMETERS:  msg_hash - ref - hash from function create_xml_hash
452 #      RETURNS:  nothing
453 #  DESCRIPTION:  process this incoming message
454 #===============================================================================
455 sub new_key {
456     my ($msg_hash) = @_;
457     my @out_msg_l;
458     
459     my $header = @{$msg_hash->{header}}[0];
460     my $source_name = @{$msg_hash->{source}}[0];
461     my $source_key = @{$msg_hash->{new_key}}[0];
462     my $query_res;
464     # check known_clients_db
465     my $sql_statement = "SELECT * FROM known_clients WHERE hostname='$source_name'";
466     $query_res = $main::known_clients_db->select_dbentry( $sql_statement );
467     if( 1 == keys %{$query_res} ) {
468         my $act_time = &get_time;
469         my $sql_statement= "UPDATE known_clients ".
470             "SET hostkey='$source_key', timestamp='$act_time' ".
471             "WHERE hostname='$source_name'";
472         my $res = $main::known_clients_db->update_dbentry( $sql_statement );
473         my $hash = &create_xml_hash("confirm_new_key", $server_address, $source_name);
474         my $out_msg = &create_xml_string($hash);
475         push(@out_msg_l, $out_msg);
476     }
478     # only do if host still not found
479     if( 0 == @out_msg_l ) {
480         # check known_server_db
481         $sql_statement = "SELECT * FROM known_server WHERE hostname='$source_name'";
482         $query_res = $main::known_server_db->select_dbentry( $sql_statement );
483         if( 1 == keys %{$query_res} ) {
484             my $act_time = &get_time;
485             my $sql_statement= "UPDATE known_server ".
486                 "SET hostkey='$source_key', timestamp='$act_time' ".
487                 "WHERE hostname='$source_name'";
488             my $res = $main::known_server_db->update_dbentry( $sql_statement );
490             my $hash = &create_xml_hash("confirm_new_key", $server_address, $source_name);
491             my $out_msg = &create_xml_string($hash);
492             push(@out_msg_l, $out_msg);
493         }
494     }
496     return @out_msg_l;
500 #===  FUNCTION  ================================================================
501 #         NAME:  here_i_am
502 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
503 #      RETURNS:  nothing
504 #  DESCRIPTION:  process this incoming message
505 #===============================================================================
506 sub here_i_am {
507     my ($msg, $msg_hash, $session_id) = @_;
508     my @out_msg_l;
509     my $out_hash;
511     my $source = @{$msg_hash->{source}}[0];
512     my $mac_address = @{$msg_hash->{mac_address}}[0];
513         my $gotoHardwareChecksum = @{$msg_hash->{gotoHardwareChecksum}}[0];
515     # number of known clients
516     my $nu_clients= $main::known_clients_db->count_dbentries('known_clients');
518     # check wether client address or mac address is already known
519     my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$source'";
520     my $db_res= $main::known_clients_db->select_dbentry( $sql_statement );
521     
522     if ( 1 == keys %{$db_res} ) {
523         &main::daemon_log("$session_id WARNING: $source is already known as a client", 1);
524         &main::daemon_log("$session_id WARNING: values for $source are being overwritten", 1);   
525         $nu_clients --;
526     }
528     # number of actual activ clients
529     my $act_nu_clients = $nu_clients;
531     &main::daemon_log("$session_id INFO: number of actual activ clients: $act_nu_clients", 5);
532     &main::daemon_log("$session_id INFO: number of maximal allowed clients: $max_clients", 5);
534     if($max_clients <= $act_nu_clients) {
535         my $out_hash = &create_xml_hash("denied", $server_address, $source);
536         &add_content2xml_hash($out_hash, "denied", "I_cannot_take_any_more_clients!");
537         my $passwd = @{$msg_hash->{new_passwd}}[0]; 
538         &send_msg_hash2address($out_hash, $source, $passwd);
539         return;
540     }
541     
542     # new client accepted
543     my $new_passwd = @{$msg_hash->{new_passwd}}[0];
545     # create entry in known_clients
546     my $events = @{$msg_hash->{events}}[0];
547     
549     # add entry to known_clients_db
550     my $act_timestamp = &get_time;
551     my $res = $main::known_clients_db->add_dbentry( {table=>'known_clients', 
552                                                 primkey=>['hostname'],
553                                                 hostname=>$source,
554                                                 events=>$events,
555                                                 macaddress=>$mac_address,
556                                                 status=>'registered',
557                                                 hostkey=>$new_passwd,
558                                                 timestamp=>$act_timestamp,
559                                                 } );
561     if ($res != 0)  {
562         &main::daemon_log("$session_id ERROR: cannot add entry to known_clients: $res");
563         return;
564     }
565     
566     # return acknowledgement to client
567     $out_hash = &create_xml_hash("registered", $server_address, $source);
569     # notify registered client to bus
570     if( $bus_activ eq "on") {
571         # fetch actual bus key
572         my $sql_statement= "SELECT * FROM known_server WHERE status='bus'";
573         my $query_res = $main::known_server_db->select_dbentry( $sql_statement );
574         my $hostkey = $query_res->{1}->{'hostkey'};
576         # send update msg to bus
577         $out_hash = &create_xml_hash("new_client", $server_address, $bus_address, $source);
578         &add_content2xml_hash($out_hash, "macaddress", $mac_address);
579         &add_content2xml_hash($out_hash, "timestamp", $act_timestamp);
580         my $new_client_out = &create_xml_string($out_hash);
581         push(@out_msg_l, $new_client_out);
582         &main::daemon_log("$session_id INFO: send bus msg that client '$source' has registered at server '$server_address'", 5);
583     }
585     # give the new client his ldap config
586     # Workaround: Send within the registration response, if the client will get an ldap config later
587         my $new_ldap_config_out = &new_ldap_config($source, $session_id);
588         if($new_ldap_config_out && (!($new_ldap_config_out =~ /error/))) {
589                 &add_content2xml_hash($out_hash, "ldap_available", "true");
590         } elsif($new_ldap_config_out && $new_ldap_config_out =~ /error/){
591                 &add_content2xml_hash($out_hash, "error", $new_ldap_config_out);
593                 my $sql_statement = "UPDATE $main::job_queue_tn ".
594                 "SET status='error', result='$new_ldap_config_out' ".
595                 "WHERE status='processing' AND macaddress LIKE '$mac_address'";
596                 my $res = $main::job_db->update_dbentry($sql_statement);
597                 &main::daemon_log("$session_id DEBUG: $sql_statement RESULT: $res", 7);         
598         }
599     my $register_out = &create_xml_string($out_hash);
600     push(@out_msg_l, $register_out);
602     # Really send the ldap config
603     if( $new_ldap_config_out && (!($new_ldap_config_out =~ /error/))) {
604             push(@out_msg_l, $new_ldap_config_out);
605     }
607         my $hardware_config_out = &hardware_config($msg, $msg_hash, $session_id);
608         if( $hardware_config_out ) {
609                 push(@out_msg_l, $hardware_config_out);
610         }
612     return @out_msg_l;
616 #===  FUNCTION  ================================================================
617 #         NAME:  who_has
618 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
619 #      RETURNS:  nothing 
620 #  DESCRIPTION:  process this incoming message
621 #===============================================================================
622 sub who_has {
623     my ($msg_hash) = @_ ;
624     my @out_msg_l;
625     
626     # what is your search pattern
627     my $search_pattern = @{$msg_hash->{who_has}}[0];
628     my $search_element = @{$msg_hash->{$search_pattern}}[0];
629     &main::daemon_log("who_has-msg looking for $search_pattern $search_element", 7);
631     # scanning known_clients for search_pattern
632     my @host_addresses = keys %$main::known_clients;
633     my $known_clients_entries = length @host_addresses;
634     my $host_address;
635     foreach my $host (@host_addresses) {
636         my $client_element = $main::known_clients->{$host}->{$search_pattern};
637         if ($search_element eq $client_element) {
638             $host_address = $host;
639             last;
640         }
641     }
642         
643     # search was successful
644     if (defined $host_address) {
645         my $source = @{$msg_hash->{source}}[0];
646         my $out_hash = &create_xml_hash("who_has_i_do", $server_address, $source, "mac_address");
647         &add_content2xml_hash($out_hash, "mac_address", $search_element);
648         my $out_msg = &create_xml_string($out_hash);
649         push(@out_msg_l, $out_msg);
650     }
651     return @out_msg_l;
655 sub who_has_i_do {
656     my ($msg_hash) = @_ ;
657     my $header = @{$msg_hash->{header}}[0];
658     my $source = @{$msg_hash->{source}}[0];
659     my $search_param = @{$msg_hash->{$header}}[0];
660     my $search_value = @{$msg_hash->{$search_param}}[0];
661     print "\ngot msg $header:\nserver $source has client with $search_param $search_value\n";
665 #===  FUNCTION  ================================================================
666 #         NAME:  new_ldap_config
667 #   PARAMETERS:  address - string - ip address and port of a host
668 #      RETURNS:  gosa-si conform message
669 #  DESCRIPTION:  send to address the ldap configuration found for dn gotoLdapServer
670 #===============================================================================
671 sub new_ldap_config {
672         my ($address, $session_id) = @_ ;
674         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address' OR macaddress LIKE '$address'";
675         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
677         # check hit
678         my $hit_counter = keys %{$res};
679         if( not $hit_counter == 1 ) {
680                 &main::daemon_log("$session_id ERROR: more or no hit found in known_clients_db by query by '$address'", 1);
681         }
683     $address = $res->{1}->{hostname};
684         my $macaddress = $res->{1}->{macaddress};
685         my $hostkey = $res->{1}->{hostkey};
687         if (not defined $macaddress) {
688                 &main::daemon_log("$session_id ERROR: no mac address found for client $address", 1);
689                 return;
690         }
692         # Build LDAP connection
693     my $ldap_handle = &main::get_ldap_handle($session_id);
694         if( not defined $ldap_handle ) {
695                 &main::daemon_log("$session_id ERROR: cannot connect to ldap: $ldap_uri", 1);
696                 return;
697         } 
699         # Perform search
700     $mesg = $ldap_handle->search( base   => $ldap_base,
701                 scope  => 'sub',
702                 attrs => ['dn', 'gotoLdapServer', 'gosaUnitTag', 'FAIclass'],
703                 filter => "(&(objectClass=GOhard)(macaddress=$macaddress))");
704         if($mesg->code) {
705                 &main::daemon_log("$session_id ".$mesg->error, 1);
706                 return;
707         }
709         # Sanity check
710         if ($mesg->count != 1) {
711                 &main::daemon_log("$session_id WARNING: client with mac address $macaddress not found/unique/active - not sending ldap config".
712                 "\n\tbase: $ldap_base".
713                 "\n\tscope: sub".
714                 "\n\tattrs: dn, gotoLdapServer".
715                 "\n\tfilter: (&(objectClass=GOhard)(macaddress=$macaddress))", 1);
716                 return;
717         }
719         my $entry= $mesg->entry(0);
720         my $dn= $entry->dn;
721         my @servers= $entry->get_value("gotoLdapServer");
722         my $unit_tag= $entry->get_value("gosaUnitTag");
723         my @ldap_uris;
724         my $server;
725         my $base;
726         my $release;
728         # Fill release if available
729         my $FAIclass= $entry->get_value("FAIclass");
730         if (defined $FAIclass && $FAIclass =~ /^.* :([A-Za-z0-9\/.]+).*$/) {
731                 $release= $1;
732         }
734         # Do we need to look at an object class?
735         if (not @servers){
736                 $mesg = $ldap_handle->search( base   => $ldap_base,
737                         scope  => 'sub',
738                         attrs => ['dn', 'gotoLdapServer', 'FAIclass'],
739                         filter => "(&(objectClass=gosaGroupOfNames)(member=$dn))");
740                 #$mesg->code && die $mesg->error;
741                 if($mesg->code) {
742                         &main::daemon_log("$session_id ".$mesg->error, 1);
743                         return;
744                 }
746                 # Sanity check
747                 if ($mesg->count != 1) {
748                         &main::daemon_log("$session_id WARNING: no LDAP information found for client mac $macaddress", 1);
749                         return;
750                 }
752                 $entry= $mesg->entry(0);
753                 $dn= $entry->dn;
754                 @servers= $entry->get_value("gotoLdapServer");
756                 if (not defined $release){
757                         $FAIclass= $entry->get_value("FAIclass");
758                         if (defined $FAIclass && $FAIclass =~ /^.* :([A-Za-z0-9\/.]+).*$/) {
759                                 $release= $1;
760                         }
761                 }
762         }
764         @servers= sort (@servers);
766         foreach $server (@servers){
767                 # Conversation for backward compatibility
768                 if (not $server =~ /^\d+:[^:]+:ldap[^:]*:\/\// ) {
769                     if ($server =~ /^([^:]+):([^:]+)$/ ) {
770                       $server= "1:dummy:ldap://$1/$2";
771                     } elsif ($server =~ /^(\d+):([^:]+):(.*)$/ ) {
772                       $server= "$1:dummy:ldap://$2/$3";
773                     }
774                 }
776                 $base= $server;
777                 $server =~ s%^[^:]+:[^:]+:(ldap.*://[^/]+)/.*$%$1%;
778                 $base =~ s%^[^:]+:[^:]+:ldap.*://[^/]+/(.*)$%$1%;
779                 push (@ldap_uris, $server);
780         }
782         # Assemble data package
783         my %data = ( 'ldap_uri'  => \@ldap_uris, 'ldap_base' => $base,
784                 'ldap_cfg' => \@ldap_cfg, 'pam_cfg' => \@pam_cfg,'nss_cfg' => \@nss_cfg );
785         if (defined $release){
786                 $data{'release'}= $release;
787         }
789         # Need to append GOto settings?
790         if (defined $goto_admin and defined $goto_secret){
791                 $data{'goto_admin'}= $goto_admin;
792                 $data{'goto_secret'}= $goto_secret;
793         }
795         # Append unit tag if needed
796         if (defined $unit_tag){
798                 # Find admin base and department name
799                 $mesg = $ldap_handle->search( base   => $ldap_base,
800                         scope  => 'sub',
801                         attrs => ['dn', 'ou'],
802                         filter => "(&(objectClass=gosaAdministrativeUnit)(gosaUnitTag=$unit_tag))");
803                 #$mesg->code && die $mesg->error;
804                 if($mesg->code) {
805                         &main::daemon_log($mesg->error, 1);
806                         return "error-unit-tag-count-0";
807                 }
809                 # Sanity check
810                 if ($mesg->count != 1) {
811                         &main::daemon_log("WARNING: cannot find administrative unit for client with tag $unit_tag", 1);
812                         return "error-unit-tag-count-".$mesg->count;
813                 }
815                 $entry= $mesg->entry(0);
816                 $data{'admin_base'}= $entry->dn;
817                 $data{'department'}= $entry->get_value("ou");
819                 # Append unit Tag
820                 $data{'unit_tag'}= $unit_tag;
821         }
823         # Send information
824         return &build_msg("new_ldap_config", $server_address, $address, \%data);
828 #===  FUNCTION  ================================================================
829 #         NAME:  hardware_config
830 #   PARAMETERS:  address - string - ip address and port of a host
831 #      RETURNS:  
832 #  DESCRIPTION:  
833 #===============================================================================
834 sub hardware_config {
835         my ($msg, $msg_hash, $session_id) = @_ ;
836         my $address = @{$msg_hash->{source}}[0];
837         my $header = @{$msg_hash->{header}}[0];
838         my $gotoHardwareChecksum = @{$msg_hash->{gotoHardwareChecksum}}[0];
840         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address'";
841         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
843         # check hit
844         my $hit_counter = keys %{$res};
845         if( not $hit_counter == 1 ) {
846                 &main::daemon_log("$session_id ERROR: more or no hit found in known_clients_db by query by '$address'", 1);
847         }
848         my $macaddress = $res->{1}->{macaddress};
849         my $hostkey = $res->{1}->{hostkey};
851         if (not defined $macaddress) {
852                 &main::daemon_log("$session_id ERROR: no mac address found for client $address", 1);
853                 return;
854         }
856         # Build LDAP connection
857     my $ldap_handle = &main::get_ldap_handle($session_id);
858         if( not defined $ldap_handle ) {
859                 &main::daemon_log("$session_id ERROR: cannot connect to ldap: $ldap_uri", 1);
860                 return;
861         } 
863         # Perform search
864         $mesg = $ldap_handle->search(
865                 base   => $ldap_base,
866                 scope  => 'sub',
867                 filter => "(&(objectClass=GOhard)(|(macAddress=$macaddress)(dhcpHWaddress=ethernet $macaddress)))"
868         );
870         if($mesg->count() == 0) {
871                 &main::daemon_log("Host was not found in LDAP!", 1);
873                 # set status = hardware_detection at jobqueue if entry exists
874                 # TODO
875                 # resolve plain name for host
876                 my $func_dic = {table=>$main::job_queue_tn,
877                                 primkey=>[],
878                                 timestamp=>&get_time,
879                                 status=>'processing',
880                                 result=>'none',
881                                 progress=>'hardware-detection',
882                                 headertag=>'trigger_action_reinstall',
883                                 targettag=>$address,
884                                 xmlmessage=>'none',
885                                 macaddress=>$macaddress,
886                                 plainname=>'none',
887                 };
888                 my $hd_res = $main::job_db->add_dbentry($func_dic);
889                 &main::daemon_log("$session_id INFO: add '$macaddress' to job queue as an installing job", 5);
890         
891         } else {
892                 my $entry= $mesg->entry(0);
893                 my $dn= $entry->dn;
894                 if (defined($entry->get_value("gotoHardwareChecksum"))) {
895                         if (! $entry->get_value("gotoHardwareChecksum") eq $gotoHardwareChecksum) {
896                                 $entry->replace(gotoHardwareChecksum => $gotoHardwareChecksum);
897                                 if($entry->update($ldap_handle)) {
898                                         &main::daemon_log("$session_id INFO: Hardware changed! Detection triggered.", 5);
899                                 }
900                         } else {
901                                 # Nothing to do
902                                 return;
903                         }
904                 } 
905         } 
907         # Assemble data package
908         my %data = ();
910         # Need to append GOto settings?
911         if (defined $goto_admin and defined $goto_secret){
912                 $data{'goto_admin'}= $goto_admin;
913                 $data{'goto_secret'}= $goto_secret;
914         }
916         # Send information
917         return &build_msg("detect_hardware", $server_address, $address, \%data);
920 sub server_matches {
921         my $target = shift;
922         my $target_ip = ($1) if $target =~ /^([0-9\.]*?):.*$/;
923         if(!defined($target_ip) or length($target_ip) == 0) {
924                 return;
925         }
927         my $result = 0;
929         if($server_ip eq $target_ip) {
930                 $result= 1;
931         } elsif ($target_ip eq "0.0.0.0") {
932                 $result= 1;
933         } elsif ($server_ip eq "0.0.0.0") {     
934                 if ($target_ip eq "127.0.0.1") {
935                         $result= 1;
936                 } else {
937                         my $PROC_NET_ROUTE= ('/proc/net/route');
939                         open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
940                                 or die "Could not open $PROC_NET_ROUTE";
942                         my @ifs = <PROC_NET_ROUTE>;
944                         close(PROC_NET_ROUTE);
946                         # Eat header line
947                         shift @ifs;
948                         chomp @ifs;
949                         foreach my $line(@ifs) {
950                                 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
951                                 my $destination;
952                                 my $mask;
953                                 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
954                                 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
955                                 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
956                                 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
957                                 if(new NetAddr::IP($target_ip)->within(new NetAddr::IP($destination, $mask))) {
958                                         # destination matches route, save mac and exit
959                                         $result= 1;
960                                         last;
961                                 }
962                         }
963                 }
964         } else {
965                 &main::daemon_log("Target ip $target_ip does not match Server ip $server_ip",1);
966         }
968         return $result;
971 1;