This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
make autogenerated files writable
[perl5.git] / lib / CGI / Carp.pm
CommitLineData
54310121 1package CGI::Carp;
2
3=head1 NAME
4
5B<CGI::Carp> - CGI routines for writing to the HTTPD (or other) error log
6
7=head1 SYNOPSIS
8
9 use CGI::Carp;
10
11 croak "We're outta here!";
12 confess "It was my fault: $!";
13 carp "It was your fault!";
14 warn "I'm confused";
15 die "I'm dying.\n";
16
71f3e297
JH
17 use CGI::Carp qw(cluck);
18 cluck "I wouldn't do that if I were you";
19
20 use CGI::Carp qw(fatalsToBrowser);
21 die "Fatal error messages are now sent to browser";
22
54310121 23=head1 DESCRIPTION
24
25CGI scripts have a nasty habit of leaving warning messages in the error
26logs that are neither time stamped nor fully identified. Tracking down
27the script that caused the error is a pain. This fixes that. Replace
28the usual
29
30 use Carp;
31
32with
33
34 use CGI::Carp
35
36And the standard warn(), die (), croak(), confess() and carp() calls
37will automagically be replaced with functions that write out nicely
38time-stamped messages to the HTTP server error log.
39
40For example:
41
42 [Fri Nov 17 21:40:43 1995] test.pl: I'm confused at test.pl line 3.
43 [Fri Nov 17 21:40:43 1995] test.pl: Got an error message: Permission denied.
44 [Fri Nov 17 21:40:43 1995] test.pl: I'm dying.
45
46=head1 REDIRECTING ERROR MESSAGES
47
48By default, error messages are sent to STDERR. Most HTTPD servers
49direct STDERR to the server's error log. Some applications may wish
50to keep private error logs, distinct from the server's error log, or
51they may wish to direct error messages to STDOUT so that the browser
52will receive them.
53
54The C<carpout()> function is provided for this purpose. Since
55carpout() is not exported by default, you must import it explicitly by
56saying
57
58 use CGI::Carp qw(carpout);
59
60The carpout() function requires one argument, which should be a
61reference to an open filehandle for writing errors. It should be
62called in a C<BEGIN> block at the top of the CGI application so that
63compiler errors will be caught. Example:
64
65 BEGIN {
66 use CGI::Carp qw(carpout);
67 open(LOG, ">>/usr/local/cgi-logs/mycgi-log") or
68 die("Unable to open mycgi-log: $!\n");
69 carpout(LOG);
70 }
71
72carpout() does not handle file locking on the log for you at this point.
73
74The real STDERR is not closed -- it is moved to SAVEERR. Some
75servers, when dealing with CGI scripts, close their connection to the
76browser when the script closes STDOUT and STDERR. SAVEERR is used to
77prevent this from happening prematurely.
78
79You can pass filehandles to carpout() in a variety of ways. The "correct"
80way according to Tom Christiansen is to pass a reference to a filehandle
81GLOB:
82
83 carpout(\*LOG);
84
85This looks weird to mere mortals however, so the following syntaxes are
86accepted as well:
87
88 carpout(LOG);
89 carpout(main::LOG);
90 carpout(main'LOG);
91 carpout(\LOG);
92 carpout(\'main::LOG');
93
94 ... and so on
95
424ec8fa
GS
96FileHandle and other objects work as well.
97
54310121 98Use of carpout() is not great for performance, so it is recommended
99for debugging purposes or for moderate-use applications. A future
100version of this module may delay redirecting STDERR until one of the
101CGI::Carp methods is called to prevent the performance hit.
102
103=head1 MAKING PERL ERRORS APPEAR IN THE BROWSER WINDOW
104
105If you want to send fatal (die, confess) errors to the browser, ask to
106import the special "fatalsToBrowser" subroutine:
107
108 use CGI::Carp qw(fatalsToBrowser);
109 die "Bad error here";
110
111Fatal errors will now be echoed to the browser as well as to the log. CGI::Carp
112arranges to send a minimal HTTP header to the browser so that even errors that
113occur in the early compile phase will be seen.
114Nonfatal errors will still be directed to the log file only (unless redirected
115with carpout).
116
424ec8fa
GS
117=head2 Changing the default message
118
119By default, the software error message is followed by a note to
120contact the Webmaster by e-mail with the time and date of the error.
121If this message is not to your liking, you can change it using the
122set_message() routine. This is not imported by default; you should
123import it on the use() line:
124
125 use CGI::Carp qw(fatalsToBrowser set_message);
126 set_message("It's not a bug, it's a feature!");
127
128You may also pass in a code reference in order to create a custom
129error message. At run time, your code will be called with the text
130of the error message that caused the script to die. Example:
131
132 use CGI::Carp qw(fatalsToBrowser set_message);
133 BEGIN {
134 sub handle_errors {
135 my $msg = shift;
136 print "<h1>Oh gosh</h1>";
137 print "Got an error: $msg";
138 }
139 set_message(\&handle_errors);
140 }
141
142In order to correctly intercept compile-time errors, you should call
143set_message() from within a BEGIN{} block.
144
54310121 145=head1 CHANGE LOG
146
1471.05 carpout() added and minor corrections by Marc Hedlund
148 <hedlund@best.com> on 11/26/95.
149
1501.06 fatalsToBrowser() no longer aborts for fatal errors within
151 eval() statements.
152
424ec8fa
GS
1531.08 set_message() added and carpout() expanded to allow for FileHandle
154 objects.
155
1561.09 set_message() now allows users to pass a code REFERENCE for
157 really custom error messages. croak and carp are now
158 exported by default. Thanks to Gunther Birznieks for the
159 patches.
160
1611.10 Patch from Chris Dean (ctdean@cogit.com) to allow
162 module to run correctly under mod_perl.
163
71f3e297
JH
1641.11 Changed order of &gt; and &lt; escapes.
165
1661.12 Changed die() on line 217 to CORE::die to avoid B<-w> warning.
167
1681.13 Added cluck() to make the module orthogonal with Carp.
169 More mod_perl related fixes.
170
54310121 171=head1 AUTHORS
172
71f3e297
JH
173Copyright 1995-1998, Lincoln D. Stein. All rights reserved.
174
175This library is free software; you can redistribute it and/or modify
176it under the same terms as Perl itself.
54310121 177
71f3e297 178Address bug reports and comments to: lstein@cshl.org
54310121 179
180=head1 SEE ALSO
181
182Carp, CGI::Base, CGI::BasePlus, CGI::Request, CGI::MiniSvr, CGI::Form,
183CGI::Response
184
185=cut
186
187require 5.000;
188use Exporter;
189use Carp;
190
191@ISA = qw(Exporter);
192@EXPORT = qw(confess croak carp);
71f3e297 193@EXPORT_OK = qw(carpout fatalsToBrowser wrap set_message cluck);
54310121 194
195$main::SIG{__WARN__}=\&CGI::Carp::warn;
196$main::SIG{__DIE__}=\&CGI::Carp::die;
71f3e297 197$CGI::Carp::VERSION = '1.13';
424ec8fa 198$CGI::Carp::CUSTOM_MSG = undef;
54310121 199
200# fancy import routine detects and handles 'errorWrap' specially.
201sub import {
202 my $pkg = shift;
203 my(%routines);
424ec8fa
GS
204 grep($routines{$_}++,@_,@EXPORT);
205 $WRAP++ if $routines{'fatalsToBrowser'} || $routines{'wrap'};
54310121 206 my($oldlevel) = $Exporter::ExportLevel;
207 $Exporter::ExportLevel = 1;
208 Exporter::import($pkg,keys %routines);
209 $Exporter::ExportLevel = $oldlevel;
210}
211
212# These are the originals
9014bb8e
GS
213sub realwarn { CORE::warn(@_); }
214sub realdie { CORE::die(@_); }
54310121 215
216sub id {
217 my $level = shift;
218 my($pack,$file,$line,$sub) = caller($level);
219 my($id) = $file=~m|([^/]+)$|;
220 return ($file,$line,$id);
221}
222
223sub stamp {
224 my $time = scalar(localtime);
225 my $frame = 0;
226 my ($id,$pack,$file);
227 do {
228 $id = $file;
229 ($pack,$file) = caller($frame++);
230 } until !$file;
231 ($id) = $id=~m|([^/]+)$|;
232 return "[$time] $id: ";
233}
234
235sub warn {
236 my $message = shift;
237 my($file,$line,$id) = id(1);
238 $message .= " at $file line $line.\n" unless $message=~/\n$/;
239 my $stamp = stamp;
240 $message=~s/^/$stamp/gm;
241 realwarn $message;
242}
243
424ec8fa
GS
244# The mod_perl package Apache::Registry loads CGI programs by calling
245# eval. These evals don't count when looking at the stack backtrace.
246sub _longmess {
247 my $message = Carp::longmess();
71f3e297 248 my $mod_perl = exists $ENV{MOD_PERL};
424ec8fa
GS
249 $message =~ s,eval[^\n]+Apache/Registry\.pm.*,,s if $mod_perl;
250 return( $message );
251}
252
54310121 253sub die {
254 my $message = shift;
255 my $time = scalar(localtime);
256 my($file,$line,$id) = id(1);
71f3e297 257 $message .= " at $file line $line." unless $message=~/\n$/;
424ec8fa 258 &fatalsToBrowser($message) if $WRAP && _longmess() !~ /eval [{\']/m;
54310121 259 my $stamp = stamp;
260 $message=~s/^/$stamp/gm;
261 realdie $message;
262}
263
424ec8fa
GS
264sub set_message {
265 $CGI::Carp::CUSTOM_MSG = shift;
266 return $CGI::Carp::CUSTOM_MSG;
267}
268
54310121 269# Avoid generating "subroutine redefined" warnings with the following
270# hack:
271{
272 local $^W=0;
273 eval <<EOF;
274sub confess { CGI::Carp::die Carp::longmess \@_; }
71f3e297
JH
275sub croak { CGI::Carp::die Carp::shortmess \@_; }
276sub carp { CGI::Carp::warn Carp::shortmess \@_; }
277sub cluck { CGI::Carp::warn Carp::longmess \@_; }
54310121 278EOF
279 ;
280}
281
282# We have to be ready to accept a filehandle as a reference
283# or a string.
284sub carpout {
285 my($in) = @_;
424ec8fa 286 my($no) = fileno(to_filehandle($in));
71f3e297 287 realdie("Invalid filehandle $in\n") unless defined $no;
54310121 288
289 open(SAVEERR, ">&STDERR");
290 open(STDERR, ">&$no") or
291 ( print SAVEERR "Unable to redirect STDERR: $!\n" and exit(1) );
292}
293
294# headers
295sub fatalsToBrowser {
296 my($msg) = @_;
71f3e297 297 $msg=~s/&/&amp;/g;
54310121 298 $msg=~s/>/&gt;/g;
299 $msg=~s/</&lt;/g;
424ec8fa
GS
300 $msg=~s/\"/&quot;/g;
301 my($wm) = $ENV{SERVER_ADMIN} ?
302 qq[the webmaster (<a href="mailto:$ENV{SERVER_ADMIN}">$ENV{SERVER_ADMIN}</a>)] :
303 "this site's webmaster";
304 my ($outer_message) = <<END;
305For help, please send mail to $wm, giving this error message
306and the time and date of the error.
307END
308 ;
71f3e297
JH
309 my $mod_perl = exists $ENV{MOD_PERL};
310 print STDOUT "Content-type: text/html\n\n"
311 unless $mod_perl;
424ec8fa
GS
312
313 if ($CUSTOM_MSG) {
314 if (ref($CUSTOM_MSG) eq 'CODE') {
315 &$CUSTOM_MSG($msg); # nicer to perl 5.003 users
316 return;
317 } else {
318 $outer_message = $CUSTOM_MSG;
319 }
320 }
321
71f3e297 322 my $mess = <<END;
54310121 323<H1>Software error:</H1>
324<CODE>$msg</CODE>
325<P>
71f3e297 326$outer_message
54310121 327END
424ec8fa 328 ;
71f3e297
JH
329
330 if ($mod_perl) {
331 my $r = Apache->request;
332 # If bytes have already been sent, then
333 # we print the message out directly.
334 # Otherwise we make a custom error
335 # handler to produce the doc for us.
336 if ($r->bytes_sent) {
337 $r->print($mess);
338 $r->exit;
339 } else {
340 $r->status(500);
341 $r->custom_response(500,$mess);
342 }
343 } else {
344 print STDOUT $mess;
345 }
424ec8fa
GS
346}
347
348# Cut and paste from CGI.pm so that we don't have the overhead of
349# always loading the entire CGI module.
350sub to_filehandle {
351 my $thingy = shift;
352 return undef unless $thingy;
353 return $thingy if UNIVERSAL::isa($thingy,'GLOB');
354 return $thingy if UNIVERSAL::isa($thingy,'FileHandle');
355 if (!ref($thingy)) {
356 my $caller = 1;
357 while (my $package = caller($caller++)) {
358 my($tmp) = $thingy=~/[\':]/ ? $thingy : "$package\:\:$thingy";
359 return $tmp if defined(fileno($tmp));
360 }
361 }
362 return undef;
54310121 363}
364
3651;