Code

Updated list image
[gosa.git] / gosa-si / modules / GosaSupportDaemon.pm
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::Quote qw(:all);
50 use XML::Simple;
51 use Data::Dumper;
52 use Net::DNS;
53 use DateTime;
55 my $op_hash = {
56     'eq' => '=',
57     'ne' => '!=',
58     'ge' => '>=',
59     'gt' => '>',
60     'le' => '<=',
61     'lt' => '<',
62     'like' => ' LIKE ',
63 };
66 BEGIN {}
68 END {}
70 ### Start ######################################################################
72 our $xml = new XML::Simple();
74 sub daemon_log {
75     my ($msg, $level) = @_ ;
76     &main::daemon_log($msg, $level);
77     return;
78 }
81 sub create_passwd {
82     my $new_passwd = "";
83     for(my $i=0; $i<31; $i++) {
84         $new_passwd .= ("a".."z","A".."Z",0..9)[int(rand(62))]
85     }
87     return $new_passwd;
88 }
91 sub del_doubles { 
92     my %all; 
93     $all{$_}=0 for @_; 
94     return (keys %all); 
95 }
98 #===  FUNCTION  ================================================================
99 #         NAME:  create_xml_hash
100 #   PARAMETERS:  header - string - message header (required)
101 #                source - string - where the message come from (required)
102 #                target - string - where the message should go to (required)
103 #                [header_value] - string - something usefull (optional)
104 #      RETURNS:  hash - hash - nomen est omen
105 #  DESCRIPTION:  creates a key-value hash, all values are stored in a array
106 #===============================================================================
107 sub create_xml_hash {
108     my ($header, $source, $target, $header_value) = @_;
109     my $hash = {
110             header => [$header],
111             source => [$source],
112             target => [$target],
113             $header => [$header_value],
114     };
115     return $hash
118 sub createXmlHash {
119         my ($header, $source, $target) = @_;
120         return { header=>$header, source=>$source, target=>$target};
123 sub _transformHashToString {
124         my ($hash) = @_;
125         my $s = "";
127         while (my ($tag, $content) = each(%$hash)) {
129                 if (ref $content eq "HASH") {
130                         $s .= "<$tag>".&_transformHashToString($content)."</$tag>";
131                 } elsif ( ref $content eq "ARRAY") {
132                         $s .= &_transformArrayToString($tag, $content);
133                 } else {
134                         $content = defined $content ? $content : "";
135                         $s .= "<$tag>".&xml_quote($content)."</$tag>";
136                 }
137         }
138         return $s;
141 sub _transformArrayToString {
142         my ($tag, $contentArray) = @_;
143         my $s = "";
144         foreach my $content (@$contentArray) {
145                 if (ref $content eq "HASH") {
146                         $s .= "<$tag>".&_transformHashToString($content)."</$tag>";
147                 } else {
148                         $content = defined $content ? $content : "";
149                         $s .= "<$tag>".&xml_quote($content)."</$tag>";
150                 }
151         }
152         return $s;
156 #===  FUNCTION  ================================================================
157 #         NAME:  myXmlHashToString
158 #   PARAMETERS:  xml_hash - hash - hash from function createXmlHash
159 #      RETURNS:  xml_string - string - xml string representation of the hash
160 #  DESCRIPTION:  Transforms the given hash to a xml wellformed string. I.e.:
161 #                    {
162 #                   'header' => 'a'
163 #                   'source' => 'c',
164 #                   'target' => 'b',
165 #                   'hit' => [ '1',
166 #                              '2',
167 #                              { 
168 #                                'hit31' => 'ABC',
169 #                                'hit32' => 'XYZ'
170 #                              }
171 #                            ],
172 #                   'res0' => {
173 #                      'res1' => {
174 #                         'res2' => 'result'
175 #                      }
176 #                   },
177 #                };
178 #           
179 #                                will be transformed to 
180 #                                <xml>
181 #                                       <header>a</header>
182 #                                       <source>c</source>
183 #                                       <target>b</target>
184 #                                       <hit>1</hit>
185 #                                       <hit>2</hit>
186 #                                       <hit>
187 #                                               <hit31>ABC</hit31>
188 #                                               <hit32>XYZ</hit32>
189 #                                       </hit>
190 #                                       <res0>
191 #                                               <res1>
192 #                                                       <res2>result</res2>
193 #                                               </res1>
194 #                                       </res0>
195 #                               </xml>
197 #===============================================================================
198 sub myXmlHashToString {
199         my ($hash) = @_;
200         return "<xml>".&_transformHashToString($hash)."</xml>";
204 #===  FUNCTION  ================================================================
205 #         NAME:  create_xml_string
206 #   PARAMETERS:  xml_hash - hash - hash from function create_xml_hash
207 #      RETURNS:  xml_string - string - xml string representation of the hash
208 #  DESCRIPTION:  transform the hash to a string using XML::Simple module
209 #===============================================================================
210 sub create_xml_string {
211     my ($xml_hash) = @_ ;
212     my $xml_string = $xml->XMLout($xml_hash, RootName => 'xml');
213     #$xml_string =~ s/[\n]+//g;
214     #daemon_log("create_xml_string:",7);
215     #daemon_log("$xml_string\n", 7);
216     return $xml_string;
220 sub transform_msg2hash {
221     my ($msg) = @_ ;
222     my $hash = $xml->XMLin($msg, ForceArray=>1);
223     
224     # xml tags without a content are created as an empty hash
225     # substitute it with an empty list
226     eval {
227         while( my ($xml_tag, $xml_content) = each %{ $hash } ) {
228             if( 1 == @{ $xml_content } ) {
229                 # there is only one element in xml_content list ...
230                 my $element = @{ $xml_content }[0];
231                 if( ref($element) eq "HASH" ) {
232                     # and this element is an hash ...
233                     my $len_element = keys %{ $element };
234                     if( $len_element == 0 ) {
235                         # and this hash is empty, then substitute the xml_content
236                         # with an empty string in list
237                         $hash->{$xml_tag} = [ "none" ];
238                     }
239                 }
240             }
241         }
242     };
243     if( $@ ) {  
244         $hash = undef;
245     }
247     return $hash;
251 #===  FUNCTION  ================================================================
252 #         NAME:  add_content2xml_hash
253 #   PARAMETERS:  xml_ref - ref - reference to a hash from function create_xml_hash
254 #                element - string - key for the hash
255 #                content - string - value for the hash
256 #      RETURNS:  nothing
257 #  DESCRIPTION:  add key-value pair to xml_ref, if key alread exists, 
258 #                then append value to list
259 #===============================================================================
260 sub add_content2xml_hash {
261     my ($xml_ref, $element, $content) = @_;
262     if(not exists $$xml_ref{$element} ) {
263         $$xml_ref{$element} = [];
264     }
265     my $tmp = $$xml_ref{$element};
266     push(@$tmp, $content);
267     return;
271 sub get_time {
272         my ($seconds, $minutes, $hours, $monthday, $month,
273                 $year, $weekday, $yearday, $sommertime) = localtime;
274         $hours = $hours < 10 ? $hours = "0".$hours : $hours;
275         $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
276         $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
277         $month+=1;
278         $month = $month < 10 ? $month = "0".$month : $month;
279         $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
280         $year+=1900;
281         return "$year$month$monthday$hours$minutes$seconds";
285 sub get_utc_time {
286     my $utc_time = qx(date --utc +%Y%m%d%H%M%S);
287     $utc_time =~ s/\s$//;
288     return $utc_time;
292 #===  FUNCTION  ================================================================
293 #         NAME: build_msg
294 #  DESCRIPTION: Send a message to a destination
295 #   PARAMETERS: [header] Name of the header
296 #               [from]   sender ip
297 #               [to]     recipient ip
298 #               [data]   Hash containing additional attributes for the xml
299 #                        package
300 #      RETURNS:  nothing
301 #===============================================================================
302 sub build_msg ($$$$) {
303         my ($header, $from, $to, $data) = @_;
305     # data is of form, i.e.
306     # %data= ('ip' => $address, 'mac' => $mac);
308         my $out_hash = &create_xml_hash($header, $from, $to);
310         while ( my ($key, $value) = each(%$data) ) {
311                 if(ref($value) eq 'ARRAY'){
312                         map(&add_content2xml_hash($out_hash, $key, $_), @$value);
313                 } else {
314                         &add_content2xml_hash($out_hash, $key, $value);
315                 }
316         }
317     my $out_msg = &create_xml_string($out_hash);
318     return $out_msg;
322 sub db_res2xml {
323     my ($db_res) = @_ ;
324     my $xml = "";
326     my $len_db_res= keys %{$db_res};
327     for( my $i= 1; $i<= $len_db_res; $i++ ) {
328         $xml .= "\n<answer$i>";
329         my $hash= $db_res->{$i};
330         while ( my ($column_name, $column_value) = each %{$hash} ) {
331             $xml .= "<$column_name>";
332             my $xml_content;
333             if( $column_name eq "xmlmessage" ) {
334                 $xml_content = &encode_base64($column_value);
335             } else {
336                 $xml_content = defined $column_value ? $column_value : "";
337             }
338             $xml .= $xml_content;
339             $xml .= "</$column_name>"; 
340         }
341         $xml .= "</answer$i>";
343     }
345     return $xml;
349 sub db_res2si_msg {
350     my ($db_res, $header, $target, $source) = @_;
352     my $si_msg = "<xml>";
353     $si_msg .= "<header>$header</header>";
354     $si_msg .= "<source>$source</source>";
355     $si_msg .= "<target>$target</target>";
356     $si_msg .= &db_res2xml;
357     $si_msg .= "</xml>";
361 sub get_where_statement {
362     my ($msg, $msg_hash) = @_;
363     my $error= 0;
364     
365     my $clause_str= "";
366     if( (not exists $msg_hash->{'where'}) || (not exists @{$msg_hash->{'where'}}[0]->{'clause'}) ) { 
367         $error++; 
368     }
370     if( $error == 0 ) {
371         my @clause_l;
372         my @where = @{@{$msg_hash->{'where'}}[0]->{'clause'}};
373         foreach my $clause (@where) {
374             my $connector = $clause->{'connector'}[0];
375             if( not defined $connector ) { $connector = "AND"; }
376             $connector = uc($connector);
377             delete($clause->{'connector'});
379             my @phrase_l ;
380             foreach my $phrase (@{$clause->{'phrase'}}) {
381                 my $operator = "=";
382                 if( exists $phrase->{'operator'} ) {
383                     my $op = $op_hash->{$phrase->{'operator'}[0]};
384                     if( not defined $op ) {
385                         &main::daemon_log("ERROR: Can not translate operator '$operator' in where-".
386                                 "statement to sql valid syntax. Please use 'eq', ".
387                                 "'ne', 'ge', 'gt', 'le', 'lt' in xml message\n", 1);
388                         &main::daemon_log($msg, 8);
389                         $op = "=";
390                     }
391                     $operator = $op;
392                     delete($phrase->{'operator'});
393                 }
395                 my @xml_tags = keys %{$phrase};
396                 my $tag = $xml_tags[0];
397                 my $val = $phrase->{$tag}[0];
398                 if( ref($val) eq "HASH" ) { next; }  # empty xml-tags should not appear in where statement
400                                 # integer columns do not have to have single quotes besides the value
401                                 if ($tag eq "id") {
402                                                 push(@phrase_l, "$tag$operator$val");
403                                 } else {
404                                                 push(@phrase_l, "$tag$operator'$val'");
405                                 }
406             }
408             if (not 0 == @phrase_l) {
409                 my $clause_str .= join(" $connector ", @phrase_l);
410                 push(@clause_l, "($clause_str)");
411             }
412         }
414         if( not 0 == @clause_l ) {
415             $clause_str = join(" AND ", @clause_l);
416             $clause_str = "WHERE ($clause_str) ";
417         }
418     }
420     return $clause_str;
423 sub get_select_statement {
424     my ($msg, $msg_hash)= @_;
425     my $select = "*";
426     if( exists $msg_hash->{'select'} ) {
427         my $select_l = \@{$msg_hash->{'select'}};
428         $select = join(', ', @{$select_l});
429     }
430     return $select;
434 sub get_update_statement {
435     my ($msg, $msg_hash) = @_;
436     my $error= 0;
437     my $update_str= "";
438     my @update_l; 
440     if( not exists $msg_hash->{'update'} ) { $error++; };
442     if( $error == 0 ) {
443         my $update= @{$msg_hash->{'update'}}[0];
444         while( my ($tag, $val) = each %{$update} ) {
445             my $val= @{$update->{$tag}}[0];
446             push(@update_l, "$tag='$val'");
447         }
448         if( 0 == @update_l ) { $error++; };   
449     }
451     if( $error == 0 ) { 
452         $update_str= join(', ', @update_l);
453         $update_str= "SET $update_str ";
454     }
456     return $update_str;
459 sub get_limit_statement {
460     my ($msg, $msg_hash)= @_; 
461     my $error= 0;
462     my $limit_str = "";
463     my ($from, $to);
465     if( not exists $msg_hash->{'limit'} ) { $error++; };
467     if( $error == 0 ) {
468         eval {
469             my $limit= @{$msg_hash->{'limit'}}[0];
470             $from= @{$limit->{'from'}}[0];
471             $to= @{$limit->{'to'}}[0];
472         };
473         if( $@ ) {
474             $error++;
475         }
476     }
478     if( $error == 0 ) {
479         $limit_str= "LIMIT $from, $to";
480     }   
481     
482     return $limit_str;
485 sub get_orderby_statement {
486     my ($msg, $msg_hash)= @_;
487     my $error= 0;
488     my $order_str= "";
489     my $order;
490     
491     if( not exists $msg_hash->{'orderby'} ) { $error++; };
493     if( $error == 0) {
494         eval {
495             $order= @{$msg_hash->{'orderby'}}[0];
496         };
497         if( $@ ) {
498             $error++;
499         }
500     }
502     if( $error == 0 ) {
503         $order_str= "ORDER BY $order";   
504     }
505     
506     return $order_str;
509 sub get_dns_domains() {
510         my $line;
511         my @searches;
512         open(RESOLV, "</etc/resolv.conf") or return @searches;
513         while(<RESOLV>){
514                 $line= $_;
515                 chomp $line;
516                 $line =~ s/^\s+//;
517                 $line =~ s/\s+$//;
518                 $line =~ s/\s+/ /;
519                 if ($line =~ /^domain (.*)$/ ){
520                         push(@searches, $1);
521                 } elsif ($line =~ /^search (.*)$/ ){
522                         push(@searches, split(/ /, $1));
523                 }
524         }
525         close(RESOLV);
527         my %tmp = map { $_ => 1 } @searches;
528         @searches = sort keys %tmp;
530         return @searches;
534 sub get_server_addresses {
535     my $domain= shift;
536     my @result;
537     my $error_string;
539     my $error = 0;
540     my $res   = Net::DNS::Resolver->new;
541     my $query = $res->send("_gosa-si._tcp.".$domain, "SRV");
542     my @hits;
544     if ($query) {
545         foreach my $rr ($query->answer) {
546             push(@hits, $rr->target.":".$rr->port);
547         }
548     }
549     else {
550         $error_string = "determination of '_gosa-si._tcp' server in domain '$domain' failed: ".$res->errorstring;
551         $error++;
552     }
554     if( $error == 0 ) {
555         foreach my $hit (@hits) {
556             my ($hit_name, $hit_port) = split(/:/, $hit);
557             chomp($hit_name);
558             chomp($hit_port);
560             my $address_query = $res->send($hit_name);
561             if( 1 == length($address_query->answer) ) {
562                 foreach my $rr ($address_query->answer) {
563                     push(@result, $rr->address.":".$hit_port);
564                 }
565             }
566         }
567     }
569     return \@result, $error_string;
573 sub get_logged_in_users {
574     my $result = qx(/usr/bin/w -hs);
575     my @res_lines;
577     if( defined $result ) { 
578         chomp($result);
579         @res_lines = split("\n", $result);
580     }
582     my @logged_in_user_list;
583     foreach my $line (@res_lines) {
584         chomp($line);
585         my @line_parts = split(/\s+/, $line); 
586         push(@logged_in_user_list, $line_parts[0]);
587     }
589     return @logged_in_user_list;
594 sub import_events {
595     my ($event_dir) = @_;
596     my $event_hash;
597     my $error = 0;
598     my @result = ();
599     if (not -e $event_dir) {
600         $error++;
601         push(@result, "cannot find directory or directory is not readable: $event_dir");   
602     }
604     my $DIR;
605     if ($error == 0) {
606         opendir ($DIR, $event_dir) or do { 
607             $error++;
608             push(@result, "cannot open directory '$event_dir' for reading: $!\n");
609         }
610     }
612     if ($error == 0) {
613         while (defined (my $event = readdir ($DIR))) {
614             if( $event eq "." || $event eq ".." || ($event =~ /^\.pm$/)) { next; }  
616                         # Check config file to exclude disabled event plugins (i.e. Opsi)
617                         if ($event eq "opsi_com.pm" &&  $main::opsi_enabled ne "true")  { 
618                                 &main::daemon_log("0 WARNING: opsi-module is installed but not enabled in config file, please set under section '[OPSI]': 'enabled=true'", 3);  
619                                 next; 
620                         }
622             # try to import event module
623             eval{ require $event; };
624             if( $@ ) {
625                 $error++;
626                 #push(@result, "import of event module '$event' failed: $@");
627                 #next;
628                 
629                 &main::daemon_log("ERROR: Import of event module '$event' failed: $@",1);
630                 exit(1);
631             }
633             # fetch all single events
634             $event =~ /(\S*?).pm$/;
635             my $event_module = $1;
636             my $events_l = eval( $1."::get_events()") ;
637             foreach my $event_name (@{$events_l}) {
638                 $event_hash->{$event_module}->{$event_name} = "";
639             }
640             my $events_string = join( ", ", @{$events_l});
641             push(@result, "import of event module '$event' succeed: $events_string");
642         }
643         
644         close $DIR;
645     }
647     return ($error, \@result, $event_hash);
652 #===  FUNCTION  ================================================================
653 #         NAME:  get_ip 
654 #   PARAMETERS:  interface name (i.e. eth0)
655 #      RETURNS:  (ip address) 
656 #  DESCRIPTION:  Uses ioctl to get ip address directly from system.
657 #===============================================================================
658 sub get_ip {
659         my $ifreq= shift;
660         my $result= "";
661         my $SIOCGIFADDR= 0x8915;       # man 2 ioctl_list
662         my $proto= getprotobyname('ip');
664         socket SOCKET, PF_INET, SOCK_DGRAM, $proto
665                 or die "socket: $!";
667         if(ioctl SOCKET, $SIOCGIFADDR, $ifreq) {
668                 my ($if, $sin)    = unpack 'a16 a16', $ifreq;
669                 my ($port, $addr) = sockaddr_in $sin;
670                 my $ip            = inet_ntoa $addr;
672                 if ($ip && length($ip) > 0) {
673                         $result = $ip;
674                 }
675         }
677         return $result;
681 #===  FUNCTION  ================================================================
682 #         NAME:  get_interface_for_ip
683 #   PARAMETERS:  ip address (i.e. 192.168.0.1)
684 #      RETURNS:  array: list of interfaces if ip=0.0.0.0, matching interface if found, undef else
685 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
686 #===============================================================================
687 sub get_interface_for_ip {
688         my $result;
689         my $ip= shift;
691         if($ip =~ /^[a-z]/i) {
692                 my $ip_address = inet_ntoa(scalar gethostbyname($ip));
693                 if(defined($ip_address) && $ip_address =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/) {
694                         # Write ip address to $source variable
695                         $ip = $ip_address;
696                 }
697         }
699         if ($ip && length($ip) > 0) {
700                 my @ifs= &get_interfaces();
701                 if($ip eq "0.0.0.0") {
702                         $result = "all";
703                 } else {
704                         foreach (@ifs) {
705                                 my $if=$_;
706                                 if(&get_ip($if) eq $ip) {
707                                         $result = $if;
708                                 }
709                         }       
710                 }
711         }       
712         return $result;
715 #===  FUNCTION  ================================================================
716 #         NAME:  get_interfaces 
717 #   PARAMETERS:  none
718 #      RETURNS:  (list of interfaces) 
719 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
720 #===============================================================================
721 sub get_interfaces {
722         my @result;
723         my $PROC_NET_DEV= ('/proc/net/dev');
725         open(PROC_NET_DEV, "<$PROC_NET_DEV")
726                 or die "Could not open $PROC_NET_DEV";
728         my @ifs = <PROC_NET_DEV>;
730         close(PROC_NET_DEV);
732         # Eat first two line
733         shift @ifs;
734         shift @ifs;
736         chomp @ifs;
737         foreach my $line(@ifs) {
738                 my $if= (split /:/, $line)[0];
739                 $if =~ s/^\s+//;
740                 push @result, $if;
741         }
743         return @result;
746 sub get_local_ip_for_remote_ip {
747         my $remote_ip= shift;
748         my $result="0.0.0.0";
750     if($remote_ip =~ /^(\d\d?\d?\.){3}\d\d?\d?$/) {
751         my $PROC_NET_ROUTE= ('/proc/net/route');
753         open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
754             or die "Could not open $PROC_NET_ROUTE";
756         my @ifs = <PROC_NET_ROUTE>;
758         close(PROC_NET_ROUTE);
760         # Eat header line
761         shift @ifs;
762         chomp @ifs;
763         my $iffallback = ''; 
765         # linux-vserver might have * as Iface due to hidden interfaces, set a default 
766         foreach my $line(@ifs) { 
767             my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line); 
768             if ($Iface =~ m/^[^\*]+$/) { 
769                  $iffallback = $Iface; 
770             } 
771         }
772  
773         foreach my $line(@ifs) {
774             my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
775             my $destination;
776             my $mask;
777             my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
778             if ($Iface =~ m/^[^\*]+$/) { 
779                  $iffallback = $Iface;
780             } 
781             $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
782             ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
783             $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
784             if(new NetAddr::IP($remote_ip)->within(new NetAddr::IP($destination, $mask))) {
785                 # destination matches route, save mac and exit
786                 #$result= &get_ip($Iface);
788                 if ($Iface =~ m/^\*$/ ) { 
789                     $result= &get_ip($iffallback);    
790                 } else { 
791                     $result= &get_ip($Iface); 
792                 } 
793                 last;
794             }
795         }
796     } 
798         return $result;
802 sub get_mac_for_interface {
803         my $ifreq= shift;
804         my $result;
805         if ($ifreq && length($ifreq) > 0) { 
806                 if($ifreq eq "all") {
807                         $result = "00:00:00:00:00:00";
808                 } else {
809                         my $SIOCGIFHWADDR= 0x8927;     # man 2 ioctl_list
811                         # A configured MAC Address should always override a guessed value
812                         if ($main::server_mac_address and length($main::server_mac_address) > 0) {
813                                 $result= $main::server_mac_address;
814                         }
816                         socket SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('ip')
817                                 or die "socket: $!";
819                         if(ioctl SOCKET, $SIOCGIFHWADDR, $ifreq) {
820                                 my ($if, $mac)= unpack 'h36 H12', $ifreq;
822                                 if (length($mac) > 0) {
823                                         $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])$/;
824                                         $mac= sprintf("%s:%s:%s:%s:%s:%s", $1, $2, $3, $4, $5, $6);
825                                         $result = $mac;
826                                 }
827                         }
828                 }
829         }
830         return $result;
834 #===  FUNCTION  ================================================================
835 #         NAME:  is_local
836 #   PARAMETERS:  Server Address
837 #      RETURNS:  true if Server Address is on this host, false otherwise
838 #  DESCRIPTION:  Checks all interface addresses, stops on first match
839 #===============================================================================
840 sub is_local {
841     my $server_address = shift || "";
842     my $result = 0;
844     my $server_ip = $1 if $server_address =~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):\d{1,6}$/;
846     if(defined($server_ip) && length($server_ip) > 0) {
847         foreach my $interface(&get_interfaces()) {
848             my $ip_address= &get_ip($interface);
849             if($ip_address eq $server_ip) {
850                 $result = 1;
851                 last;
852             }
853         }
854     }
856     return $result;
860 #===  FUNCTION  ================================================================
861 #         NAME:  run_as
862 #   PARAMETERS:  uid, command
863 #      RETURNS:  hash with keys 'resultCode' = resultCode of command and 
864 #                'output' = program output
865 #  DESCRIPTION:  Runs command as uid using the sudo utility.
866 #===============================================================================
867 sub run_as {
868         my ($uid, $command) = @_;
869         my $sudo_cmd = `which sudo`;
870         chomp($sudo_cmd);
871         if(! -x $sudo_cmd) {
872                 &main::daemon_log("ERROR: The sudo utility is not available! Please fix this!");
873         }
874         my $cmd_line= "$sudo_cmd su - $uid -c '$command'";
875         open(PIPE, "$cmd_line |");
876         my $result = {'command' => $cmd_line};
877         push @{$result->{'output'}}, <PIPE>;
878         close(PIPE);
879         my $exit_value = $? >> 8;
880         $result->{'resultCode'} = $exit_value;
881         return $result;
885 #===  FUNCTION  ================================================================
886 #         NAME:  inform_other_si_server
887 #   PARAMETERS:  message
888 #      RETURNS:  nothing
889 #  DESCRIPTION:  Sends message to all other SI-server found in known_server_db. 
890 #===============================================================================
891 sub inform_all_other_si_server {
892     my ($msg) = @_;
894     # determine all other si-server from known_server_db
895     my $sql_statement= "SELECT * FROM $main::known_server_tn";
896     my $res = $main::known_server_db->select_dbentry( $sql_statement ); 
898     while( my ($hit_num, $hit) = each %$res ) {    
899         my $act_target_address = $hit->{hostname};
900         my $act_target_key = $hit->{hostkey};
902         # determine the source address corresponding to the actual target address
903         my ($act_target_ip, $act_target_port) = split(/:/, $act_target_address);
904         my $act_source_address = &main::get_local_ip_for_remote_ip($act_target_ip).":$act_target_port";
906         # fill into message the correct target and source addresses
907         my $act_msg = $msg;
908         $act_msg =~ s/<target>\w*<\/target>/<target>$act_target_address<\/target>/g;
909         $act_msg =~ s/<source>\w*<\/source>/<source>$act_source_address<\/source>/g;
911         # send message to the target
912         &main::send_msg_to_target($act_msg, $act_target_address, $act_target_key, "foreign_job_updates" , "J");
913     }
915     return;
919 sub read_configfile {
920     my ($cfg_file, %cfg_defaults) = @_ ;
921     my $cfg;
922     if( defined( $cfg_file) && ( (-s $cfg_file) > 0 )) {
923         if( -r $cfg_file ) {
924             $cfg = Config::IniFiles->new( -file => $cfg_file, -nocase => 1 );
925         } else {
926             print STDERR "Couldn't read config file!";
927         }
928     } else {
929         $cfg = Config::IniFiles->new() ;
930     }
931     foreach my $section (keys %cfg_defaults) {
932         foreach my $param (keys %{$cfg_defaults{ $section }}) {
933             my $pinfo = $cfg_defaults{ $section }{ $param };
934            ${@$pinfo[ 0 ]} = $cfg->val( $section, $param, @$pinfo[ 1 ] );
935         }
936     }
940 sub check_opsi_res {
941     my $res= shift;
943     if($res) {
944         if ($res->is_error) {
945             my $error_string;
946             if (ref $res->error_message eq "HASH") { 
947                                 # for different versions
948                 $error_string = $res->error_message->{'message'}; 
949                                 $_ = $res->error_message->{'message'};
950             } else { 
951                                 # for different versions
952                 $error_string = $res->error_message; 
953                                 $_ = $res->error_message;
954             }
955             return 1, $error_string;
956         }
957     } else {
958                 # for different versions
959                 $_ = $main::opsi_client->status_line;
960         return 1, $main::opsi_client->status_line;
961     }
962     return 0;
965 sub calc_timestamp {
966     my ($timestamp, $operation, $value, $entity) = @_ ;
967         $entity = defined $entity ? $entity : "seconds";
968     my $res_timestamp = 0;
969     
970     $value = int($value);
971     $timestamp = int($timestamp);
972     $timestamp =~ /(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)/;
973     my $dt = DateTime->new( year   => $1,
974             month  => $2,
975             day    => $3,
976             hour   => $4,
977             minute => $5,
978             second => $6,
979             );
981     if ($operation eq "plus" || $operation eq "+") {
982         $dt->add($entity => $value);
983         $res_timestamp = $dt->ymd('').$dt->hms('');
984     }
986     if ($operation eq "minus" || $operation eq "-") {
987         $dt->subtract($entity => $value);
988         $res_timestamp = $dt->ymd('').$dt->hms('');
989     }
991     return $res_timestamp;
994 sub opsi_callobj2string {
995     my ($callobj) = @_;
996     my @callobj_string;
997     while(my ($key, $value) = each(%$callobj)) {
998         my $value_string = "";
999         if (ref($value) eq "ARRAY") {
1000             $value_string = join(",", @$value);
1001         } else {
1002             $value_string = $value;
1003         }
1004         push(@callobj_string, "$key=$value_string")
1005     }
1006     return join(", ", @callobj_string);
1009 1;