4c46c58e26fc43b649f456a11505c1d6e0e1f59d
1 package GOSA::GosaSupportDaemon;
3 use Exporter;
4 @ISA = qw(Exporter);
5 my @functions = (
6 "create_passwd",
7 "create_xml_hash",
8 "createXmlHash",
9 "myXmlHashToString",
10 "get_content_from_xml_hash",
11 "add_content2xml_hash",
12 "create_xml_string",
13 "transform_msg2hash",
14 "get_time",
15 "get_utc_time",
16 "build_msg",
17 "db_res2xml",
18 "db_res2si_msg",
19 "get_where_statement",
20 "get_select_statement",
21 "get_update_statement",
22 "get_limit_statement",
23 "get_orderby_statement",
24 "get_dns_domains",
25 "get_server_addresses",
26 "get_logged_in_users",
27 "import_events",
28 "del_doubles",
29 "get_ip",
30 "get_interface_for_ip",
31 "get_interfaces",
32 "get_mac_for_interface",
33 "get_local_ip_for_remote_ip",
34 "is_local",
35 "run_as",
36 "inform_all_other_si_server",
37 "read_configfile",
38 "check_opsi_res",
39 "calc_timestamp",
40 "opsi_callobj2string",
41 );
42 @EXPORT = @functions;
43 use strict;
44 use warnings;
45 use IO::Socket::INET;
46 use Crypt::Rijndael;
47 use Digest::MD5 qw(md5 md5_hex md5_base64);
48 use MIME::Base64;
49 use XML::Simple;
50 use Data::Dumper;
51 use Net::DNS;
52 use DateTime;
54 my $op_hash = {
55 'eq' => '=',
56 'ne' => '!=',
57 'ge' => '>=',
58 'gt' => '>',
59 'le' => '<=',
60 'lt' => '<',
61 'like' => ' LIKE ',
62 };
65 BEGIN {}
67 END {}
69 ### Start ######################################################################
71 my $xml = new XML::Simple();
73 sub daemon_log {
74 my ($msg, $level) = @_ ;
75 &main::daemon_log($msg, $level);
76 return;
77 }
80 sub create_passwd {
81 my $new_passwd = "";
82 for(my $i=0; $i<31; $i++) {
83 $new_passwd .= ("a".."z","A".."Z",0..9)[int(rand(62))]
84 }
86 return $new_passwd;
87 }
90 sub del_doubles {
91 my %all;
92 $all{$_}=0 for @_;
93 return (keys %all);
94 }
97 #=== FUNCTION ================================================================
98 # NAME: create_xml_hash
99 # PARAMETERS: header - string - message header (required)
100 # source - string - where the message come from (required)
101 # target - string - where the message should go to (required)
102 # [header_value] - string - something usefull (optional)
103 # RETURNS: hash - hash - nomen est omen
104 # DESCRIPTION: creates a key-value hash, all values are stored in a array
105 #===============================================================================
106 sub create_xml_hash {
107 my ($header, $source, $target, $header_value) = @_;
108 my $hash = {
109 header => [$header],
110 source => [$source],
111 target => [$target],
112 $header => [$header_value],
113 };
114 return $hash
115 }
117 sub createXmlHash {
118 my ($header, $source, $target) = @_;
119 return { header=>$header, source=>$source, target=>$target};
120 }
122 sub _transformHashToString {
123 my ($hash) = @_;
124 my $s = "";
126 while (my ($tag, $content) = each(%$hash)) {
128 if (ref $content eq "HASH") {
129 $s .= "<$tag>".&_transformHashToString($content)."</$tag>";
130 } elsif ( ref $content eq "ARRAY") {
131 $s .= &_transformArrayToString($tag, $content);
132 } else {
133 $s .= "<$tag>".$content."</$tag>";
134 }
135 }
136 return $s;
137 }
139 sub _transformArrayToString {
140 my ($tag, $contentArray) = @_;
141 my $s = "";
142 foreach my $content (@$contentArray) {
143 if (ref $content eq "HASH") {
144 $s .= "<$tag>".&_transformHashToString($content)."</$tag>";
145 } else {
146 $s .= "<$tag>$content</$tag>";
147 }
148 }
149 return $s;
150 }
153 #=== FUNCTION ================================================================
154 # NAME: myXmlHashToString
155 # PARAMETERS: xml_hash - hash - hash from function createXmlHash
156 # RETURNS: xml_string - string - xml string representation of the hash
157 # DESCRIPTION: Transforms the given hash to a xml wellformed string. I.e.:
158 # {
159 # 'header' => 'a'
160 # 'source' => 'c',
161 # 'target' => 'b',
162 # 'hit' => [ '1',
163 # '2',
164 # {
165 # 'hit31' => 'ABC',
166 # 'hit32' => 'XYZ'
167 # }
168 # ],
169 # 'res0' => {
170 # 'res1' => {
171 # 'res2' => 'result'
172 # }
173 # },
174 # };
175 #
176 # will be transformed to
177 # <xml>
178 # <header>a</header>
179 # <source>c</source>
180 # <target>b</target>
181 # <hit>1</hit>
182 # <hit>2</hit>
183 # <hit>
184 # <hit31>ABC</hit31>
185 # <hit32>XYZ</hit32>
186 # </hit>
187 # <res0>
188 # <res1>
189 # <res2>result</res2>
190 # </res1>
191 # </res0>
192 # </xml>
193 #
194 #===============================================================================
195 sub myXmlHashToString {
196 my ($hash) = @_;
197 return "<xml>".&_transformHashToString($hash)."</xml>";
198 }
201 #=== FUNCTION ================================================================
202 # NAME: create_xml_string
203 # PARAMETERS: xml_hash - hash - hash from function create_xml_hash
204 # RETURNS: xml_string - string - xml string representation of the hash
205 # DESCRIPTION: transform the hash to a string using XML::Simple module
206 #===============================================================================
207 sub create_xml_string {
208 my ($xml_hash) = @_ ;
209 my $xml_string = $xml->XMLout($xml_hash, RootName => 'xml');
210 #$xml_string =~ s/[\n]+//g;
211 #daemon_log("create_xml_string:",7);
212 #daemon_log("$xml_string\n", 7);
213 return $xml_string;
214 }
217 sub transform_msg2hash {
218 my ($msg) = @_ ;
219 my $hash = $xml->XMLin($msg, ForceArray=>1);
221 # xml tags without a content are created as an empty hash
222 # substitute it with an empty list
223 eval {
224 while( my ($xml_tag, $xml_content) = each %{ $hash } ) {
225 if( 1 == @{ $xml_content } ) {
226 # there is only one element in xml_content list ...
227 my $element = @{ $xml_content }[0];
228 if( ref($element) eq "HASH" ) {
229 # and this element is an hash ...
230 my $len_element = keys %{ $element };
231 if( $len_element == 0 ) {
232 # and this hash is empty, then substitute the xml_content
233 # with an empty string in list
234 $hash->{$xml_tag} = [ "none" ];
235 }
236 }
237 }
238 }
239 };
240 if( $@ ) {
241 $hash = undef;
242 }
244 return $hash;
245 }
248 #=== FUNCTION ================================================================
249 # NAME: add_content2xml_hash
250 # PARAMETERS: xml_ref - ref - reference to a hash from function create_xml_hash
251 # element - string - key for the hash
252 # content - string - value for the hash
253 # RETURNS: nothing
254 # DESCRIPTION: add key-value pair to xml_ref, if key alread exists,
255 # then append value to list
256 #===============================================================================
257 sub add_content2xml_hash {
258 my ($xml_ref, $element, $content) = @_;
259 if(not exists $$xml_ref{$element} ) {
260 $$xml_ref{$element} = [];
261 }
262 my $tmp = $$xml_ref{$element};
263 push(@$tmp, $content);
264 return;
265 }
268 sub get_time {
269 my ($seconds, $minutes, $hours, $monthday, $month,
270 $year, $weekday, $yearday, $sommertime) = localtime;
271 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
272 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
273 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
274 $month+=1;
275 $month = $month < 10 ? $month = "0".$month : $month;
276 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
277 $year+=1900;
278 return "$year$month$monthday$hours$minutes$seconds";
279 }
282 sub get_utc_time {
283 my $utc_time = qx(date --utc +%Y%m%d%H%M%S);
284 $utc_time =~ s/\s$//;
285 return $utc_time;
286 }
289 #=== FUNCTION ================================================================
290 # NAME: build_msg
291 # DESCRIPTION: Send a message to a destination
292 # PARAMETERS: [header] Name of the header
293 # [from] sender ip
294 # [to] recipient ip
295 # [data] Hash containing additional attributes for the xml
296 # package
297 # RETURNS: nothing
298 #===============================================================================
299 sub build_msg ($$$$) {
300 my ($header, $from, $to, $data) = @_;
302 # data is of form, i.e.
303 # %data= ('ip' => $address, 'mac' => $mac);
305 my $out_hash = &create_xml_hash($header, $from, $to);
307 while ( my ($key, $value) = each(%$data) ) {
308 if(ref($value) eq 'ARRAY'){
309 map(&add_content2xml_hash($out_hash, $key, $_), @$value);
310 } else {
311 &add_content2xml_hash($out_hash, $key, $value);
312 }
313 }
314 my $out_msg = &create_xml_string($out_hash);
315 return $out_msg;
316 }
319 sub db_res2xml {
320 my ($db_res) = @_ ;
321 my $xml = "";
323 my $len_db_res= keys %{$db_res};
324 for( my $i= 1; $i<= $len_db_res; $i++ ) {
325 $xml .= "\n<answer$i>";
326 my $hash= $db_res->{$i};
327 while ( my ($column_name, $column_value) = each %{$hash} ) {
328 $xml .= "<$column_name>";
329 my $xml_content;
330 if( $column_name eq "xmlmessage" ) {
331 $xml_content = &encode_base64($column_value);
332 } else {
333 $xml_content = defined $column_value ? $column_value : "";
334 }
335 $xml .= $xml_content;
336 $xml .= "</$column_name>";
337 }
338 $xml .= "</answer$i>";
340 }
342 return $xml;
343 }
346 sub db_res2si_msg {
347 my ($db_res, $header, $target, $source) = @_;
349 my $si_msg = "<xml>";
350 $si_msg .= "<header>$header</header>";
351 $si_msg .= "<source>$source</source>";
352 $si_msg .= "<target>$target</target>";
353 $si_msg .= &db_res2xml;
354 $si_msg .= "</xml>";
355 }
358 sub get_where_statement {
359 my ($msg, $msg_hash) = @_;
360 my $error= 0;
362 my $clause_str= "";
363 if( (not exists $msg_hash->{'where'}) || (not exists @{$msg_hash->{'where'}}[0]->{'clause'}) ) {
364 $error++;
365 }
367 if( $error == 0 ) {
368 my @clause_l;
369 my @where = @{@{$msg_hash->{'where'}}[0]->{'clause'}};
370 foreach my $clause (@where) {
371 my $connector = $clause->{'connector'}[0];
372 if( not defined $connector ) { $connector = "AND"; }
373 $connector = uc($connector);
374 delete($clause->{'connector'});
376 my @phrase_l ;
377 foreach my $phrase (@{$clause->{'phrase'}}) {
378 my $operator = "=";
379 if( exists $phrase->{'operator'} ) {
380 my $op = $op_hash->{$phrase->{'operator'}[0]};
381 if( not defined $op ) {
382 &main::daemon_log("ERROR: Can not translate operator '$operator' in where-".
383 "statement to sql valid syntax. Please use 'eq', ".
384 "'ne', 'ge', 'gt', 'le', 'lt' in xml message\n", 1);
385 &main::daemon_log($msg, 8);
386 $op = "=";
387 }
388 $operator = $op;
389 delete($phrase->{'operator'});
390 }
392 my @xml_tags = keys %{$phrase};
393 my $tag = $xml_tags[0];
394 my $val = $phrase->{$tag}[0];
395 if( ref($val) eq "HASH" ) { next; } # empty xml-tags should not appear in where statement
397 # integer columns do not have to have single quotes besides the value
398 if ($tag eq "id") {
399 push(@phrase_l, "$tag$operator$val");
400 } else {
401 push(@phrase_l, "$tag$operator'$val'");
402 }
403 }
405 if (not 0 == @phrase_l) {
406 my $clause_str .= join(" $connector ", @phrase_l);
407 push(@clause_l, "($clause_str)");
408 }
409 }
411 if( not 0 == @clause_l ) {
412 $clause_str = join(" AND ", @clause_l);
413 $clause_str = "WHERE ($clause_str) ";
414 }
415 }
417 return $clause_str;
418 }
420 sub get_select_statement {
421 my ($msg, $msg_hash)= @_;
422 my $select = "*";
423 if( exists $msg_hash->{'select'} ) {
424 my $select_l = \@{$msg_hash->{'select'}};
425 $select = join(', ', @{$select_l});
426 }
427 return $select;
428 }
431 sub get_update_statement {
432 my ($msg, $msg_hash) = @_;
433 my $error= 0;
434 my $update_str= "";
435 my @update_l;
437 if( not exists $msg_hash->{'update'} ) { $error++; };
439 if( $error == 0 ) {
440 my $update= @{$msg_hash->{'update'}}[0];
441 while( my ($tag, $val) = each %{$update} ) {
442 my $val= @{$update->{$tag}}[0];
443 push(@update_l, "$tag='$val'");
444 }
445 if( 0 == @update_l ) { $error++; };
446 }
448 if( $error == 0 ) {
449 $update_str= join(', ', @update_l);
450 $update_str= "SET $update_str ";
451 }
453 return $update_str;
454 }
456 sub get_limit_statement {
457 my ($msg, $msg_hash)= @_;
458 my $error= 0;
459 my $limit_str = "";
460 my ($from, $to);
462 if( not exists $msg_hash->{'limit'} ) { $error++; };
464 if( $error == 0 ) {
465 eval {
466 my $limit= @{$msg_hash->{'limit'}}[0];
467 $from= @{$limit->{'from'}}[0];
468 $to= @{$limit->{'to'}}[0];
469 };
470 if( $@ ) {
471 $error++;
472 }
473 }
475 if( $error == 0 ) {
476 $limit_str= "LIMIT $from, $to";
477 }
479 return $limit_str;
480 }
482 sub get_orderby_statement {
483 my ($msg, $msg_hash)= @_;
484 my $error= 0;
485 my $order_str= "";
486 my $order;
488 if( not exists $msg_hash->{'orderby'} ) { $error++; };
490 if( $error == 0) {
491 eval {
492 $order= @{$msg_hash->{'orderby'}}[0];
493 };
494 if( $@ ) {
495 $error++;
496 }
497 }
499 if( $error == 0 ) {
500 $order_str= "ORDER BY $order";
501 }
503 return $order_str;
504 }
506 sub get_dns_domains() {
507 my $line;
508 my @searches;
509 open(RESOLV, "</etc/resolv.conf") or return @searches;
510 while(<RESOLV>){
511 $line= $_;
512 chomp $line;
513 $line =~ s/^\s+//;
514 $line =~ s/\s+$//;
515 $line =~ s/\s+/ /;
516 if ($line =~ /^domain (.*)$/ ){
517 push(@searches, $1);
518 } elsif ($line =~ /^search (.*)$/ ){
519 push(@searches, split(/ /, $1));
520 }
521 }
522 close(RESOLV);
524 my %tmp = map { $_ => 1 } @searches;
525 @searches = sort keys %tmp;
527 return @searches;
528 }
531 sub get_server_addresses {
532 my $domain= shift;
533 my @result;
534 my $error_string;
536 my $error = 0;
537 my $res = Net::DNS::Resolver->new;
538 my $query = $res->send("_gosa-si._tcp.".$domain, "SRV");
539 my @hits;
541 if ($query) {
542 foreach my $rr ($query->answer) {
543 push(@hits, $rr->target.":".$rr->port);
544 }
545 }
546 else {
547 $error_string = "determination of '_gosa-si._tcp' server in domain '$domain' failed: ".$res->errorstring;
548 $error++;
549 }
551 if( $error == 0 ) {
552 foreach my $hit (@hits) {
553 my ($hit_name, $hit_port) = split(/:/, $hit);
554 chomp($hit_name);
555 chomp($hit_port);
557 my $address_query = $res->send($hit_name);
558 if( 1 == length($address_query->answer) ) {
559 foreach my $rr ($address_query->answer) {
560 push(@result, $rr->address.":".$hit_port);
561 }
562 }
563 }
564 }
566 return \@result, $error_string;
567 }
570 sub get_logged_in_users {
571 my $result = qx(/usr/bin/w -hs);
572 my @res_lines;
574 if( defined $result ) {
575 chomp($result);
576 @res_lines = split("\n", $result);
577 }
579 my @logged_in_user_list;
580 foreach my $line (@res_lines) {
581 chomp($line);
582 my @line_parts = split(/\s+/, $line);
583 push(@logged_in_user_list, $line_parts[0]);
584 }
586 return @logged_in_user_list;
588 }
591 sub import_events {
592 my ($event_dir) = @_;
593 my $event_hash;
594 my $error = 0;
595 my @result = ();
596 if (not -e $event_dir) {
597 $error++;
598 push(@result, "cannot find directory or directory is not readable: $event_dir");
599 }
601 my $DIR;
602 if ($error == 0) {
603 opendir ($DIR, $event_dir) or do {
604 $error++;
605 push(@result, "cannot open directory '$event_dir' for reading: $!\n");
606 }
607 }
609 if ($error == 0) {
610 while (defined (my $event = readdir ($DIR))) {
611 if( $event eq "." || $event eq ".." || ($event =~ /^\.pm$/)) { next; }
613 # Check config file to exclude disabled event plugins (i.e. Opsi)
614 if ($event eq "opsi_com.pm" && $main::opsi_enabled ne "true") {
615 &main::daemon_log("0 WARNING: opsi-module is installed but not enabled in config file, please set under section '[OPSI]': 'enabled=true'", 3);
616 next;
617 }
619 # try to import event module
620 eval{ require $event; };
621 if( $@ ) {
622 $error++;
623 #push(@result, "import of event module '$event' failed: $@");
624 #next;
626 &main::daemon_log("ERROR: Import of event module '$event' failed: $@",1);
627 exit(1);
628 }
630 # fetch all single events
631 $event =~ /(\S*?).pm$/;
632 my $event_module = $1;
633 my $events_l = eval( $1."::get_events()") ;
634 foreach my $event_name (@{$events_l}) {
635 $event_hash->{$event_module}->{$event_name} = "";
636 }
637 my $events_string = join( ", ", @{$events_l});
638 push(@result, "import of event module '$event' succeed: $events_string");
639 }
641 close $DIR;
642 }
644 return ($error, \@result, $event_hash);
646 }
649 #=== FUNCTION ================================================================
650 # NAME: get_ip
651 # PARAMETERS: interface name (i.e. eth0)
652 # RETURNS: (ip address)
653 # DESCRIPTION: Uses ioctl to get ip address directly from system.
654 #===============================================================================
655 sub get_ip {
656 my $ifreq= shift;
657 my $result= "";
658 my $SIOCGIFADDR= 0x8915; # man 2 ioctl_list
659 my $proto= getprotobyname('ip');
661 socket SOCKET, PF_INET, SOCK_DGRAM, $proto
662 or die "socket: $!";
664 if(ioctl SOCKET, $SIOCGIFADDR, $ifreq) {
665 my ($if, $sin) = unpack 'a16 a16', $ifreq;
666 my ($port, $addr) = sockaddr_in $sin;
667 my $ip = inet_ntoa $addr;
669 if ($ip && length($ip) > 0) {
670 $result = $ip;
671 }
672 }
674 return $result;
675 }
678 #=== FUNCTION ================================================================
679 # NAME: get_interface_for_ip
680 # PARAMETERS: ip address (i.e. 192.168.0.1)
681 # RETURNS: array: list of interfaces if ip=0.0.0.0, matching interface if found, undef else
682 # DESCRIPTION: Uses proc fs (/proc/net/dev) to get list of interfaces.
683 #===============================================================================
684 sub get_interface_for_ip {
685 my $result;
686 my $ip= shift;
687 if ($ip && length($ip) > 0) {
688 my @ifs= &get_interfaces();
689 if($ip eq "0.0.0.0") {
690 $result = "all";
691 } else {
692 foreach (@ifs) {
693 my $if=$_;
694 if(&get_ip($if) eq $ip) {
695 $result = $if;
696 }
697 }
698 }
699 }
700 return $result;
701 }
703 #=== FUNCTION ================================================================
704 # NAME: get_interfaces
705 # PARAMETERS: none
706 # RETURNS: (list of interfaces)
707 # DESCRIPTION: Uses proc fs (/proc/net/dev) to get list of interfaces.
708 #===============================================================================
709 sub get_interfaces {
710 my @result;
711 my $PROC_NET_DEV= ('/proc/net/dev');
713 open(PROC_NET_DEV, "<$PROC_NET_DEV")
714 or die "Could not open $PROC_NET_DEV";
716 my @ifs = <PROC_NET_DEV>;
718 close(PROC_NET_DEV);
720 # Eat first two line
721 shift @ifs;
722 shift @ifs;
724 chomp @ifs;
725 foreach my $line(@ifs) {
726 my $if= (split /:/, $line)[0];
727 $if =~ s/^\s+//;
728 push @result, $if;
729 }
731 return @result;
732 }
734 sub get_local_ip_for_remote_ip {
735 my $remote_ip= shift;
736 my $result="0.0.0.0";
738 if($remote_ip =~ /^(\d\d?\d?\.){3}\d\d?\d?$/) {
739 my $PROC_NET_ROUTE= ('/proc/net/route');
741 open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
742 or die "Could not open $PROC_NET_ROUTE";
744 my @ifs = <PROC_NET_ROUTE>;
746 close(PROC_NET_ROUTE);
748 # Eat header line
749 shift @ifs;
750 chomp @ifs;
751 my $iffallback = '';
753 # linux-vserver might have * as Iface due to hidden interfaces, set a default
754 foreach my $line(@ifs) {
755 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
756 if ($Iface =~ m/^[^\*]+$/) {
757 $iffallback = $Iface;
758 }
759 }
761 foreach my $line(@ifs) {
762 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
763 my $destination;
764 my $mask;
765 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
766 if ($Iface =~ m/^[^\*]+$/) {
767 $iffallback = $Iface;
768 }
769 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
770 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
771 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
772 if(new NetAddr::IP($remote_ip)->within(new NetAddr::IP($destination, $mask))) {
773 # destination matches route, save mac and exit
774 #$result= &get_ip($Iface);
776 if ($Iface =~ m/^\*$/ ) {
777 $result= &get_ip($iffallback);
778 } else {
779 $result= &get_ip($Iface);
780 }
781 last;
782 }
783 }
784 }
786 return $result;
787 }
790 sub get_mac_for_interface {
791 my $ifreq= shift;
792 my $result;
793 if ($ifreq && length($ifreq) > 0) {
794 if($ifreq eq "all") {
795 $result = "00:00:00:00:00:00";
796 } else {
797 my $SIOCGIFHWADDR= 0x8927; # man 2 ioctl_list
799 # A configured MAC Address should always override a guessed value
800 if ($main::server_mac_address and length($main::server_mac_address) > 0) {
801 $result= $main::server_mac_address;
802 }
804 socket SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('ip')
805 or die "socket: $!";
807 if(ioctl SOCKET, $SIOCGIFHWADDR, $ifreq) {
808 my ($if, $mac)= unpack 'h36 H12', $ifreq;
810 if (length($mac) > 0) {
811 $mac=~ m/^([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])$/;
812 $mac= sprintf("%s:%s:%s:%s:%s:%s", $1, $2, $3, $4, $5, $6);
813 $result = $mac;
814 }
815 }
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(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;