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 our $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;
688 if($ip =~ /^[a-z]/i) {
689 my $ip_address = inet_ntoa(scalar gethostbyname($ip));
690 if(defined($ip_address) && $ip_address =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/) {
691 # Write ip address to $source variable
692 $ip = $ip_address;
693 }
694 }
696 if ($ip && length($ip) > 0) {
697 my @ifs= &get_interfaces();
698 if($ip eq "0.0.0.0") {
699 $result = "all";
700 } else {
701 foreach (@ifs) {
702 my $if=$_;
703 if(&get_ip($if) eq $ip) {
704 $result = $if;
705 }
706 }
707 }
708 }
709 return $result;
710 }
712 #=== FUNCTION ================================================================
713 # NAME: get_interfaces
714 # PARAMETERS: none
715 # RETURNS: (list of interfaces)
716 # DESCRIPTION: Uses proc fs (/proc/net/dev) to get list of interfaces.
717 #===============================================================================
718 sub get_interfaces {
719 my @result;
720 my $PROC_NET_DEV= ('/proc/net/dev');
722 open(PROC_NET_DEV, "<$PROC_NET_DEV")
723 or die "Could not open $PROC_NET_DEV";
725 my @ifs = <PROC_NET_DEV>;
727 close(PROC_NET_DEV);
729 # Eat first two line
730 shift @ifs;
731 shift @ifs;
733 chomp @ifs;
734 foreach my $line(@ifs) {
735 my $if= (split /:/, $line)[0];
736 $if =~ s/^\s+//;
737 push @result, $if;
738 }
740 return @result;
741 }
743 sub get_local_ip_for_remote_ip {
744 my $remote_ip= shift;
745 my $result="0.0.0.0";
747 if($remote_ip =~ /^(\d\d?\d?\.){3}\d\d?\d?$/) {
748 my $PROC_NET_ROUTE= ('/proc/net/route');
750 open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
751 or die "Could not open $PROC_NET_ROUTE";
753 my @ifs = <PROC_NET_ROUTE>;
755 close(PROC_NET_ROUTE);
757 # Eat header line
758 shift @ifs;
759 chomp @ifs;
760 my $iffallback = '';
762 # linux-vserver might have * as Iface due to hidden interfaces, set a default
763 foreach my $line(@ifs) {
764 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
765 if ($Iface =~ m/^[^\*]+$/) {
766 $iffallback = $Iface;
767 }
768 }
770 foreach my $line(@ifs) {
771 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
772 my $destination;
773 my $mask;
774 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
775 if ($Iface =~ m/^[^\*]+$/) {
776 $iffallback = $Iface;
777 }
778 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
779 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
780 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
781 if(new NetAddr::IP($remote_ip)->within(new NetAddr::IP($destination, $mask))) {
782 # destination matches route, save mac and exit
783 #$result= &get_ip($Iface);
785 if ($Iface =~ m/^\*$/ ) {
786 $result= &get_ip($iffallback);
787 } else {
788 $result= &get_ip($Iface);
789 }
790 last;
791 }
792 }
793 }
795 return $result;
796 }
799 sub get_mac_for_interface {
800 my $ifreq= shift;
801 my $result;
802 if ($ifreq && length($ifreq) > 0) {
803 if($ifreq eq "all") {
804 $result = "00:00:00:00:00:00";
805 } else {
806 my $SIOCGIFHWADDR= 0x8927; # man 2 ioctl_list
808 # A configured MAC Address should always override a guessed value
809 if ($main::server_mac_address and length($main::server_mac_address) > 0) {
810 $result= $main::server_mac_address;
811 }
813 socket SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('ip')
814 or die "socket: $!";
816 if(ioctl SOCKET, $SIOCGIFHWADDR, $ifreq) {
817 my ($if, $mac)= unpack 'h36 H12', $ifreq;
819 if (length($mac) > 0) {
820 $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])$/;
821 $mac= sprintf("%s:%s:%s:%s:%s:%s", $1, $2, $3, $4, $5, $6);
822 $result = $mac;
823 }
824 }
825 }
826 }
827 return $result;
828 }
831 #=== FUNCTION ================================================================
832 # NAME: is_local
833 # PARAMETERS: Server Address
834 # RETURNS: true if Server Address is on this host, false otherwise
835 # DESCRIPTION: Checks all interface addresses, stops on first match
836 #===============================================================================
837 sub is_local {
838 my $server_address = shift || "";
839 my $result = 0;
841 my $server_ip = $1 if $server_address =~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):\d{1,6}$/;
843 if(defined($server_ip) && length($server_ip) > 0) {
844 foreach my $interface(&get_interfaces()) {
845 my $ip_address= &get_ip($interface);
846 if($ip_address eq $server_ip) {
847 $result = 1;
848 last;
849 }
850 }
851 }
853 return $result;
854 }
857 #=== FUNCTION ================================================================
858 # NAME: run_as
859 # PARAMETERS: uid, command
860 # RETURNS: hash with keys 'resultCode' = resultCode of command and
861 # 'output' = program output
862 # DESCRIPTION: Runs command as uid using the sudo utility.
863 #===============================================================================
864 sub run_as {
865 my ($uid, $command) = @_;
866 my $sudo_cmd = `which sudo`;
867 chomp($sudo_cmd);
868 if(! -x $sudo_cmd) {
869 &main::daemon_log("ERROR: The sudo utility is not available! Please fix this!");
870 }
871 my $cmd_line= "$sudo_cmd su - $uid -c '$command'";
872 open(PIPE, "$cmd_line |");
873 my $result = {'command' => $cmd_line};
874 push @{$result->{'output'}}, <PIPE>;
875 close(PIPE);
876 my $exit_value = $? >> 8;
877 $result->{'resultCode'} = $exit_value;
878 return $result;
879 }
882 #=== FUNCTION ================================================================
883 # NAME: inform_other_si_server
884 # PARAMETERS: message
885 # RETURNS: nothing
886 # DESCRIPTION: Sends message to all other SI-server found in known_server_db.
887 #===============================================================================
888 sub inform_all_other_si_server {
889 my ($msg) = @_;
891 # determine all other si-server from known_server_db
892 my $sql_statement= "SELECT * FROM $main::known_server_tn";
893 my $res = $main::known_server_db->select_dbentry( $sql_statement );
895 while( my ($hit_num, $hit) = each %$res ) {
896 my $act_target_address = $hit->{hostname};
897 my $act_target_key = $hit->{hostkey};
899 # determine the source address corresponding to the actual target address
900 my ($act_target_ip, $act_target_port) = split(/:/, $act_target_address);
901 my $act_source_address = &main::get_local_ip_for_remote_ip($act_target_ip).":$act_target_port";
903 # fill into message the correct target and source addresses
904 my $act_msg = $msg;
905 $act_msg =~ s/<target>\w*<\/target>/<target>$act_target_address<\/target>/g;
906 $act_msg =~ s/<source>\w*<\/source>/<source>$act_source_address<\/source>/g;
908 # send message to the target
909 &main::send_msg_to_target($act_msg, $act_target_address, $act_target_key, "foreign_job_updates" , "J");
910 }
912 return;
913 }
916 sub read_configfile {
917 my ($cfg_file, %cfg_defaults) = @_ ;
918 my $cfg;
919 if( defined( $cfg_file) && ( (-s $cfg_file) > 0 )) {
920 if( -r $cfg_file ) {
921 $cfg = Config::IniFiles->new( -file => $cfg_file, -nocase => 1 );
922 } else {
923 print STDERR "Couldn't read config file!";
924 }
925 } else {
926 $cfg = Config::IniFiles->new() ;
927 }
928 foreach my $section (keys %cfg_defaults) {
929 foreach my $param (keys %{$cfg_defaults{ $section }}) {
930 my $pinfo = $cfg_defaults{ $section }{ $param };
931 ${@$pinfo[ 0 ]} = $cfg->val( $section, $param, @$pinfo[ 1 ] );
932 }
933 }
934 }
937 sub check_opsi_res {
938 my $res= shift;
940 if($res) {
941 if ($res->is_error) {
942 my $error_string;
943 if (ref $res->error_message eq "HASH") {
944 # for different versions
945 $error_string = $res->error_message->{'message'};
946 $_ = $res->error_message->{'message'};
947 } else {
948 # for different versions
949 $error_string = $res->error_message;
950 $_ = $res->error_message;
951 }
952 return 1, $error_string;
953 }
954 } else {
955 # for different versions
956 $_ = $main::opsi_client->status_line;
957 return 1, $main::opsi_client->status_line;
958 }
959 return 0;
960 }
962 sub calc_timestamp {
963 my ($timestamp, $operation, $value, $entity) = @_ ;
964 $entity = defined $entity ? $entity : "seconds";
965 my $res_timestamp = 0;
967 $value = int($value);
968 $timestamp = int($timestamp);
969 $timestamp =~ /(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)/;
970 my $dt = DateTime->new( year => $1,
971 month => $2,
972 day => $3,
973 hour => $4,
974 minute => $5,
975 second => $6,
976 );
978 if ($operation eq "plus" || $operation eq "+") {
979 $dt->add($entity => $value);
980 $res_timestamp = $dt->ymd('').$dt->hms('');
981 }
983 if ($operation eq "minus" || $operation eq "-") {
984 $dt->subtract($entity => $value);
985 $res_timestamp = $dt->ymd('').$dt->hms('');
986 }
988 return $res_timestamp;
989 }
991 sub opsi_callobj2string {
992 my ($callobj) = @_;
993 my @callobj_string;
994 while(my ($key, $value) = each(%$callobj)) {
995 my $value_string = "";
996 if (ref($value) eq "ARRAY") {
997 $value_string = join(",", @$value);
998 } else {
999 $value_string = $value;
1000 }
1001 push(@callobj_string, "$key=$value_string")
1002 }
1003 return join(", ", @callobj_string);
1004 }
1006 1;