Code

Added support for loading / parsing package lists
[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_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" => [\$main::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 $main::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 $main::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=$main::server_mac_address)"
82                 );
84                 if ($mesg->count == 1) {
85                         my $entry= $mesg->entry(0);
86                         my $unit_tag= $entry->get_value("gosaUnitTag");
87                         $main::ldap_server_dn= $mesg->entry(0)->dn;
88                         if(defined($unit_tag) && length($unit_tag) > 0) {
89                                 &main::daemon_log("INFO: Detected gosaUnitTag $unit_tag for creating entries", 5);
90                                 $main::gosa_unit_tag= $unit_tag;
91                         }
92                 } else {
93                         # Perform another search for Unit Tag
94                         my $hostname= `hostname -f`;
95                         chomp($hostname);
96                         &main::daemon_log("INFO: Searching for servers gosaUnitTag with hostname $hostname",5);
97                         $mesg = $main::ldap_handle->search(
98                                 base   => $ldap_base,
99                                 scope  => 'sub',
100                                 attrs  => ['gosaUnitTag'],
101                                 filter => "(&(cn=$hostname)(objectClass=goServer))"
102                         );
103                         if ($mesg->count == 1) {
104                                 my $entry= $mesg->entry(0);
105                                 my $unit_tag= $entry->get_value("gosaUnitTag");
106                                 $main::ldap_server_dn= $mesg->entry(0)->dn;
107                                 if(defined($unit_tag) && length($unit_tag) > 0) {
108                                         &main::daemon_log("INFO: Detected gosaUnitTag $unit_tag for creating entries", 5);
109                                         $main::gosa_unit_tag= $unit_tag;
110                                 }
111                         } else {
112                                 # Perform another search for Unit Tag
113                                 $hostname= `hostname -s`;
114                                 chomp($hostname);
115                                 &main::daemon_log("INFO: Searching for servers gosaUnitTag with hostname $hostname",5);
116                                 $mesg = $main::ldap_handle->search(
117                                         base   => $ldap_base,
118                                         scope  => 'sub',
119                                         attrs  => ['gosaUnitTag'],
120                                         filter => "(&(cn=$hostname)(objectClass=goServer))"
121                                 );
122                                 if ($mesg->count == 1) {
123                                         my $entry= $mesg->entry(0);
124                                         my $unit_tag= $entry->get_value("gosaUnitTag");
125                                         $main::ldap_server_dn= $mesg->entry(0)->dn;
126                                         if(defined($unit_tag) && length($unit_tag) > 0) {
127                                                 &main::daemon_log("INFO: Detected gosaUnitTag $unit_tag for creating entries", 5);
128                                                 $main::gosa_unit_tag= $unit_tag;
129                                         }
130                                 } else {
131                                         &main::daemon_log("WARNING: No gosaUnitTag detected. Not using gosaUnitTag", 3);
132                                 }
133                         }
134                 }
135         } else {
136                 &main::daemon_log("INFO: Using gosaUnitTag from config-file: $main::gosa_unit_tag",5);
137         }
141 my $server_address = "$server_ip:$server_port";
142 $main::server_address = $server_address;
145 if( inet_aton($bus_ip) ){ $bus_ip = inet_ntoa(inet_aton($bus_ip)); } 
146 ######################################################
147 # to change
148 if( $bus_ip eq "127.0.1.1" ) { $bus_ip = "127.0.0.1" }
149 ######################################################
150 my $bus_address = "$bus_ip:$bus_port";
151 $main::bus_address = $bus_address;
153 # create general settings for this module
154 my $xml = new XML::Simple();
156 # register at bus
157 if ($main::no_bus > 0) {
158     $bus_activ = "off"
160 if($bus_activ eq "on") {
161     &register_at_bus();
164 # add myself to known_server_db
165 my $res = $main::known_server_db->add_dbentry( {table=>'known_server',
166         primkey=>['hostname'],
167         hostname=>$server_address,
168         status=>'myself',
169         hostkey=>$SIPackages_key,
170         timestamp=>&get_time,
171         } );
175 ### functions #################################################################
178 sub get_module_info {
179     my @info = ($server_address,
180                 $SIPackages_key,
181                 );
182     return \@info;
186 #===  FUNCTION  ================================================================
187 #         NAME:  read_configfile
188 #   PARAMETERS:  cfg_file - string -
189 #      RETURNS:  nothing
190 #  DESCRIPTION:  read cfg_file and set variables
191 #===============================================================================
192 sub read_configfile {
193     my $cfg;
194     if( defined( $main::cfg_file) && ( length($main::cfg_file) > 0 )) {
195         if( -r $main::cfg_file ) {
196             $cfg = Config::IniFiles->new( -file => $main::cfg_file );
197         } else {
198             print STDERR "Couldn't read config file!";
199         }
200     } else {
201         $cfg = Config::IniFiles->new() ;
202     }
203     foreach my $section (keys %cfg_defaults) {
204         foreach my $param (keys %{$cfg_defaults{ $section }}) {
205             my $pinfo = $cfg_defaults{ $section }{ $param };
206             ${@$pinfo[0]} = $cfg->val( $section, $param, @$pinfo[1] );
207         }
208     }
210     # Read non predefined sections
211     my $param;
212     if ($cfg->SectionExists('ldap')){
213                 foreach $param ($cfg->Parameters('ldap')){
214                         push (@ldap_cfg, "$param ".$cfg->val('ldap', $param));
215                 }
216     }
217     if ($cfg->SectionExists('pam_ldap')){
218                 foreach $param ($cfg->Parameters('pam_ldap')){
219                         push (@pam_cfg, "$param ".$cfg->val('pam_ldap', $param));
220                 }
221     }
222     if ($cfg->SectionExists('nss_ldap')){
223                 foreach $param ($cfg->Parameters('nss_ldap')){
224                         push (@nss_cfg, "$param ".$cfg->val('nss_ldap', $param));
225                 }
226     }
227     if ($cfg->SectionExists('goto')){
228         $goto_admin= $cfg->val('goto', 'terminal_admin');
229         $goto_secret= $cfg->val('goto', 'terminal_secret');
230     } else {
231         $goto_admin= undef;
232         $goto_secret= undef;
233     }
237 #===  FUNCTION  ================================================================
238 #         NAME:  get_interface_for_ip
239 #   PARAMETERS:  ip address (i.e. 192.168.0.1)
240 #      RETURNS:  array: list of interfaces if ip=0.0.0.0, matching interface if found, undef else
241 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
242 #===============================================================================
243 sub get_interface_for_ip {
244         my $result;
245         my $ip= shift;
246         if ($ip && length($ip) > 0) {
247                 my @ifs= &get_interfaces();
248                 if($ip eq "0.0.0.0") {
249                         $result = "all";
250                 } else {
251                         foreach (@ifs) {
252                                 my $if=$_;
253                                 if(&main::get_ip($if) eq $ip) {
254                                         $result = $if;
255                                 }
256                         }       
257                 }
258         }       
259         return $result;
262 #===  FUNCTION  ================================================================
263 #         NAME:  get_interfaces 
264 #   PARAMETERS:  none
265 #      RETURNS:  (list of interfaces) 
266 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
267 #===============================================================================
268 sub get_interfaces {
269         my @result;
270         my $PROC_NET_DEV= ('/proc/net/dev');
272         open(PROC_NET_DEV, "<$PROC_NET_DEV")
273                 or die "Could not open $PROC_NET_DEV";
275         my @ifs = <PROC_NET_DEV>;
277         close(PROC_NET_DEV);
279         # Eat first two line
280         shift @ifs;
281         shift @ifs;
283         chomp @ifs;
284         foreach my $line(@ifs) {
285                 my $if= (split /:/, $line)[0];
286                 $if =~ s/^\s+//;
287                 push @result, $if;
288         }
290         return @result;
293 #===  FUNCTION  ================================================================
294 #         NAME:  get_mac 
295 #   PARAMETERS:  interface name (i.e. eth0)
296 #      RETURNS:  (mac address) 
297 #  DESCRIPTION:  Uses ioctl to get mac address directly from system.
298 #===============================================================================
299 sub get_mac {
300         my $ifreq= shift;
301         my $result;
302         if ($ifreq && length($ifreq) > 0) { 
303                 if($ifreq eq "all") {
304                         $result = "00:00:00:00:00:00";
305                 } else {
306                         my $SIOCGIFHWADDR= 0x8927;     # man 2 ioctl_list
308                         # A configured MAC Address should always override a guessed value
309                         if ($main::server_mac_address and length($main::server_mac_address) > 0) {
310                                 $result= $main::server_mac_address;
311                         }
313                         socket SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('ip')
314                                 or die "socket: $!";
316                         if(ioctl SOCKET, $SIOCGIFHWADDR, $ifreq) {
317                                 my ($if, $mac)= unpack 'h36 H12', $ifreq;
319                                 if (length($mac) > 0) {
320                                         $mac=~ m/^([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])$/;
321                                         $mac= sprintf("%s:%s:%s:%s:%s:%s", $1, $2, $3, $4, $5, $6);
322                                         $result = $mac;
323                                 }
324                         }
325                 }
326         }
327         return $result;
331 #===  FUNCTION  ================================================================
332 #         NAME:  register_at_bus
333 #   PARAMETERS:  nothing
334 #      RETURNS:  nothing
335 #  DESCRIPTION:  creates an entry in known_daemons and send a 'here_i_am' msg to bus
336 #===============================================================================
337 sub register_at_bus {
339     # add bus to known_server_db
340     my $res = $main::known_server_db->add_dbentry( {table=>'known_server',
341                                                     primkey=>['hostname'],
342                                                     hostname=>$bus_address,
343                                                     status=>'bus',
344                                                     hostkey=>$bus_key,
345                                                     timestamp=>&get_time,
346                                                 } );
347     my $msg_hash = &create_xml_hash("here_i_am", $server_address, $bus_address);
348     my $msg = &create_xml_string($msg_hash);
350     &main::send_msg_to_target($msg, $bus_address, $bus_key, "here_i_am");
351     return $msg;
355 sub import_events {
356     if (not -e $event_dir) {
357         &main::daemon_log("ERROR: cannot find directory or directory is not readable: $event_dir", 1);   
358     }
359     opendir (DIR, $event_dir) or die "ERROR while loading gosa-si-events from directory $event_dir : $!\n";
361     while (defined (my $event = readdir (DIR))) {
362         if( $event eq "." || $event eq ".." ) { next; }  
363         if( $event eq "gosaTriggered.pm" ) { next; }    # only GOsa specific events
365         eval{ require $event; };
366         if( $@ ) {
367             &main::daemon_log("import of event module '$event' failed", 1);
368             &main::daemon_log("$@", 8);
369             next;
370         }
372         $event =~ /(\S*?).pm$/;
373         my $event_module = $1;
374         my $events_l = eval( $1."::get_events()") ;
375         foreach my $event_name (@{$events_l}) {
376             $event_hash->{$event_name} = $event_module;
377         }
378         my $events_string = join( ", ", @{$events_l});
379         &main::daemon_log("INFO: SIPackages imported events $events_string", 5);
380     }
384 #===  FUNCTION  ================================================================
385 #         NAME:  process_incoming_msg
386 #   PARAMETERS:  crypted_msg - string - incoming crypted message
387 #      RETURNS:  nothing
388 #  DESCRIPTION:  handels the proceeded distribution to the appropriated functions
389 #===============================================================================
390 sub process_incoming_msg {
391     my ($msg, $msg_hash, $session_id) = @_ ;
392     my $error = 0;
393     my $host_name;
394     my $host_key;
395     my @out_msg_l = ("nohandler");
397     # process incoming msg
398     my $header = @{$msg_hash->{header}}[0]; 
399     my @target_l = @{$msg_hash->{target}};
401     # skip PREFIX
402     $header =~ s/^CLMSG_//;
404     &main::daemon_log("$session_id DEBUG: SIPackages: msg to process: $header", 7);
406     if( 0 == length @target_l){     
407         &main::daemon_log("$session_id ERROR: no target specified for msg $header", 1);
408         $error++;
409     }
411     if( 1 == length @target_l) {
412         my $target = $target_l[0];
413                 if(&server_matches($target)) {
416             if ($header eq 'new_key') {
417                 @out_msg_l = &new_key($msg_hash)
418             } elsif ($header eq 'here_i_am') {
419                 @out_msg_l = &here_i_am($msg, $msg_hash, $session_id)
420             } else {
421                 if( exists $event_hash->{$header} ) {
422                     # a event exists with the header as name
423                     &main::daemon_log("$session_id INFO: found event '$header' at event-module '".$event_hash->{$header}."'", 5);
424                     no strict 'refs';
425                     @out_msg_l = &{$event_hash->{$header}."::$header"}($msg, $msg_hash, $session_id);
426                 }
427             }
429             # if delivery not possible raise error and return 
430             if( not defined $out_msg_l[0] ) {
431                 @out_msg_l = ();
432             } elsif( $out_msg_l[0] eq 'nohandler') {
433                 &main::daemon_log("$session_id ERROR: SIPackages: no event handler or core function defined for '$header'", 1);
434                 @out_msg_l = ();
435             } 
437         }
438                 else {
439                         &main::daemon_log("INFO: msg is not for gosa-si-server '$server_address', deliver it to target '$target'", 5);
440                         push(@out_msg_l, $msg);
441                 }
442     }
444     return \@out_msg_l;
448 #===  FUNCTION  ================================================================
449 #         NAME:  new_passwd
450 #   PARAMETERS:  msg_hash - ref - hash from function create_xml_hash
451 #      RETURNS:  nothing
452 #  DESCRIPTION:  process this incoming message
453 #===============================================================================
454 sub new_key {
455     my ($msg_hash) = @_;
456     my @out_msg_l;
457     
458     my $header = @{$msg_hash->{header}}[0];
459     my $source_name = @{$msg_hash->{source}}[0];
460     my $source_key = @{$msg_hash->{new_key}}[0];
461     my $query_res;
463     # check known_clients_db
464     my $sql_statement = "SELECT * FROM known_clients WHERE hostname='$source_name'";
465     $query_res = $main::known_clients_db->select_dbentry( $sql_statement );
466     if( 1 == keys %{$query_res} ) {
467         my $act_time = &get_time;
468         my $sql_statement= "UPDATE known_clients ".
469             "SET hostkey='$source_key', timestamp='$act_time' ".
470             "WHERE hostname='$source_name'";
471         my $res = $main::known_clients_db->update_dbentry( $sql_statement );
472         my $hash = &create_xml_hash("confirm_new_key", $server_address, $source_name);
473         my $out_msg = &create_xml_string($hash);
474         push(@out_msg_l, $out_msg);
475     }
477     # only do if host still not found
478     if( 0 == @out_msg_l ) {
479         # check known_server_db
480         $sql_statement = "SELECT * FROM known_server WHERE hostname='$source_name'";
481         $query_res = $main::known_server_db->select_dbentry( $sql_statement );
482         if( 1 == keys %{$query_res} ) {
483             my $act_time = &get_time;
484             my $sql_statement= "UPDATE known_server ".
485                 "SET hostkey='$source_key', timestamp='$act_time' ".
486                 "WHERE hostname='$source_name'";
487             my $res = $main::known_server_db->update_dbentry( $sql_statement );
489             my $hash = &create_xml_hash("confirm_new_key", $server_address, $source_name);
490             my $out_msg = &create_xml_string($hash);
491             push(@out_msg_l, $out_msg);
492         }
493     }
495     return @out_msg_l;
499 #===  FUNCTION  ================================================================
500 #         NAME:  here_i_am
501 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
502 #      RETURNS:  nothing
503 #  DESCRIPTION:  process this incoming message
504 #===============================================================================
505 sub here_i_am {
506     my ($msg, $msg_hash, $session_id) = @_;
507     my @out_msg_l;
508     my $out_hash;
510     my $source = @{$msg_hash->{source}}[0];
511     my $mac_address = @{$msg_hash->{mac_address}}[0];
512         my $gotoHardwareChecksum = @{$msg_hash->{gotoHardwareChecksum}}[0];
514     # number of known clients
515     my $nu_clients= $main::known_clients_db->count_dbentries('known_clients');
517     # check wether client address or mac address is already known
518     my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$source'";
519     my $db_res= $main::known_clients_db->select_dbentry( $sql_statement );
520     
521     if ( 1 == keys %{$db_res} ) {
522         &main::daemon_log("$session_id WARNING: $source is already known as a client", 1);
523         &main::daemon_log("$session_id WARNING: values for $source are being overwritten", 1);   
524         $nu_clients --;
525     }
527     # number of actual activ clients
528     my $act_nu_clients = $nu_clients;
530     &main::daemon_log("$session_id INFO: number of actual activ clients: $act_nu_clients", 5);
531     &main::daemon_log("$session_id INFO: number of maximal allowed clients: $max_clients", 5);
533     if($max_clients <= $act_nu_clients) {
534         my $out_hash = &create_xml_hash("denied", $server_address, $source);
535         &add_content2xml_hash($out_hash, "denied", "I_cannot_take_any_more_clients!");
536         my $passwd = @{$msg_hash->{new_passwd}}[0]; 
537         &send_msg_hash2address($out_hash, $source, $passwd);
538         return;
539     }
540     
541     # new client accepted
542     my $new_passwd = @{$msg_hash->{new_passwd}}[0];
544     # create entry in known_clients
545     my $events = @{$msg_hash->{events}}[0];
546     
548     # add entry to known_clients_db
549     my $act_timestamp = &get_time;
550     my $res = $main::known_clients_db->add_dbentry( {table=>'known_clients', 
551                                                 primkey=>['hostname'],
552                                                 hostname=>$source,
553                                                 events=>$events,
554                                                 macaddress=>$mac_address,
555                                                 status=>'registered',
556                                                 hostkey=>$new_passwd,
557                                                 timestamp=>$act_timestamp,
558                                                 } );
560     if ($res != 0)  {
561         &main::daemon_log("$session_id ERROR: cannot add entry to known_clients: $res");
562         return;
563     }
564     
565     # return acknowledgement to client
566     $out_hash = &create_xml_hash("registered", $server_address, $source);
568     # notify registered client to bus
569     if( $bus_activ eq "on") {
570         # fetch actual bus key
571         my $sql_statement= "SELECT * FROM known_server WHERE status='bus'";
572         my $query_res = $main::known_server_db->select_dbentry( $sql_statement );
573         my $hostkey = $query_res->{1}->{'hostkey'};
575         # send update msg to bus
576         $out_hash = &create_xml_hash("new_client", $server_address, $bus_address, $source);
577         &add_content2xml_hash($out_hash, "macaddress", $mac_address);
578         &add_content2xml_hash($out_hash, "timestamp", $act_timestamp);
579         my $new_client_out = &create_xml_string($out_hash);
580         push(@out_msg_l, $new_client_out);
581         &main::daemon_log("$session_id INFO: send bus msg that client '$source' has registered at server '$server_address'", 5);
582     }
584     # give the new client his ldap config
585     # Workaround: Send within the registration response, if the client will get an ldap config later
586         my $new_ldap_config_out = &new_ldap_config($source, $session_id);
587         if($new_ldap_config_out && (!($new_ldap_config_out =~ /error/))) {
588                 &add_content2xml_hash($out_hash, "ldap_available", "true");
589         } elsif($new_ldap_config_out && $new_ldap_config_out =~ /error/){
590                 &add_content2xml_hash($out_hash, "error", $new_ldap_config_out);
592                 my $sql_statement = "UPDATE $main::job_queue_tn ".
593                 "SET status='error', result='$new_ldap_config_out' ".
594                 "WHERE status='processing' AND macaddress LIKE '$mac_address'";
595                 my $res = $main::job_db->update_dbentry($sql_statement);
596                 &main::daemon_log("$session_id DEBUG: $sql_statement RESULT: $res", 7);         
597         }
598     my $register_out = &create_xml_string($out_hash);
599     push(@out_msg_l, $register_out);
601     # Really send the ldap config
602     if( $new_ldap_config_out && (!($new_ldap_config_out =~ /error/))) {
603             push(@out_msg_l, $new_ldap_config_out);
604     }
606         my $hardware_config_out = &hardware_config($msg, $msg_hash, $session_id);
607         if( $hardware_config_out ) {
608                 push(@out_msg_l, $hardware_config_out);
609         }
611     return @out_msg_l;
615 #===  FUNCTION  ================================================================
616 #         NAME:  who_has
617 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
618 #      RETURNS:  nothing 
619 #  DESCRIPTION:  process this incoming message
620 #===============================================================================
621 sub who_has {
622     my ($msg_hash) = @_ ;
623     my @out_msg_l;
624     
625     # what is your search pattern
626     my $search_pattern = @{$msg_hash->{who_has}}[0];
627     my $search_element = @{$msg_hash->{$search_pattern}}[0];
628     &main::daemon_log("who_has-msg looking for $search_pattern $search_element", 7);
630     # scanning known_clients for search_pattern
631     my @host_addresses = keys %$main::known_clients;
632     my $known_clients_entries = length @host_addresses;
633     my $host_address;
634     foreach my $host (@host_addresses) {
635         my $client_element = $main::known_clients->{$host}->{$search_pattern};
636         if ($search_element eq $client_element) {
637             $host_address = $host;
638             last;
639         }
640     }
641         
642     # search was successful
643     if (defined $host_address) {
644         my $source = @{$msg_hash->{source}}[0];
645         my $out_hash = &create_xml_hash("who_has_i_do", $server_address, $source, "mac_address");
646         &add_content2xml_hash($out_hash, "mac_address", $search_element);
647         my $out_msg = &create_xml_string($out_hash);
648         push(@out_msg_l, $out_msg);
649     }
650     return @out_msg_l;
654 sub who_has_i_do {
655     my ($msg_hash) = @_ ;
656     my $header = @{$msg_hash->{header}}[0];
657     my $source = @{$msg_hash->{source}}[0];
658     my $search_param = @{$msg_hash->{$header}}[0];
659     my $search_value = @{$msg_hash->{$search_param}}[0];
660     print "\ngot msg $header:\nserver $source has client with $search_param $search_value\n";
664 #===  FUNCTION  ================================================================
665 #         NAME:  new_ldap_config
666 #   PARAMETERS:  address - string - ip address and port of a host
667 #      RETURNS:  gosa-si conform message
668 #  DESCRIPTION:  send to address the ldap configuration found for dn gotoLdapServer
669 #===============================================================================
670 sub new_ldap_config {
671         my ($address, $session_id) = @_ ;
673         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address' OR macaddress LIKE '$address'";
674         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
676         # check hit
677         my $hit_counter = keys %{$res};
678         if( not $hit_counter == 1 ) {
679                 &main::daemon_log("$session_id ERROR: more or no hit found in known_clients_db by query by '$address'", 1);
680         }
682     $address = $res->{1}->{hostname};
683         my $macaddress = $res->{1}->{macaddress};
684         my $hostkey = $res->{1}->{hostkey};
686         if (not defined $macaddress) {
687                 &main::daemon_log("$session_id ERROR: no mac address found for client $address", 1);
688                 return;
689         }
691         # Build LDAP connection
692   &main::refresh_ldap_handle();
693         if( not defined $main::ldap_handle ) {
694                 &main::daemon_log("$session_id ERROR: cannot connect to ldap: $ldap_uri", 1);
695                 return;
696         } 
698         # Perform search
699         $mesg = $main::ldap_handle->search( base   => $ldap_base,
700                 scope  => 'sub',
701                 attrs => ['dn', 'gotoLdapServer', 'gosaUnitTag', 'FAIclass'],
702                 filter => "(&(objectClass=GOhard)(macaddress=$macaddress)(gotoLdapServer=*))");
703         #$mesg->code && die $mesg->error;
704         if($mesg->code) {
705                 &main::daemon_log("$session_id ".$mesg->error, 1);
706                 return;
707         }
709         # Sanity check
710         if ($mesg->count != 1) {
711                 &main::daemon_log("$session_id WARNING: client with mac address $macaddress not found/unique/active - not sending ldap config".
712                 "\n\tbase: $ldap_base".
713                 "\n\tscope: sub".
714                 "\n\tattrs: dn, gotoLdapServer".
715                 "\n\tfilter: (&(objectClass=GOhard)(macaddress=$macaddress)(gotoLdapServer=*))", 1);
716                 return;
717         }
719         my $entry= $mesg->entry(0);
720         my $dn= $entry->dn;
721         my @servers= $entry->get_value("gotoLdapServer");
722         my $unit_tag= $entry->get_value("gosaUnitTag");
723         my @ldap_uris;
724         my $server;
725         my $base;
726         my $release;
728         # Fill release if available
729         my $FAIclass= $entry->get_value("FAIclass");
730         if (defined $FAIclass && $FAIclass =~ /^.* :([A-Za-z0-9\/.]+).*$/) {
731                 $release= $1;
732         }
734         # Do we need to look at an object class?
735         if (length(@servers) < 1){
736                 $mesg = $main::ldap_handle->search( base   => $ldap_base,
737                         scope  => 'sub',
738                         attrs => ['dn', 'gotoLdapServer', 'FAIclass'],
739                         filter => "(&(objectClass=gosaGroupOfNames)(member=$dn))");
740                 #$mesg->code && die $mesg->error;
741                 if($mesg->code) {
742                         &main::daemon_log("$session_id ".$mesg->error, 1);
743                         return;
744                 }
746                 # Sanity check
747                 if ($mesg->count != 1) {
748                         &main::daemon_log("$session_id WARNING: no LDAP information found for client mac $macaddress", 1);
749                         return;
750                 }
752                 $entry= $mesg->entry(0);
753                 $dn= $entry->dn;
754                 @servers= $entry->get_value("gotoLdapServer");
756                 if (not defined $release){
757                         $FAIclass= $entry->get_value("FAIclass");
758                         if (defined $FAIclass && $FAIclass =~ /^.* :([A-Za-z0-9\/.]+).*$/) {
759                                 $release= $1;
760                         }
761                 }
762         }
764         @servers= sort (@servers);
766         foreach $server (@servers){
767                 # Conversation for backward compatibility
768                 if (not $server =~ /^\d+:[^:]+:ldap[^:]*:\/\// ) {
769                     if ($server =~ /^([^:]+):([^:]+)$/ ) {
770                       $server= "1:dummy:ldap://$1/$2";
771                     } elsif ($server =~ /^(\d+):([^:]+):(.*)$/ ) {
772                       $server= "$1:dummy:ldap://$2/$3";
773                     }
774                 }
776                 $base= $server;
777                 $server =~ s%^[^:]+:[^:]+:(ldap.*://[^/]+)/.*$%$1%;
778                 $base =~ s%^[^:]+:[^:]+:ldap.*://[^/]+/(.*)$%$1%;
779                 push (@ldap_uris, $server);
780         }
782         # Assemble data package
783         my %data = ( 'ldap_uri'  => \@ldap_uris, 'ldap_base' => $base,
784                 'ldap_cfg' => \@ldap_cfg, 'pam_cfg' => \@pam_cfg,'nss_cfg' => \@nss_cfg );
785         if (defined $release){
786                 $data{'release'}= $release;
787         }
789         # Need to append GOto settings?
790         if (defined $goto_admin and defined $goto_secret){
791                 $data{'goto_admin'}= $goto_admin;
792                 $data{'goto_secret'}= $goto_secret;
793         }
795         # Append unit tag if needed
796         if (defined $unit_tag){
798                 # Find admin base and department name
799                 $mesg = $main::ldap_handle->search( base   => $ldap_base,
800                         scope  => 'sub',
801                         attrs => ['dn', 'ou'],
802                         filter => "(&(objectClass=gosaAdministrativeUnit)(gosaUnitTag=$unit_tag))");
803                 #$mesg->code && die $mesg->error;
804                 if($mesg->code) {
805                         &main::daemon_log($mesg->error, 1);
806                         return "error-unit-tag-count-0";
807                 }
809                 # Sanity check
810                 if ($mesg->count != 1) {
811                         &main::daemon_log("WARNING: cannot find administrative unit for client with tag $unit_tag", 1);
812                         return "error-unit-tag-count-".$mesg->count;
813                 }
815                 $entry= $mesg->entry(0);
816                 $data{'admin_base'}= $entry->dn;
817                 $data{'department'}= $entry->get_value("ou");
819                 # Append unit Tag
820                 $data{'unit_tag'}= $unit_tag;
821         }
823         # Send information
824         return &build_msg("new_ldap_config", $server_address, $address, \%data);
828 #===  FUNCTION  ================================================================
829 #         NAME:  hardware_config
830 #   PARAMETERS:  address - string - ip address and port of a host
831 #      RETURNS:  
832 #  DESCRIPTION:  
833 #===============================================================================
834 sub hardware_config {
835         my ($msg, $msg_hash, $session_id) = @_ ;
836         my $address = @{$msg_hash->{source}}[0];
837         my $header = @{$msg_hash->{header}}[0];
838         my $gotoHardwareChecksum = @{$msg_hash->{gotoHardwareChecksum}}[0];
840         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address'";
841         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
843         # check hit
844         my $hit_counter = keys %{$res};
845         if( not $hit_counter == 1 ) {
846                 &main::daemon_log("ERROR: more or no hit found in known_clients_db by query by '$address'", 1);
847         }
848         my $macaddress = $res->{1}->{macaddress};
849         my $hostkey = $res->{1}->{hostkey};
851         if (not defined $macaddress) {
852                 &main::daemon_log("ERROR: no mac address found for client $address", 1);
853                 return;
854         }
856         # Build LDAP connection
857   &main::refresh_ldap_handle();
858         if( not defined $main::ldap_handle ) {
859                 &main::daemon_log("ERROR: cannot connect to ldap: $ldap_uri", 1);
860                 return;
861         } 
863         # Perform search
864         $mesg = $main::ldap_handle->search(
865                 base   => $ldap_base,
866                 scope  => 'sub',
867                 filter => "(&(objectClass=GOhard)(|(macAddress=$macaddress)(dhcpHWaddress=ethernet $macaddress)))"
868         );
870         if($mesg->count() == 0) {
871                 &main::daemon_log("Host was not found in LDAP!", 1);
872         } else {
873                 my $entry= $mesg->entry(0);
874                 my $dn= $entry->dn;
875                 if(defined($entry->get_value("gotoHardwareChecksum"))) {
876                         if(! $entry->get_value("gotoHardwareChecksum") eq $gotoHardwareChecksum) {
877                                 $entry->replace(gotoHardwareChecksum => $gotoHardwareChecksum);
878                                 if($entry->update($main::ldap_handle)) {
879                                         &main::daemon_log("Hardware changed! Detection triggered.", 4);
880                                 }
881                         } else {
882                                 # Nothing to do
883                                 return;
884                         }
885                 }
886         } 
888         # Assemble data package
889         my %data = ();
891         # Need to append GOto settings?
892         if (defined $goto_admin and defined $goto_secret){
893                 $data{'goto_admin'}= $goto_admin;
894                 $data{'goto_secret'}= $goto_secret;
895         }
897         # set status = hardware_detection at jobqueue if entry exists
898         my $func_dic = {table=>$main::job_queue_tn,
899                 primkey=>['id'],
900                 timestamp=>&get_time,
901                 status=>'processing',
902                 result=>'none',
903                 progress=>'hardware-detection',
904                 headertag=>'trigger_action_reinstall',
905                 targettag=>$address,
906                 xmlmessage=>'none',
907                 macaddress=>$macaddress,
908         };
909         my $hd_res = $main::job_db->add_dbentry($func_dic);
910         &main::daemon_log("$session_id INFO: add '$macaddress' to job queue as an installing job", 5);
912         # Send information
913         &main::daemon_log("$session_id INFO: Send detect_hardware message to $address", 5);
914         return &build_msg("detect_hardware", $server_address, $address, \%data);
917 sub server_matches {
918         my $target = shift;
919         my $target_ip = sprintf("%s", $target =~ /^([0-9\.]*?):.*$/);
920         my $result = 0;
922         if($server_ip eq $target_ip) {
923                 $result= 1;
924         } elsif ($target_ip eq "0.0.0.0") {
925                 $result= 1;
926         } elsif ($server_ip eq "0.0.0.0") {     
927                 if ($target_ip eq "127.0.0.1") {
928                         $result= 1;
929                 } else {
930                         my $PROC_NET_ROUTE= ('/proc/net/route');
932                         open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
933                                 or die "Could not open $PROC_NET_ROUTE";
935                         my @ifs = <PROC_NET_ROUTE>;
937                         close(PROC_NET_ROUTE);
939                         # Eat header line
940                         shift @ifs;
941                         chomp @ifs;
942                         foreach my $line(@ifs) {
943                                 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
944                                 my $destination;
945                                 my $mask;
946                                 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
947                                 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
948                                 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
949                                 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
950                                 if(new NetAddr::IP($target_ip)->within(new NetAddr::IP($destination, $mask))) {
951                                         # destination matches route, save mac and exit
952                                         $result= 1;
953                                         last;
954                                 }
955                         }
956                 }
957         } else {
958                 &main::daemon_log("Target ip $target_ip does not match Server ip $server_ip",1);
959         }
961         return $result;
964 1;