Code

9d07d0a0cea6bcfba2b805d5ef8f806dfd04c116
[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     "check_opsi_res",
34     ); 
35 @EXPORT = @functions;
36 use strict;
37 use warnings;
38 use IO::Socket::INET;
39 use Crypt::Rijndael;
40 use Digest::MD5  qw(md5 md5_hex md5_base64);
41 use MIME::Base64;
42 use XML::Simple;
43 use Data::Dumper;
44 use Net::DNS;
47 my $op_hash = {
48     'eq' => '=',
49     'ne' => '!=',
50     'ge' => '>=',
51     'gt' => '>',
52     'le' => '<=',
53     'lt' => '<',
54     'like' => ' LIKE ',
55 };
58 BEGIN {}
60 END {}
62 ### Start ######################################################################
64 my $xml = new XML::Simple();
66 sub daemon_log {
67     my ($msg, $level) = @_ ;
68     &main::daemon_log($msg, $level);
69     return;
70 }
73 sub create_passwd {
74     my $new_passwd = "";
75     for(my $i=0; $i<31; $i++) {
76         $new_passwd .= ("a".."z","A".."Z",0..9)[int(rand(62))]
77     }
79     return $new_passwd;
80 }
83 sub del_doubles { 
84     my %all; 
85     $all{$_}=0 for @_; 
86     return (keys %all); 
87 }
90 #===  FUNCTION  ================================================================
91 #         NAME:  create_xml_hash
92 #   PARAMETERS:  header - string - message header (required)
93 #                source - string - where the message come from (required)
94 #                target - string - where the message should go to (required)
95 #                [header_value] - string - something usefull (optional)
96 #      RETURNS:  hash - hash - nomen est omen
97 #  DESCRIPTION:  creates a key-value hash, all values are stored in a array
98 #===============================================================================
99 sub create_xml_hash {
100     my ($header, $source, $target, $header_value) = @_;
101     my $hash = {
102             header => [$header],
103             source => [$source],
104             target => [$target],
105             $header => [$header_value],
106     };
107     return $hash
111 #===  FUNCTION  ================================================================
112 #         NAME:  create_xml_string
113 #   PARAMETERS:  xml_hash - hash - hash from function create_xml_hash
114 #      RETURNS:  xml_string - string - xml string representation of the hash
115 #  DESCRIPTION:  transform the hash to a string using XML::Simple module
116 #===============================================================================
117 sub create_xml_string {
118     my ($xml_hash) = @_ ;
119     my $xml_string = $xml->XMLout($xml_hash, RootName => 'xml');
120     #$xml_string =~ s/[\n]+//g;
121     #daemon_log("create_xml_string:",7);
122     #daemon_log("$xml_string\n", 7);
123     return $xml_string;
127 sub transform_msg2hash {
128     my ($msg) = @_ ;
129     my $hash = $xml->XMLin($msg, ForceArray=>1);
130     
131     # xml tags without a content are created as an empty hash
132     # substitute it with an empty list
133     eval {
134         while( my ($xml_tag, $xml_content) = each %{ $hash } ) {
135             if( 1 == @{ $xml_content } ) {
136                 # there is only one element in xml_content list ...
137                 my $element = @{ $xml_content }[0];
138                 if( ref($element) eq "HASH" ) {
139                     # and this element is an hash ...
140                     my $len_element = keys %{ $element };
141                     if( $len_element == 0 ) {
142                         # and this hash is empty, then substitute the xml_content
143                         # with an empty string in list
144                         $hash->{$xml_tag} = [ "none" ];
145                     }
146                 }
147             }
148         }
149     };
150     if( $@ ) {  
151         $hash = undef;
152     }
154     return $hash;
158 #===  FUNCTION  ================================================================
159 #         NAME:  add_content2xml_hash
160 #   PARAMETERS:  xml_ref - ref - reference to a hash from function create_xml_hash
161 #                element - string - key for the hash
162 #                content - string - value for the hash
163 #      RETURNS:  nothing
164 #  DESCRIPTION:  add key-value pair to xml_ref, if key alread exists, 
165 #                then append value to list
166 #===============================================================================
167 sub add_content2xml_hash {
168     my ($xml_ref, $element, $content) = @_;
169     if(not exists $$xml_ref{$element} ) {
170         $$xml_ref{$element} = [];
171     }
172     my $tmp = $$xml_ref{$element};
173     push(@$tmp, $content);
174     return;
178 sub get_time {
179     my ($seconds, $minutes, $hours, $monthday, $month,
180             $year, $weekday, $yearday, $sommertime) = localtime(time);
181     $hours = $hours < 10 ? $hours = "0".$hours : $hours;
182     $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
183     $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
184     $month+=1;
185     $month = $month < 10 ? $month = "0".$month : $month;
186     $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
187     $year+=1900;
188     return "$year$month$monthday$hours$minutes$seconds";
193 #===  FUNCTION  ================================================================
194 #         NAME: build_msg
195 #  DESCRIPTION: Send a message to a destination
196 #   PARAMETERS: [header] Name of the header
197 #               [from]   sender ip
198 #               [to]     recipient ip
199 #               [data]   Hash containing additional attributes for the xml
200 #                        package
201 #      RETURNS:  nothing
202 #===============================================================================
203 sub build_msg ($$$$) {
204         my ($header, $from, $to, $data) = @_;
206     # data is of form, i.e.
207     # %data= ('ip' => $address, 'mac' => $mac);
209         my $out_hash = &create_xml_hash($header, $from, $to);
211         while ( my ($key, $value) = each(%$data) ) {
212                 if(ref($value) eq 'ARRAY'){
213                         map(&add_content2xml_hash($out_hash, $key, $_), @$value);
214                 } else {
215                         &add_content2xml_hash($out_hash, $key, $value);
216                 }
217         }
218     my $out_msg = &create_xml_string($out_hash);
219     return $out_msg;
223 sub db_res2xml {
224     my ($db_res) = @_ ;
225     my $xml = "";
227     my $len_db_res= keys %{$db_res};
228     for( my $i= 1; $i<= $len_db_res; $i++ ) {
229         $xml .= "\n<answer$i>";
230         my $hash= $db_res->{$i};
231         while ( my ($column_name, $column_value) = each %{$hash} ) {
232             $xml .= "<$column_name>";
233             my $xml_content;
234             if( $column_name eq "xmlmessage" ) {
235                 $xml_content = &encode_base64($column_value);
236             } else {
237                 $xml_content = $column_value;
238             }
239             $xml .= $xml_content;
240             $xml .= "</$column_name>"; 
241         }
242         $xml .= "</answer$i>";
244     }
246     return $xml;
250 sub db_res2si_msg {
251     my ($db_res, $header, $target, $source) = @_;
253     my $si_msg = "<xml>";
254     $si_msg .= "<header>$header</header>";
255     $si_msg .= "<source>$source</source>";
256     $si_msg .= "<target>$target</target>";
257     $si_msg .= &db_res2xml;
258     $si_msg .= "</xml>";
262 sub get_where_statement {
263     my ($msg, $msg_hash) = @_;
264     my $error= 0;
265     
266     my $clause_str= "";
267     if( (not exists $msg_hash->{'where'}) || (not exists @{$msg_hash->{'where'}}[0]->{'clause'}) ) { 
268         $error++; 
269     }
271     if( $error == 0 ) {
272         my @clause_l;
273         my @where = @{@{$msg_hash->{'where'}}[0]->{'clause'}};
274         foreach my $clause (@where) {
275             my $connector = $clause->{'connector'}[0];
276             if( not defined $connector ) { $connector = "AND"; }
277             $connector = uc($connector);
278             delete($clause->{'connector'});
280             my @phrase_l ;
281             foreach my $phrase (@{$clause->{'phrase'}}) {
282                 my $operator = "=";
283                 if( exists $phrase->{'operator'} ) {
284                     my $op = $op_hash->{$phrase->{'operator'}[0]};
285                     if( not defined $op ) {
286                         &main::daemon_log("ERROR: Can not translate operator '$operator' in where-".
287                                 "statement to sql valid syntax. Please use 'eq', ".
288                                 "'ne', 'ge', 'gt', 'le', 'lt' in xml message\n", 1);
289                         &main::daemon_log($msg, 8);
290                         $op = "=";
291                     }
292                     $operator = $op;
293                     delete($phrase->{'operator'});
294                 }
296                 my @xml_tags = keys %{$phrase};
297                 my $tag = $xml_tags[0];
298                 my $val = $phrase->{$tag}[0];
299                 if( ref($val) eq "HASH" ) { next; }  # empty xml-tags should not appear in where statement
301                                 # integer columns do not have to have single quotes besides the value
302                                 if ($tag eq "id") {
303                                                 push(@phrase_l, "$tag$operator$val");
304                                 } else {
305                                                 push(@phrase_l, "$tag$operator'$val'");
306                                 }
307             }
309             if (not 0 == @phrase_l) {
310                 my $clause_str .= join(" $connector ", @phrase_l);
311                 push(@clause_l, "($clause_str)");
312             }
313         }
315         if( not 0 == @clause_l ) {
316             $clause_str = join(" AND ", @clause_l);
317             $clause_str = "WHERE ($clause_str) ";
318         }
319     }
321     return $clause_str;
324 sub get_select_statement {
325     my ($msg, $msg_hash)= @_;
326     my $select = "*";
327     if( exists $msg_hash->{'select'} ) {
328         my $select_l = \@{$msg_hash->{'select'}};
329         $select = join(', ', @{$select_l});
330     }
331     return $select;
335 sub get_update_statement {
336     my ($msg, $msg_hash) = @_;
337     my $error= 0;
338     my $update_str= "";
339     my @update_l; 
341     if( not exists $msg_hash->{'update'} ) { $error++; };
343     if( $error == 0 ) {
344         my $update= @{$msg_hash->{'update'}}[0];
345         while( my ($tag, $val) = each %{$update} ) {
346             my $val= @{$update->{$tag}}[0];
347             push(@update_l, "$tag='$val'");
348         }
349         if( 0 == @update_l ) { $error++; };   
350     }
352     if( $error == 0 ) { 
353         $update_str= join(', ', @update_l);
354         $update_str= "SET $update_str ";
355     }
357     return $update_str;
360 sub get_limit_statement {
361     my ($msg, $msg_hash)= @_; 
362     my $error= 0;
363     my $limit_str = "";
364     my ($from, $to);
366     if( not exists $msg_hash->{'limit'} ) { $error++; };
368     if( $error == 0 ) {
369         eval {
370             my $limit= @{$msg_hash->{'limit'}}[0];
371             $from= @{$limit->{'from'}}[0];
372             $to= @{$limit->{'to'}}[0];
373         };
374         if( $@ ) {
375             $error++;
376         }
377     }
379     if( $error == 0 ) {
380         $limit_str= "LIMIT $from, $to";
381     }   
382     
383     return $limit_str;
386 sub get_orderby_statement {
387     my ($msg, $msg_hash)= @_;
388     my $error= 0;
389     my $order_str= "";
390     my $order;
391     
392     if( not exists $msg_hash->{'orderby'} ) { $error++; };
394     if( $error == 0) {
395         eval {
396             $order= @{$msg_hash->{'orderby'}}[0];
397         };
398         if( $@ ) {
399             $error++;
400         }
401     }
403     if( $error == 0 ) {
404         $order_str= "ORDER BY $order";   
405     }
406     
407     return $order_str;
410 sub get_dns_domains() {
411         my $line;
412         my @searches;
413         open(RESOLV, "</etc/resolv.conf") or return @searches;
414         while(<RESOLV>){
415                 $line= $_;
416                 chomp $line;
417                 $line =~ s/^\s+//;
418                 $line =~ s/\s+$//;
419                 $line =~ s/\s+/ /;
420                 if ($line =~ /^domain (.*)$/ ){
421                         push(@searches, $1);
422                 } elsif ($line =~ /^search (.*)$/ ){
423                         push(@searches, split(/ /, $1));
424                 }
425         }
426         close(RESOLV);
428         my %tmp = map { $_ => 1 } @searches;
429         @searches = sort keys %tmp;
431         return @searches;
435 sub get_server_addresses {
436     my $domain= shift;
437     my @result;
438     my $error_string;
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         $error_string = "determination of '_gosa-si._tcp' server in domain '$domain' failed: ".$res->errorstring;
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, $error_string;
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                 
524                 &main::daemon_log("ERROR: Import of event module '$event' failed: $@",1);
525                 exit(1);
526             }
528             # fetch all single events
529             $event =~ /(\S*?).pm$/;
530             my $event_module = $1;
531             my $events_l = eval( $1."::get_events()") ;
532             foreach my $event_name (@{$events_l}) {
533                 $event_hash->{$event_name} = $event_module;
534             }
535             my $events_string = join( ", ", @{$events_l});
536             push(@result, "import of event module '$event' succeed: $events_string");
537         }
538         
539         close $DIR;
540     }
542     return ($error, \@result, $event_hash);
547 #===  FUNCTION  ================================================================
548 #         NAME:  get_ip 
549 #   PARAMETERS:  interface name (i.e. eth0)
550 #      RETURNS:  (ip address) 
551 #  DESCRIPTION:  Uses ioctl to get ip address directly from system.
552 #===============================================================================
553 sub get_ip {
554         my $ifreq= shift;
555         my $result= "";
556         my $SIOCGIFADDR= 0x8915;       # man 2 ioctl_list
557         my $proto= getprotobyname('ip');
559         socket SOCKET, PF_INET, SOCK_DGRAM, $proto
560                 or die "socket: $!";
562         if(ioctl SOCKET, $SIOCGIFADDR, $ifreq) {
563                 my ($if, $sin)    = unpack 'a16 a16', $ifreq;
564                 my ($port, $addr) = sockaddr_in $sin;
565                 my $ip            = inet_ntoa $addr;
567                 if ($ip && length($ip) > 0) {
568                         $result = $ip;
569                 }
570         }
572         return $result;
576 #===  FUNCTION  ================================================================
577 #         NAME:  get_interface_for_ip
578 #   PARAMETERS:  ip address (i.e. 192.168.0.1)
579 #      RETURNS:  array: list of interfaces if ip=0.0.0.0, matching interface if found, undef else
580 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
581 #===============================================================================
582 sub get_interface_for_ip {
583         my $result;
584         my $ip= shift;
585         if ($ip && length($ip) > 0) {
586                 my @ifs= &get_interfaces();
587                 if($ip eq "0.0.0.0") {
588                         $result = "all";
589                 } else {
590                         foreach (@ifs) {
591                                 my $if=$_;
592                                 if(&get_ip($if) eq $ip) {
593                                         $result = $if;
594                                 }
595                         }       
596                 }
597         }       
598         return $result;
601 #===  FUNCTION  ================================================================
602 #         NAME:  get_interfaces 
603 #   PARAMETERS:  none
604 #      RETURNS:  (list of interfaces) 
605 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
606 #===============================================================================
607 sub get_interfaces {
608         my @result;
609         my $PROC_NET_DEV= ('/proc/net/dev');
611         open(PROC_NET_DEV, "<$PROC_NET_DEV")
612                 or die "Could not open $PROC_NET_DEV";
614         my @ifs = <PROC_NET_DEV>;
616         close(PROC_NET_DEV);
618         # Eat first two line
619         shift @ifs;
620         shift @ifs;
622         chomp @ifs;
623         foreach my $line(@ifs) {
624                 my $if= (split /:/, $line)[0];
625                 $if =~ s/^\s+//;
626                 push @result, $if;
627         }
629         return @result;
633 #===  FUNCTION  ================================================================
634 #         NAME:  is_local
635 #   PARAMETERS:  Server Address
636 #      RETURNS:  true if Server Address is on this host, false otherwise
637 #  DESCRIPTION:  Checks all interface addresses, stops on first match
638 #===============================================================================
639 sub is_local {
640     my $server_address = shift || "";
641     my $result = 0;
643     my $server_ip = $1 if $server_address =~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):\d{1,6}$/;
645     if(defined($server_ip) && length($server_ip) > 0) {
646         foreach my $interface(&get_interfaces()) {
647             my $ip_address= &get_ip($interface);
648             if($ip_address eq $server_ip) {
649                 $result = 1;
650                 last;
651             }
652         }
653     }
655     return $result;
659 #===  FUNCTION  ================================================================
660 #         NAME:  run_as
661 #   PARAMETERS:  uid, command
662 #      RETURNS:  hash with keys 'resultCode' = resultCode of command and 
663 #                'output' = program output
664 #  DESCRIPTION:  Runs command as uid using the sudo utility.
665 #===============================================================================
666 sub run_as {
667         my ($uid, $command) = @_;
668         my $sudo_cmd = `which sudo`;
669         chomp($sudo_cmd);
670         if(! -x $sudo_cmd) {
671                 &main::daemon_log("ERROR: The sudo utility is not available! Please fix this!");
672         }
673         my $cmd_line= "$sudo_cmd su - $uid -c '$command'";
674         open(PIPE, "$cmd_line |");
675         my $result = {'resultCode' => $?};
676         $result->{'command'} = $cmd_line;
677         push @{$result->{'output'}}, <PIPE>;
678         return $result;
682 #===  FUNCTION  ================================================================
683 #         NAME:  inform_other_si_server
684 #   PARAMETERS:  message
685 #      RETURNS:  nothing
686 #  DESCRIPTION:  Sends message to all other SI-server found in known_server_db. 
687 #===============================================================================
688 sub inform_all_other_si_server {
689     my ($msg) = @_;
691     # determine all other si-server from known_server_db
692     my $sql_statement= "SELECT * FROM $main::known_server_tn";
693     my $res = $main::known_server_db->select_dbentry( $sql_statement ); 
695     while( my ($hit_num, $hit) = each %$res ) {    
696         my $act_target_address = $hit->{hostname};
697         my $act_target_key = $hit->{hostkey};
699         # determine the source address corresponding to the actual target address
700         my ($act_target_ip, $act_target_port) = split(/:/, $act_target_address);
701         my $act_source_address = &main::get_local_ip_for_remote_ip($act_target_ip).":$act_target_port";
703         # fill into message the correct target and source addresses
704         my $act_msg = $msg;
705         $act_msg =~ s/<target>\w*<\/target>/<target>$act_target_address<\/target>/g;
706         $act_msg =~ s/<source>\w*<\/source>/<source>$act_source_address<\/source>/g;
708         # send message to the target
709         &main::send_msg_to_target($act_msg, $act_target_address, $act_target_key, "foreign_job_updates" , "J");
710     }
712     return;
716 sub read_configfile {
717     my ($cfg_file, %cfg_defaults) = @_ ;
718     my $cfg;
719     if( defined( $cfg_file) && ( (-s $cfg_file) > 0 )) {
720         if( -r $cfg_file ) {
721             $cfg = Config::IniFiles->new( -file => $cfg_file );
722         } else {
723             print STDERR "Couldn't read config file!";
724         }
725     } else {
726         $cfg = Config::IniFiles->new() ;
727     }
728     foreach my $section (keys %cfg_defaults) {
729         foreach my $param (keys %{$cfg_defaults{ $section }}) {
730             my $pinfo = $cfg_defaults{ $section }{ $param };
731            ${@$pinfo[ 0 ]} = $cfg->val( $section, $param, @$pinfo[ 1 ] );
732         }
733     }
737 sub check_opsi_res {
738     my $res= shift;
740     if($res) {
741         if ($res->is_error) {
742             my $error_string;
743             if (ref $res->error_message eq "HASH") { 
744                 $error_string = $res->error_message->{'message'}; 
745             } else { 
746                 $error_string = $res->error_message; 
747             }
748             return 1, $error_string;
749         }
750     } else {
751         return 1, $main::opsi_client->status_line;
752     }
753     return 0;
757 1;