This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Fixing extra -I's with PERL_CORE
[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
ba056755 74The real STDERR is not closed -- it is moved to CGI::Carp::SAVEERR. Some
54310121 75servers, when dealing with CGI scripts, close their connection to the
ba056755 76browser when the script closes STDOUT and STDERR. CGI::Carp::SAVEERR is there to
54310121 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
6b4ac661
JH
145=head1 MAKING WARNINGS APPEAR AS HTML COMMENTS
146
147It is now also possible to make non-fatal errors appear as HTML
148comments embedded in the output of your program. To enable this
149feature, export the new "warningsToBrowser" subroutine. Since sending
150warnings to the browser before the HTTP headers have been sent would
151cause an error, any warnings are stored in an internal buffer until
152you call the warningsToBrowser() subroutine with a true argument:
153
154 use CGI::Carp qw(fatalsToBrowser warningsToBrowser);
155 use CGI qw(:standard);
156 print header();
157 warningsToBrowser(1);
158
159You may also give a false argument to warningsToBrowser() to prevent
160warnings from being sent to the browser while you are printing some
161content where HTML comments are not allowed:
162
163 warningsToBrowser(0); # disable warnings
164 print "<SCRIPT type=javascript><!--\n";
165 print_some_javascript_code();
166 print "//--></SCRIPT>\n";
167 warningsToBrowser(1); # re-enable warnings
168
169Note: In this respect warningsToBrowser() differs fundamentally from
170fatalsToBrowser(), which you should never call yourself!
171
54310121 172=head1 CHANGE LOG
173
1741.05 carpout() added and minor corrections by Marc Hedlund
175 <hedlund@best.com> on 11/26/95.
176
1771.06 fatalsToBrowser() no longer aborts for fatal errors within
178 eval() statements.
179
424ec8fa
GS
1801.08 set_message() added and carpout() expanded to allow for FileHandle
181 objects.
182
1831.09 set_message() now allows users to pass a code REFERENCE for
184 really custom error messages. croak and carp are now
185 exported by default. Thanks to Gunther Birznieks for the
186 patches.
187
1881.10 Patch from Chris Dean (ctdean@cogit.com) to allow
189 module to run correctly under mod_perl.
190
71f3e297
JH
1911.11 Changed order of &gt; and &lt; escapes.
192
1931.12 Changed die() on line 217 to CORE::die to avoid B<-w> warning.
194
1951.13 Added cluck() to make the module orthogonal with Carp.
6b4ac661
JH
196 More mod_perl related fixes.
197
1981.20 Patch from Ilmari Karonen (perl@itz.pp.sci.fi): Added
199 warningsToBrowser(). Replaced <CODE> tags with <PRE> in
200 fatalsToBrowser() output.
71f3e297 201
54310121 202=head1 AUTHORS
203
71f3e297
JH
204Copyright 1995-1998, Lincoln D. Stein. All rights reserved.
205
206This library is free software; you can redistribute it and/or modify
207it under the same terms as Perl itself.
54310121 208
71f3e297 209Address bug reports and comments to: lstein@cshl.org
54310121 210
211=head1 SEE ALSO
212
213Carp, CGI::Base, CGI::BasePlus, CGI::Request, CGI::MiniSvr, CGI::Form,
214CGI::Response
215
216=cut
217
218require 5.000;
219use Exporter;
220use Carp;
221
222@ISA = qw(Exporter);
223@EXPORT = qw(confess croak carp);
6b4ac661 224@EXPORT_OK = qw(carpout fatalsToBrowser warningsToBrowser wrap set_message cluck);
3538e1d5 225
54310121 226$main::SIG{__WARN__}=\&CGI::Carp::warn;
227$main::SIG{__DIE__}=\&CGI::Carp::die;
6b4ac661 228$CGI::Carp::VERSION = '1.20';
424ec8fa 229$CGI::Carp::CUSTOM_MSG = undef;
54310121 230
231# fancy import routine detects and handles 'errorWrap' specially.
232sub import {
233 my $pkg = shift;
234 my(%routines);
424ec8fa
GS
235 grep($routines{$_}++,@_,@EXPORT);
236 $WRAP++ if $routines{'fatalsToBrowser'} || $routines{'wrap'};
6b4ac661 237 $WARN++ if $routines{'warningsToBrowser'};
54310121 238 my($oldlevel) = $Exporter::ExportLevel;
239 $Exporter::ExportLevel = 1;
240 Exporter::import($pkg,keys %routines);
241 $Exporter::ExportLevel = $oldlevel;
242}
243
244# These are the originals
9014bb8e
GS
245sub realwarn { CORE::warn(@_); }
246sub realdie { CORE::die(@_); }
54310121 247
248sub id {
249 my $level = shift;
250 my($pack,$file,$line,$sub) = caller($level);
6b4ac661 251 my($id) = $file=~m|([^/]+)$|;
54310121 252 return ($file,$line,$id);
253}
254
255sub stamp {
256 my $time = scalar(localtime);
257 my $frame = 0;
258 my ($id,$pack,$file);
259 do {
260 $id = $file;
261 ($pack,$file) = caller($frame++);
262 } until !$file;
6b4ac661 263 ($id) = $id=~m|([^/]+)$|;
54310121 264 return "[$time] $id: ";
265}
266
267sub warn {
268 my $message = shift;
269 my($file,$line,$id) = id(1);
270 $message .= " at $file line $line.\n" unless $message=~/\n$/;
6b4ac661 271 _warn($message) if $WARN;
54310121 272 my $stamp = stamp;
273 $message=~s/^/$stamp/gm;
274 realwarn $message;
275}
276
6b4ac661
JH
277sub _warn {
278 my $msg = shift;
279 if ($EMIT_WARNINGS) {
280 # We need to mangle the message a bit to make it a valid HTML
281 # comment. This is done by substituting similar-looking ISO
282 # 8859-1 characters for <, > and -. This is a hack.
283 $msg =~ tr/<>-/\253\273\255/;
284 chomp $msg;
285 print STDOUT "<!-- warning: $msg -->\n";
286 } else {
287 push @WARNINGS, $msg;
288 }
289}
290
291sub ineval { _longmess() =~ /eval [\{\']/m }
292
424ec8fa
GS
293# The mod_perl package Apache::Registry loads CGI programs by calling
294# eval. These evals don't count when looking at the stack backtrace.
295sub _longmess {
296 my $message = Carp::longmess();
71f3e297 297 my $mod_perl = exists $ENV{MOD_PERL};
424ec8fa 298 $message =~ s,eval[^\n]+Apache/Registry\.pm.*,,s if $mod_perl;
6b4ac661 299 return $message;
424ec8fa
GS
300}
301
54310121 302sub die {
3538e1d5 303 realdie @_ if ineval;
6b4ac661 304 my ($message) = @_;
3538e1d5
GS
305 my $time = scalar(localtime);
306 my($file,$line,$id) = id(1);
307 $message .= " at $file line $line." unless $message=~/\n$/;
308 &fatalsToBrowser($message) if $WRAP;
309 my $stamp = stamp;
310 $message=~s/^/$stamp/gm;
311 realdie $message;
54310121 312}
313
424ec8fa
GS
314sub set_message {
315 $CGI::Carp::CUSTOM_MSG = shift;
316 return $CGI::Carp::CUSTOM_MSG;
317}
318
54310121 319# Avoid generating "subroutine redefined" warnings with the following
320# hack:
321{
322 local $^W=0;
323 eval <<EOF;
324sub confess { CGI::Carp::die Carp::longmess \@_; }
71f3e297
JH
325sub croak { CGI::Carp::die Carp::shortmess \@_; }
326sub carp { CGI::Carp::warn Carp::shortmess \@_; }
327sub cluck { CGI::Carp::warn Carp::longmess \@_; }
54310121 328EOF
329 ;
330}
331
332# We have to be ready to accept a filehandle as a reference
333# or a string.
334sub carpout {
335 my($in) = @_;
424ec8fa 336 my($no) = fileno(to_filehandle($in));
71f3e297 337 realdie("Invalid filehandle $in\n") unless defined $no;
54310121 338
339 open(SAVEERR, ">&STDERR");
340 open(STDERR, ">&$no") or
341 ( print SAVEERR "Unable to redirect STDERR: $!\n" and exit(1) );
342}
343
6b4ac661
JH
344sub warningsToBrowser {
345 $EMIT_WARNINGS = @_ ? shift : 1;
346 _warn(shift @WARNINGS) while $EMIT_WARNINGS and @WARNINGS;
347}
348
54310121 349# headers
350sub fatalsToBrowser {
351 my($msg) = @_;
71f3e297 352 $msg=~s/&/&amp;/g;
54310121 353 $msg=~s/>/&gt;/g;
354 $msg=~s/</&lt;/g;
424ec8fa
GS
355 $msg=~s/\"/&quot;/g;
356 my($wm) = $ENV{SERVER_ADMIN} ?
357 qq[the webmaster (<a href="mailto:$ENV{SERVER_ADMIN}">$ENV{SERVER_ADMIN}</a>)] :
358 "this site's webmaster";
359 my ($outer_message) = <<END;
360For help, please send mail to $wm, giving this error message
361and the time and date of the error.
362END
363 ;
71f3e297
JH
364 my $mod_perl = exists $ENV{MOD_PERL};
365 print STDOUT "Content-type: text/html\n\n"
366 unless $mod_perl;
424ec8fa 367
6b4ac661
JH
368 warningsToBrowser(1); # emit warnings before dying
369
424ec8fa
GS
370 if ($CUSTOM_MSG) {
371 if (ref($CUSTOM_MSG) eq 'CODE') {
372 &$CUSTOM_MSG($msg); # nicer to perl 5.003 users
373 return;
374 } else {
375 $outer_message = $CUSTOM_MSG;
376 }
377 }
378
71f3e297 379 my $mess = <<END;
54310121 380<H1>Software error:</H1>
6b4ac661 381<PRE>$msg</PRE>
54310121 382<P>
71f3e297 383$outer_message
54310121 384END
424ec8fa 385 ;
71f3e297 386
3d1a2ec4 387 if ($mod_perl && (my $r = Apache->request)) {
71f3e297
JH
388 # If bytes have already been sent, then
389 # we print the message out directly.
390 # Otherwise we make a custom error
391 # handler to produce the doc for us.
392 if ($r->bytes_sent) {
393 $r->print($mess);
394 $r->exit;
395 } else {
396 $r->status(500);
397 $r->custom_response(500,$mess);
398 }
399 } else {
400 print STDOUT $mess;
401 }
424ec8fa
GS
402}
403
404# Cut and paste from CGI.pm so that we don't have the overhead of
405# always loading the entire CGI module.
406sub to_filehandle {
407 my $thingy = shift;
408 return undef unless $thingy;
409 return $thingy if UNIVERSAL::isa($thingy,'GLOB');
410 return $thingy if UNIVERSAL::isa($thingy,'FileHandle');
411 if (!ref($thingy)) {
412 my $caller = 1;
413 while (my $package = caller($caller++)) {
414 my($tmp) = $thingy=~/[\':]/ ? $thingy : "$package\:\:$thingy";
415 return $tmp if defined(fileno($tmp));
416 }
417 }
418 return undef;
54310121 419}
420
4211;