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();
175 # add myself to known_server_db
176 my $res = $main::known_server_db->add_dbentry( {table=>'known_server',
177         primkey=>['hostname'],
178         hostname=>$server_address,
179         status=>'myself',
180         hostkey=>$ClientPackages_key,
181         timestamp=>&get_time,
182         } );
186 ### functions #################################################################
189 sub get_module_info {
190     my @info = ($server_address,
191                 $ClientPackages_key,
192                 );
193     return \@info;
197 #===  FUNCTION  ================================================================
198 #         NAME:  read_configfile
199 #   PARAMETERS:  cfg_file - string -
200 #      RETURNS:  nothing
201 #  DESCRIPTION:  read cfg_file and set variables
202 #===============================================================================
203 sub read_configfile {
204     my $cfg;
205     if( defined( $main::cfg_file) && ( (-s $main::cfg_file) > 0 )) {
206         if( -r $main::cfg_file ) {
207             $cfg = Config::IniFiles->new( -file => $main::cfg_file );
208         } else {
209             print STDERR "Couldn't read config file!";
210         }
211     } else {
212         $cfg = Config::IniFiles->new() ;
213     }
214     foreach my $section (keys %cfg_defaults) {
215         foreach my $param (keys %{$cfg_defaults{ $section }}) {
216             my $pinfo = $cfg_defaults{ $section }{ $param };
217             ${@$pinfo[0]} = $cfg->val( $section, $param, @$pinfo[1] );
218         }
219     }
221     # Read non predefined sections
222     my $param;
223     if ($cfg->SectionExists('ldap')){
224                 foreach $param ($cfg->Parameters('ldap')){
225                         push (@ldap_cfg, "$param ".$cfg->val('ldap', $param));
226                 }
227     }
228     if ($cfg->SectionExists('pam_ldap')){
229                 foreach $param ($cfg->Parameters('pam_ldap')){
230                         push (@pam_cfg, "$param ".$cfg->val('pam_ldap', $param));
231                 }
232     }
233     if ($cfg->SectionExists('nss_ldap')){
234                 foreach $param ($cfg->Parameters('nss_ldap')){
235                         push (@nss_cfg, "$param ".$cfg->val('nss_ldap', $param));
236                 }
237     }
238     if ($cfg->SectionExists('goto')){
239         $goto_admin= $cfg->val('goto', 'terminal_admin');
240         $goto_secret= $cfg->val('goto', 'terminal_secret');
241     } else {
242         $goto_admin= undef;
243         $goto_secret= undef;
244     }
248 #===  FUNCTION  ================================================================
249 #         NAME:  get_interface_for_ip
250 #   PARAMETERS:  ip address (i.e. 192.168.0.1)
251 #      RETURNS:  array: list of interfaces if ip=0.0.0.0, matching interface if found, undef else
252 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
253 #===============================================================================
254 sub get_interface_for_ip {
255         my $result;
256         my $ip= shift;
257         if ($ip && length($ip) > 0) {
258                 my @ifs= &get_interfaces();
259                 if($ip eq "0.0.0.0") {
260                         $result = "all";
261                 } else {
262                         foreach (@ifs) {
263                                 my $if=$_;
264                                 if(&main::get_ip($if) eq $ip) {
265                                         $result = $if;
266                                 }
267                         }       
268                 }
269         }       
270         return $result;
273 #===  FUNCTION  ================================================================
274 #         NAME:  get_interfaces 
275 #   PARAMETERS:  none
276 #      RETURNS:  (list of interfaces) 
277 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
278 #===============================================================================
279 sub get_interfaces {
280         my @result;
281         my $PROC_NET_DEV= ('/proc/net/dev');
283         open(PROC_NET_DEV, "<$PROC_NET_DEV")
284                 or die "Could not open $PROC_NET_DEV";
286         my @ifs = <PROC_NET_DEV>;
288         close(PROC_NET_DEV);
290         # Eat first two line
291         shift @ifs;
292         shift @ifs;
294         chomp @ifs;
295         foreach my $line(@ifs) {
296                 my $if= (split /:/, $line)[0];
297                 $if =~ s/^\s+//;
298                 push @result, $if;
299         }
301         return @result;
304 #===  FUNCTION  ================================================================
305 #         NAME:  get_mac 
306 #   PARAMETERS:  interface name (i.e. eth0)
307 #      RETURNS:  (mac address) 
308 #  DESCRIPTION:  Uses ioctl to get mac address directly from system.
309 #===============================================================================
310 sub get_mac {
311         my $ifreq= shift;
312         my $result;
313         if ($ifreq && length($ifreq) > 0) { 
314                 if($ifreq eq "all") {
315                         $result = "00:00:00:00:00:00";
316                 } else {
317                         my $SIOCGIFHWADDR= 0x8927;     # man 2 ioctl_list
319                         # A configured MAC Address should always override a guessed value
320                         if ($main::server_mac_address and length($main::server_mac_address) > 0) {
321                                 $result= $main::server_mac_address;
322                         }
324                         socket SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('ip')
325                                 or die "socket: $!";
327                         if(ioctl SOCKET, $SIOCGIFHWADDR, $ifreq) {
328                                 my ($if, $mac)= unpack 'h36 H12', $ifreq;
330                                 if (length($mac) > 0) {
331                                         $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])$/;
332                                         $mac= sprintf("%s:%s:%s:%s:%s:%s", $1, $2, $3, $4, $5, $6);
333                                         $result = $mac;
334                                 }
335                         }
336                 }
337         }
338         return $result;
342 #===  FUNCTION  ================================================================
343 #         NAME:  register_at_bus
344 #   PARAMETERS:  nothing
345 #      RETURNS:  nothing
346 #  DESCRIPTION:  creates an entry in known_daemons and send a 'here_i_am' msg to bus
347 #===============================================================================
348 sub register_at_bus {
350     # add bus to known_server_db
351     my $res = $main::known_server_db->add_dbentry( {table=>'known_server',
352                                                     primkey=>['hostname'],
353                                                     hostname=>$bus_address,
354                                                     status=>'bus',
355                                                     hostkey=>$bus_key,
356                                                     timestamp=>&get_time,
357                                                 } );
358     my $msg_hash = &create_xml_hash("here_i_am", $server_address, $bus_address);
359     my $msg = &create_xml_string($msg_hash);
361     &main::send_msg_to_target($msg, $bus_address, $bus_key, "here_i_am");
362     return $msg;
367 # outcommented from rettenbe: moved to GosaSupportDaemon.pm
368 #sub import_events {
369 #    if (not -e $event_dir) {
370 #        &main::daemon_log("S ERROR: cannot find directory or directory is not readable: $event_dir", 1);   
371 #    }
372 #    opendir (DIR, $event_dir) or die "ERROR while loading gosa-si-events from directory $event_dir : $!\n";
374 #    while (defined (my $event = readdir (DIR))) {
375 #        if( $event eq "." || $event eq ".." ) { next; }  
376 #        if( $event eq "gosaTriggered.pm" ) { next; }    # only GOsa specific events
378 #        eval{ require $event; };
379 #        if( $@ ) {
380 #            &main::daemon_log("S ERROR: import of event module '$event' failed", 1);
381 #            &main::daemon_log("$@", 8);
382 #            next;
383 #        }
385 #        $event =~ /(\S*?).pm$/;
386 #        my $event_module = $1;
387 #        my $events_l = eval( $1."::get_events()") ;
388 #        foreach my $event_name (@{$events_l}) {
389 #            $event_hash->{$event_name} = $event_module;
390 #        }
391 #        my $events_string = join( ", ", @{$events_l});
392 #        &main::daemon_log("S DEBUG: ClientPackages imported events $events_string", 8);
393 #    }
394 #}
397 #===  FUNCTION  ================================================================
398 #         NAME:  process_incoming_msg
399 #   PARAMETERS:  crypted_msg - string - incoming crypted message
400 #      RETURNS:  nothing
401 #  DESCRIPTION:  handels the proceeded distribution to the appropriated functions
402 #===============================================================================
403 sub process_incoming_msg {
404     my ($msg, $msg_hash, $session_id) = @_ ;
405     my $error = 0;
406     my $host_name;
407     my $host_key;
408     my @out_msg_l = ("nohandler");
409     my $sql_events;
411     # process incoming msg
412     my $header = @{$msg_hash->{header}}[0]; 
413     my $source = @{$msg_hash->{source}}[0]; 
414     my @target_l = @{$msg_hash->{target}};
416     # skip PREFIX
417     $header =~ s/^CLMSG_//;
419     &main::daemon_log("$session_id DEBUG: ClientPackages: msg to process: $header", 7);
421     if( 0 == length @target_l){     
422         &main::daemon_log("$session_id ERROR: no target specified for msg $header", 1);
423         $error++;
424     }
426     if( 1 == length @target_l) {
427         my $target = $target_l[0];
428                 if(&server_matches($target)) {
429             if ($header eq 'new_key') {
430                 @out_msg_l = &new_key($msg_hash)
431             } elsif ($header eq 'here_i_am') {
432                 @out_msg_l = &here_i_am($msg, $msg_hash, $session_id)
433             } else {
434                 if( exists $event_hash->{$header} ) {
435                     # a event exists with the header as name
436                     &main::daemon_log("$session_id INFO: found event '$header' at event-module '".$event_hash->{$header}."'", 5);
437                     no strict 'refs';
438                     @out_msg_l = &{$event_hash->{$header}."::$header"}($msg, $msg_hash, $session_id);
439                 } else {
440                     $sql_events = "SELECT * FROM $main::known_clients_tn WHERE ( (macaddress LIKE '$source') OR (hostname='$source') )"; 
441                     my $res = $main::known_clients_db->select_dbentry( $sql_events );
442                     my $l = keys(%$res);
444                     # set error if no or more than 1 hits are found for sql query
445                     if ( $l != 1) {
446                         @out_msg_l = ('knownclienterror');
448                     # found exact 1 hit in db
449                     } else {
450                         my $client_events = $res->{'1'}->{'events'};
452                         # client is registered for this event, deliver this message to client
453                         $header =~ s/^answer_//;
454                         if ($client_events =~ /,$header,/) {
455                             # answer message finally arrived destination server, so forward messages to GOsa
456                             if ($target eq $main::server_address) {        
457                                 $msg =~ s/<header>answer_/<header>/;
458                                 $msg =~ s/<target>\S+<\/target>/<target>GOSA<\/target>/;
459                             }
460                             @out_msg_l = ( $msg );
462                         # client is not registered for this event, set error
463                         } else {
464                             @out_msg_l = ('noeventerror');
465                         }
466                     }
467                 }
468             }
470             # if delivery not possible raise error and return 
471             if( not defined $out_msg_l[0] ) {
472                 @out_msg_l = ();
473             } elsif( $out_msg_l[0] eq 'nohandler') {
474                 &main::daemon_log("$session_id ERROR: ClientPackages: no event handler or core function defined for '$header'", 1);
475                 @out_msg_l = ();
476             }  elsif ($out_msg_l[0] eq 'knownclienterror') {
477                 &main::daemon_log("$session_id ERROR: no or more than 1 hits are found at known_clients_db with sql query: '$sql_events'", 1);
478                 &main::daemon_log("$session_id WARNING: processing is aborted and message will not be forwarded");
479                 @out_msg_l = ();
480             } elsif ($out_msg_l[0] eq 'noeventerror') {
481                 &main::daemon_log("$session_id WARNING: client '$target' is not registered for event '$header', processing is aborted", 1); 
482                 @out_msg_l = ();
483             }
488         }
489                 else {
490                         &main::daemon_log("INFO: msg is not for gosa-si-server '$server_address', deliver it to target '$target'", 5);
491                         push(@out_msg_l, $msg);
492                 }
493     }
495     return \@out_msg_l;
499 #===  FUNCTION  ================================================================
500 #         NAME:  new_passwd
501 #   PARAMETERS:  msg_hash - ref - hash from function create_xml_hash
502 #      RETURNS:  nothing
503 #  DESCRIPTION:  process this incoming message
504 #===============================================================================
505 sub new_key {
506     my ($msg_hash) = @_;
507     my @out_msg_l;
508     
509     my $header = @{$msg_hash->{header}}[0];
510     my $source_name = @{$msg_hash->{source}}[0];
511     my $source_key = @{$msg_hash->{new_key}}[0];
512     my $query_res;
514     # check known_clients_db
515     my $sql_statement = "SELECT * FROM known_clients WHERE hostname='$source_name'";
516     $query_res = $main::known_clients_db->select_dbentry( $sql_statement );
517     if( 1 == keys %{$query_res} ) {
518         my $act_time = &get_time;
519         my $sql_statement= "UPDATE known_clients ".
520             "SET hostkey='$source_key', timestamp='$act_time' ".
521             "WHERE hostname='$source_name'";
522         my $res = $main::known_clients_db->update_dbentry( $sql_statement );
523         my $hash = &create_xml_hash("confirm_new_key", $server_address, $source_name);
524         my $out_msg = &create_xml_string($hash);
525         push(@out_msg_l, $out_msg);
526     }
528     # only do if host still not found
529     if( 0 == @out_msg_l ) {
530         # check known_server_db
531         $sql_statement = "SELECT * FROM known_server WHERE hostname='$source_name'";
532         $query_res = $main::known_server_db->select_dbentry( $sql_statement );
533         if( 1 == keys %{$query_res} ) {
534             my $act_time = &get_time;
535             my $sql_statement= "UPDATE known_server ".
536                 "SET hostkey='$source_key', timestamp='$act_time' ".
537                 "WHERE hostname='$source_name'";
538             my $res = $main::known_server_db->update_dbentry( $sql_statement );
540             my $hash = &create_xml_hash("confirm_new_key", $server_address, $source_name);
541             my $out_msg = &create_xml_string($hash);
542             push(@out_msg_l, $out_msg);
543         }
544     }
546     return @out_msg_l;
550 #===  FUNCTION  ================================================================
551 #         NAME:  here_i_am
552 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
553 #      RETURNS:  nothing
554 #  DESCRIPTION:  process this incoming message
555 #===============================================================================
556 sub here_i_am {
557     my ($msg, $msg_hash, $session_id) = @_;
558     my @out_msg_l;
559     my $out_hash;
561     my $source = @{$msg_hash->{source}}[0];
562     my $mac_address = @{$msg_hash->{mac_address}}[0];
563         my $gotoHardwareChecksum = @{$msg_hash->{gotoHardwareChecksum}}[0];
564     my $client_status = @{$msg_hash->{client_status}}[0];
565     my $client_revision = @{$msg_hash->{client_revision}}[0];
567     # number of known clients
568     my $nu_clients= $main::known_clients_db->count_dbentries('known_clients');
570     # check wether client address or mac address is already known
571     my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$source'";
572     my $db_res= $main::known_clients_db->select_dbentry( $sql_statement );
573     
574     if ( 1 == keys %{$db_res} ) {
575         &main::daemon_log("$session_id WARNING: $source is already known as a client", 1);
576         &main::daemon_log("$session_id WARNING: values for $source are being overwritten", 1);   
577         $nu_clients --;
578     }
580     # number of actual activ clients
581     my $act_nu_clients = $nu_clients;
583     &main::daemon_log("$session_id INFO: number of actual activ clients: $act_nu_clients", 5);
584     &main::daemon_log("$session_id INFO: number of maximal allowed clients: $max_clients", 5);
586     if($max_clients <= $act_nu_clients) {
587         my $out_hash = &create_xml_hash("denied", $server_address, $source);
588         &add_content2xml_hash($out_hash, "denied", "I_cannot_take_any_more_clients!");
589         my $passwd = @{$msg_hash->{new_passwd}}[0]; 
590         &send_msg_hash2address($out_hash, $source, $passwd);
591         return;
592     }
593     
594     # new client accepted
595     my $new_passwd = @{$msg_hash->{new_passwd}}[0];
597     # create entry in known_clients
598     my $events = @{$msg_hash->{events}}[0];
599     
601     # add entry to known_clients_db
602     my $act_timestamp = &get_time;
603     my $res = $main::known_clients_db->add_dbentry( {table=>'known_clients', 
604                                                 primkey=>['hostname'],
605                                                 hostname=>$source,
606                                                 events=>$events,
607                                                 macaddress=>$mac_address,
608                                                 status=>'registered',
609                                                 hostkey=>$new_passwd,
610                                                 timestamp=>$act_timestamp,
611                                                 } );
613     if ($res != 0)  {
614         &main::daemon_log("$session_id ERROR: cannot add entry to known_clients: $res");
615         return;
616     }
617     
618     # return acknowledgement to client
619     $out_hash = &create_xml_hash("registered", $server_address, $source);
621     # notify registered client to bus
622     if( $bus_activ eq "on") {
623         # fetch actual bus key
624         my $sql_statement= "SELECT * FROM known_server WHERE status='bus'";
625         my $query_res = $main::known_server_db->select_dbentry( $sql_statement );
626         my $hostkey = $query_res->{1}->{'hostkey'};
628         # send update msg to bus
629         $out_hash = &create_xml_hash("new_client", $server_address, $bus_address, $source);
630         &add_content2xml_hash($out_hash, "macaddress", $mac_address);
631         &add_content2xml_hash($out_hash, "timestamp", $act_timestamp);
632         my $new_client_out = &create_xml_string($out_hash);
633         push(@out_msg_l, $new_client_out);
634         &main::daemon_log("$session_id INFO: send bus msg that client '$source' has registered at server '$server_address'", 5);
635     }
637     # give the new client his ldap config
638     # Workaround: Send within the registration response, if the client will get an ldap config later
639         my $new_ldap_config_out = &new_ldap_config($source, $session_id);
640         if($new_ldap_config_out && (!($new_ldap_config_out =~ /error/))) {
641                 &add_content2xml_hash($out_hash, "ldap_available", "true");
642         } elsif($new_ldap_config_out && $new_ldap_config_out =~ /error/){
643                 &add_content2xml_hash($out_hash, "error", $new_ldap_config_out);
645                 my $sql_statement = "UPDATE $main::job_queue_tn ".
646                 "SET status='error', result='$new_ldap_config_out' ".
647                 "WHERE status='processing' AND macaddress LIKE '$mac_address'";
648                 my $res = $main::job_db->update_dbentry($sql_statement);
649                 &main::daemon_log("$session_id DEBUG: $sql_statement RESULT: $res", 7);         
650         }
651     my $register_out = &create_xml_string($out_hash);
652     push(@out_msg_l, $register_out);
654     # Really send the ldap config
655     if( $new_ldap_config_out && (!($new_ldap_config_out =~ /error/))) {
656             push(@out_msg_l, $new_ldap_config_out);
657     }
659         my $hardware_config_out = &hardware_config($msg, $msg_hash, $session_id);
660         if( $hardware_config_out ) {
661                 push(@out_msg_l, $hardware_config_out);
662         }
664     &main::daemon_log("$session_id INFO: register client $source ($mac_address)", 5);
665     &main::daemon_log("$session_id INFO: client version: $client_status - $client_revision", 5); 
667     return @out_msg_l;
671 #===  FUNCTION  ================================================================
672 #         NAME:  who_has
673 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
674 #      RETURNS:  nothing 
675 #  DESCRIPTION:  process this incoming message
676 #===============================================================================
677 sub who_has {
678     my ($msg_hash) = @_ ;
679     my @out_msg_l;
680     
681     # what is your search pattern
682     my $search_pattern = @{$msg_hash->{who_has}}[0];
683     my $search_element = @{$msg_hash->{$search_pattern}}[0];
684     &main::daemon_log("who_has-msg looking for $search_pattern $search_element", 7);
686     # scanning known_clients for search_pattern
687     my @host_addresses = keys %$main::known_clients;
688     my $known_clients_entries = length @host_addresses;
689     my $host_address;
690     foreach my $host (@host_addresses) {
691         my $client_element = $main::known_clients->{$host}->{$search_pattern};
692         if ($search_element eq $client_element) {
693             $host_address = $host;
694             last;
695         }
696     }
697         
698     # search was successful
699     if (defined $host_address) {
700         my $source = @{$msg_hash->{source}}[0];
701         my $out_hash = &create_xml_hash("who_has_i_do", $server_address, $source, "mac_address");
702         &add_content2xml_hash($out_hash, "mac_address", $search_element);
703         my $out_msg = &create_xml_string($out_hash);
704         push(@out_msg_l, $out_msg);
705     }
706     return @out_msg_l;
710 sub who_has_i_do {
711     my ($msg_hash) = @_ ;
712     my $header = @{$msg_hash->{header}}[0];
713     my $source = @{$msg_hash->{source}}[0];
714     my $search_param = @{$msg_hash->{$header}}[0];
715     my $search_value = @{$msg_hash->{$search_param}}[0];
716     print "\ngot msg $header:\nserver $source has client with $search_param $search_value\n";
720 #===  FUNCTION  ================================================================
721 #         NAME:  new_ldap_config
722 #   PARAMETERS:  address - string - ip address and port of a host
723 #      RETURNS:  gosa-si conform message
724 #  DESCRIPTION:  send to address the ldap configuration found for dn gotoLdapServer
725 #===============================================================================
726 sub new_ldap_config {
727         my ($address, $session_id) = @_ ;
729         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address' OR macaddress LIKE '$address'";
730         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
732         # check hit
733         my $hit_counter = keys %{$res};
734         if( not $hit_counter == 1 ) {
735                 &main::daemon_log("$session_id ERROR: more or no hit found in known_clients_db by query '$sql_statement'", 1);
736         }
738     $address = $res->{1}->{hostname};
739         my $macaddress = $res->{1}->{macaddress};
740         my $hostkey = $res->{1}->{hostkey};
742         if (not defined $macaddress) {
743                 &main::daemon_log("$session_id ERROR: no mac address found for client $address", 1);
744                 return;
745         }
747         # Build LDAP connection
748     my $ldap_handle = &main::get_ldap_handle($session_id);
749         if( not defined $ldap_handle ) {
750                 &main::daemon_log("$session_id ERROR: cannot connect to ldap: $ldap_uri", 1);
751                 return;
752         } 
754         # Perform search
755     $mesg = $ldap_handle->search( base   => $ldap_base,
756                 scope  => 'sub',
757                 attrs => ['dn', 'gotoLdapServer', 'gosaUnitTag', 'FAIclass'],
758                 filter => "(&(objectClass=GOhard)(macaddress=$macaddress))");
759         if($mesg->code) {
760                 &main::daemon_log("$session_id ".$mesg->error, 1);
761                 return;
762         }
764         # Sanity check
765         if ($mesg->count != 1) {
766                 &main::daemon_log("$session_id WARNING: client with mac address $macaddress not found/unique/active - not sending ldap config".
767                 "\n\tbase: $ldap_base".
768                 "\n\tscope: sub".
769                 "\n\tattrs: dn, gotoLdapServer".
770                 "\n\tfilter: (&(objectClass=GOhard)(macaddress=$macaddress))", 1);
771                 return;
772         }
774         my $entry= $mesg->entry(0);
775         my $dn= $entry->dn;
776         my @servers= $entry->get_value("gotoLdapServer");
777         my $unit_tag= $entry->get_value("gosaUnitTag");
778         my @ldap_uris;
779         my $server;
780         my $base;
781         my $release;
783         # Fill release if available
784         my $FAIclass= $entry->get_value("FAIclass");
785         if (defined $FAIclass && $FAIclass =~ /^.* :([A-Za-z0-9\/.]+).*$/) {
786                 $release= $1;
787         }
789         # Do we need to look at an object class?
790         if (not @servers){
791                 $mesg = $ldap_handle->search( base   => $ldap_base,
792                         scope  => 'sub',
793                         attrs => ['dn', 'gotoLdapServer', 'FAIclass'],
794                         filter => "(&(objectClass=gosaGroupOfNames)(member=$dn))");
795                 #$mesg->code && die $mesg->error;
796                 if($mesg->code) {
797                         &main::daemon_log("$session_id ".$mesg->error, 1);
798                         return;
799                 }
801                 # Sanity check
802                 if ($mesg->count != 1) {
803                         &main::daemon_log("$session_id WARNING: no LDAP information found for client mac $macaddress", 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         foreach $server (@servers){
822                 # Conversation for backward compatibility
823                 if (not $server =~ /^\d+:[^:]+:ldap[^:]*:\/\// ) {
824                     if ($server =~ /^([^:]+):([^:]+)$/ ) {
825                       $server= "1:dummy:ldap://$1/$2";
826                     } elsif ($server =~ /^(\d+):([^:]+):(.*)$/ ) {
827                       $server= "$1:dummy:ldap://$2/$3";
828                     }
829                 }
831                 $base= $server;
832                 $server =~ s%^[^:]+:[^:]+:(ldap.*://[^/]+)/.*$%$1%;
833                 $base =~ s%^[^:]+:[^:]+:ldap.*://[^/]+/(.*)$%$1%;
834                 push (@ldap_uris, $server);
835         }
837         # Assemble data package
838         my %data = ( 'ldap_uri'  => \@ldap_uris, 'ldap_base' => $base,
839                 'ldap_cfg' => \@ldap_cfg, 'pam_cfg' => \@pam_cfg,'nss_cfg' => \@nss_cfg );
840         if (defined $release){
841                 $data{'release'}= $release;
842         }
844         # Need to append GOto settings?
845         if (defined $goto_admin and defined $goto_secret){
846                 $data{'goto_admin'}= $goto_admin;
847                 $data{'goto_secret'}= $goto_secret;
848         }
850         # Append unit tag if needed
851         if (defined $unit_tag){
853                 # Find admin base and department name
854                 $mesg = $ldap_handle->search( base   => $ldap_base,
855                         scope  => 'sub',
856                         attrs => ['dn', 'ou'],
857                         filter => "(&(objectClass=gosaAdministrativeUnit)(gosaUnitTag=$unit_tag))");
858                 #$mesg->code && die $mesg->error;
859                 if($mesg->code) {
860                         &main::daemon_log($mesg->error, 1);
861                         return "error-unit-tag-count-0";
862                 }
864                 # Sanity check
865                 if ($mesg->count != 1) {
866                         &main::daemon_log("WARNING: cannot find administrative unit for client with tag $unit_tag", 1);
867                         return "error-unit-tag-count-".$mesg->count;
868                 }
870                 $entry= $mesg->entry(0);
871                 $data{'admin_base'}= $entry->dn;
872                 $data{'department'}= $entry->get_value("ou");
874                 # Append unit Tag
875                 $data{'unit_tag'}= $unit_tag;
876         }
878         # Send information
879         return &build_msg("new_ldap_config", $server_address, $address, \%data);
883 #===  FUNCTION  ================================================================
884 #         NAME:  hardware_config
885 #   PARAMETERS:  address - string - ip address and port of a host
886 #      RETURNS:  
887 #  DESCRIPTION:  
888 #===============================================================================
889 sub hardware_config {
890         my ($msg, $msg_hash, $session_id) = @_ ;
891         my $address = @{$msg_hash->{source}}[0];
892         my $header = @{$msg_hash->{header}}[0];
893         my $gotoHardwareChecksum = @{$msg_hash->{gotoHardwareChecksum}}[0];
895         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address'";
896         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
898         # check hit
899         my $hit_counter = keys %{$res};
900         if( not $hit_counter == 1 ) {
901                 &main::daemon_log("$session_id ERROR: more or no hit found in known_clients_db by query by '$address'", 1);
902         }
903         my $macaddress = $res->{1}->{macaddress};
904         my $hostkey = $res->{1}->{hostkey};
906         if (not defined $macaddress) {
907                 &main::daemon_log("$session_id ERROR: no mac address found for client $address", 1);
908                 return;
909         }
911         # Build LDAP connection
912     my $ldap_handle = &main::get_ldap_handle($session_id);
913         if( not defined $ldap_handle ) {
914                 &main::daemon_log("$session_id ERROR: cannot connect to ldap: $ldap_uri", 1);
915                 return;
916         } 
918         # Perform search
919         $mesg = $ldap_handle->search(
920                 base   => $ldap_base,
921                 scope  => 'sub',
922                 filter => "(&(objectClass=GOhard)(|(macAddress=$macaddress)(dhcpHWaddress=ethernet $macaddress)))"
923         );
925         if($mesg->count() == 0) {
926                 &main::daemon_log("Host was not found in LDAP!", 1);
928                 # set status = hardware_detection at jobqueue if entry exists
929                 # TODO
930                 # resolve plain name for host
931                 my $func_dic = {table=>$main::job_queue_tn,
932                                 primkey=>[],
933                                 timestamp=>&get_time,
934                                 status=>'processing',
935                                 result=>'none',
936                                 progress=>'hardware-detection',
937                                 headertag=>'trigger_action_reinstall',
938                                 targettag=>$address,
939                                 xmlmessage=>'none',
940                                 macaddress=>$macaddress,
941                                 plainname=>'none',
942                 };
943                 my $hd_res = $main::job_db->add_dbentry($func_dic);
944                 &main::daemon_log("$session_id INFO: add '$macaddress' to job queue as an installing job", 5);
945         
946         } else {
947                 my $entry= $mesg->entry(0);
948                 my $dn= $entry->dn;
949                 if (defined($entry->get_value("gotoHardwareChecksum"))) {
950                         if (! $entry->get_value("gotoHardwareChecksum") eq $gotoHardwareChecksum) {
951                                 $entry->replace(gotoHardwareChecksum => $gotoHardwareChecksum);
952                                 if($entry->update($ldap_handle)) {
953                                         &main::daemon_log("$session_id INFO: Hardware changed! Detection triggered.", 5);
954                                 }
955                         } else {
956                                 # Nothing to do
957                                 return;
958                         }
959                 } 
960         } 
962         # Assemble data package
963         my %data = ();
965         # Need to append GOto settings?
966         if (defined $goto_admin and defined $goto_secret){
967                 $data{'goto_admin'}= $goto_admin;
968                 $data{'goto_secret'}= $goto_secret;
969         }
971         # Send information
972         return &build_msg("detect_hardware", $server_address, $address, \%data);
975 sub server_matches {
976         my $target = shift;
977         my $target_ip = ($1) if $target =~ /^([0-9\.]*?):.*$/;
978         if(!defined($target_ip) or length($target_ip) == 0) {
979                 return;
980         }
982         my $result = 0;
984         if($server_ip eq $target_ip) {
985                 $result= 1;
986         } elsif ($target_ip eq "0.0.0.0") {
987                 $result= 1;
988         } elsif ($server_ip eq "0.0.0.0") {     
989                 if ($target_ip eq "127.0.0.1") {
990                         $result= 1;
991                 } else {
992                         my $PROC_NET_ROUTE= ('/proc/net/route');
994                         open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
995                                 or die "Could not open $PROC_NET_ROUTE";
997                         my @ifs = <PROC_NET_ROUTE>;
999                         close(PROC_NET_ROUTE);
1001                         # Eat header line
1002                         shift @ifs;
1003                         chomp @ifs;
1004                         foreach my $line(@ifs) {
1005                                 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
1006                                 my $destination;
1007                                 my $mask;
1008                                 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
1009                                 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
1010                                 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
1011                                 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
1012                                 if(new NetAddr::IP($target_ip)->within(new NetAddr::IP($destination, $mask))) {
1013                                         # destination matches route, save mac and exit
1014                                         $result= 1;
1015                                         last;
1016                                 }
1017                         }
1018                 }
1019         } else {
1020                 &main::daemon_log("Target ip $target_ip does not match Server ip $server_ip",1);
1021         }
1023         return $result;
1026 1;