1 package GOSA::GosaSupportDaemon;
3 use strict;
4 use warnings;
6 use Exporter;
7 use IO::Socket::INET;
8 use Crypt::Rijndael;
9 use Digest::MD5 qw(md5 md5_hex md5_base64);
10 use MIME::Base64;
11 use XML::Quote qw(:all);
12 use XML::Simple;
13 use Data::Dumper;
14 use Net::DNS;
15 use Net::ARP;
16 use DateTime;
18 @ISA = qw(Exporter);
20 my @functions = (
21 "create_passwd",
22 "create_xml_hash",
23 "createXmlHash",
24 "myXmlHashToString",
25 "get_content_from_xml_hash",
26 "add_content2xml_hash",
27 "create_xml_string",
28 "transform_msg2hash",
29 "get_time",
30 "get_utc_time",
31 "build_msg",
32 "db_res2xml",
33 "db_res2si_msg",
34 "get_where_statement",
35 "get_select_statement",
36 "get_update_statement",
37 "get_limit_statement",
38 "get_orderby_statement",
39 "get_dns_domains",
40 "get_server_addresses",
41 "get_logged_in_users",
42 "import_events",
43 "del_doubles",
44 "get_ip",
45 "get_interface_for_ip",
46 "get_interfaces",
47 "get_mac_for_interface",
48 "get_local_ip_for_remote_ip",
49 "is_local",
50 "run_as",
51 "inform_all_other_si_server",
52 "read_configfile",
53 "check_opsi_res",
54 "calc_timestamp",
55 "opsi_callobj2string",
56 );
57 @EXPORT = @functions;
59 my $op_hash = {
60 'eq' => '=',
61 'ne' => '!=',
62 'ge' => '>=',
63 'gt' => '>',
64 'le' => '<=',
65 'lt' => '<',
66 'like' => ' LIKE ',
67 };
70 BEGIN {}
72 END {}
74 ### Start ######################################################################
76 our $xml = new XML::Simple();
78 sub daemon_log {
79 my ($msg, $level) = @_ ;
80 &main::daemon_log($msg, $level);
81 return;
82 }
85 sub create_passwd {
86 my $new_passwd = "";
87 for(my $i=0; $i<31; $i++) {
88 $new_passwd .= ("a".."z","A".."Z",0..9)[int(rand(62))]
89 }
91 return $new_passwd;
92 }
95 sub del_doubles {
96 my %all;
97 $all{$_}=0 for @_;
98 return (keys %all);
99 }
102 #=== FUNCTION ================================================================
103 # NAME: create_xml_hash
104 # PARAMETERS: header - string - message header (required)
105 # source - string - where the message come from (required)
106 # target - string - where the message should go to (required)
107 # [header_value] - string - something usefull (optional)
108 # RETURNS: hash - hash - nomen est omen
109 # DESCRIPTION: creates a key-value hash, all values are stored in a array
110 #===============================================================================
111 sub create_xml_hash {
112 my ($header, $source, $target, $header_value) = @_;
113 my $hash = {
114 header => [$header],
115 source => [$source],
116 target => [$target],
117 $header => [$header_value],
118 };
119 return $hash
120 }
122 sub createXmlHash {
123 my ($header, $source, $target) = @_;
124 return { header=>$header, source=>$source, target=>$target};
125 }
127 sub _transformHashToString {
128 my ($hash) = @_;
129 my $s = "";
131 while (my ($tag, $content) = each(%$hash)) {
133 if (ref $content eq "HASH") {
134 $s .= "<$tag>".&_transformHashToString($content)."</$tag>";
135 } elsif ( ref $content eq "ARRAY") {
136 $s .= &_transformArrayToString($tag, $content);
137 } else {
138 $content = defined $content ? $content : "";
139 $s .= "<$tag>".&xml_quote($content)."</$tag>";
140 }
141 }
142 return $s;
143 }
145 sub _transformArrayToString {
146 my ($tag, $contentArray) = @_;
147 my $s = "";
148 foreach my $content (@$contentArray) {
149 if (ref $content eq "HASH") {
150 $s .= "<$tag>".&_transformHashToString($content)."</$tag>";
151 } else {
152 $content = defined $content ? $content : "";
153 $s .= "<$tag>".&xml_quote($content)."</$tag>";
154 }
155 }
156 return $s;
157 }
160 #=== FUNCTION ================================================================
161 # NAME: myXmlHashToString
162 # PARAMETERS: xml_hash - hash - hash from function createXmlHash
163 # RETURNS: xml_string - string - xml string representation of the hash
164 # DESCRIPTION: Transforms the given hash to a xml wellformed string. I.e.:
165 # {
166 # 'header' => 'a'
167 # 'source' => 'c',
168 # 'target' => 'b',
169 # 'hit' => [ '1',
170 # '2',
171 # {
172 # 'hit31' => 'ABC',
173 # 'hit32' => 'XYZ'
174 # }
175 # ],
176 # 'res0' => {
177 # 'res1' => {
178 # 'res2' => 'result'
179 # }
180 # },
181 # };
182 #
183 # will be transformed to
184 # <xml>
185 # <header>a</header>
186 # <source>c</source>
187 # <target>b</target>
188 # <hit>1</hit>
189 # <hit>2</hit>
190 # <hit>
191 # <hit31>ABC</hit31>
192 # <hit32>XYZ</hit32>
193 # </hit>
194 # <res0>
195 # <res1>
196 # <res2>result</res2>
197 # </res1>
198 # </res0>
199 # </xml>
200 #
201 #===============================================================================
202 sub myXmlHashToString {
203 my ($hash) = @_;
204 return "<xml>".&_transformHashToString($hash)."</xml>";
205 }
208 #=== FUNCTION ================================================================
209 # NAME: create_xml_string
210 # PARAMETERS: xml_hash - hash - hash from function create_xml_hash
211 # RETURNS: xml_string - string - xml string representation of the hash
212 # DESCRIPTION: transform the hash to a string using XML::Simple module
213 #===============================================================================
214 sub create_xml_string {
215 my ($xml_hash) = @_ ;
216 my $xml_string = $xml->XMLout($xml_hash, RootName => 'xml');
217 #$xml_string =~ s/[\n]+//g;
218 #daemon_log("create_xml_string:",7);
219 #daemon_log("$xml_string\n", 7);
220 return $xml_string;
221 }
224 sub transform_msg2hash {
225 my ($msg) = @_ ;
226 my $hash = $xml->XMLin($msg, ForceArray=>1);
228 # xml tags without a content are created as an empty hash
229 # substitute it with an empty list
230 eval {
231 while( my ($xml_tag, $xml_content) = each %{ $hash } ) {
232 if( 1 == @{ $xml_content } ) {
233 # there is only one element in xml_content list ...
234 my $element = @{ $xml_content }[0];
235 if( ref($element) eq "HASH" ) {
236 # and this element is an hash ...
237 my $len_element = keys %{ $element };
238 if( $len_element == 0 ) {
239 # and this hash is empty, then substitute the xml_content
240 # with an empty string in list
241 $hash->{$xml_tag} = [ "none" ];
242 }
243 }
244 }
245 }
246 };
247 if( $@ ) {
248 $hash = undef;
249 }
251 return $hash;
252 }
255 #=== FUNCTION ================================================================
256 # NAME: add_content2xml_hash
257 # PARAMETERS: xml_ref - ref - reference to a hash from function create_xml_hash
258 # element - string - key for the hash
259 # content - string - value for the hash
260 # RETURNS: nothing
261 # DESCRIPTION: add key-value pair to xml_ref, if key alread exists,
262 # then append value to list
263 #===============================================================================
264 sub add_content2xml_hash {
265 my ($xml_ref, $element, $content) = @_;
266 if(not exists $$xml_ref{$element} ) {
267 $$xml_ref{$element} = [];
268 }
269 my $tmp = $$xml_ref{$element};
270 push(@$tmp, $content);
271 return;
272 }
275 sub get_time {
276 my ($seconds, $minutes, $hours, $monthday, $month,
277 $year, $weekday, $yearday, $sommertime) = localtime;
278 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
279 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
280 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
281 $month+=1;
282 $month = $month < 10 ? $month = "0".$month : $month;
283 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
284 $year+=1900;
285 return "$year$month$monthday$hours$minutes$seconds";
286 }
289 sub get_utc_time {
290 my $utc_time = qx(date --utc +%Y%m%d%H%M%S);
291 $utc_time =~ s/\s$//;
292 return $utc_time;
293 }
296 #=== FUNCTION ================================================================
297 # NAME: build_msg
298 # DESCRIPTION: Send a message to a destination
299 # PARAMETERS: [header] Name of the header
300 # [from] sender ip
301 # [to] recipient ip
302 # [data] Hash containing additional attributes for the xml
303 # package
304 # RETURNS: nothing
305 #===============================================================================
306 sub build_msg ($$$$) {
307 my ($header, $from, $to, $data) = @_;
309 # data is of form, i.e.
310 # %data= ('ip' => $address, 'mac' => $mac);
312 my $out_hash = &create_xml_hash($header, $from, $to);
314 while ( my ($key, $value) = each(%$data) ) {
315 if(ref($value) eq 'ARRAY'){
316 map(&add_content2xml_hash($out_hash, $key, $_), @$value);
317 } else {
318 &add_content2xml_hash($out_hash, $key, $value);
319 }
320 }
321 my $out_msg = &create_xml_string($out_hash);
322 return $out_msg;
323 }
326 sub db_res2xml {
327 my ($db_res) = @_ ;
328 my $xml = "";
330 my $len_db_res= keys %{$db_res};
331 for( my $i= 1; $i<= $len_db_res; $i++ ) {
332 $xml .= "\n<answer$i>";
333 my $hash= $db_res->{$i};
334 while ( my ($column_name, $column_value) = each %{$hash} ) {
335 $xml .= "<$column_name>";
336 my $xml_content;
337 if( $column_name eq "xmlmessage" ) {
338 $xml_content = &encode_base64($column_value);
339 } else {
340 $xml_content = defined $column_value ? $column_value : "";
341 }
342 $xml .= $xml_content;
343 $xml .= "</$column_name>";
344 }
345 $xml .= "</answer$i>";
347 }
349 return $xml;
350 }
353 sub db_res2si_msg {
354 my ($db_res, $header, $target, $source) = @_;
356 my $si_msg = "<xml>";
357 $si_msg .= "<header>$header</header>";
358 $si_msg .= "<source>$source</source>";
359 $si_msg .= "<target>$target</target>";
360 $si_msg .= &db_res2xml;
361 $si_msg .= "</xml>";
362 }
365 sub get_where_statement {
366 my ($msg, $msg_hash) = @_;
367 my $error= 0;
369 my $clause_str= "";
370 if( (not exists $msg_hash->{'where'}) || (not exists @{$msg_hash->{'where'}}[0]->{'clause'}) ) {
371 $error++;
372 }
374 if( $error == 0 ) {
375 my @clause_l;
376 my @where = @{@{$msg_hash->{'where'}}[0]->{'clause'}};
377 foreach my $clause (@where) {
378 my $connector = $clause->{'connector'}[0];
379 if( not defined $connector ) { $connector = "AND"; }
380 $connector = uc($connector);
381 delete($clause->{'connector'});
383 my @phrase_l ;
384 foreach my $phrase (@{$clause->{'phrase'}}) {
385 my $operator = "=";
386 if( exists $phrase->{'operator'} ) {
387 my $op = $op_hash->{$phrase->{'operator'}[0]};
388 if( not defined $op ) {
389 &main::daemon_log("ERROR: Can not translate operator '$operator' in where-".
390 "statement to sql valid syntax. Please use 'eq', ".
391 "'ne', 'ge', 'gt', 'le', 'lt' in xml message\n", 1);
392 &main::daemon_log($msg, 8);
393 $op = "=";
394 }
395 $operator = $op;
396 delete($phrase->{'operator'});
397 }
399 my @xml_tags = keys %{$phrase};
400 my $tag = $xml_tags[0];
401 my $val = $phrase->{$tag}[0];
402 if( ref($val) eq "HASH" ) { next; } # empty xml-tags should not appear in where statement
404 # integer columns do not have to have single quotes besides the value
405 if ($tag eq "id") {
406 push(@phrase_l, "$tag$operator$val");
407 } else {
408 push(@phrase_l, "$tag$operator'$val'");
409 }
410 }
412 if (not 0 == @phrase_l) {
413 my $clause_str .= join(" $connector ", @phrase_l);
414 push(@clause_l, "($clause_str)");
415 }
416 }
418 if( not 0 == @clause_l ) {
419 $clause_str = join(" AND ", @clause_l);
420 $clause_str = "WHERE ($clause_str) ";
421 }
422 }
424 return $clause_str;
425 }
427 sub get_select_statement {
428 my ($msg, $msg_hash)= @_;
429 my $select = "*";
430 if( exists $msg_hash->{'select'} ) {
431 my $select_l = \@{$msg_hash->{'select'}};
432 $select = join(', ', @{$select_l});
433 }
434 return $select;
435 }
438 sub get_update_statement {
439 my ($msg, $msg_hash) = @_;
440 my $error= 0;
441 my $update_str= "";
442 my @update_l;
444 if( not exists $msg_hash->{'update'} ) { $error++; };
446 if( $error == 0 ) {
447 my $update= @{$msg_hash->{'update'}}[0];
448 while( my ($tag, $val) = each %{$update} ) {
449 my $val= @{$update->{$tag}}[0];
450 push(@update_l, "$tag='$val'");
451 }
452 if( 0 == @update_l ) { $error++; };
453 }
455 if( $error == 0 ) {
456 $update_str= join(', ', @update_l);
457 $update_str= "SET $update_str ";
458 }
460 return $update_str;
461 }
463 sub get_limit_statement {
464 my ($msg, $msg_hash)= @_;
465 my $error= 0;
466 my $limit_str = "";
467 my ($from, $to);
469 if( not exists $msg_hash->{'limit'} ) { $error++; };
471 if( $error == 0 ) {
472 eval {
473 my $limit= @{$msg_hash->{'limit'}}[0];
474 $from= @{$limit->{'from'}}[0];
475 $to= @{$limit->{'to'}}[0];
476 };
477 if( $@ ) {
478 $error++;
479 }
480 }
482 if( $error == 0 ) {
483 $limit_str= "LIMIT $from, $to";
484 }
486 return $limit_str;
487 }
489 sub get_orderby_statement {
490 my ($msg, $msg_hash)= @_;
491 my $error= 0;
492 my $order_str= "";
493 my $order;
495 if( not exists $msg_hash->{'orderby'} ) { $error++; };
497 if( $error == 0) {
498 eval {
499 $order= @{$msg_hash->{'orderby'}}[0];
500 };
501 if( $@ ) {
502 $error++;
503 }
504 }
506 if( $error == 0 ) {
507 $order_str= "ORDER BY $order";
508 }
510 return $order_str;
511 }
513 sub get_dns_domains() {
514 my $line;
515 my @searches;
516 open($RESOLV, "<", "/etc/resolv.conf") or return @searches;
517 while(<$RESOLV>){
518 $line= $_;
519 chomp $line;
520 $line =~ s/^\s+//;
521 $line =~ s/\s+$//;
522 $line =~ s/\s+/ /;
523 if ($line =~ /^domain (.*)$/ ){
524 push(@searches, $1);
525 } elsif ($line =~ /^search (.*)$/ ){
526 push(@searches, split(/ /, $1));
527 }
528 }
529 close($RESOLV);
531 my %tmp = map { $_ => 1 } @searches;
532 @searches = sort keys %tmp;
534 return @searches;
535 }
538 sub get_server_addresses {
539 my $domain= shift;
540 my @result;
541 my $error_string;
543 my $error = 0;
544 my $res = Net::DNS::Resolver->new;
545 my $query = $res->send("_gosa-si._tcp.".$domain, "SRV");
546 my @hits;
548 if ($query) {
549 foreach my $rr ($query->answer) {
550 push(@hits, $rr->target.":".$rr->port);
551 }
552 }
553 else {
554 $error_string = "determination of '_gosa-si._tcp' server in domain '$domain' failed: ".$res->errorstring;
555 $error++;
556 }
558 if( $error == 0 ) {
559 foreach my $hit (@hits) {
560 my ($hit_name, $hit_port) = split(/:/, $hit);
561 chomp($hit_name);
562 chomp($hit_port);
564 my $address_query = $res->send($hit_name);
565 if( 1 == length($address_query->answer) ) {
566 foreach my $rr ($address_query->answer) {
567 push(@result, $rr->address.":".$hit_port);
568 }
569 }
570 }
571 }
573 return \@result, $error_string;
574 }
577 sub get_logged_in_users {
578 my $result = qx(/usr/bin/w -hs);
579 my @res_lines;
581 if( defined $result ) {
582 chomp($result);
583 @res_lines = split("\n", $result);
584 }
586 my @logged_in_user_list;
587 foreach my $line (@res_lines) {
588 chomp($line);
589 my @line_parts = split(/\s+/, $line);
590 push(@logged_in_user_list, $line_parts[0]);
591 }
593 return @logged_in_user_list;
595 }
598 sub import_events {
599 my ($event_dir) = @_;
600 my $event_hash;
601 my $error = 0;
602 my @result = ();
603 if (not -e $event_dir) {
604 $error++;
605 push(@result, "cannot find directory or directory is not readable: $event_dir");
606 }
608 my $DIR;
609 if ($error == 0) {
610 opendir ($DIR, $event_dir) or do {
611 $error++;
612 push(@result, "cannot open directory '$event_dir' for reading: $!\n");
613 }
614 }
616 if ($error == 0) {
617 while (defined (my $event = readdir ($DIR))) {
618 if( $event eq "." || $event eq ".." || ($event =~ /^\.pm$/)) { next; }
620 # Check config file to exclude disabled event plugins (i.e. Opsi)
621 if ($event eq "opsi_com.pm" && $main::opsi_enabled ne "true") {
622 &main::daemon_log("0 WARNING: opsi-module is installed but not enabled in config file, please set under section '[OPSI]': 'enabled=true'", 3);
623 next;
624 }
626 # try to import event module
627 eval{ require $event; };
628 if( $@ ) {
629 $error++;
630 #push(@result, "import of event module '$event' failed: $@");
631 #next;
633 &main::daemon_log("ERROR: Import of event module '$event' failed: $@",1);
634 exit(1);
635 }
637 # fetch all single events
638 $event =~ /(\S*?).pm$/;
639 my $event_module = $1;
640 my $events_l = eval( $1."::get_events()") ;
641 foreach my $event_name (@{$events_l}) {
642 $event_hash->{$event_module}->{$event_name} = "";
643 }
644 my $events_string = join( ", ", @{$events_l});
645 push(@result, "import of event module '$event' succeed: $events_string");
646 }
648 close $DIR;
649 }
651 return ($error, \@result, $event_hash);
653 }
656 #=== FUNCTION ================================================================
657 # NAME: get_ip
658 # PARAMETERS: interface name (i.e. eth0)
659 # RETURNS: (ip address)
660 # DESCRIPTION: Uses ioctl to get ip address directly from system.
661 #===============================================================================
662 sub get_ip {
663 my $ifreq= shift;
664 my $result= "";
665 my $SIOCGIFADDR= 0x8915; # man 2 ioctl_list
666 my $proto= getprotobyname('ip');
668 socket SOCKET, PF_INET, SOCK_DGRAM, $proto
669 or die "socket: $!";
671 if(ioctl SOCKET, $SIOCGIFADDR, $ifreq) {
672 my ($if, $sin) = unpack 'a16 a16', $ifreq;
673 my ($port, $addr) = sockaddr_in $sin;
674 my $ip = inet_ntoa $addr;
676 if ($ip && length($ip) > 0) {
677 $result = $ip;
678 }
679 }
681 return $result;
682 }
685 #=== FUNCTION ================================================================
686 # NAME: get_interface_for_ip
687 # PARAMETERS: ip address (i.e. 192.168.0.1)
688 # RETURNS: array: list of interfaces if ip=0.0.0.0, matching interface if found, undef else
689 # DESCRIPTION: Uses proc fs (/proc/net/dev) to get list of interfaces.
690 #===============================================================================
691 sub get_interface_for_ip {
692 my $result;
693 my $ip= shift;
695 if($ip =~ /^[a-z]/i) {
696 my $ip_address = inet_ntoa(scalar gethostbyname($ip));
697 if(defined($ip_address) && $ip_address =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/) {
698 # Write ip address to $source variable
699 $ip = $ip_address;
700 }
701 }
703 if ($ip && length($ip) > 0) {
704 my @ifs= &get_interfaces();
705 if($ip eq "0.0.0.0") {
706 $result = "all";
707 } else {
708 foreach (@ifs) {
709 my $if=$_;
710 if(&get_ip($if) eq $ip) {
711 $result = $if;
712 }
713 }
714 }
715 }
716 return $result;
717 }
719 #=== FUNCTION ================================================================
720 # NAME: get_interfaces
721 # PARAMETERS: none
722 # RETURNS: (list of interfaces)
723 # DESCRIPTION: Uses proc fs (/proc/net/dev) to get list of interfaces.
724 #===============================================================================
725 sub get_interfaces {
726 my @result;
727 my $PROC_NET_DEV= ('/proc/net/dev');
729 open($FD_PROC_NET_DEV, "<", "$PROC_NET_DEV")
730 or die "Could not open $PROC_NET_DEV";
732 my @ifs = <$FD_PROC_NET_DEV>;
734 close($FD_PROC_NET_DEV);
736 # Eat first two line
737 shift @ifs;
738 shift @ifs;
740 chomp @ifs;
741 foreach my $line(@ifs) {
742 my $if= (split /:/, $line)[0];
743 $if =~ s/^\s+//;
744 push @result, $if;
745 }
747 return @result;
748 }
750 sub get_local_ip_for_remote_ip {
751 my $remote_ip= shift;
752 my $result="0.0.0.0";
754 if($remote_ip =~ /^(\d\d?\d?\.){3}\d\d?\d?$/) {
755 my $PROC_NET_ROUTE= ('/proc/net/route');
757 open($FD_PROC_NET_ROUTE, "<", "$PROC_NET_ROUTE")
758 or die "Could not open $PROC_NET_ROUTE";
760 my @ifs = <$FD_PROC_NET_ROUTE>;
762 close($FD_PROC_NET_ROUTE);
764 # Eat header line
765 shift @ifs;
766 chomp @ifs;
767 my $iffallback = '';
769 # linux-vserver might have * as Iface due to hidden interfaces, set a default
770 foreach my $line(@ifs) {
771 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
772 if ($Iface =~ m/^[^\*]+$/) {
773 $iffallback = $Iface;
774 }
775 }
777 foreach my $line(@ifs) {
778 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
779 my $destination;
780 my $mask;
781 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
782 if ($Iface =~ m/^[^\*]+$/) {
783 $iffallback = $Iface;
784 }
785 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
786 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
787 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
788 if(new NetAddr::IP($remote_ip)->within(new NetAddr::IP($destination, $mask))) {
789 # destination matches route, save mac and exit
790 #$result= &get_ip($Iface);
792 if ($Iface =~ m/^\*$/ ) {
793 $result= &get_ip($iffallback);
794 } else {
795 $result= &get_ip($Iface);
796 }
797 last;
798 }
799 }
800 }
802 return $result;
803 }
806 sub get_mac_for_interface {
807 my $ifreq= shift;
808 my $result;
809 if ($ifreq && length($ifreq) > 0) {
810 if($ifreq eq "all") {
811 $result = "00:00:00:00:00:00";
812 } else {
813 $result = Net::ARP::get_mac($ifreq);
814 }
815 }
816 return $result;
817 }
820 #=== FUNCTION ================================================================
821 # NAME: is_local
822 # PARAMETERS: Server Address
823 # RETURNS: true if Server Address is on this host, false otherwise
824 # DESCRIPTION: Checks all interface addresses, stops on first match
825 #===============================================================================
826 sub is_local {
827 my $server_address = shift || "";
828 my $result = 0;
830 my $server_ip = $1 if $server_address =~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):\d{1,6}$/;
832 if(defined($server_ip) && length($server_ip) > 0) {
833 foreach my $interface(&get_interfaces()) {
834 my $ip_address= &get_ip($interface);
835 if($ip_address eq $server_ip) {
836 $result = 1;
837 last;
838 }
839 }
840 }
842 return $result;
843 }
846 #=== FUNCTION ================================================================
847 # NAME: run_as
848 # PARAMETERS: uid, command
849 # RETURNS: hash with keys 'resultCode' = resultCode of command and
850 # 'output' = program output
851 # DESCRIPTION: Runs command as uid using the sudo utility.
852 #===============================================================================
853 sub run_as {
854 my ($uid, $command) = @_;
855 my $sudo_cmd = `which sudo`;
856 chomp($sudo_cmd);
857 if(! -x $sudo_cmd) {
858 &main::daemon_log("ERROR: The sudo utility is not available! Please fix this!");
859 }
860 my $cmd_line= "$sudo_cmd su - $uid -c '$command'";
861 open($PIPE, "$cmd_line |");
862 my $result = {'command' => $cmd_line};
863 push @{$result->{'output'}}, <$PIPE>;
864 close($PIPE);
865 my $exit_value = $? >> 8;
866 $result->{'resultCode'} = $exit_value;
867 return $result;
868 }
871 #=== FUNCTION ================================================================
872 # NAME: inform_other_si_server
873 # PARAMETERS: message
874 # RETURNS: nothing
875 # DESCRIPTION: Sends message to all other SI-server found in known_server_db.
876 #===============================================================================
877 sub inform_all_other_si_server {
878 my ($msg) = @_;
880 # determine all other si-server from known_server_db
881 my $sql_statement= "SELECT * FROM $main::known_server_tn";
882 my $res = $main::known_server_db->select_dbentry( $sql_statement );
884 while( my ($hit_num, $hit) = each %$res ) {
885 my $act_target_address = $hit->{hostname};
886 my $act_target_key = $hit->{hostkey};
888 # determine the source address corresponding to the actual target address
889 my ($act_target_ip, $act_target_port) = split(/:/, $act_target_address);
890 my $act_source_address = &main::get_local_ip_for_remote_ip($act_target_ip).":$act_target_port";
892 # fill into message the correct target and source addresses
893 my $act_msg = $msg;
894 $act_msg =~ s/<target>\w*<\/target>/<target>$act_target_address<\/target>/g;
895 $act_msg =~ s/<source>\w*<\/source>/<source>$act_source_address<\/source>/g;
897 # send message to the target
898 &main::send_msg_to_target($act_msg, $act_target_address, $act_target_key, "foreign_job_updates" , "J");
899 }
901 return;
902 }
905 sub read_configfile {
906 my ($cfg_file, %cfg_defaults) = @_ ;
907 my $cfg;
908 if( defined( $cfg_file) && ( (-s $cfg_file) > 0 )) {
909 if( -r $cfg_file ) {
910 $cfg = Config::IniFiles->new( -file => $cfg_file, -nocase => 1 );
911 } else {
912 print STDERR "Couldn't read config file!";
913 }
914 } else {
915 $cfg = Config::IniFiles->new() ;
916 }
917 foreach my $section (keys %cfg_defaults) {
918 foreach my $param (keys %{$cfg_defaults{ $section }}) {
919 my $pinfo = $cfg_defaults{ $section }{ $param };
920 ${@$pinfo[ 0 ]} = $cfg->val( $section, $param, @$pinfo[ 1 ] );
921 }
922 }
923 }
926 sub check_opsi_res {
927 my $res= shift;
929 if($res) {
930 if ($res->is_error) {
931 my $error_string;
932 if (ref $res->error_message eq "HASH") {
933 # for different versions
934 $error_string = $res->error_message->{'message'};
935 $_ = $res->error_message->{'message'};
936 } else {
937 # for different versions
938 $error_string = $res->error_message;
939 $_ = $res->error_message;
940 }
941 return 1, $error_string;
942 }
943 } else {
944 # for different versions
945 $_ = $main::opsi_client->status_line;
946 return 1, $main::opsi_client->status_line;
947 }
948 return 0;
949 }
951 sub calc_timestamp {
952 my ($timestamp, $operation, $value, $entity) = @_ ;
953 $entity = defined $entity ? $entity : "seconds";
954 my $res_timestamp = 0;
956 $value = int($value);
957 $timestamp = int($timestamp);
958 $timestamp =~ /(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)/;
959 my $dt = DateTime->new( year => $1,
960 month => $2,
961 day => $3,
962 hour => $4,
963 minute => $5,
964 second => $6,
965 );
967 if ($operation eq "plus" || $operation eq "+") {
968 $dt->add($entity => $value);
969 $res_timestamp = $dt->ymd('').$dt->hms('');
970 }
972 if ($operation eq "minus" || $operation eq "-") {
973 $dt->subtract($entity => $value);
974 $res_timestamp = $dt->ymd('').$dt->hms('');
975 }
977 return $res_timestamp;
978 }
980 sub opsi_callobj2string {
981 my ($callobj) = @_;
982 my @callobj_string;
983 while(my ($key, $value) = each(%$callobj)) {
984 my $value_string = "";
985 if (ref($value) eq "ARRAY") {
986 $value_string = join(",", @$value);
987 } else {
988 $value_string = $value;
989 }
990 push(@callobj_string, "$key=$value_string")
991 }
992 return join(", ", @callobj_string);
993 }
995 1;