c10a0e46f5d19f03f12017b6974ea30b1f9104eb
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
108 }
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;
124 }
127 sub transform_msg2hash {
128 my ($msg) = @_ ;
129 my $hash = $xml->XMLin($msg, ForceArray=>1);
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;
155 }
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;
175 }
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";
190 }
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;
220 }
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;
247 }
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>";
259 }
262 sub get_where_statement {
263 my ($msg, $msg_hash) = @_;
264 my $error= 0;
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;
322 }
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;
332 }
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;
358 }
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 }
383 return $limit_str;
384 }
386 sub get_orderby_statement {
387 my ($msg, $msg_hash)= @_;
388 my $error= 0;
389 my $order_str= "";
390 my $order;
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 }
407 return $order_str;
408 }
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;
432 }
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;
523 &main::daemon_log("ERROR: Import of event module '$event' failed: $@",1);
524 exit(1);
525 }
527 # fetch all single events
528 $event =~ /(\S*?).pm$/;
529 my $event_module = $1;
530 my $events_l = eval( $1."::get_events()") ;
531 foreach my $event_name (@{$events_l}) {
532 $event_hash->{$event_name} = $event_module;
533 }
534 my $events_string = join( ", ", @{$events_l});
535 push(@result, "import of event module '$event' succeed: $events_string");
536 }
538 close $DIR;
539 }
541 return ($error, \@result, $event_hash);
543 }
546 #=== FUNCTION ================================================================
547 # NAME: get_ip
548 # PARAMETERS: interface name (i.e. eth0)
549 # RETURNS: (ip address)
550 # DESCRIPTION: Uses ioctl to get ip address directly from system.
551 #===============================================================================
552 sub get_ip {
553 my $ifreq= shift;
554 my $result= "";
555 my $SIOCGIFADDR= 0x8915; # man 2 ioctl_list
556 my $proto= getprotobyname('ip');
558 socket SOCKET, PF_INET, SOCK_DGRAM, $proto
559 or die "socket: $!";
561 if(ioctl SOCKET, $SIOCGIFADDR, $ifreq) {
562 my ($if, $sin) = unpack 'a16 a16', $ifreq;
563 my ($port, $addr) = sockaddr_in $sin;
564 my $ip = inet_ntoa $addr;
566 if ($ip && length($ip) > 0) {
567 $result = $ip;
568 }
569 }
571 return $result;
572 }
575 #=== FUNCTION ================================================================
576 # NAME: get_interface_for_ip
577 # PARAMETERS: ip address (i.e. 192.168.0.1)
578 # RETURNS: array: list of interfaces if ip=0.0.0.0, matching interface if found, undef else
579 # DESCRIPTION: Uses proc fs (/proc/net/dev) to get list of interfaces.
580 #===============================================================================
581 sub get_interface_for_ip {
582 my $result;
583 my $ip= shift;
584 if ($ip && length($ip) > 0) {
585 my @ifs= &get_interfaces();
586 if($ip eq "0.0.0.0") {
587 $result = "all";
588 } else {
589 foreach (@ifs) {
590 my $if=$_;
591 if(&get_ip($if) eq $ip) {
592 $result = $if;
593 }
594 }
595 }
596 }
597 return $result;
598 }
600 #=== FUNCTION ================================================================
601 # NAME: get_interfaces
602 # PARAMETERS: none
603 # RETURNS: (list of interfaces)
604 # DESCRIPTION: Uses proc fs (/proc/net/dev) to get list of interfaces.
605 #===============================================================================
606 sub get_interfaces {
607 my @result;
608 my $PROC_NET_DEV= ('/proc/net/dev');
610 open(PROC_NET_DEV, "<$PROC_NET_DEV")
611 or die "Could not open $PROC_NET_DEV";
613 my @ifs = <PROC_NET_DEV>;
615 close(PROC_NET_DEV);
617 # Eat first two line
618 shift @ifs;
619 shift @ifs;
621 chomp @ifs;
622 foreach my $line(@ifs) {
623 my $if= (split /:/, $line)[0];
624 $if =~ s/^\s+//;
625 push @result, $if;
626 }
628 return @result;
629 }
632 #=== FUNCTION ================================================================
633 # NAME: is_local
634 # PARAMETERS: Server Address
635 # RETURNS: true if Server Address is on this host, false otherwise
636 # DESCRIPTION: Checks all interface addresses, stops on first match
637 #===============================================================================
638 sub is_local {
639 my $server_address = shift || "";
640 my $result = 0;
642 my $server_ip = $1 if $server_address =~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):\d{1,6}$/;
644 if(defined($server_ip) && length($server_ip) > 0) {
645 foreach my $interface(&get_interfaces()) {
646 my $ip_address= &get_ip($interface);
647 if($ip_address eq $server_ip) {
648 $result = 1;
649 last;
650 }
651 }
652 }
654 return $result;
655 }
658 #=== FUNCTION ================================================================
659 # NAME: run_as
660 # PARAMETERS: uid, command
661 # RETURNS: hash with keys 'resultCode' = resultCode of command and
662 # 'output' = program output
663 # DESCRIPTION: Runs command as uid using the sudo utility.
664 #===============================================================================
665 sub run_as {
666 my ($uid, $command) = @_;
667 my $sudo_cmd = `which sudo`;
668 chomp($sudo_cmd);
669 if(! -x $sudo_cmd) {
670 &main::daemon_log("ERROR: The sudo utility is not available! Please fix this!");
671 }
672 my $cmd_line= "$sudo_cmd su - $uid -c '$command'";
673 open(PIPE, "$cmd_line |");
674 my $result = {'resultCode' => $?};
675 $result->{'command'} = $cmd_line;
676 push @{$result->{'output'}}, <PIPE>;
677 return $result;
678 }
681 #=== FUNCTION ================================================================
682 # NAME: inform_other_si_server
683 # PARAMETERS: message
684 # RETURNS: nothing
685 # DESCRIPTION: Sends message to all other SI-server found in known_server_db.
686 #===============================================================================
687 sub inform_all_other_si_server {
688 my ($msg) = @_;
690 # determine all other si-server from known_server_db
691 my $sql_statement= "SELECT * FROM $main::known_server_tn";
692 my $res = $main::known_server_db->select_dbentry( $sql_statement );
694 while( my ($hit_num, $hit) = each %$res ) {
695 my $act_target_address = $hit->{hostname};
696 my $act_target_key = $hit->{hostkey};
698 # determine the source address corresponding to the actual target address
699 my ($act_target_ip, $act_target_port) = split(/:/, $act_target_address);
700 my $act_source_address = &main::get_local_ip_for_remote_ip($act_target_ip).":$act_target_port";
702 # fill into message the correct target and source addresses
703 my $act_msg = $msg;
704 $act_msg =~ s/<target>\w*<\/target>/<target>$act_target_address<\/target>/g;
705 $act_msg =~ s/<source>\w*<\/source>/<source>$act_source_address<\/source>/g;
707 # send message to the target
708 &main::send_msg_to_target($act_msg, $act_target_address, $act_target_key, "foreign_job_updates" , "J");
709 }
711 return;
712 }
715 sub read_configfile {
716 my ($cfg_file, %cfg_defaults) = @_ ;
717 my $cfg;
718 if( defined( $cfg_file) && ( (-s $cfg_file) > 0 )) {
719 if( -r $cfg_file ) {
720 $cfg = Config::IniFiles->new( -file => $cfg_file );
721 } else {
722 print STDERR "Couldn't read config file!";
723 }
724 } else {
725 $cfg = Config::IniFiles->new() ;
726 }
727 foreach my $section (keys %cfg_defaults) {
728 foreach my $param (keys %{$cfg_defaults{ $section }}) {
729 my $pinfo = $cfg_defaults{ $section }{ $param };
730 ${@$pinfo[ 0 ]} = $cfg->val( $section, $param, @$pinfo[ 1 ] );
731 }
732 }
733 }
736 sub check_opsi_res {
737 my $res= shift;
739 if($res) {
740 if ($res->is_error) {
741 my $error_string;
742 if (ref $res->error_message eq "HASH") {
743 $error_string = $res->error_message->{'message'};
744 } else {
745 $error_string = $res->error_message;
746 }
747 return 1, $error_string;
748 }
749 } else {
750 return 1, $main::opsi_client->status_line;
751 }
752 return 0;
753 }
756 1;