Code

6872485d552acc43988a159fb0c43ccd2bcbb135
[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 XML::Simple;
11 use File::Spec;
12 use Data::Dumper;
13 use GOSA::DBsqlite;
14 use MIME::Base64;
16 BEGIN{}
17 END{}
19 my ($server_activ, $server_ip, $server_mac_address, $server_port, $server_passwd, $max_clients, $server_event_dir);
20 my ($bus_activ, $bus_passwd, $bus_ip, $bus_port);
21 my ($gosa_activ, $gosa_ip, $gosa_mac_address, $gosa_port, $gosa_passwd, $network_interface);
22 my ($job_queue_timeout, $job_queue_file_name);
24 my $gosa_server;
26 my %cfg_defaults = 
27 ("general" =>
28     {"job_queue_file_name" => [\$job_queue_file_name, '/var/lib/gosa-si/jobs.db'],
29     },
30 "server" =>
31     {"server_activ" => [\$server_activ, "on"],
32     "server_ip" => [\$server_ip, "0.0.0.0"],
33     "server_port" => [\$server_port, "20081"],
34     "server_passwd" => [\$server_passwd, ""],
35     "max_clients" => [\$max_clients, 100],
36     "server_event_dir" => [\$server_event_dir, '/usr/lib/gosa-si/server/events'],
37     },
38 "bus" =>
39     {"bus_activ" => [\$bus_activ, "on"],
40     "bus_passwd" => [\$bus_passwd, ""],
41     "bus_ip" => [\$bus_ip, "0.0.0.0"],
42     "bus_port" => [\$bus_port, "20080"],
43     },
44 "gosa" =>
45     {"gosa_activ" => [\$gosa_activ, "on"],
46     "gosa_ip" => [\$gosa_ip, "0.0.0.0"],
47     "gosa_port" => [\$gosa_port, "20082"],
48     "gosa_passwd" => [\$gosa_passwd, "none"],
49     },
50 );
51  
53 ## START ##########################
55 # read configfile and import variables
56 &read_configfile();
57 $network_interface= &get_interface_for_ip($server_ip);
58 $gosa_mac_address= &get_mac($network_interface);
60 # complete addresses
61 my $server_address = "$server_ip:$server_port";
62 my $bus_address = "$bus_ip:$bus_port";
63 my $gosa_address = "$gosa_ip:$gosa_port";
65 # create general settings for this module
66 my $gosa_cipher = &create_ciphering($gosa_passwd);
67 my $xml = new XML::Simple();
70 ## FUNCTIONS #################################################################
72 sub get_module_info {
73     my @info = ($gosa_address,
74                 $gosa_passwd,
75                 $gosa_server,
76                 $gosa_activ,
77                 "socket",
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) && ( length($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 #===  FUNCTION  ================================================================
109 #         NAME:  get_interface_for_ip
110 #   PARAMETERS:  ip address (i.e. 192.168.0.1)
111 #      RETURNS:  array: list of interfaces if ip=0.0.0.0, matching interface if found, undef else
112 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
113 #===============================================================================
114 sub get_interface_for_ip {
115         my $result;
116         my $ip= shift;
117         if ($ip && length($ip) > 0) {
118                 my @ifs= &get_interfaces();
119                 if($ip eq "0.0.0.0") {
120                         $result = "all";
121                 } else {
122                         foreach (@ifs) {
123                                 my $if=$_;
124                                 if(get_ip($if) eq $ip) {
125                                         $result = $if;
126                                 }
127                         }       
128                 }
129         }       
130         return $result;
133 #===  FUNCTION  ================================================================
134 #         NAME:  get_interfaces 
135 #   PARAMETERS:  none
136 #      RETURNS:  (list of interfaces) 
137 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
138 #===============================================================================
139 sub get_interfaces {
140         my @result;
141         my $PROC_NET_DEV= ('/proc/net/dev');
143         open(PROC_NET_DEV, "<$PROC_NET_DEV")
144                 or die "Could not open $PROC_NET_DEV";
146         my @ifs = <PROC_NET_DEV>;
148         close(PROC_NET_DEV);
150         # Eat first two line
151         shift @ifs;
152         shift @ifs;
154         chomp @ifs;
155         foreach my $line(@ifs) {
156                 my $if= (split /:/, $line)[0];
157                 $if =~ s/^\s+//;
158                 push @result, $if;
159         }
161         return @result;
164 #===  FUNCTION  ================================================================
165 #         NAME:  get_mac 
166 #   PARAMETERS:  interface name (i.e. eth0)
167 #      RETURNS:  (mac address) 
168 #  DESCRIPTION:  Uses ioctl to get mac address directly from system.
169 #===============================================================================
170 sub get_mac {
171         my $ifreq= shift;
172         my $result;
173         if ($ifreq && length($ifreq) > 0) { 
174                 if($ifreq eq "all") {
175                         $result = "00:00:00:00:00:00";
176                 } else {
177                         my $SIOCGIFHWADDR= 0x8927;     # man 2 ioctl_list
179                         # A configured MAC Address should always override a guessed value
180                         if ($gosa_mac_address and length($gosa_mac_address) > 0) {
181                                 $result= $gosa_mac_address;
182                         }
184                         socket SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('ip')
185                                 or die "socket: $!";
187                         if(ioctl SOCKET, $SIOCGIFHWADDR, $ifreq) {
188                                 my ($if, $mac)= unpack 'h36 H12', $ifreq;
190                                 if (length($mac) > 0) {
191                                         $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])$/;
192                                         $mac= sprintf("%s:%s:%s:%s:%s:%s", $1, $2, $3, $4, $5, $6);
193                                         $result = $mac;
194                                 }
195                         }
196                 }
197         }
198         return $result;
201 #===  FUNCTION  ================================================================
202 #         NAME:  get_ip 
203 #   PARAMETERS:  interface name (i.e. eth0)
204 #      RETURNS:  (ip address) 
205 #  DESCRIPTION:  Uses ioctl to get ip address directly from system.
206 #===============================================================================
207 sub get_ip {
208         my $ifreq= shift;
209         my $result= "";
210         my $SIOCGIFADDR= 0x8915;       # man 2 ioctl_list
211         my $proto= getprotobyname('ip');
213         socket SOCKET, PF_INET, SOCK_DGRAM, $proto
214                 or die "socket: $!";
216         if(ioctl SOCKET, $SIOCGIFADDR, $ifreq) {
217                 my ($if, $sin)    = unpack 'a16 a16', $ifreq;
218                 my ($port, $addr) = sockaddr_in $sin;
219                 my $ip            = inet_ntoa $addr;
221                 if ($ip && length($ip) > 0) {
222                         $result = $ip;
223                 }
224         }
226         return $result;
229 #===  FUNCTION  ================================================================
230 #         NAME:  open_socket
231 #   PARAMETERS:  PeerAddr string something like 192.168.1.1 or 192.168.1.1:10000
232 #                [PeerPort] string necessary if port not appended by PeerAddr
233 #      RETURNS:  socket IO::Socket::INET
234 #  DESCRIPTION:  open a socket to PeerAddr
235 #===============================================================================
236 sub open_socket {
237     my ($PeerAddr, $PeerPort) = @_ ;
238     if(defined($PeerPort)){
239         $PeerAddr = $PeerAddr.":".$PeerPort;
240     }
241     my $socket;
242     $socket = new IO::Socket::INET(PeerAddr => $PeerAddr ,
243             Porto => "tcp" ,
244             Type => SOCK_STREAM,
245             Timeout => 5,
246             );
247     if(not defined $socket) {
248         return;
249     }
250     &main::daemon_log("open_socket to: $PeerAddr", 7);
251     return $socket;
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 ($crypted_msg) = @_ ;
263         &main::daemon_log("Got message $crypted_msg", 8);
264         if( (not(defined($crypted_msg))) || (length($crypted_msg) <= 0)) {
265         &main::daemon_log("function 'process_incoming_msg': got no msg", 7);
266         return;
267     }
269     $crypted_msg =~ /^([\s\S]*?)\.(\d{1,3}?)\.(\d{1,3}?)\.(\d{1,3}?)\.(\d{1,3}?)$/;
270     $crypted_msg = $1;
271         my $host = sprintf("%s.%s.%s.%s", $2, $3, $4, $5);
272  
273     # collect addresses from possible incoming clients
274     # only gosa is allowd as incoming client
275     &main::daemon_log("GosaPackages: host_key: $host", 7);
276     &main::daemon_log("GosaPackages: key_passwd: $gosa_passwd", 7);
278     $gosa_cipher = &create_ciphering($gosa_passwd);
280     # determine the correct passwd for deciphering of the incoming msgs
281     my $msg = "";
282     my $msg_hash;
283     eval{
284         $msg = &decrypt_msg($crypted_msg, $gosa_cipher);
285         &main::daemon_log("GosaPackages: decrypted_msg: \n$msg", 8);
287         $msg_hash = $xml->XMLin($msg, ForceArray=>1);
288     };
289     if($@) {
290         &main::daemon_log("WARNING: GosaPackages do not understand the message:", 5);
291         &main::daemon_log("$@", 7);
292         return;
293     }
295     my $header = @{$msg_hash->{header}}[0];
296     
297     &main::daemon_log("GosaPackages: receive '$header' from $host", 1);
298     
299     my $out_msg;
300     if ($header =~ /^job_/) {
301         $out_msg = &process_job_msg($msg, $msg_hash);
302     } elsif ($header =~ /^gosa_/) {
303         $out_msg = &process_gosa_msg($msg, $header);
304     } else {
305         &main::daemon_log("ERROR: $header is not a valid GosaPackage-header, need a 'job_' or a 'gosa_' prefix");
306     }
307     
308     if (not defined $out_msg) {
309         return;
310     }
312     if ($out_msg =~ /<jobdb_id>(\d*?)<\/jobdb_id>/) {
313         my $job_id = $1;
314         my $sql = "UPDATE '".$main::job_queue_table_name.
315             "' SET status='done', result='".$out_msg.
316             "' WHERE id='$job_id'";
317         my $res = $main::job_db->exec_statement($sql);
318         return;
320     } else {
322         my $out_cipher = &create_ciphering($gosa_passwd);
323         $out_msg = &encrypt_msg($out_msg, $out_cipher);
324         return $out_msg;
325         }
329 sub process_gosa_msg {
330     my ($msg, $header) = @_ ;
331     my $out_msg;
332     $header =~ s/gosa_//;
334     # decide wether msg is a core function or a event handler
335     if ( $header eq 'query_jobdb') { $out_msg = &query_jobdb }
336     elsif ($header eq 'delete_jobdb_entry') { $out_msg = &delete_jobdb_entry }
337     elsif ($header eq 'clear_jobdb') { $out_msg = &clear_jobdb }
338     elsif ($header eq 'update_status_jobdb_entry' ) { $out_msg = &update_status_jobdb_entry }
339     elsif ($header eq 'update_timestamp_jobdb_entry' ) { $out_msg = &update_timestamp_jobdb_entry }
340     else {
341         # msg could not be assigned to core function
342         # fetch all available eventhandler under $server_event_dir
343         opendir (DIR, $server_event_dir) or &main::daemon_log("ERROR cannot open $server_event_dir: $!\n", 1) and return;
344         while (defined (my $file = readdir (DIR))) {
345             if (not $file eq $header) {
346                 next;
347             }
348             # try to deliver incoming msg to eventhandler
349             my $cmd = File::Spec->join($server_event_dir, $header)." '$msg'";
350             &main::daemon_log("GosaPackages: execute event_handler $header", 3);
351             &main::daemon_log("GosaPackages: cmd: $cmd", 7);
353             $out_msg = "";
354             open(PIPE, "$cmd 2>&1 |");
355             while(<PIPE>) {
356                 $out_msg.=$_;
357             }
358             close(PIPE);
359             &main::daemon_log("GosaPackages: answer of cmd: $out_msg", 5);
360             last;
361         }
362     }
364     # if delivery not possible raise error and return 
365     if (not defined $out_msg) {
366         &main::daemon_log("ERROR: GosaPackages: no event handler or core function defined for $header", 1);
367     } elsif ($out_msg eq "") {
368         &main::daemon_log("ERROR: GosaPackages got not answer from event_handler $header", 1);
369     }
370     return $out_msg;
371     
375 sub process_job_msg {
376     my ($msg, $msg_hash)= @_ ;    
378     my $header = @{$msg_hash->{header}}[0];
379     $header =~ s/job_//;
380     
381     # check wether mac address is already known in known_daemons or known_clients
382     my $target = 'none';
384     # add job to job queue
385     my $func_dic = {table=>$main::job_queue_table_name, 
386                     primkey=>'id',
387                     timestamp=>@{$msg_hash->{timestamp}}[0],
388                     status=>'waiting', 
389                     result=>'none',
390                     headertag=>$header, 
391                     targettag=>$target,
392                     xmlmessage=>$msg,
393                     macaddress=>@{$msg_hash->{mac}}[0],
394                     };
395     my $res = $main::job_db->add_dbentry($func_dic);
396     if (not $res == 0) {
397         &main::daemon_log("ERROR: GosaPackages: process_job_msg: $res", 1);
398     }
399     
400     &main::daemon_log("GosaPackages: $header job successfully added to job queue", 3);
401     return "<xml><1>$res</1></xml>";
406 sub db_res_2_xml {
407     my ($db_res) = @_ ;
409     my $xml = "<xml>";
411     while ( my ($hit, $hash) = each %{ $db_res } ) {
412         $xml .= "\n<answer$hit>";
414         while ( my ($column_name, $column_value) = each %{$hash} ) {
415             $xml .= "<$column_name>";
416             my $xml_content;
417             if( $column_name eq "xmlmessage" ) {
418                 $xml_content = &encode_base64($column_value);
419             } else {
420                 $xml_content = $column_value;
421             }
422             $xml .= $xml_content;
423             $xml .= "</$column_name>"; 
424         }
426         $xml .= "</answer$hit>";
427     }
429     $xml .= "</xml>";
430     return $xml;
434 ## CORE FUNCTIONS ############################################################
436 sub query_jobdb {
437     my ($msg) = @_;
438     my $msg_hash = &transform_msg2hash($msg);
440     # prepare query sql statement
441     my @where = @{$msg_hash->{where}};
442     my $where_hash = {table=>$main::job_queue_table_name };
443     foreach my $where_pram (@where) {
444         my $where_val = @{$msg_hash->{$where_pram}}[0];
445         if (defined $where_val) {
446             $where_hash->{$where_pram} = $where_val;
447         }
448     }
449  
450     # execute db query   
451     my $res_hash = $main::job_db->select_dbentry($where_hash);
453     my $out_xml = &db_res_2_xml($res_hash);
454     return $out_xml;
457 sub delete_jobdb_entry {
458     my ($msg) = @_ ;
459     my $msg_hash = &transform_msg2hash($msg);
460     
461     # prepare query sql statement
462     my @where = @{$msg_hash->{where}};
463     my $where_hash = {table=>$main::job_queue_table_name };
464     foreach my $where_pram (@where) {
465         my $where_val = @{$msg_hash->{$where_pram}}[0];
466         if (defined $where_val) {
467             $where_hash->{$where_pram} = $where_val;
468         }
469     }
470     
471     # execute db query
472     my $db_res = $main::job_db->del_dbentry($where_hash);
474     my $res;
475     if( $db_res > 0 ) { 
476         $res = 0 ;
477     } else {
478         $res = 1;
479     }
481     # prepare xml answer
482     my $out_xml = "<xml><answer1>$res</answer1></xml>";
483     return $out_xml;
487 sub clear_jobdb {
488     my ($msg) = @_ ;
489     my $msg_hash = &transform_msg2hash($msg);
490     
491     my $where_hash = {table=>$main::job_queue_table_name };
492     
493     # execute db query
494     my $db_res = $main::job_db->del_dbentry($where_hash);
495     print STDERR "db_res=$db_res\n";
496     my $res;
497     if( $db_res eq '0E0' ) { 
498         $res = 0 ;
499     } else {
500         $res = 1;
501     }
503     # prepare xml answer
504     my $out_xml = "<xml><answer1>$res</answer1></xml>";
505     return $out_xml;
508 sub update_status_jobdb_entry {
509     my ($msg) = @_ ;
510     my $msg_hash = &transform_msg2hash($msg);
511     
512     # prepare query sql statement
513     my $update_hash = {table=>$main::job_queue_table_name };
514     if( exists $msg_hash->{where} ) {
515         $update_hash->{where} = $msg_hash->{where};
516     } else {
517         $update_hash->{where} = [];
518     }
520     if( not exists $msg_hash->{update}[0]->{status} ) {
521         return "<xml><answer1>1</answer1></xml>";
522     }
523     $update_hash->{update} = [ { status=>$msg_hash->{update}[0]->{status} } ];
525     # execute db query
526     my $db_res = $main::job_db->update_dbentry($update_hash);
528     # transform db answer to error returnment
529     my $res;
530     if( $db_res > 0 ) { 
531         $res = 0 ;
532     } else {
533         $res = 1;
534     }
536     # prepare xml answer
537     my $out_xml = "<xml><answer1>$res</answer1></xml>";
538     return $out_xml;
541 sub update_timestamp_jobdb_entry {
542     my ($msg) = @_ ;
543     my $msg_hash = &transform_msg2hash($msg);
544     
545     # prepare query sql statement
546     my $update_hash = {table=>$main::job_queue_table_name };
547     if( exists $msg_hash->{where} ) {
548         $update_hash->{where} = $msg_hash->{where};
549     } else {
550         $update_hash->{where} = [];
551     }
553     if( not exists $msg_hash->{update}[0]->{timestamp} ) {
554         return "<xml><answer1>1</answer1></xml>";
555     }
557     $update_hash->{update} = [ { timestamp=>$msg_hash->{update}[0]->{timestamp} } ];
559     # execute db query
560     my $db_res = $main::job_db->update_dbentry($update_hash);
562     # transform db answer to error returnment
563     my $res;
564     if( $db_res > 0 ) { 
565         $res = 0 ;
566     } else {
567         $res = 1;
568     }
570     # prepare xml answer
571     my $out_xml = "<xml><answer1>$res</answer1></xml>";
572     return $out_xml;
577 1;