2076b09798e96d0da7df0ea1c3dca0cfa781b557
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 elsif ($header eq 'detect_hardware') { &detect_hardware()}
1007 else { daemon_log("ERROR: no function assigned to msg $header", 5) }
1009 return;
1010 }
1013 #=== FUNCTION ================================================================
1014 # NAME:
1015 # PARAMETERS:
1016 # RETURNS:
1017 # DESCRIPTION:
1018 #===============================================================================
1019 sub update_status {
1020 my ($new_status) = @_ ;
1021 my $out_hash = &create_xml_hash("update_status", $client_address, $server_address);
1022 &add_content2xml_hash($out_hash, "update_status", $new_status);
1023 &send_msg_hash2address($out_hash, $server_address);
1024 return;
1025 }
1028 #=== FUNCTION ================================================================
1029 # NAME:
1030 # PARAMETERS:
1031 # RETURNS:
1032 # DESCRIPTION:
1033 #===============================================================================
1034 sub server_leaving {
1035 my ($msg_hash) = @_ ;
1036 my $source = &get_content_from_xml_hash("source");
1037 my $header = &get_content_from_xml_hash("header");
1039 daemon_log("gosa daemon $source is going down, cause registration procedure", 1);
1040 my $server_address = "none";
1041 my $server_passwd = "none";
1042 my $server_cipher = "none";
1044 # reinitialization of default values in config file
1045 &read_configfile;
1047 # registrated at new daemon
1048 ®ister_at_server();
1050 return;
1051 }
1054 sub got_ping {
1055 my ($msg_hash) = @_ ;
1057 my $source = &get_content_from_xml_hash($msg_hash, 'source');
1058 my $target = &get_content_from_xml_hash($msg_hash, 'target');
1059 my $header = &get_content_from_xml_hash($msg_hash, 'header');
1061 &add_content2known_hosts(hostname=>$target, status=>$header);
1063 my $out_hash = &create_xml_hash("got_ping", $target, $source);
1064 &send_msg_hash2address($out_hash, $source, $server_passwd);
1066 return;
1067 }
1070 sub new_ldap_config {
1071 my ($msg_hash) = @_ ;
1072 my $element;
1073 my @ldap_uris;
1074 my $ldap_base;
1075 my @ldap_options;
1076 my @pam_options;
1077 my @nss_options;
1078 my $goto_admin;
1079 my $goto_secret;
1080 my $admin_base= "";
1081 my $department= "";
1082 my $unit_tag;
1084 # Transform input into array
1085 while ( my ($key, $value) = each(%$msg_hash) ) {
1086 if ($key =~ /^(source|target|header)$/) {
1087 next;
1088 }
1090 foreach $element (@$value) {
1091 if ($key =~ /^ldap_uri$/) {
1092 push (@ldap_uris, $element);
1093 next;
1094 }
1095 if ($key =~ /^ldap_base$/) {
1096 $ldap_base= $element;
1097 next;
1098 }
1099 if ($key =~ /^goto_admin$/) {
1100 $goto_admin= $element;
1101 next;
1102 }
1103 if ($key =~ /^goto_secret$/) {
1104 $goto_secret= $element;
1105 next;
1106 }
1107 if ($key =~ /^ldap_cfg$/) {
1108 push (@ldap_options, "$element");
1109 next;
1110 }
1111 if ($key =~ /^pam_cfg$/) {
1112 push (@pam_options, "$element");
1113 next;
1114 }
1115 if ($key =~ /^nss_cfg$/) {
1116 push (@nss_options, "$element");
1117 next;
1118 }
1119 if ($key =~ /^admin_base$/) {
1120 $admin_base= $element;
1121 next;
1122 }
1123 if ($key =~ /^department$/) {
1124 $department= $element;
1125 next;
1126 }
1127 if ($key =~ /^unit_tag$/) {
1128 $unit_tag= $element;
1129 next;
1130 }
1131 }
1132 }
1134 # Unit tagging enabled?
1135 if (defined $unit_tag){
1136 push (@pam_options, "pam_filter gosaUnitTag=$unit_tag");
1137 push (@nss_options, "nss_base_passwd $admin_base?sub?gosaUnitTag=$unit_tag");
1138 push (@nss_options, "nss_base_group $admin_base?sub?gosaUnitTag=$unit_tag");
1139 }
1141 # Setup ldap.conf
1142 my $file1;
1143 my $file2;
1144 open(file1, "> $ldap_config");
1145 print file1 "# This file was automatically generated by gosa-si-client. Do not change.\n";
1146 print file1 "URI";
1147 foreach $element (@ldap_uris) {
1148 print file1 " $element";
1149 }
1150 print file1 "\nBASE $ldap_base\n";
1151 foreach $element (@ldap_options) {
1152 print file1 "$element\n";
1153 }
1154 close (file1);
1155 daemon_log("wrote $ldap_config", 5);
1157 # Setup pam_ldap.conf / libnss_ldap.conf
1158 open(file1, "> $pam_config");
1159 open(file2, "> $nss_config");
1160 print file1 "# This file was automatically generated by gosa-si-client. Do not change.\n";
1161 print file2 "# This file was automatically generated by gosa-si-client. Do not change.\n";
1162 print file1 "uri";
1163 print file2 "uri";
1164 foreach $element (@ldap_uris) {
1165 print file1 " $element";
1166 print file2 " $element";
1167 }
1168 print file1 "\nbase $ldap_base\n";
1169 print file2 "\nbase $ldap_base\n";
1170 foreach $element (@pam_options) {
1171 print file1 "$element\n";
1172 }
1173 foreach $element (@nss_options) {
1174 print file2 "$element\n";
1175 }
1176 close (file2);
1177 daemon_log("wrote $nss_config", 5);
1178 close (file1);
1179 daemon_log("wrote $pam_config", 5);
1181 # Create goto.secrets if told so - for compatibility reasons
1182 if (defined $goto_admin){
1183 open(file1, "> /etc/goto/secret");
1184 close(file1);
1185 chown(0,0, "/etc/goto/secret");
1186 chmod(0600, "/etc/goto/secret");
1187 open(file1, "> /etc/goto/secret");
1188 print file1 "GOTOADMIN=\"$goto_admin\"\nGOTOSECRET=\"$goto_secret\"\n";
1189 close(file1);
1190 daemon_log("wrote /etc/goto/secret", 5);
1191 }
1195 # Write shell based config
1196 my $cfg_name= dirname($ldap_config)."/ldap-shell.conf";
1197 open(file1, "> $cfg_name");
1198 print file1 "LDAP_BASE=\"$ldap_base\"\n";
1199 print file1 "ADMIN_BASE=\"$admin_base\"\n";
1200 print file1 "DEPARTMENT=\"$department\"\n";
1201 print file1 "UNIT_TAG=\"".(defined $unit_tag ? "$unit_tag" : "")."\"\n";
1202 print file1 "UNIT_TAG_FILTER=\"".(defined $unit_tag ? "(gosaUnitTag=$unit_tag)" : "")."\"\n";
1203 close(file1);
1204 daemon_log("wrote $cfg_name", 5);
1206 return;
1208 }
1211 sub execute_event {
1212 my ($msg_hash)= @_;
1213 my $configdir= '/etc/gosa-si/client/events/';
1214 my $result;
1216 my $header = &get_content_from_xml_hash($msg_hash, 'header');
1217 my $source = &get_content_from_xml_hash($msg_hash, 'source');
1218 my $target = &get_content_from_xml_hash($msg_hash, 'target');
1221 if((not defined $source)
1222 && (not defined $target)
1223 && (not defined $header)) {
1224 daemon_log("ERROR: Entries missing in XML msg for gosa events under $configdir");
1225 } else {
1226 my $parameters="";
1227 my @params = &get_content_from_xml_hash($msg_hash, $header);
1228 my $params = join(", ", @params);
1229 daemon_log("execute_event: got parameters: $params", 5);
1231 if (@params) {
1232 foreach my $param (@params) {
1233 my $param_value = (&get_content_from_xml_hash($msg_hash, $param))[0];
1234 daemon_log("execute_event: parameter -> value: $param -> $param_value", 7);
1235 $parameters.= " ".$param_value;
1236 }
1237 }
1239 my $cmd= $configdir.$header."$parameters";
1240 daemon_log("execute_event: executing cmd: $cmd", 7);
1241 $result= "";
1242 open(PIPE, "$cmd 2>&1 |");
1243 while(<PIPE>) {
1244 $result.=$_;
1245 }
1246 close(PIPE);
1247 }
1249 # process the event result
1252 return;
1253 }
1256 sub new_passwd {
1257 # my ($msg_hash) = @_ ;
1258 my $new_server_passwd = &create_passwd();
1259 my $new_server_cipher = &create_ciphering($new_server_passwd);
1261 my $out_hash = &create_xml_hash("new_passwd", $client_address, $server_address, $new_server_passwd);
1263 &send_msg_hash2address($out_hash, $server_address, $server_passwd);
1265 $server_passwd = $new_server_passwd;
1266 $server_cipher = $new_server_cipher;
1267 return;
1268 }
1270 sub generate_hw_digest {
1271 my $hw_data;
1272 foreach my $line (split /\n/, `cat /proc/bus/pci/devices`) {
1273 $hw_data.= sprintf "%s", $line =~ /[^\s]+\s([^\s]+)\s.*/;
1274 }
1275 return(md5_base64($hw_data));
1276 }
1278 sub detect_hardware {
1279 my $hwinfo= `which hwinfo`;
1280 chomp $hwinfo;
1282 if (!(defined($hwinfo) && length($hwinfo) > 0)) {
1283 &main::daemon_log("ERROR: hwinfo was not found in \$PATH! Hardware detection will not work!", 1);
1284 return;
1285 }
1287 my $result= {
1288 gotoXDriver => "",
1289 gotoXMouseType => "",
1290 gotoXMouseport => "",
1291 gotoXkbModel => "",
1292 gotoXHsync => "",
1293 gotoXVsync => "",
1294 gotoXResolution => "",
1295 ghUsbSupport => "",
1296 gotoSndModule => "",
1297 ghGfxAdapter => "",
1298 ghNetNic => "",
1299 ghSoundAdapter => "",
1300 ghMemSize => "",
1301 ghCpuType => "",
1302 gotoModules => [],
1303 ghIdeDev => [],
1304 ghScsiDev => [],
1305 };
1307 &main::daemon_log("Starting hardware detection", 4);
1308 my $gfxcard= `$hwinfo --gfxcard`;
1309 my $primary_adapter= $1 if $gfxcard =~ /^Primary display adapter:\s#(\d+)\n/m;
1310 if(defined($primary_adapter)) {
1311 ($result->{ghGfxAdapter}, $result->{gotoXDriver}) = ($1,$2) if
1312 $gfxcard =~ /$primary_adapter:.*?Model:\s\"([^\"]*)\".*?Server Module:\s(\w*).*?\n\n/s;
1313 }
1314 my $monitor= `$hwinfo --monitor`;
1315 my $primary_monitor= $1 if $monitor =~ /^(\d*):.*/m;
1316 if(defined($primary_monitor)) {
1317 ($result->{gotoXResolution}, $result->{gotoXVsync}, $result->{gotoXHsync})= ($1,$2,$3) if
1318 $monitor =~ /$primary_monitor:\s.*?Max\.\sResolution:\s([0-9x]*).*?Vert\.\sSync\sRange:\s([\d\-]*)\sHz.*?Hor\.\sSync\sRange:\s([\d\-]*)\skHz.*/s;
1319 }
1321 if(length($result->{gotoXHsync}) == 0) {
1322 # set default values
1323 $result->{gotoXHsync} = "30+50";
1324 $result->{gotoXVsync} = "30+90";
1325 }
1327 my $mouse= `$hwinfo --mouse`;
1328 my $primary_mouse= $1 if $mouse =~ /^(\d*):.*/m;
1329 if(defined($primary_mouse)) {
1330 ($result->{gotoXMouseport}, $result->{gotoXMouseType}) = ($1,$2) if
1331 $mouse =~ /$primary_mouse:\s.*?Device\sFile:\s(.*?)\s.*?XFree86\sProtocol:\s(.*?)\n.*?/s;
1332 }
1334 my $sound= `$hwinfo --sound`;
1335 my $primary_sound= $1 if $sound =~ /^(\d*):.*/m;
1336 if(defined($primary_sound)) {
1337 ($result->{ghSoundAdapter}, $result->{gotoSndModule})= ($1,$2) if
1338 $sound =~ /$primary_sound:\s.*?Model:\s\"(.*?)\".*?Driver\sModules:\s\"(.*?)\".*/s;
1339 }
1341 my $netcard= `hwinfo --netcard`;
1342 my $primary_netcard= $1 if $netcard =~ /^(\d*):.*/m;
1343 if(defined($primary_netcard)) {
1344 $result->{ghNetNic}= $1 if $netcard =~ /$primary_netcard:\s.*?Model:\s\"(.*?)\".*/s;
1345 }
1347 my $keyboard= `hwinfo --keyboard`;
1348 my $primary_keyboard= $1 if $keyboard =~ /^(\d*):.*/m;
1349 if(defined($primary_keyboard)) {
1350 $result->{gotoXkbModel}= $1 if $keyboard =~ /$primary_keyboard:\s.*?XkbModel:\s(.*?)\n.*/s;
1351 }
1353 $result->{ghCpuType}= sprintf "%s / %s - %s",
1354 `cat /proc/cpuinfo` =~ /.*?vendor_id\s+:\s(.*?)\n.*?model\sname\s+:\s(.*?)\n.*?cpu\sMHz\s+:\s(.*?)\n.*/s;
1355 $result->{ghMemSize}= $1 if `cat /proc/meminfo` =~ /^MemTotal:\s+(.*?)\skB.*/s;
1357 my @gotoModules=();
1358 for my $line(`lsmod`) {
1359 if (($line =~ /^Module.*$/) or ($line =~ /^snd.*$/)) {
1360 next;
1361 } else {
1362 push @gotoModules, $1 if $line =~ /^(\w*).*$/
1363 }
1364 }
1365 my %seen = ();
1367 # Remove duplicates and save
1368 push @{$result->{gotoModules}}, grep { ! $seen{$_} ++ } @gotoModules;
1370 $result->{ghUsbSupport} = (-d "/proc/bus/usb")?"true":"false";
1372 #TODO Ide detection
1373 #$result->{ghIdeDev} = $@ if ``
1374 #opendir(IDE, "/proc/ide");
1375 #for my $model(grep /ide\d\/hd\w\/model/, readdir(DIR)) {
1376 # print "$model\n";
1377 #}
1378 #close(IDE);
1380 while ( `cat /proc/scsi/scsi` =~ /^.*?Vendor:\s(.*?)\s+Model:\s(.*?)\s+.*$/mg ) {
1381 push (@{$result->{ghScsiDev}}, "$1 $2");
1382 }
1384 &main::daemon_log("Hardware detection done!", 4);
1386 return &send_msg_hash2address(
1387 &create_xml_hash("detected_hardware", $client_address, $server_address, $result),
1388 $server_address,
1389 $server_passwd
1390 );
1391 }
1393 #==== MAIN = main ==============================================================
1395 # parse commandline options
1396 Getopt::Long::Configure( "bundling" );
1397 GetOptions("h|help" => \&usage,
1398 "c|config=s" => \$cfg_file,
1399 "f|foreground" => \$foreground,
1400 "v|verbose+" => \$verbose,
1401 );
1403 # read and set config parameters
1404 &check_cmdline_param ;
1405 &read_configfile;
1406 &check_pid;
1408 if ( ! $foreground ) {
1409 open STDIN, '/dev/null' or die "Can’t read /dev/null: $!";
1410 open STDOUT, '>>/dev/null' or die "Can't write to /dev/null: $!";
1411 open STDERR, '>>/dev/null' or die "Can't write to /dev/null: $!";
1412 }
1415 # restart daemon log file
1416 if(-e $log_file ) { unlink $log_file }
1417 daemon_log(" ", 1);
1418 daemon_log("$0 started!", 1);
1420 # Just fork, if we"re not in foreground mode
1421 if( ! $foreground ) { $pid = fork(); }
1422 else { $pid = $$; }
1424 # Do something useful - put our PID into the pid_file
1425 if( 0 != $pid ) {
1426 open( LOCK_FILE, ">$pid_file" );
1427 print LOCK_FILE "$pid\n";
1428 close( LOCK_FILE );
1429 if( !$foreground ) { exit( 0 ) };
1430 }
1432 # detect own ip and mac address
1433 $network_interface= &get_interface_for_ip($client_ip);
1434 $client_mac_address= &get_mac($network_interface);
1436 # ($client_ip, $client_mac_address) = &get_ip_and_mac();
1437 #if (not defined $client_ip) {
1438 # die "EXIT: ip address of $0 could not be detected";
1439 #}
1440 daemon_log("client ip address detected: $client_ip", 1);
1441 daemon_log("client mac address detected: $client_mac_address", 1);
1443 # prepare variables
1444 if (defined $server_ip && defined $server_port) {
1445 $server_address = $server_ip.":".$server_port;
1446 }
1448 # this is necessary that gosa-si-server knowns to which ip-address he can send msgs
1449 if( $client_ip eq "0.0.0.0" ) {
1450 $client_ip = "127.0.0.1";
1451 }
1452 $client_address = $client_ip.":".$client_port;
1454 # setup xml parser
1455 $xml = new XML::Simple();
1457 # compute hardware checksum
1458 $gotoHardwareChecksum= &generate_hw_digest();
1460 # create input socket
1461 daemon_log(" ", 1);
1462 $rbits = $wbits = $ebits = "";
1463 $input_socket = IO::Socket::INET->new(LocalPort => $client_port,
1464 Type => SOCK_STREAM,
1465 Reuse => 1,
1466 Listen => 20,
1467 );
1468 if(not defined $input_socket){
1469 daemon_log("cannot be a tcp server at $client_port : $@\n");
1470 } else {
1471 daemon_log("start client at $client_address",1) ;
1472 vec($rbits, fileno $input_socket, 1) = 1;
1473 vec($wbits, fileno $input_socket, 1) = 1;
1474 }
1476 # register at server
1477 daemon_log(" ", 1);
1478 ®ister_at_server();
1481 ##############
1482 # Debugging
1483 #############
1484 #sleep(2);
1485 #&update_status("ich_bin_ein_neuer_status");
1487 ###################################
1488 #everything ready, okay, lets start
1489 ###################################
1490 while(1) {
1491 my ($rout, $wout);
1492 my $nf = select($rout=$rbits, $wout=$wbits, undef, undef);
1494 # error handling
1495 if($nf < 0 ) {
1496 }
1498 # something is coming in
1499 if(vec $rout, fileno $input_socket, 1) {
1500 my $client = $input_socket->accept();
1501 my $other_end = getpeername($client);
1503 if(not defined $other_end) {
1504 daemon_log("client cannot be identified: $!");
1505 } else {
1506 my ($port, $iaddr) = unpack_sockaddr_in($other_end);
1507 my $actual_ip = inet_ntoa($iaddr);
1508 daemon_log("accept client from $actual_ip", 5);
1509 my $in_msg = &read_from_socket($client);
1510 if(defined $in_msg){
1511 chomp($in_msg);
1512 $in_msg = $in_msg.".".$actual_ip;
1513 &process_incoming_msg($in_msg);
1515 }
1516 }
1517 }
1518 }