VBTK/PHttpd.pm untested

filter: Statementstmt 0.0% 0 / 257 Branchbran 0.0% 0 / 118 Conditioncond 0.0% 0 / 16 MC/DCmcdc 0.0% 0 / 10 Subroutinesub 0.0% 0 / 23 Podpod 0.0% 0 / 12 totaltotal 0.0% 0 / 436 CC 60 SCAR 49.0
CC
60
Cov
0%
handleRequest
420.0
run
110.0
new
72.0
CRAP 134.0
1 #############################################################################
2 #
3 # NOTE: This file under revision control using RCS
4 # Any changes made without RCS will be lost
5 #
6 # $Source: /usr/local/cvsroot/vbtk/VBTK/PHttpd.pm,v $
7 # $Revision: 1.12 $
8 # $Date: 2002/03/04 20:53:07 $
9 # $Author: bhenry $
10 # $Locker: $
11 # $State: Exp $
12 #
13 # Purpose:
14 #
15 # Depends on: HTTP::Daemon, HTTP::Status, IPC::Open2, URI::Escape
16 #
17 # Copyright (C) 1996 - 2002 Brent Henry
18 #
19 # This program is free software; you can redistribute it and/or
20 # modify it under the terms of version 2 of the GNU General Public
21 # License as published by the Free Software Foundation available at:
22 # http://www.gnu.org/copyleft/gpl.html
23 #
24 # This program is distributed in the hope that it will be useful,
25 # but WITHOUT ANY WARRANTY; without even the implied warranty of
26 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27 # GNU General Public License for more details.
28 #
29 #############################################################################
30 #
31 #
32 # REVISION HISTORY:
33 #
34 # $Log: PHttpd.pm,v $
35 # Revision 1.12 2002/03/04 20:53:07 bhenry
36 # *** empty log message ***
37 #
38 # Revision 1.11 2002/03/04 16:49:09 bhenry
39 # Changed requirement back to perl 5.6.0
40 #
41 # Revision 1.10 2002/03/02 00:53:55 bhenry
42 # Documentation updates
43 #
44 # Revision 1.9 2002/02/13 07:41:05 bhenry
45 # Changed to use instead of
46 #
47 # Revision 1.8 2002/01/29 00:50:08 bhenry
48 # Changes to make generic
49 #
50 # Revision 1.7 2002/01/28 22:28:45 bhenry
51 # *** empty log message ***
52 #
53 # Revision 1.6 2002/01/28 18:13:19 bhenry
54 # *** empty log message ***
55 #
56 # Revision 1.5 2002/01/26 06:15:59 bhenry
57 # *** empty log message ***
58 #
59 # Revision 1.4 2002/01/23 20:21:43 bhenry
60 # Improved handling of passed parms
61 #
62 # Revision 1.3 2002/01/21 17:07:40 bhenry
63 # Disabled 'uninitialized' warnings
64 #
65 # Revision 1.2 2002/01/18 19:24:50 bhenry
66 # Warning Fixes
67 #
68 # Revision 1.1.1.1 2002/01/17 18:05:57 bhenry
69 # VBTK Project
70 #
71 # Revision 1.23 2002/01/04 10:40:44 bhenry
72 # Improvements during vacation.
73 # Revision 1.22 2001/12/18 10:40:08 bhenry
74 #
75  
76 package VBTK::PHttpd;
77  
78 use 5.6.0;
79 use strict;
80 use warnings;
81 # I like using undef as a value so I'm turning off the uninitialized warnings
82 no warnings qw(uninitialized);
83  
84 use VBTK::Common;
85 use VBTK::PHtml;
86 use HTTP::Daemon;
87 use HTTP::Status;
88 use IPC::Open2;
89 use URI::Escape;
90 use POSIX;
91  
92 our $VERBOSE = $ENV{VERBOSE};
93  
94 our $ALARM_SUPPORTED;
95 our $FORK_SUPPORTED;
96 our $SIGNAL_CAUGHT;
97  
98 our $REQUIRED = "$;$;::REQUIRED_PARM::$;$;";
99  
100 #-------------------------------------------------------------------------------
101 # Function: new
102 # Description: Object constructor. Allocates memory for all class members
103 # Input Parms:
104 # Output Parms: Pointer to class
105 #-------------------------------------------------------------------------------
106 sub new
107 {
108 my $type = shift;
109 my $self = {};
110 bless $self, $type;
111  
112 &log("Creating PHttpd object") if ($VERBOSE);
113  
114 # Call the set method to setup all passed arguments
115 $self->set(@_);
116  
117 my $defaultParms = {
118 DocRoot => $REQUIRED,
119 LocalPort => 80,
120 LocalAddr => undef,
121 ListenQueue => 30,
122 IndexNames => 'index.html,index.htm,index.phtml',
123 Handlers => {},
124 Redirects => {},
125 AuthList => {},
126 AuthRealm => "Perl PHttpd",
127 DontForkList => [],
128 ReqTimeout => 6,
129 };
130  
131 # Validate the passed parms
132 $self->validateParms($defaultParms) || &fatal("Exiting");
133  
134 # Setup some default handlers
135 my $h = $self->{Handlers};
136 $h->{'.phtml$'} = \&defaultPHtmlHandler if (! defined $h->{'.phtml$'});
137 #$h->{'.cgi$'} = \&defaultCgiHandler if (! defined $h->{'.cgi$'});
138  
139 # Convert comma-separated lists into arrays if they aren't already
140 $self->{IndexNames} = [ split(/,/,$self->{IndexNames}) ]
141 unless (ref($self->{IndexNames}) eq 'ARRAY');
142 $self->{DontForkList} = [ split(/,/,$self->{DontForkList}) ]
143 unless (ref($self->{DontForkList}) eq 'ARRAY');
144  
145 # Create a listener
146 my $localAddr = $self->{LocalAddr};
147 $localAddr = '*' if (! defined $localAddr);
148
149 &log("Setting up HTTP listener on $localAddr:$self->{LocalPort}")
150 if ($VERBOSE);
151 my $httpd = new HTTP::Daemon(
152 LocalPort => $self->{LocalPort},
153 LocalAddr => $self->{LocalAddr},
154 Reuse => 1,
155 Listen => $self->{ListenQueue});
156  
157 # Check for errors
158 unless($httpd)
159 {
160 &error("Can't allocate HTTP::Daemon on $self->{LocalAddr}:$self->{LocalPort}");
161 return undef;
162 }
163  
164 # Test the alarm and fork functions
165 # $ALARM_SUPPORTED = &testAlarm;
166 $FORK_SUPPORTED = &testFork;
167  
168 $self->{httpd} = $httpd;
169  
170 ($self);
171 }
172  
173 #-------------------------------------------------------------------------------
174 # Function: run
175 # Description: Start listening for and handling requests
176 # Input Parms:
177 # Output Parms:
178 #-------------------------------------------------------------------------------
179 sub run
180 {
181 my ($self,$returnAfter,$parms) = @_;
182  
183 my $httpd = $self->{httpd};
184  
185 # Calculate when to return, if the 'returnAfter' value was set.
186 my $returnTime = time + $returnAfter;
187 my ($conn,$req,$timeLeft,$pid);
188  
189 # If no parameters were passed in then create an empty hash.
190 $parms = {} unless ($parms);
191  
192 # Ignore SIGPIPE errors, which seem to occur sporadically during
193 # communications.
194 $SIG{'PIPE'} = 'IGNORE';
195  
196 # Setup local signal handlers
197 local $SIG{'TERM'} = \&catchSignal;
198 local $SIG{'INT'} = \&catchSignal;
199  
200 # Handle connections forever
201 for(;;)
202 {
203 # Calculate how much time we have left
204 $timeLeft = $returnTime - time if ($returnAfter);
205 $conn = $self->waitForRequest($timeLeft);
206  
207 # Check for any signals previously caught
208 &catchSignal($SIGNAL_CAUGHT) if (defined $SIGNAL_CAUGHT);
209  
210 if(defined $conn)
211 {
212 while ($req = $self->getRequest)
213 {
214 if ($req->method =~ /^GET$|^POST$/)
215 {
216 $self->forkHandleRequest($conn,$req,$parms);
217 }
218 else
219 {
220 &error("Invalid request method - " . $req->method);
221 $conn->send_error(RC_FORBIDDEN);
222 }
223 # Force a new connection each time so we don't lock up waiting
224 # for a subsequent request from the same client.
225 $conn->force_last_request;
226 }
227 $conn->close;
228 }
229  
230 # Close the connection
231 undef($conn);
232 undef($self->{conn});
233  
234 # Cleanup any zombies
235 while(($pid = waitpid(-1,&WNOHANG)) > 0)
236 {
237 &log("VBTK::PHttpd - Reaping pid $pid") if ($VERBOSE > 1);
238 }
239  
240 # Check for any signals previously caught
241 &catchSignal($SIGNAL_CAUGHT) if (defined $SIGNAL_CAUGHT);
242  
243 # If we've exceeded our time limit then return
244 if(($returnAfter > 0)&&(time >= $returnTime))
245 {
246 &log("PHttpd::run, time to return") if ($VERBOSE > 1);
247 return 0;
248 }
249 }
250 }
251  
252 #-------------------------------------------------------------------------------
253 # Function: getRequest
254 # Description: Get the incoming HTTP request. Only allow the specified amount
255 # of time before hanging up.
256 # Input Parms:
257 # Output Parms:
258 #-------------------------------------------------------------------------------
259 sub getRequest
260 {
261 my $self = shift;
262  
263 my $httpd = $self->{httpd};
264 my $conn = $self->{conn};
265 my $ReqTimeout = $self->{ReqTimeout};
266  
267 my ($req);
268  
269 &log("Retrieving request...") if ($VERBOSE > 1);
270  
271 $conn->timeout($ReqTimeout);
272 $req = $conn->get_request;
273
274 # eval {
275 # local $SIG{ALRM} = sub { die "Timed out waiting for request\n"; };
276 # alarm $ReqTimeout if($ALARM_SUPPORTED);
277 #
278 # $req = $conn->get_request;
279 #
280 # alarm 0 if ($ALARM_SUPPORTED);
281 # };
282 #
283 # alarm 0 if ($ALARM_SUPPORTED);
284  
285 # Store connection object in the main object.
286 $self->{req} = $req;
287  
288 ($req);
289 }
290  
291  
292 #-------------------------------------------------------------------------------
293 # Function: waitForRequest
294 # Description: Wait for a HTTP request. Only wait as long as the specified
295 # time.
296 # Input Parms:
297 # Output Parms:
298 #-------------------------------------------------------------------------------
299 sub waitForRequest
300 {
301 my $self = shift;
302 my $timeLeft = shift;
303  
304 my $httpd = $self->{httpd};
305  
306 my ($conn,$logStr);
307  
308 $logStr = "up to $timeLeft seconds " if ($timeLeft > 0);
309 &log("Waiting " . $logStr . "for a connection...") if ($VERBOSE > 2);
310  
311 $httpd->timeout($timeLeft);
312 $conn = $httpd->accept;
313  
314 # Log a message if we timed out
315 unless ($conn)
316 {
317 &log('Timed out waiting for connection') if ($VERBOSE > 2);
318 }
319  
320 # Store connection object in the main object.
321 $self->{conn} = $conn;
322  
323 ($conn);
324 }
325  
326 #-------------------------------------------------------------------------------
327 # Function: forkHandleRequest
328 # Description: Check to see if we match the 'dontFork' pattern list and if not,
329 # then fork a process to handle the passed request. Otherwise,
330 # just process it inline.
331 # Input Parms:
332 # Output Parms:
333 #-------------------------------------------------------------------------------
334 sub forkHandleRequest
335 {
336 my ($self,$conn,$req,$parms) = @_;
337 my $DontForkList = $self->{DontForkList};
338 my $target = $req->url->path;
339 my $fork = 1;
340 my ($pattern,$pid);
341  
342 # Check to see if we should prevent forking.
343 foreach $pattern (@{$DontForkList})
344 {
345 &log("Checking dontForkList - $pattern") if ($VERBOSE > 2);
346 $fork = 0 if ($target =~ /$pattern/);
347 }
348  
349 if($fork)
350 {
351 &log("Forking process to handle request") if ($VERBOSE > 1);
352  
353 # If this is the parent process, then just return
354 if($pid = fork)
355 {
356 return 1;
357 }
358 # If it's the child, then handle the request and die
359 elsif(defined $pid)
360 {
361 $self->handleRequest($conn,$req,$parms);
362 $conn->force_last_request;
363 $conn->close;
364 exit 0;
365 }
366 # Otherwise, there was an error while forking, so just handle it
367 # inline.
368 else
369 {
370 &error("Unable to fork, processing in-line");
371 }
372 }
373  
374 # If we made it this far, then either the fork failed, or we're not
375 # supposed to fork. Either way, we'll just handle it inline.
376 $self->handleRequest($conn,$req,$parms);
377 }
378  
379 #-------------------------------------------------------------------------------
380 # Function: handleRequest
381 # Description: Handle the passed request
382 # Input Parms:
383 # Output Parms:
384 #-------------------------------------------------------------------------------
385 sub handleRequest
386 {
387 my ($self,$conn,$req,$parms) = @_;
388  
389 my $DocRoot = $self->{DocRoot};
390 my $IndexNames = $self->{IndexNames};
391 my $Handlers = $self->{Handlers};
392 my $Redirects = $self->{Redirects};
393 my $ReqTimeout = $self->{ReqTimeout};
394 my $HouseKeeper = $self->{HouseKeeper};
395 my $AuthList = $self->{AuthList};
396 my $AuthRealm = $self->{AuthRealm};
397 my $httpd = $self->{httpd};
398  
399 my $target = $req->url->path;
400 my $equery = $req->url->equery || '';
401 my $from = $conn->peerhost;
402  
403 # Set the host part of the URL back to what the user typed in
404 my $reqHost = $req->header('Host');
405 $req->url->host_port($reqHost) if ($reqHost);
406  
407 if($VERBOSE)
408 {
409 my $reqStr = $req->method . " $target?" . $equery;
410 $reqStr .= $req->content if ($VERBOSE > 2);
411 $reqStr =~ s/[^\w\s\=\&\?\/\\\-\%\.]//g;
412 &log("Request from '$from' - $reqStr");
413 }
414  
415 my ($str,$key,$value,$response,$pattern,$rURI,$listRef);
416  
417 # If the target matches one of the redirects, then redirect
418 foreach $pattern (keys %{$Redirects})
419 {
420 &log("Checking redirect rule for '$pattern'") if ($VERBOSE > 2);
421 if($target =~ /$pattern/)
422 {
423 # Create a redirect URI, using the current URI as it's base
424 $rURI = URI->new_abs($Redirects->{$pattern},$req->url);
425  
426 &log("Redirecting to '$rURI'") if ($VERBOSE > 1);
427 $conn->send_redirect($rURI);
428 return 0;
429 }
430 }
431  
432 # If the target is a directory, then see if there's an index and if so
433 # send a redirect to it.
434 if(-d "$DocRoot/$target")
435 {
436 foreach my $indexName (@{$IndexNames})
437 {
438 &log("Checking for '$DocRoot$target$indexName'") if ($VERBOSE > 2);
439 if (-f "$DocRoot$target$indexName")
440 {
441 # Create a redirect URI, using the current URI as it's base
442 $rURI = URI->new_abs("$indexName",$req->url);
443  
444 &log("Redirecting to '$rURI'") if ($VERBOSE > 1);
445 $conn->send_redirect($rURI);
446 return 0;
447 }
448 }
449 }
450  
451 # Check to see if access has been restricted
452 foreach $pattern (keys %{$AuthList})
453 {
454 &log("Checking security restrictions for '$pattern'") if ($VERBOSE > 2);
455  
456 # If it matches, then see if we've received the authentication,
457 # otherwise, request authentication
458 if($target =~ /$pattern/)
459 {
460 &log("Using security settings for '$pattern'") if ($VERBOSE > 2);
461  
462 my $handler = $AuthList->{$pattern};
463 my ($user,$pswd) = $req->authorization_basic;
464  
465 # If the user and password are blank, or the authentication fails,
466 # then we need to send the authenticate challenge
467 if((! defined $user)||(! &$handler($user,$pswd)))
468 {
469 $response = new HTTP::Response;
470 $response->code(RC_UNAUTHORIZED);
471 $response->www_authenticate("basic realm=\"$AuthRealm\"");
472 $conn->send_response($response);
473 return 0;
474 }
475  
476 # If we made it this far, then setup a cookie to save the fact
477 # that we made it through the authorization
478 # -- TBD --
479 }
480 }
481  
482 # Check for passed handlers
483 foreach $pattern (keys %{$Handlers})
484 {
485 &log("Checking handler list for '$pattern'") if ($VERBOSE > 2);
486  
487 # If it matches, then call it, passing the target and parms.
488 if($target =~ /$pattern/)
489 {
490 &log("Using handler for '$pattern'") if ($VERBOSE > 1);
491  
492 my $sub = $Handlers->{$pattern};
493  
494 my %allParms = %{$parms};
495  
496 # Create a hash with all passed name/value pairs, including
497 # the ones passed from the calling method.
498 foreach my $str (split(/[&]/, $equery),split(/[&]/, $req->content))
499 {
500 ($key,$value) = split(/[=]/, $str);
501 $value =~ s/\+/ /g;
502 $value = uri_unescape($value);
503  
504 # Create a list entry, in case multiple values are passed in for
505 # the same parm.
506 $allParms{'list',$key} ||= [];
507 push(@{$allParms{'list',$key}},$value);
508  
509 $allParms{$key} = $value;
510 }
511  
512 &$sub($conn,$req,"$DocRoot$target",$DocRoot,\%allParms);
513  
514 &log("Finished handling request") if ($VERBOSE > 2);
515  
516 return 0;
517 }
518 }
519  
520 # If there's no special handler, then just serve up the file
521 if (-f "$DocRoot$target")
522 {
523 $conn->send_file_response("$DocRoot$target");
524 }
525 else
526 {
527 &error("Request for invalid file - '$DocRoot$target'");
528 $conn->send_error(RC_NOT_FOUND);
529 }
530  
531 (0);
532 }
533  
534 #-------------------------------------------------------------------------------
535 # Function: defaultPHtmlHandler
536 # Description: Handle the incoming request
537 # Input Parms:
538 # Output Parms:
539 #-------------------------------------------------------------------------------
540 sub defaultPHtmlHandler
541 {
542 my ($conn,$req,$target,$baseDir,$parms) = @_;
543  
544 my $html = VBTK::PHtml::generateHtml($target,$baseDir,$parms,$conn,$req);
545  
546 if(defined $html)
547 {
548 &log("Creating HTTP::Response object") if ($VERBOSE > 2);
549 my $response = new HTTP::Response;
550 $response->content($html);
551  
552 # Force the content type if the PHtml set it in the parms hash
553 $response->content_type($parms->{content_type})
554 if (defined $parms->{content_type});
555  
556 $conn->send_response($response);
557 }
558 else
559 {
560 $conn->send_error(RC_INTERNAL_SERVER_ERROR);
561 }
562 (0);
563 }
564  
565 #-------------------------------------------------------------------------------
566 # Function: defaultCgiHandler
567 # Description: Handle the incoming request
568 # Input Parms:
569 # Output Parms:
570 #-------------------------------------------------------------------------------
571 #sub defaultCgiHandler
572 #{
573 # my ($conn,$req,$baseDir,$target,$parms) = @_;
574 # my ($rdrfh,$wtrfh,$key,$str,$pid,@html,$htmlRoot,$podFile);
575 #
576 # pipe (CRDR, CWTR) || &fatal("defaultCgiHandler: Can't create pipe");
577 # pipe (PRDR, PWTR) || &fatal("defaultCgiHandler: Can't create pipe");
578 # CWTR->autoflush(1);
579 # PWTR->autoflush(1);
580 #
581 # if($pid = fork)
582 # {
583 # &log("In parent, waiting for response from child") if ($VERBOSE > 3);
584 # WTR->close();
585 # @html = <RDR>;
586 # RDR->close();
587 # waitpid $pid, 0;
588 # }
589 # elsif(defined $pid)
590 # {
591 # &log("In child, preparing to run pod2html") if ($VERBOSE > 3);
592 #
593 # RDR->close();
594 # open(STDOUT,">&WTR") || &fatal("Can't redirect STDOUT to pipe");
595 #
596 # pod2html(
597 # "--htmlroot=$htmlRoot",
598 # "--header",
599 # "--libpods=perlfunc:perlguts:perlvar:perlrun:perlop",
600 # "--infile=$podFile"
601 # );
602 #
603 # WTR->close();
604 # STDOUT->close();
605 # exit 0;
606 # }
607 # else
608 # {
609 # error("genPodHtml: Can't fork");
610 # }
611 #
612 # # Run the command;
613 # $pid = open2($rdrfh,$wtrfh,$target);
614 #
615 # # If there's no PID, then just return
616 # unless($pid)
617 # {
618 # $conn->send_error(RC_INTERNAL_SERVER_ERROR);
619 # $rdrfh->close;
620 # $wtrfh->close;
621 # return -1;
622 # }
623 #
624 # # Write out all the passed parameters to the CGI
625 # foreach $key (keys %{$parms})
626 # {
627 # print $wtrfh "$key=$parms->{$key}\n";
628 # }
629 # $wtrfh->close;
630 #
631 # # Read all the output
632 # my @output = <$rdrfh>;
633 #
634 # # Define a response object
635 # my $response = new HTTP::Response;
636 #
637 # # Step through the headers
638 # for(;;)
639 # {
640 # $str = unshift(@output);
641 # last if ($str =~ /^\s*$/);
642 #
643 # if($str =~ /ContentType/) { $response->type($1); }
644 # }
645 #
646 # my $html = join('',@output);
647 #
648 # if(defined $html)
649 # {
650 # $response->content($html);
651 #
652 # $conn->send_response($response);
653 # }
654 # else
655 # {
656 # $conn->send_error(RC_INTERNAL_SERVER_ERROR);
657 # }
658 #
659 # (0);
660 #}
661  
662 #-------------------------------------------------------------------------------
663 # Function: unixAuthWGroup
664 # Description: Check the passed userid and password using the getpwuid function.
665 # If they authenticate, then check to see if the user is in one of
666 # the specified groups.
667 # Input Parms: Userid, Password, Group List (space or comma delimited)
668 # Output Parms: True | False
669 #-------------------------------------------------------------------------------
670 sub unixAuthWGroup
671 {
672 my ($userId,$passwd,$groupList) = @_;
673  
674 &unixAuth($userId,$passwd) && &inGroup($userId,$groupList);
675 }
676  
677 #-------------------------------------------------------------------------------
678 # Function: unixAuth
679 # Description: Check the passed userid and password using the getpwuid function
680 # Input Parms: Userid, Password
681 # Output Parms: True | False
682 #-------------------------------------------------------------------------------
683 sub unixAuth
684 {
685 my ($userId,$passwd) = @_;
686  
687 my $pwd = (getpwnam($userId))[1];
688  
689 if (! defined $pwd)
690 {
691 &log("Invalid user '$userId'");
692 (0);
693 }
694 elsif (crypt($passwd, $pwd) ne $pwd)
695 {
696 &log("User '$userId' failed authorization");
697 (0);
698 }
699 else
700 {
701 &log("User '$userId' passed authorization") if ($VERBOSE);
702 (1);
703 }
704 }
705  
706 #-------------------------------------------------------------------------------
707 # Function: inGroup
708 # Description: See if the passed userid is in the specified group.
709 # Input Parms: Userid, Group
710 # Output Parms: True | False
711 #-------------------------------------------------------------------------------
712 sub inGroup
713 {
714 my($userId,$groupList) = @_;
715 my($str,$group,$gid,$userList);
716  
717 # Load up the list of allowed groups.
718 my(@allowedGroupList) = split(/[\s,:]+/,$groupList);
719  
720 foreach $group (@allowedGroupList)
721 {
722 my $memberStr = (getgrnam($group))[3];
723  
724 if ($memberStr =~ /\b$userId\b/)
725 {
726 &log("User '$userId' is in group '$group'") if ($VERBOSE > 1);
727 return 1;
728 }
729 }
730  
731 &log("User '$userId' is not in group '$groupList'") if ($VERBOSE);
732  
733 (0);
734 }
735  
736 #-------------------------------------------------------------------------------
737 # Function: reaper
738 # Description: Look for dead child processes and reap them
739 # Input Parms: None
740 # Output Parms: None
741 #-------------------------------------------------------------------------------
742 sub reaper
743 {
744 my $waitpid = wait;
745 &log("Reaped pid $waitpid") if ($VERBOSE);
746  
747 # Store the exit code in a global location
748 $::EC = $?;
749  
750 # Reinstate the handler
751 $SIG{'CHLD'} = \&reaper;
752 (0);
753 }
754  
755 #-------------------------------------------------------------------------------
756 # Function: catchSignal
757 # Description: Handle any INT or TERM signals.
758 # Input Parms: None
759 # Output Parms: None
760 #-------------------------------------------------------------------------------
761 sub catchSignal
762 {
763 my ($signal) = @_;
764 my ($pgrp);
765  
766 # Ignore all but TERM and INT signals
767 if($signal =~ /^TERM|^INT/)
768 {
769 # If signal was caught once already, then kill all child procs and
770 # exit immediately
771 if($SIGNAL_CAUGHT eq $signal)
772 {
773 # Now kill anything else in the process group before we exit
774 $SIG{'TERM'} = 'IGNORE';
775  
776 # Run 'getpgrp' in an eval, just in case it's not supported
777 eval { $pgrp = getpgrp; };
778  
779 if ($pgrp > 0)
780 {
781 print STDOUT "Killing pgrp $pgrp\n";
782 kill 15, -$pgrp;
783 }
784  
785 exit(1);
786 }
787 # Otherwise, just mark the signal as caught, so that the main program
788 # can exit when it's convenient.
789 else
790 {
791 $SIGNAL_CAUGHT = $signal;
792 }
793 }
794 }
795  
796 1;
797 __END__