Code

Added Function run_as.
[gosa.git] / gosa-si / modules / GosaPackages.pm
1 package GosaPackages;
3 use Exporter;
4 @ISA = ("Exporter");
6 use strict;
7 use warnings;
8 use GOSA::GosaSupportDaemon;
9 use IO::Socket::INET;
10 use Socket;
11 use XML::Simple;
12 use File::Spec;
13 use Data::Dumper;
14 use GOSA::DBsqlite;
15 use MIME::Base64;
17 my $event_dir = "/usr/lib/gosa-si/server/GosaPackages";
18 use lib "/usr/lib/gosa-si/server/GosaPackages";
20 BEGIN{}
21 END{}
23 my ($server_ip, $server_port, $server_passwd, $max_clients);
24 my ($gosa_ip, $gosa_mac_address, $gosa_port, $gosa_passwd, $network_interface);
25 my ($job_queue_timeout, $job_queue_file_name);
27 my %cfg_defaults = (
28 "server" => {
29     "ip" => [\$server_ip, "0.0.0.0"],
30     "port" => [\$server_port, "20081"],
31     "key" => [\$server_passwd, ""],
32     "max-clients" => [\$max_clients, 100],
33     },
34 "GOsaPackages" => {
35     "ip" => [\$gosa_ip, "0.0.0.0"],
36     "port" => [\$gosa_port, "20082"],
37     "key" => [\$gosa_passwd, "none"],
38     "job-queue" => [\$job_queue_file_name, '/var/lib/gosa-si/jobs.db'],
39     },
40 );
41  
43 ## START ##########################
45 # read configfile and import variables
46 &read_configfile();
47 $network_interface= &get_interface_for_ip($server_ip);
48 $gosa_mac_address= &get_mac($network_interface);
50 # complete addresses
51 if( inet_aton($server_ip) ){ $server_ip = inet_ntoa(inet_aton($server_ip)); } 
52 our $server_address = "$server_ip:$server_port";
53 if( inet_aton($gosa_ip) ){ $gosa_ip = inet_ntoa(inet_aton($gosa_ip)); }
54 $main::gosa_address = "$gosa_ip:$gosa_port";
56 # create general settings for this module
57 #y $gosa_cipher = &create_ciphering($gosa_passwd);
58 my $xml = new XML::Simple();
60 # import local events
61 my ($error, $result, $event_hash) = &import_events($event_dir);
62 if ($error == 0) {
63     foreach my $log_line (@$result) {
64         &main::daemon_log("0 DEBUG: GosaPackages - $log_line", 7);
65     }
66 } else {
67     foreach my $log_line (@$result) {
68         &main::daemon_log("0 ERROR: GosaPackages - $log_line", 1);
69     }
70 }
73 ## FUNCTIONS #################################################################
75 sub get_module_info {
76     my @info = ($main::gosa_address,
77                 $gosa_passwd,
78                 );
79     return \@info;
80 }
83 #===  FUNCTION  ================================================================
84 #         NAME:  read_configfile
85 #   PARAMETERS:  cfg_file - string -
86 #      RETURNS:  nothing
87 #  DESCRIPTION:  read cfg_file and set variables
88 #===============================================================================
89 sub read_configfile {
90     my $cfg;
91     if( defined( $main::cfg_file) && ( (-s $main::cfg_file) > 0 )) {
92         if( -r $main::cfg_file ) {
93             $cfg = Config::IniFiles->new( -file => $main::cfg_file );
94         } else {
95             print STDERR "Couldn't read config file!";
96         }
97     } else {
98         $cfg = Config::IniFiles->new() ;
99     }
100     foreach my $section (keys %cfg_defaults) {
101         foreach my $param (keys %{$cfg_defaults{ $section }}) {
102             my $pinfo = $cfg_defaults{ $section }{ $param };
103             ${@$pinfo[0]} = $cfg->val( $section, $param, @$pinfo[1] );
104         }
105     }
108 # moved to GosaSupportDaemon: 03-06-2008: rettenbe
109 #===  FUNCTION  ================================================================
110 #         NAME:  get_interface_for_ip
111 #   PARAMETERS:  ip address (i.e. 192.168.0.1)
112 #      RETURNS:  array: list of interfaces if ip=0.0.0.0, matching interface if found, undef else
113 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
114 #===============================================================================
115 #sub get_interface_for_ip {
116 #    my $result;
117 #    my $ip= shift;
118 #    if ($ip && length($ip) > 0) {
119 #        my @ifs= &get_interfaces();
120 #        if($ip eq "0.0.0.0") {
121 #            $result = "all";
122 #        } else {
123 #            foreach (@ifs) {
124 #                my $if=$_;
125 #                if(get_ip($if) eq $ip) {
126 #                    $result = $if;
127 #                }
128 #            }       
129 #        }
130 #    }       
131 #    return $result;
132 #}
134 # moved to GosaSupportDaemon: 03-06-2008: rettenbe
135 #===  FUNCTION  ================================================================
136 #         NAME:  get_interfaces 
137 #   PARAMETERS:  none
138 #      RETURNS:  (list of interfaces) 
139 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
140 #===============================================================================
141 #sub get_interfaces {
142 #        my @result;
143 #        my $PROC_NET_DEV= ('/proc/net/dev');
145 #        open(PROC_NET_DEV, "<$PROC_NET_DEV")
146 #                or die "Could not open $PROC_NET_DEV";
148 #        my @ifs = <PROC_NET_DEV>;
150 #        close(PROC_NET_DEV);
152 #        # Eat first two line
153 #        shift @ifs;
154 #        shift @ifs;
156 #        chomp @ifs;
157 #        foreach my $line(@ifs) {
158 #                my $if= (split /:/, $line)[0];
159 #                $if =~ s/^\s+//;
160 #                push @result, $if;
161 #        }
163 #        return @result;
164 #}
166 #===  FUNCTION  ================================================================
167 #         NAME:  get_mac 
168 #   PARAMETERS:  interface name (i.e. eth0)
169 #      RETURNS:  (mac address) 
170 #  DESCRIPTION:  Uses ioctl to get mac address directly from system.
171 #===============================================================================
172 sub get_mac {
173     my $ifreq= shift;
174     my $result;
175     if ($ifreq && length($ifreq) > 0) { 
176         if($ifreq eq "all") {
177             $result = "00:00:00:00:00:00";
178         } else {
179             my $SIOCGIFHWADDR= 0x8927;     # man 2 ioctl_list
181                 # A configured MAC Address should always override a guessed value
182                 if ($gosa_mac_address and length($gosa_mac_address) > 0) {
183                     $result= $gosa_mac_address;
184                 }
186             socket SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('ip')
187                 or die "socket: $!";
189             if(ioctl SOCKET, $SIOCGIFHWADDR, $ifreq) {
190                 my ($if, $mac)= unpack 'h36 H12', $ifreq;
192                 if (length($mac) > 0) {
193                     $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])$/;
194                     $mac= sprintf("%s:%s:%s:%s:%s:%s", $1, $2, $3, $4, $5, $6);
195                     $result = $mac;
196                 }
197             }
198         }
199     }
200     return $result;
203 # moved to GosaSupportDaemon: 03-06-2008: rettenbe
204 #===  FUNCTION  ================================================================
205 #         NAME:  get_ip 
206 #   PARAMETERS:  interface name (i.e. eth0)
207 #      RETURNS:  (ip address) 
208 #  DESCRIPTION:  Uses ioctl to get ip address directly from system.
209 #===============================================================================
210 #sub get_ip {
211 #        my $ifreq= shift;
212 #        my $result= "";
213 #        my $SIOCGIFADDR= 0x8915;       # man 2 ioctl_list
214 #        my $proto= getprotobyname('ip');
216 #        socket SOCKET, PF_INET, SOCK_DGRAM, $proto
217 #                or die "socket: $!";
219 #        if(ioctl SOCKET, $SIOCGIFADDR, $ifreq) {
220 #                my ($if, $sin)    = unpack 'a16 a16', $ifreq;
221 #                my ($port, $addr) = sockaddr_in $sin;
222 #                my $ip            = inet_ntoa $addr;
224 #                if ($ip && length($ip) > 0) {
225 #                        $result = $ip;
226 #                }
227 #        }
229 #        return $result;
230 #}
233 #===  FUNCTION  ================================================================
234 #         NAME:  process_incoming_msg
235 #   PARAMETERS:  crypted_msg - string - incoming crypted message
236 #      RETURNS:  nothing
237 #  DESCRIPTION:  handels the proceeded distribution to the appropriated functions
238 #===============================================================================
239 sub process_incoming_msg {
240     my ($msg, $msg_hash, $session_id) = @_ ;
241     my $header = @{$msg_hash->{header}}[0];
242     my @msg_l;
243     my @out_msg_l;
245     &main::daemon_log("$session_id DEBUG: GosaPackages: msg to process '$header'", 7);
246     
247     if ($header =~ /^job_/) {
248         @msg_l = &process_job_msg($msg, $msg_hash, $session_id);
249     } 
250     elsif ($header =~ /^gosa_/) {
251         @msg_l = &process_gosa_msg($msg, $msg_hash, $session_id);
252     } 
253     else {
254         &main::daemon_log("$session_id ERROR: $header is not a valid GosaPackage-header, need a 'job_' or a 'gosa_' prefix", 1);
255     }
257     foreach my $out_msg ( @msg_l ) {
258         # substitute in all outgoing msg <source>GOSA</source> of <source>$server_address</source>
259         $out_msg =~ s/<source>GOSA<\/source>/<source>$server_address<\/source>/g;
260         $out_msg =~ s/<\/xml>/<session_id>$session_id<\/session_id><\/xml>/;
261         if (defined $out_msg){
262             push(@out_msg_l, $out_msg);
263         }
265     }
267     return \@out_msg_l;
271 sub process_gosa_msg {
272     my ($msg, $msg_hash, $session_id) = @_ ;
273     my $out_msg;
274     my @out_msg_l = ('nohandler');
275     my $sql_events;
277     my $header = @{$msg_hash->{'header'}}[0];
278     my $target = @{$msg_hash->{'target'}}[0];
279     $header =~ s/gosa_//;
281     # check local installed events
282     if( exists $event_hash->{$header} ) {
283         # a event exists with the header as name
284         &main::daemon_log("$session_id INFO: found event '$header' at event-module '".$event_hash->{$header}."'", 5);
285         no strict 'refs';
286         @out_msg_l = &{$event_hash->{$header}."::$header"}( $msg, $msg_hash, $session_id );
288     # check client registered events
289     } else {
290         $sql_events = "SELECT * FROM $main::known_clients_tn WHERE ( (macaddress LIKE '$target') OR (hostname='$target') )"; 
291         my $res = $main::known_clients_db->select_dbentry( $sql_events );
292         my $l = keys(%$res);
293         
294         # set error if no or more than 1 hits are found for sql query
295         if ( $l != 1) {
296             @out_msg_l = ('knownclienterror');
297         
298         # found exact 1 hit in db
299         } else {
300             my $client_events = $res->{'1'}->{'events'};
302             # client is registered for this event, deliver this message to client
303             if ($client_events =~ /,$header,/) {
304                 $msg =~ s/<header>gosa_/<header>/;
305                 @out_msg_l = ( $msg );
307             # client is not registered for this event, set error
308             } else {
309                 @out_msg_l = ('noeventerror');
310             }
311         }
312     }
314     # if delivery not possible raise error and return 
315     if (not defined $out_msg_l[0]) {
316         @out_msg_l = ();
317     } elsif ($out_msg_l[0] eq 'nohandler') {
318         &main::daemon_log("$session_id ERROR: GosaPackages: no event handler or core function defined for '$header'", 1);
319         @out_msg_l = ();
320     } elsif ($out_msg_l[0] eq 'knownclienterror') {
321         &main::daemon_log("$session_id ERROR: no event handler found for '$header', check client registraion events!", 1);
322         &main::daemon_log("$session_id ERROR: no or more than 1 hits are found at known_clients_db with sql query: '$sql_events'", 1);
323         &main::daemon_log("$session_id ERROR: processing is aborted and message will not be forwarded", 1);
324         @out_msg_l = ();
325     } elsif ($out_msg_l[0] eq 'noeventerror') {
326         &main::daemon_log("$session_id ERROR: client '$target' is not registered for event '$header', processing is aborted", 1); 
327         @out_msg_l = ();
328     }
330     return @out_msg_l;
334 sub process_job_msg {
335     my ($msg, $msg_hash, $session_id)= @_ ;    
336     my $out_msg;
337     my $error = 0;
339     my $header = @{$msg_hash->{'header'}}[0];
340     $header =~ s/job_//;
341         my $target = @{$msg_hash->{'target'}}[0];
342     
343     # if no timestamp is specified, use 19700101000000
344     my $timestamp = "19700101000000";
345     if( exists $msg_hash->{'timestamp'} ) {
346         $timestamp = @{$msg_hash->{'timestamp'}}[0];
347     }
349     #if no macaddress is specified, raise error 
350     my $macaddress;
351     if( exists $msg_hash->{'macaddress'} ) {
352         $macaddress = @{$msg_hash->{'macaddress'}}[0];
353     } elsif (@{$msg_hash->{'target'}}[0] =~ /^([0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2})$/i ) {
354         $macaddress = $1;
355     } else {
356         $error ++;
357         $out_msg = "<xml>".
358             "<header>answer</header>".
359             "<source>$server_address</source>".
360             "<target>GOSA</target>".
361             "<answer1>1</answer1>".
362             "<error_string>no mac address specified, neither in target-tag nor in macaddres-tag</error_string>".
363             "</xml>";
364     }
365     
366         # if mac address is already known in ldap, set plain_name to 'cn'
367     my $plain_name;
368         my $ldap_handle = &main::get_ldap_handle($session_id); 
369         if( not defined $ldap_handle ) {
370                 &main::daemon_log("$session_id ERROR: cannot connect to ldap", 1);
371                 $plain_name = "none"; 
372                 
373         # try to fetch a 'real name'            
374         } else {
375                 my $mesg = $ldap_handle->search(
376                                                 base => $main::ldap_base,
377                                                 scope => 'sub',
378                                                 attrs => ['cn'],
379                                                 filter => "(macAddress=$macaddress)");
380                 if($mesg->code) {
381                         &main::daemon_log($mesg->error, 1);
382                         $plain_name = "none";
383                 } else {
384                         my $entry= $mesg->entry(0);
385                         $plain_name = $entry->get_value("cn");
386                 }
387         }
389     if( $error == 0 ) {
390         # add job to job queue
391         my $func_dic = {table=>$main::job_queue_tn, 
392             primkey=>['macaddress', 'headertag'],
393             timestamp=>$timestamp,
394             status=>'waiting', 
395             result=>'none',
396             progress=>'none',
397             headertag=>$header, 
398             targettag=>$target,
399             xmlmessage=>$msg,
400             macaddress=>$macaddress,
401                         plainname=>$plain_name,
402         };
403         my $res = $main::job_db->add_dbentry($func_dic);
404         if (not $res == 0) {
405             &main::daemon_log("$session_id ERROR: GosaPackages: process_job_msg: $res", 1);
406         } else {
407             &main::daemon_log("$session_id INFO: GosaPackages: $header job successfully added to job queue", 5);
408         }
409         $out_msg = "<xml><header>answer</header><source>$server_address</source><target>GOSA</target><answer1>$res</answer1></xml>";
410     }
411     
412     my @out_msg_l = ( $out_msg );
413     return @out_msg_l;
416 # vim:ts=4:shiftwidth:expandtab
417 1;