Code

* gosa-si-server-nobus
[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     ); 
27 @EXPORT = @functions;
28 use strict;
29 use warnings;
30 use IO::Socket::INET;
31 use Crypt::Rijndael;
32 use Digest::MD5  qw(md5 md5_hex md5_base64);
33 use MIME::Base64;
34 use XML::Simple;
35 use Data::Dumper;
36 use Net::DNS;
39 my $op_hash = {
40     'eq' => '=',
41     'ne' => '!=',
42     'ge' => '>=',
43     'gt' => '>',
44     'le' => '<=',
45     'lt' => '<',
46     'like' => ' LIKE ',
47 };
50 BEGIN {}
52 END {}
54 ### Start ######################################################################
56 my $xml = new XML::Simple();
58 sub daemon_log {
59     my ($msg, $level) = @_ ;
60     &main::daemon_log($msg, $level);
61     return;
62 }
65 sub create_passwd {
66     my $new_passwd = "";
67     for(my $i=0; $i<31; $i++) {
68         $new_passwd .= ("a".."z","A".."Z",0..9)[int(rand(62))]
69     }
71     return $new_passwd;
72 }
75 sub del_doubles { 
76     my %all; 
77     $all{$_}=0 for @_; 
78     return (keys %all); 
79 }
82 #===  FUNCTION  ================================================================
83 #         NAME:  create_xml_hash
84 #   PARAMETERS:  header - string - message header (required)
85 #                source - string - where the message come from (required)
86 #                target - string - where the message should go to (required)
87 #                [header_value] - string - something usefull (optional)
88 #      RETURNS:  hash - hash - nomen est omen
89 #  DESCRIPTION:  creates a key-value hash, all values are stored in a array
90 #===============================================================================
91 sub create_xml_hash {
92     my ($header, $source, $target, $header_value) = @_;
93     my $hash = {
94             header => [$header],
95             source => [$source],
96             target => [$target],
97             $header => [$header_value],
98     };
99     return $hash
103 #===  FUNCTION  ================================================================
104 #         NAME:  create_xml_string
105 #   PARAMETERS:  xml_hash - hash - hash from function create_xml_hash
106 #      RETURNS:  xml_string - string - xml string representation of the hash
107 #  DESCRIPTION:  transform the hash to a string using XML::Simple module
108 #===============================================================================
109 sub create_xml_string {
110     my ($xml_hash) = @_ ;
111     my $xml_string = $xml->XMLout($xml_hash, RootName => 'xml');
112     #$xml_string =~ s/[\n]+//g;
113     #daemon_log("create_xml_string:",7);
114     #daemon_log("$xml_string\n", 7);
115     return $xml_string;
119 sub transform_msg2hash {
120     my ($msg) = @_ ;
121     my $hash = $xml->XMLin($msg, ForceArray=>1);
122     
123     # xml tags without a content are created as an empty hash
124     # substitute it with an empty list
125     eval {
126         while( my ($xml_tag, $xml_content) = each %{ $hash } ) {
127             if( 1 == @{ $xml_content } ) {
128                 # there is only one element in xml_content list ...
129                 my $element = @{ $xml_content }[0];
130                 if( ref($element) eq "HASH" ) {
131                     # and this element is an hash ...
132                     my $len_element = keys %{ $element };
133                     if( $len_element == 0 ) {
134                         # and this hash is empty, then substitute the xml_content
135                         # with an empty string in list
136                         $hash->{$xml_tag} = [ "none" ];
137                     }
138                 }
139             }
140         }
141     };
142     if( $@ ) {  
143         $hash = undef;
144     }
146     return $hash;
150 #===  FUNCTION  ================================================================
151 #         NAME:  add_content2xml_hash
152 #   PARAMETERS:  xml_ref - ref - reference to a hash from function create_xml_hash
153 #                element - string - key for the hash
154 #                content - string - value for the hash
155 #      RETURNS:  nothing
156 #  DESCRIPTION:  add key-value pair to xml_ref, if key alread exists, 
157 #                then append value to list
158 #===============================================================================
159 sub add_content2xml_hash {
160     my ($xml_ref, $element, $content) = @_;
161     if(not exists $$xml_ref{$element} ) {
162         $$xml_ref{$element} = [];
163     }
164     my $tmp = $$xml_ref{$element};
165     push(@$tmp, $content);
166     return;
170 sub get_time {
171     my ($seconds, $minutes, $hours, $monthday, $month,
172             $year, $weekday, $yearday, $sommertime) = localtime(time);
173     $hours = $hours < 10 ? $hours = "0".$hours : $hours;
174     $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
175     $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
176     $month+=1;
177     $month = $month < 10 ? $month = "0".$month : $month;
178     $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
179     $year+=1900;
180     return "$year$month$monthday$hours$minutes$seconds";
185 #===  FUNCTION  ================================================================
186 #         NAME: build_msg
187 #  DESCRIPTION: Send a message to a destination
188 #   PARAMETERS: [header] Name of the header
189 #               [from]   sender ip
190 #               [to]     recipient ip
191 #               [data]   Hash containing additional attributes for the xml
192 #                        package
193 #      RETURNS:  nothing
194 #===============================================================================
195 sub build_msg ($$$$) {
196         my ($header, $from, $to, $data) = @_;
198     # data is of form, i.e.
199     # %data= ('ip' => $address, 'mac' => $mac);
201         my $out_hash = &create_xml_hash($header, $from, $to);
203         while ( my ($key, $value) = each(%$data) ) {
204                 if(ref($value) eq 'ARRAY'){
205                         map(&add_content2xml_hash($out_hash, $key, $_), @$value);
206                 } else {
207                         &add_content2xml_hash($out_hash, $key, $value);
208                 }
209         }
210     my $out_msg = &create_xml_string($out_hash);
211     return $out_msg;
215 sub db_res2xml {
216     my ($db_res) = @_ ;
217     my $xml = "";
219     my $len_db_res= keys %{$db_res};
220     for( my $i= 1; $i<= $len_db_res; $i++ ) {
221         $xml .= "\n<answer$i>";
222         my $hash= $db_res->{$i};
223         while ( my ($column_name, $column_value) = each %{$hash} ) {
224             $xml .= "<$column_name>";
225             my $xml_content;
226             if( $column_name eq "xmlmessage" ) {
227                 $xml_content = &encode_base64($column_value);
228             } else {
229                 $xml_content = $column_value;
230             }
231             $xml .= $xml_content;
232             $xml .= "</$column_name>"; 
233         }
234         $xml .= "</answer$i>";
236     }
238     return $xml;
242 sub db_res2si_msg {
243     my ($db_res, $header, $target, $source) = @_;
245     my $si_msg = "<xml>";
246     $si_msg .= "<header>$header</header>";
247     $si_msg .= "<source>$source</source>";
248     $si_msg .= "<target>$target</target>";
249     $si_msg .= &db_res2xml;
250     $si_msg .= "</xml>";
254 sub get_where_statement {
255     my ($msg, $msg_hash) = @_;
256     my $error= 0;
257     
258     my $clause_str= "";
259     if( (not exists $msg_hash->{'where'}) || (not exists @{$msg_hash->{'where'}}[0]->{'clause'}) ) { 
260         $error++; 
261     }
263     if( $error == 0 ) {
264         my @clause_l;
265         my @where = @{@{$msg_hash->{'where'}}[0]->{'clause'}};
266         foreach my $clause (@where) {
267             my $connector = $clause->{'connector'}[0];
268             if( not defined $connector ) { $connector = "AND"; }
269             $connector = uc($connector);
270             delete($clause->{'connector'});
272             my @phrase_l ;
273             foreach my $phrase (@{$clause->{'phrase'}}) {
274                 my $operator = "=";
275                 if( exists $phrase->{'operator'} ) {
276                     my $op = $op_hash->{$phrase->{'operator'}[0]};
277                     if( not defined $op ) {
278                         &main::daemon_log("ERROR: Can not translate operator '$operator' in where-".
279                                 "statement to sql valid syntax. Please use 'eq', ".
280                                 "'ne', 'ge', 'gt', 'le', 'lt' in xml message\n", 1);
281                         &main::daemon_log($msg, 8);
282                         $op = "=";
283                     }
284                     $operator = $op;
285                     delete($phrase->{'operator'});
286                 }
288                 my @xml_tags = keys %{$phrase};
289                 my $tag = $xml_tags[0];
290                 my $val = $phrase->{$tag}[0];
291                                 # integer columns do not have to have single quotes besides the value
292                                 if ($tag eq "id") {
293                                                 push(@phrase_l, "$tag$operator$val");
294                                 } else {
295                                                 push(@phrase_l, "$tag$operator'$val'");
296                                 }
297             }
298             my $clause_str .= join(" $connector ", @phrase_l);
299             push(@clause_l, "($clause_str)");
300         }
302         if( not 0 == @clause_l ) {
303             $clause_str = join(" AND ", @clause_l);
304             $clause_str = "WHERE ($clause_str) ";
305         }
306     }
308     return $clause_str;
311 sub get_select_statement {
312     my ($msg, $msg_hash)= @_;
313     my $select = "*";
314     if( exists $msg_hash->{'select'} ) {
315         my $select_l = \@{$msg_hash->{'select'}};
316         $select = join(', ', @{$select_l});
317     }
318     return $select;
322 sub get_update_statement {
323     my ($msg, $msg_hash) = @_;
324     my $error= 0;
325     my $update_str= "";
326     my @update_l; 
328     if( not exists $msg_hash->{'update'} ) { $error++; };
330     if( $error == 0 ) {
331         my $update= @{$msg_hash->{'update'}}[0];
332         while( my ($tag, $val) = each %{$update} ) {
333             my $val= @{$update->{$tag}}[0];
334             push(@update_l, "$tag='$val'");
335         }
336         if( 0 == @update_l ) { $error++; };   
337     }
339     if( $error == 0 ) { 
340         $update_str= join(', ', @update_l);
341         $update_str= "SET $update_str ";
342     }
344     return $update_str;
347 sub get_limit_statement {
348     my ($msg, $msg_hash)= @_; 
349     my $error= 0;
350     my $limit_str = "";
351     my ($from, $to);
353     if( not exists $msg_hash->{'limit'} ) { $error++; };
355     if( $error == 0 ) {
356         eval {
357             my $limit= @{$msg_hash->{'limit'}}[0];
358             $from= @{$limit->{'from'}}[0];
359             $to= @{$limit->{'to'}}[0];
360         };
361         if( $@ ) {
362             $error++;
363         }
364     }
366     if( $error == 0 ) {
367         $limit_str= "LIMIT $from, $to";
368     }   
369     
370     return $limit_str;
373 sub get_orderby_statement {
374     my ($msg, $msg_hash)= @_;
375     my $error= 0;
376     my $order_str= "";
377     my $order;
378     
379     if( not exists $msg_hash->{'orderby'} ) { $error++; };
381     if( $error == 0) {
382         eval {
383             $order= @{$msg_hash->{'orderby'}}[0];
384         };
385         if( $@ ) {
386             $error++;
387         }
388     }
390     if( $error == 0 ) {
391         $order_str= "ORDER BY $order";   
392     }
393     
394     return $order_str;
397 sub get_dns_domains() {
398         my $line;
399         my @searches;
400         open(RESOLV, "</etc/resolv.conf") or return @searches;
401         while(<RESOLV>){
402                 $line= $_;
403                 chomp $line;
404                 $line =~ s/^\s+//;
405                 $line =~ s/\s+$//;
406                 $line =~ s/\s+/ /;
407                 if ($line =~ /^domain (.*)$/ ){
408                         push(@searches, $1);
409                 } elsif ($line =~ /^search (.*)$/ ){
410                         push(@searches, split(/ /, $1));
411                 }
412         }
413         close(RESOLV);
415         my %tmp = map { $_ => 1 } @searches;
416         @searches = sort keys %tmp;
418         return @searches;
422 #############################################
423 # moved from gosa-si-client: rettenbe, 16.05.2008
424 # outcommented at gosa-si-client
425 sub get_server_addresses {
426     my $domain= shift;
427     my @result;
429     my $error = 0;
430     my $res   = Net::DNS::Resolver->new;
431     my $query = $res->send("_gosa-si._tcp.".$domain, "SRV");
432     my @hits;
434     if ($query) {
435         foreach my $rr ($query->answer) {
436             push(@hits, $rr->target.":".$rr->port);
437         }
438     }
439     else {
440         #warn "query failed: ", $res->errorstring, "\n";
441         $error++;
442     }
444     if( $error == 0 ) {
445         foreach my $hit (@hits) {
446             my ($hit_name, $hit_port) = split(/:/, $hit);
447             chomp($hit_name);
448             chomp($hit_port);
450             my $address_query = $res->send($hit_name);
451             if( 1 == length($address_query->answer) ) {
452                 foreach my $rr ($address_query->answer) {
453                     push(@result, $rr->address.":".$hit_port);
454                 }
455             }
456         }
457     }
459     return @result;
463 sub get_logged_in_users {
464     my $result = qx(/usr/bin/w -hs);
465     my @res_lines;
467     if( defined $result ) { 
468         chomp($result);
469         @res_lines = split("\n", $result);
470     }
472     my @logged_in_user_list;
473     foreach my $line (@res_lines) {
474         chomp($line);
475         my @line_parts = split(/\s+/, $line); 
476         push(@logged_in_user_list, $line_parts[0]);
477     }
479     return @logged_in_user_list;
484 sub import_events {
485     my ($event_dir) = @_;
486     my $event_hash;
487     my $error = 0;
488     my @result = ();
489     if (not -e $event_dir) {
490         $error++;
491         push(@result, "cannot find directory or directory is not readable: $event_dir");   
492     }
494     my $DIR;
495     if ($error == 0) {
496         opendir ($DIR, $event_dir) or do { 
497             $error++;
498             push(@result, "cannot open directory '$event_dir' for reading: $!\n");
499         }
500     }
502     if ($error == 0) {
503         while (defined (my $event = readdir ($DIR))) {
504             if( $event eq "." || $event eq ".." ) { next; }  
506             # try to import event module
507             eval{ require $event; };
508             if( $@ ) {
509                 $error++;
510                 push(@result, "import of event module '$event' failed: $@");
511                 next;
512             }
514             # fetch all single events
515             $event =~ /(\S*?).pm$/;
516             my $event_module = $1;
517             my $events_l = eval( $1."::get_events()") ;
518             foreach my $event_name (@{$events_l}) {
519                 $event_hash->{$event_name} = $event_module;
520             }
521             my $events_string = join( ", ", @{$events_l});
522             push(@result, "import of event module '$event' succeed: $events_string");
523         }
524         
525         close $DIR;
526     }
528     return ($error, \@result, $event_hash);
533 1;