Code

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