Code

update: failed importing of event modules cause a programm crash now
[gosa.git] / gosa-si / modules / GosaSupportDaemon.pm
1 package GOSA::GosaSupportDaemon;
3 use Exporter;
4 @ISA = qw(Exporter);
5 my @functions = (
6     "create_passwd",
7     "create_xml_hash",
8     "get_content_from_xml_hash",
9     "add_content2xml_hash",
10     "create_xml_string",
11     "transform_msg2hash",
12     "get_time",
13     "build_msg",
14     "db_res2xml",
15     "db_res2si_msg",
16     "get_where_statement",
17     "get_select_statement",
18     "get_update_statement",
19     "get_limit_statement",
20     "get_orderby_statement",
21     "get_dns_domains",
22     "get_server_addresses",
23     "get_logged_in_users",
24     "import_events",
25     "del_doubles",
26     "get_ip",
27     "get_interface_for_ip",
28     "get_interfaces",
29     "is_local",
30     "run_as",
31     "inform_all_other_si_server",
32     "read_configfile",
33     ); 
34 @EXPORT = @functions;
35 use strict;
36 use warnings;
37 use IO::Socket::INET;
38 use Crypt::Rijndael;
39 use Digest::MD5  qw(md5 md5_hex md5_base64);
40 use MIME::Base64;
41 use XML::Simple;
42 use Data::Dumper;
43 use Net::DNS;
46 my $op_hash = {
47     'eq' => '=',
48     'ne' => '!=',
49     'ge' => '>=',
50     'gt' => '>',
51     'le' => '<=',
52     'lt' => '<',
53     'like' => ' LIKE ',
54 };
57 BEGIN {}
59 END {}
61 ### Start ######################################################################
63 my $xml = new XML::Simple();
65 sub daemon_log {
66     my ($msg, $level) = @_ ;
67     &main::daemon_log($msg, $level);
68     return;
69 }
72 sub create_passwd {
73     my $new_passwd = "";
74     for(my $i=0; $i<31; $i++) {
75         $new_passwd .= ("a".."z","A".."Z",0..9)[int(rand(62))]
76     }
78     return $new_passwd;
79 }
82 sub del_doubles { 
83     my %all; 
84     $all{$_}=0 for @_; 
85     return (keys %all); 
86 }
89 #===  FUNCTION  ================================================================
90 #         NAME:  create_xml_hash
91 #   PARAMETERS:  header - string - message header (required)
92 #                source - string - where the message come from (required)
93 #                target - string - where the message should go to (required)
94 #                [header_value] - string - something usefull (optional)
95 #      RETURNS:  hash - hash - nomen est omen
96 #  DESCRIPTION:  creates a key-value hash, all values are stored in a array
97 #===============================================================================
98 sub create_xml_hash {
99     my ($header, $source, $target, $header_value) = @_;
100     my $hash = {
101             header => [$header],
102             source => [$source],
103             target => [$target],
104             $header => [$header_value],
105     };
106     return $hash
110 #===  FUNCTION  ================================================================
111 #         NAME:  create_xml_string
112 #   PARAMETERS:  xml_hash - hash - hash from function create_xml_hash
113 #      RETURNS:  xml_string - string - xml string representation of the hash
114 #  DESCRIPTION:  transform the hash to a string using XML::Simple module
115 #===============================================================================
116 sub create_xml_string {
117     my ($xml_hash) = @_ ;
118     my $xml_string = $xml->XMLout($xml_hash, RootName => 'xml');
119     #$xml_string =~ s/[\n]+//g;
120     #daemon_log("create_xml_string:",7);
121     #daemon_log("$xml_string\n", 7);
122     return $xml_string;
126 sub transform_msg2hash {
127     my ($msg) = @_ ;
128     my $hash = $xml->XMLin($msg, ForceArray=>1);
129     
130     # xml tags without a content are created as an empty hash
131     # substitute it with an empty list
132     eval {
133         while( my ($xml_tag, $xml_content) = each %{ $hash } ) {
134             if( 1 == @{ $xml_content } ) {
135                 # there is only one element in xml_content list ...
136                 my $element = @{ $xml_content }[0];
137                 if( ref($element) eq "HASH" ) {
138                     # and this element is an hash ...
139                     my $len_element = keys %{ $element };
140                     if( $len_element == 0 ) {
141                         # and this hash is empty, then substitute the xml_content
142                         # with an empty string in list
143                         $hash->{$xml_tag} = [ "none" ];
144                     }
145                 }
146             }
147         }
148     };
149     if( $@ ) {  
150         $hash = undef;
151     }
153     return $hash;
157 #===  FUNCTION  ================================================================
158 #         NAME:  add_content2xml_hash
159 #   PARAMETERS:  xml_ref - ref - reference to a hash from function create_xml_hash
160 #                element - string - key for the hash
161 #                content - string - value for the hash
162 #      RETURNS:  nothing
163 #  DESCRIPTION:  add key-value pair to xml_ref, if key alread exists, 
164 #                then append value to list
165 #===============================================================================
166 sub add_content2xml_hash {
167     my ($xml_ref, $element, $content) = @_;
168     if(not exists $$xml_ref{$element} ) {
169         $$xml_ref{$element} = [];
170     }
171     my $tmp = $$xml_ref{$element};
172     push(@$tmp, $content);
173     return;
177 sub get_time {
178     my ($seconds, $minutes, $hours, $monthday, $month,
179             $year, $weekday, $yearday, $sommertime) = localtime(time);
180     $hours = $hours < 10 ? $hours = "0".$hours : $hours;
181     $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
182     $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
183     $month+=1;
184     $month = $month < 10 ? $month = "0".$month : $month;
185     $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
186     $year+=1900;
187     return "$year$month$monthday$hours$minutes$seconds";
192 #===  FUNCTION  ================================================================
193 #         NAME: build_msg
194 #  DESCRIPTION: Send a message to a destination
195 #   PARAMETERS: [header] Name of the header
196 #               [from]   sender ip
197 #               [to]     recipient ip
198 #               [data]   Hash containing additional attributes for the xml
199 #                        package
200 #      RETURNS:  nothing
201 #===============================================================================
202 sub build_msg ($$$$) {
203         my ($header, $from, $to, $data) = @_;
205     # data is of form, i.e.
206     # %data= ('ip' => $address, 'mac' => $mac);
208         my $out_hash = &create_xml_hash($header, $from, $to);
210         while ( my ($key, $value) = each(%$data) ) {
211                 if(ref($value) eq 'ARRAY'){
212                         map(&add_content2xml_hash($out_hash, $key, $_), @$value);
213                 } else {
214                         &add_content2xml_hash($out_hash, $key, $value);
215                 }
216         }
217     my $out_msg = &create_xml_string($out_hash);
218     return $out_msg;
222 sub db_res2xml {
223     my ($db_res) = @_ ;
224     my $xml = "";
226     my $len_db_res= keys %{$db_res};
227     for( my $i= 1; $i<= $len_db_res; $i++ ) {
228         $xml .= "\n<answer$i>";
229         my $hash= $db_res->{$i};
230         while ( my ($column_name, $column_value) = each %{$hash} ) {
231             $xml .= "<$column_name>";
232             my $xml_content;
233             if( $column_name eq "xmlmessage" ) {
234                 $xml_content = &encode_base64($column_value);
235             } else {
236                 $xml_content = $column_value;
237             }
238             $xml .= $xml_content;
239             $xml .= "</$column_name>"; 
240         }
241         $xml .= "</answer$i>";
243     }
245     return $xml;
249 sub db_res2si_msg {
250     my ($db_res, $header, $target, $source) = @_;
252     my $si_msg = "<xml>";
253     $si_msg .= "<header>$header</header>";
254     $si_msg .= "<source>$source</source>";
255     $si_msg .= "<target>$target</target>";
256     $si_msg .= &db_res2xml;
257     $si_msg .= "</xml>";
261 sub get_where_statement {
262     my ($msg, $msg_hash) = @_;
263     my $error= 0;
264     
265     my $clause_str= "";
266     if( (not exists $msg_hash->{'where'}) || (not exists @{$msg_hash->{'where'}}[0]->{'clause'}) ) { 
267         $error++; 
268     }
270     if( $error == 0 ) {
271         my @clause_l;
272         my @where = @{@{$msg_hash->{'where'}}[0]->{'clause'}};
273         foreach my $clause (@where) {
274             my $connector = $clause->{'connector'}[0];
275             if( not defined $connector ) { $connector = "AND"; }
276             $connector = uc($connector);
277             delete($clause->{'connector'});
279             my @phrase_l ;
280             foreach my $phrase (@{$clause->{'phrase'}}) {
281                 my $operator = "=";
282                 if( exists $phrase->{'operator'} ) {
283                     my $op = $op_hash->{$phrase->{'operator'}[0]};
284                     if( not defined $op ) {
285                         &main::daemon_log("ERROR: Can not translate operator '$operator' in where-".
286                                 "statement to sql valid syntax. Please use 'eq', ".
287                                 "'ne', 'ge', 'gt', 'le', 'lt' in xml message\n", 1);
288                         &main::daemon_log($msg, 8);
289                         $op = "=";
290                     }
291                     $operator = $op;
292                     delete($phrase->{'operator'});
293                 }
295                 my @xml_tags = keys %{$phrase};
296                 my $tag = $xml_tags[0];
297                 my $val = $phrase->{$tag}[0];
298                 if( ref($val) eq "HASH" ) { next; }  # empty xml-tags should not appear in where statement
300                                 # integer columns do not have to have single quotes besides the value
301                                 if ($tag eq "id") {
302                                                 push(@phrase_l, "$tag$operator$val");
303                                 } else {
304                                                 push(@phrase_l, "$tag$operator'$val'");
305                                 }
306             }
308             if (not 0 == @phrase_l) {
309                 my $clause_str .= join(" $connector ", @phrase_l);
310                 push(@clause_l, "($clause_str)");
311             }
312         }
314         if( not 0 == @clause_l ) {
315             $clause_str = join(" AND ", @clause_l);
316             $clause_str = "WHERE ($clause_str) ";
317         }
318     }
320     return $clause_str;
323 sub get_select_statement {
324     my ($msg, $msg_hash)= @_;
325     my $select = "*";
326     if( exists $msg_hash->{'select'} ) {
327         my $select_l = \@{$msg_hash->{'select'}};
328         $select = join(', ', @{$select_l});
329     }
330     return $select;
334 sub get_update_statement {
335     my ($msg, $msg_hash) = @_;
336     my $error= 0;
337     my $update_str= "";
338     my @update_l; 
340     if( not exists $msg_hash->{'update'} ) { $error++; };
342     if( $error == 0 ) {
343         my $update= @{$msg_hash->{'update'}}[0];
344         while( my ($tag, $val) = each %{$update} ) {
345             my $val= @{$update->{$tag}}[0];
346             push(@update_l, "$tag='$val'");
347         }
348         if( 0 == @update_l ) { $error++; };   
349     }
351     if( $error == 0 ) { 
352         $update_str= join(', ', @update_l);
353         $update_str= "SET $update_str ";
354     }
356     return $update_str;
359 sub get_limit_statement {
360     my ($msg, $msg_hash)= @_; 
361     my $error= 0;
362     my $limit_str = "";
363     my ($from, $to);
365     if( not exists $msg_hash->{'limit'} ) { $error++; };
367     if( $error == 0 ) {
368         eval {
369             my $limit= @{$msg_hash->{'limit'}}[0];
370             $from= @{$limit->{'from'}}[0];
371             $to= @{$limit->{'to'}}[0];
372         };
373         if( $@ ) {
374             $error++;
375         }
376     }
378     if( $error == 0 ) {
379         $limit_str= "LIMIT $from, $to";
380     }   
381     
382     return $limit_str;
385 sub get_orderby_statement {
386     my ($msg, $msg_hash)= @_;
387     my $error= 0;
388     my $order_str= "";
389     my $order;
390     
391     if( not exists $msg_hash->{'orderby'} ) { $error++; };
393     if( $error == 0) {
394         eval {
395             $order= @{$msg_hash->{'orderby'}}[0];
396         };
397         if( $@ ) {
398             $error++;
399         }
400     }
402     if( $error == 0 ) {
403         $order_str= "ORDER BY $order";   
404     }
405     
406     return $order_str;
409 sub get_dns_domains() {
410         my $line;
411         my @searches;
412         open(RESOLV, "</etc/resolv.conf") or return @searches;
413         while(<RESOLV>){
414                 $line= $_;
415                 chomp $line;
416                 $line =~ s/^\s+//;
417                 $line =~ s/\s+$//;
418                 $line =~ s/\s+/ /;
419                 if ($line =~ /^domain (.*)$/ ){
420                         push(@searches, $1);
421                 } elsif ($line =~ /^search (.*)$/ ){
422                         push(@searches, split(/ /, $1));
423                 }
424         }
425         close(RESOLV);
427         my %tmp = map { $_ => 1 } @searches;
428         @searches = sort keys %tmp;
430         return @searches;
434 sub get_server_addresses {
435     my $domain= shift;
436     my @result;
438     my $error = 0;
439     my $res   = Net::DNS::Resolver->new;
440     my $query = $res->send("_gosa-si._tcp.".$domain, "SRV");
441     my @hits;
443     if ($query) {
444         foreach my $rr ($query->answer) {
445             push(@hits, $rr->target.":".$rr->port);
446         }
447     }
448     else {
449         #warn "query failed: ", $res->errorstring, "\n";
450         $error++;
451     }
453     if( $error == 0 ) {
454         foreach my $hit (@hits) {
455             my ($hit_name, $hit_port) = split(/:/, $hit);
456             chomp($hit_name);
457             chomp($hit_port);
459             my $address_query = $res->send($hit_name);
460             if( 1 == length($address_query->answer) ) {
461                 foreach my $rr ($address_query->answer) {
462                     push(@result, $rr->address.":".$hit_port);
463                 }
464             }
465         }
466     }
468     return @result;
472 sub get_logged_in_users {
473     my $result = qx(/usr/bin/w -hs);
474     my @res_lines;
476     if( defined $result ) { 
477         chomp($result);
478         @res_lines = split("\n", $result);
479     }
481     my @logged_in_user_list;
482     foreach my $line (@res_lines) {
483         chomp($line);
484         my @line_parts = split(/\s+/, $line); 
485         push(@logged_in_user_list, $line_parts[0]);
486     }
488     return @logged_in_user_list;
493 sub import_events {
494     my ($event_dir) = @_;
495     my $event_hash;
496     my $error = 0;
497     my @result = ();
498     if (not -e $event_dir) {
499         $error++;
500         push(@result, "cannot find directory or directory is not readable: $event_dir");   
501     }
503     my $DIR;
504     if ($error == 0) {
505         opendir ($DIR, $event_dir) or do { 
506             $error++;
507             push(@result, "cannot open directory '$event_dir' for reading: $!\n");
508         }
509     }
511     if ($error == 0) {
512         while (defined (my $event = readdir ($DIR))) {
513             if( $event eq "." || $event eq ".." ) { next; }  
515             # try to import event module
516             eval{ require $event; };
517             if( $@ ) {
518                 $error++;
519                 #push(@result, "import of event module '$event' failed: $@");
520                 #next;
521                 
522                 &main::daemon_log("ERROR: Import of event module '$event' failed: $@",1);
523                 exit(1);
524             }
526             # fetch all single events
527             $event =~ /(\S*?).pm$/;
528             my $event_module = $1;
529             my $events_l = eval( $1."::get_events()") ;
530             foreach my $event_name (@{$events_l}) {
531                 $event_hash->{$event_name} = $event_module;
532             }
533             my $events_string = join( ", ", @{$events_l});
534             push(@result, "import of event module '$event' succeed: $events_string");
535         }
536         
537         close $DIR;
538     }
540     return ($error, \@result, $event_hash);
545 #===  FUNCTION  ================================================================
546 #         NAME:  get_ip 
547 #   PARAMETERS:  interface name (i.e. eth0)
548 #      RETURNS:  (ip address) 
549 #  DESCRIPTION:  Uses ioctl to get ip address directly from system.
550 #===============================================================================
551 sub get_ip {
552         my $ifreq= shift;
553         my $result= "";
554         my $SIOCGIFADDR= 0x8915;       # man 2 ioctl_list
555         my $proto= getprotobyname('ip');
557         socket SOCKET, PF_INET, SOCK_DGRAM, $proto
558                 or die "socket: $!";
560         if(ioctl SOCKET, $SIOCGIFADDR, $ifreq) {
561                 my ($if, $sin)    = unpack 'a16 a16', $ifreq;
562                 my ($port, $addr) = sockaddr_in $sin;
563                 my $ip            = inet_ntoa $addr;
565                 if ($ip && length($ip) > 0) {
566                         $result = $ip;
567                 }
568         }
570         return $result;
574 #===  FUNCTION  ================================================================
575 #         NAME:  get_interface_for_ip
576 #   PARAMETERS:  ip address (i.e. 192.168.0.1)
577 #      RETURNS:  array: list of interfaces if ip=0.0.0.0, matching interface if found, undef else
578 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
579 #===============================================================================
580 sub get_interface_for_ip {
581         my $result;
582         my $ip= shift;
583         if ($ip && length($ip) > 0) {
584                 my @ifs= &get_interfaces();
585                 if($ip eq "0.0.0.0") {
586                         $result = "all";
587                 } else {
588                         foreach (@ifs) {
589                                 my $if=$_;
590                                 if(&get_ip($if) eq $ip) {
591                                         $result = $if;
592                                 }
593                         }       
594                 }
595         }       
596         return $result;
599 #===  FUNCTION  ================================================================
600 #         NAME:  get_interfaces 
601 #   PARAMETERS:  none
602 #      RETURNS:  (list of interfaces) 
603 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
604 #===============================================================================
605 sub get_interfaces {
606         my @result;
607         my $PROC_NET_DEV= ('/proc/net/dev');
609         open(PROC_NET_DEV, "<$PROC_NET_DEV")
610                 or die "Could not open $PROC_NET_DEV";
612         my @ifs = <PROC_NET_DEV>;
614         close(PROC_NET_DEV);
616         # Eat first two line
617         shift @ifs;
618         shift @ifs;
620         chomp @ifs;
621         foreach my $line(@ifs) {
622                 my $if= (split /:/, $line)[0];
623                 $if =~ s/^\s+//;
624                 push @result, $if;
625         }
627         return @result;
631 #===  FUNCTION  ================================================================
632 #         NAME:  is_local
633 #   PARAMETERS:  Server Address
634 #      RETURNS:  true if Server Address is on this host, false otherwise
635 #  DESCRIPTION:  Checks all interface addresses, stops on first match
636 #===============================================================================
637 sub is_local {
638     my $server_address = shift || "";
639     my $result = 0;
641     my $server_ip = $1 if $server_address =~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):\d{1,6}$/;
643     if(defined($server_ip) && length($server_ip) > 0) {
644         foreach my $interface(&get_interfaces()) {
645             my $ip_address= &get_ip($interface);
646             if($ip_address eq $server_ip) {
647                 $result = 1;
648                 last;
649             }
650         }
651     }
653     return $result;
657 #===  FUNCTION  ================================================================
658 #         NAME:  run_as
659 #   PARAMETERS:  uid, command
660 #      RETURNS:  hash with keys 'resultCode' = resultCode of command and 
661 #                'output' = program output
662 #  DESCRIPTION:  Runs command as uid using the sudo utility.
663 #===============================================================================
664 sub run_as {
665         my ($uid, $command) = @_;
666         my $sudo_cmd = `which sudo`;
667         chomp($sudo_cmd);
668         if(! -x $sudo_cmd) {
669                 &main::daemon_log("ERROR: The sudo utility is not available! Please fix this!");
670         }
671         my $cmd_line= "$sudo_cmd su - $uid -c '$command'";
672         open(PIPE, "$cmd_line |");
673         my $result = {'resultCode' => $?};
674         $result->{'command'} = $cmd_line;
675         push @{$result->{'output'}}, <PIPE>;
676         return $result;
680 #===  FUNCTION  ================================================================
681 #         NAME:  inform_other_si_server
682 #   PARAMETERS:  message
683 #      RETURNS:  nothing
684 #  DESCRIPTION:  Sends message to all other SI-server found in known_server_db. 
685 #===============================================================================
686 sub inform_all_other_si_server {
687     my ($msg) = @_;
689     # determine all other si-server from known_server_db
690     my $sql_statement= "SELECT * FROM $main::known_server_tn";
691     my $res = $main::known_server_db->select_dbentry( $sql_statement ); 
693     while( my ($hit_num, $hit) = each %$res ) {    
694         my $act_target_address = $hit->{hostname};
695         my $act_target_key = $hit->{hostkey};
697         # determine the source address corresponding to the actual target address
698         my ($act_target_ip, $act_target_port) = split(/:/, $act_target_address);
699         my $act_source_address = &main::get_local_ip_for_remote_ip($act_target_ip).":$act_target_port";
701         # fill into message the correct target and source addresses
702         my $act_msg = $msg;
703         $act_msg =~ s/<target>\w*<\/target>/<target>$act_target_address<\/target>/g;
704         $act_msg =~ s/<source>\w*<\/source>/<source>$act_source_address<\/source>/g;
706         # send message to the target
707         &main::send_msg_to_target($act_msg, $act_target_address, $act_target_key, "foreign_job_updates" , "J");
708     }
710     return;
714 sub read_configfile {
715     my ($cfg_file, %cfg_defaults) = @_ ;
716     my $cfg;
717     if( defined( $cfg_file) && ( (-s $cfg_file) > 0 )) {
718         if( -r $cfg_file ) {
719             $cfg = Config::IniFiles->new( -file => $cfg_file );
720         } else {
721             print STDERR "Couldn't read config file!";
722         }
723     } else {
724         $cfg = Config::IniFiles->new() ;
725     }
726     foreach my $section (keys %cfg_defaults) {
727         foreach my $param (keys %{$cfg_defaults{ $section }}) {
728             my $pinfo = $cfg_defaults{ $section }{ $param };
729            ${@$pinfo[ 0 ]} = $cfg->val( $section, $param, @$pinfo[ 1 ] );
730         }
731     }
735 1;