Code

sharing job queue information among all si-server
[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     ); 
33 @EXPORT = @functions;
34 use strict;
35 use warnings;
36 use IO::Socket::INET;
37 use Crypt::Rijndael;
38 use Digest::MD5  qw(md5 md5_hex md5_base64);
39 use MIME::Base64;
40 use XML::Simple;
41 use Data::Dumper;
42 use Net::DNS;
45 my $op_hash = {
46     'eq' => '=',
47     'ne' => '!=',
48     'ge' => '>=',
49     'gt' => '>',
50     'le' => '<=',
51     'lt' => '<',
52     'like' => ' LIKE ',
53 };
56 BEGIN {}
58 END {}
60 ### Start ######################################################################
62 my $xml = new XML::Simple();
64 sub daemon_log {
65     my ($msg, $level) = @_ ;
66     &main::daemon_log($msg, $level);
67     return;
68 }
71 sub create_passwd {
72     my $new_passwd = "";
73     for(my $i=0; $i<31; $i++) {
74         $new_passwd .= ("a".."z","A".."Z",0..9)[int(rand(62))]
75     }
77     return $new_passwd;
78 }
81 sub del_doubles { 
82     my %all; 
83     $all{$_}=0 for @_; 
84     return (keys %all); 
85 }
88 #===  FUNCTION  ================================================================
89 #         NAME:  create_xml_hash
90 #   PARAMETERS:  header - string - message header (required)
91 #                source - string - where the message come from (required)
92 #                target - string - where the message should go to (required)
93 #                [header_value] - string - something usefull (optional)
94 #      RETURNS:  hash - hash - nomen est omen
95 #  DESCRIPTION:  creates a key-value hash, all values are stored in a array
96 #===============================================================================
97 sub create_xml_hash {
98     my ($header, $source, $target, $header_value) = @_;
99     my $hash = {
100             header => [$header],
101             source => [$source],
102             target => [$target],
103             $header => [$header_value],
104     };
105     return $hash
109 #===  FUNCTION  ================================================================
110 #         NAME:  create_xml_string
111 #   PARAMETERS:  xml_hash - hash - hash from function create_xml_hash
112 #      RETURNS:  xml_string - string - xml string representation of the hash
113 #  DESCRIPTION:  transform the hash to a string using XML::Simple module
114 #===============================================================================
115 sub create_xml_string {
116     my ($xml_hash) = @_ ;
117     my $xml_string = $xml->XMLout($xml_hash, RootName => 'xml');
118     #$xml_string =~ s/[\n]+//g;
119     #daemon_log("create_xml_string:",7);
120     #daemon_log("$xml_string\n", 7);
121     return $xml_string;
125 sub transform_msg2hash {
126     my ($msg) = @_ ;
127     my $hash = $xml->XMLin($msg, ForceArray=>1);
128     
129     # xml tags without a content are created as an empty hash
130     # substitute it with an empty list
131     eval {
132         while( my ($xml_tag, $xml_content) = each %{ $hash } ) {
133             if( 1 == @{ $xml_content } ) {
134                 # there is only one element in xml_content list ...
135                 my $element = @{ $xml_content }[0];
136                 if( ref($element) eq "HASH" ) {
137                     # and this element is an hash ...
138                     my $len_element = keys %{ $element };
139                     if( $len_element == 0 ) {
140                         # and this hash is empty, then substitute the xml_content
141                         # with an empty string in list
142                         $hash->{$xml_tag} = [ "none" ];
143                     }
144                 }
145             }
146         }
147     };
148     if( $@ ) {  
149         $hash = undef;
150     }
152     return $hash;
156 #===  FUNCTION  ================================================================
157 #         NAME:  add_content2xml_hash
158 #   PARAMETERS:  xml_ref - ref - reference to a hash from function create_xml_hash
159 #                element - string - key for the hash
160 #                content - string - value for the hash
161 #      RETURNS:  nothing
162 #  DESCRIPTION:  add key-value pair to xml_ref, if key alread exists, 
163 #                then append value to list
164 #===============================================================================
165 sub add_content2xml_hash {
166     my ($xml_ref, $element, $content) = @_;
167     if(not exists $$xml_ref{$element} ) {
168         $$xml_ref{$element} = [];
169     }
170     my $tmp = $$xml_ref{$element};
171     push(@$tmp, $content);
172     return;
176 sub get_time {
177     my ($seconds, $minutes, $hours, $monthday, $month,
178             $year, $weekday, $yearday, $sommertime) = localtime(time);
179     $hours = $hours < 10 ? $hours = "0".$hours : $hours;
180     $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
181     $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
182     $month+=1;
183     $month = $month < 10 ? $month = "0".$month : $month;
184     $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
185     $year+=1900;
186     return "$year$month$monthday$hours$minutes$seconds";
191 #===  FUNCTION  ================================================================
192 #         NAME: build_msg
193 #  DESCRIPTION: Send a message to a destination
194 #   PARAMETERS: [header] Name of the header
195 #               [from]   sender ip
196 #               [to]     recipient ip
197 #               [data]   Hash containing additional attributes for the xml
198 #                        package
199 #      RETURNS:  nothing
200 #===============================================================================
201 sub build_msg ($$$$) {
202         my ($header, $from, $to, $data) = @_;
204     # data is of form, i.e.
205     # %data= ('ip' => $address, 'mac' => $mac);
207         my $out_hash = &create_xml_hash($header, $from, $to);
209         while ( my ($key, $value) = each(%$data) ) {
210                 if(ref($value) eq 'ARRAY'){
211                         map(&add_content2xml_hash($out_hash, $key, $_), @$value);
212                 } else {
213                         &add_content2xml_hash($out_hash, $key, $value);
214                 }
215         }
216     my $out_msg = &create_xml_string($out_hash);
217     return $out_msg;
221 sub db_res2xml {
222     my ($db_res) = @_ ;
223     my $xml = "";
225     my $len_db_res= keys %{$db_res};
226     for( my $i= 1; $i<= $len_db_res; $i++ ) {
227         $xml .= "\n<answer$i>";
228         my $hash= $db_res->{$i};
229         while ( my ($column_name, $column_value) = each %{$hash} ) {
230             $xml .= "<$column_name>";
231             my $xml_content;
232             if( $column_name eq "xmlmessage" ) {
233                 $xml_content = &encode_base64($column_value);
234             } else {
235                 $xml_content = $column_value;
236             }
237             $xml .= $xml_content;
238             $xml .= "</$column_name>"; 
239         }
240         $xml .= "</answer$i>";
242     }
244     return $xml;
248 sub db_res2si_msg {
249     my ($db_res, $header, $target, $source) = @_;
251     my $si_msg = "<xml>";
252     $si_msg .= "<header>$header</header>";
253     $si_msg .= "<source>$source</source>";
254     $si_msg .= "<target>$target</target>";
255     $si_msg .= &db_res2xml;
256     $si_msg .= "</xml>";
260 sub get_where_statement {
261     my ($msg, $msg_hash) = @_;
262     my $error= 0;
263     
264     my $clause_str= "";
265     if( (not exists $msg_hash->{'where'}) || (not exists @{$msg_hash->{'where'}}[0]->{'clause'}) ) { 
266         $error++; 
267     }
269     if( $error == 0 ) {
270         my @clause_l;
271         my @where = @{@{$msg_hash->{'where'}}[0]->{'clause'}};
272         foreach my $clause (@where) {
273             my $connector = $clause->{'connector'}[0];
274             if( not defined $connector ) { $connector = "AND"; }
275             $connector = uc($connector);
276             delete($clause->{'connector'});
278             my @phrase_l ;
279             foreach my $phrase (@{$clause->{'phrase'}}) {
280                 my $operator = "=";
281                 if( exists $phrase->{'operator'} ) {
282                     my $op = $op_hash->{$phrase->{'operator'}[0]};
283                     if( not defined $op ) {
284                         &main::daemon_log("ERROR: Can not translate operator '$operator' in where-".
285                                 "statement to sql valid syntax. Please use 'eq', ".
286                                 "'ne', 'ge', 'gt', 'le', 'lt' in xml message\n", 1);
287                         &main::daemon_log($msg, 8);
288                         $op = "=";
289                     }
290                     $operator = $op;
291                     delete($phrase->{'operator'});
292                 }
294                 my @xml_tags = keys %{$phrase};
295                 my $tag = $xml_tags[0];
296                 my $val = $phrase->{$tag}[0];
297                 if( ref($val) eq "HASH" ) { next; }  # empty xml-tags should not appear in where statement
299                                 # integer columns do not have to have single quotes besides the value
300                                 if ($tag eq "id") {
301                                                 push(@phrase_l, "$tag$operator$val");
302                                 } else {
303                                                 push(@phrase_l, "$tag$operator'$val'");
304                                 }
305             }
307             if (not 0 == @phrase_l) {
308                 my $clause_str .= join(" $connector ", @phrase_l);
309                 push(@clause_l, "($clause_str)");
310             }
311         }
313         if( not 0 == @clause_l ) {
314             $clause_str = join(" AND ", @clause_l);
315             $clause_str = "WHERE ($clause_str) ";
316         }
317     }
319     return $clause_str;
322 sub get_select_statement {
323     my ($msg, $msg_hash)= @_;
324     my $select = "*";
325     if( exists $msg_hash->{'select'} ) {
326         my $select_l = \@{$msg_hash->{'select'}};
327         $select = join(', ', @{$select_l});
328     }
329     return $select;
333 sub get_update_statement {
334     my ($msg, $msg_hash) = @_;
335     my $error= 0;
336     my $update_str= "";
337     my @update_l; 
339     if( not exists $msg_hash->{'update'} ) { $error++; };
341     if( $error == 0 ) {
342         my $update= @{$msg_hash->{'update'}}[0];
343         while( my ($tag, $val) = each %{$update} ) {
344             my $val= @{$update->{$tag}}[0];
345             push(@update_l, "$tag='$val'");
346         }
347         if( 0 == @update_l ) { $error++; };   
348     }
350     if( $error == 0 ) { 
351         $update_str= join(', ', @update_l);
352         $update_str= "SET $update_str ";
353     }
355     return $update_str;
358 sub get_limit_statement {
359     my ($msg, $msg_hash)= @_; 
360     my $error= 0;
361     my $limit_str = "";
362     my ($from, $to);
364     if( not exists $msg_hash->{'limit'} ) { $error++; };
366     if( $error == 0 ) {
367         eval {
368             my $limit= @{$msg_hash->{'limit'}}[0];
369             $from= @{$limit->{'from'}}[0];
370             $to= @{$limit->{'to'}}[0];
371         };
372         if( $@ ) {
373             $error++;
374         }
375     }
377     if( $error == 0 ) {
378         $limit_str= "LIMIT $from, $to";
379     }   
380     
381     return $limit_str;
384 sub get_orderby_statement {
385     my ($msg, $msg_hash)= @_;
386     my $error= 0;
387     my $order_str= "";
388     my $order;
389     
390     if( not exists $msg_hash->{'orderby'} ) { $error++; };
392     if( $error == 0) {
393         eval {
394             $order= @{$msg_hash->{'orderby'}}[0];
395         };
396         if( $@ ) {
397             $error++;
398         }
399     }
401     if( $error == 0 ) {
402         $order_str= "ORDER BY $order";   
403     }
404     
405     return $order_str;
408 sub get_dns_domains() {
409         my $line;
410         my @searches;
411         open(RESOLV, "</etc/resolv.conf") or return @searches;
412         while(<RESOLV>){
413                 $line= $_;
414                 chomp $line;
415                 $line =~ s/^\s+//;
416                 $line =~ s/\s+$//;
417                 $line =~ s/\s+/ /;
418                 if ($line =~ /^domain (.*)$/ ){
419                         push(@searches, $1);
420                 } elsif ($line =~ /^search (.*)$/ ){
421                         push(@searches, split(/ /, $1));
422                 }
423         }
424         close(RESOLV);
426         my %tmp = map { $_ => 1 } @searches;
427         @searches = sort keys %tmp;
429         return @searches;
433 #############################################
434 # moved from gosa-si-client: rettenbe, 16.05.2008
435 # outcommented at gosa-si-client
436 sub get_server_addresses {
437     my $domain= shift;
438     my @result;
440     my $error = 0;
441     my $res   = Net::DNS::Resolver->new;
442     my $query = $res->send("_gosa-si._tcp.".$domain, "SRV");
443     my @hits;
445     if ($query) {
446         foreach my $rr ($query->answer) {
447             push(@hits, $rr->target.":".$rr->port);
448         }
449     }
450     else {
451         #warn "query failed: ", $res->errorstring, "\n";
452         $error++;
453     }
455     if( $error == 0 ) {
456         foreach my $hit (@hits) {
457             my ($hit_name, $hit_port) = split(/:/, $hit);
458             chomp($hit_name);
459             chomp($hit_port);
461             my $address_query = $res->send($hit_name);
462             if( 1 == length($address_query->answer) ) {
463                 foreach my $rr ($address_query->answer) {
464                     push(@result, $rr->address.":".$hit_port);
465                 }
466             }
467         }
468     }
470     return @result;
474 sub get_logged_in_users {
475     my $result = qx(/usr/bin/w -hs);
476     my @res_lines;
478     if( defined $result ) { 
479         chomp($result);
480         @res_lines = split("\n", $result);
481     }
483     my @logged_in_user_list;
484     foreach my $line (@res_lines) {
485         chomp($line);
486         my @line_parts = split(/\s+/, $line); 
487         push(@logged_in_user_list, $line_parts[0]);
488     }
490     return @logged_in_user_list;
495 sub import_events {
496     my ($event_dir) = @_;
497     my $event_hash;
498     my $error = 0;
499     my @result = ();
500     if (not -e $event_dir) {
501         $error++;
502         push(@result, "cannot find directory or directory is not readable: $event_dir");   
503     }
505     my $DIR;
506     if ($error == 0) {
507         opendir ($DIR, $event_dir) or do { 
508             $error++;
509             push(@result, "cannot open directory '$event_dir' for reading: $!\n");
510         }
511     }
513     if ($error == 0) {
514         while (defined (my $event = readdir ($DIR))) {
515             if( $event eq "." || $event eq ".." ) { next; }  
517             # try to import event module
518             eval{ require $event; };
519             if( $@ ) {
520                 $error++;
521                 push(@result, "import of event module '$event' failed: $@");
522                 next;
523             }
525             # fetch all single events
526             $event =~ /(\S*?).pm$/;
527             my $event_module = $1;
528             my $events_l = eval( $1."::get_events()") ;
529             foreach my $event_name (@{$events_l}) {
530                 $event_hash->{$event_name} = $event_module;
531             }
532             my $events_string = join( ", ", @{$events_l});
533             push(@result, "import of event module '$event' succeed: $events_string");
534         }
535         
536         close $DIR;
537     }
539     return ($error, \@result, $event_hash);
544 #===  FUNCTION  ================================================================
545 #         NAME:  get_ip 
546 #   PARAMETERS:  interface name (i.e. eth0)
547 #      RETURNS:  (ip address) 
548 #  DESCRIPTION:  Uses ioctl to get ip address directly from system.
549 #===============================================================================
550 sub get_ip {
551         my $ifreq= shift;
552         my $result= "";
553         my $SIOCGIFADDR= 0x8915;       # man 2 ioctl_list
554         my $proto= getprotobyname('ip');
556         socket SOCKET, PF_INET, SOCK_DGRAM, $proto
557                 or die "socket: $!";
559         if(ioctl SOCKET, $SIOCGIFADDR, $ifreq) {
560                 my ($if, $sin)    = unpack 'a16 a16', $ifreq;
561                 my ($port, $addr) = sockaddr_in $sin;
562                 my $ip            = inet_ntoa $addr;
564                 if ($ip && length($ip) > 0) {
565                         $result = $ip;
566                 }
567         }
569         return $result;
573 #===  FUNCTION  ================================================================
574 #         NAME:  get_interface_for_ip
575 #   PARAMETERS:  ip address (i.e. 192.168.0.1)
576 #      RETURNS:  array: list of interfaces if ip=0.0.0.0, matching interface if found, undef else
577 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
578 #===============================================================================
579 sub get_interface_for_ip {
580         my $result;
581         my $ip= shift;
582         if ($ip && length($ip) > 0) {
583                 my @ifs= &get_interfaces();
584                 if($ip eq "0.0.0.0") {
585                         $result = "all";
586                 } else {
587                         foreach (@ifs) {
588                                 my $if=$_;
589                                 if(&get_ip($if) eq $ip) {
590                                         $result = $if;
591                                 }
592                         }       
593                 }
594         }       
595         return $result;
598 #===  FUNCTION  ================================================================
599 #         NAME:  get_interfaces 
600 #   PARAMETERS:  none
601 #      RETURNS:  (list of interfaces) 
602 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
603 #===============================================================================
604 sub get_interfaces {
605         my @result;
606         my $PROC_NET_DEV= ('/proc/net/dev');
608         open(PROC_NET_DEV, "<$PROC_NET_DEV")
609                 or die "Could not open $PROC_NET_DEV";
611         my @ifs = <PROC_NET_DEV>;
613         close(PROC_NET_DEV);
615         # Eat first two line
616         shift @ifs;
617         shift @ifs;
619         chomp @ifs;
620         foreach my $line(@ifs) {
621                 my $if= (split /:/, $line)[0];
622                 $if =~ s/^\s+//;
623                 push @result, $if;
624         }
626         return @result;
630 #===  FUNCTION  ================================================================
631 #         NAME:  is_local
632 #   PARAMETERS:  Server Address
633 #      RETURNS:  true if Server Address is on this host, false otherwise
634 #  DESCRIPTION:  Checks all interface addresses, stops on first match
635 #===============================================================================
636 sub is_local {
637     my $server_address = shift || "";
638     my $result = 0;
640     my $server_ip = $1 if $server_address =~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):\d{1,6}$/;
642     if(defined($server_ip) && length($server_ip) > 0) {
643         foreach my $interface(&get_interfaces()) {
644             my $ip_address= &get_ip($interface);
645             if($ip_address eq $server_ip) {
646                 $result = 1;
647                 last;
648             }
649         }
650     }
652     return $result;
656 #===  FUNCTION  ================================================================
657 #         NAME:  run_as
658 #   PARAMETERS:  uid, command
659 #      RETURNS:  hash with keys 'resultCode' = resultCode of command and 
660 #                'output' = program output
661 #  DESCRIPTION:  Runs command as uid using the sudo utility.
662 #===============================================================================
663 sub run_as {
664         my ($uid, $command) = @_;
665         my $sudo_cmd = `which sudo`;
666         chomp($sudo_cmd);
667         if(! -x $sudo_cmd) {
668                 &main::daemon_log("ERROR: The sudo utility is not available! Please fix this!");
669         }
670         my $cmd_line= "$sudo_cmd su - $uid -c '$command'";
671         open(PIPE, "$cmd_line |");
672         my $result = {'resultCode' => $?};
673         $result->{'command'} = $cmd_line;
674         push @{$result->{'output'}}, <PIPE>;
675         return $result;
679 #===  FUNCTION  ================================================================
680 #         NAME:  inform_other_si_server
681 #   PARAMETERS:  message
682 #      RETURNS:  nothing
683 #  DESCRIPTION:  Sends message to all other SI-server found in known_server_db. 
684 #===============================================================================
685 sub inform_all_other_si_server {
686     my ($msg) = @_;
688     # determine all other si-server from known_server_db
689     my $sql_statement= "SELECT * FROM $main::known_server_tn";
690     my $res = $main::known_server_db->select_dbentry( $sql_statement ); 
692     while( my ($hit_num, $hit) = each %$res ) {    
693         my $act_target_address = $hit->{hostname};
694         my $act_target_key = $hit->{hostkey};
696         # determine the source address corresponding to the actual target address
697         my ($act_target_ip, $act_target_port) = split(/:/, $act_target_address);
698         my $act_source_address = &main::get_local_ip_for_remote_ip($act_target_ip).":$act_target_port";
700         # fill into message the correct target and source addresses
701         my $act_msg = $msg;
702         $act_msg =~ s/<target>\w*<\/target>/<target>$act_target_address<\/target>/g;
703         $act_msg =~ s/<source>\w*<\/source>/<source>$act_source_address<\/source>/g;
705         # send message to the target
706         &main::send_msg_to_target($act_msg, $act_target_address, $act_target_key, "foreign_job_updates" , "J");
707     }
709     return;
712 1;