Code

better multitasking and job queue handling
[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;
19 use utf8;
21 my $event_dir = "/usr/lib/gosa-si/server/events";
22 use lib "/usr/lib/gosa-si/server/events";
24 BEGIN{}
25 END {}
27 my ($server_ip, $server_mac_address, $server_port, $SIPackages_key, $max_clients, $ldap_uri, $ldap_base, $ldap_admin_dn, $ldap_admin_password, $server_interface);
28 my ($bus_activ, $bus_key, $bus_ip, $bus_port);
29 my $server;
30 my $event_hash;
31 my $network_interface;
32 my $no_bus;
33 my (@ldap_cfg, @pam_cfg, @nss_cfg, $goto_admin, $goto_secret);
34 my $mesg;
36 my %cfg_defaults = (
37 "bus" => {
38     "activ" => [\$bus_activ, "on"],
39     "key" => [\$bus_key, ""],
40     "ip" => [\$bus_ip, ""],
41     "port" => [\$bus_port, "20080"],
42     },
43 "server" => {
44     "ip" => [\$server_ip, "0.0.0.0"],
45     "mac-address" => [\$server_mac_address, "00:00:00:00:00"],
46     "port" => [\$server_port, "20081"],
47     "ldap-uri" => [\$ldap_uri, ""],
48     "ldap-base" => [\$ldap_base, ""],
49     "ldap-admin-dn" => [\$ldap_admin_dn, ""],
50     "ldap-admin-password" => [\$ldap_admin_password, ""],
51     "max-clients" => [\$max_clients, 100],
52     },
53 "SIPackages" => {
54     "key" => [\$SIPackages_key, ""],
55     },
56 );
58 ### START #####################################################################
60 # read configfile and import variables
61 &read_configfile();
64 # if server_ip is not an ip address but a name
65 if( inet_aton($server_ip) ){ $server_ip = inet_ntoa(inet_aton($server_ip)); } 
66 $network_interface= &get_interface_for_ip($server_ip);
67 $server_mac_address= &get_mac($network_interface);
69 &import_events();
71 # Unit tag can be defined in config
72 if((not defined($main::gosa_unit_tag)) || length($main::gosa_unit_tag) == 0) {
73         # Read gosaUnitTag from LDAP
74   &main::refresh_ldap_handle();
75         if( defined($main::ldap_handle) ) {
76                 &main::daemon_log("INFO: Searching for servers gosaUnitTag with mac address $server_mac_address",5);
77                 # Perform search for Unit Tag
78                 $mesg = $main::ldap_handle->search(
79                         base   => $ldap_base,
80                         scope  => 'sub',
81                         attrs  => ['gosaUnitTag'],
82                         filter => "(macaddress=$server_mac_address)"
83                 );
85                 if ($mesg->count == 1) {
86                         my $entry= $mesg->entry(0);
87                         my $unit_tag= $entry->get_value("gosaUnitTag");
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                                 if(defined($unit_tag) && length($unit_tag) > 0) {
107                                         &main::daemon_log("INFO: Detected gosaUnitTag $unit_tag for creating entries", 5);
108                                         $main::gosa_unit_tag= $unit_tag;
109                                 }
110                         } else {
111                                 # Perform another search for Unit Tag
112                                 $hostname= `hostname -s`;
113                                 chomp($hostname);
114                                 &main::daemon_log("INFO: Searching for servers gosaUnitTag with hostname $hostname",5);
115                                 $mesg = $main::ldap_handle->search(
116                                         base   => $ldap_base,
117                                         scope  => 'sub',
118                                         attrs  => ['gosaUnitTag'],
119                                         filter => "(&(cn=$hostname)(objectClass=goServer))"
120                                 );
121                                 if ($mesg->count == 1) {
122                                         my $entry= $mesg->entry(0);
123                                         my $unit_tag= $entry->get_value("gosaUnitTag");
124                                         if(defined($unit_tag) && length($unit_tag) > 0) {
125                                                 &main::daemon_log("INFO: Detected gosaUnitTag $unit_tag for creating entries", 5);
126                                                 $main::gosa_unit_tag= $unit_tag;
127                                         }
128                                 } else {
129                                         &main::daemon_log("WARNING: No gosaUnitTag detected. Not using gosaUnitTag", 3);
130                                 }
131                         }
132                 }
133         } else {
134                 &main::daemon_log("INFO: Using gosaUnitTag from config-file: $main::gosa_unit_tag",5);
135         }
139 my $server_address = "$server_ip:$server_port";
140 $main::server_address = $server_address;
143 if( inet_aton($bus_ip) ){ $bus_ip = inet_ntoa(inet_aton($bus_ip)); } 
144 ######################################################
145 # to change
146 if( $bus_ip eq "127.0.1.1" ) { $bus_ip = "127.0.0.1" }
147 ######################################################
148 my $bus_address = "$bus_ip:$bus_port";
149 $main::bus_address = $bus_address;
151 # create general settings for this module
152 my $xml = new XML::Simple();
154 # register at bus
155 if ($main::no_bus > 0) {
156     $bus_activ = "off"
158 if($bus_activ eq "on") {
159     &register_at_bus();
162 # add myself to known_server_db
163 my $res = $main::known_server_db->add_dbentry( {table=>'known_server',
164         primkey=>['hostname'],
165         hostname=>$server_address,
166         status=>'myself',
167         hostkey=>$SIPackages_key,
168         timestamp=>&get_time,
169         } );
173 ### functions #################################################################
176 sub get_module_info {
177     my @info = ($server_address,
178                 $SIPackages_key,
179                 );
180     return \@info;
184 #===  FUNCTION  ================================================================
185 #         NAME:  read_configfile
186 #   PARAMETERS:  cfg_file - string -
187 #      RETURNS:  nothing
188 #  DESCRIPTION:  read cfg_file and set variables
189 #===============================================================================
190 sub read_configfile {
191     my $cfg;
192     if( defined( $main::cfg_file) && ( length($main::cfg_file) > 0 )) {
193         if( -r $main::cfg_file ) {
194             $cfg = Config::IniFiles->new( -file => $main::cfg_file );
195         } else {
196             print STDERR "Couldn't read config file!";
197         }
198     } else {
199         $cfg = Config::IniFiles->new() ;
200     }
201     foreach my $section (keys %cfg_defaults) {
202         foreach my $param (keys %{$cfg_defaults{ $section }}) {
203             my $pinfo = $cfg_defaults{ $section }{ $param };
204             ${@$pinfo[0]} = $cfg->val( $section, $param, @$pinfo[1] );
205         }
206     }
208     # Read non predefined sections
209     my $param;
210     if ($cfg->SectionExists('ldap')){
211                 foreach $param ($cfg->Parameters('ldap')){
212                         push (@ldap_cfg, "$param ".$cfg->val('ldap', $param));
213                 }
214     }
215     if ($cfg->SectionExists('pam_ldap')){
216                 foreach $param ($cfg->Parameters('pam_ldap')){
217                         push (@pam_cfg, "$param ".$cfg->val('pam_ldap', $param));
218                 }
219     }
220     if ($cfg->SectionExists('nss_ldap')){
221                 foreach $param ($cfg->Parameters('nss_ldap')){
222                         push (@nss_cfg, "$param ".$cfg->val('nss_ldap', $param));
223                 }
224     }
225     if ($cfg->SectionExists('goto')){
226         $goto_admin= $cfg->val('goto', 'terminal_admin');
227         $goto_secret= $cfg->val('goto', 'terminal_secret');
228     } else {
229         $goto_admin= undef;
230         $goto_secret= undef;
231     }
235 #===  FUNCTION  ================================================================
236 #         NAME:  get_interface_for_ip
237 #   PARAMETERS:  ip address (i.e. 192.168.0.1)
238 #      RETURNS:  array: list of interfaces if ip=0.0.0.0, matching interface if found, undef else
239 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
240 #===============================================================================
241 sub get_interface_for_ip {
242         my $result;
243         my $ip= shift;
244         if ($ip && length($ip) > 0) {
245                 my @ifs= &get_interfaces();
246                 if($ip eq "0.0.0.0") {
247                         $result = "all";
248                 } else {
249                         foreach (@ifs) {
250                                 my $if=$_;
251                                 if(&main::get_ip($if) eq $ip) {
252                                         $result = $if;
253                                 }
254                         }       
255                 }
256         }       
257         return $result;
260 #===  FUNCTION  ================================================================
261 #         NAME:  get_interfaces 
262 #   PARAMETERS:  none
263 #      RETURNS:  (list of interfaces) 
264 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
265 #===============================================================================
266 sub get_interfaces {
267         my @result;
268         my $PROC_NET_DEV= ('/proc/net/dev');
270         open(PROC_NET_DEV, "<$PROC_NET_DEV")
271                 or die "Could not open $PROC_NET_DEV";
273         my @ifs = <PROC_NET_DEV>;
275         close(PROC_NET_DEV);
277         # Eat first two line
278         shift @ifs;
279         shift @ifs;
281         chomp @ifs;
282         foreach my $line(@ifs) {
283                 my $if= (split /:/, $line)[0];
284                 $if =~ s/^\s+//;
285                 push @result, $if;
286         }
288         return @result;
291 #===  FUNCTION  ================================================================
292 #         NAME:  get_mac 
293 #   PARAMETERS:  interface name (i.e. eth0)
294 #      RETURNS:  (mac address) 
295 #  DESCRIPTION:  Uses ioctl to get mac address directly from system.
296 #===============================================================================
297 sub get_mac {
298         my $ifreq= shift;
299         my $result;
300         if ($ifreq && length($ifreq) > 0) { 
301                 if($ifreq eq "all") {
302                         $result = "00:00:00:00:00:00";
303                 } else {
304                         my $SIOCGIFHWADDR= 0x8927;     # man 2 ioctl_list
306                         # A configured MAC Address should always override a guessed value
307                         if ($server_mac_address and length($server_mac_address) > 0) {
308                                 $result= $server_mac_address;
309                         }
311                         socket SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('ip')
312                                 or die "socket: $!";
314                         if(ioctl SOCKET, $SIOCGIFHWADDR, $ifreq) {
315                                 my ($if, $mac)= unpack 'h36 H12', $ifreq;
317                                 if (length($mac) > 0) {
318                                         $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])$/;
319                                         $mac= sprintf("%s:%s:%s:%s:%s:%s", $1, $2, $3, $4, $5, $6);
320                                         $result = $mac;
321                                 }
322                         }
323                 }
324         }
325         return $result;
329 #===  FUNCTION  ================================================================
330 #         NAME:  register_at_bus
331 #   PARAMETERS:  nothing
332 #      RETURNS:  nothing
333 #  DESCRIPTION:  creates an entry in known_daemons and send a 'here_i_am' msg to bus
334 #===============================================================================
335 sub register_at_bus {
337     # add bus to known_server_db
338     my $res = $main::known_server_db->add_dbentry( {table=>'known_server',
339                                                     primkey=>['hostname'],
340                                                     hostname=>$bus_address,
341                                                     status=>'bus',
342                                                     hostkey=>$bus_key,
343                                                     timestamp=>&get_time,
344                                                 } );
345     my $msg_hash = &create_xml_hash("here_i_am", $server_address, $bus_address);
346     my $msg = &create_xml_string($msg_hash);
348     &main::send_msg_to_target($msg, $bus_address, $bus_key, "here_i_am");
349     return $msg;
353 sub import_events {
354     if (not -e $event_dir) {
355         &main::daemon_log("ERROR: cannot find directory or directory is not readable: $event_dir", 1);   
356     }
357     opendir (DIR, $event_dir) or die "ERROR while loading gosa-si-events from directory $event_dir : $!\n";
359     while (defined (my $event = readdir (DIR))) {
360         if( $event eq "." || $event eq ".." ) { next; }  
361         if( $event eq "gosaTriggered.pm" ) { next; }    # only GOsa specific events
363         eval{ require $event; };
364         if( $@ ) {
365             &main::daemon_log("import of event module '$event' failed", 1);
366             &main::daemon_log("$@", 8);
367             next;
368         }
370         $event =~ /(\S*?).pm$/;
371         my $event_module = $1;
372         my $events_l = eval( $1."::get_events()") ;
373         foreach my $event_name (@{$events_l}) {
374             $event_hash->{$event_name} = $event_module;
375         }
376         my $events_string = join( ", ", @{$events_l});
377         &main::daemon_log("INFO: SIPackages imported events $events_string", 5);
378     }
382 #===  FUNCTION  ================================================================
383 #         NAME:  process_incoming_msg
384 #   PARAMETERS:  crypted_msg - string - incoming crypted message
385 #      RETURNS:  nothing
386 #  DESCRIPTION:  handels the proceeded distribution to the appropriated functions
387 #===============================================================================
388 sub process_incoming_msg {
389     my ($msg, $msg_hash, $session_id) = @_ ;
390     my $error = 0;
391     my $host_name;
392     my $host_key;
393     my @out_msg_l = ("nohandler");
395     # process incoming msg
396     my $header = @{$msg_hash->{header}}[0]; 
397     my @target_l = @{$msg_hash->{target}};
399     # skip PREFIX
400     $header =~ s/^CLMSG_//;
402     &main::daemon_log("$session_id DEBUG: SIPackages: msg to process: $header", 7);
404     if( 0 == length @target_l){     
405         &main::daemon_log("$session_id ERROR: no target specified for msg $header", 1);
406         $error++;
407     }
409     if( 1 == length @target_l) {
410         my $target = $target_l[0];
411                 if(&server_matches($target)) {
414             if ($header eq 'new_key') {
415                 @out_msg_l = &new_key($msg_hash)
416             } elsif ($header eq 'here_i_am') {
417                 @out_msg_l = &here_i_am($msg_hash, $session_id)
418             } else {
419                 if( exists $event_hash->{$header} ) {
420                     # a event exists with the header as name
421                     &main::daemon_log("$session_id INFO: found event '$header' at event-module '".$event_hash->{$header}."'", 5);
422                     no strict 'refs';
423                     @out_msg_l = &{$event_hash->{$header}."::$header"}($msg, $msg_hash, $session_id);
424                 }
425             }
427             # if delivery not possible raise error and return 
428             if( not defined $out_msg_l[0] ) {
429                 @out_msg_l = ();
430             } elsif( $out_msg_l[0] eq 'nohandler') {
431                 &main::daemon_log("$session_id ERROR: SIPackages: no event handler or core function defined for '$header'", 1);
432                 @out_msg_l = ();
433             } 
435         }
436                 else {
437                         &main::daemon_log("INFO: msg is not for gosa-si-server '$server_address', deliver it to target '$target'", 5);
438                         push(@out_msg_l, $msg);
439                 }
440     }
442     return \@out_msg_l;
446 #===  FUNCTION  ================================================================
447 #         NAME:  new_passwd
448 #   PARAMETERS:  msg_hash - ref - hash from function create_xml_hash
449 #      RETURNS:  nothing
450 #  DESCRIPTION:  process this incoming message
451 #===============================================================================
452 sub new_key {
453     my ($msg_hash) = @_;
454     my @out_msg_l;
455     
456     my $header = @{$msg_hash->{header}}[0];
457     my $source_name = @{$msg_hash->{source}}[0];
458     my $source_key = @{$msg_hash->{new_key}}[0];
459     my $query_res;
461     # check known_clients_db
462     my $sql_statement = "SELECT * FROM known_clients WHERE hostname='$source_name'";
463     $query_res = $main::known_clients_db->select_dbentry( $sql_statement );
464     if( 1 == keys %{$query_res} ) {
465         my $act_time = &get_time;
466         my $sql_statement= "UPDATE known_clients ".
467             "SET hostkey='$source_key', timestamp='$act_time' ".
468             "WHERE hostname='$source_name'";
469         my $res = $main::known_clients_db->update_dbentry( $sql_statement );
470         my $hash = &create_xml_hash("confirm_new_key", $server_address, $source_name);
471         my $out_msg = &create_xml_string($hash);
472         push(@out_msg_l, $out_msg);
473     }
475     # only do if host still not found
476     if( 0 == @out_msg_l ) {
477         # check known_server_db
478         $sql_statement = "SELECT * FROM known_server WHERE hostname='$source_name'";
479         $query_res = $main::known_server_db->select_dbentry( $sql_statement );
480         if( 1 == keys %{$query_res} ) {
481             my $act_time = &get_time;
482             my $sql_statement= "UPDATE known_server ".
483                 "SET hostkey='$source_key', timestamp='$act_time' ".
484                 "WHERE hostname='$source_name'";
485             my $res = $main::known_server_db->update_dbentry( $sql_statement );
487             my $hash = &create_xml_hash("confirm_new_key", $server_address, $source_name);
488             my $out_msg = &create_xml_string($hash);
489             push(@out_msg_l, $out_msg);
490         }
491     }
493     return @out_msg_l;
497 #===  FUNCTION  ================================================================
498 #         NAME:  here_i_am
499 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
500 #      RETURNS:  nothing
501 #  DESCRIPTION:  process this incoming message
502 #===============================================================================
503 sub here_i_am {
504     my ($msg_hash, $session_id) = @_;
505     my @out_msg_l;
506     my $out_hash;
508     my $source = @{$msg_hash->{source}}[0];
509     my $mac_address = @{$msg_hash->{mac_address}}[0];
510         my $gotoHardwareChecksum = @{$msg_hash->{gotoHardwareChecksum}}[0];
512     # number of known clients
513     my $nu_clients= $main::known_clients_db->count_dbentries('known_clients');
515     # check wether client address or mac address is already known
516     my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$source'";
517     my $db_res= $main::known_clients_db->select_dbentry( $sql_statement );
518     
519     if ( 1 == keys %{$db_res} ) {
520         &main::daemon_log("$session_id WARNING: $source is already known as a client", 1);
521         &main::daemon_log("$session_id WARNING: values for $source are being overwritten", 1);   
522         $nu_clients --;
523     }
525     # number of actual activ clients
526     my $act_nu_clients = $nu_clients;
528     &main::daemon_log("$session_id INFO: number of actual activ clients: $act_nu_clients", 5);
529     &main::daemon_log("$session_id INFO: number of maximal allowed clients: $max_clients", 5);
531     if($max_clients <= $act_nu_clients) {
532         my $out_hash = &create_xml_hash("denied", $server_address, $source);
533         &add_content2xml_hash($out_hash, "denied", "I_cannot_take_any_more_clients!");
534         my $passwd = @{$msg_hash->{new_passwd}}[0]; 
535         &send_msg_hash2address($out_hash, $source, $passwd);
536         return;
537     }
538     
539     # new client accepted
540     my $new_passwd = @{$msg_hash->{new_passwd}}[0];
542     # create entry in known_clients
543     my $events = @{$msg_hash->{events}}[0];
544     
546     # add entry to known_clients_db
547     my $act_timestamp = &get_time;
548     my $res = $main::known_clients_db->add_dbentry( {table=>'known_clients', 
549                                                 primkey=>['hostname'],
550                                                 hostname=>$source,
551                                                 events=>$events,
552                                                 macaddress=>$mac_address,
553                                                 status=>'registered',
554                                                 hostkey=>$new_passwd,
555                                                 timestamp=>$act_timestamp,
556                                                 } );
558     if ($res != 0)  {
559         &main::daemon_log("$session_id ERROR: cannot add entry to known_clients: $res");
560         return;
561     }
562     
563     # return acknowledgement to client
564     $out_hash = &create_xml_hash("registered", $server_address, $source);
566     # notify registered client to bus
567     if( $bus_activ eq "on") {
568         # fetch actual bus key
569         my $sql_statement= "SELECT * FROM known_server WHERE status='bus'";
570         my $query_res = $main::known_server_db->select_dbentry( $sql_statement );
571         my $hostkey = $query_res->{1}->{'hostkey'};
573         # send update msg to bus
574         $out_hash = &create_xml_hash("new_client", $server_address, $bus_address, $source);
575         &add_content2xml_hash($out_hash, "macaddress", $mac_address);
576         &add_content2xml_hash($out_hash, "timestamp", $act_timestamp);
577         my $new_client_out = &create_xml_string($out_hash);
578         push(@out_msg_l, $new_client_out);
579         &main::daemon_log("$session_id INFO: send bus msg that client '$source' has registered at server '$server_address'", 5);
580     }
582     # give the new client his ldap config
583     # Workaround: Send within the registration response, if the client will get an ldap config later
584         my $new_ldap_config_out = &new_ldap_config($source, $session_id);
585         if($new_ldap_config_out && (!($new_ldap_config_out =~ /error/))) {
586                 &add_content2xml_hash($out_hash, "ldap_available", "true");
587         } elsif($new_ldap_config_out && $new_ldap_config_out =~ /error/){
588                 &add_content2xml_hash($out_hash, "error", $new_ldap_config_out);
590                 my $sql_statement = "UPDATE $main::job_queue_tn ".
591                 "SET status='error', result='$new_ldap_config_out' ".
592                 "WHERE status='processing' AND macaddress LIKE '$mac_address'";
593                 my $res = $main::job_db->update_dbentry($sql_statement);
594                 &main::daemon_log("$session_id DEBUG: $sql_statement RESULT: $res", 7);         
595         }
596     my $register_out = &create_xml_string($out_hash);
597     push(@out_msg_l, $register_out);
599     # Really send the ldap config
600     if( $new_ldap_config_out && (!($new_ldap_config_out =~ /error/))) {
601             push(@out_msg_l, $new_ldap_config_out);
602     }
604         my $hardware_config_out = &hardware_config($source, $gotoHardwareChecksum);
605         if( $hardware_config_out ) {
606                 push(@out_msg_l, $hardware_config_out);
607         }
609     return @out_msg_l;
613 #===  FUNCTION  ================================================================
614 #         NAME:  who_has
615 #   PARAMETERS:  msg_hash - hash - hash from function create_xml_hash
616 #      RETURNS:  nothing 
617 #  DESCRIPTION:  process this incoming message
618 #===============================================================================
619 sub who_has {
620     my ($msg_hash) = @_ ;
621     my @out_msg_l;
622     
623     # what is your search pattern
624     my $search_pattern = @{$msg_hash->{who_has}}[0];
625     my $search_element = @{$msg_hash->{$search_pattern}}[0];
626     &main::daemon_log("who_has-msg looking for $search_pattern $search_element", 7);
628     # scanning known_clients for search_pattern
629     my @host_addresses = keys %$main::known_clients;
630     my $known_clients_entries = length @host_addresses;
631     my $host_address;
632     foreach my $host (@host_addresses) {
633         my $client_element = $main::known_clients->{$host}->{$search_pattern};
634         if ($search_element eq $client_element) {
635             $host_address = $host;
636             last;
637         }
638     }
639         
640     # search was successful
641     if (defined $host_address) {
642         my $source = @{$msg_hash->{source}}[0];
643         my $out_hash = &create_xml_hash("who_has_i_do", $server_address, $source, "mac_address");
644         &add_content2xml_hash($out_hash, "mac_address", $search_element);
645         my $out_msg = &create_xml_string($out_hash);
646         push(@out_msg_l, $out_msg);
647     }
648     return @out_msg_l;
652 sub who_has_i_do {
653     my ($msg_hash) = @_ ;
654     my $header = @{$msg_hash->{header}}[0];
655     my $source = @{$msg_hash->{source}}[0];
656     my $search_param = @{$msg_hash->{$header}}[0];
657     my $search_value = @{$msg_hash->{$search_param}}[0];
658     print "\ngot msg $header:\nserver $source has client with $search_param $search_value\n";
662 #===  FUNCTION  ================================================================
663 #         NAME:  new_ldap_config
664 #   PARAMETERS:  address - string - ip address and port of a host
665 #      RETURNS:  gosa-si conform message
666 #  DESCRIPTION:  send to address the ldap configuration found for dn gotoLdapServer
667 #===============================================================================
668 sub new_ldap_config {
669         my ($address, $session_id) = @_ ;
671         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address' OR macaddress LIKE '$address'";
672         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
674         # check hit
675         my $hit_counter = keys %{$res};
676         if( not $hit_counter == 1 ) {
677                 &main::daemon_log("$session_id ERROR: more or no hit found in known_clients_db by query by '$address'", 1);
678         }
680     $address = $res->{1}->{hostname};
681         my $macaddress = $res->{1}->{macaddress};
682         my $hostkey = $res->{1}->{hostkey};
684         if (not defined $macaddress) {
685                 &main::daemon_log("$session_id ERROR: no mac address found for client $address", 1);
686                 return;
687         }
689         # Build LDAP connection
690   &main::refresh_ldap_handle();
691         if( not defined $main::ldap_handle ) {
692                 &main::daemon_log("$session_id ERROR: cannot connect to ldap: $ldap_uri", 1);
693                 return;
694         } 
696         # Perform search
697         $mesg = $main::ldap_handle->search( base   => $ldap_base,
698                 scope  => 'sub',
699                 attrs => ['dn', 'gotoLdapServer', 'gosaUnitTag', 'FAIclass'],
700                 filter => "(&(objectClass=GOhard)(macaddress=$macaddress)(gotoLdapServer=*))");
701         #$mesg->code && die $mesg->error;
702         if($mesg->code) {
703                 &main::daemon_log("$session_id ".$mesg->error, 1);
704                 return;
705         }
707         # Sanity check
708         if ($mesg->count != 1) {
709                 &main::daemon_log("$session_id WARNING: client with mac address $macaddress not found/unique/active - not sending ldap config".
710                 "\n\tbase: $ldap_base".
711                 "\n\tscope: sub".
712                 "\n\tattrs: dn, gotoLdapServer".
713                 "\n\tfilter: (&(objectClass=GOhard)(macaddress=$macaddress)(gotoLdapServer=*))", 1);
714                 return;
715         }
717         my $entry= $mesg->entry(0);
718         my $dn= $entry->dn;
719         my @servers= $entry->get_value("gotoLdapServer");
720         my $unit_tag= $entry->get_value("gosaUnitTag");
721         my @ldap_uris;
722         my $server;
723         my $base;
724         my $release;
726         # Fill release if available
727         my $FAIclass= $entry->get_value("FAIclass");
728         if (defined $FAIclass && $FAIclass =~ /^.* :([A-Za-z0-9\/.]+).*$/) {
729                 $release= $1;
730         }
732         # Do we need to look at an object class?
733         if (length(@servers) < 1){
734                 $mesg = $main::ldap_handle->search( base   => $ldap_base,
735                         scope  => 'sub',
736                         attrs => ['dn', 'gotoLdapServer', 'FAIclass'],
737                         filter => "(&(objectClass=gosaGroupOfNames)(member=$dn))");
738                 #$mesg->code && die $mesg->error;
739                 if($mesg->code) {
740                         &main::daemon_log("$session_id ".$mesg->error, 1);
741                         return;
742                 }
744                 # Sanity check
745                 if ($mesg->count != 1) {
746                         &main::daemon_log("$session_id WARNING: no LDAP information found for client mac $macaddress", 1);
747                         return;
748                 }
750                 $entry= $mesg->entry(0);
751                 $dn= $entry->dn;
752                 @servers= $entry->get_value("gotoLdapServer");
754                 if (not defined $release){
755                         $FAIclass= $entry->get_value("FAIclass");
756                         if (defined $FAIclass && $FAIclass =~ /^.* :([A-Za-z0-9\/.]+).*$/) {
757                                 $release= $1;
758                         }
759                 }
760         }
762         @servers= sort (@servers);
764         foreach $server (@servers){
765                 # Conversation for backward compatibility
766                 if (not $server =~ /^\d+:[^:]+:ldap[^:]*:\/\// ) {
767                     if ($server =~ /^([^:]+):([^:]+)$/ ) {
768                       $server= "1:dummy:ldap://$1/$2";
769                     } elsif ($server =~ /^(\d+):([^:]+):(.*)$/ ) {
770                       $server= "$1:dummy:ldap://$2/$3";
771                     }
772                 }
774                 $base= $server;
775                 $server =~ s%^[^:]+:[^:]+:(ldap.*://[^/]+)/.*$%$1%;
776                 $base =~ s%^[^:]+:[^:]+:ldap.*://[^/]+/(.*)$%$1%;
777                 push (@ldap_uris, $server);
778         }
780         # Assemble data package
781         my %data = ( 'ldap_uri'  => \@ldap_uris, 'ldap_base' => $base,
782                 'ldap_cfg' => \@ldap_cfg, 'pam_cfg' => \@pam_cfg,'nss_cfg' => \@nss_cfg );
783         if (defined $release){
784                 $data{'release'}= $release;
785         }
787         # Need to append GOto settings?
788         if (defined $goto_admin and defined $goto_secret){
789                 $data{'goto_admin'}= $goto_admin;
790                 $data{'goto_secret'}= $goto_secret;
791         }
793         # Append unit tag if needed
794         if (defined $unit_tag){
796                 # Find admin base and department name
797                 $mesg = $main::ldap_handle->search( base   => $ldap_base,
798                         scope  => 'sub',
799                         attrs => ['dn', 'ou'],
800                         filter => "(&(objectClass=gosaAdministrativeUnit)(gosaUnitTag=$unit_tag))");
801                 #$mesg->code && die $mesg->error;
802                 if($mesg->code) {
803                         &main::daemon_log($mesg->error, 1);
804                         return "error-unit-tag-count-0";
805                 }
807                 # Sanity check
808                 if ($mesg->count != 1) {
809                         &main::daemon_log("WARNING: cannot find administrative unit for client with tag $unit_tag", 1);
810                         return "error-unit-tag-count-".$mesg->count;
811                 }
813                 $entry= $mesg->entry(0);
814                 $data{'admin_base'}= $entry->dn;
815                 $data{'department'}= $entry->get_value("ou");
817                 # Append unit Tag
818                 $data{'unit_tag'}= $unit_tag;
819         }
821         # Send information
822         return &build_msg("new_ldap_config", $server_address, $address, \%data);
826 #===  FUNCTION  ================================================================
827 #         NAME:  hardware_config
828 #   PARAMETERS:  address - string - ip address and port of a host
829 #      RETURNS:  
830 #  DESCRIPTION:  
831 #===============================================================================
832 sub hardware_config {
833         my ($address, $gotoHardwareChecksum) = @_ ;
835         my $sql_statement= "SELECT * FROM known_clients WHERE hostname='$address'";
836         my $res = $main::known_clients_db->select_dbentry( $sql_statement );
838         # check hit
839         my $hit_counter = keys %{$res};
840         if( not $hit_counter == 1 ) {
841                 &main::daemon_log("ERROR: more or no hit found in known_clients_db by query by '$address'", 1);
842         }
844         my $macaddress = $res->{1}->{macaddress};
845         my $hostkey = $res->{1}->{hostkey};
847         if (not defined $macaddress) {
848                 &main::daemon_log("ERROR: no mac address found for client $address", 1);
849                 return;
850         }
852         # Build LDAP connection
853   &main::refresh_ldap_handle();
854         if( not defined $main::ldap_handle ) {
855                 &main::daemon_log("ERROR: cannot connect to ldap: $ldap_uri", 1);
856                 return;
857         } 
859         # Perform search
860         $mesg = $main::ldap_handle->search(
861                 base   => $ldap_base,
862                 scope  => 'sub',
863                 filter => "(&(objectClass=GOhard)(|(macAddress=$macaddress)(dhcpHWaddress=ethernet $macaddress)))"
864         );
866         if($mesg->count() == 0) {
867                 &main::daemon_log("Host was not found in LDAP!", 1);
868         } else {
869                 my $entry= $mesg->entry(0);
870                 my $dn= $entry->dn;
871                 if(defined($entry->get_value("gotoHardwareChecksum"))) {
872                         if(! $entry->get_value("gotoHardwareChecksum") eq $gotoHardwareChecksum) {
873                                 $entry->replace(gotoHardwareChecksum => $gotoHardwareChecksum);
874                                 if($entry->update($main::ldap_handle)) {
875                                         &main::daemon_log("Hardware changed! Detection triggered.", 4);
876                                 }
877                         } else {
878                                 # Nothing to do
879                                 return;
880                         }
881                 }
882         } 
884         # Assemble data package
885         my %data = ();
887         # Need to append GOto settings?
888         if (defined $goto_admin and defined $goto_secret){
889                 $data{'goto_admin'}= $goto_admin;
890                 $data{'goto_secret'}= $goto_secret;
891         }
893         &main::daemon_log("Send detect_hardware message to $address", 4);
895         # Send information
896         return &build_msg("detect_hardware", $server_address, $address, \%data);
899 sub server_matches {
900         my $target = shift;
901         my $target_ip = sprintf("%s", $target =~ /^([0-9\.]*?):.*$/);
902         my $result = 0;
904         if($server_ip eq $target_ip) {
905                 $result= 1;
906         } elsif ($target_ip eq "0.0.0.0") {
907                 $result= 1;
908         } elsif ($server_ip eq "0.0.0.0") {     
909                 if ($target_ip eq "127.0.0.1") {
910                         $result= 1;
911                 } else {
912                         my $PROC_NET_ROUTE= ('/proc/net/route');
914                         open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
915                                 or die "Could not open $PROC_NET_ROUTE";
917                         my @ifs = <PROC_NET_ROUTE>;
919                         close(PROC_NET_ROUTE);
921                         # Eat header line
922                         shift @ifs;
923                         chomp @ifs;
924                         foreach my $line(@ifs) {
925                                 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
926                                 my $destination;
927                                 my $mask;
928                                 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
929                                 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
930                                 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
931                                 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
932                                 if(new NetAddr::IP($target_ip)->within(new NetAddr::IP($destination, $mask))) {
933                                         # destination matches route, save mac and exit
934                                         $result= 1;
935                                         last;
936                                 }
937                         }
938                 }
939         } else {
940                 &main::daemon_log("Target ip $target_ip does not match Server ip $server_ip",1);
941         }
943         return $result;
946 1;