Code

ae94225520dbe79d3449fec53d9d05e68e85c6b2
[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 sub get_server_addresses {
434     my $domain= shift;
435     my @result;
437     my $error = 0;
438     my $res   = Net::DNS::Resolver->new;
439     my $query = $res->send("_gosa-si._tcp.".$domain, "SRV");
440     my @hits;
442     if ($query) {
443         foreach my $rr ($query->answer) {
444             push(@hits, $rr->target.":".$rr->port);
445         }
446     }
447     else {
448         #warn "query failed: ", $res->errorstring, "\n";
449         $error++;
450     }
452     if( $error == 0 ) {
453         foreach my $hit (@hits) {
454             my ($hit_name, $hit_port) = split(/:/, $hit);
455             chomp($hit_name);
456             chomp($hit_port);
458             my $address_query = $res->send($hit_name);
459             if( 1 == length($address_query->answer) ) {
460                 foreach my $rr ($address_query->answer) {
461                     push(@result, $rr->address.":".$hit_port);
462                 }
463             }
464         }
465     }
467     return @result;
471 sub get_logged_in_users {
472     my $result = qx(/usr/bin/w -hs);
473     my @res_lines;
475     if( defined $result ) { 
476         chomp($result);
477         @res_lines = split("\n", $result);
478     }
480     my @logged_in_user_list;
481     foreach my $line (@res_lines) {
482         chomp($line);
483         my @line_parts = split(/\s+/, $line); 
484         push(@logged_in_user_list, $line_parts[0]);
485     }
487     return @logged_in_user_list;
492 sub import_events {
493     my ($event_dir) = @_;
494     my $event_hash;
495     my $error = 0;
496     my @result = ();
497     if (not -e $event_dir) {
498         $error++;
499         push(@result, "cannot find directory or directory is not readable: $event_dir");   
500     }
502     my $DIR;
503     if ($error == 0) {
504         opendir ($DIR, $event_dir) or do { 
505             $error++;
506             push(@result, "cannot open directory '$event_dir' for reading: $!\n");
507         }
508     }
510     if ($error == 0) {
511         while (defined (my $event = readdir ($DIR))) {
512             if( $event eq "." || $event eq ".." ) { next; }  
514             # try to import event module
515             eval{ require $event; };
516             if( $@ ) {
517                 $error++;
518                 push(@result, "import of event module '$event' failed: $@");
519                 next;
520             }
522             # fetch all single events
523             $event =~ /(\S*?).pm$/;
524             my $event_module = $1;
525             my $events_l = eval( $1."::get_events()") ;
526             foreach my $event_name (@{$events_l}) {
527                 $event_hash->{$event_name} = $event_module;
528             }
529             my $events_string = join( ", ", @{$events_l});
530             push(@result, "import of event module '$event' succeed: $events_string");
531         }
532         
533         close $DIR;
534     }
536     return ($error, \@result, $event_hash);
541 #===  FUNCTION  ================================================================
542 #         NAME:  get_ip 
543 #   PARAMETERS:  interface name (i.e. eth0)
544 #      RETURNS:  (ip address) 
545 #  DESCRIPTION:  Uses ioctl to get ip address directly from system.
546 #===============================================================================
547 sub get_ip {
548         my $ifreq= shift;
549         my $result= "";
550         my $SIOCGIFADDR= 0x8915;       # man 2 ioctl_list
551         my $proto= getprotobyname('ip');
553         socket SOCKET, PF_INET, SOCK_DGRAM, $proto
554                 or die "socket: $!";
556         if(ioctl SOCKET, $SIOCGIFADDR, $ifreq) {
557                 my ($if, $sin)    = unpack 'a16 a16', $ifreq;
558                 my ($port, $addr) = sockaddr_in $sin;
559                 my $ip            = inet_ntoa $addr;
561                 if ($ip && length($ip) > 0) {
562                         $result = $ip;
563                 }
564         }
566         return $result;
570 #===  FUNCTION  ================================================================
571 #         NAME:  get_interface_for_ip
572 #   PARAMETERS:  ip address (i.e. 192.168.0.1)
573 #      RETURNS:  array: list of interfaces if ip=0.0.0.0, matching interface if found, undef else
574 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
575 #===============================================================================
576 sub get_interface_for_ip {
577         my $result;
578         my $ip= shift;
579         if ($ip && length($ip) > 0) {
580                 my @ifs= &get_interfaces();
581                 if($ip eq "0.0.0.0") {
582                         $result = "all";
583                 } else {
584                         foreach (@ifs) {
585                                 my $if=$_;
586                                 if(&get_ip($if) eq $ip) {
587                                         $result = $if;
588                                 }
589                         }       
590                 }
591         }       
592         return $result;
595 #===  FUNCTION  ================================================================
596 #         NAME:  get_interfaces 
597 #   PARAMETERS:  none
598 #      RETURNS:  (list of interfaces) 
599 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
600 #===============================================================================
601 sub get_interfaces {
602         my @result;
603         my $PROC_NET_DEV= ('/proc/net/dev');
605         open(PROC_NET_DEV, "<$PROC_NET_DEV")
606                 or die "Could not open $PROC_NET_DEV";
608         my @ifs = <PROC_NET_DEV>;
610         close(PROC_NET_DEV);
612         # Eat first two line
613         shift @ifs;
614         shift @ifs;
616         chomp @ifs;
617         foreach my $line(@ifs) {
618                 my $if= (split /:/, $line)[0];
619                 $if =~ s/^\s+//;
620                 push @result, $if;
621         }
623         return @result;
627 #===  FUNCTION  ================================================================
628 #         NAME:  is_local
629 #   PARAMETERS:  Server Address
630 #      RETURNS:  true if Server Address is on this host, false otherwise
631 #  DESCRIPTION:  Checks all interface addresses, stops on first match
632 #===============================================================================
633 sub is_local {
634     my $server_address = shift || "";
635     my $result = 0;
637     my $server_ip = $1 if $server_address =~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):\d{1,6}$/;
639     if(defined($server_ip) && length($server_ip) > 0) {
640         foreach my $interface(&get_interfaces()) {
641             my $ip_address= &get_ip($interface);
642             if($ip_address eq $server_ip) {
643                 $result = 1;
644                 last;
645             }
646         }
647     }
649     return $result;
653 #===  FUNCTION  ================================================================
654 #         NAME:  run_as
655 #   PARAMETERS:  uid, command
656 #      RETURNS:  hash with keys 'resultCode' = resultCode of command and 
657 #                'output' = program output
658 #  DESCRIPTION:  Runs command as uid using the sudo utility.
659 #===============================================================================
660 sub run_as {
661         my ($uid, $command) = @_;
662         my $sudo_cmd = `which sudo`;
663         chomp($sudo_cmd);
664         if(! -x $sudo_cmd) {
665                 &main::daemon_log("ERROR: The sudo utility is not available! Please fix this!");
666         }
667         my $cmd_line= "$sudo_cmd su - $uid -c '$command'";
668         open(PIPE, "$cmd_line |");
669         my $result = {'resultCode' => $?};
670         $result->{'command'} = $cmd_line;
671         push @{$result->{'output'}}, <PIPE>;
672         return $result;
676 #===  FUNCTION  ================================================================
677 #         NAME:  inform_other_si_server
678 #   PARAMETERS:  message
679 #      RETURNS:  nothing
680 #  DESCRIPTION:  Sends message to all other SI-server found in known_server_db. 
681 #===============================================================================
682 sub inform_all_other_si_server {
683     my ($msg) = @_;
685     # determine all other si-server from known_server_db
686     my $sql_statement= "SELECT * FROM $main::known_server_tn";
687     my $res = $main::known_server_db->select_dbentry( $sql_statement ); 
689     while( my ($hit_num, $hit) = each %$res ) {    
690         my $act_target_address = $hit->{hostname};
691         my $act_target_key = $hit->{hostkey};
693         # determine the source address corresponding to the actual target address
694         my ($act_target_ip, $act_target_port) = split(/:/, $act_target_address);
695         my $act_source_address = &main::get_local_ip_for_remote_ip($act_target_ip).":$act_target_port";
697         # fill into message the correct target and source addresses
698         my $act_msg = $msg;
699         $act_msg =~ s/<target>\w*<\/target>/<target>$act_target_address<\/target>/g;
700         $act_msg =~ s/<source>\w*<\/source>/<source>$act_source_address<\/source>/g;
702         # send message to the target
703         &main::send_msg_to_target($act_msg, $act_target_address, $act_target_key, "foreign_job_updates" , "J");
704     }
706     return;
709 1;