Code

Added configuration file check
[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. 
8 use strict;
9 use warnings;
10 use GOSA::GosaSupportDaemon;
11 use IO::Socket::INET;
12 use XML::Simple;
13 use Data::Dumper;
14 use NetAddr::IP;
15 use Net::LDAP;
16 use Socket;
17 use Net::hostent;
19 my $event_dir = "/usr/lib/gosa-si/server/events";
20 use lib "/usr/lib/gosa-si/server/events";
22 BEGIN{}
23 END {}
25 my ($server_ip, $server_port, $SIPackages_key, $max_clients, $ldap_uri, $ldap_base, $ldap_admin_dn, $ldap_admin_password, $server_interface);
26 my ($bus_activ, $bus_key, $bus_ip, $bus_port);
27 my $server;
28 my $event_hash;
29 my $network_interface;
30 my $no_bus;
31 my (@ldap_cfg, @pam_cfg, @nss_cfg, $goto_admin, $goto_secret);
32 my $mesg;
34 my %cfg_defaults = (
35 "bus" => {
36     "activ" => [\$bus_activ, "on"],
37     "key" => [\$bus_key, ""],
38     "ip" => [\$bus_ip, ""],
39     "port" => [\$bus_port, "20080"],
40     },
41 "server" => {
42     "ip" => [\$server_ip, "0.0.0.0"],
43     "mac-address" => [\$main::server_mac_address, "00:00:00:00:00"],
44     "port" => [\$server_port, "20081"],
45     "ldap-uri" => [\$ldap_uri, ""],
46     "ldap-base" => [\$ldap_base, ""],
47     "ldap-admin-dn" => [\$ldap_admin_dn, ""],
48     "ldap-admin-password" => [\$ldap_admin_password, ""],
49     "max-clients" => [\$max_clients, 100],
50     },
51 "SIPackages" => {
52     "key" => [\$SIPackages_key, ""],
53     },
54 );
56 ### START #####################################################################
58 # read configfile and import variables
59 &read_configfile();
62 # if server_ip is not an ip address but a name
63 if( inet_aton($server_ip) ){ $server_ip = inet_ntoa(inet_aton($server_ip)); } 
64 $network_interface= &get_interface_for_ip($server_ip);
65 $main::server_mac_address= &get_mac($network_interface);
67 &import_events();
69 # Unit tag can be defined in config
70 if((not defined($main::gosa_unit_tag)) || length($main::gosa_unit_tag) == 0) {
71         # Read gosaUnitTag from LDAP
72         
73     my $ldap_handle = &main::get_ldap_handle(); 
74     if( defined($ldap_handle) ) {
75                 &main::daemon_log("INFO: Searching for servers gosaUnitTag with mac address $main::server_mac_address",5);
76                 # Perform search for Unit Tag
77                 $mesg = $ldap_handle->search(
78                         base   => $ldap_base,
79                         scope  => 'sub',
80                         attrs  => ['gosaUnitTag'],
81                         filter => "(macaddress=$main::server_mac_address)"
82                 );
84                 if ($mesg->count == 1) {
85                         my $entry= $mesg->entry(0);
86                         my $unit_tag= $entry->get_value("gosaUnitTag");
87                         $main::ldap_server_dn= $mesg->entry(0)->dn;
88                         if(defined($unit_tag) && length($unit_tag) > 0) {
89                                 &main::daemon_log("INFO: Detected gosaUnitTag $unit_tag for creating entries", 5);
90                                 $main::gosa_unit_tag= $unit_tag;
91                         }
92                 } else {
93                         # Perform another search for Unit Tag
94                         my $hostname= `hostname -f`;
95                         chomp($hostname);
96                         &main::daemon_log("INFO: Searching for servers gosaUnitTag with hostname $hostname",5);
97                         $mesg = $ldap_handle->search(
98                                 base   => $ldap_base,
99                                 scope  => 'sub',
100                                 attrs  => ['gosaUnitTag'],
101                                 filter => "(&(cn=$hostname)(objectClass=goServer))"
102                         );
103                         if ($mesg->count == 1) {
104                                 my $entry= $mesg->entry(0);
105                                 my $unit_tag= $entry->get_value("gosaUnitTag");
106                                 $main::ldap_server_dn= $mesg->entry(0)->dn;
107                                 if(defined($unit_tag) && length($unit_tag) > 0) {
108                                         &main::daemon_log("INFO: Detected gosaUnitTag $unit_tag for creating entries", 5);
109                                         $main::gosa_unit_tag= $unit_tag;
110                                 }
111                         } else {
112                                 # Perform another search for Unit Tag
113                                 $hostname= `hostname -s`;
114                                 chomp($hostname);
115                                 &main::daemon_log("INFO: Searching for servers gosaUnitTag with hostname $hostname",5);
116                                 $mesg = $ldap_handle->search(
117                                         base   => $ldap_base,
118                                         scope  => 'sub',
119                                         attrs  => ['gosaUnitTag'],
120                                         filter => "(&(cn=$hostname)(objectClass=goServer))"
121                                 );
122                                 if ($mesg->count == 1) {
123                                         my $entry= $mesg->entry(0);
124                                         my $unit_tag= $entry->get_value("gosaUnitTag");
125                                         $main::ldap_server_dn= $mesg->entry(0)->dn;
126                                         if(defined($unit_tag) && length($unit_tag) > 0) {
127                                                 &main::daemon_log("INFO: Detected gosaUnitTag $unit_tag for creating entries", 5);
128                                                 $main::gosa_unit_tag= $unit_tag;
129                                         }
130                                 } else {
131                                         &main::daemon_log("WARNING: No gosaUnitTag detected. Not using gosaUnitTag", 3);
132                                 }
133                         }
134                 }
135         } else {
136                 &main::daemon_log("INFO: Using gosaUnitTag from config-file: $main::gosa_unit_tag",5);
137         }
141 my $server_address = "$server_ip:$server_port";
142 $main::server_address = $server_address;
145 if( inet_aton($bus_ip) ){ $bus_ip = inet_ntoa(inet_aton($bus_ip)); } 
146 ######################################################
147 # to change
148 if( $bus_ip eq "127.0.1.1" ) { $bus_ip = "127.0.0.1" }
149 ######################################################
150 my $bus_address = "$bus_ip:$bus_port";
151 $main::bus_address = $bus_address;
153 # create general settings for this module
154 my $xml = new XML::Simple();
156 # register at bus
157 if ($main::no_bus > 0) {
158     $bus_activ = "off"
160 if($bus_activ eq "on") {
161     &register_at_bus();
164 # add myself to known_server_db
165 my $res = $main::known_server_db->add_dbentry( {table=>'known_server',
166         primkey=>['hostname'],
167         hostname=>$server_address,
168         status=>'myself',
169         hostkey=>$SIPackages_key,
170         timestamp=>&get_time,
171         } );
175 ### functions #################################################################
178 sub get_module_info {
179     my @info = ($server_address,
180                 $SIPackages_key,
181                 );
182     return \@info;
186 #===  FUNCTION  ================================================================
187 #         NAME:  read_configfile
188 #   PARAMETERS:  cfg_file - string -
189 #      RETURNS:  nothing
190 #  DESCRIPTION:  read cfg_file and set variables
191 #===============================================================================
192 sub read_configfile {
193     my $cfg;
194     if( defined( $main::cfg_file) && ( (-s $main::cfg_file) > 0 )) {
195         if( -r $main::cfg_file ) {
196             $cfg = Config::IniFiles->new( -file => $main::cfg_file );
197         } else {
198             print STDERR "Couldn't read config file!";
199         }
200     } else {
201         $cfg = Config::IniFiles->new() ;
202     }
203     foreach my $section (keys %cfg_defaults) {
204         foreach my $param (keys %{$cfg_defaults{ $section }}) {
205             my $pinfo = $cfg_defaults{ $section }{ $param };
206             ${@$pinfo[0]} = $cfg->val( $section, $param, @$pinfo[1] );
207         }
208     }
210     # Read non predefined sections
211     my $param;
212     if ($cfg->SectionExists('ldap')){
213                 foreach $param ($cfg->Parameters('ldap')){
214                         push (@ldap_cfg, "$param ".$cfg->val('ldap', $param));
215                 }
216     }
217     if ($cfg->SectionExists('pam_ldap')){
218                 foreach $param ($cfg->Parameters('pam_ldap')){
219                         push (@pam_cfg, "$param ".$cfg->val('pam_ldap', $param));
220                 }
221     }
222     if ($cfg->SectionExists('nss_ldap')){
223                 foreach $param ($cfg->Parameters('nss_ldap')){
224                         push (@nss_cfg, "$param ".$cfg->val('nss_ldap', $param));
225                 }
226     }
227     if ($cfg->SectionExists('goto')){
228         $goto_admin= $cfg->val('goto', 'terminal_admin');
229         $goto_secret= $cfg->val('goto', 'terminal_secret');
230     } else {
231         $goto_admin= undef;
232         $goto_secret= undef;
233     }
237 #===  FUNCTION  ================================================================
238 #         NAME:  get_interface_for_ip
239 #   PARAMETERS:  ip address (i.e. 192.168.0.1)
240 #      RETURNS:  array: list of interfaces if ip=0.0.0.0, matching interface if found, undef else
241 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
242 #===============================================================================
243 sub get_interface_for_ip {
244         my $result;
245         my $ip= shift;
246         if ($ip && length($ip) > 0) {
247                 my @ifs= &get_interfaces();
248                 if($ip eq "0.0.0.0") {
249                         $result = "all";
250                 } else {
251                         foreach (@ifs) {
252                                 my $if=$_;
253                                 if(&main::get_ip($if) eq $ip) {
254                                         $result = $if;
255                                 }
256                         }       
257                 }
258         }       
259         return $result;
262 #===  FUNCTION  ================================================================
263 #         NAME:  get_interfaces 
264 #   PARAMETERS:  none
265 #      RETURNS:  (list of interfaces) 
266 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
267 #===============================================================================
268 sub get_interfaces {
269         my @result;
270         my $PROC_NET_DEV= ('/proc/net/dev');
272         open(PROC_NET_DEV, "<$PROC_NET_DEV")
273                 or die "Could not open $PROC_NET_DEV";
275         my @ifs = <PROC_NET_DEV>;
277         close(PROC_NET_DEV);
279         # Eat first two line
280         shift @ifs;
281         shift @ifs;
283         chomp @ifs;
284         foreach my $line(@ifs) {
285                 my $if= (split /:/, $line)[0];
286                 $if =~ s/^\s+//;
287                 push @result, $if;
288         }
290         return @result;
293 #===  FUNCTION  ================================================================
294 #         NAME:  get_mac 
295 #   PARAMETERS:  interface name (i.e. eth0)
296 #      RETURNS:  (mac address) 
297 #  DESCRIPTION:  Uses ioctl to get mac address directly from system.
298 #===============================================================================
299 sub get_mac {
300         my $ifreq= shift;
301         my $result;
302         if ($ifreq && length($ifreq) > 0) { 
303                 if($ifreq eq "all") {
304                         $result = "00:00:00:00:00:00";
305                 } else {
306                         my $SIOCGIFHWADDR= 0x8927;     # man 2 ioctl_list
308                         # A configured MAC Address should always override a guessed value
309                         if ($main::server_mac_address and length($main::server_mac_address) > 0) {
310                                 $result= $main::server_mac_address;
311                         }
313                         socket SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('ip')
314                                 or die "socket: $!";
316                         if(ioctl SOCKET, $SIOCGIFHWADDR, $ifreq) {
317                                 my ($if, $mac)= unpack 'h36 H12', $ifreq;
319                                 if (length($mac) > 0) {
320                                         $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])$/;
321                                         $mac= sprintf("%s:%s:%s:%s:%s:%s", $1, $2, $3, $4, $5, $6);
322                                         $result = $mac;
323                                 }
324                         }
325                 }
326         }
327         return $result;
331 #===  FUNCTION  ================================================================
332 #         NAME:  register_at_bus
333 #   PARAMETERS:  nothing
334 #      RETURNS:  nothing
335 #  DESCRIPTION:  creates an entry in known_daemons and send a 'here_i_am' msg to bus
336 #===============================================================================
337 sub register_at_bus {
339     # add bus to known_server_db
340     my $res = $main::known_server_db->add_dbentry( {table=>'known_server',
341                                                     primkey=>['hostname'],
342                                                     hostname=>$bus_address,
343                                                     status=>'bus',
344                                                     hostkey=>$bus_key,
345                                                     timestamp=>&get_time,
346                                                 } );
347     my $msg_hash = &create_xml_hash("here_i_am", $server_address, $bus_address);
348     my $msg = &create_xml_string($msg_hash);
350     &main::send_msg_to_target($msg, $bus_address, $bus_key, "here_i_am");
351     return $msg;
355 sub import_events {
356     if (not -e $event_dir) {
357         &main::daemon_log("S ERROR: cannot find directory or directory is not readable: $event_dir", 1);   
358     }
359     opendir (DIR, $event_dir) or die "ERROR while loading gosa-si-events from directory $event_dir : $!\n";
361     while (defined (my $event = readdir (DIR))) {
362         if( $event eq "." || $event eq ".." ) { next; }  
363         if( $event eq "gosaTriggered.pm" ) { next; }    # only GOsa specific events
365         eval{ require $event; };
366         if( $@ ) {
367             &main::daemon_log("S ERROR: import of event module '$event' failed", 1);
368             &main::daemon_log("$@", 8);
369             next;
370         }
372         $event =~ /(\S*?).pm$/;
373         my $event_module = $1;
374         my $events_l = eval( $1."::get_events()") ;
375         foreach my $event_name (@{$events_l}) {
376             $event_hash->{$event_name} = $event_module;
377         }
378         my $events_string = join( ", ", @{$events_l});
379         &main::daemon_log("S DEBUG: SIPackages imported events $events_string", 8);
380     }
384 #===  FUNCTION  ================================================================
385 #         NAME:  process_incoming_msg
386 #   PARAMETERS:  crypted_msg - string - incoming crypted message
387 #      RETURNS:  nothing
388 #  DESCRIPTION:  handels the proceeded distribution to the appropriated functions
389 #===============================================================================
390 sub process_incoming_msg {
391     my ($msg, $msg_hash, $session_id) = @_ ;
392     my $error = 0;
393     my $host_name;
394     my $host_key;
395     my @out_msg_l = ("nohandler");
396     my $sql_events;
398     # process incoming msg
399     my $header = @{$msg_hash->{header}}[0]; 
400     my $source = @{$msg_hash->{source}}[0]; 
401     my @target_l = @{$msg_hash->{target}};
403     # skip PREFIX
404     $header =~ s/^CLMSG_//;
406     &main::daemon_log("$session_id DEBUG: SIPackages: msg to process: $header", 7);
408     if( 0 == length @target_l){     
409         &main::daemon_log("$session_id ERROR: no target specified for msg $header", 1);
410         $error++;
411     }
413     if( 1 == length @target_l) {
414         my $target = $target_l[0];
415                 if(&server_matches($target)) {
416             if ($header eq 'new_key') {
417                 @out_msg_l = &new_key($msg_hash)
418             } elsif ($header eq 'here_i_am') {
419                 @out_msg_l = &here_i_am($msg, $msg_hash, $session_id)
420             } else {
421                 if( exists $event_hash->{$header} ) {
422                     # a event exists with the header as name
423                     &main::daemon_log("$session_id INFO: found event '$header' at event-module '".$event_hash->{$header}."'", 5);
424                     no strict 'refs';
425                     @out_msg_l = &{$event_hash->{$header}."::$header"}($msg, $msg_hash, $session_id);
426                 } else {
427                     $sql_events = "SELECT * FROM $main::known_clients_tn WHERE ( (macaddress LIKE '$source') OR (hostname='$source') )"; 
428                     my $res = $main::known_clients_db->select_dbentry( $sql_events );
429                     my $l = keys(%$res);
431                     # set error if no or more than 1 hits are found for sql query
432                     if ( $l != 1) {
433                         @out_msg_l = ('knownclienterror');
435                     # found exact 1 hit in db
436                     } else {
437                         my $client_events = $res->{'1'}->{'events'};
439                         # client is registered for this event, deliver this message to client
440                         $header =~ s/^answer_//;
441                         if ($client_events =~ /,$header,/) {
442                             # answer message finally arrived destination server, so forward messages to GOsa
443                             if ($target eq $main::server_address) {        
444                                 $msg =~ s/<header>answer_/<header>/;
445                                 $msg =~ s/<target>\S+<\/target>/<target>GOSA<\/target>/;
446                             }
447                             @out_msg_l = ( $msg );
449                         # client is not registered for this event, set error
450                         } else {
451                             @out_msg_l = ('noeventerror');
452                         }
453                     }
454                 }
455             }
457             # if delivery not possible raise error and return 
458             if( not defined $out_msg_l[0] ) {
459                 @out_msg_l = ();
460             } elsif( $out_msg_l[0] eq 'nohandler') {
461                 &main::daemon_log("$session_id ERROR: SIPackages: no event handler or core function defined for '$header'", 1);
462                 @out_msg_l = ();
463             }  elsif ($out_msg_l[0] eq 'knownclienterror') {
464                 &main::daemon_log("$session_id ERROR: no or more than 1 hits are found at known_clients_db with sql query: '$sql_events'", 1);
465                 &main::daemon_log("$session_id WARNING: processing is aborted and message will not be forwarded");
466                 @out_msg_l = ();
467             } elsif ($out_msg_l[0] eq 'noeventerror') {
468                 &main::daemon_log("$session_id WARNING: client '$target' is not registered for event '$header', processing is aborted", 1); 
469                 @out_msg_l = ();
470             }
475         }
476                 else {
477                         &main::daemon_log("INFO: msg is not for gosa-si-server '$server_address', deliver it to target '$target'", 5);
478                         push(@out_msg_l, $msg);
479                 }
480     }
482     return \@out_msg_l;
486 #===  FUNCTION  ================================================================
487 #         NAME:  new_passwd
488 #   PARAMETERS:  msg_hash - ref - hash from function create_xml_hash
489 #      RETURNS:  nothing
490 #  DESCRIPTION:  process this incoming message
491 #===============================================================================
492 sub new_key {
493     my ($msg_hash) = @_;
494     my @out_msg_l;
495     
496     my $header = @{$msg_hash->{header}}[0];
497     my $source_name = @{$msg_hash->{source}}[0];
498     my $source_key = @{$msg_hash->{new_key}}[0];
499     my $query_res;
501     # check known_clients_db
502     my $sql_statement = "SELECT * FROM known_clients WHERE hostname='$source_name'";
503     $query_res = $main::known_clients_db->select_dbentry( $sql_statement );
504     if( 1 == keys %{$query_res} ) {
505         my $act_time = &get_time;
506         my $sql_statement= "UPDATE known_clients ".
507             "SET hostkey='$source_key', timestamp='$act_time' ".
508             "WHERE hostname='$source_name'";
509         my $res = $main::known_clients_db->update_dbentry( $sql_statement );
510         my $hash = &create_xml_hash("confirm_new_key", $server_address, $source_name);
511         my $out_msg = &create_xml_string($hash);
512         push(@out_msg_l, $out_msg);
513     }
515     # only do if host still not found
516     if( 0 == @out_msg_l ) {
517         # check known_server_db
518         $sql_statement = "SELECT * FROM known_server WHERE hostname='$source_name'";
519         $query_res = $main::known_server_db->select_dbentry( $sql_statement );
520         if( 1 == keys %{$query_res} ) {
521             my $act_time = &get_time;
522             my $sql_statement= "UPDATE known_server ".
523                 "SET hostkey='$source_key', timestamp='$act_time' ".
524                 "WHERE hostname='$source_name'";
525             my $res = $main::known_server_db->update_dbentry( $sql_statement );
527             my $hash = &create_xml_hash("confirm_new_key", $server_address, $source_name);
528             my $out_msg = &create_xml_string($hash);
529             push(@out_msg_l, $out_msg);
530         }
531     }
533     return @out_msg_l;
537 #===  FUNCTION  ================================================================
538 #         NAME:  here_i_am
539 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
540 #      RETURNS:  nothing
541 #  DESCRIPTION:  process this incoming message
542 #===============================================================================
543 sub here_i_am {
544     my ($msg, $msg_hash, $session_id) = @_;
545     my @out_msg_l;
546     my $out_hash;
548     my $source = @{$msg_hash->{source}}[0];
549     my $mac_address = @{$msg_hash->{mac_address}}[0];
550         my $gotoHardwareChecksum = @{$msg_hash->{gotoHardwareChecksum}}[0];
551     my $client_status = @{$msg_hash->{client_status}}[0];
552     my $client_revision = @{$msg_hash->{client_revision}}[0];
554     # number of known clients
555     my $nu_clients= $main::known_clients_db->count_dbentries('known_clients');
557     # check wether client address or mac address is already known
558     my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$source'";
559     my $db_res= $main::known_clients_db->select_dbentry( $sql_statement );
560     
561     if ( 1 == keys %{$db_res} ) {
562         &main::daemon_log("$session_id WARNING: $source is already known as a client", 1);
563         &main::daemon_log("$session_id WARNING: values for $source are being overwritten", 1);   
564         $nu_clients --;
565     }
567     # number of actual activ clients
568     my $act_nu_clients = $nu_clients;
570     &main::daemon_log("$session_id INFO: number of actual activ clients: $act_nu_clients", 5);
571     &main::daemon_log("$session_id INFO: number of maximal allowed clients: $max_clients", 5);
573     if($max_clients <= $act_nu_clients) {
574         my $out_hash = &create_xml_hash("denied", $server_address, $source);
575         &add_content2xml_hash($out_hash, "denied", "I_cannot_take_any_more_clients!");
576         my $passwd = @{$msg_hash->{new_passwd}}[0]; 
577         &send_msg_hash2address($out_hash, $source, $passwd);
578         return;
579     }
580     
581     # new client accepted
582     my $new_passwd = @{$msg_hash->{new_passwd}}[0];
584     # create entry in known_clients
585     my $events = @{$msg_hash->{events}}[0];
586     
588     # add entry to known_clients_db
589     my $act_timestamp = &get_time;
590     my $res = $main::known_clients_db->add_dbentry( {table=>'known_clients', 
591                                                 primkey=>['hostname'],
592                                                 hostname=>$source,
593                                                 events=>$events,
594                                                 macaddress=>$mac_address,
595                                                 status=>'registered',
596                                                 hostkey=>$new_passwd,
597                                                 timestamp=>$act_timestamp,
598                                                 } );
600     if ($res != 0)  {
601         &main::daemon_log("$session_id ERROR: cannot add entry to known_clients: $res");
602         return;
603     }
604     
605     # return acknowledgement to client
606     $out_hash = &create_xml_hash("registered", $server_address, $source);
608     # notify registered client to bus
609     if( $bus_activ eq "on") {
610         # fetch actual bus key
611         my $sql_statement= "SELECT * FROM known_server WHERE status='bus'";
612         my $query_res = $main::known_server_db->select_dbentry( $sql_statement );
613         my $hostkey = $query_res->{1}->{'hostkey'};
615         # send update msg to bus
616         $out_hash = &create_xml_hash("new_client", $server_address, $bus_address, $source);
617         &add_content2xml_hash($out_hash, "macaddress", $mac_address);
618         &add_content2xml_hash($out_hash, "timestamp", $act_timestamp);
619         my $new_client_out = &create_xml_string($out_hash);
620         push(@out_msg_l, $new_client_out);
621         &main::daemon_log("$session_id INFO: send bus msg that client '$source' has registered at server '$server_address'", 5);
622     }
624     # give the new client his ldap config
625     # Workaround: Send within the registration response, if the client will get an ldap config later
626         my $new_ldap_config_out = &new_ldap_config($source, $session_id);
627         if($new_ldap_config_out && (!($new_ldap_config_out =~ /error/))) {
628                 &add_content2xml_hash($out_hash, "ldap_available", "true");
629         } elsif($new_ldap_config_out && $new_ldap_config_out =~ /error/){
630                 &add_content2xml_hash($out_hash, "error", $new_ldap_config_out);
632                 my $sql_statement = "UPDATE $main::job_queue_tn ".
633                 "SET status='error', result='$new_ldap_config_out' ".
634                 "WHERE status='processing' AND macaddress LIKE '$mac_address'";
635                 my $res = $main::job_db->update_dbentry($sql_statement);
636                 &main::daemon_log("$session_id DEBUG: $sql_statement RESULT: $res", 7);         
637         }
638     my $register_out = &create_xml_string($out_hash);
639     push(@out_msg_l, $register_out);
641     # Really send the ldap config
642     if( $new_ldap_config_out && (!($new_ldap_config_out =~ /error/))) {
643             push(@out_msg_l, $new_ldap_config_out);
644     }
646         my $hardware_config_out = &hardware_config($msg, $msg_hash, $session_id);
647         if( $hardware_config_out ) {
648                 push(@out_msg_l, $hardware_config_out);
649         }
651     &main::daemon_log("$session_id INFO: register client $source ($mac_address)", 5);
652     &main::daemon_log("$session_id INFO: client version: $client_status - $client_revision", 5); 
654     return @out_msg_l;
658 #===  FUNCTION  ================================================================
659 #         NAME:  who_has
660 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
661 #      RETURNS:  nothing 
662 #  DESCRIPTION:  process this incoming message
663 #===============================================================================
664 sub who_has {
665     my ($msg_hash) = @_ ;
666     my @out_msg_l;
667     
668     # what is your search pattern
669     my $search_pattern = @{$msg_hash->{who_has}}[0];
670     my $search_element = @{$msg_hash->{$search_pattern}}[0];
671     &main::daemon_log("who_has-msg looking for $search_pattern $search_element", 7);
673     # scanning known_clients for search_pattern
674     my @host_addresses = keys %$main::known_clients;
675     my $known_clients_entries = length @host_addresses;
676     my $host_address;
677     foreach my $host (@host_addresses) {
678         my $client_element = $main::known_clients->{$host}->{$search_pattern};
679         if ($search_element eq $client_element) {
680             $host_address = $host;
681             last;
682         }
683     }
684         
685     # search was successful
686     if (defined $host_address) {
687         my $source = @{$msg_hash->{source}}[0];
688         my $out_hash = &create_xml_hash("who_has_i_do", $server_address, $source, "mac_address");
689         &add_content2xml_hash($out_hash, "mac_address", $search_element);
690         my $out_msg = &create_xml_string($out_hash);
691         push(@out_msg_l, $out_msg);
692     }
693     return @out_msg_l;
697 sub who_has_i_do {
698     my ($msg_hash) = @_ ;
699     my $header = @{$msg_hash->{header}}[0];
700     my $source = @{$msg_hash->{source}}[0];
701     my $search_param = @{$msg_hash->{$header}}[0];
702     my $search_value = @{$msg_hash->{$search_param}}[0];
703     print "\ngot msg $header:\nserver $source has client with $search_param $search_value\n";
707 #===  FUNCTION  ================================================================
708 #         NAME:  new_ldap_config
709 #   PARAMETERS:  address - string - ip address and port of a host
710 #      RETURNS:  gosa-si conform message
711 #  DESCRIPTION:  send to address the ldap configuration found for dn gotoLdapServer
712 #===============================================================================
713 sub new_ldap_config {
714         my ($address, $session_id) = @_ ;
716         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address' OR macaddress LIKE '$address'";
717         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
719         # check hit
720         my $hit_counter = keys %{$res};
721         if( not $hit_counter == 1 ) {
722                 &main::daemon_log("$session_id ERROR: more or no hit found in known_clients_db by query '$sql_statement'", 1);
723         }
725     $address = $res->{1}->{hostname};
726         my $macaddress = $res->{1}->{macaddress};
727         my $hostkey = $res->{1}->{hostkey};
729         if (not defined $macaddress) {
730                 &main::daemon_log("$session_id ERROR: no mac address found for client $address", 1);
731                 return;
732         }
734         # Build LDAP connection
735     my $ldap_handle = &main::get_ldap_handle($session_id);
736         if( not defined $ldap_handle ) {
737                 &main::daemon_log("$session_id ERROR: cannot connect to ldap: $ldap_uri", 1);
738                 return;
739         } 
741         # Perform search
742     $mesg = $ldap_handle->search( base   => $ldap_base,
743                 scope  => 'sub',
744                 attrs => ['dn', 'gotoLdapServer', 'gosaUnitTag', 'FAIclass'],
745                 filter => "(&(objectClass=GOhard)(macaddress=$macaddress))");
746         if($mesg->code) {
747                 &main::daemon_log("$session_id ".$mesg->error, 1);
748                 return;
749         }
751         # Sanity check
752         if ($mesg->count != 1) {
753                 &main::daemon_log("$session_id WARNING: client with mac address $macaddress not found/unique/active - not sending ldap config".
754                 "\n\tbase: $ldap_base".
755                 "\n\tscope: sub".
756                 "\n\tattrs: dn, gotoLdapServer".
757                 "\n\tfilter: (&(objectClass=GOhard)(macaddress=$macaddress))", 1);
758                 return;
759         }
761         my $entry= $mesg->entry(0);
762         my $dn= $entry->dn;
763         my @servers= $entry->get_value("gotoLdapServer");
764         my $unit_tag= $entry->get_value("gosaUnitTag");
765         my @ldap_uris;
766         my $server;
767         my $base;
768         my $release;
770         # Fill release if available
771         my $FAIclass= $entry->get_value("FAIclass");
772         if (defined $FAIclass && $FAIclass =~ /^.* :([A-Za-z0-9\/.]+).*$/) {
773                 $release= $1;
774         }
776         # Do we need to look at an object class?
777         if (not @servers){
778                 $mesg = $ldap_handle->search( base   => $ldap_base,
779                         scope  => 'sub',
780                         attrs => ['dn', 'gotoLdapServer', 'FAIclass'],
781                         filter => "(&(objectClass=gosaGroupOfNames)(member=$dn))");
782                 #$mesg->code && die $mesg->error;
783                 if($mesg->code) {
784                         &main::daemon_log("$session_id ".$mesg->error, 1);
785                         return;
786                 }
788                 # Sanity check
789                 if ($mesg->count != 1) {
790                         &main::daemon_log("$session_id WARNING: no LDAP information found for client mac $macaddress", 1);
791                         return;
792                 }
794                 $entry= $mesg->entry(0);
795                 $dn= $entry->dn;
796                 @servers= $entry->get_value("gotoLdapServer");
798                 if (not defined $release){
799                         $FAIclass= $entry->get_value("FAIclass");
800                         if (defined $FAIclass && $FAIclass =~ /^.* :([A-Za-z0-9\/.]+).*$/) {
801                                 $release= $1;
802                         }
803                 }
804         }
806         @servers= sort (@servers);
808         foreach $server (@servers){
809                 # Conversation for backward compatibility
810                 if (not $server =~ /^\d+:[^:]+:ldap[^:]*:\/\// ) {
811                     if ($server =~ /^([^:]+):([^:]+)$/ ) {
812                       $server= "1:dummy:ldap://$1/$2";
813                     } elsif ($server =~ /^(\d+):([^:]+):(.*)$/ ) {
814                       $server= "$1:dummy:ldap://$2/$3";
815                     }
816                 }
818                 $base= $server;
819                 $server =~ s%^[^:]+:[^:]+:(ldap.*://[^/]+)/.*$%$1%;
820                 $base =~ s%^[^:]+:[^:]+:ldap.*://[^/]+/(.*)$%$1%;
821                 push (@ldap_uris, $server);
822         }
824         # Assemble data package
825         my %data = ( 'ldap_uri'  => \@ldap_uris, 'ldap_base' => $base,
826                 'ldap_cfg' => \@ldap_cfg, 'pam_cfg' => \@pam_cfg,'nss_cfg' => \@nss_cfg );
827         if (defined $release){
828                 $data{'release'}= $release;
829         }
831         # Need to append GOto settings?
832         if (defined $goto_admin and defined $goto_secret){
833                 $data{'goto_admin'}= $goto_admin;
834                 $data{'goto_secret'}= $goto_secret;
835         }
837         # Append unit tag if needed
838         if (defined $unit_tag){
840                 # Find admin base and department name
841                 $mesg = $ldap_handle->search( base   => $ldap_base,
842                         scope  => 'sub',
843                         attrs => ['dn', 'ou'],
844                         filter => "(&(objectClass=gosaAdministrativeUnit)(gosaUnitTag=$unit_tag))");
845                 #$mesg->code && die $mesg->error;
846                 if($mesg->code) {
847                         &main::daemon_log($mesg->error, 1);
848                         return "error-unit-tag-count-0";
849                 }
851                 # Sanity check
852                 if ($mesg->count != 1) {
853                         &main::daemon_log("WARNING: cannot find administrative unit for client with tag $unit_tag", 1);
854                         return "error-unit-tag-count-".$mesg->count;
855                 }
857                 $entry= $mesg->entry(0);
858                 $data{'admin_base'}= $entry->dn;
859                 $data{'department'}= $entry->get_value("ou");
861                 # Append unit Tag
862                 $data{'unit_tag'}= $unit_tag;
863         }
865         # Send information
866         return &build_msg("new_ldap_config", $server_address, $address, \%data);
870 #===  FUNCTION  ================================================================
871 #         NAME:  hardware_config
872 #   PARAMETERS:  address - string - ip address and port of a host
873 #      RETURNS:  
874 #  DESCRIPTION:  
875 #===============================================================================
876 sub hardware_config {
877         my ($msg, $msg_hash, $session_id) = @_ ;
878         my $address = @{$msg_hash->{source}}[0];
879         my $header = @{$msg_hash->{header}}[0];
880         my $gotoHardwareChecksum = @{$msg_hash->{gotoHardwareChecksum}}[0];
882         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address'";
883         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
885         # check hit
886         my $hit_counter = keys %{$res};
887         if( not $hit_counter == 1 ) {
888                 &main::daemon_log("$session_id ERROR: more or no hit found in known_clients_db by query by '$address'", 1);
889         }
890         my $macaddress = $res->{1}->{macaddress};
891         my $hostkey = $res->{1}->{hostkey};
893         if (not defined $macaddress) {
894                 &main::daemon_log("$session_id ERROR: no mac address found for client $address", 1);
895                 return;
896         }
898         # Build LDAP connection
899     my $ldap_handle = &main::get_ldap_handle($session_id);
900         if( not defined $ldap_handle ) {
901                 &main::daemon_log("$session_id ERROR: cannot connect to ldap: $ldap_uri", 1);
902                 return;
903         } 
905         # Perform search
906         $mesg = $ldap_handle->search(
907                 base   => $ldap_base,
908                 scope  => 'sub',
909                 filter => "(&(objectClass=GOhard)(|(macAddress=$macaddress)(dhcpHWaddress=ethernet $macaddress)))"
910         );
912         if($mesg->count() == 0) {
913                 &main::daemon_log("Host was not found in LDAP!", 1);
915                 # set status = hardware_detection at jobqueue if entry exists
916                 # TODO
917                 # resolve plain name for host
918                 my $func_dic = {table=>$main::job_queue_tn,
919                                 primkey=>[],
920                                 timestamp=>&get_time,
921                                 status=>'processing',
922                                 result=>'none',
923                                 progress=>'hardware-detection',
924                                 headertag=>'trigger_action_reinstall',
925                                 targettag=>$address,
926                                 xmlmessage=>'none',
927                                 macaddress=>$macaddress,
928                                 plainname=>'none',
929                 };
930                 my $hd_res = $main::job_db->add_dbentry($func_dic);
931                 &main::daemon_log("$session_id INFO: add '$macaddress' to job queue as an installing job", 5);
932         
933         } else {
934                 my $entry= $mesg->entry(0);
935                 my $dn= $entry->dn;
936                 if (defined($entry->get_value("gotoHardwareChecksum"))) {
937                         if (! $entry->get_value("gotoHardwareChecksum") eq $gotoHardwareChecksum) {
938                                 $entry->replace(gotoHardwareChecksum => $gotoHardwareChecksum);
939                                 if($entry->update($ldap_handle)) {
940                                         &main::daemon_log("$session_id INFO: Hardware changed! Detection triggered.", 5);
941                                 }
942                         } else {
943                                 # Nothing to do
944                                 return;
945                         }
946                 } 
947         } 
949         # Assemble data package
950         my %data = ();
952         # Need to append GOto settings?
953         if (defined $goto_admin and defined $goto_secret){
954                 $data{'goto_admin'}= $goto_admin;
955                 $data{'goto_secret'}= $goto_secret;
956         }
958         # Send information
959         return &build_msg("detect_hardware", $server_address, $address, \%data);
962 sub server_matches {
963         my $target = shift;
964         my $target_ip = ($1) if $target =~ /^([0-9\.]*?):.*$/;
965         if(!defined($target_ip) or length($target_ip) == 0) {
966                 return;
967         }
969         my $result = 0;
971         if($server_ip eq $target_ip) {
972                 $result= 1;
973         } elsif ($target_ip eq "0.0.0.0") {
974                 $result= 1;
975         } elsif ($server_ip eq "0.0.0.0") {     
976                 if ($target_ip eq "127.0.0.1") {
977                         $result= 1;
978                 } else {
979                         my $PROC_NET_ROUTE= ('/proc/net/route');
981                         open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
982                                 or die "Could not open $PROC_NET_ROUTE";
984                         my @ifs = <PROC_NET_ROUTE>;
986                         close(PROC_NET_ROUTE);
988                         # Eat header line
989                         shift @ifs;
990                         chomp @ifs;
991                         foreach my $line(@ifs) {
992                                 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
993                                 my $destination;
994                                 my $mask;
995                                 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
996                                 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
997                                 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
998                                 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
999                                 if(new NetAddr::IP($target_ip)->within(new NetAddr::IP($destination, $mask))) {
1000                                         # destination matches route, save mac and exit
1001                                         $result= 1;
1002                                         last;
1003                                 }
1004                         }
1005                 }
1006         } else {
1007                 &main::daemon_log("Target ip $target_ip does not match Server ip $server_ip",1);
1008         }
1010         return $result;
1013 1;