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