Code

sharing job queue information among all si-server
[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;
165 #my $hostkey = &create_passwd;
166 #my $res = $main::known_server_db->add_dbentry( {table=>$main::known_server_tn, 
167 #            primkey=>['hostname'],
168 #            hostname=>$main::server_address,
169 #            status=>'myself',
170 #            hostkey=>$hostkey,
171 #            timestamp=>&get_time(),
172 #            } );
173 #if (not $res == 0) {
174 #    &main::daemon_log("0 ERROR: cannot add server to known_server_db: $res", 1);
175 #} else {
176 #    &main::daemon_log("0 INFO: '$main::server_address' successfully added to known_server_db", 5);
177 #}
181 ## create general settings for this module
182 #my $xml = new XML::Simple();
184 ## register at bus
185 #if ($main::no_bus > 0) {
186 #    $bus_activ = "off"
187 #}
188 #if($bus_activ eq "on") {
189 #    &register_at_bus();
190 #}
193 ### functions #################################################################
196 sub get_module_info {
197     my @info = ($server_address,
198                 $ClientPackages_key,
199                 );
200     return \@info;
204 #===  FUNCTION  ================================================================
205 #         NAME:  read_configfile
206 #   PARAMETERS:  cfg_file - string -
207 #      RETURNS:  nothing
208 #  DESCRIPTION:  read cfg_file and set variables
209 #===============================================================================
210 sub read_configfile {
211     my $cfg;
212     if( defined( $main::cfg_file) && ( (-s $main::cfg_file) > 0 )) {
213         if( -r $main::cfg_file ) {
214             $cfg = Config::IniFiles->new( -file => $main::cfg_file );
215         } else {
216             print STDERR "Couldn't read config file!";
217         }
218     } else {
219         $cfg = Config::IniFiles->new() ;
220     }
221     foreach my $section (keys %cfg_defaults) {
222         foreach my $param (keys %{$cfg_defaults{ $section }}) {
223             my $pinfo = $cfg_defaults{ $section }{ $param };
224             ${@$pinfo[0]} = $cfg->val( $section, $param, @$pinfo[1] );
225         }
226     }
228     # Read non predefined sections
229     my $param;
230     if ($cfg->SectionExists('ldap')){
231                 foreach $param ($cfg->Parameters('ldap')){
232                         push (@ldap_cfg, "$param ".$cfg->val('ldap', $param));
233                 }
234     }
235     if ($cfg->SectionExists('pam_ldap')){
236                 foreach $param ($cfg->Parameters('pam_ldap')){
237                         push (@pam_cfg, "$param ".$cfg->val('pam_ldap', $param));
238                 }
239     }
240     if ($cfg->SectionExists('nss_ldap')){
241                 foreach $param ($cfg->Parameters('nss_ldap')){
242                         push (@nss_cfg, "$param ".$cfg->val('nss_ldap', $param));
243                 }
244     }
245     if ($cfg->SectionExists('goto')){
246         $goto_admin= $cfg->val('goto', 'terminal_admin');
247         $goto_secret= $cfg->val('goto', 'terminal_secret');
248     } else {
249         $goto_admin= undef;
250         $goto_secret= undef;
251     }
255 # moved to GosaSupportDaemon: 03-06-2008 rettenbe
256 #===  FUNCTION  ================================================================
257 #         NAME:  get_interface_for_ip
258 #   PARAMETERS:  ip address (i.e. 192.168.0.1)
259 #      RETURNS:  array: list of interfaces if ip=0.0.0.0, matching interface if found, undef else
260 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
261 #===============================================================================
262 #sub get_interface_for_ip {
263 #       my $result;
264 #       my $ip= shift;
265 #       if ($ip && length($ip) > 0) {
266 #               my @ifs= &get_interfaces();
267 #               if($ip eq "0.0.0.0") {
268 #                       $result = "all";
269 #               } else {
270 #                       foreach (@ifs) {
271 #                               my $if=$_;
272 #                               if(&main::get_ip($if) eq $ip) {
273 #                                       $result = $if;
274 #                               }
275 #                       }       
276 #               }
277 #       }       
278 #       return $result;
279 #}
281 # moved to GosaSupportDaemon: 03-06-2008 rettenbe
282 #===  FUNCTION  ================================================================
283 #         NAME:  get_interfaces 
284 #   PARAMETERS:  none
285 #      RETURNS:  (list of interfaces) 
286 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
287 #===============================================================================
288 #sub get_interfaces {
289 #       my @result;
290 #       my $PROC_NET_DEV= ('/proc/net/dev');
292 #       open(PROC_NET_DEV, "<$PROC_NET_DEV")
293 #               or die "Could not open $PROC_NET_DEV";
295 #       my @ifs = <PROC_NET_DEV>;
297 #       close(PROC_NET_DEV);
299 #       # Eat first two line
300 #       shift @ifs;
301 #       shift @ifs;
303 #       chomp @ifs;
304 #       foreach my $line(@ifs) {
305 #               my $if= (split /:/, $line)[0];
306 #               $if =~ s/^\s+//;
307 #               push @result, $if;
308 #       }
310 #       return @result;
311 #}
313 #===  FUNCTION  ================================================================
314 #         NAME:  get_mac 
315 #   PARAMETERS:  interface name (i.e. eth0)
316 #      RETURNS:  (mac address) 
317 #  DESCRIPTION:  Uses ioctl to get mac address directly from system.
318 #===============================================================================
319 sub get_mac {
320         my $ifreq= shift;
321         my $result;
322         if ($ifreq && length($ifreq) > 0) { 
323                 if($ifreq eq "all") {
324                         $result = "00:00:00:00:00:00";
325                 } else {
326                         my $SIOCGIFHWADDR= 0x8927;     # man 2 ioctl_list
328                         # A configured MAC Address should always override a guessed value
329                         if ($main::server_mac_address and length($main::server_mac_address) > 0) {
330                                 $result= $main::server_mac_address;
331                         }
333                         socket SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('ip')
334                                 or die "socket: $!";
336                         if(ioctl SOCKET, $SIOCGIFHWADDR, $ifreq) {
337                                 my ($if, $mac)= unpack 'h36 H12', $ifreq;
339                                 if (length($mac) > 0) {
340                                         $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])$/;
341                                         $mac= sprintf("%s:%s:%s:%s:%s:%s", $1, $2, $3, $4, $5, $6);
342                                         $result = $mac;
343                                 }
344                         }
345                 }
346         }
347         return $result;
351 #===  FUNCTION  ================================================================
352 #         NAME:  register_at_bus
353 #   PARAMETERS:  nothing
354 #      RETURNS:  nothing
355 #  DESCRIPTION:  creates an entry in known_daemons and send a 'here_i_am' msg to bus
356 #===============================================================================
357 #sub register_at_bus {
359 #    # add bus to known_server_db
360 #    my $res = $main::known_server_db->add_dbentry( {table=>'known_server',
361 #                                                    primkey=>['hostname'],
362 #                                                    hostname=>$bus_address,
363 #                                                    status=>'bus',
364 #                                                    hostkey=>$bus_key,
365 #                                                    timestamp=>&get_time,
366 #                                                } );
367 #    my $msg_hash = &create_xml_hash("here_i_am", $server_address, $bus_address);
368 #    my $msg = &create_xml_string($msg_hash);
370 #    &main::send_msg_to_target($msg, $bus_address, $bus_key, "here_i_am");
371 #    return $msg;
372 #}
376 # outcommented from rettenbe: moved to GosaSupportDaemon.pm
377 #sub import_events {
378 #    if (not -e $event_dir) {
379 #        &main::daemon_log("S ERROR: cannot find directory or directory is not readable: $event_dir", 1);   
380 #    }
381 #    opendir (DIR, $event_dir) or die "ERROR while loading gosa-si-events from directory $event_dir : $!\n";
383 #    while (defined (my $event = readdir (DIR))) {
384 #        if( $event eq "." || $event eq ".." ) { next; }  
385 #        if( $event eq "gosaTriggered.pm" ) { next; }    # only GOsa specific events
387 #        eval{ require $event; };
388 #        if( $@ ) {
389 #            &main::daemon_log("S ERROR: import of event module '$event' failed", 1);
390 #            &main::daemon_log("$@", 8);
391 #            next;
392 #        }
394 #        $event =~ /(\S*?).pm$/;
395 #        my $event_module = $1;
396 #        my $events_l = eval( $1."::get_events()") ;
397 #        foreach my $event_name (@{$events_l}) {
398 #            $event_hash->{$event_name} = $event_module;
399 #        }
400 #        my $events_string = join( ", ", @{$events_l});
401 #        &main::daemon_log("S DEBUG: ClientPackages imported events $events_string", 8);
402 #    }
403 #}
406 #===  FUNCTION  ================================================================
407 #         NAME:  process_incoming_msg
408 #   PARAMETERS:  crypted_msg - string - incoming crypted message
409 #      RETURNS:  nothing
410 #  DESCRIPTION:  handels the proceeded distribution to the appropriated functions
411 #===============================================================================
412 sub process_incoming_msg {
413     my ($msg, $msg_hash, $session_id) = @_ ;
414     my $error = 0;
415     my $host_name;
416     my $host_key;
417     my @out_msg_l = ("nohandler");
418     my $sql_events;
420     # process incoming msg
421     my $header = @{$msg_hash->{header}}[0]; 
422     my $source = @{$msg_hash->{source}}[0]; 
423     my @target_l = @{$msg_hash->{target}};
425     # skip PREFIX
426     $header =~ s/^CLMSG_//;
428     &main::daemon_log("$session_id DEBUG: ClientPackages: msg to process: $header", 7);
430     if( 0 == length @target_l){     
431         &main::daemon_log("$session_id ERROR: no target specified for msg $header", 1);
432         $error++;
433     }
435     if( 1 == length @target_l) {
436         my $target = $target_l[0];
437                 if(&server_matches($target)) {
438             if ($header eq 'new_key') {
439                 @out_msg_l = &new_key($msg_hash)
440             } elsif ($header eq 'here_i_am') {
441                 @out_msg_l = &here_i_am($msg, $msg_hash, $session_id)
442             } else {
443                 # a event exists with the header as name
444                 if( exists $event_hash->{$header} ) {
445                     &main::daemon_log("$session_id INFO: found event '$header' at event-module '".$event_hash->{$header}."'", 5);
446                     no strict 'refs';
447                     @out_msg_l = &{$event_hash->{$header}."::$header"}($msg, $msg_hash, $session_id);
449                 # if no event handler is implemented   
450                 } else {
451                     $sql_events = "SELECT * FROM $main::known_clients_tn WHERE ( (macaddress LIKE '$source') OR (hostname='$source') )"; 
452                     my $res = $main::known_clients_db->select_dbentry( $sql_events );
453                     my $l = keys(%$res);
455                     # set error if no or more than 1 hits are found for sql query
456                     if ( $l != 1) {
457                         @out_msg_l = ('knownclienterror');
459                     # found exact 1 hit in db
460                     } else {
461                         my $client_events = $res->{'1'}->{'events'};
463                         # client is registered for this event, deliver this message to client
464                         $header =~ s/^answer_//;
465                         if ($client_events =~ /,$header,/) {
466                             # answer message finally arrived destination server, so forward messages to GOsa
467                             if ($target eq $main::server_address) {        
468                                 $msg =~ s/<header>answer_/<header>/;
469                                 $msg =~ s/<target>\S+<\/target>/<target>GOSA<\/target>/;
470                             }
471                             @out_msg_l = ( $msg );
473                         # client is not registered for this event, set error
474                         } else {
475                             @out_msg_l = ('noeventerror');
476                         }
477                     }
478                 }
479             }
481             # if delivery not possible raise error and return 
482             if( not defined $out_msg_l[0] ) {
483                 @out_msg_l = ();
484             } elsif( $out_msg_l[0] eq 'nohandler') {
485                 &main::daemon_log("$session_id ERROR: ClientPackages: no event handler or core function defined for '$header'", 1);
486                 @out_msg_l = ();
487             }  elsif ($out_msg_l[0] eq 'knownclienterror') {
488                 &main::daemon_log("$session_id ERROR: no or more than 1 hits are found at known_clients_db with sql query: '$sql_events'", 1);
489                 &main::daemon_log("$session_id WARNING: processing is aborted and message will not be forwarded");
490                 @out_msg_l = ();
491             } elsif ($out_msg_l[0] eq 'noeventerror') {
492                 &main::daemon_log("$session_id WARNING: client '$target' is not registered for event '$header', processing is aborted", 1); 
493                 @out_msg_l = ();
494             }
499         }
500                 else {
501                         &main::daemon_log("INFO: msg is not for gosa-si-server '$server_address', deliver it to target '$target'", 5);
502                         push(@out_msg_l, $msg);
503                 }
504     }
506     return \@out_msg_l;
510 #===  FUNCTION  ================================================================
511 #         NAME:  new_passwd
512 #   PARAMETERS:  msg_hash - ref - hash from function create_xml_hash
513 #      RETURNS:  nothing
514 #  DESCRIPTION:  process this incoming message
515 #===============================================================================
516 sub new_key {
517     my ($msg_hash) = @_;
518     my @out_msg_l;
519     
520     my $header = @{$msg_hash->{header}}[0];
521     my $source_name = @{$msg_hash->{source}}[0];
522     my $source_key = @{$msg_hash->{new_key}}[0];
523     my $query_res;
525     # check known_clients_db
526     my $sql_statement = "SELECT * FROM known_clients WHERE hostname='$source_name'";
527     $query_res = $main::known_clients_db->select_dbentry( $sql_statement );
528     if( 1 == keys %{$query_res} ) {
529         my $act_time = &get_time;
530         my $sql_statement= "UPDATE known_clients ".
531             "SET hostkey='$source_key', timestamp='$act_time' ".
532             "WHERE hostname='$source_name'";
533         my $res = $main::known_clients_db->update_dbentry( $sql_statement );
534         my $hash = &create_xml_hash("confirm_new_key", $server_address, $source_name);
535         my $out_msg = &create_xml_string($hash);
536         push(@out_msg_l, $out_msg);
537     }
539     # only do if host still not found
540     if( 0 == @out_msg_l ) {
541         # check known_server_db
542         $sql_statement = "SELECT * FROM known_server WHERE hostname='$source_name'";
543         $query_res = $main::known_server_db->select_dbentry( $sql_statement );
544         if( 1 == keys %{$query_res} ) {
545             my $act_time = &get_time;
546             my $sql_statement= "UPDATE known_server ".
547                 "SET hostkey='$source_key', timestamp='$act_time' ".
548                 "WHERE hostname='$source_name'";
549             my $res = $main::known_server_db->update_dbentry( $sql_statement );
551             my $hash = &create_xml_hash("confirm_new_key", $server_address, $source_name);
552             my $out_msg = &create_xml_string($hash);
553             push(@out_msg_l, $out_msg);
554         }
555     }
557     return @out_msg_l;
561 #===  FUNCTION  ================================================================
562 #         NAME:  here_i_am
563 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
564 #      RETURNS:  nothing
565 #  DESCRIPTION:  process this incoming message
566 #===============================================================================
567 sub here_i_am {
568     my ($msg, $msg_hash, $session_id) = @_;
569     my @out_msg_l;
570     my $out_hash;
571     my $source = @{$msg_hash->{source}}[0];
572     my $mac_address = @{$msg_hash->{mac_address}}[0];
573         my $gotoHardwareChecksum = @{$msg_hash->{gotoHardwareChecksum}}[0];
574     my $client_status = @{$msg_hash->{client_status}}[0];
575     my $client_revision = @{$msg_hash->{client_revision}}[0];
576     my $key_lifetime = @{$msg_hash->{key_lifetime}}[0];
578     # number of known clients
579     my $nu_clients= $main::known_clients_db->count_dbentries('known_clients');
581     # check wether client address or mac address is already known
582     my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$source'";
583     my $db_res= $main::known_clients_db->select_dbentry( $sql_statement );
584     
585     if ( 1 == keys %{$db_res} ) {
586         &main::daemon_log("$session_id WARNING: $source is already known as a client", 1);
587         &main::daemon_log("$session_id WARNING: values for $source are being overwritten", 1);   
588         $nu_clients --;
589     }
591     # number of actual activ clients
592     my $act_nu_clients = $nu_clients;
594     &main::daemon_log("$session_id INFO: number of actual activ clients: $act_nu_clients", 5);
595     &main::daemon_log("$session_id INFO: number of maximal allowed clients: $max_clients", 5);
597     if($max_clients <= $act_nu_clients) {
598         my $out_hash = &create_xml_hash("denied", $server_address, $source);
599         &add_content2xml_hash($out_hash, "denied", "I_cannot_take_any_more_clients!");
600         my $passwd = @{$msg_hash->{new_passwd}}[0]; 
601         &send_msg_hash2address($out_hash, $source, $passwd);
602         return;
603     }
604     
605     # new client accepted
606     my $new_passwd = @{$msg_hash->{new_passwd}}[0];
608     # add entry to known_clients_db
609     my $events = @{$msg_hash->{events}}[0];
610     my $act_timestamp = &get_time;
611     my $res = $main::known_clients_db->add_dbentry( {table=>'known_clients', 
612                                                 primkey=>['hostname'],
613                                                 hostname=>$source,
614                                                 events=>$events,
615                                                 macaddress=>$mac_address,
616                                                 status=>'registered',
617                                                 hostkey=>$new_passwd,
618                                                 timestamp=>$act_timestamp,
619                                                 keylifetime=>$key_lifetime,
620                                                 } );
622     if ($res != 0)  {
623         &main::daemon_log("$session_id ERROR: cannot add entry to known_clients: $res");
624         return;
625     }
626     
627     # return acknowledgement to client
628     $out_hash = &create_xml_hash("registered", $server_address, $source);
631     # give the new client his ldap config
632     # Workaround: Send within the registration response, if the client will get an ldap config later
633         my $new_ldap_config_out = &new_ldap_config($source, $session_id);
634         if($new_ldap_config_out && (!($new_ldap_config_out =~ /error/))) {
635                 &add_content2xml_hash($out_hash, "ldap_available", "true");
636         } elsif($new_ldap_config_out && $new_ldap_config_out =~ /error/){
637                 &add_content2xml_hash($out_hash, "error", $new_ldap_config_out);
639                 my $sql_statement = "UPDATE $main::job_queue_tn ".
640                 "SET status='error', result='$new_ldap_config_out' ".
641                 "WHERE status='processing' AND macaddress LIKE '$mac_address'";
642                 my $res = $main::job_db->update_dbentry($sql_statement);
643                 &main::daemon_log("$session_id DEBUG: $sql_statement RESULT: $res", 7);         
644         }
645     my $register_out = &create_xml_string($out_hash);
646     push(@out_msg_l, $register_out);
648     # Really send the ldap config
649     if( $new_ldap_config_out && (!($new_ldap_config_out =~ /error/))) {
650             push(@out_msg_l, $new_ldap_config_out);
651     }
653         my $hardware_config_out = &hardware_config($msg, $msg_hash, $session_id);
654         if( $hardware_config_out ) {
655                 push(@out_msg_l, $hardware_config_out);
656         }
658     # notify registered client to all other server
659     my %mydata = ( 'client' => $source, 'macaddress' => $mac_address);
660     my $mymsg = &build_msg('new_foreign_client', $main::server_address, "KNOWN_SERVER", \%mydata);
661     push(@out_msg_l, $mymsg);
663     &main::daemon_log("$session_id INFO: register client $source ($mac_address)", 5);
664     &main::daemon_log("$session_id INFO: client version: $client_status - $client_revision", 5); 
665     return @out_msg_l;
669 #===  FUNCTION  ================================================================
670 #         NAME:  who_has
671 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
672 #      RETURNS:  nothing 
673 #  DESCRIPTION:  process this incoming message
674 #===============================================================================
675 sub who_has {
676     my ($msg_hash) = @_ ;
677     my @out_msg_l;
678     
679     # what is your search pattern
680     my $search_pattern = @{$msg_hash->{who_has}}[0];
681     my $search_element = @{$msg_hash->{$search_pattern}}[0];
682     &main::daemon_log("who_has-msg looking for $search_pattern $search_element", 7);
684     # scanning known_clients for search_pattern
685     my @host_addresses = keys %$main::known_clients;
686     my $known_clients_entries = length @host_addresses;
687     my $host_address;
688     foreach my $host (@host_addresses) {
689         my $client_element = $main::known_clients->{$host}->{$search_pattern};
690         if ($search_element eq $client_element) {
691             $host_address = $host;
692             last;
693         }
694     }
695         
696     # search was successful
697     if (defined $host_address) {
698         my $source = @{$msg_hash->{source}}[0];
699         my $out_hash = &create_xml_hash("who_has_i_do", $server_address, $source, "mac_address");
700         &add_content2xml_hash($out_hash, "mac_address", $search_element);
701         my $out_msg = &create_xml_string($out_hash);
702         push(@out_msg_l, $out_msg);
703     }
704     return @out_msg_l;
708 sub who_has_i_do {
709     my ($msg_hash) = @_ ;
710     my $header = @{$msg_hash->{header}}[0];
711     my $source = @{$msg_hash->{source}}[0];
712     my $search_param = @{$msg_hash->{$header}}[0];
713     my $search_value = @{$msg_hash->{$search_param}}[0];
714     print "\ngot msg $header:\nserver $source has client with $search_param $search_value\n";
718 #===  FUNCTION  ================================================================
719 #         NAME:  new_ldap_config
720 #   PARAMETERS:  address - string - ip address and port of a host
721 #      RETURNS:  gosa-si conform message
722 #  DESCRIPTION:  send to address the ldap configuration found for dn gotoLdapServer
723 #===============================================================================
724 sub new_ldap_config {
725         my ($address, $session_id) = @_ ;
727         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address' OR macaddress LIKE '$address'";
728         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
730         # check hit
731         my $hit_counter = keys %{$res};
732         if( not $hit_counter == 1 ) {
733                 &main::daemon_log("$session_id ERROR: more or no hit found in known_clients_db by query '$sql_statement'", 1);
734         }
736     $address = $res->{1}->{hostname};
737         my $macaddress = $res->{1}->{macaddress};
738         my $hostkey = $res->{1}->{hostkey};
740         if (not defined $macaddress) {
741                 &main::daemon_log("$session_id ERROR: no mac address found for client $address", 1);
742                 return;
743         }
745         # Build LDAP connection
746     my $ldap_handle = &main::get_ldap_handle($session_id);
747         if( not defined $ldap_handle ) {
748                 &main::daemon_log("$session_id ERROR: cannot connect to ldap: $ldap_uri", 1);
749                 return;
750         } 
752         # Perform search
753     $mesg = $ldap_handle->search( base   => $ldap_base,
754                 scope  => 'sub',
755                 attrs => ['dn', 'gotoLdapServer', 'gosaUnitTag', 'FAIclass'],
756                 filter => "(&(objectClass=GOhard)(macaddress=$macaddress))");
757         if($mesg->code) {
758                 &main::daemon_log("$session_id ".$mesg->error, 1);
759                 return;
760         }
762         # Sanity check
763         if ($mesg->count != 1) {
764                 &main::daemon_log("$session_id WARNING: client with mac address $macaddress not found/unique/active - not sending ldap config".
765                 "\n\tbase: $ldap_base".
766                 "\n\tscope: sub".
767                 "\n\tattrs: dn, gotoLdapServer".
768                 "\n\tfilter: (&(objectClass=GOhard)(macaddress=$macaddress))", 1);
769                 return;
770         }
772         my $entry= $mesg->entry(0);
773         my $dn= $entry->dn;
774         my @servers= $entry->get_value("gotoLdapServer");
775         my $unit_tag= $entry->get_value("gosaUnitTag");
776         my @ldap_uris;
777         my $server;
778         my $base;
779         my $release;
781         # Fill release if available
782         my $FAIclass= $entry->get_value("FAIclass");
783         if (defined $FAIclass && $FAIclass =~ /^.* :([A-Za-z0-9\/.]+).*$/) {
784                 $release= $1;
785         }
787         # Do we need to look at an object class?
788         if (not @servers){
789                 $mesg = $ldap_handle->search( base   => $ldap_base,
790                         scope  => 'sub',
791                         attrs => ['dn', 'gotoLdapServer', 'FAIclass'],
792                         filter => "(&(objectClass=gosaGroupOfNames)(member=$dn))");
793                 if($mesg->code) {
794                         &main::daemon_log("$session_id ERROR: unable to search for '(&(objectClass=gosaGroupOfNames)(member=$dn))': ".$mesg->error, 1);
795                         return;
796                 }
798                 # Sanity check
799                 if ($mesg->count == 0) {
800                         &main::daemon_log("$session_id WARNING: no LDAP informations found for client  with filter '(&(objectClass=gosaGroupOfNames)(member=$dn))'", 3);
801                         return;
802                 } elsif ($mesg->count >= 2) {
803             &main::daemon_log("$session_id ERROR: multiple LDAP informations found for client  with filter '(&(objectClass=gosaGroupOfNames)(member=$dn))'", 1);
804             return;
805         }
807                 $entry= $mesg->entry(0);
808                 $dn= $entry->dn;
809                 @servers= $entry->get_value("gotoLdapServer");
811                 if (not defined $release){
812                         $FAIclass= $entry->get_value("FAIclass");
813                         if (defined $FAIclass && $FAIclass =~ /^.* :([A-Za-z0-9\/.]+).*$/) {
814                                 $release= $1;
815                         }
816                 }
817         }
819         @servers= sort (@servers);
821     # complain if no ldap information found
822     if (@servers == 0) {
823         &main::daemon_log("$session_id ERROR: no gotoLdapServer information for LDAP entry with filter '(&(objectClass=gosaGroupOfNames)(member=$dn))'");
824     }
826         foreach $server (@servers){
827                 # Conversation for backward compatibility
828                 if (not $server =~ /^\d+:[^:]+:ldap[^:]*:\/\// ) {
829                     if ($server =~ /^([^:]+):([^:]+)$/ ) {
830                       $server= "1:dummy:ldap://$1/$2";
831                     } elsif ($server =~ /^(\d+):([^:]+):(.*)$/ ) {
832                       $server= "$1:dummy:ldap://$2/$3";
833                     }
834                 }
836                 $base= $server;
837                 $server =~ s%^[^:]+:[^:]+:(ldap.*://[^/]+)/.*$%$1%;
838                 $base =~ s%^[^:]+:[^:]+:ldap.*://[^/]+/(.*)$%$1%;
839                 push (@ldap_uris, $server);
840         }
842         # Assemble data package
843         my %data = ( 'ldap_uri'  => \@ldap_uris, 'ldap_base' => $base,
844                 'ldap_cfg' => \@ldap_cfg, 'pam_cfg' => \@pam_cfg,'nss_cfg' => \@nss_cfg );
845         if (defined $release){
846                 $data{'release'}= $release;
847         }
849         # Need to append GOto settings?
850         if (defined $goto_admin and defined $goto_secret){
851                 $data{'goto_admin'}= $goto_admin;
852                 $data{'goto_secret'}= $goto_secret;
853         }
855         # Append unit tag if needed
856         if (defined $unit_tag){
858                 # Find admin base and department name
859                 $mesg = $ldap_handle->search( base   => $ldap_base,
860                         scope  => 'sub',
861                         attrs => ['dn', 'ou'],
862                         filter => "(&(objectClass=gosaAdministrativeUnit)(gosaUnitTag=$unit_tag))");
863                 #$mesg->code && die $mesg->error;
864                 if($mesg->code) {
865                         &main::daemon_log($mesg->error, 1);
866                         return "error-unit-tag-count-0";
867                 }
869                 # Sanity check
870                 if ($mesg->count != 1) {
871                         &main::daemon_log("WARNING: cannot find administrative unit for client with tag $unit_tag", 1);
872                         return "error-unit-tag-count-".$mesg->count;
873                 }
875                 $entry= $mesg->entry(0);
876                 $data{'admin_base'}= $entry->dn;
877                 $data{'department'}= $entry->get_value("ou");
879                 # Append unit Tag
880                 $data{'unit_tag'}= $unit_tag;
881         }
883         # Send information
884         return &build_msg("new_ldap_config", $server_address, $address, \%data);
888 #===  FUNCTION  ================================================================
889 #         NAME:  hardware_config
890 #   PARAMETERS:  address - string - ip address and port of a host
891 #      RETURNS:  
892 #  DESCRIPTION:  
893 #===============================================================================
894 sub hardware_config {
895         my ($msg, $msg_hash, $session_id) = @_ ;
896         my $address = @{$msg_hash->{source}}[0];
897         my $header = @{$msg_hash->{header}}[0];
898         my $gotoHardwareChecksum = @{$msg_hash->{gotoHardwareChecksum}}[0];
900         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address'";
901         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
903         # check hit
904         my $hit_counter = keys %{$res};
905         if( not $hit_counter == 1 ) {
906                 &main::daemon_log("$session_id ERROR: more or no hit found in known_clients_db by query by '$address'", 1);
907         }
908         my $macaddress = $res->{1}->{macaddress};
909         my $hostkey = $res->{1}->{hostkey};
911         if (not defined $macaddress) {
912                 &main::daemon_log("$session_id ERROR: no mac address found for client $address", 1);
913                 return;
914         }
916         # Build LDAP connection
917     my $ldap_handle = &main::get_ldap_handle($session_id);
918         if( not defined $ldap_handle ) {
919                 &main::daemon_log("$session_id ERROR: cannot connect to ldap: $ldap_uri", 1);
920                 return;
921         } 
923         # Perform search
924         $mesg = $ldap_handle->search(
925                 base   => $ldap_base,
926                 scope  => 'sub',
927                 filter => "(&(objectClass=GOhard)(|(macAddress=$macaddress)(dhcpHWaddress=ethernet $macaddress)))"
928         );
930         if($mesg->count() == 0) {
931                 &main::daemon_log("Host was not found in LDAP!", 1);
933                 # set status = hardware_detection at jobqueue if entry exists
934                 # TODO
935                 # resolve plain name for host
936                 my $func_dic = {table=>$main::job_queue_tn,
937                                 primkey=>['macaddress', 'headertag'],
938                                 timestamp=>&get_time,
939                                 status=>'processing',
940                                 result=>'none',
941                                 progress=>'hardware-detection',
942                                 headertag=>'trigger_action_reinstall',
943                                 targettag=>$address,
944                                 xmlmessage=>'none',
945                                 macaddress=>$macaddress,
946                                 plainname=>'none',
947                 siserver=>'localhost',
948                 modified=>'1',
949                 };
950                 my $hd_res = $main::job_db->add_dbentry($func_dic);
951                 &main::daemon_log("$session_id INFO: add '$macaddress' to job queue as an installing job", 5);
952         
953         } else {
954                 my $entry= $mesg->entry(0);
955                 my $dn= $entry->dn;
956                 if (defined($entry->get_value("gotoHardwareChecksum"))) {
957                         if (! $entry->get_value("gotoHardwareChecksum") eq $gotoHardwareChecksum) {
958                                 $entry->replace(gotoHardwareChecksum => $gotoHardwareChecksum);
959                                 if($entry->update($ldap_handle)) {
960                                         &main::daemon_log("$session_id INFO: Hardware changed! Detection triggered.", 5);
961                                 }
962                         } else {
963                                 # Nothing to do
964                                 return;
965                         }
966                 } 
967         } 
969         # Assemble data package
970         my %data = ();
972         # Need to append GOto settings?
973         if (defined $goto_admin and defined $goto_secret){
974                 $data{'goto_admin'}= $goto_admin;
975                 $data{'goto_secret'}= $goto_secret;
976         }
978         # Send information
979         return &build_msg("detect_hardware", $server_address, $address, \%data);
982 sub server_matches {
983         my $target = shift;
984         my $target_ip = ($1) if $target =~ /^([0-9\.]*?):.*$/;
985         if(!defined($target_ip) or length($target_ip) == 0) {
986                 return;
987         }
989         my $result = 0;
991         if($server_ip eq $target_ip) {
992                 $result= 1;
993         } elsif ($target_ip eq "0.0.0.0") {
994                 $result= 1;
995         } elsif ($server_ip eq "0.0.0.0") {     
996                 if ($target_ip eq "127.0.0.1") {
997                         $result= 1;
998                 } else {
999                         my $PROC_NET_ROUTE= ('/proc/net/route');
1001                         open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
1002                                 or die "Could not open $PROC_NET_ROUTE";
1004                         my @ifs = <PROC_NET_ROUTE>;
1006                         close(PROC_NET_ROUTE);
1008                         # Eat header line
1009                         shift @ifs;
1010                         chomp @ifs;
1011                         foreach my $line(@ifs) {
1012                                 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
1013                                 my $destination;
1014                                 my $mask;
1015                                 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
1016                                 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
1017                                 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
1018                                 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
1019                                 if(new NetAddr::IP($target_ip)->within(new NetAddr::IP($destination, $mask))) {
1020                                         # destination matches route, save mac and exit
1021                                         $result= 1;
1022                                         last;
1023                                 }
1024                         }
1025                 }
1026         } else {
1027                 &main::daemon_log("Target ip $target_ip does not match Server ip $server_ip",1);
1028         }
1030         return $result;
1033 1;