21db30a5974acedb2677887fe3bb5df3828f0b34
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 );
32 @EXPORT = @functions;
33 use strict;
34 use warnings;
35 use IO::Socket::INET;
36 use Crypt::Rijndael;
37 use Digest::MD5 qw(md5 md5_hex md5_base64);
38 use MIME::Base64;
39 use XML::Simple;
40 use Data::Dumper;
41 use Net::DNS;
44 my $op_hash = {
45 'eq' => '=',
46 'ne' => '!=',
47 'ge' => '>=',
48 'gt' => '>',
49 'le' => '<=',
50 'lt' => '<',
51 'like' => ' LIKE ',
52 };
55 BEGIN {}
57 END {}
59 ### Start ######################################################################
61 my $xml = new XML::Simple();
63 sub daemon_log {
64 my ($msg, $level) = @_ ;
65 &main::daemon_log($msg, $level);
66 return;
67 }
70 sub create_passwd {
71 my $new_passwd = "";
72 for(my $i=0; $i<31; $i++) {
73 $new_passwd .= ("a".."z","A".."Z",0..9)[int(rand(62))]
74 }
76 return $new_passwd;
77 }
80 sub del_doubles {
81 my %all;
82 $all{$_}=0 for @_;
83 return (keys %all);
84 }
87 #=== FUNCTION ================================================================
88 # NAME: create_xml_hash
89 # PARAMETERS: header - string - message header (required)
90 # source - string - where the message come from (required)
91 # target - string - where the message should go to (required)
92 # [header_value] - string - something usefull (optional)
93 # RETURNS: hash - hash - nomen est omen
94 # DESCRIPTION: creates a key-value hash, all values are stored in a array
95 #===============================================================================
96 sub create_xml_hash {
97 my ($header, $source, $target, $header_value) = @_;
98 my $hash = {
99 header => [$header],
100 source => [$source],
101 target => [$target],
102 $header => [$header_value],
103 };
104 return $hash
105 }
108 #=== FUNCTION ================================================================
109 # NAME: create_xml_string
110 # PARAMETERS: xml_hash - hash - hash from function create_xml_hash
111 # RETURNS: xml_string - string - xml string representation of the hash
112 # DESCRIPTION: transform the hash to a string using XML::Simple module
113 #===============================================================================
114 sub create_xml_string {
115 my ($xml_hash) = @_ ;
116 my $xml_string = $xml->XMLout($xml_hash, RootName => 'xml');
117 #$xml_string =~ s/[\n]+//g;
118 #daemon_log("create_xml_string:",7);
119 #daemon_log("$xml_string\n", 7);
120 return $xml_string;
121 }
124 sub transform_msg2hash {
125 my ($msg) = @_ ;
126 my $hash = $xml->XMLin($msg, ForceArray=>1);
128 # xml tags without a content are created as an empty hash
129 # substitute it with an empty list
130 eval {
131 while( my ($xml_tag, $xml_content) = each %{ $hash } ) {
132 if( 1 == @{ $xml_content } ) {
133 # there is only one element in xml_content list ...
134 my $element = @{ $xml_content }[0];
135 if( ref($element) eq "HASH" ) {
136 # and this element is an hash ...
137 my $len_element = keys %{ $element };
138 if( $len_element == 0 ) {
139 # and this hash is empty, then substitute the xml_content
140 # with an empty string in list
141 $hash->{$xml_tag} = [ "none" ];
142 }
143 }
144 }
145 }
146 };
147 if( $@ ) {
148 $hash = undef;
149 }
151 return $hash;
152 }
155 #=== FUNCTION ================================================================
156 # NAME: add_content2xml_hash
157 # PARAMETERS: xml_ref - ref - reference to a hash from function create_xml_hash
158 # element - string - key for the hash
159 # content - string - value for the hash
160 # RETURNS: nothing
161 # DESCRIPTION: add key-value pair to xml_ref, if key alread exists,
162 # then append value to list
163 #===============================================================================
164 sub add_content2xml_hash {
165 my ($xml_ref, $element, $content) = @_;
166 if(not exists $$xml_ref{$element} ) {
167 $$xml_ref{$element} = [];
168 }
169 my $tmp = $$xml_ref{$element};
170 push(@$tmp, $content);
171 return;
172 }
175 sub get_time {
176 my ($seconds, $minutes, $hours, $monthday, $month,
177 $year, $weekday, $yearday, $sommertime) = localtime(time);
178 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
179 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
180 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
181 $month+=1;
182 $month = $month < 10 ? $month = "0".$month : $month;
183 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
184 $year+=1900;
185 return "$year$month$monthday$hours$minutes$seconds";
187 }
190 #=== FUNCTION ================================================================
191 # NAME: build_msg
192 # DESCRIPTION: Send a message to a destination
193 # PARAMETERS: [header] Name of the header
194 # [from] sender ip
195 # [to] recipient ip
196 # [data] Hash containing additional attributes for the xml
197 # package
198 # RETURNS: nothing
199 #===============================================================================
200 sub build_msg ($$$$) {
201 my ($header, $from, $to, $data) = @_;
203 # data is of form, i.e.
204 # %data= ('ip' => $address, 'mac' => $mac);
206 my $out_hash = &create_xml_hash($header, $from, $to);
208 while ( my ($key, $value) = each(%$data) ) {
209 if(ref($value) eq 'ARRAY'){
210 map(&add_content2xml_hash($out_hash, $key, $_), @$value);
211 } else {
212 &add_content2xml_hash($out_hash, $key, $value);
213 }
214 }
215 my $out_msg = &create_xml_string($out_hash);
216 return $out_msg;
217 }
220 sub db_res2xml {
221 my ($db_res) = @_ ;
222 my $xml = "";
224 my $len_db_res= keys %{$db_res};
225 for( my $i= 1; $i<= $len_db_res; $i++ ) {
226 $xml .= "\n<answer$i>";
227 my $hash= $db_res->{$i};
228 while ( my ($column_name, $column_value) = each %{$hash} ) {
229 $xml .= "<$column_name>";
230 my $xml_content;
231 if( $column_name eq "xmlmessage" ) {
232 $xml_content = &encode_base64($column_value);
233 } else {
234 $xml_content = $column_value;
235 }
236 $xml .= $xml_content;
237 $xml .= "</$column_name>";
238 }
239 $xml .= "</answer$i>";
241 }
243 return $xml;
244 }
247 sub db_res2si_msg {
248 my ($db_res, $header, $target, $source) = @_;
250 my $si_msg = "<xml>";
251 $si_msg .= "<header>$header</header>";
252 $si_msg .= "<source>$source</source>";
253 $si_msg .= "<target>$target</target>";
254 $si_msg .= &db_res2xml;
255 $si_msg .= "</xml>";
256 }
259 sub get_where_statement {
260 my ($msg, $msg_hash) = @_;
261 my $error= 0;
263 my $clause_str= "";
264 if( (not exists $msg_hash->{'where'}) || (not exists @{$msg_hash->{'where'}}[0]->{'clause'}) ) {
265 $error++;
266 }
268 if( $error == 0 ) {
269 my @clause_l;
270 my @where = @{@{$msg_hash->{'where'}}[0]->{'clause'}};
271 foreach my $clause (@where) {
272 my $connector = $clause->{'connector'}[0];
273 if( not defined $connector ) { $connector = "AND"; }
274 $connector = uc($connector);
275 delete($clause->{'connector'});
277 my @phrase_l ;
278 foreach my $phrase (@{$clause->{'phrase'}}) {
279 my $operator = "=";
280 if( exists $phrase->{'operator'} ) {
281 my $op = $op_hash->{$phrase->{'operator'}[0]};
282 if( not defined $op ) {
283 &main::daemon_log("ERROR: Can not translate operator '$operator' in where-".
284 "statement to sql valid syntax. Please use 'eq', ".
285 "'ne', 'ge', 'gt', 'le', 'lt' in xml message\n", 1);
286 &main::daemon_log($msg, 8);
287 $op = "=";
288 }
289 $operator = $op;
290 delete($phrase->{'operator'});
291 }
293 my @xml_tags = keys %{$phrase};
294 my $tag = $xml_tags[0];
295 my $val = $phrase->{$tag}[0];
296 # integer columns do not have to have single quotes besides the value
297 if ($tag eq "id") {
298 push(@phrase_l, "$tag$operator$val");
299 } else {
300 push(@phrase_l, "$tag$operator'$val'");
301 }
302 }
303 my $clause_str .= join(" $connector ", @phrase_l);
304 push(@clause_l, "($clause_str)");
305 }
307 if( not 0 == @clause_l ) {
308 $clause_str = join(" AND ", @clause_l);
309 $clause_str = "WHERE ($clause_str) ";
310 }
311 }
313 return $clause_str;
314 }
316 sub get_select_statement {
317 my ($msg, $msg_hash)= @_;
318 my $select = "*";
319 if( exists $msg_hash->{'select'} ) {
320 my $select_l = \@{$msg_hash->{'select'}};
321 $select = join(', ', @{$select_l});
322 }
323 return $select;
324 }
327 sub get_update_statement {
328 my ($msg, $msg_hash) = @_;
329 my $error= 0;
330 my $update_str= "";
331 my @update_l;
333 if( not exists $msg_hash->{'update'} ) { $error++; };
335 if( $error == 0 ) {
336 my $update= @{$msg_hash->{'update'}}[0];
337 while( my ($tag, $val) = each %{$update} ) {
338 my $val= @{$update->{$tag}}[0];
339 push(@update_l, "$tag='$val'");
340 }
341 if( 0 == @update_l ) { $error++; };
342 }
344 if( $error == 0 ) {
345 $update_str= join(', ', @update_l);
346 $update_str= "SET $update_str ";
347 }
349 return $update_str;
350 }
352 sub get_limit_statement {
353 my ($msg, $msg_hash)= @_;
354 my $error= 0;
355 my $limit_str = "";
356 my ($from, $to);
358 if( not exists $msg_hash->{'limit'} ) { $error++; };
360 if( $error == 0 ) {
361 eval {
362 my $limit= @{$msg_hash->{'limit'}}[0];
363 $from= @{$limit->{'from'}}[0];
364 $to= @{$limit->{'to'}}[0];
365 };
366 if( $@ ) {
367 $error++;
368 }
369 }
371 if( $error == 0 ) {
372 $limit_str= "LIMIT $from, $to";
373 }
375 return $limit_str;
376 }
378 sub get_orderby_statement {
379 my ($msg, $msg_hash)= @_;
380 my $error= 0;
381 my $order_str= "";
382 my $order;
384 if( not exists $msg_hash->{'orderby'} ) { $error++; };
386 if( $error == 0) {
387 eval {
388 $order= @{$msg_hash->{'orderby'}}[0];
389 };
390 if( $@ ) {
391 $error++;
392 }
393 }
395 if( $error == 0 ) {
396 $order_str= "ORDER BY $order";
397 }
399 return $order_str;
400 }
402 sub get_dns_domains() {
403 my $line;
404 my @searches;
405 open(RESOLV, "</etc/resolv.conf") or return @searches;
406 while(<RESOLV>){
407 $line= $_;
408 chomp $line;
409 $line =~ s/^\s+//;
410 $line =~ s/\s+$//;
411 $line =~ s/\s+/ /;
412 if ($line =~ /^domain (.*)$/ ){
413 push(@searches, $1);
414 } elsif ($line =~ /^search (.*)$/ ){
415 push(@searches, split(/ /, $1));
416 }
417 }
418 close(RESOLV);
420 my %tmp = map { $_ => 1 } @searches;
421 @searches = sort keys %tmp;
423 return @searches;
424 }
427 #############################################
428 # moved from gosa-si-client: rettenbe, 16.05.2008
429 # outcommented at gosa-si-client
430 sub get_server_addresses {
431 my $domain= shift;
432 my @result;
434 my $error = 0;
435 my $res = Net::DNS::Resolver->new;
436 my $query = $res->send("_gosa-si._tcp.".$domain, "SRV");
437 my @hits;
439 if ($query) {
440 foreach my $rr ($query->answer) {
441 push(@hits, $rr->target.":".$rr->port);
442 }
443 }
444 else {
445 #warn "query failed: ", $res->errorstring, "\n";
446 $error++;
447 }
449 if( $error == 0 ) {
450 foreach my $hit (@hits) {
451 my ($hit_name, $hit_port) = split(/:/, $hit);
452 chomp($hit_name);
453 chomp($hit_port);
455 my $address_query = $res->send($hit_name);
456 if( 1 == length($address_query->answer) ) {
457 foreach my $rr ($address_query->answer) {
458 push(@result, $rr->address.":".$hit_port);
459 }
460 }
461 }
462 }
464 return @result;
465 }
468 sub get_logged_in_users {
469 my $result = qx(/usr/bin/w -hs);
470 my @res_lines;
472 if( defined $result ) {
473 chomp($result);
474 @res_lines = split("\n", $result);
475 }
477 my @logged_in_user_list;
478 foreach my $line (@res_lines) {
479 chomp($line);
480 my @line_parts = split(/\s+/, $line);
481 push(@logged_in_user_list, $line_parts[0]);
482 }
484 return @logged_in_user_list;
486 }
489 sub import_events {
490 my ($event_dir) = @_;
491 my $event_hash;
492 my $error = 0;
493 my @result = ();
494 if (not -e $event_dir) {
495 $error++;
496 push(@result, "cannot find directory or directory is not readable: $event_dir");
497 }
499 my $DIR;
500 if ($error == 0) {
501 opendir ($DIR, $event_dir) or do {
502 $error++;
503 push(@result, "cannot open directory '$event_dir' for reading: $!\n");
504 }
505 }
507 if ($error == 0) {
508 while (defined (my $event = readdir ($DIR))) {
509 if( $event eq "." || $event eq ".." ) { next; }
511 # try to import event module
512 eval{ require $event; };
513 if( $@ ) {
514 $error++;
515 push(@result, "import of event module '$event' failed: $@");
516 next;
517 }
519 # fetch all single events
520 $event =~ /(\S*?).pm$/;
521 my $event_module = $1;
522 my $events_l = eval( $1."::get_events()") ;
523 foreach my $event_name (@{$events_l}) {
524 $event_hash->{$event_name} = $event_module;
525 }
526 my $events_string = join( ", ", @{$events_l});
527 push(@result, "import of event module '$event' succeed: $events_string");
528 }
530 close $DIR;
531 }
533 return ($error, \@result, $event_hash);
535 }
538 #=== FUNCTION ================================================================
539 # NAME: get_ip
540 # PARAMETERS: interface name (i.e. eth0)
541 # RETURNS: (ip address)
542 # DESCRIPTION: Uses ioctl to get ip address directly from system.
543 #===============================================================================
544 sub get_ip {
545 my $ifreq= shift;
546 my $result= "";
547 my $SIOCGIFADDR= 0x8915; # man 2 ioctl_list
548 my $proto= getprotobyname('ip');
550 socket SOCKET, PF_INET, SOCK_DGRAM, $proto
551 or die "socket: $!";
553 if(ioctl SOCKET, $SIOCGIFADDR, $ifreq) {
554 my ($if, $sin) = unpack 'a16 a16', $ifreq;
555 my ($port, $addr) = sockaddr_in $sin;
556 my $ip = inet_ntoa $addr;
558 if ($ip && length($ip) > 0) {
559 $result = $ip;
560 }
561 }
563 return $result;
564 }
567 #=== FUNCTION ================================================================
568 # NAME: get_interface_for_ip
569 # PARAMETERS: ip address (i.e. 192.168.0.1)
570 # RETURNS: array: list of interfaces if ip=0.0.0.0, matching interface if found, undef else
571 # DESCRIPTION: Uses proc fs (/proc/net/dev) to get list of interfaces.
572 #===============================================================================
573 sub get_interface_for_ip {
574 my $result;
575 my $ip= shift;
576 if ($ip && length($ip) > 0) {
577 my @ifs= &get_interfaces();
578 if($ip eq "0.0.0.0") {
579 $result = "all";
580 } else {
581 foreach (@ifs) {
582 my $if=$_;
583 if(&get_ip($if) eq $ip) {
584 $result = $if;
585 }
586 }
587 }
588 }
589 return $result;
590 }
592 #=== FUNCTION ================================================================
593 # NAME: get_interfaces
594 # PARAMETERS: none
595 # RETURNS: (list of interfaces)
596 # DESCRIPTION: Uses proc fs (/proc/net/dev) to get list of interfaces.
597 #===============================================================================
598 sub get_interfaces {
599 my @result;
600 my $PROC_NET_DEV= ('/proc/net/dev');
602 open(PROC_NET_DEV, "<$PROC_NET_DEV")
603 or die "Could not open $PROC_NET_DEV";
605 my @ifs = <PROC_NET_DEV>;
607 close(PROC_NET_DEV);
609 # Eat first two line
610 shift @ifs;
611 shift @ifs;
613 chomp @ifs;
614 foreach my $line(@ifs) {
615 my $if= (split /:/, $line)[0];
616 $if =~ s/^\s+//;
617 push @result, $if;
618 }
620 return @result;
621 }
624 #=== FUNCTION ================================================================
625 # NAME: is_local
626 # PARAMETERS: Server Address
627 # RETURNS: true if Server Address is on this host, false otherwise
628 # DESCRIPTION: Checks all interface addresses, stops on first match
629 #===============================================================================
630 sub is_local {
631 my $server_address = shift || "";
632 my $result = 0;
634 my $server_ip = $1 if $server_address =~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):\d{1,6}$/;
636 if(defined($server_ip) && length($server_ip) > 0) {
637 foreach my $interface(&get_interfaces()) {
638 my $ip_address= &get_ip($interface);
639 if($ip_address eq $server_ip) {
640 $result = 1;
641 last;
642 }
643 }
644 }
646 return $result;
647 }
650 #=== FUNCTION ================================================================
651 # NAME: run_as
652 # PARAMETERS: uid, command
653 # RETURNS: hash with keys 'resultCode' = resultCode of command and
654 # 'output' = program output
655 # DESCRIPTION: Runs command as uid using the sudo utility.
656 #===============================================================================
657 sub run_as {
658 my ($uid, $command) = @_;
659 my $sudo_cmd = `which sudo`;
660 chomp($sudo_cmd);
661 if(! -x $sudo_cmd) {
662 &main::daemon_log("ERROR: The sudo utility is not available! Please fix this!");
663 }
664 my $cmd_line= "$sudo_cmd su - $uid -c '$command'";
665 open(PIPE, "$cmd_line |");
666 my $result = {'resultCode' => $?};
667 $result->{'command'} = $cmd_line;
668 push @{$result->{'output'}}, <PIPE>;
669 return $result;
670 }
673 1;