33c9ec47d741532fc1548a18599757a98c6ee4f4
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 if( ref($val) eq "HASH" ) { next; } # empty xml-tags should not appear in where statement
298 # integer columns do not have to have single quotes besides the value
299 if ($tag eq "id") {
300 push(@phrase_l, "$tag$operator$val");
301 } else {
302 push(@phrase_l, "$tag$operator'$val'");
303 }
304 }
306 if (not 0 == @phrase_l) {
307 my $clause_str .= join(" $connector ", @phrase_l);
308 push(@clause_l, "($clause_str)");
309 }
310 }
312 if( not 0 == @clause_l ) {
313 $clause_str = join(" AND ", @clause_l);
314 $clause_str = "WHERE ($clause_str) ";
315 }
316 }
318 return $clause_str;
319 }
321 sub get_select_statement {
322 my ($msg, $msg_hash)= @_;
323 my $select = "*";
324 if( exists $msg_hash->{'select'} ) {
325 my $select_l = \@{$msg_hash->{'select'}};
326 $select = join(', ', @{$select_l});
327 }
328 return $select;
329 }
332 sub get_update_statement {
333 my ($msg, $msg_hash) = @_;
334 my $error= 0;
335 my $update_str= "";
336 my @update_l;
338 if( not exists $msg_hash->{'update'} ) { $error++; };
340 if( $error == 0 ) {
341 my $update= @{$msg_hash->{'update'}}[0];
342 while( my ($tag, $val) = each %{$update} ) {
343 my $val= @{$update->{$tag}}[0];
344 push(@update_l, "$tag='$val'");
345 }
346 if( 0 == @update_l ) { $error++; };
347 }
349 if( $error == 0 ) {
350 $update_str= join(', ', @update_l);
351 $update_str= "SET $update_str ";
352 }
354 return $update_str;
355 }
357 sub get_limit_statement {
358 my ($msg, $msg_hash)= @_;
359 my $error= 0;
360 my $limit_str = "";
361 my ($from, $to);
363 if( not exists $msg_hash->{'limit'} ) { $error++; };
365 if( $error == 0 ) {
366 eval {
367 my $limit= @{$msg_hash->{'limit'}}[0];
368 $from= @{$limit->{'from'}}[0];
369 $to= @{$limit->{'to'}}[0];
370 };
371 if( $@ ) {
372 $error++;
373 }
374 }
376 if( $error == 0 ) {
377 $limit_str= "LIMIT $from, $to";
378 }
380 return $limit_str;
381 }
383 sub get_orderby_statement {
384 my ($msg, $msg_hash)= @_;
385 my $error= 0;
386 my $order_str= "";
387 my $order;
389 if( not exists $msg_hash->{'orderby'} ) { $error++; };
391 if( $error == 0) {
392 eval {
393 $order= @{$msg_hash->{'orderby'}}[0];
394 };
395 if( $@ ) {
396 $error++;
397 }
398 }
400 if( $error == 0 ) {
401 $order_str= "ORDER BY $order";
402 }
404 return $order_str;
405 }
407 sub get_dns_domains() {
408 my $line;
409 my @searches;
410 open(RESOLV, "</etc/resolv.conf") or return @searches;
411 while(<RESOLV>){
412 $line= $_;
413 chomp $line;
414 $line =~ s/^\s+//;
415 $line =~ s/\s+$//;
416 $line =~ s/\s+/ /;
417 if ($line =~ /^domain (.*)$/ ){
418 push(@searches, $1);
419 } elsif ($line =~ /^search (.*)$/ ){
420 push(@searches, split(/ /, $1));
421 }
422 }
423 close(RESOLV);
425 my %tmp = map { $_ => 1 } @searches;
426 @searches = sort keys %tmp;
428 return @searches;
429 }
432 #############################################
433 # moved from gosa-si-client: rettenbe, 16.05.2008
434 # outcommented at gosa-si-client
435 sub get_server_addresses {
436 my $domain= shift;
437 my @result;
439 my $error = 0;
440 my $res = Net::DNS::Resolver->new;
441 my $query = $res->send("_gosa-si._tcp.".$domain, "SRV");
442 my @hits;
444 if ($query) {
445 foreach my $rr ($query->answer) {
446 push(@hits, $rr->target.":".$rr->port);
447 }
448 }
449 else {
450 #warn "query failed: ", $res->errorstring, "\n";
451 $error++;
452 }
454 if( $error == 0 ) {
455 foreach my $hit (@hits) {
456 my ($hit_name, $hit_port) = split(/:/, $hit);
457 chomp($hit_name);
458 chomp($hit_port);
460 my $address_query = $res->send($hit_name);
461 if( 1 == length($address_query->answer) ) {
462 foreach my $rr ($address_query->answer) {
463 push(@result, $rr->address.":".$hit_port);
464 }
465 }
466 }
467 }
469 return @result;
470 }
473 sub get_logged_in_users {
474 my $result = qx(/usr/bin/w -hs);
475 my @res_lines;
477 if( defined $result ) {
478 chomp($result);
479 @res_lines = split("\n", $result);
480 }
482 my @logged_in_user_list;
483 foreach my $line (@res_lines) {
484 chomp($line);
485 my @line_parts = split(/\s+/, $line);
486 push(@logged_in_user_list, $line_parts[0]);
487 }
489 return @logged_in_user_list;
491 }
494 sub import_events {
495 my ($event_dir) = @_;
496 my $event_hash;
497 my $error = 0;
498 my @result = ();
499 if (not -e $event_dir) {
500 $error++;
501 push(@result, "cannot find directory or directory is not readable: $event_dir");
502 }
504 my $DIR;
505 if ($error == 0) {
506 opendir ($DIR, $event_dir) or do {
507 $error++;
508 push(@result, "cannot open directory '$event_dir' for reading: $!\n");
509 }
510 }
512 if ($error == 0) {
513 while (defined (my $event = readdir ($DIR))) {
514 if( $event eq "." || $event eq ".." ) { next; }
516 # try to import event module
517 eval{ require $event; };
518 if( $@ ) {
519 $error++;
520 push(@result, "import of event module '$event' failed: $@");
521 next;
522 }
524 # fetch all single events
525 $event =~ /(\S*?).pm$/;
526 my $event_module = $1;
527 my $events_l = eval( $1."::get_events()") ;
528 foreach my $event_name (@{$events_l}) {
529 $event_hash->{$event_name} = $event_module;
530 }
531 my $events_string = join( ", ", @{$events_l});
532 push(@result, "import of event module '$event' succeed: $events_string");
533 }
535 close $DIR;
536 }
538 return ($error, \@result, $event_hash);
540 }
543 #=== FUNCTION ================================================================
544 # NAME: get_ip
545 # PARAMETERS: interface name (i.e. eth0)
546 # RETURNS: (ip address)
547 # DESCRIPTION: Uses ioctl to get ip address directly from system.
548 #===============================================================================
549 sub get_ip {
550 my $ifreq= shift;
551 my $result= "";
552 my $SIOCGIFADDR= 0x8915; # man 2 ioctl_list
553 my $proto= getprotobyname('ip');
555 socket SOCKET, PF_INET, SOCK_DGRAM, $proto
556 or die "socket: $!";
558 if(ioctl SOCKET, $SIOCGIFADDR, $ifreq) {
559 my ($if, $sin) = unpack 'a16 a16', $ifreq;
560 my ($port, $addr) = sockaddr_in $sin;
561 my $ip = inet_ntoa $addr;
563 if ($ip && length($ip) > 0) {
564 $result = $ip;
565 }
566 }
568 return $result;
569 }
572 #=== FUNCTION ================================================================
573 # NAME: get_interface_for_ip
574 # PARAMETERS: ip address (i.e. 192.168.0.1)
575 # RETURNS: array: list of interfaces if ip=0.0.0.0, matching interface if found, undef else
576 # DESCRIPTION: Uses proc fs (/proc/net/dev) to get list of interfaces.
577 #===============================================================================
578 sub get_interface_for_ip {
579 my $result;
580 my $ip= shift;
581 if ($ip && length($ip) > 0) {
582 my @ifs= &get_interfaces();
583 if($ip eq "0.0.0.0") {
584 $result = "all";
585 } else {
586 foreach (@ifs) {
587 my $if=$_;
588 if(&get_ip($if) eq $ip) {
589 $result = $if;
590 }
591 }
592 }
593 }
594 return $result;
595 }
597 #=== FUNCTION ================================================================
598 # NAME: get_interfaces
599 # PARAMETERS: none
600 # RETURNS: (list of interfaces)
601 # DESCRIPTION: Uses proc fs (/proc/net/dev) to get list of interfaces.
602 #===============================================================================
603 sub get_interfaces {
604 my @result;
605 my $PROC_NET_DEV= ('/proc/net/dev');
607 open(PROC_NET_DEV, "<$PROC_NET_DEV")
608 or die "Could not open $PROC_NET_DEV";
610 my @ifs = <PROC_NET_DEV>;
612 close(PROC_NET_DEV);
614 # Eat first two line
615 shift @ifs;
616 shift @ifs;
618 chomp @ifs;
619 foreach my $line(@ifs) {
620 my $if= (split /:/, $line)[0];
621 $if =~ s/^\s+//;
622 push @result, $if;
623 }
625 return @result;
626 }
629 #=== FUNCTION ================================================================
630 # NAME: is_local
631 # PARAMETERS: Server Address
632 # RETURNS: true if Server Address is on this host, false otherwise
633 # DESCRIPTION: Checks all interface addresses, stops on first match
634 #===============================================================================
635 sub is_local {
636 my $server_address = shift || "";
637 my $result = 0;
639 my $server_ip = $1 if $server_address =~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):\d{1,6}$/;
641 if(defined($server_ip) && length($server_ip) > 0) {
642 foreach my $interface(&get_interfaces()) {
643 my $ip_address= &get_ip($interface);
644 if($ip_address eq $server_ip) {
645 $result = 1;
646 last;
647 }
648 }
649 }
651 return $result;
652 }
655 #=== FUNCTION ================================================================
656 # NAME: run_as
657 # PARAMETERS: uid, command
658 # RETURNS: hash with keys 'resultCode' = resultCode of command and
659 # 'output' = program output
660 # DESCRIPTION: Runs command as uid using the sudo utility.
661 #===============================================================================
662 sub run_as {
663 my ($uid, $command) = @_;
664 my $sudo_cmd = `which sudo`;
665 chomp($sudo_cmd);
666 if(! -x $sudo_cmd) {
667 &main::daemon_log("ERROR: The sudo utility is not available! Please fix this!");
668 }
669 my $cmd_line= "$sudo_cmd su - $uid -c '$command'";
670 open(PIPE, "$cmd_line |");
671 my $result = {'resultCode' => $?};
672 $result->{'command'} = $cmd_line;
673 push @{$result->{'output'}}, <PIPE>;
674 return $result;
675 }
678 1;