Code

Fixed upper-lowercase problem of class names used when creating a new component.
[gosa.git] / contrib / daemon / gosa-sd
1 #!/usr/bin/perl 
2 #===============================================================================
3 #
4 #         FILE:  gosa-support-daemon.pl
5 #
6 #        USAGE:  ./.gosa-support-daemon.pl
7 #
8 #  DESCRIPTION:  
9 #
10 #      OPTIONS:  ---
11 # REQUIREMENTS:  ---
12 #         BUGS:  ---
13 #        NOTES:  ---
14 #       AUTHOR:   Andreas Rettenberger, <rettenberger@gonicus.de>
15 #      COMPANY:  Gonicus GmbH, Arnsberg
16 #      VERSION:  1.0
17 #      CREATED:  21.08.2007 15:13:51 CEST
18 #     REVISION:  ---
19 #===============================================================================
21 use strict;
22 use warnings;
23 use Getopt::Long;
24 use Config::IniFiles;
25 use POSIX;
26 use Fcntl;
27 use Net::LDAP;
28 use Net::LDAP::LDIF;
29 use Net::LDAP::Entry;
30 use Switch;
33 my ($verbose, $cfg_file, $log_file, $pid_file, $foreground); 
34 my ($timeout, $mailto, $mailfrom, $user, $group);
35 my ($procid, $pid, $loglevel);
36 my ($fifo_path, $max_process_timeout, $max_process );
37 my %daemon_children;
38 my ($ldap, $bind_phrase, $password, $ldap_base) ;
40 $procid = -1 ;
41 $foreground = 0 ;
42 $verbose = 0 ;
43 $max_process = 2 ;
44 $max_process_timeout = 1 ;
45 $ldap_base = "dc=gonicus,dc=de" ;
46 #$ldap_path = "/var/run/gosa-support-daemon.socket";
47 #$log_path = "/var/log/gosa-support-daemon.log";
48 #$pid_path = "/var/run/gosa-support-daemon/gosa-support-daemon.pid";
50 #---------------------------------------------------------------------------
51 #  parse commandline options
52 #---------------------------------------------------------------------------
53 Getopt::Long::Configure( "bundling" );
54 GetOptions( "v|verbose+" => \$verbose,
55         "c|config=s" => \$cfg_file,
56         "h|help" => \&usage,
57         "l|logfile=s" => \$log_file,
58         "p|pid=s" => \$pid_file,
59         "f|foreground" => \$foreground);
61 #---------------------------------------------------------------------------
62 #  read and set config parameters
63 #---------------------------------------------------------------------------
64 my %cfg_defaults =
65 ("Allgemein" =>
66  {"timeout"  => [ \$timeout, 1000 ],
67  "mailto"   => [ \$mailto, 'root@localhost' ],
68  "mailfrom" => [ \$mailfrom, 'sps-daemon@localhost' ],
69  "user"     => [ \$user, "nobody" ],
70  "group"    => [ \$group, "nogroup" ],
71  "fifo_path" => [ \$fifo_path, "/home/rettenbe/gonicus/gosa-support/tmp/fifo" ],
72  "log_file"  => [ \$log_file, "/home/rettenbe/gonicus/gosa-support/tmp/gosa-support.log" ],
73  "pid_file"  => [ \$pid_file, "/home/rettenbe/gonicus/gosa-support/tmp/gosa-support.pid" ],
74  "loglevel"     => [ \$loglevel, 1]
75  },
76 "LDAP"  =>
77     {"bind" => [ \$bind_phrase, "cn=ldapadmin,dc=gonicus,dc=de" ],
78      "password" => [ \$password, "tester" ],
79     }
80  );
81 &read_configfile;
84 #===  FUNCTION  ================================================================
85 #         NAME:  check_cmdline_param
86 #      PURPOSE:  checks all commandline parameters to validity
87 #   PARAMETERS:  none
88 #      RETURNS:  none
89 #  DESCRIPTION:  ????
90 #       THROWS:  no exceptions
91 #     COMMENTS:  none
92 #     SEE ALSO:  n/a
93 #===============================================================================
94 sub check_cmdline_param () {
95     my $err_config;
96     my $err_log;
97     my $err_pid;
98     my $err_counter = 0;
99     if( not defined( $cfg_file)) {
100         $err_config = "please specify a config file";
101         $err_counter += 1;
102     }
103     if( not defined( $log_file)) {
104         $err_log = "please specify a log file";
105         $err_counter += 1;
106     }
107     if( not defined( $pid_file)) {
108         $err_pid = "please specify a pid file";
109         $err_counter += 1;
110     }
111     if( $err_counter > 0 ) {
112         &usage( "", 1 );
113         if( defined( $err_config)) { print STDERR "$err_config\n"}
114         if( defined( $err_log)) { print STDERR "$err_log\n" }
115         if( defined( $err_pid)) { print STDERR "$err_pid\n"}
116         print STDERR "\n";
117         exit( -1 );
118     }
121 #===  FUNCTION  ================================================================
122 #         NAME:  check_pid
123 #      PURPOSE:  
124 #   PARAMETERS:  none
125 #      RETURNS:  none
126 #  DESCRIPTION:  ????
127 #       THROWS:  no exceptions
128 #     COMMENTS:  none
129 #     SEE ALSO:  n/a
130 #===============================================================================
131 sub check_pid { 
132     if( open( LOCK_FILE, "<$pid_file") ) {
133         $procid = <LOCK_FILE>;
134         if( defined $procid ) {
135             chomp( $procid );
136             if( -f "/proc/$procid/stat" ) {
137                 my($stat) = `cat /proc/$procid/stat` =~ m/$procid \((.+)\).*/;
138                 print "\t".$stat."\n";
139                 if( "sps-daemon.pl" eq $stat ) {
140                     close( LOCK_FILE );
141                     exit -1;
142                 }
143             }
144         }
145         close( LOCK_FILE );
146         unlink( $pid_file );
147     }
149     # Try to open PID file
150     if (!sysopen(LOCK_FILE, $pid_file, O_WRONLY|O_CREAT|O_EXCL, 0644)) {
151         my($msg) = "Couldn't obtain lockfile '$pid_file' ";
152         if (open(LOCK_FILE, "<", $pid_file) && ($pid = <LOCK_FILE>)) {
153             chomp($pid);
154             $msg .= "(PID $pid)\n";
155         } else {
156             $msg .= "(unable to read PID)\n";
157         }
158         if ( ! $foreground ) {
159             daemon_log( $msg."\n");
160         } else {
161             print( STDERR " $msg " );
162         }
163         exit( -1 );
164     }
167 #===  FUNCTION  ================================================================
168 #         NAME:  read_configfile
169 #      PURPOSE:  read the configuration file and provide the programm with 
170 #                parameters
171 #   PARAMETERS:  none
172 #      RETURNS:  none
173 #  DESCRIPTION:  ????
174 #       THROWS:  no exceptions
175 #     COMMENTS:  none
176 #     SEE ALSO:  n/a
177 #===============================================================================
178 sub read_configfile {
179     my $log_time = localtime(time);
180     my $cfg;
181     if( defined( $cfg_file) && ( length($cfg_file) > 0 )) {
182         if( -r $cfg_file ) { 
183             $cfg = Config::IniFiles->new( -file => $cfg_file ); 
184         } else { 
185             usage( "Couldn't read config file: $cfg_file \n" ); 
186         }
187     } else { 
188         $cfg = Config::IniFiles->new() ; 
189     }
191     foreach my $section (keys %cfg_defaults) {      # "Parse" config into values
192         foreach my $param (keys %{$cfg_defaults{ $section }}) {
193             my $pinfo = $cfg_defaults{ $section }{ $param };
194             ${@$pinfo[ 0 ]} = $cfg->val( $section, $param, @$pinfo[ 1 ] );
195         }
196     }
198     if(-e $log_file ) { unlink $log_file }
199     daemon_log("$log_time: config file read\n");
202 #===  FUNCTION  ================================================================
203 #         NAME:  daemon_log
204 #      PURPOSE:  log messages to specified logfile
205 #   PARAMETERS:  $msg, $level
206 #      RETURNS:  ????
207 #  DESCRIPTION:  Takes a message ($msg) and append it to the logfile. The 
208 #                standard log-level ($level) is 1. Messages whith higher level
209 #                than the verbosity-level (defined by commandline) are printed 
210 #                out to commandline. Messages with log-level lower than 2 are 
211 #                not logged to logfile!
212 #       THROWS:  no exceptions
213 #     COMMENTS:  none
214 #     SEE ALSO:  n/a
215 #===============================================================================
216 sub daemon_log {
217     my( $msg, $level ) = @_;
218     if(not defined $msg) { return } 
219     if(not defined $level) { $level = 1 }
220     open(LOG_HANDLE, ">>$log_file");
221     if(not defined open( LOG_HANDLE, ">>$log_file" ) ) { return }
222     chomp($msg);
223     if( $verbose >= $level ) { print "$msg"."\n" }
224     if( $level <= 1 ) { print LOG_HANDLE $msg."\n"  }
225     close( LOG_HANDLE );
226     }
228 #===  FUNCTION  ================================================================
229 #         NAME:  signal handler
230 #      PURPOSE:  catches signals from the programm and do diffrent things 
231 #                than default
232 #   PARAMETERS:  none
233 #      RETURNS:  none
234 #  DESCRIPTION:  sighandler
235 #       THROWS:  no exceptions
236 #     COMMENTS:  none
237 #     SEE ALSO:  n/a
238 #===============================================================================
239 sub sigINT {
240     my $log_time = localtime(time);
241     print "INT\n";
242     if( -p $fifo_path ) {
243         close FIFO  ;
244         unlink($fifo_path) ;
245         daemon_log( "$log_time: FIFO closed after signal INT!\n") ;
246         }
247     if(defined($ldap)) {
248         $ldap->unbind;
249     }
250     $SIG{INT} = "DEFAULT" ;
251     kill INT => $$ ;
253 $SIG{INT} = \&sigINT ;
255 #===  FUNCTION  ================================================================
256 #         NAME:  usage
257 #      PURPOSE:  
258 #   PARAMETERS:  none
259 #      RETURNS:  none
260 #  DESCRIPTION:  print out the usage of the program
261 #       THROWS:  no exceptions
262 #     COMMENTS:  none
263 #     SEE ALSO:  n/a
264 #===============================================================================
265 sub usage {
266         my( $text, $help ) = @_;
267         $text = undef if( "h" eq $text );
268         (defined $text) && print STDERR "\n$text\n";
269         if( (defined $help && $help) || (!defined $help && !defined $text) ) {
270                 print STDERR << "EOF" ;
271 usage: $0 [-hvf] [-c config, -l logfile, -p pidfile]
273     -h        : this (help) message
274     -c <file> : config file
275     -l <file> : log file (example: /var/log/sps/sps.log)
276     -p <file> : pid file (example: /var/run/sps/sps.pid)
277     -f        : foreground (don"t fork)
278     -v        : be verbose (multiple to increase verbosity)
279 EOF
280         }
281         print "\n" ;
285 #===  FUNCTION  ================================================================
286 #         NAME:  open_fifo
287 #      PURPOSE:  
288 #   PARAMETERS:  $fifo_path
289 #      RETURNS:  0: FIFO couldn"t be setup, 1: FIFO setup correctly
290 #  DESCRIPTION:  creates a FIFO at $fifo_path
291 #       THROWS:  no exceptions
292 #     COMMENTS:  none
293 #     SEE ALSO:  n/a
294 #===============================================================================
295 sub open_fifo {
296     my ($fifo_path) = @_ ;
297     my $log_time = localtime( time );
298     if( -p $fifo_path ) {
299         daemon_log("$log_time: FIFO at $fifo_path already exists\n");
300         return 0;
301         } 
302     POSIX::mkfifo($fifo_path, 0666) or die "can't mkfifo $fifo_path: $!";
303     daemon_log( "$log_time: FIFO started at $fifo_path\n" ) ;
304     return 1;
305     }
308 #===  FUNCTION  ================================================================
309 #         NAME:  add_ldap_entry
310 #      PURPOSE:  adds an element to ldap-tree
311 #   PARAMETERS:  
312 #      RETURNS:  none
313 #  DESCRIPTION:  ????
314 #       THROWS:  no exceptions
315 #     COMMENTS:  none
316 #     SEE ALSO:  n/a
317 #===============================================================================
318 sub add_ldap_entry {
319     my ($ldap_tree, $ldap_base, $mac, $gotoSysStatus, $ip, $interface, $desc) = @_;
320     my $dn = "cn=$mac,ou=incoming,$ldap_base";
321     my $s_res = &search_ldap_entry($ldap_tree, $ldap_base, "(|(macAddress=$mac)(dhcpHWAddress=ethernet $mac))");
322     my $c_res = $s_res->count;
323     if($c_res == 1) {
324         daemon_log("WARNING: macAddress $mac already in LDAP", 1);
325         return;
326     } elsif($c_res > 0) {
327         daemon_log("ERROR: macAddress $mac exists $c_res times in LDAP", 1);
328         return;
329     }
331     # create LDAP entry 
332     my $entry = Net::LDAP::Entry->new( $dn );
333     $entry->dn($dn);
334     $entry->add("objectClass" => "goHard");
335     $entry->add("cn" => $mac);
336     $entry->add("macAddress" => $mac);
337     if(defined $gotoSysStatus) {$entry->add("gotoSysStatus" => $gotoSysStatus)}
338     if(defined $ip) {$entry->add("ipHostNumber" => $ip) }
339     #if(defined $interface) { }
340     if(defined $desc) {$entry->add("description" => $desc) }
341     
342     # submit entry to LDAP
343     my $result = $entry->update ($ldap_tree); 
344         
345     # for $result->code constants please look at Net::LDAP::Constant
346     my $log_time = localtime( time );
347     if($result->code == 68) {   # entry already exists 
348         daemon_log("WARNING: $log_time: $dn ".$result->error, 3);
349     } elsif($result->code == 0) {   # everything went fine
350         daemon_log("$log_time: add entry $dn to ldap", 1);
351     } else {  # if any other error occur
352         daemon_log("ERROR: $log_time: $dn, ".$result->code.", ".$result->error, 1);
353     }
354     return;
358 #===  FUNCTION  ================================================================
359 #         NAME:  change_ldap_entry
360 #      PURPOSE:  ????
361 #   PARAMETERS:  ????
362 #      RETURNS:  ????
363 #  DESCRIPTION:  ????
364 #       THROWS:  no exceptions
365 #     COMMENTS:  none
366 #     SEE ALSO:  n/a
367 #===============================================================================
368 sub change_ldap_entry {
369     my ($ldap_tree, $ldap_base, $mac, $gotoSysStatus ) = @_;
370     
371     # check if ldap_entry exists or not
372     my $s_res = &search_ldap_entry($ldap_tree, $ldap_base, "(|(macAddress=$mac)(dhcpHWAddress=ethernet $mac))");
373     my $c_res = $s_res->count;
374     if($c_res == 0) {
375         daemon_log("WARNING: macAddress $mac not in LDAP", 1);
376         return;
377     } elsif($c_res > 1) {
378         daemon_log("ERROR: macAddress $mac exists $c_res times in LDAP", 1);
379         return;
380     }
382     my $s_res_entry = $s_res->pop_entry();
383     my $dn = $s_res_entry->dn();
384     my $result = $ldap->modify( $dn, replace => {'gotoSysStatus' => $gotoSysStatus } );
386     # for $result->code constants please look at Net::LDAP::Constant
387     my $log_time = localtime( time );
388     if($result->code == 32) {   # entry doesnt exists 
389         &add_ldap_entry($mac, $gotoSysStatus);
390     } elsif($result->code == 0) {   # everything went fine
391         daemon_log("$log_time: entry $dn changed successful", 1);
392     } else {  # if any other error occur
393         daemon_log("ERROR: $log_time: $dn, ".$result->code.", ".$result->error, 1);
394     }
396     return;
399 #===  FUNCTION  ================================================================
400 #         NAME:  search_ldap_entry
401 #      PURPOSE:  ????
402 #   PARAMETERS:  [Net::LDAP] $ldap_tree - object of an ldap-tree
403 #                string $sub_tree - dn of the subtree the search is performed
404 #                string $search_string - either a string or a Net::LDAP::Filter object
405 #      RETURNS:  [Net::LDAP::Search] $msg - result object of the performed search
406 #  DESCRIPTION:  ????
407 #       THROWS:  no exceptions
408 #     COMMENTS:  none
409 #     SEE ALSO:  n/a
410 #===============================================================================
411 sub search_ldap_entry {
412     my ($ldap_tree, $sub_tree, $search_string) = @_;
413     my $msg = $ldap_tree->search( # perform a search
414                         base   => $sub_tree,
415                         filter => $search_string,
416                       ) or daemon_log("cannot perform search at ldap: $@", 1);
417 #    if(defined $msg) {
418 #        print $sub_tree."\t".$search_string."\t";
419 #        print $msg->count."\n";
420 #        foreach my $entry ($msg->entries) { $entry->dump; };
421 #    }
423     return $msg;
428 #========= MAIN = main ========================================================
429 daemon_log( "####### START DAEMON ######\n", 1 );
430 #&check_cmdline_param ;
431 &check_pid;
432 &open_fifo($fifo_path);
434 # Just fork, if we"re not in foreground mode
435 if( ! $foreground ) { $pid = fork(); }
436 else { $pid = $$; }
438 # Do something useful - put our PID into the pid_file
439 if( 0 != $pid ) {
440     open( LOCK_FILE, ">$pid_file" );
441     print LOCK_FILE "$pid\n";
442     close( LOCK_FILE );
443     if( !$foreground ) { exit( 0 ) };
447 if( not -p $fifo_path ) { die "fifo file disappeared\n" }
448 sysopen(FIFO, $fifo_path, O_RDONLY) or die "can't read from $fifo_path: $!" ;
450 while( 1 ) {
451     # checke alle prozesse im hash daemon_children ob sie noch aktiv sind, wenn
452     # nicht, dann entferne prozess aus hash
453     while( (my $key, my $val) = each( %daemon_children) ) {
454         my $status = waitpid( $key, &WNOHANG) ;
455         if( $status == -1 ) { 
456             delete $daemon_children{$key} ; 
457             daemon_log("childprocess finished: $key", 3) ;
458         }
459     }
461     # ist die max_process anzahl von prozesskindern erreicht, dann warte und 
462     # prüfe erneut, ob in der zwischenzeit prozesse fertig geworden sind
463     if( keys( %daemon_children ) >= $max_process ) { 
464         sleep($max_process_timeout) ;
465         next ;
466     }
468     my $msg = <FIFO>;
469     if( not defined( $msg )) { next ; }
470     
471     chomp( $msg );
472     if( length( $msg ) == 0 ) { next ; }
474     my $forked_pid = fork();
475 #=== PARENT = parent ==========================================================
476     if ( $forked_pid != 0 ) { 
477         daemon_log("childprocess forked: $forked_pid", 3) ;
478         $daemon_children{$forked_pid} = 0 ;
479     }
480 #=== CHILD = child ============================================================
481     else {
482         # parse the incoming message from arp, split the message and return 
483         # the values in an array. not defined values are set to "none" 
484         #my ($mac, $ip, $interface, $arp_sig, $desc) = &parse_input( $msg ) ;
485         daemon_log( "childprocess read from arp: $fifo_path\nline: $msg", 3);
486         my ($mac, $ip, $interface, $arp_sig, $desc) = split('\s', $msg, 5);
488         # create connection to LDAP
489         $ldap = Net::LDAP->new( "localhost" ) or die "$@";
490         $ldap->bind($bind_phrase,
491                     password => $password,
492                     ) ;
493         
494         switch($arp_sig) {
495             case 0 {&change_ldap_entry($ldap, $ldap_base, 
496                                       $mac, "ip-changed",
497                                       )} 
498             case 1 {&change_ldap_entry($ldap, $ldap_base, 
499                                       $mac, "mac-not-whitelisted",
500                                       )}
501             case 2 {&change_ldap_entry($ldap, $ldap_base, 
502                                       $mac, "mac-in-blacklist",
503                                       )}
504             case 3 {&add_ldap_entry($ldap, $ldap_base, 
505                                    $mac, "new-mac-address", $ip, 
506                                    $interface, $desc, 
507                                    )}
508             case 4 {&change_ldap_entry($ldap, $ldap_base, 
509                                       $mac, "unauthorized-arp-request",
510                                       )}
511             case 5 {&change_ldap_entry($ldap, $ldap_base, 
512                                       $mac, "abusive-number-of-arp-requests",
513                                       )}
514             case 6 {&change_ldap_entry($ldap, $ldap_base, 
515                                       $mac, "ether-and-arp-mac-differs",
516                                       )}
517             case 7 {&change_ldap_entry($ldap, $ldap_base, 
518                                       $mac, "flood-detected",
519                                       )}
520             case 8 {&add_ldap_entry($ldap, $ldap_base, 
521                                    $mac, $ip, "new-system",
522                                    )}
523             case 9 {&change_ldap_entry($ldap, $ldap_base, 
524                                       $mac, "mac-changed",
525                                       )}
526         }
529         # ldap search
530 #        my $base_phrase = "dc=gonicus,dc=de";
531 #        my $filter_phrase = "cn=keinesorge";
532 #        my $attrs_phrase = "cn macAdress";
533 #        my $msg_search = $ldap->search( base   => $base_phrase,
534 #                                        filter => $filter_phrase,
535 #                                        attrs => $attrs_phrase,
536 #                                        );
537 #        $msg_search->code && die $msg_search->error;
538 #        
539 #        my @entries = $msg_search->entries;
540 #        my $max = $msg_search->count;
541 #        print "anzahl der entries: $max\n";
542 #        my $i;
543 #        for ( $i = 0 ; $i < $max ; $i++ ) {
544 #            my $entry = $msg_search->entry ( $i );
545 #            foreach my $attr ( $entry->attributes ) {
546 #                if( not $attr eq "cn") {
547 #                    next;
548 #                }
549 #                print join( "\n ", $attr, $entry->get_value( $attr ) ), "\n\n";
550 #            }
551 #        }
553         # ldap add
554        
555         
556         $ldap->unbind;
557         exit;
558     }