Code

* gosa-si-server-nobus
[gosa.git] / gosa-si / modules / ClientPackages.pm
1 package ClientPackages;
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/ClientPackages";
20 use lib "/usr/lib/gosa-si/server/ClientPackages";
22 BEGIN{}
23 END {}
25 my ($server_ip, $server_port, $ClientPackages_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 $network_interface;
29 my $no_bus;
30 my (@ldap_cfg, @pam_cfg, @nss_cfg, $goto_admin, $goto_secret);
31 my $mesg;
33 my %cfg_defaults = (
34 "bus" => {
35     "activ" => [\$bus_activ, "on"],
36     "key" => [\$bus_key, ""],
37     "ip" => [\$bus_ip, ""],
38     "port" => [\$bus_port, "20080"],
39     },
40 "server" => {
41     "ip" => [\$server_ip, "0.0.0.0"],
42     "mac-address" => [\$main::server_mac_address, "00:00:00:00:00"],
43     "port" => [\$server_port, "20081"],
44     "ldap-uri" => [\$ldap_uri, ""],
45     "ldap-base" => [\$ldap_base, ""],
46     "ldap-admin-dn" => [\$ldap_admin_dn, ""],
47     "ldap-admin-password" => [\$ldap_admin_password, ""],
48     "max-clients" => [\$max_clients, 100],
49     },
50 "ClientPackages" => {
51     "key" => [\$ClientPackages_key, ""],
52     },
53 );
55 ### START #####################################################################
57 # read configfile and import variables
58 &read_configfile();
61 # if server_ip is not an ip address but a name
62 if( inet_aton($server_ip) ){ $server_ip = inet_ntoa(inet_aton($server_ip)); } 
63 $network_interface= &get_interface_for_ip($server_ip);
64 $main::server_mac_address= &get_mac($network_interface);
67 # import local events
68 my ($error, $result, $event_hash) = &import_events($event_dir);
69 if ($error == 0) {
70     foreach my $log_line (@$result) {
71         &main::daemon_log("0 DEBUG: ClientPackages - $log_line", 7);
72     }
73 } else {
74     foreach my $log_line (@$result) {
75         &main::daemon_log("0 ERROR: ClientPackages - $log_line", 1);
76     }
78 }
80 # Unit tag can be defined in config
81 if((not defined($main::gosa_unit_tag)) || length($main::gosa_unit_tag) == 0) {
82         # Read gosaUnitTag from LDAP
83         
84     my $ldap_handle = &main::get_ldap_handle(); 
85     if( defined($ldap_handle) ) {
86                 &main::daemon_log("0 INFO: Searching for servers gosaUnitTag with mac address $main::server_mac_address",5);
87                 # Perform search for Unit Tag
88                 $mesg = $ldap_handle->search(
89                         base   => $ldap_base,
90                         scope  => 'sub',
91                         attrs  => ['gosaUnitTag'],
92                         filter => "(macaddress=$main::server_mac_address)"
93                 );
95                 if ((! $main::server_mac_address eq "00:00:00:00:00:00") and $mesg->count == 1) {
96                         my $entry= $mesg->entry(0);
97                         my $unit_tag= $entry->get_value("gosaUnitTag");
98                         $main::ldap_server_dn= $mesg->entry(0)->dn;
99                         if(defined($unit_tag) && length($unit_tag) > 0) {
100                                 &main::daemon_log("0 INFO: Detected gosaUnitTag $unit_tag for creating entries", 5);
101                                 $main::gosa_unit_tag= $unit_tag;
102                         }
103                 } else {
104                         # Perform another search for Unit Tag
105                         my $hostname= `hostname -f`;
106                         chomp($hostname);
107                         &main::daemon_log("0 INFO: Searching for servers gosaUnitTag with hostname $hostname",5);
108                         $mesg = $ldap_handle->search(
109                                 base   => $ldap_base,
110                                 scope  => 'sub',
111                                 attrs  => ['gosaUnitTag'],
112                                 filter => "(&(cn=$hostname)(objectClass=goServer))"
113                         );
114                         if ($mesg->count == 1) {
115                                 my $entry= $mesg->entry(0);
116                                 my $unit_tag= $entry->get_value("gosaUnitTag");
117                                 $main::ldap_server_dn= $mesg->entry(0)->dn;
118                                 if(defined($unit_tag) && length($unit_tag) > 0) {
119                                         &main::daemon_log("0 INFO: Detected gosaUnitTag $unit_tag for creating entries", 5);
120                                         $main::gosa_unit_tag= $unit_tag;
121                                 }
122                         } else {
123                                 # Perform another search for Unit Tag
124                                 $hostname= `hostname -s`;
125                                 chomp($hostname);
126                                 &main::daemon_log("0 INFO: Searching for servers gosaUnitTag with hostname $hostname",5);
127                                 $mesg = $ldap_handle->search(
128                                         base   => $ldap_base,
129                                         scope  => 'sub',
130                                         attrs  => ['gosaUnitTag'],
131                                         filter => "(&(cn=$hostname)(objectClass=goServer))"
132                                 );
133                                 if ($mesg->count == 1) {
134                                         my $entry= $mesg->entry(0);
135                                         my $unit_tag= $entry->get_value("gosaUnitTag");
136                                         $main::ldap_server_dn= $mesg->entry(0)->dn;
137                                         if(defined($unit_tag) && length($unit_tag) > 0) {
138                                                 &main::daemon_log("INFO: Detected gosaUnitTag $unit_tag for creating entries", 5);
139                                                 $main::gosa_unit_tag= $unit_tag;
140                                         }
141                                 } else {
142                                         &main::daemon_log("0 WARNING: No gosaUnitTag detected. Not using gosaUnitTag", 3);
143                                 }
144                         }
145                 }
146         } else {
147                 &main::daemon_log("0 INFO: Using gosaUnitTag from config-file: $main::gosa_unit_tag",5);
148         }
152 my $server_address = "$server_ip:$server_port";
153 $main::server_address = $server_address;
156 if( inet_aton($bus_ip) ){ $bus_ip = inet_ntoa(inet_aton($bus_ip)); } 
157 ######################################################
158 # to change
159 if( $bus_ip eq "127.0.1.1" ) { $bus_ip = "127.0.0.1" }
160 ######################################################
161 my $bus_address = "$bus_ip:$bus_port";
162 $main::bus_address = $bus_address;
164 # create general settings for this module
165 my $xml = new XML::Simple();
167 # register at bus
168 if ($main::no_bus > 0) {
169     $bus_activ = "off"
171 if($bus_activ eq "on") {
172     &register_at_bus();
176 ### functions #################################################################
179 sub get_module_info {
180     my @info = ($server_address,
181                 $ClientPackages_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;
357 # outcommented from rettenbe: moved to GosaSupportDaemon.pm
358 #sub import_events {
359 #    if (not -e $event_dir) {
360 #        &main::daemon_log("S ERROR: cannot find directory or directory is not readable: $event_dir", 1);   
361 #    }
362 #    opendir (DIR, $event_dir) or die "ERROR while loading gosa-si-events from directory $event_dir : $!\n";
364 #    while (defined (my $event = readdir (DIR))) {
365 #        if( $event eq "." || $event eq ".." ) { next; }  
366 #        if( $event eq "gosaTriggered.pm" ) { next; }    # only GOsa specific events
368 #        eval{ require $event; };
369 #        if( $@ ) {
370 #            &main::daemon_log("S ERROR: import of event module '$event' failed", 1);
371 #            &main::daemon_log("$@", 8);
372 #            next;
373 #        }
375 #        $event =~ /(\S*?).pm$/;
376 #        my $event_module = $1;
377 #        my $events_l = eval( $1."::get_events()") ;
378 #        foreach my $event_name (@{$events_l}) {
379 #            $event_hash->{$event_name} = $event_module;
380 #        }
381 #        my $events_string = join( ", ", @{$events_l});
382 #        &main::daemon_log("S DEBUG: ClientPackages imported events $events_string", 8);
383 #    }
384 #}
387 #===  FUNCTION  ================================================================
388 #         NAME:  process_incoming_msg
389 #   PARAMETERS:  crypted_msg - string - incoming crypted message
390 #      RETURNS:  nothing
391 #  DESCRIPTION:  handels the proceeded distribution to the appropriated functions
392 #===============================================================================
393 sub process_incoming_msg {
394     my ($msg, $msg_hash, $session_id) = @_ ;
395     my $error = 0;
396     my $host_name;
397     my $host_key;
398     my @out_msg_l = ("nohandler");
399     my $sql_events;
401     # process incoming msg
402     my $header = @{$msg_hash->{header}}[0]; 
403     my $source = @{$msg_hash->{source}}[0]; 
404     my @target_l = @{$msg_hash->{target}};
406     # skip PREFIX
407     $header =~ s/^CLMSG_//;
409     &main::daemon_log("$session_id DEBUG: ClientPackages: msg to process: $header", 7);
411     if( 0 == length @target_l){     
412         &main::daemon_log("$session_id ERROR: no target specified for msg $header", 1);
413         $error++;
414     }
416     if( 1 == length @target_l) {
417         my $target = $target_l[0];
418                 if(&server_matches($target)) {
419             if ($header eq 'new_key') {
420                 @out_msg_l = &new_key($msg_hash)
421             } elsif ($header eq 'here_i_am') {
422                 @out_msg_l = &here_i_am($msg, $msg_hash, $session_id)
423             } else {
424                 # a event exists with the header as name
425                 if( exists $event_hash->{$header} ) {
426                     &main::daemon_log("$session_id INFO: found event '$header' at event-module '".$event_hash->{$header}."'", 5);
427                     no strict 'refs';
428                     @out_msg_l = &{$event_hash->{$header}."::$header"}($msg, $msg_hash, $session_id);
430                 # if no event handler is implemented   
431                 } else {
432                     $sql_events = "SELECT * FROM $main::known_clients_tn WHERE ( (macaddress LIKE '$source') OR (hostname='$source') )"; 
433                     my $res = $main::known_clients_db->select_dbentry( $sql_events );
434                     my $l = keys(%$res);
436                     # set error if no or more than 1 hits are found for sql query
437                     if ( $l != 1) {
438                         @out_msg_l = ('knownclienterror');
440                     # found exact 1 hit in db
441                     } else {
442                         my $client_events = $res->{'1'}->{'events'};
444                         # client is registered for this event, deliver this message to client
445                         $header =~ s/^answer_//;
446                         if ($client_events =~ /,$header,/) {
447                             # answer message finally arrived destination server, so forward messages to GOsa
448                             if ($target eq $main::server_address) {        
449                                 $msg =~ s/<header>answer_/<header>/;
450                                 $msg =~ s/<target>\S+<\/target>/<target>GOSA<\/target>/;
451                             }
452                             @out_msg_l = ( $msg );
454                         # client is not registered for this event, set error
455                         } else {
456                             @out_msg_l = ('noeventerror');
457                         }
458                     }
459                 }
460             }
462             # if delivery not possible raise error and return 
463             if( not defined $out_msg_l[0] ) {
464                 @out_msg_l = ();
465             } elsif( $out_msg_l[0] eq 'nohandler') {
466                 &main::daemon_log("$session_id ERROR: ClientPackages: no event handler or core function defined for '$header'", 1);
467                 @out_msg_l = ();
468             }  elsif ($out_msg_l[0] eq 'knownclienterror') {
469                 &main::daemon_log("$session_id ERROR: no or more than 1 hits are found at known_clients_db with sql query: '$sql_events'", 1);
470                 &main::daemon_log("$session_id WARNING: processing is aborted and message will not be forwarded");
471                 @out_msg_l = ();
472             } elsif ($out_msg_l[0] eq 'noeventerror') {
473                 &main::daemon_log("$session_id WARNING: client '$target' is not registered for event '$header', processing is aborted", 1); 
474                 @out_msg_l = ();
475             }
480         }
481                 else {
482                         &main::daemon_log("INFO: msg is not for gosa-si-server '$server_address', deliver it to target '$target'", 5);
483                         push(@out_msg_l, $msg);
484                 }
485     }
487     return \@out_msg_l;
491 #===  FUNCTION  ================================================================
492 #         NAME:  new_passwd
493 #   PARAMETERS:  msg_hash - ref - hash from function create_xml_hash
494 #      RETURNS:  nothing
495 #  DESCRIPTION:  process this incoming message
496 #===============================================================================
497 sub new_key {
498     my ($msg_hash) = @_;
499     my @out_msg_l;
500     
501     my $header = @{$msg_hash->{header}}[0];
502     my $source_name = @{$msg_hash->{source}}[0];
503     my $source_key = @{$msg_hash->{new_key}}[0];
504     my $query_res;
506     # check known_clients_db
507     my $sql_statement = "SELECT * FROM known_clients WHERE hostname='$source_name'";
508     $query_res = $main::known_clients_db->select_dbentry( $sql_statement );
509     if( 1 == keys %{$query_res} ) {
510         my $act_time = &get_time;
511         my $sql_statement= "UPDATE known_clients ".
512             "SET hostkey='$source_key', timestamp='$act_time' ".
513             "WHERE hostname='$source_name'";
514         my $res = $main::known_clients_db->update_dbentry( $sql_statement );
515         my $hash = &create_xml_hash("confirm_new_key", $server_address, $source_name);
516         my $out_msg = &create_xml_string($hash);
517         push(@out_msg_l, $out_msg);
518     }
520     # only do if host still not found
521     if( 0 == @out_msg_l ) {
522         # check known_server_db
523         $sql_statement = "SELECT * FROM known_server WHERE hostname='$source_name'";
524         $query_res = $main::known_server_db->select_dbentry( $sql_statement );
525         if( 1 == keys %{$query_res} ) {
526             my $act_time = &get_time;
527             my $sql_statement= "UPDATE known_server ".
528                 "SET hostkey='$source_key', timestamp='$act_time' ".
529                 "WHERE hostname='$source_name'";
530             my $res = $main::known_server_db->update_dbentry( $sql_statement );
532             my $hash = &create_xml_hash("confirm_new_key", $server_address, $source_name);
533             my $out_msg = &create_xml_string($hash);
534             push(@out_msg_l, $out_msg);
535         }
536     }
538     return @out_msg_l;
542 #===  FUNCTION  ================================================================
543 #         NAME:  here_i_am
544 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
545 #      RETURNS:  nothing
546 #  DESCRIPTION:  process this incoming message
547 #===============================================================================
548 sub here_i_am {
549     my ($msg, $msg_hash, $session_id) = @_;
550     my @out_msg_l;
551     my $out_hash;
552     my $source = @{$msg_hash->{source}}[0];
553     my $mac_address = @{$msg_hash->{mac_address}}[0];
554         my $gotoHardwareChecksum = @{$msg_hash->{gotoHardwareChecksum}}[0];
555     my $client_status = @{$msg_hash->{client_status}}[0];
556     my $client_revision = @{$msg_hash->{client_revision}}[0];
558     # number of known clients
559     my $nu_clients= $main::known_clients_db->count_dbentries('known_clients');
561     # check wether client address or mac address is already known
562     my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$source'";
563     my $db_res= $main::known_clients_db->select_dbentry( $sql_statement );
564     
565     if ( 1 == keys %{$db_res} ) {
566         &main::daemon_log("$session_id WARNING: $source is already known as a client", 1);
567         &main::daemon_log("$session_id WARNING: values for $source are being overwritten", 1);   
568         $nu_clients --;
569     }
571     # number of actual activ clients
572     my $act_nu_clients = $nu_clients;
574     &main::daemon_log("$session_id INFO: number of actual activ clients: $act_nu_clients", 5);
575     &main::daemon_log("$session_id INFO: number of maximal allowed clients: $max_clients", 5);
577     if($max_clients <= $act_nu_clients) {
578         my $out_hash = &create_xml_hash("denied", $server_address, $source);
579         &add_content2xml_hash($out_hash, "denied", "I_cannot_take_any_more_clients!");
580         my $passwd = @{$msg_hash->{new_passwd}}[0]; 
581         &send_msg_hash2address($out_hash, $source, $passwd);
582         return;
583     }
584     
585     # new client accepted
586     my $new_passwd = @{$msg_hash->{new_passwd}}[0];
588     # add entry to known_clients_db
589     my $events = @{$msg_hash->{events}}[0];
590     my $act_timestamp = &get_time;
591     my $res = $main::known_clients_db->add_dbentry( {table=>'known_clients', 
592                                                 primkey=>['hostname'],
593                                                 hostname=>$source,
594                                                 events=>$events,
595                                                 macaddress=>$mac_address,
596                                                 status=>'registered',
597                                                 hostkey=>$new_passwd,
598                                                 timestamp=>$act_timestamp,
599                                                 } );
601     if ($res != 0)  {
602         &main::daemon_log("$session_id ERROR: cannot add entry to known_clients: $res");
603         return;
604     }
605     
606     # return acknowledgement to client
607     $out_hash = &create_xml_hash("registered", $server_address, $source);
612 #    # notify registered client to all other server
613 #    if( $bus_activ eq "on") {
614 #        # fetch actual bus key
615 #        my $sql_statement= "SELECT * FROM known_server WHERE status='bus'";
616 #        my $query_res = $main::known_server_db->select_dbentry( $sql_statement );
617 #        my $hostkey = $query_res->{1}->{'hostkey'};
619 #        # send update msg to bus
620 #        $out_hash = &create_xml_hash("new_client", $server_address, $bus_address, $source);
621 #        &add_content2xml_hash($out_hash, "macaddress", $mac_address);
622 #        &add_content2xml_hash($out_hash, "timestamp", $act_timestamp);
623 #        my $new_client_out = &create_xml_string($out_hash);
624 #        push(@out_msg_l, $new_client_out);
625 #        &main::daemon_log("$session_id INFO: send bus msg that client '$source' has registered at server '$server_address'", 5);
626 #    }
628     # give the new client his ldap config
629     # Workaround: Send within the registration response, if the client will get an ldap config later
630         my $new_ldap_config_out = &new_ldap_config($source, $session_id);
631         if($new_ldap_config_out && (!($new_ldap_config_out =~ /error/))) {
632                 &add_content2xml_hash($out_hash, "ldap_available", "true");
633         } elsif($new_ldap_config_out && $new_ldap_config_out =~ /error/){
634                 &add_content2xml_hash($out_hash, "error", $new_ldap_config_out);
636                 my $sql_statement = "UPDATE $main::job_queue_tn ".
637                 "SET status='error', result='$new_ldap_config_out' ".
638                 "WHERE status='processing' AND macaddress LIKE '$mac_address'";
639                 my $res = $main::job_db->update_dbentry($sql_statement);
640                 &main::daemon_log("$session_id DEBUG: $sql_statement RESULT: $res", 7);         
641         }
642     my $register_out = &create_xml_string($out_hash);
643     push(@out_msg_l, $register_out);
645     # Really send the ldap config
646     if( $new_ldap_config_out && (!($new_ldap_config_out =~ /error/))) {
647             push(@out_msg_l, $new_ldap_config_out);
648     }
650         my $hardware_config_out = &hardware_config($msg, $msg_hash, $session_id);
651         if( $hardware_config_out ) {
652                 push(@out_msg_l, $hardware_config_out);
653         }
655     # notify registered client to all other server
656     my %mydata = ( 'client' => $source, 'macaddress' => $mac_address);
657     my $mymsg = &build_msg('new_foreign_client', $main::server_address, "KNOWN_SERVER", \%mydata);
658     push(@out_msg_l, $mymsg);
660     &main::daemon_log("$session_id INFO: register client $source ($mac_address)", 5);
661     &main::daemon_log("$session_id INFO: client version: $client_status - $client_revision", 5); 
662     return @out_msg_l;
666 #===  FUNCTION  ================================================================
667 #         NAME:  who_has
668 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
669 #      RETURNS:  nothing 
670 #  DESCRIPTION:  process this incoming message
671 #===============================================================================
672 sub who_has {
673     my ($msg_hash) = @_ ;
674     my @out_msg_l;
675     
676     # what is your search pattern
677     my $search_pattern = @{$msg_hash->{who_has}}[0];
678     my $search_element = @{$msg_hash->{$search_pattern}}[0];
679     &main::daemon_log("who_has-msg looking for $search_pattern $search_element", 7);
681     # scanning known_clients for search_pattern
682     my @host_addresses = keys %$main::known_clients;
683     my $known_clients_entries = length @host_addresses;
684     my $host_address;
685     foreach my $host (@host_addresses) {
686         my $client_element = $main::known_clients->{$host}->{$search_pattern};
687         if ($search_element eq $client_element) {
688             $host_address = $host;
689             last;
690         }
691     }
692         
693     # search was successful
694     if (defined $host_address) {
695         my $source = @{$msg_hash->{source}}[0];
696         my $out_hash = &create_xml_hash("who_has_i_do", $server_address, $source, "mac_address");
697         &add_content2xml_hash($out_hash, "mac_address", $search_element);
698         my $out_msg = &create_xml_string($out_hash);
699         push(@out_msg_l, $out_msg);
700     }
701     return @out_msg_l;
705 sub who_has_i_do {
706     my ($msg_hash) = @_ ;
707     my $header = @{$msg_hash->{header}}[0];
708     my $source = @{$msg_hash->{source}}[0];
709     my $search_param = @{$msg_hash->{$header}}[0];
710     my $search_value = @{$msg_hash->{$search_param}}[0];
711     print "\ngot msg $header:\nserver $source has client with $search_param $search_value\n";
715 #===  FUNCTION  ================================================================
716 #         NAME:  new_ldap_config
717 #   PARAMETERS:  address - string - ip address and port of a host
718 #      RETURNS:  gosa-si conform message
719 #  DESCRIPTION:  send to address the ldap configuration found for dn gotoLdapServer
720 #===============================================================================
721 sub new_ldap_config {
722         my ($address, $session_id) = @_ ;
724         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address' OR macaddress LIKE '$address'";
725         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
727         # check hit
728         my $hit_counter = keys %{$res};
729         if( not $hit_counter == 1 ) {
730                 &main::daemon_log("$session_id ERROR: more or no hit found in known_clients_db by query '$sql_statement'", 1);
731         }
733     $address = $res->{1}->{hostname};
734         my $macaddress = $res->{1}->{macaddress};
735         my $hostkey = $res->{1}->{hostkey};
737         if (not defined $macaddress) {
738                 &main::daemon_log("$session_id ERROR: no mac address found for client $address", 1);
739                 return;
740         }
742         # Build LDAP connection
743     my $ldap_handle = &main::get_ldap_handle($session_id);
744         if( not defined $ldap_handle ) {
745                 &main::daemon_log("$session_id ERROR: cannot connect to ldap: $ldap_uri", 1);
746                 return;
747         } 
749         # Perform search
750     $mesg = $ldap_handle->search( base   => $ldap_base,
751                 scope  => 'sub',
752                 attrs => ['dn', 'gotoLdapServer', 'gosaUnitTag', 'FAIclass'],
753                 filter => "(&(objectClass=GOhard)(macaddress=$macaddress))");
754         if($mesg->code) {
755                 &main::daemon_log("$session_id ".$mesg->error, 1);
756                 return;
757         }
759         # Sanity check
760         if ($mesg->count != 1) {
761                 &main::daemon_log("$session_id WARNING: client with mac address $macaddress not found/unique/active - not sending ldap config".
762                 "\n\tbase: $ldap_base".
763                 "\n\tscope: sub".
764                 "\n\tattrs: dn, gotoLdapServer".
765                 "\n\tfilter: (&(objectClass=GOhard)(macaddress=$macaddress))", 1);
766                 return;
767         }
769         my $entry= $mesg->entry(0);
770         my $dn= $entry->dn;
771         my @servers= $entry->get_value("gotoLdapServer");
772         my $unit_tag= $entry->get_value("gosaUnitTag");
773         my @ldap_uris;
774         my $server;
775         my $base;
776         my $release;
778         # Fill release if available
779         my $FAIclass= $entry->get_value("FAIclass");
780         if (defined $FAIclass && $FAIclass =~ /^.* :([A-Za-z0-9\/.]+).*$/) {
781                 $release= $1;
782         }
784         # Do we need to look at an object class?
785         if (not @servers){
786                 $mesg = $ldap_handle->search( base   => $ldap_base,
787                         scope  => 'sub',
788                         attrs => ['dn', 'gotoLdapServer', 'FAIclass'],
789                         filter => "(&(objectClass=gosaGroupOfNames)(member=$dn))");
790                 #$mesg->code && die $mesg->error;
791                 if($mesg->code) {
792                         &main::daemon_log("$session_id ".$mesg->error, 1);
793                         return;
794                 }
796                 # Sanity check
797                 if ($mesg->count != 1) {
798                         &main::daemon_log("$session_id WARNING: no LDAP information found for client mac $macaddress", 1);
799                         return;
800                 }
802                 $entry= $mesg->entry(0);
803                 $dn= $entry->dn;
804                 @servers= $entry->get_value("gotoLdapServer");
806                 if (not defined $release){
807                         $FAIclass= $entry->get_value("FAIclass");
808                         if (defined $FAIclass && $FAIclass =~ /^.* :([A-Za-z0-9\/.]+).*$/) {
809                                 $release= $1;
810                         }
811                 }
812         }
814         @servers= sort (@servers);
816         foreach $server (@servers){
817                 # Conversation for backward compatibility
818                 if (not $server =~ /^\d+:[^:]+:ldap[^:]*:\/\// ) {
819                     if ($server =~ /^([^:]+):([^:]+)$/ ) {
820                       $server= "1:dummy:ldap://$1/$2";
821                     } elsif ($server =~ /^(\d+):([^:]+):(.*)$/ ) {
822                       $server= "$1:dummy:ldap://$2/$3";
823                     }
824                 }
826                 $base= $server;
827                 $server =~ s%^[^:]+:[^:]+:(ldap.*://[^/]+)/.*$%$1%;
828                 $base =~ s%^[^:]+:[^:]+:ldap.*://[^/]+/(.*)$%$1%;
829                 push (@ldap_uris, $server);
830         }
832         # Assemble data package
833         my %data = ( 'ldap_uri'  => \@ldap_uris, 'ldap_base' => $base,
834                 'ldap_cfg' => \@ldap_cfg, 'pam_cfg' => \@pam_cfg,'nss_cfg' => \@nss_cfg );
835         if (defined $release){
836                 $data{'release'}= $release;
837         }
839         # Need to append GOto settings?
840         if (defined $goto_admin and defined $goto_secret){
841                 $data{'goto_admin'}= $goto_admin;
842                 $data{'goto_secret'}= $goto_secret;
843         }
845         # Append unit tag if needed
846         if (defined $unit_tag){
848                 # Find admin base and department name
849                 $mesg = $ldap_handle->search( base   => $ldap_base,
850                         scope  => 'sub',
851                         attrs => ['dn', 'ou'],
852                         filter => "(&(objectClass=gosaAdministrativeUnit)(gosaUnitTag=$unit_tag))");
853                 #$mesg->code && die $mesg->error;
854                 if($mesg->code) {
855                         &main::daemon_log($mesg->error, 1);
856                         return "error-unit-tag-count-0";
857                 }
859                 # Sanity check
860                 if ($mesg->count != 1) {
861                         &main::daemon_log("WARNING: cannot find administrative unit for client with tag $unit_tag", 1);
862                         return "error-unit-tag-count-".$mesg->count;
863                 }
865                 $entry= $mesg->entry(0);
866                 $data{'admin_base'}= $entry->dn;
867                 $data{'department'}= $entry->get_value("ou");
869                 # Append unit Tag
870                 $data{'unit_tag'}= $unit_tag;
871         }
873         # Send information
874         return &build_msg("new_ldap_config", $server_address, $address, \%data);
878 #===  FUNCTION  ================================================================
879 #         NAME:  hardware_config
880 #   PARAMETERS:  address - string - ip address and port of a host
881 #      RETURNS:  
882 #  DESCRIPTION:  
883 #===============================================================================
884 sub hardware_config {
885         my ($msg, $msg_hash, $session_id) = @_ ;
886         my $address = @{$msg_hash->{source}}[0];
887         my $header = @{$msg_hash->{header}}[0];
888         my $gotoHardwareChecksum = @{$msg_hash->{gotoHardwareChecksum}}[0];
890         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address'";
891         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
893         # check hit
894         my $hit_counter = keys %{$res};
895         if( not $hit_counter == 1 ) {
896                 &main::daemon_log("$session_id ERROR: more or no hit found in known_clients_db by query by '$address'", 1);
897         }
898         my $macaddress = $res->{1}->{macaddress};
899         my $hostkey = $res->{1}->{hostkey};
901         if (not defined $macaddress) {
902                 &main::daemon_log("$session_id ERROR: no mac address found for client $address", 1);
903                 return;
904         }
906         # Build LDAP connection
907     my $ldap_handle = &main::get_ldap_handle($session_id);
908         if( not defined $ldap_handle ) {
909                 &main::daemon_log("$session_id ERROR: cannot connect to ldap: $ldap_uri", 1);
910                 return;
911         } 
913         # Perform search
914         $mesg = $ldap_handle->search(
915                 base   => $ldap_base,
916                 scope  => 'sub',
917                 filter => "(&(objectClass=GOhard)(|(macAddress=$macaddress)(dhcpHWaddress=ethernet $macaddress)))"
918         );
920         if($mesg->count() == 0) {
921                 &main::daemon_log("Host was not found in LDAP!", 1);
923                 # set status = hardware_detection at jobqueue if entry exists
924                 # TODO
925                 # resolve plain name for host
926                 my $func_dic = {table=>$main::job_queue_tn,
927                                 primkey=>[],
928                                 timestamp=>&get_time,
929                                 status=>'processing',
930                                 result=>'none',
931                                 progress=>'hardware-detection',
932                                 headertag=>'trigger_action_reinstall',
933                                 targettag=>$address,
934                                 xmlmessage=>'none',
935                                 macaddress=>$macaddress,
936                                 plainname=>'none',
937                 };
938                 my $hd_res = $main::job_db->add_dbentry($func_dic);
939                 &main::daemon_log("$session_id INFO: add '$macaddress' to job queue as an installing job", 5);
940         
941         } else {
942                 my $entry= $mesg->entry(0);
943                 my $dn= $entry->dn;
944                 if (defined($entry->get_value("gotoHardwareChecksum"))) {
945                         if (! $entry->get_value("gotoHardwareChecksum") eq $gotoHardwareChecksum) {
946                                 $entry->replace(gotoHardwareChecksum => $gotoHardwareChecksum);
947                                 if($entry->update($ldap_handle)) {
948                                         &main::daemon_log("$session_id INFO: Hardware changed! Detection triggered.", 5);
949                                 }
950                         } else {
951                                 # Nothing to do
952                                 return;
953                         }
954                 } 
955         } 
957         # Assemble data package
958         my %data = ();
960         # Need to append GOto settings?
961         if (defined $goto_admin and defined $goto_secret){
962                 $data{'goto_admin'}= $goto_admin;
963                 $data{'goto_secret'}= $goto_secret;
964         }
966         # Send information
967         return &build_msg("detect_hardware", $server_address, $address, \%data);
970 sub server_matches {
971         my $target = shift;
972         my $target_ip = ($1) if $target =~ /^([0-9\.]*?):.*$/;
973         if(!defined($target_ip) or length($target_ip) == 0) {
974                 return;
975         }
977         my $result = 0;
979         if($server_ip eq $target_ip) {
980                 $result= 1;
981         } elsif ($target_ip eq "0.0.0.0") {
982                 $result= 1;
983         } elsif ($server_ip eq "0.0.0.0") {     
984                 if ($target_ip eq "127.0.0.1") {
985                         $result= 1;
986                 } else {
987                         my $PROC_NET_ROUTE= ('/proc/net/route');
989                         open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
990                                 or die "Could not open $PROC_NET_ROUTE";
992                         my @ifs = <PROC_NET_ROUTE>;
994                         close(PROC_NET_ROUTE);
996                         # Eat header line
997                         shift @ifs;
998                         chomp @ifs;
999                         foreach my $line(@ifs) {
1000                                 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
1001                                 my $destination;
1002                                 my $mask;
1003                                 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
1004                                 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
1005                                 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
1006                                 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
1007                                 if(new NetAddr::IP($target_ip)->within(new NetAddr::IP($destination, $mask))) {
1008                                         # destination matches route, save mac and exit
1009                                         $result= 1;
1010                                         last;
1011                                 }
1012                         }
1013                 }
1014         } else {
1015                 &main::daemon_log("Target ip $target_ip does not match Server ip $server_ip",1);
1016         }
1018         return $result;
1021 1;