Code

Fixes.
[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;
16 use utf8;
18 my $event_dir = "/usr/lib/gosa-si/server/events";
19 use lib "/usr/lib/gosa-si/server/events";
21 BEGIN{}
22 END{}
24 my ($server_ip, $server_mac_address, $server_port, $server_passwd, $max_clients);
25 my ($gosa_ip, $gosa_mac_address, $gosa_port, $gosa_passwd, $network_interface);
26 my ($job_queue_timeout, $job_queue_file_name);
28 my $gosa_server;
29 my $event_hash;
31 my %cfg_defaults = (
32 "server" => {
33     "ip" => [\$server_ip, "0.0.0.0"],
34     "port" => [\$server_port, "20081"],
35     "key" => [\$server_passwd, ""],
36     "max-clients" => [\$max_clients, 100],
37     },
38 "GOsaPackages" => {
39     "ip" => [\$gosa_ip, "0.0.0.0"],
40     "port" => [\$gosa_port, "20082"],
41     "key" => [\$gosa_passwd, "none"],
42     "job-queue" => [\$job_queue_file_name, '/var/lib/gosa-si/jobs.db'],
43     },
44 );
45  
47 ## START ##########################
49 # read configfile and import variables
50 &read_configfile();
51 $network_interface= &get_interface_for_ip($server_ip);
52 $gosa_mac_address= &get_mac($network_interface);
54 # complete addresses
55 if( inet_aton($server_ip) ){ $server_ip = inet_ntoa(inet_aton($server_ip)); } 
56 our $server_address = "$server_ip:$server_port";
57 if( inet_aton($gosa_ip) ){ $gosa_ip = inet_ntoa(inet_aton($gosa_ip)); }
58 my $gosa_address = "$gosa_ip:$gosa_port";
60 # create general settings for this module
61 #y $gosa_cipher = &create_ciphering($gosa_passwd);
62 my $xml = new XML::Simple();
65 # import events
66 &import_events();
68 ## FUNCTIONS #################################################################
70 sub get_module_info {
71     my @info = ($gosa_address,
72                 $gosa_passwd,
73                 );
74     return \@info;
75 }
78 #===  FUNCTION  ================================================================
79 #         NAME:  read_configfile
80 #   PARAMETERS:  cfg_file - string -
81 #      RETURNS:  nothing
82 #  DESCRIPTION:  read cfg_file and set variables
83 #===============================================================================
84 sub read_configfile {
85     my $cfg;
86     if( defined( $main::cfg_file) && ( length($main::cfg_file) > 0 )) {
87         if( -r $main::cfg_file ) {
88             $cfg = Config::IniFiles->new( -file => $main::cfg_file );
89         } else {
90             print STDERR "Couldn't read config file!";
91         }
92     } else {
93         $cfg = Config::IniFiles->new() ;
94     }
95     foreach my $section (keys %cfg_defaults) {
96         foreach my $param (keys %{$cfg_defaults{ $section }}) {
97             my $pinfo = $cfg_defaults{ $section }{ $param };
98             ${@$pinfo[0]} = $cfg->val( $section, $param, @$pinfo[1] );
99         }
100     }
103 #===  FUNCTION  ================================================================
104 #         NAME:  get_interface_for_ip
105 #   PARAMETERS:  ip address (i.e. 192.168.0.1)
106 #      RETURNS:  array: list of interfaces if ip=0.0.0.0, matching interface if found, undef else
107 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
108 #===============================================================================
109 sub get_interface_for_ip {
110         my $result;
111         my $ip= shift;
112         if ($ip && length($ip) > 0) {
113                 my @ifs= &get_interfaces();
114                 if($ip eq "0.0.0.0") {
115                         $result = "all";
116                 } else {
117                         foreach (@ifs) {
118                                 my $if=$_;
119                                 if(get_ip($if) eq $ip) {
120                                         $result = $if;
121                                 }
122                         }       
123                 }
124         }       
125         return $result;
128 #===  FUNCTION  ================================================================
129 #         NAME:  get_interfaces 
130 #   PARAMETERS:  none
131 #      RETURNS:  (list of interfaces) 
132 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
133 #===============================================================================
134 sub get_interfaces {
135         my @result;
136         my $PROC_NET_DEV= ('/proc/net/dev');
138         open(PROC_NET_DEV, "<$PROC_NET_DEV")
139                 or die "Could not open $PROC_NET_DEV";
141         my @ifs = <PROC_NET_DEV>;
143         close(PROC_NET_DEV);
145         # Eat first two line
146         shift @ifs;
147         shift @ifs;
149         chomp @ifs;
150         foreach my $line(@ifs) {
151                 my $if= (split /:/, $line)[0];
152                 $if =~ s/^\s+//;
153                 push @result, $if;
154         }
156         return @result;
159 #===  FUNCTION  ================================================================
160 #         NAME:  get_mac 
161 #   PARAMETERS:  interface name (i.e. eth0)
162 #      RETURNS:  (mac address) 
163 #  DESCRIPTION:  Uses ioctl to get mac address directly from system.
164 #===============================================================================
165 sub get_mac {
166         my $ifreq= shift;
167         my $result;
168         if ($ifreq && length($ifreq) > 0) { 
169                 if($ifreq eq "all") {
170                         $result = "00:00:00:00:00:00";
171                 } else {
172                         my $SIOCGIFHWADDR= 0x8927;     # man 2 ioctl_list
174                         # A configured MAC Address should always override a guessed value
175                         if ($gosa_mac_address and length($gosa_mac_address) > 0) {
176                                 $result= $gosa_mac_address;
177                         }
179                         socket SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('ip')
180                                 or die "socket: $!";
182                         if(ioctl SOCKET, $SIOCGIFHWADDR, $ifreq) {
183                                 my ($if, $mac)= unpack 'h36 H12', $ifreq;
185                                 if (length($mac) > 0) {
186                                         $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])$/;
187                                         $mac= sprintf("%s:%s:%s:%s:%s:%s", $1, $2, $3, $4, $5, $6);
188                                         $result = $mac;
189                                 }
190                         }
191                 }
192         }
193         return $result;
196 #===  FUNCTION  ================================================================
197 #         NAME:  get_ip 
198 #   PARAMETERS:  interface name (i.e. eth0)
199 #      RETURNS:  (ip address) 
200 #  DESCRIPTION:  Uses ioctl to get ip address directly from system.
201 #===============================================================================
202 sub get_ip {
203         my $ifreq= shift;
204         my $result= "";
205         my $SIOCGIFADDR= 0x8915;       # man 2 ioctl_list
206         my $proto= getprotobyname('ip');
208         socket SOCKET, PF_INET, SOCK_DGRAM, $proto
209                 or die "socket: $!";
211         if(ioctl SOCKET, $SIOCGIFADDR, $ifreq) {
212                 my ($if, $sin)    = unpack 'a16 a16', $ifreq;
213                 my ($port, $addr) = sockaddr_in $sin;
214                 my $ip            = inet_ntoa $addr;
216                 if ($ip && length($ip) > 0) {
217                         $result = $ip;
218                 }
219         }
221         return $result;
225 sub import_events {
226     if (not -e $event_dir) {
227         &main::daemon_log("ERROR: cannot find directory or directory is not readable: $event_dir", 1);   
228     }
229     opendir (DIR, $event_dir) or die "ERROR while loading gosa-si-events from directory $event_dir : $!\n";
231     while (defined (my $event = readdir (DIR))) {
232         if( $event eq "." || $event eq ".." ) { next; }   
233         if( $event eq "siTriggered.pm" ) { next; }      # SI specific events not needed in GosaPackages.pm
234         if( $event eq "clMessages.pm" ) { next; }                    # SI specific events not needed in GosaPackages.pm
236         eval{ require $event; };
237         if( $@ ) {
238             &main::daemon_log("ERROR: import of event module '$event' failed", 1);
239             &main::daemon_log("$@", 1);
240             next;
241         }
243         $event =~ /(\S*?).pm$/;
244         my $event_module = $1;
245         my $events_l = eval( $1."::get_events()") ;
246         foreach my $event_name (@{$events_l}) {
247             $event_hash->{$event_name} = $event_module;
248         }
249         my $events_string = join( ", ", @{$events_l});
250         &main::daemon_log("INFO: GosaPackages imported events $events_string", 5);
251     }
255 #===  FUNCTION  ================================================================
256 #         NAME:  process_incoming_msg
257 #   PARAMETERS:  crypted_msg - string - incoming crypted message
258 #      RETURNS:  nothing
259 #  DESCRIPTION:  handels the proceeded distribution to the appropriated functions
260 #===============================================================================
261 sub process_incoming_msg {
262     my ($msg, $msg_hash, $session_id) = @_ ;
263     my $header = @{$msg_hash->{header}}[0];
264     my @msg_l;
265     my @out_msg_l;
267     &main::daemon_log("DEBUG: GosaPackages: msg to process '$header'", 7);
268     
269     if ($header =~ /^job_/) {
270         @msg_l = &process_job_msg($msg, $msg_hash, $session_id);
271     } 
272     elsif ($header =~ /^gosa_/) {
273         @msg_l = &process_gosa_msg($msg, $msg_hash, $session_id);
274     } 
275     else {
276         &main::daemon_log("ERROR: $header is not a valid GosaPackage-header, need a 'job_' or a 'gosa_' prefix", 1);
277     }
279     foreach my $out_msg ( @msg_l ) {
281         # keep job queue up-to-date and save result and status
282         if (defined ($out_msg) && $out_msg =~ /<jobdb_id>(\d+)<\/jobdb_id>/) {
283             my $job_id = $1;
284             my $sql = "UPDATE '".$main::job_queue_tn."'".
285                 " SET status='processing'".
286                 " WHERE id='$job_id'";
287             my $res = $main::job_db->exec_statement($sql);
288         } 
290         # substitute in all outgoing msg <source>GOSA</source> of <source>$server_address</source>
291         $out_msg =~ s/<source>GOSA<\/source>/<source>$server_address<\/source>/g;
293         if (defined $out_msg){
294             push(@out_msg_l, $out_msg);
295         }
297     }
299     return \@out_msg_l;
303 sub process_gosa_msg {
304     my ($msg, $msg_hash, $session_id) = @_ ;
305     my $out_msg;
306     my @out_msg_l = ('nohandler');
307     
308     my $header = @{$msg_hash->{'header'}}[0];
309     $header =~ s/gosa_//;
311     if( exists $event_hash->{$header} ) {
312         # a event exists with the header as name
313         &main::daemon_log("INFO: found event '$header' at event-module '".$event_hash->{$header}."'", 5);
314         no strict 'refs';
315         @out_msg_l = &{$event_hash->{$header}."::$header"}($msg, $msg_hash, $session_id);
316     }
318     # if incoming 'gosa_'-msg is scheduled from job_queue, than it contains xml-tag 'jobdb_id'
319     # after procesing this msg, set status of this job in job_queue to done
320     if ($msg =~ /<jobdb_id>(\d+)<\/jobdb_id>/) {
321         my $sql_statement = "UPDATE $main::job_queue_tn ".
322             "SET status='done' ".
323             "WHERE id='$1'";
324         &main::daemon_log("DEBUG: $sql_statement", 7);         
325         my $res = $main::job_db->update_dbentry($sql_statement);
326         &main::daemon_log("INFO: set job '$1' to status processed", 5); 
327     }
329     # if delivery not possible raise error and return 
330     if( not defined $out_msg_l[0] ) {
331         &main::daemon_log("WARNING: GosaPackages got no answer from event handler '$header'", 3);
332         @out_msg_l = ();
333     } elsif( $out_msg_l[0] eq 'nohandler') {
334         &main::daemon_log("ERROR: GosaPackages: no event handler or core function defined for '$header'", 1);
335         @out_msg_l = ();
336     } 
338     return @out_msg_l;
342 sub process_job_msg {
343     my ($msg, $msg_hash, $session_id)= @_ ;    
344     my $out_msg;
345     my $error = 0;
347     my $header = @{$msg_hash->{'header'}}[0];
348     $header =~ s/job_//;
349     
350     # if no timestamp is specified, use 19700101000000
351     my $timestamp = "19700101000000";
352     if( exists $msg_hash->{'timestamp'} ) {
353         $timestamp = @{$msg_hash->{'timestamp'}}[0];
354     }
356     #if no macaddress is specified, raise error 
357     my $macaddress;
358     if( exists $msg_hash->{'macaddress'} ) {
359         $macaddress = @{$msg_hash->{'macaddress'}}[0];
360     } 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 ) {
361         $macaddress = $1;
362     } else {
363         $error ++;
364         $out_msg = "<xml>".
365             "<header>answer</header>".
366             "<source>$server_address</source>".
367             "<target>GOSA</target>".
368             "<answer1>1</answer1>".
369             "<error_string>no mac address specified, neither in target-tag nor in macaddres-tag</error_string>".
370             "</xml>";
371     }
372     
373     # check wether mac address is already known in known_daemons or known_clients
374     my $target = 'none';
376     if( $error == 0 ) {
377         # add job to job queue
378         my $func_dic = {table=>$main::job_queue_tn, 
379             primkey=>['id'],
380             timestamp=>$timestamp,
381             status=>'waiting', 
382             result=>'none',
383             progress=>'none',
384             headertag=>$header, 
385             targettag=>$target,
386             xmlmessage=>$msg,
387             macaddress=>$macaddress,
388         };
390         my $res = $main::job_db->add_dbentry($func_dic);
391         if (not $res == 0) {
392             &main::daemon_log("ERROR: GosaPackages: process_job_msg: $res", 1);
393         } else {
394             &main::daemon_log("INFO: GosaPackages: $header job successfully added to job queue", 5);
395         }
396         $out_msg = "<xml><header>answer</header><source>$server_address</source><target>GOSA</target><answer1>$res</answer1></xml>";
397     }
398     
399     my @out_msg_l = ( $out_msg );
400     return @out_msg_l;
403 1;