af23971bf83b37251d40503052f451ede444569d
1 package GOSA::GosaSupportDaemon;
3 use Exporter;
4 @ISA = qw(Exporter);
5 my @functions = (
6 "create_passwd",
7 "create_xml_hash",
8 "get_content_from_xml_hash",
9 "add_content2xml_hash",
10 "create_xml_string",
11 "transform_msg2hash",
12 "get_time",
13 "build_msg",
14 "db_res2xml",
15 "db_res2si_msg",
16 "get_where_statement",
17 "get_select_statement",
18 "get_update_statement",
19 "get_limit_statement",
20 "get_orderby_statement",
21 "get_dns_domains",
22 "get_server_addresses",
23 "get_logged_in_users",
24 "import_events",
25 "del_doubles",
26 "get_ip",
27 "get_interface_for_ip",
28 "get_interfaces",
29 "run_as",
30 );
31 @EXPORT = @functions;
32 use strict;
33 use warnings;
34 use IO::Socket::INET;
35 use Crypt::Rijndael;
36 use Digest::MD5 qw(md5 md5_hex md5_base64);
37 use MIME::Base64;
38 use XML::Simple;
39 use Data::Dumper;
40 use Net::DNS;
43 my $op_hash = {
44 'eq' => '=',
45 'ne' => '!=',
46 'ge' => '>=',
47 'gt' => '>',
48 'le' => '<=',
49 'lt' => '<',
50 'like' => ' LIKE ',
51 };
54 BEGIN {}
56 END {}
58 ### Start ######################################################################
60 my $xml = new XML::Simple();
62 sub daemon_log {
63 my ($msg, $level) = @_ ;
64 &main::daemon_log($msg, $level);
65 return;
66 }
69 sub create_passwd {
70 my $new_passwd = "";
71 for(my $i=0; $i<31; $i++) {
72 $new_passwd .= ("a".."z","A".."Z",0..9)[int(rand(62))]
73 }
75 return $new_passwd;
76 }
79 sub del_doubles {
80 my %all;
81 $all{$_}=0 for @_;
82 return (keys %all);
83 }
86 #=== FUNCTION ================================================================
87 # NAME: create_xml_hash
88 # PARAMETERS: header - string - message header (required)
89 # source - string - where the message come from (required)
90 # target - string - where the message should go to (required)
91 # [header_value] - string - something usefull (optional)
92 # RETURNS: hash - hash - nomen est omen
93 # DESCRIPTION: creates a key-value hash, all values are stored in a array
94 #===============================================================================
95 sub create_xml_hash {
96 my ($header, $source, $target, $header_value) = @_;
97 my $hash = {
98 header => [$header],
99 source => [$source],
100 target => [$target],
101 $header => [$header_value],
102 };
103 return $hash
104 }
107 #=== FUNCTION ================================================================
108 # NAME: create_xml_string
109 # PARAMETERS: xml_hash - hash - hash from function create_xml_hash
110 # RETURNS: xml_string - string - xml string representation of the hash
111 # DESCRIPTION: transform the hash to a string using XML::Simple module
112 #===============================================================================
113 sub create_xml_string {
114 my ($xml_hash) = @_ ;
115 my $xml_string = $xml->XMLout($xml_hash, RootName => 'xml');
116 #$xml_string =~ s/[\n]+//g;
117 #daemon_log("create_xml_string:",7);
118 #daemon_log("$xml_string\n", 7);
119 return $xml_string;
120 }
123 sub transform_msg2hash {
124 my ($msg) = @_ ;
125 my $hash = $xml->XMLin($msg, ForceArray=>1);
127 # xml tags without a content are created as an empty hash
128 # substitute it with an empty list
129 eval {
130 while( my ($xml_tag, $xml_content) = each %{ $hash } ) {
131 if( 1 == @{ $xml_content } ) {
132 # there is only one element in xml_content list ...
133 my $element = @{ $xml_content }[0];
134 if( ref($element) eq "HASH" ) {
135 # and this element is an hash ...
136 my $len_element = keys %{ $element };
137 if( $len_element == 0 ) {
138 # and this hash is empty, then substitute the xml_content
139 # with an empty string in list
140 $hash->{$xml_tag} = [ "none" ];
141 }
142 }
143 }
144 }
145 };
146 if( $@ ) {
147 $hash = undef;
148 }
150 return $hash;
151 }
154 #=== FUNCTION ================================================================
155 # NAME: add_content2xml_hash
156 # PARAMETERS: xml_ref - ref - reference to a hash from function create_xml_hash
157 # element - string - key for the hash
158 # content - string - value for the hash
159 # RETURNS: nothing
160 # DESCRIPTION: add key-value pair to xml_ref, if key alread exists,
161 # then append value to list
162 #===============================================================================
163 sub add_content2xml_hash {
164 my ($xml_ref, $element, $content) = @_;
165 if(not exists $$xml_ref{$element} ) {
166 $$xml_ref{$element} = [];
167 }
168 my $tmp = $$xml_ref{$element};
169 push(@$tmp, $content);
170 return;
171 }
174 sub get_time {
175 my ($seconds, $minutes, $hours, $monthday, $month,
176 $year, $weekday, $yearday, $sommertime) = localtime(time);
177 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
178 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
179 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
180 $month+=1;
181 $month = $month < 10 ? $month = "0".$month : $month;
182 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
183 $year+=1900;
184 return "$year$month$monthday$hours$minutes$seconds";
186 }
189 #=== FUNCTION ================================================================
190 # NAME: build_msg
191 # DESCRIPTION: Send a message to a destination
192 # PARAMETERS: [header] Name of the header
193 # [from] sender ip
194 # [to] recipient ip
195 # [data] Hash containing additional attributes for the xml
196 # package
197 # RETURNS: nothing
198 #===============================================================================
199 sub build_msg ($$$$) {
200 my ($header, $from, $to, $data) = @_;
202 # data is of form, i.e.
203 # %data= ('ip' => $address, 'mac' => $mac);
205 my $out_hash = &create_xml_hash($header, $from, $to);
207 while ( my ($key, $value) = each(%$data) ) {
208 if(ref($value) eq 'ARRAY'){
209 map(&add_content2xml_hash($out_hash, $key, $_), @$value);
210 } else {
211 &add_content2xml_hash($out_hash, $key, $value);
212 }
213 }
214 my $out_msg = &create_xml_string($out_hash);
215 return $out_msg;
216 }
219 sub db_res2xml {
220 my ($db_res) = @_ ;
221 my $xml = "";
223 my $len_db_res= keys %{$db_res};
224 for( my $i= 1; $i<= $len_db_res; $i++ ) {
225 $xml .= "\n<answer$i>";
226 my $hash= $db_res->{$i};
227 while ( my ($column_name, $column_value) = each %{$hash} ) {
228 $xml .= "<$column_name>";
229 my $xml_content;
230 if( $column_name eq "xmlmessage" ) {
231 $xml_content = &encode_base64($column_value);
232 } else {
233 $xml_content = $column_value;
234 }
235 $xml .= $xml_content;
236 $xml .= "</$column_name>";
237 }
238 $xml .= "</answer$i>";
240 }
242 return $xml;
243 }
246 sub db_res2si_msg {
247 my ($db_res, $header, $target, $source) = @_;
249 my $si_msg = "<xml>";
250 $si_msg .= "<header>$header</header>";
251 $si_msg .= "<source>$source</source>";
252 $si_msg .= "<target>$target</target>";
253 $si_msg .= &db_res2xml;
254 $si_msg .= "</xml>";
255 }
258 sub get_where_statement {
259 my ($msg, $msg_hash) = @_;
260 my $error= 0;
262 my $clause_str= "";
263 if( (not exists $msg_hash->{'where'}) || (not exists @{$msg_hash->{'where'}}[0]->{'clause'}) ) {
264 $error++;
265 }
267 if( $error == 0 ) {
268 my @clause_l;
269 my @where = @{@{$msg_hash->{'where'}}[0]->{'clause'}};
270 foreach my $clause (@where) {
271 my $connector = $clause->{'connector'}[0];
272 if( not defined $connector ) { $connector = "AND"; }
273 $connector = uc($connector);
274 delete($clause->{'connector'});
276 my @phrase_l ;
277 foreach my $phrase (@{$clause->{'phrase'}}) {
278 my $operator = "=";
279 if( exists $phrase->{'operator'} ) {
280 my $op = $op_hash->{$phrase->{'operator'}[0]};
281 if( not defined $op ) {
282 &main::daemon_log("ERROR: Can not translate operator '$operator' in where-".
283 "statement to sql valid syntax. Please use 'eq', ".
284 "'ne', 'ge', 'gt', 'le', 'lt' in xml message\n", 1);
285 &main::daemon_log($msg, 8);
286 $op = "=";
287 }
288 $operator = $op;
289 delete($phrase->{'operator'});
290 }
292 my @xml_tags = keys %{$phrase};
293 my $tag = $xml_tags[0];
294 my $val = $phrase->{$tag}[0];
295 # integer columns do not have to have single quotes besides the value
296 if ($tag eq "id") {
297 push(@phrase_l, "$tag$operator$val");
298 } else {
299 push(@phrase_l, "$tag$operator'$val'");
300 }
301 }
302 my $clause_str .= join(" $connector ", @phrase_l);
303 push(@clause_l, "($clause_str)");
304 }
306 if( not 0 == @clause_l ) {
307 $clause_str = join(" AND ", @clause_l);
308 $clause_str = "WHERE ($clause_str) ";
309 }
310 }
312 return $clause_str;
313 }
315 sub get_select_statement {
316 my ($msg, $msg_hash)= @_;
317 my $select = "*";
318 if( exists $msg_hash->{'select'} ) {
319 my $select_l = \@{$msg_hash->{'select'}};
320 $select = join(', ', @{$select_l});
321 }
322 return $select;
323 }
326 sub get_update_statement {
327 my ($msg, $msg_hash) = @_;
328 my $error= 0;
329 my $update_str= "";
330 my @update_l;
332 if( not exists $msg_hash->{'update'} ) { $error++; };
334 if( $error == 0 ) {
335 my $update= @{$msg_hash->{'update'}}[0];
336 while( my ($tag, $val) = each %{$update} ) {
337 my $val= @{$update->{$tag}}[0];
338 push(@update_l, "$tag='$val'");
339 }
340 if( 0 == @update_l ) { $error++; };
341 }
343 if( $error == 0 ) {
344 $update_str= join(', ', @update_l);
345 $update_str= "SET $update_str ";
346 }
348 return $update_str;
349 }
351 sub get_limit_statement {
352 my ($msg, $msg_hash)= @_;
353 my $error= 0;
354 my $limit_str = "";
355 my ($from, $to);
357 if( not exists $msg_hash->{'limit'} ) { $error++; };
359 if( $error == 0 ) {
360 eval {
361 my $limit= @{$msg_hash->{'limit'}}[0];
362 $from= @{$limit->{'from'}}[0];
363 $to= @{$limit->{'to'}}[0];
364 };
365 if( $@ ) {
366 $error++;
367 }
368 }
370 if( $error == 0 ) {
371 $limit_str= "LIMIT $from, $to";
372 }
374 return $limit_str;
375 }
377 sub get_orderby_statement {
378 my ($msg, $msg_hash)= @_;
379 my $error= 0;
380 my $order_str= "";
381 my $order;
383 if( not exists $msg_hash->{'orderby'} ) { $error++; };
385 if( $error == 0) {
386 eval {
387 $order= @{$msg_hash->{'orderby'}}[0];
388 };
389 if( $@ ) {
390 $error++;
391 }
392 }
394 if( $error == 0 ) {
395 $order_str= "ORDER BY $order";
396 }
398 return $order_str;
399 }
401 sub get_dns_domains() {
402 my $line;
403 my @searches;
404 open(RESOLV, "</etc/resolv.conf") or return @searches;
405 while(<RESOLV>){
406 $line= $_;
407 chomp $line;
408 $line =~ s/^\s+//;
409 $line =~ s/\s+$//;
410 $line =~ s/\s+/ /;
411 if ($line =~ /^domain (.*)$/ ){
412 push(@searches, $1);
413 } elsif ($line =~ /^search (.*)$/ ){
414 push(@searches, split(/ /, $1));
415 }
416 }
417 close(RESOLV);
419 my %tmp = map { $_ => 1 } @searches;
420 @searches = sort keys %tmp;
422 return @searches;
423 }
426 #############################################
427 # moved from gosa-si-client: rettenbe, 16.05.2008
428 # outcommented at gosa-si-client
429 sub get_server_addresses {
430 my $domain= shift;
431 my @result;
433 my $error = 0;
434 my $res = Net::DNS::Resolver->new;
435 my $query = $res->send("_gosa-si._tcp.".$domain, "SRV");
436 my @hits;
438 if ($query) {
439 foreach my $rr ($query->answer) {
440 push(@hits, $rr->target.":".$rr->port);
441 }
442 }
443 else {
444 #warn "query failed: ", $res->errorstring, "\n";
445 $error++;
446 }
448 if( $error == 0 ) {
449 foreach my $hit (@hits) {
450 my ($hit_name, $hit_port) = split(/:/, $hit);
451 chomp($hit_name);
452 chomp($hit_port);
454 my $address_query = $res->send($hit_name);
455 if( 1 == length($address_query->answer) ) {
456 foreach my $rr ($address_query->answer) {
457 push(@result, $rr->address.":".$hit_port);
458 }
459 }
460 }
461 }
463 return @result;
464 }
467 sub get_logged_in_users {
468 my $result = qx(/usr/bin/w -hs);
469 my @res_lines;
471 if( defined $result ) {
472 chomp($result);
473 @res_lines = split("\n", $result);
474 }
476 my @logged_in_user_list;
477 foreach my $line (@res_lines) {
478 chomp($line);
479 my @line_parts = split(/\s+/, $line);
480 push(@logged_in_user_list, $line_parts[0]);
481 }
483 return @logged_in_user_list;
485 }
488 sub import_events {
489 my ($event_dir) = @_;
490 my $event_hash;
491 my $error = 0;
492 my @result = ();
493 if (not -e $event_dir) {
494 $error++;
495 push(@result, "cannot find directory or directory is not readable: $event_dir");
496 }
498 my $DIR;
499 if ($error == 0) {
500 opendir ($DIR, $event_dir) or do {
501 $error++;
502 push(@result, "cannot open directory '$event_dir' for reading: $!\n");
503 }
504 }
506 if ($error == 0) {
507 while (defined (my $event = readdir ($DIR))) {
508 if( $event eq "." || $event eq ".." ) { next; }
510 # try to import event module
511 eval{ require $event; };
512 if( $@ ) {
513 $error++;
514 push(@result, "import of event module '$event' failed: $@");
515 next;
516 }
518 # fetch all single events
519 $event =~ /(\S*?).pm$/;
520 my $event_module = $1;
521 my $events_l = eval( $1."::get_events()") ;
522 foreach my $event_name (@{$events_l}) {
523 $event_hash->{$event_name} = $event_module;
524 }
525 my $events_string = join( ", ", @{$events_l});
526 push(@result, "import of event module '$event' succeed: $events_string");
527 }
529 close $DIR;
530 }
532 return ($error, \@result, $event_hash);
534 }
537 #=== FUNCTION ================================================================
538 # NAME: get_ip
539 # PARAMETERS: interface name (i.e. eth0)
540 # RETURNS: (ip address)
541 # DESCRIPTION: Uses ioctl to get ip address directly from system.
542 #===============================================================================
543 sub get_ip {
544 my $ifreq= shift;
545 my $result= "";
546 my $SIOCGIFADDR= 0x8915; # man 2 ioctl_list
547 my $proto= getprotobyname('ip');
549 socket SOCKET, PF_INET, SOCK_DGRAM, $proto
550 or die "socket: $!";
552 if(ioctl SOCKET, $SIOCGIFADDR, $ifreq) {
553 my ($if, $sin) = unpack 'a16 a16', $ifreq;
554 my ($port, $addr) = sockaddr_in $sin;
555 my $ip = inet_ntoa $addr;
557 if ($ip && length($ip) > 0) {
558 $result = $ip;
559 }
560 }
562 return $result;
563 }
566 #=== FUNCTION ================================================================
567 # NAME: get_interface_for_ip
568 # PARAMETERS: ip address (i.e. 192.168.0.1)
569 # RETURNS: array: list of interfaces if ip=0.0.0.0, matching interface if found, undef else
570 # DESCRIPTION: Uses proc fs (/proc/net/dev) to get list of interfaces.
571 #===============================================================================
572 sub get_interface_for_ip {
573 my $result;
574 my $ip= shift;
575 if ($ip && length($ip) > 0) {
576 my @ifs= &get_interfaces();
577 if($ip eq "0.0.0.0") {
578 $result = "all";
579 } else {
580 foreach (@ifs) {
581 my $if=$_;
582 if(&get_ip($if) eq $ip) {
583 $result = $if;
584 }
585 }
586 }
587 }
588 return $result;
589 }
591 #=== FUNCTION ================================================================
592 # NAME: get_interfaces
593 # PARAMETERS: none
594 # RETURNS: (list of interfaces)
595 # DESCRIPTION: Uses proc fs (/proc/net/dev) to get list of interfaces.
596 #===============================================================================
597 sub get_interfaces {
598 my @result;
599 my $PROC_NET_DEV= ('/proc/net/dev');
601 open(PROC_NET_DEV, "<$PROC_NET_DEV")
602 or die "Could not open $PROC_NET_DEV";
604 my @ifs = <PROC_NET_DEV>;
606 close(PROC_NET_DEV);
608 # Eat first two line
609 shift @ifs;
610 shift @ifs;
612 chomp @ifs;
613 foreach my $line(@ifs) {
614 my $if= (split /:/, $line)[0];
615 $if =~ s/^\s+//;
616 push @result, $if;
617 }
619 return @result;
620 }
623 #=== FUNCTION ================================================================
624 # NAME: run_as
625 # PARAMETERS: uid, command
626 # RETURNS: result of command
627 # DESCRIPTION: Runs command as uid using the sudo utility.
628 #===============================================================================
629 sub run_as {
630 my ($uid, $command) = @_;
631 my $sudo_cmd = `which sudo`;
632 chomp($sudo_cmd);
633 if(! -x $sudo_cmd) {
634 &main::daemon_log("ERROR: The sudo utility is not available! Please fix this!");
635 }
636 open(PIPE, "$sudo_cmd su - $uid -c '$command' |");
637 my @result=<PIPE>;
638 return @result;
639 }
642 1;