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     "get_ip",
27     "get_interface_for_ip",
28     "get_interfaces",
29     ); 
30 @EXPORT = @functions;
31 use strict;
32 use warnings;
33 use IO::Socket::INET;
34 use Crypt::Rijndael;
35 use Digest::MD5  qw(md5 md5_hex md5_base64);
36 use MIME::Base64;
37 use XML::Simple;
38 use Data::Dumper;
39 use Net::DNS;
42 my $op_hash = {
43     'eq' => '=',
44     'ne' => '!=',
45     'ge' => '>=',
46     'gt' => '>',
47     'le' => '<=',
48     'lt' => '<',
49     'like' => ' LIKE ',
50 };
53 BEGIN {}
55 END {}
57 ### Start ######################################################################
59 my $xml = new XML::Simple();
61 sub daemon_log {
62     my ($msg, $level) = @_ ;
63     &main::daemon_log($msg, $level);
64     return;
65 }
68 sub create_passwd {
69     my $new_passwd = "";
70     for(my $i=0; $i<31; $i++) {
71         $new_passwd .= ("a".."z","A".."Z",0..9)[int(rand(62))]
72     }
74     return $new_passwd;
75 }
78 sub del_doubles { 
79     my %all; 
80     $all{$_}=0 for @_; 
81     return (keys %all); 
82 }
85 #===  FUNCTION  ================================================================
86 #         NAME:  create_xml_hash
87 #   PARAMETERS:  header - string - message header (required)
88 #                source - string - where the message come from (required)
89 #                target - string - where the message should go to (required)
90 #                [header_value] - string - something usefull (optional)
91 #      RETURNS:  hash - hash - nomen est omen
92 #  DESCRIPTION:  creates a key-value hash, all values are stored in a array
93 #===============================================================================
94 sub create_xml_hash {
95     my ($header, $source, $target, $header_value) = @_;
96     my $hash = {
97             header => [$header],
98             source => [$source],
99             target => [$target],
100             $header => [$header_value],
101     };
102     return $hash
106 #===  FUNCTION  ================================================================
107 #         NAME:  create_xml_string
108 #   PARAMETERS:  xml_hash - hash - hash from function create_xml_hash
109 #      RETURNS:  xml_string - string - xml string representation of the hash
110 #  DESCRIPTION:  transform the hash to a string using XML::Simple module
111 #===============================================================================
112 sub create_xml_string {
113     my ($xml_hash) = @_ ;
114     my $xml_string = $xml->XMLout($xml_hash, RootName => 'xml');
115     #$xml_string =~ s/[\n]+//g;
116     #daemon_log("create_xml_string:",7);
117     #daemon_log("$xml_string\n", 7);
118     return $xml_string;
122 sub transform_msg2hash {
123     my ($msg) = @_ ;
124     my $hash = $xml->XMLin($msg, ForceArray=>1);
125     
126     # xml tags without a content are created as an empty hash
127     # substitute it with an empty list
128     eval {
129         while( my ($xml_tag, $xml_content) = each %{ $hash } ) {
130             if( 1 == @{ $xml_content } ) {
131                 # there is only one element in xml_content list ...
132                 my $element = @{ $xml_content }[0];
133                 if( ref($element) eq "HASH" ) {
134                     # and this element is an hash ...
135                     my $len_element = keys %{ $element };
136                     if( $len_element == 0 ) {
137                         # and this hash is empty, then substitute the xml_content
138                         # with an empty string in list
139                         $hash->{$xml_tag} = [ "none" ];
140                     }
141                 }
142             }
143         }
144     };
145     if( $@ ) {  
146         $hash = undef;
147     }
149     return $hash;
153 #===  FUNCTION  ================================================================
154 #         NAME:  add_content2xml_hash
155 #   PARAMETERS:  xml_ref - ref - reference to a hash from function create_xml_hash
156 #                element - string - key for the hash
157 #                content - string - value for the hash
158 #      RETURNS:  nothing
159 #  DESCRIPTION:  add key-value pair to xml_ref, if key alread exists, 
160 #                then append value to list
161 #===============================================================================
162 sub add_content2xml_hash {
163     my ($xml_ref, $element, $content) = @_;
164     if(not exists $$xml_ref{$element} ) {
165         $$xml_ref{$element} = [];
166     }
167     my $tmp = $$xml_ref{$element};
168     push(@$tmp, $content);
169     return;
173 sub get_time {
174     my ($seconds, $minutes, $hours, $monthday, $month,
175             $year, $weekday, $yearday, $sommertime) = localtime(time);
176     $hours = $hours < 10 ? $hours = "0".$hours : $hours;
177     $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
178     $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
179     $month+=1;
180     $month = $month < 10 ? $month = "0".$month : $month;
181     $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
182     $year+=1900;
183     return "$year$month$monthday$hours$minutes$seconds";
188 #===  FUNCTION  ================================================================
189 #         NAME: build_msg
190 #  DESCRIPTION: Send a message to a destination
191 #   PARAMETERS: [header] Name of the header
192 #               [from]   sender ip
193 #               [to]     recipient ip
194 #               [data]   Hash containing additional attributes for the xml
195 #                        package
196 #      RETURNS:  nothing
197 #===============================================================================
198 sub build_msg ($$$$) {
199         my ($header, $from, $to, $data) = @_;
201     # data is of form, i.e.
202     # %data= ('ip' => $address, 'mac' => $mac);
204         my $out_hash = &create_xml_hash($header, $from, $to);
206         while ( my ($key, $value) = each(%$data) ) {
207                 if(ref($value) eq 'ARRAY'){
208                         map(&add_content2xml_hash($out_hash, $key, $_), @$value);
209                 } else {
210                         &add_content2xml_hash($out_hash, $key, $value);
211                 }
212         }
213     my $out_msg = &create_xml_string($out_hash);
214     return $out_msg;
218 sub db_res2xml {
219     my ($db_res) = @_ ;
220     my $xml = "";
222     my $len_db_res= keys %{$db_res};
223     for( my $i= 1; $i<= $len_db_res; $i++ ) {
224         $xml .= "\n<answer$i>";
225         my $hash= $db_res->{$i};
226         while ( my ($column_name, $column_value) = each %{$hash} ) {
227             $xml .= "<$column_name>";
228             my $xml_content;
229             if( $column_name eq "xmlmessage" ) {
230                 $xml_content = &encode_base64($column_value);
231             } else {
232                 $xml_content = $column_value;
233             }
234             $xml .= $xml_content;
235             $xml .= "</$column_name>"; 
236         }
237         $xml .= "</answer$i>";
239     }
241     return $xml;
245 sub db_res2si_msg {
246     my ($db_res, $header, $target, $source) = @_;
248     my $si_msg = "<xml>";
249     $si_msg .= "<header>$header</header>";
250     $si_msg .= "<source>$source</source>";
251     $si_msg .= "<target>$target</target>";
252     $si_msg .= &db_res2xml;
253     $si_msg .= "</xml>";
257 sub get_where_statement {
258     my ($msg, $msg_hash) = @_;
259     my $error= 0;
260     
261     my $clause_str= "";
262     if( (not exists $msg_hash->{'where'}) || (not exists @{$msg_hash->{'where'}}[0]->{'clause'}) ) { 
263         $error++; 
264     }
266     if( $error == 0 ) {
267         my @clause_l;
268         my @where = @{@{$msg_hash->{'where'}}[0]->{'clause'}};
269         foreach my $clause (@where) {
270             my $connector = $clause->{'connector'}[0];
271             if( not defined $connector ) { $connector = "AND"; }
272             $connector = uc($connector);
273             delete($clause->{'connector'});
275             my @phrase_l ;
276             foreach my $phrase (@{$clause->{'phrase'}}) {
277                 my $operator = "=";
278                 if( exists $phrase->{'operator'} ) {
279                     my $op = $op_hash->{$phrase->{'operator'}[0]};
280                     if( not defined $op ) {
281                         &main::daemon_log("ERROR: Can not translate operator '$operator' in where-".
282                                 "statement to sql valid syntax. Please use 'eq', ".
283                                 "'ne', 'ge', 'gt', 'le', 'lt' in xml message\n", 1);
284                         &main::daemon_log($msg, 8);
285                         $op = "=";
286                     }
287                     $operator = $op;
288                     delete($phrase->{'operator'});
289                 }
291                 my @xml_tags = keys %{$phrase};
292                 my $tag = $xml_tags[0];
293                 my $val = $phrase->{$tag}[0];
294                                 # integer columns do not have to have single quotes besides the value
295                                 if ($tag eq "id") {
296                                                 push(@phrase_l, "$tag$operator$val");
297                                 } else {
298                                                 push(@phrase_l, "$tag$operator'$val'");
299                                 }
300             }
301             my $clause_str .= join(" $connector ", @phrase_l);
302             push(@clause_l, "($clause_str)");
303         }
305         if( not 0 == @clause_l ) {
306             $clause_str = join(" AND ", @clause_l);
307             $clause_str = "WHERE ($clause_str) ";
308         }
309     }
311     return $clause_str;
314 sub get_select_statement {
315     my ($msg, $msg_hash)= @_;
316     my $select = "*";
317     if( exists $msg_hash->{'select'} ) {
318         my $select_l = \@{$msg_hash->{'select'}};
319         $select = join(', ', @{$select_l});
320     }
321     return $select;
325 sub get_update_statement {
326     my ($msg, $msg_hash) = @_;
327     my $error= 0;
328     my $update_str= "";
329     my @update_l; 
331     if( not exists $msg_hash->{'update'} ) { $error++; };
333     if( $error == 0 ) {
334         my $update= @{$msg_hash->{'update'}}[0];
335         while( my ($tag, $val) = each %{$update} ) {
336             my $val= @{$update->{$tag}}[0];
337             push(@update_l, "$tag='$val'");
338         }
339         if( 0 == @update_l ) { $error++; };   
340     }
342     if( $error == 0 ) { 
343         $update_str= join(', ', @update_l);
344         $update_str= "SET $update_str ";
345     }
347     return $update_str;
350 sub get_limit_statement {
351     my ($msg, $msg_hash)= @_; 
352     my $error= 0;
353     my $limit_str = "";
354     my ($from, $to);
356     if( not exists $msg_hash->{'limit'} ) { $error++; };
358     if( $error == 0 ) {
359         eval {
360             my $limit= @{$msg_hash->{'limit'}}[0];
361             $from= @{$limit->{'from'}}[0];
362             $to= @{$limit->{'to'}}[0];
363         };
364         if( $@ ) {
365             $error++;
366         }
367     }
369     if( $error == 0 ) {
370         $limit_str= "LIMIT $from, $to";
371     }   
372     
373     return $limit_str;
376 sub get_orderby_statement {
377     my ($msg, $msg_hash)= @_;
378     my $error= 0;
379     my $order_str= "";
380     my $order;
381     
382     if( not exists $msg_hash->{'orderby'} ) { $error++; };
384     if( $error == 0) {
385         eval {
386             $order= @{$msg_hash->{'orderby'}}[0];
387         };
388         if( $@ ) {
389             $error++;
390         }
391     }
393     if( $error == 0 ) {
394         $order_str= "ORDER BY $order";   
395     }
396     
397     return $order_str;
400 sub get_dns_domains() {
401         my $line;
402         my @searches;
403         open(RESOLV, "</etc/resolv.conf") or return @searches;
404         while(<RESOLV>){
405                 $line= $_;
406                 chomp $line;
407                 $line =~ s/^\s+//;
408                 $line =~ s/\s+$//;
409                 $line =~ s/\s+/ /;
410                 if ($line =~ /^domain (.*)$/ ){
411                         push(@searches, $1);
412                 } elsif ($line =~ /^search (.*)$/ ){
413                         push(@searches, split(/ /, $1));
414                 }
415         }
416         close(RESOLV);
418         my %tmp = map { $_ => 1 } @searches;
419         @searches = sort keys %tmp;
421         return @searches;
425 #############################################
426 # moved from gosa-si-client: rettenbe, 16.05.2008
427 # outcommented at gosa-si-client
428 sub get_server_addresses {
429     my $domain= shift;
430     my @result;
432     my $error = 0;
433     my $res   = Net::DNS::Resolver->new;
434     my $query = $res->send("_gosa-si._tcp.".$domain, "SRV");
435     my @hits;
437     if ($query) {
438         foreach my $rr ($query->answer) {
439             push(@hits, $rr->target.":".$rr->port);
440         }
441     }
442     else {
443         #warn "query failed: ", $res->errorstring, "\n";
444         $error++;
445     }
447     if( $error == 0 ) {
448         foreach my $hit (@hits) {
449             my ($hit_name, $hit_port) = split(/:/, $hit);
450             chomp($hit_name);
451             chomp($hit_port);
453             my $address_query = $res->send($hit_name);
454             if( 1 == length($address_query->answer) ) {
455                 foreach my $rr ($address_query->answer) {
456                     push(@result, $rr->address.":".$hit_port);
457                 }
458             }
459         }
460     }
462     return @result;
466 sub get_logged_in_users {
467     my $result = qx(/usr/bin/w -hs);
468     my @res_lines;
470     if( defined $result ) { 
471         chomp($result);
472         @res_lines = split("\n", $result);
473     }
475     my @logged_in_user_list;
476     foreach my $line (@res_lines) {
477         chomp($line);
478         my @line_parts = split(/\s+/, $line); 
479         push(@logged_in_user_list, $line_parts[0]);
480     }
482     return @logged_in_user_list;
487 sub import_events {
488     my ($event_dir) = @_;
489     my $event_hash;
490     my $error = 0;
491     my @result = ();
492     if (not -e $event_dir) {
493         $error++;
494         push(@result, "cannot find directory or directory is not readable: $event_dir");   
495     }
497     my $DIR;
498     if ($error == 0) {
499         opendir ($DIR, $event_dir) or do { 
500             $error++;
501             push(@result, "cannot open directory '$event_dir' for reading: $!\n");
502         }
503     }
505     if ($error == 0) {
506         while (defined (my $event = readdir ($DIR))) {
507             if( $event eq "." || $event eq ".." ) { next; }  
509             # try to import event module
510             eval{ require $event; };
511             if( $@ ) {
512                 $error++;
513                 push(@result, "import of event module '$event' failed: $@");
514                 next;
515             }
517             # fetch all single events
518             $event =~ /(\S*?).pm$/;
519             my $event_module = $1;
520             my $events_l = eval( $1."::get_events()") ;
521             foreach my $event_name (@{$events_l}) {
522                 $event_hash->{$event_name} = $event_module;
523             }
524             my $events_string = join( ", ", @{$events_l});
525             push(@result, "import of event module '$event' succeed: $events_string");
526         }
527         
528         close $DIR;
529     }
531     return ($error, \@result, $event_hash);
536 #===  FUNCTION  ================================================================
537 #         NAME:  get_ip 
538 #   PARAMETERS:  interface name (i.e. eth0)
539 #      RETURNS:  (ip address) 
540 #  DESCRIPTION:  Uses ioctl to get ip address directly from system.
541 #===============================================================================
542 sub get_ip {
543         my $ifreq= shift;
544         my $result= "";
545         my $SIOCGIFADDR= 0x8915;       # man 2 ioctl_list
546         my $proto= getprotobyname('ip');
548         socket SOCKET, PF_INET, SOCK_DGRAM, $proto
549                 or die "socket: $!";
551         if(ioctl SOCKET, $SIOCGIFADDR, $ifreq) {
552                 my ($if, $sin)    = unpack 'a16 a16', $ifreq;
553                 my ($port, $addr) = sockaddr_in $sin;
554                 my $ip            = inet_ntoa $addr;
556                 if ($ip && length($ip) > 0) {
557                         $result = $ip;
558                 }
559         }
561         return $result;
565 #===  FUNCTION  ================================================================
566 #         NAME:  get_interface_for_ip
567 #   PARAMETERS:  ip address (i.e. 192.168.0.1)
568 #      RETURNS:  array: list of interfaces if ip=0.0.0.0, matching interface if found, undef else
569 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
570 #===============================================================================
571 sub get_interface_for_ip {
572         my $result;
573         my $ip= shift;
574         if ($ip && length($ip) > 0) {
575                 my @ifs= &get_interfaces();
576                 if($ip eq "0.0.0.0") {
577                         $result = "all";
578                 } else {
579                         foreach (@ifs) {
580                                 my $if=$_;
581                                 if(&get_ip($if) eq $ip) {
582                                         $result = $if;
583                                 }
584                         }       
585                 }
586         }       
587         return $result;
590 #===  FUNCTION  ================================================================
591 #         NAME:  get_interfaces 
592 #   PARAMETERS:  none
593 #      RETURNS:  (list of interfaces) 
594 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
595 #===============================================================================
596 sub get_interfaces {
597         my @result;
598         my $PROC_NET_DEV= ('/proc/net/dev');
600         open(PROC_NET_DEV, "<$PROC_NET_DEV")
601                 or die "Could not open $PROC_NET_DEV";
603         my @ifs = <PROC_NET_DEV>;
605         close(PROC_NET_DEV);
607         # Eat first two line
608         shift @ifs;
609         shift @ifs;
611         chomp @ifs;
612         foreach my $line(@ifs) {
613                 my $if= (split /:/, $line)[0];
614                 $if =~ s/^\s+//;
615                 push @result, $if;
616         }
618         return @result;
622 1;