27ae2d160bc5ff473a637b268161af733a811f50
1 #!/usr/bin/perl
2 #===============================================================================
3 #
4 # FILE: gosa-server
5 #
6 # USAGE: gosa-si-client
7 #
8 # DESCRIPTION:
9 #
10 # OPTIONS: ---
11 # REQUIREMENTS: libnetaddr-ip-perl
12 # BUGS: ---
13 # NOTES:
14 # AUTHOR: (Andreas Rettenberger), <rettenberger@gonicus.de>
15 # COMPANY:
16 # VERSION: 1.0
17 # CREATED: 12.09.2007 08:54:41 CEST
18 # REVISION: ---
19 #===============================================================================
21 use strict;
22 use warnings;
23 use Getopt::Long;
24 use Config::IniFiles;
25 use POSIX;
26 use Time::HiRes qw( gettimeofday );
27 use File::Basename;
29 use Fcntl;
30 use IO::Socket::INET;
31 use Crypt::Rijndael;
32 use MIME::Base64;
33 use Digest::MD5 qw(md5 md5_hex md5_base64);
34 use XML::Simple;
35 use Data::Dumper;
36 use Sys::Syslog qw( :DEFAULT setlogsock);
37 use File::Spec;
38 use Cwd;
39 use NetAddr::IP;
40 use GOSA::GosaSupportDaemon;
43 my ($cfg_file, %cfg_defaults, $foreground, $verbose, $pid_file, $procid, $pid, $log_file);
44 my ($server_address, $server_ip, $server_port, $server_domain, $server_passwd, $server_cipher, $server_timeout);
45 my ($client_address, $client_ip, $client_port, $client_mac_address, $network_interface, $ldap_config, $pam_config, $nss_config, $gotoHardwareChecksum);
46 my ($input_socket, $rbits, $wbits, $ebits, $xml, $known_hosts, $ldap_enabled);
47 my (@events);
49 # default variables
50 my $event_dir = "/usr/lib/gosa-si/client/events";
51 $known_hosts = {};
52 $foreground = 0 ;
53 %cfg_defaults =
54 ("general" =>
55 {"log_file" => [\$log_file, "/var/run/".$0.".log"],
56 "pid_file" => [\$pid_file, "/var/run/".$0.".pid"],
57 },
58 "client" =>
59 {"client_port" => [\$client_port, "20083"],
60 "client_ip" => [\$client_ip, "0.0.0.0"],
61 "ldap" => [\$ldap_enabled, 1],
62 "ldap_config" => [\$ldap_config, "/etc/ldap/ldap.conf"],
63 "pam_config" => [\$pam_config, "/etc/pam_ldap.conf"],
64 "nss_config" => [\$nss_config, "/etc/libnss_ldap.conf"],
65 },
66 "server" =>
67 {"server_ip" => [\$server_ip, ""],
68 "server_port" => [\$server_port, "20081"],
69 "server_passwd" => [\$server_passwd, ""],
70 "server_timeout" => [\$server_timeout, 10],
71 "server_domain" => [\$server_domain, ""],
72 },
73 );
76 #=== FUNCTION ================================================================
77 # NAME: read_configfile
78 # PARAMETERS: cfg_file - string -
79 # RETURNS:
80 # DESCRIPTION:
81 #===============================================================================
82 sub read_configfile {
83 my $cfg;
84 if( defined( $cfg_file) && ( length($cfg_file) > 0 )) {
85 if( -r $cfg_file ) {
86 $cfg = Config::IniFiles->new( -file => $cfg_file );
87 } else {
88 print STDERR "Couldn't read config file!";
89 }
90 } else {
91 $cfg = Config::IniFiles->new() ;
92 }
93 foreach my $section (keys %cfg_defaults) {
94 foreach my $param (keys %{$cfg_defaults{ $section }}) {
95 my $pinfo = $cfg_defaults{ $section }{ $param };
96 ${@$pinfo[ 0 ]} = $cfg->val( $section, $param, @$pinfo[ 1 ] );
97 }
98 }
99 }
102 #=== FUNCTION ================================================================
103 # NAME: logging
104 # PARAMETERS: level - string - default 'info'
105 # msg - string -
106 # facility - string - default 'LOG_DAEMON'
107 # RETURNS:
108 # DESCRIPTION:
109 #===============================================================================
110 sub daemon_log {
111 my( $msg, $level ) = @_;
112 if(not defined $msg) { return }
113 if(not defined $level) { $level = 1 }
114 if(defined $log_file){
115 open(LOG_HANDLE, ">>$log_file");
116 if(not defined open( LOG_HANDLE, ">>$log_file" )) {
117 print STDERR "cannot open $log_file: $!";
118 return }
119 chomp($msg);
120 if($level <= $verbose){
121 print LOG_HANDLE $msg."\n";
122 if(defined $foreground) { print $msg."\n" }
123 }
124 }
125 close( LOG_HANDLE );
126 # my ($msg, $level, $facility) = @_;
127 # if(not defined $msg) {return}
128 # if(not defined $level) {$level = "info"}
129 # if(not defined $facility) {$facility = "LOG_DAEMON"}
130 # openlog($0, "pid,cons,", $facility);
131 # syslog($level, $msg);
132 # closelog;
133 # return;
134 }
137 #=== FUNCTION ================================================================
138 # NAME: check_cmdline_param
139 # PARAMETERS:
140 # RETURNS:
141 # DESCRIPTION:
142 #===============================================================================
143 sub check_cmdline_param () {
144 my $err_config;
145 my $err_counter = 0;
146 if(not defined($cfg_file)) {
147 $cfg_file = "/etc/gosa-si/client.conf";
148 if(! -r $cfg_file) {
149 $err_config = "please specify a config file";
150 $err_counter += 1;
151 }
152 }
153 if( $err_counter > 0 ) {
154 &usage( "", 1 );
155 if( defined( $err_config)) { print STDERR "$err_config\n"}
156 print STDERR "\n";
157 exit( -1 );
158 }
159 }
162 #=== FUNCTION ================================================================
163 # NAME: check_pid
164 # PARAMETERS:
165 # RETURNS:
166 # DESCRIPTION:
167 #===============================================================================
168 sub check_pid {
169 $pid = -1;
170 # Check, if we are already running
171 if( open(LOCK_FILE, "<$pid_file") ) {
172 $pid = <LOCK_FILE>;
173 if( defined $pid ) {
174 chomp( $pid );
175 if( -f "/proc/$pid/stat" ) {
176 my($stat) = `cat /proc/$pid/stat` =~ m/$pid \((.+)\).*/;
177 if( $0 eq $stat ) {
178 close( LOCK_FILE );
179 exit -1;
180 }
181 }
182 }
183 close( LOCK_FILE );
184 unlink( $pid_file );
185 }
187 # create a syslog msg if it is not to possible to open PID file
188 if (not sysopen(LOCK_FILE, $pid_file, O_WRONLY|O_CREAT|O_EXCL, 0644)) {
189 my($msg) = "Couldn't obtain lockfile '$pid_file' ";
190 if (open(LOCK_FILE, '<', $pid_file)
191 && ($pid = <LOCK_FILE>))
192 {
193 chomp($pid);
194 $msg .= "(PID $pid)\n";
195 } else {
196 $msg .= "(unable to read PID)\n";
197 }
198 if( ! ($foreground) ) {
199 openlog( $0, "cons,pid", "daemon" );
200 syslog( "warning", $msg );
201 closelog();
202 }
203 else {
204 print( STDERR " $msg " );
205 }
206 exit( -1 );
207 }
208 }
210 #=== FUNCTION ================================================================
211 # NAME: get_interface_for_ip
212 # PARAMETERS: ip address (i.e. 192.168.0.1)
213 # RETURNS: array: list of interfaces if ip=0.0.0.0, matching interface if found, undef else
214 # DESCRIPTION: Uses proc fs (/proc/net/dev) to get list of interfaces.
215 #===============================================================================
216 sub get_interface_for_ip {
217 my $result;
218 my $ip= shift;
219 if ($ip && length($ip) > 0) {
220 my @ifs= &get_interfaces();
221 if($ip eq "0.0.0.0") {
222 $result = "all";
223 } else {
224 foreach (@ifs) {
225 my $if=$_;
226 if(get_ip($if) eq $ip) {
227 $result = $if;
228 last;
229 }
230 }
231 }
232 }
233 return $result;
234 }
236 #=== FUNCTION ================================================================
237 # NAME: get_interfaces
238 # PARAMETERS: none
239 # RETURNS: (list of interfaces)
240 # DESCRIPTION: Uses proc fs (/proc/net/dev) to get list of interfaces.
241 #===============================================================================
242 sub get_interfaces {
243 my @result;
244 my $PROC_NET_DEV= ('/proc/net/dev');
246 open(PROC_NET_DEV, "<$PROC_NET_DEV")
247 or die "Could not open $PROC_NET_DEV";
249 my @ifs = <PROC_NET_DEV>;
251 close(PROC_NET_DEV);
253 # Eat first two line
254 shift @ifs;
255 shift @ifs;
257 chomp @ifs;
258 foreach my $line(@ifs) {
259 my $if= (split /:/, $line)[0];
260 $if =~ s/^\s+//;
261 push @result, $if;
262 }
264 return @result;
265 }
267 #=== FUNCTION ================================================================
268 # NAME: get_mac
269 # PARAMETERS: interface name (i.e. eth0)
270 # RETURNS: (mac address)
271 # DESCRIPTION: Uses ioctl to get mac address directly from system.
272 #===============================================================================
273 sub get_mac {
274 my $ifreq= shift;
275 my $result;
276 if ($ifreq && length($ifreq) > 0) {
277 if($ifreq eq "all") {
278 if(defined($server_ip)) {
279 $result = &get_local_mac_for_remote_ip($server_ip);
280 } else {
281 $result = "00:00:00:00:00:00";
282 }
283 } else {
284 my $SIOCGIFHWADDR= 0x8927; # man 2 ioctl_list
286 # A configured MAC Address should always override a guessed value
287 if ($client_mac_address and length($client_mac_address) > 0) {
288 $result= $client_mac_address;
289 }
291 socket SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('ip')
292 or die "socket: $!";
294 if(ioctl SOCKET, $SIOCGIFHWADDR, $ifreq) {
295 my ($if, $mac)= unpack 'h36 H12', $ifreq;
297 if (length($mac) > 0) {
298 $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])$/;
299 $mac= sprintf("%s:%s:%s:%s:%s:%s", $1, $2, $3, $4, $5, $6);
300 $result = $mac;
301 }
302 }
303 }
304 }
305 return $result;
306 }
308 #=== FUNCTION ================================================================
309 # NAME: get_ip
310 # PARAMETERS: interface name (i.e. eth0)
311 # RETURNS: (ip address)
312 # DESCRIPTION: Uses ioctl to get ip address directly from system.
313 #===============================================================================
314 sub get_ip {
315 my $ifreq= shift;
316 my $result= "";
317 my $SIOCGIFADDR= 0x8915; # man 2 ioctl_list
318 my $proto= getprotobyname('ip');
320 socket SOCKET, PF_INET, SOCK_DGRAM, $proto
321 or die "socket: $!";
323 if(ioctl SOCKET, $SIOCGIFADDR, $ifreq) {
324 my ($if, $sin) = unpack 'a16 a16', $ifreq;
325 my ($port, $addr) = sockaddr_in $sin;
326 my $ip = inet_ntoa $addr;
328 if ($ip && length($ip) > 0) {
329 $result = $ip;
330 }
331 }
333 return $result;
334 }
336 #=== FUNCTION ================================================================
337 # NAME: get_local_mac_for_remote_ip
338 # PARAMETERS: none (takes server_ip from global variable)
339 # RETURNS: (ip address from interface that is used for communication)
340 # DESCRIPTION: Uses ioctl to get routing table from system, checks which entry
341 # matches (defaultroute last).
342 #===============================================================================
343 sub get_local_mac_for_remote_ip {
344 my $ifreq= shift;
345 my $result= "00:00:00:00:00:00";
346 my $PROC_NET_ROUTE= ('/proc/net/route');
348 open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
349 or die "Could not open $PROC_NET_ROUTE";
351 my @ifs = <PROC_NET_ROUTE>;
353 close(PROC_NET_ROUTE);
355 # Eat header line
356 shift @ifs;
357 chomp @ifs;
358 foreach my $line(@ifs) {
359 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
360 my $destination;
361 my $mask;
362 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
363 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
364 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
365 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
366 if(new NetAddr::IP($server_ip)->within(new NetAddr::IP($destination, $mask))) {
367 # destination matches route, save mac and exit
368 $result= &get_mac($Iface);
369 last;
370 }
371 }
374 return $result;
375 }
377 #=== FUNCTION ================================================================
378 # NAME: usage
379 # PARAMETERS:
380 # RETURNS:
381 # DESCRIPTION:
382 #===============================================================================
383 sub usage {
384 my( $text, $help ) = @_;
385 $text = undef if( "h" eq $text );
386 (defined $text) && print STDERR "\n$text\n";
387 if( (defined $help && $help) || (!defined $help && !defined $text) ) {
388 print STDERR << "EOF" ;
389 usage: $0 [-hvf] [-c config]
391 -h : this (help) message
392 -c <file> : config file
393 -f : foreground, process will not be forked to background
394 -v : be verbose (multiple to increase verbosity)
395 EOF
396 }
397 print "\n" ;
398 }
400 #=== FUNCTION ================================================================
401 # NAME: get_server_addresses
402 # PARAMETERS:
403 # RETURNS:
404 # DESCRIPTION:
405 #===============================================================================
406 sub get_server_addresses {
407 my $domain= shift;
408 my @result;
409 my $dig_cmd= 'dig +nocomments srv _gosad._tcp.'.$domain;
411 my $output= `$dig_cmd 2>&1`;
412 open (PIPE, "$dig_cmd 2>&1 |");
413 while(<PIPE>) {
414 chomp $_;
415 # If it's not a comment
416 if($_ =~ m/^[^;]/) {
417 my @matches= split /\s+/;
419 # Push hostname with port
420 if($matches[3] eq 'SRV') {
421 push @result, $matches[7].':'.$matches[6];
422 } elsif ($matches[3] eq 'A') {
423 my $i=0;
425 # Substitute the hostname with the ip address of the matching A record
426 foreach my $host (@result) {
427 if ((split /\:/, $host)[0] eq $matches[0]) {
428 $result[$i]= $matches[4].':'.(split /\:/, $host)[1];
429 }
430 $i++;
431 }
432 }
433 }
434 }
435 close(PIPE);
436 return @result;
437 }
440 #=== FUNCTION ================================================================
441 # NAME: register_at_server
442 # PARAMETERS:
443 # RETURNS:
444 # DESCRIPTION:
445 #===============================================================================
446 sub register_at_server {
447 my ($tmp) = @_;
449 # create new passwd and ciphering object for client-server communication
450 my $new_server_passwd = &create_passwd();
451 my $new_server_cipher;
453 # detect all client accepted events
454 opendir(DIR, $event_dir)
455 or daemon_log("cannot find directory $event_dir!\ngosa-si-client starts without any accepting events!", 1);
456 my $file_name;
457 my @events_list = ();
458 while(defined($file_name = readdir(DIR))){
459 if ($file_name eq "." || $file_name eq "..") {
460 next;
461 }
462 push(@events_list, $file_name);
463 }
464 my $events = join(",", @events_list);
465 daemon_log("found events: $events", 1);
467 # fill in all possible servers
468 my @servers;
469 if (defined $server_domain) {
470 my @tmp_servers = &get_server_addresses($server_domain);
471 foreach my $server (@tmp_servers) { unshift(@servers, $server); }
472 }
473 # add server address from config file at first position of server list
474 if (defined $server_address) {
475 unshift(@servers, $server_address);
476 }
477 daemon_log("found servers in configuration file and via DNS:", 5);
478 foreach my $server (@servers) {
479 daemon_log("\t$server", 5);
480 }
482 my ($rout, $wout, $reg_server);
483 foreach my $server (@servers) {
485 # create msg hash
486 my $register_hash = &create_xml_hash("here_i_am", $client_address, $server);
487 &add_content2xml_hash($register_hash, "new_passwd", $new_server_passwd);
488 &add_content2xml_hash($register_hash, "mac_address", $client_mac_address);
489 &add_content2xml_hash($register_hash, "events", $events);
490 &add_content2xml_hash($register_hash, "gotoHardwareChecksum", $gotoHardwareChecksum);
492 # send xml hash to server with general server passwd
493 my $answer = &send_msg_hash2address($register_hash, $server, $server_passwd);
495 if ($answer != 0) { next; }
497 # waiting for response
498 daemon_log("waiting for response...\n", 5);
499 my $nf = select($rout=$rbits, $wout=$wbits, undef, $server_timeout);
501 # something is coming in
502 if(vec $rout, fileno $input_socket, 1) {
503 my $crypted_msg;
504 my $client = $input_socket->accept();
505 my $other_end = getpeername($client);
506 if(not defined $other_end) {
507 daemon_log("client cannot be identified: $!\n");
508 } else {
509 my ($port, $iaddr) = unpack_sockaddr_in($other_end);
510 my $actual_ip = inet_ntoa($iaddr);
511 daemon_log("\naccept client from $actual_ip\n", 5);
512 my $in_msg = &read_from_socket($client);
513 if(defined $in_msg){
514 chomp($in_msg);
515 $crypted_msg = $in_msg;
516 } else {
517 daemon_log("cannot read from $actual_ip\n", 5);
518 }
519 }
520 close($client);
522 # validate acknowledge msg from server
523 $new_server_cipher = &create_ciphering($new_server_passwd);
524 my $msg_hash;
525 eval {
526 my $decrypted_msg = &decrypt_msg($crypted_msg, $new_server_cipher);
527 daemon_log("decrypted register msg: $decrypted_msg", 5);
528 $msg_hash = $xml->XMLin($decrypted_msg, ForceArray=>1);
529 };
530 if($@) {
531 daemon_log("ERROR: do not understand the incoming message:" , 5);
532 daemon_log("$@", 7);
533 } else {
534 my $header = @{$msg_hash->{header}}[0];
535 if($header eq "registered") {
536 $reg_server = $server;
537 last;
538 } elsif($header eq "denied") {
539 my $reason = (&get_content_from_xml_hash($msg_hash, "denied"))[0];
540 daemon_log("registration at $server denied: $reason", 1);
541 } else {
542 daemon_log("cannot register at $server", 1);
543 }
544 }
545 }
546 # if no answer arrive, try next server in list
548 }
550 if(defined $reg_server) {
551 daemon_log("registered at $reg_server", 1);
552 } else {
553 daemon_log("cannot register at any server", 1);
554 daemon_log("exiting!!!", 1);
555 exit(1);
556 }
558 # update the global available variables
559 $server_address = $reg_server;
560 $server_passwd = $new_server_passwd;
561 $server_cipher = $new_server_cipher;
562 return;
563 }
566 #=== FUNCTION ================================================================
567 # NAME: create_xml_hash
568 # PARAMETERS:
569 # RETURNS:
570 # DESCRIPTION:
571 #===============================================================================
572 #sub create_xml_hash {
573 # my ($header, $source, $target, $header_value) = @_;
574 # my $hash = {
575 # header => [$header],
576 # source => [$source],
577 # target => [$target],
578 # $header => [$header_value],
579 # };
580 # daemon_log("create_xml_hash:", 7),
581 # chomp(my $tmp = Dumper $hash);
582 # daemon_log("\t$tmp\n", 7);
583 # return $hash
584 #}
587 #=== FUNCTION ================================================================
588 # NAME: create_xml_string
589 # PARAMETERS:
590 # RETURNS:
591 # DESCRIPTION:
592 #===============================================================================
593 #sub create_xml_string {
594 # my ($xml_hash) = @_ ;
595 # my $xml_string = $xml->XMLout($xml_hash, RootName => 'xml');
596 # $xml_string =~ s/[\n]+//g;
597 # daemon_log("create_xml_string:\n\t$xml_string\n", 7);
598 # return $xml_string;
599 #}
602 #=== FUNCTION ================================================================
603 # NAME: add_content2xml_hash
604 # PARAMETERS:
605 # RETURNS:
606 # DESCRIPTION:
607 #===============================================================================
608 #sub add_content2xml_hash {
609 # my ($xml_ref, $element, $content) = @_;
610 # if(not exists $$xml_ref{$element} ) {
611 # $$xml_ref{$element} = [];
612 # }
613 # my $tmp = $$xml_ref{$element};
614 # push(@$tmp, $content);
615 # return;
616 #}
619 #=== FUNCTION ================================================================
620 # NAME: get_content_from_xml_hash
621 # PARAMETERS: ref : reference to the xml hash
622 # string: key of the value you want
623 # RETURNS: STRING AND ARRAY
624 # DESCRIPTION: if key of the hash is either 'header', 'target' or 'source' the
625 # function returns a string cause it is expected that these keys
626 # do just have one value, all other keys returns an array!!!
627 #===============================================================================
628 #sub get_content_from_xml_hash {
629 # my ($xml_ref, $element) = @_;
630 # my $result = $xml_ref->{$element};
631 # if( $element eq "header" || $element eq "target" || $element eq "source") {
632 # return @$result[0];
633 # }
634 # return @$result;
635 #}
637 # my ($xml_ref, $element) = @_;
638 # if (exists $xml_ref->{$element}) {
639 # my $result = $xml_ref->{$element};
640 # if( $element eq "header" || $element eq "target" || $element eq "source") {
641 # return @$result[0];
642 # } else {
643 # return @$result;
644 # }
645 #
646 # } else {
647 # my $result = ();
648 # return @$result;
649 # }
650 #}
653 #=== FUNCTION ================================================================
654 # NAME: encrypt_msg
655 # PARAMETERS:
656 # RETURNS:
657 # DESCRIPTION:
658 #===============================================================================
659 #sub encrypt_msg {
660 # my ($msg, $my_cipher) = @_;
661 # if(not defined $my_cipher) { print "no cipher object\n"; }
662 # $msg = "\0"x(16-length($msg)%16).$msg;
663 # my $crypted_msg = $my_cipher->encrypt($msg);
664 # chomp($crypted_msg = &encode_base64($crypted_msg));
665 # return $crypted_msg;
666 #}
669 #=== FUNCTION ================================================================
670 # NAME: decrypt_msg
671 # PARAMETERS:
672 # RETURNS:
673 # DESCRIPTION:
674 #===============================================================================
675 #sub decrypt_msg {
676 # my ($crypted_msg, $my_cipher) = @_ ;
677 # $crypted_msg = &decode_base64($crypted_msg);
678 # my $msg = $my_cipher->decrypt($crypted_msg);
679 # $msg =~ s/\0*//g;
680 # return $msg;
681 #}
684 #=== FUNCTION ================================================================
685 # NAME: create_ciphering
686 # PARAMETERS:
687 # RETURNS: cipher object
688 # DESCRIPTION:
689 #===============================================================================
690 #sub create_ciphering {
691 # my ($passwd) = @_;
692 # $passwd = substr(md5_hex("$passwd") x 32, 0, 32);
693 # my $iv = substr(md5_hex('GONICUS GmbH'),0, 16);
694 #
695 # #daemon_log("iv: $iv", 7);
696 # #daemon_log("key: $passwd", 7);
697 # my $my_cipher = Crypt::Rijndael->new($passwd , Crypt::Rijndael::MODE_CBC());
698 # $my_cipher->set_iv($iv);
699 # return $my_cipher;
700 #}
703 #=== FUNCTION ================================================================
704 # NAME: create_passwd
705 # PARAMETERS:
706 # RETURNS: cipher object
707 # DESCRIPTION:
708 #===============================================================================
709 sub create_passwd {
710 my $new_passwd = "";
711 for(my $i=0; $i<31; $i++) {
712 $new_passwd .= ("a".."z","A".."Z",0..9)[int(rand(62))]
713 }
715 return $new_passwd;
716 }
719 #=== FUNCTION ================================================================
720 # NAME: send_msg_hash2address
721 # PARAMETERS: msg string - xml message
722 # PeerAddr string - socket address to send msg
723 # PeerPort string - socket port, if not included in socket address
724 # RETURNS: nothing
725 # DESCRIPTION: ????
726 #===============================================================================
727 #sub send_msg_hash2address {
728 # my ($msg_hash, $address, $passwd) = @_ ;
729 #
730 # # fetch header for logging
731 # my $header = @{$msg_hash->{header}}[0];
732 #
733 # # generiere xml string
734 # my $msg_xml = &create_xml_string($msg_hash);
735 #
736 # # hole das entsprechende passwd aus dem hash
737 # if(not defined $passwd) {
738 # if(exists $known_hosts->{$address}) {
739 # $passwd = $known_hosts->{$address}->{passwd};
740 # } elsif ($address eq $server_address) {
741 # $passwd = $server_passwd;
742 # } else {
743 # daemon_log("$address not known, neither as server nor as client", 1);
744 # return "failed";
745 # }
746 # }
747 #
748 # # erzeuge ein ciphering object
749 # my $act_cipher = &create_ciphering($passwd);
750 #
751 # # encrypt xml msg
752 # my $crypted_msg = &encrypt_msg($msg_xml, $act_cipher);
753 #
754 # # öffne socket
755 # my $socket = &open_socket($address);
756 # if(not defined $socket){
757 # daemon_log("cannot open socket to $address, server not reachable", 1);
758 # daemon_log("cannot send '$header'-msg", 1);
759 # return "failed";
760 # }
761 #
762 # # versende xml msg
763 # print $socket $crypted_msg."\n";
764 #
765 # # schlieĂźe socket
766 # close $socket;
767 #
768 # daemon_log("send '$header'-msg to $address", 5);
769 # daemon_log("crypted_msg:\n\t$crypted_msg", 7);
770 #
771 # return "done";
772 #}
775 #=== FUNCTION ================================================================
776 # NAME: open_socket
777 # PARAMETERS: PeerAddr string something like 192.168.1.1 or 192.168.1.1:10000
778 # [PeerPort] string necessary if port not appended by PeerAddr
779 # RETURNS: socket IO::Socket::INET
780 # DESCRIPTION:
781 #===============================================================================
782 sub open_socket {
783 my ($PeerAddr, $PeerPort) = @_ ;
784 if(defined($PeerPort)){
785 $PeerAddr = $PeerAddr.":".$PeerPort;
786 }
787 my $socket;
788 $socket = new IO::Socket::INET(PeerAddr => $PeerAddr ,
789 Porto => "tcp" ,
790 Type => SOCK_STREAM,
791 Timeout => 5,
792 );
793 if(not defined $socket) {
794 #daemon_log("cannot connect to socket at $PeerAddr, $@\n");
795 return;
796 }
797 daemon_log("open_socket:\n\t$PeerAddr", 7);
798 return $socket;
799 }
802 #=== FUNCTION ================================================================
803 # NAME: read_from_socket
804 # PARAMETERS: socket fh -
805 # RETURNS: result string - readed characters from socket
806 # DESCRIPTION: reads data from socket in 16 byte steps
807 #===============================================================================
808 sub read_from_socket {
809 my ($socket) = @_;
810 my $result = "";
812 $socket->blocking(1);
813 $result = <$socket>;
815 $socket->blocking(0);
816 while ( my $char = <$socket> ) {
817 if (not defined $char) { last }
818 $result .= $char;
819 }
820 return $result;
824 # my ($socket) = @_;
825 # my $result = "";
826 # my $len = 16;
827 # while($len == 16){
828 # my $char;
829 # $len = sysread($socket, $char, 16);
830 # if($len != 16) { last }
831 # if($len != 16) { last }
832 # $result .= $char;
833 # }
834 # return $result;
835 }
838 #=== FUNCTION ================================================================
839 # NAME: print_known_hosts_hash
840 # PARAMETERS:
841 # RETURNS:
842 # DESCRIPTION:
843 #===============================================================================
844 sub print_known_hosts_hash {
845 my ($tmp) = @_;
846 print "####################################\n";
847 print "# status of known_hosts\n";
848 my $hosts;
849 my $host_hash;
850 my @hosts = keys %$known_hosts;
851 foreach my $host (@hosts) {
852 #my @elements = keys %$known_hosts->{$host};
853 my $status = $known_hosts->{$host}->{status} ;
854 my $passwd = $known_hosts->{$host}->{passwd};
855 my $timestamp = $known_hosts->{$host}->{timestamp};
856 print "$host\n";
857 print "\t$status\n";
858 print "\t$passwd\n";
859 print "\t$timestamp\n";
860 }
861 print "####################################\n";
862 return;
863 }
865 #=== FUNCTION ================================================================
866 # NAME:
867 # PARAMETERS:
868 # RETURNS:
869 # DESCRIPTION:
870 #===============================================================================
871 sub create_known_hosts_entry {
872 my ($hostname) = @_;
873 $known_hosts->{$hostname} = {};
874 $known_hosts->{$hostname}->{status} = "none";
875 $known_hosts->{$hostname}->{passwd} = "none";
876 $known_hosts->{$hostname}->{timestamp} = "none";
877 return;
878 }
881 #=== FUNCTION ================================================================
882 # NAME:
883 # PARAMETERS:
884 # RETURNS:
885 # DESCRIPTION:
886 #===============================================================================
887 sub update_known_hosts_entry {
888 my ($hostname, $status, $passwd, $timestamp) = @_;
889 my ($seconds, $minutes, $hours, $monthday, $month,
890 $year, $weekday, $yearday, $sommertime) = localtime(time);
891 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
892 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
893 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
894 $month+=1;
895 $month = $month < 10 ? $month = "0".$month : $month;
896 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
897 $year+=1900;
898 my $t = "$year$month$monthday$hours$minutes$seconds";
900 if($status) {
901 $known_hosts->{$hostname}->{status} = $status;
902 }
903 if($passwd) {
904 $known_hosts->{$hostname}->{passwd} = $passwd;
905 }
906 if($timestamp) {
907 $t = $timestamp;
908 }
909 $known_hosts->{$hostname}->{timestamp} = $t;
910 return;
911 }
914 #=== FUNCTION ================================================================
915 # NAME:
916 # PARAMETERS:
917 # RETURNS:
918 # DESCRIPTION:
919 #===============================================================================
920 sub add_content2known_hosts {
921 my ($hostname, $element, $content) = @_;
922 my ($seconds, $minutes, $hours, $monthday, $month,
923 $year, $weekday, $yearday, $sommertime) = localtime(time);
924 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
925 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
926 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
927 $month+=1;
928 $month = $month < 10 ? $month = "0".$month : $month;
929 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
930 $year+=1900;
931 my $t = "$year$month$monthday$hours$minutes$seconds";
933 $known_hosts->{$hostname}->{$element} = $content;
934 $known_hosts->{$hostname}->{timestamp} = $t;
935 return;
936 }
939 #=== FUNCTION ================================================================
940 # NAME:
941 # PARAMETERS:
942 # RETURNS:
943 # DESCRIPTION:
944 #===============================================================================
945 sub process_incoming_msg {
946 my ($crypted_msg) = @_;
947 if(not defined $crypted_msg) {
948 daemon_log("function 'process_incoming_msg': got no msg", 7);
949 }
950 $crypted_msg =~ /^([\s\S]*?)\.(\d{1,3}?)\.(\d{1,3}?)\.(\d{1,3}?)\.(\d{1,3}?)$/;
951 $crypted_msg = $1;
952 my $host = sprintf("%s.%s.%s.%s", $2, $3, $4, $5);
953 daemon_log("msg from host:", 1);
954 daemon_log("\t$host", 1);
955 daemon_log("crypted msg:", 7);
956 daemon_log("\t$crypted_msg", 7);
958 my $act_cipher = &create_ciphering($server_passwd);
960 # try to decrypt incoming msg
961 my ($msg, $msg_hash);
962 eval{
963 $msg = &decrypt_msg($crypted_msg, $act_cipher);
964 $msg_hash = $xml->XMLin($msg, ForceArray=>1);
965 };
966 if($@) {
967 daemon_log("ERROR: incoming msg cannot be decrypted with server passwd", 1);
968 return;
969 }
971 my $header = @{$msg_hash->{header}}[0];
973 daemon_log("receive '$header' from $host", 1);
975 #check whether msg to process is a event
976 opendir(DIR, $event_dir)
977 or daemon_log("cannot find directory $event_dir, no events specified", 5);
978 my $file_name;
979 while(defined($file_name = readdir(DIR))){
980 if ($file_name eq "." || $file_name eq "..") {
981 next;
982 }
983 if ($file_name eq $header) {
984 my $cmd = "$event_dir/$file_name '$msg'";
985 my $result_xml = "";
986 open(PIPE, "$cmd 2>&1 |");
987 while(<PIPE>) {
988 $result_xml.=$_;
989 last;
990 }
991 close(PIPE);
992 my $res_hash = &transform_msg2hash($result_xml);
993 my $res_target = @{$res_hash->{target}}[0];
994 &send_msg_hash2address($res_hash, $server_address);
996 return;
997 }
998 }
999 close(DIR);
1000 daemon_log("could not assign the msg $header to an event", 5);
1002 if ($header eq 'new_ldap_config') { if ($ldap_enabled == 1) {&new_ldap_config($msg_hash)}}
1003 elsif ($header eq 'ping') { &got_ping($msg_hash) }
1004 elsif ($header eq 'wake_up') { &execute_event($msg_hash)}
1005 elsif ($header eq 'new_passwd') { &new_passwd()}
1006 else { daemon_log("ERROR: no function assigned to msg $header", 5) }
1008 return;
1009 }
1012 #=== FUNCTION ================================================================
1013 # NAME:
1014 # PARAMETERS:
1015 # RETURNS:
1016 # DESCRIPTION:
1017 #===============================================================================
1018 sub update_status {
1019 my ($new_status) = @_ ;
1020 my $out_hash = &create_xml_hash("update_status", $client_address, $server_address);
1021 &add_content2xml_hash($out_hash, "update_status", $new_status);
1022 &send_msg_hash2address($out_hash, $server_address);
1023 return;
1024 }
1027 #=== FUNCTION ================================================================
1028 # NAME:
1029 # PARAMETERS:
1030 # RETURNS:
1031 # DESCRIPTION:
1032 #===============================================================================
1033 sub server_leaving {
1034 my ($msg_hash) = @_ ;
1035 my $source = &get_content_from_xml_hash("source");
1036 my $header = &get_content_from_xml_hash("header");
1038 daemon_log("gosa daemon $source is going down, cause registration procedure", 1);
1039 my $server_address = "none";
1040 my $server_passwd = "none";
1041 my $server_cipher = "none";
1043 # reinitialization of default values in config file
1044 &read_configfile;
1046 # registrated at new daemon
1047 ®ister_at_server();
1049 return;
1050 }
1053 sub got_ping {
1054 my ($msg_hash) = @_ ;
1056 my $source = &get_content_from_xml_hash($msg_hash, 'source');
1057 my $target = &get_content_from_xml_hash($msg_hash, 'target');
1058 my $header = &get_content_from_xml_hash($msg_hash, 'header');
1060 &add_content2known_hosts(hostname=>$target, status=>$header);
1062 my $out_hash = &create_xml_hash("got_ping", $target, $source);
1063 &send_msg_hash2address($out_hash, $source, $server_passwd);
1065 return;
1066 }
1069 sub new_ldap_config {
1070 my ($msg_hash) = @_ ;
1071 my $element;
1072 my @ldap_uris;
1073 my $ldap_base;
1074 my @ldap_options;
1075 my @pam_options;
1076 my @nss_options;
1077 my $goto_admin;
1078 my $goto_secret;
1079 my $admin_base= "";
1080 my $department= "";
1081 my $unit_tag;
1083 # Transform input into array
1084 while ( my ($key, $value) = each(%$msg_hash) ) {
1085 if ($key =~ /^(source|target|header)$/) {
1086 next;
1087 }
1089 foreach $element (@$value) {
1090 if ($key =~ /^ldap_uri$/) {
1091 push (@ldap_uris, $element);
1092 next;
1093 }
1094 if ($key =~ /^ldap_base$/) {
1095 $ldap_base= $element;
1096 next;
1097 }
1098 if ($key =~ /^goto_admin$/) {
1099 $goto_admin= $element;
1100 next;
1101 }
1102 if ($key =~ /^goto_secret$/) {
1103 $goto_secret= $element;
1104 next;
1105 }
1106 if ($key =~ /^ldap_cfg$/) {
1107 push (@ldap_options, "$element");
1108 next;
1109 }
1110 if ($key =~ /^pam_cfg$/) {
1111 push (@pam_options, "$element");
1112 next;
1113 }
1114 if ($key =~ /^nss_cfg$/) {
1115 push (@nss_options, "$element");
1116 next;
1117 }
1118 if ($key =~ /^admin_base$/) {
1119 $admin_base= $element;
1120 next;
1121 }
1122 if ($key =~ /^department$/) {
1123 $department= $element;
1124 next;
1125 }
1126 if ($key =~ /^unit_tag$/) {
1127 $unit_tag= $element;
1128 next;
1129 }
1130 }
1131 }
1133 # Unit tagging enabled?
1134 if (defined $unit_tag){
1135 push (@pam_options, "pam_filter gosaUnitTag=$unit_tag");
1136 push (@nss_options, "nss_base_passwd $admin_base?sub?gosaUnitTag=$unit_tag");
1137 push (@nss_options, "nss_base_group $admin_base?sub?gosaUnitTag=$unit_tag");
1138 }
1140 # Setup ldap.conf
1141 my $file1;
1142 my $file2;
1143 open(file1, "> $ldap_config");
1144 print file1 "# This file was automatically generated by gosa-si-client. Do not change.\n";
1145 print file1 "URI";
1146 foreach $element (@ldap_uris) {
1147 print file1 " $element";
1148 }
1149 print file1 "\nBASE $ldap_base\n";
1150 foreach $element (@ldap_options) {
1151 print file1 "$element\n";
1152 }
1153 close (file1);
1154 daemon_log("wrote $ldap_config", 5);
1156 # Setup pam_ldap.conf / libnss_ldap.conf
1157 open(file1, "> $pam_config");
1158 open(file2, "> $nss_config");
1159 print file1 "# This file was automatically generated by gosa-si-client. Do not change.\n";
1160 print file2 "# This file was automatically generated by gosa-si-client. Do not change.\n";
1161 print file1 "uri";
1162 print file2 "uri";
1163 foreach $element (@ldap_uris) {
1164 print file1 " $element";
1165 print file2 " $element";
1166 }
1167 print file1 "\nbase $ldap_base\n";
1168 print file2 "\nbase $ldap_base\n";
1169 foreach $element (@pam_options) {
1170 print file1 "$element\n";
1171 }
1172 foreach $element (@nss_options) {
1173 print file2 "$element\n";
1174 }
1175 close (file2);
1176 daemon_log("wrote $nss_config", 5);
1177 close (file1);
1178 daemon_log("wrote $pam_config", 5);
1180 # Create goto.secrets if told so - for compatibility reasons
1181 if (defined $goto_admin){
1182 open(file1, "> /etc/goto/secret");
1183 close(file1);
1184 chown(0,0, "/etc/goto/secret");
1185 chmod(0600, "/etc/goto/secret");
1186 open(file1, "> /etc/goto/secret");
1187 print file1 "GOTOADMIN=\"$goto_admin\"\nGOTOSECRET=\"$goto_secret\"\n";
1188 close(file1);
1189 daemon_log("wrote /etc/goto/secret", 5);
1190 }
1194 # Write shell based config
1195 my $cfg_name= dirname($ldap_config)."/ldap-shell.conf";
1196 open(file1, "> $cfg_name");
1197 print file1 "LDAP_BASE=\"$ldap_base\"\n";
1198 print file1 "ADMIN_BASE=\"$admin_base\"\n";
1199 print file1 "DEPARTMENT=\"$department\"\n";
1200 print file1 "UNIT_TAG=\"".(defined $unit_tag ? "$unit_tag" : "")."\"\n";
1201 print file1 "UNIT_TAG_FILTER=\"".(defined $unit_tag ? "(gosaUnitTag=$unit_tag)" : "")."\"\n";
1202 close(file1);
1203 daemon_log("wrote $cfg_name", 5);
1205 return;
1207 }
1210 sub execute_event {
1211 my ($msg_hash)= @_;
1212 my $configdir= '/etc/gosa-si/client/events/';
1213 my $result;
1215 my $header = &get_content_from_xml_hash($msg_hash, 'header');
1216 my $source = &get_content_from_xml_hash($msg_hash, 'source');
1217 my $target = &get_content_from_xml_hash($msg_hash, 'target');
1220 if((not defined $source)
1221 && (not defined $target)
1222 && (not defined $header)) {
1223 daemon_log("ERROR: Entries missing in XML msg for gosa events under $configdir");
1224 } else {
1225 my $parameters="";
1226 my @params = &get_content_from_xml_hash($msg_hash, $header);
1227 my $params = join(", ", @params);
1228 daemon_log("execute_event: got parameters: $params", 5);
1230 if (@params) {
1231 foreach my $param (@params) {
1232 my $param_value = (&get_content_from_xml_hash($msg_hash, $param))[0];
1233 daemon_log("execute_event: parameter -> value: $param -> $param_value", 7);
1234 $parameters.= " ".$param_value;
1235 }
1236 }
1238 my $cmd= $configdir.$header."$parameters";
1239 daemon_log("execute_event: executing cmd: $cmd", 7);
1240 $result= "";
1241 open(PIPE, "$cmd 2>&1 |");
1242 while(<PIPE>) {
1243 $result.=$_;
1244 }
1245 close(PIPE);
1246 }
1248 # process the event result
1251 return;
1252 }
1255 sub new_passwd {
1256 # my ($msg_hash) = @_ ;
1257 my $new_server_passwd = &create_passwd();
1258 my $new_server_cipher = &create_ciphering($new_server_passwd);
1260 my $out_hash = &create_xml_hash("new_passwd", $client_address, $server_address, $new_server_passwd);
1262 &send_msg_hash2address($out_hash, $server_address, $server_passwd);
1264 $server_passwd = $new_server_passwd;
1265 $server_cipher = $new_server_cipher;
1266 return;
1267 }
1269 sub generate_hw_digest {
1270 my $hw_data;
1271 foreach my $line (split /\n/, `cat /proc/bus/pci/devices`) {
1272 $hw_data.= sprintf "%s", $line =~ /[^\s]+\s([^\s]+)\s.*/;
1273 }
1274 return(md5_base64($hw_data));
1275 }
1277 sub detect_hardware {
1278 my $hwinfo= `which hwinfo`;
1279 chomp $hwinfo;
1281 if (!(defined($hwinfo) && length($hwinfo) > 0)) {
1282 print "ERROR: hwinfo was not found in \$PATH!\n";
1283 exit(1);
1284 }
1286 my $result= {
1287 gotoXDriver => "",
1288 gotoXMouseType => "",
1289 gotoXMouseport => "",
1290 gotoXkbModel => "",
1291 gotoXHsync => "",
1292 gotoXVsync => "",
1293 gotoXResolution => "",
1294 ghUsbSupport => "",
1295 gotoSndModule => "",
1296 ghGfxAdapter => "",
1297 ghNetNic => "",
1298 ghSoundAdapter => "",
1299 ghMemSize => "",
1300 ghCpuType => "",
1301 gotoModules => [],
1302 ghIdeDev => [],
1303 ghScsiDev => [],
1304 };
1306 my $gfxcard= `$hwinfo --gfxcard`;
1307 my $primary_adapter= $1 if $gfxcard =~ /^Primary display adapter:\s#(\d+)\n/m;
1308 if(defined($primary_adapter)) {
1309 ($result->{ghGfxAdapter}, $result->{gotoXDriver}) = ($1,$2) if
1310 $gfxcard =~ /$primary_adapter:.*?Model:\s\"([^\"]*)\".*?Server Module:\s(\w*).*?\n\n/s;
1311 }
1312 my $monitor= `$hwinfo --monitor`;
1313 my $primary_monitor= $1 if $monitor =~ /^(\d*):.*/m;
1314 if(defined($primary_monitor)) {
1315 ($result->{gotoXResolution}, $result->{gotoXVsync}, $result->{gotoXHsync})= ($1,$2,$3) if
1316 $monitor =~ /$primary_monitor:\s.*?Max\.\sResolution:\s([0-9x]*).*?Vert\.\sSync\sRange:\s([\d\-]*)\sHz.*?Hor\.\sSync\sRange:\s([\d\-]*)\skHz.*/s;
1317 }
1319 if(length($result->{gotoXHsync}) == 0) {
1320 # set default values
1321 $result->{gotoXHsync} = "30+50";
1322 $result->{gotoXVsync} = "30+90";
1323 }
1325 my $mouse= `$hwinfo --mouse`;
1326 my $primary_mouse= $1 if $mouse =~ /^(\d*):.*/m;
1327 if(defined($primary_mouse)) {
1328 ($result->{gotoXMouseport}, $result->{gotoXMouseType}) = ($1,$2) if
1329 $mouse =~ /$primary_mouse:\s.*?Device\sFile:\s(.*?)\s.*?XFree86\sProtocol:\s(.*?)\n.*?/s;
1330 }
1332 my $sound= `$hwinfo --sound`;
1333 my $primary_sound= $1 if $sound =~ /^(\d*):.*/m;
1334 if(defined($primary_sound)) {
1335 ($result->{ghSoundAdapter}, $result->{gotoSndModule})= ($1,$2) if
1336 $sound =~ /$primary_sound:\s.*?Model:\s\"(.*?)\".*?Driver\sModules:\s\"(.*?)\".*/s;
1337 }
1339 my $netcard= `hwinfo --netcard`;
1340 my $primary_netcard= $1 if $netcard =~ /^(\d*):.*/m;
1341 if(defined($primary_netcard)) {
1342 $result->{ghNetNic}= $1 if $netcard =~ /$primary_netcard:\s.*?Model:\s\"(.*?)\".*/s;
1343 }
1345 my $keyboard= `hwinfo --keyboard`;
1346 my $primary_keyboard= $1 if $keyboard =~ /^(\d*):.*/m;
1347 if(defined($primary_keyboard)) {
1348 $result->{gotoXkbModel}= $1 if $keyboard =~ /$primary_keyboard:\s.*?XkbModel:\s(.*?)\n.*/s;
1349 }
1351 $result->{ghCpuType}= sprintf "%s / %s - %s",
1352 `cat /proc/cpuinfo` =~ /.*?vendor_id\s+:\s(.*?)\n.*?model\sname\s+:\s(.*?)\n.*?cpu\sMHz\s+:\s(.*?)\n.*/s;
1353 $result->{ghMemSize}= $1 if `cat /proc/meminfo` =~ /^MemTotal:\s+(.*?)\skB.*/s;
1355 my @gotoModules=();
1356 for my $line(`lsmod`) {
1357 if (($line =~ /^Module.*$/) or ($line =~ /^snd.*$/)) {
1358 next;
1359 } else {
1360 push @gotoModules, $1 if $line =~ /^(\w*).*$/
1361 }
1362 }
1363 my %seen = ();
1365 # Remove duplicates and save
1366 push @{$result->{gotoModules}}, grep { ! $seen{$_} ++ } @gotoModules;
1368 $result->{ghUsbSupport} = (-d "/proc/bus/usb")?"true":"false";
1370 #TODO Ide detection
1371 #$result->{ghIdeDev} = $@ if ``
1372 #opendir(IDE, "/proc/ide");
1373 #for my $model(grep /ide\d\/hd\w\/model/, readdir(DIR)) {
1374 # print "$model\n";
1375 #}
1376 #close(IDE);
1378 while ( `cat /proc/scsi/scsi` =~ /^.*?Vendor:\s(.*?)\s+Model:\s(.*?)\s+.*$/mg ) {
1379 push (@{$result->{ghScsiDev}}, "$1 $2");
1380 }
1382 return $result;
1383 }
1385 #==== MAIN = main ==============================================================
1387 # parse commandline options
1388 Getopt::Long::Configure( "bundling" );
1389 GetOptions("h|help" => \&usage,
1390 "c|config=s" => \$cfg_file,
1391 "f|foreground" => \$foreground,
1392 "v|verbose+" => \$verbose,
1393 );
1395 # read and set config parameters
1396 &check_cmdline_param ;
1397 &read_configfile;
1398 &check_pid;
1400 if ( ! $foreground ) {
1401 open STDIN, '/dev/null' or die "Can’t read /dev/null: $!";
1402 open STDOUT, '>>/dev/null' or die "Can't write to /dev/null: $!";
1403 open STDERR, '>>/dev/null' or die "Can't write to /dev/null: $!";
1404 }
1407 # restart daemon log file
1408 if(-e $log_file ) { unlink $log_file }
1409 daemon_log(" ", 1);
1410 daemon_log("$0 started!", 1);
1412 # Just fork, if we"re not in foreground mode
1413 if( ! $foreground ) { $pid = fork(); }
1414 else { $pid = $$; }
1416 # Do something useful - put our PID into the pid_file
1417 if( 0 != $pid ) {
1418 open( LOCK_FILE, ">$pid_file" );
1419 print LOCK_FILE "$pid\n";
1420 close( LOCK_FILE );
1421 if( !$foreground ) { exit( 0 ) };
1422 }
1424 # detect own ip and mac address
1425 $network_interface= &get_interface_for_ip($client_ip);
1426 $client_mac_address= &get_mac($network_interface);
1428 # ($client_ip, $client_mac_address) = &get_ip_and_mac();
1429 #if (not defined $client_ip) {
1430 # die "EXIT: ip address of $0 could not be detected";
1431 #}
1432 daemon_log("client ip address detected: $client_ip", 1);
1433 daemon_log("client mac address detected: $client_mac_address", 1);
1435 # prepare variables
1436 if (defined $server_ip && defined $server_port) {
1437 $server_address = $server_ip.":".$server_port;
1438 }
1440 # this is necessary that gosa-si-server knowns to which ip-address he can send msgs
1441 if( $client_ip eq "0.0.0.0" ) {
1442 $client_ip = "127.0.0.1";
1443 }
1444 $client_address = $client_ip.":".$client_port;
1446 # setup xml parser
1447 $xml = new XML::Simple();
1449 # compute hardware checksum
1450 $gotoHardwareChecksum= &generate_hw_digest();
1452 # create input socket
1453 daemon_log(" ", 1);
1454 $rbits = $wbits = $ebits = "";
1455 $input_socket = IO::Socket::INET->new(LocalPort => $client_port,
1456 Type => SOCK_STREAM,
1457 Reuse => 1,
1458 Listen => 20,
1459 );
1460 if(not defined $input_socket){
1461 daemon_log("cannot be a tcp server at $client_port : $@\n");
1462 } else {
1463 daemon_log("start client at $client_address",1) ;
1464 vec($rbits, fileno $input_socket, 1) = 1;
1465 vec($wbits, fileno $input_socket, 1) = 1;
1466 }
1468 # register at server
1469 daemon_log(" ", 1);
1470 ®ister_at_server();
1473 ##############
1474 # Debugging
1475 #############
1476 #sleep(2);
1477 #&update_status("ich_bin_ein_neuer_status");
1479 ###################################
1480 #everything ready, okay, lets start
1481 ###################################
1482 while(1) {
1483 my ($rout, $wout);
1484 my $nf = select($rout=$rbits, $wout=$wbits, undef, undef);
1486 # error handling
1487 if($nf < 0 ) {
1488 }
1490 # something is coming in
1491 if(vec $rout, fileno $input_socket, 1) {
1492 my $client = $input_socket->accept();
1493 my $other_end = getpeername($client);
1495 if(not defined $other_end) {
1496 daemon_log("client cannot be identified: $!");
1497 } else {
1498 my ($port, $iaddr) = unpack_sockaddr_in($other_end);
1499 my $actual_ip = inet_ntoa($iaddr);
1500 daemon_log("accept client from $actual_ip", 5);
1501 my $in_msg = &read_from_socket($client);
1502 if(defined $in_msg){
1503 chomp($in_msg);
1504 $in_msg = $in_msg.".".$actual_ip;
1505 &process_incoming_msg($in_msg);
1507 }
1508 }
1509 }
1510 }