Upgrade to CGI.pm 3.49
[p5sagit/p5-mst-13.2.git] / cpan / CGI / lib / CGI / Carp.pm
1 package CGI::Carp;
2
3 =head1 NAME
4
5 B<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
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
23 =head1 DESCRIPTION
24
25 CGI scripts have a nasty habit of leaving warning messages in the error
26 logs that are neither time stamped nor fully identified.  Tracking down
27 the script that caused the error is a pain.  This fixes that.  Replace
28 the usual
29
30     use Carp;
31
32 with
33
34     use CGI::Carp
35
36 And the standard warn(), die (), croak(), confess() and carp() calls
37 will automagically be replaced with functions that write out nicely
38 time-stamped messages to the HTTP server error log.
39
40 For 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
48 By default, error messages are sent to STDERR.  Most HTTPD servers
49 direct STDERR to the server's error log.  Some applications may wish
50 to keep private error logs, distinct from the server's error log, or
51 they may wish to direct error messages to STDOUT so that the browser
52 will receive them.
53
54 The C<carpout()> function is provided for this purpose.  Since
55 carpout() is not exported by default, you must import it explicitly by
56 saying
57
58    use CGI::Carp qw(carpout);
59
60 The carpout() function requires one argument, which should be a
61 reference to an open filehandle for writing errors.  It should be
62 called in a C<BEGIN> block at the top of the CGI application so that
63 compiler 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
72 carpout() does not handle file locking on the log for you at this point.
73 Also, note that carpout() does not work with in-memory file handles, although
74 a patch would be welcome to address that.
75
76 The real STDERR is not closed -- it is moved to CGI::Carp::SAVEERR.  Some
77 servers, when dealing with CGI scripts, close their connection to the
78 browser when the script closes STDOUT and STDERR.  CGI::Carp::SAVEERR is there to
79 prevent this from happening prematurely.
80
81 You can pass filehandles to carpout() in a variety of ways.  The "correct"
82 way according to Tom Christiansen is to pass a reference to a filehandle
83 GLOB:
84
85     carpout(\*LOG);
86
87 This looks weird to mere mortals however, so the following syntaxes are
88 accepted as well:
89
90     carpout(LOG);
91     carpout(main::LOG);
92     carpout(main'LOG);
93     carpout(\LOG);
94     carpout(\'main::LOG');
95
96     ... and so on
97
98 FileHandle and other objects work as well.
99
100 Use of carpout() is not great for performance, so it is recommended
101 for debugging purposes or for moderate-use applications.  A future
102 version of this module may delay redirecting STDERR until one of the
103 CGI::Carp methods is called to prevent the performance hit.
104
105 =head1 MAKING PERL ERRORS APPEAR IN THE BROWSER WINDOW
106
107 If you want to send fatal (die, confess) errors to the browser, ask to
108 import the special "fatalsToBrowser" subroutine:
109
110     use CGI::Carp qw(fatalsToBrowser);
111     die "Bad error here";
112
113 Fatal errors will now be echoed to the browser as well as to the log.  CGI::Carp
114 arranges to send a minimal HTTP header to the browser so that even errors that
115 occur in the early compile phase will be seen.
116 Nonfatal errors will still be directed to the log file only (unless redirected
117 with carpout).
118
119 Note that fatalsToBrowser does B<not> work with mod_perl version 2.0
120 and higher.
121
122 =head2 Changing the default message
123
124 By default, the software error message is followed by a note to
125 contact the Webmaster by e-mail with the time and date of the error.
126 If this message is not to your liking, you can change it using the
127 set_message() routine.  This is not imported by default; you should
128 import it on the use() line:
129
130     use CGI::Carp qw(fatalsToBrowser set_message);
131     set_message("It's not a bug, it's a feature!");
132
133 You may also pass in a code reference in order to create a custom
134 error message.  At run time, your code will be called with the text
135 of the error message that caused the script to die.  Example:
136
137     use CGI::Carp qw(fatalsToBrowser set_message);
138     BEGIN {
139        sub handle_errors {
140           my $msg = shift;
141           print "<h1>Oh gosh</h1>";
142           print "<p>Got an error: $msg</p>";
143       }
144       set_message(\&handle_errors);
145     }
146
147 In order to correctly intercept compile-time errors, you should call
148 set_message() from within a BEGIN{} block.
149
150 =head1 DOING MORE THAN PRINTING A MESSAGE IN THE EVENT OF PERL ERRORS
151
152 If fatalsToBrowser in conjunction with set_message does not provide 
153 you with all of the functionality you need, you can go one step 
154 further by specifying a function to be executed any time a script
155 calls "die", has a syntax error, or dies unexpectedly at runtime
156 with a line like "undef->explode();". 
157
158     use CGI::Carp qw(set_die_handler);
159     BEGIN {
160        sub handle_errors {
161           my $msg = shift;
162           print "content-type: text/html\n\n";
163           print "<h1>Oh gosh</h1>";
164           print "<p>Got an error: $msg</p>";
165
166           #proceed to send an email to a system administrator,
167           #write a detailed message to the browser and/or a log,
168           #etc....
169       }
170       set_die_handler(\&handle_errors);
171     }
172
173 Notice that if you use set_die_handler(), you must handle sending
174 HTML headers to the browser yourself if you are printing a message.
175
176 If you use set_die_handler(), you will most likely interfere with 
177 the behavior of fatalsToBrowser, so you must use this or that, not 
178 both. 
179
180 Using set_die_handler() sets SIG{__DIE__} (as does fatalsToBrowser),
181 and there is only one SIG{__DIE__}. This means that if you are 
182 attempting to set SIG{__DIE__} yourself, you may interfere with 
183 this module's functionality, or this module may interfere with 
184 your module's functionality.
185
186 =head1 MAKING WARNINGS APPEAR AS HTML COMMENTS
187
188 It is now also possible to make non-fatal errors appear as HTML
189 comments embedded in the output of your program.  To enable this
190 feature, export the new "warningsToBrowser" subroutine.  Since sending
191 warnings to the browser before the HTTP headers have been sent would
192 cause an error, any warnings are stored in an internal buffer until
193 you call the warningsToBrowser() subroutine with a true argument:
194
195     use CGI::Carp qw(fatalsToBrowser warningsToBrowser);
196     use CGI qw(:standard);
197     print header();
198     warningsToBrowser(1);
199
200 You may also give a false argument to warningsToBrowser() to prevent
201 warnings from being sent to the browser while you are printing some
202 content where HTML comments are not allowed:
203
204     warningsToBrowser(0);    # disable warnings
205     print "<script type=\"text/javascript\"><!--\n";
206     print_some_javascript_code();
207     print "//--></script>\n";
208     warningsToBrowser(1);    # re-enable warnings
209
210 Note: In this respect warningsToBrowser() differs fundamentally from
211 fatalsToBrowser(), which you should never call yourself!
212
213 =head1 OVERRIDING THE NAME OF THE PROGRAM
214
215 CGI::Carp includes the name of the program that generated the error or
216 warning in the messages written to the log and the browser window.
217 Sometimes, Perl can get confused about what the actual name of the
218 executed program was.  In these cases, you can override the program
219 name that CGI::Carp will use for all messages.
220
221 The quick way to do that is to tell CGI::Carp the name of the program
222 in its use statement.  You can do that by adding
223 "name=cgi_carp_log_name" to your "use" statement.  For example:
224
225     use CGI::Carp qw(name=cgi_carp_log_name);
226
227 .  If you want to change the program name partway through the program,
228 you can use the C<set_progname()> function instead.  It is not
229 exported by default, you must import it explicitly by saying
230
231     use CGI::Carp qw(set_progname);
232
233 Once you've done that, you can change the logged name of the program
234 at any time by calling
235
236     set_progname(new_program_name);
237
238 You can set the program back to the default by calling
239
240     set_progname(undef);
241
242 Note that this override doesn't happen until after the program has
243 compiled, so any compile-time errors will still show up with the
244 non-overridden program name
245   
246 =head1 CHANGE LOG
247
248 1.29 Patch from Peter Whaite to fix the unfixable problem of CGI::Carp
249      not behaving correctly in an eval() context.
250
251 1.05 carpout() added and minor corrections by Marc Hedlund
252      <hedlund@best.com> on 11/26/95.
253
254 1.06 fatalsToBrowser() no longer aborts for fatal errors within
255      eval() statements.
256
257 1.08 set_message() added and carpout() expanded to allow for FileHandle
258      objects.
259
260 1.09 set_message() now allows users to pass a code REFERENCE for 
261      really custom error messages.  croak and carp are now
262      exported by default.  Thanks to Gunther Birznieks for the
263      patches.
264
265 1.10 Patch from Chris Dean (ctdean@cogit.com) to allow 
266      module to run correctly under mod_perl.
267
268 1.11 Changed order of &gt; and &lt; escapes.
269
270 1.12 Changed die() on line 217 to CORE::die to avoid B<-w> warning.
271
272 1.13 Added cluck() to make the module orthogonal with Carp.
273      More mod_perl related fixes.
274
275 1.20 Patch from Ilmari Karonen (perl@itz.pp.sci.fi):  Added
276      warningsToBrowser().  Replaced <CODE> tags with <PRE> in
277      fatalsToBrowser() output.
278
279 1.23 ineval() now checks both $^S and inspects the message for the "eval" pattern
280      (hack alert!) in order to accommodate various combinations of Perl and
281      mod_perl.
282
283 1.24 Patch from Scott Gifford (sgifford@suspectclass.com): Add support
284      for overriding program name.
285
286 1.26 Replaced CORE::GLOBAL::die with the evil $SIG{__DIE__} because the
287      former isn't working in some people's hands.  There is no such thing
288      as reliable exception handling in Perl.
289
290 1.27 Replaced tell STDOUT with bytes=tell STDOUT.
291
292 =head1 AUTHORS
293
294 Copyright 1995-2002, Lincoln D. Stein.  All rights reserved.  
295
296 This library is free software; you can redistribute it and/or modify
297 it under the same terms as Perl itself.
298
299 Address bug reports and comments to: lstein@cshl.org
300
301 =head1 SEE ALSO
302
303 Carp, CGI::Base, CGI::BasePlus, CGI::Request, CGI::MiniSvr, CGI::Form,
304 CGI::Response
305
306 =cut
307
308 require 5.000;
309 use Exporter;
310 #use Carp;
311 BEGIN { 
312   require Carp; 
313   *CORE::GLOBAL::die = \&CGI::Carp::die;
314 }
315
316 use File::Spec;
317
318 @ISA = qw(Exporter);
319 @EXPORT = qw(confess croak carp);
320 @EXPORT_OK = qw(carpout fatalsToBrowser warningsToBrowser wrap set_message set_die_handler set_progname cluck ^name= die);
321
322 $main::SIG{__WARN__}=\&CGI::Carp::warn;
323
324 $CGI::Carp::VERSION     = '3.45';
325 $CGI::Carp::CUSTOM_MSG  = undef;
326 $CGI::Carp::DIE_HANDLER = undef;
327
328
329 # fancy import routine detects and handles 'errorWrap' specially.
330 sub import {
331     my $pkg = shift;
332     my(%routines);
333     my(@name);
334     if (@name=grep(/^name=/,@_))
335       {
336         my($n) = (split(/=/,$name[0]))[1];
337         set_progname($n);
338         @_=grep(!/^name=/,@_);
339       }
340
341     grep($routines{$_}++,@_,@EXPORT);
342     $WRAP++ if $routines{'fatalsToBrowser'} || $routines{'wrap'};
343     $WARN++ if $routines{'warningsToBrowser'};
344     my($oldlevel) = $Exporter::ExportLevel;
345     $Exporter::ExportLevel = 1;
346     Exporter::import($pkg,keys %routines);
347     $Exporter::ExportLevel = $oldlevel;
348     $main::SIG{__DIE__} =\&CGI::Carp::die if $routines{'fatalsToBrowser'};
349 #    $pkg->export('CORE::GLOBAL','die');
350 }
351
352 # These are the originals
353 sub realwarn { CORE::warn(@_); }
354 sub realdie { CORE::die(@_); }
355
356 sub id {
357     my $level = shift;
358     my($pack,$file,$line,$sub) = caller($level);
359     my($dev,$dirs,$id) = File::Spec->splitpath($file);
360     return ($file,$line,$id);
361 }
362
363 sub stamp {
364     my $time = scalar(localtime);
365     my $frame = 0;
366     my ($id,$pack,$file,$dev,$dirs);
367     if (defined($CGI::Carp::PROGNAME)) {
368         $id = $CGI::Carp::PROGNAME;
369     } else {
370         do {
371           $id = $file;
372           ($pack,$file) = caller($frame++);
373         } until !$file;
374     }
375     ($dev,$dirs,$id) = File::Spec->splitpath($id);
376     return "[$time] $id: ";
377 }
378
379 sub set_progname {
380     $CGI::Carp::PROGNAME = shift;
381     return $CGI::Carp::PROGNAME;
382 }
383
384
385 sub warn {
386     my $message = shift;
387     my($file,$line,$id) = id(1);
388     $message .= " at $file line $line.\n" unless $message=~/\n$/;
389     _warn($message) if $WARN;
390     my $stamp = stamp;
391     $message=~s/^/$stamp/gm;
392     realwarn $message;
393 }
394
395 sub _warn {
396     my $msg = shift;
397     if ($EMIT_WARNINGS) {
398         # We need to mangle the message a bit to make it a valid HTML
399         # comment.  This is done by substituting similar-looking ISO
400         # 8859-1 characters for <, > and -.  This is a hack.
401         $msg =~ tr/<>-/\253\273\255/;
402         chomp $msg;
403         print STDOUT "<!-- warning: $msg -->\n";
404     } else {
405         push @WARNINGS, $msg;
406     }
407 }
408
409
410 # The mod_perl package Apache::Registry loads CGI programs by calling
411 # eval.  These evals don't count when looking at the stack backtrace.
412 sub _longmess {
413     my $message = Carp::longmess();
414     $message =~ s,eval[^\n]+(ModPerl|Apache)/(?:Registry|Dispatch)\w*\.pm.*,,s
415         if exists $ENV{MOD_PERL};
416     return $message;
417 }
418
419 sub ineval {
420   (exists $ENV{MOD_PERL} ? 0 : $^S) || _longmess() =~ /eval [\{\']/m
421 }
422
423 sub die {
424   my ($arg,@rest) = @_;
425
426   &$DIE_HANDLER($arg,@rest) if $DIE_HANDLER;
427
428   # if called as die( $object, 'string' ),
429   # all is stringified, just like with
430   # the real 'die'
431   $arg = join '' => "$arg", @rest if @rest;
432
433   $arg ||= 'Died';
434
435   my($file,$line,$id) = id(1);
436
437   $arg .= " at $file line $line.\n" unless ref $arg or $arg=~/\n$/;
438
439   realdie $arg           if ineval();
440   &fatalsToBrowser($arg) if $WRAP;
441
442   $arg=~s/^/ stamp() /gme if $arg =~ /\n$/ or not exists $ENV{MOD_PERL};
443
444   $arg .= "\n" unless $arg =~ /\n$/;
445
446   realdie $arg;
447 }
448
449 sub set_message {
450     $CGI::Carp::CUSTOM_MSG = shift;
451     return $CGI::Carp::CUSTOM_MSG;
452 }
453
454 sub set_die_handler {
455
456     my ($handler) = shift;
457     
458     #setting SIG{__DIE__} here is necessary to catch runtime
459     #errors which are not called by literally saying "die",
460     #such as the line "undef->explode();". however, doing this
461     #will interfere with fatalsToBrowser, which also sets 
462     #SIG{__DIE__} in the import() function above (or the 
463     #import() function above may interfere with this). for
464     #this reason, you should choose to either set the die
465     #handler here, or use fatalsToBrowser, not both. 
466     $main::SIG{__DIE__} = $handler;
467     
468     $CGI::Carp::DIE_HANDLER = $handler; 
469     
470     return $CGI::Carp::DIE_HANDLER;
471 }
472
473 sub confess { CGI::Carp::die Carp::longmess @_; }
474 sub croak   { CGI::Carp::die Carp::shortmess @_; }
475 sub carp    { CGI::Carp::warn Carp::shortmess @_; }
476 sub cluck   { CGI::Carp::warn Carp::longmess @_; }
477
478 # We have to be ready to accept a filehandle as a reference
479 # or a string.
480 sub carpout {
481     my($in) = @_;
482     my($no) = fileno(to_filehandle($in));
483     realdie("Invalid filehandle $in\n") unless defined $no;
484     
485     open(SAVEERR, ">&STDERR");
486     open(STDERR, ">&$no") or 
487         ( print SAVEERR "Unable to redirect STDERR: $!\n" and exit(1) );
488 }
489
490 sub warningsToBrowser {
491     $EMIT_WARNINGS = @_ ? shift : 1;
492     _warn(shift @WARNINGS) while $EMIT_WARNINGS and @WARNINGS;
493 }
494
495 # headers
496 sub fatalsToBrowser {
497   my $msg = shift;
498
499   $msg = "$msg" if ref $msg;
500
501   $msg=~s/&/&amp;/g;
502   $msg=~s/>/&gt;/g;
503   $msg=~s/</&lt;/g;
504   $msg=~s/"/&quot;/g;
505
506   my($wm) = $ENV{SERVER_ADMIN} ? 
507     qq[the webmaster (<a href="mailto:$ENV{SERVER_ADMIN}">$ENV{SERVER_ADMIN}</a>)] :
508       "this site's webmaster";
509   my ($outer_message) = <<END;
510 For help, please send mail to $wm, giving this error message 
511 and the time and date of the error.
512 END
513   ;
514   my $mod_perl = exists $ENV{MOD_PERL};
515
516   if ($CUSTOM_MSG) {
517     if (ref($CUSTOM_MSG) eq 'CODE') {
518       print STDOUT "Content-type: text/html\n\n" 
519         unless $mod_perl;
520         eval { 
521             &$CUSTOM_MSG($msg); # nicer to perl 5.003 users
522         };
523         if ($@) { print STDERR q(error while executing the error handler: $@); }
524
525       return;
526     } else {
527       $outer_message = $CUSTOM_MSG;
528     }
529   }
530
531   my $mess = <<END;
532 <h1>Software error:</h1>
533 <pre>$msg</pre>
534 <p>
535 $outer_message
536 </p>
537 END
538   ;
539
540   if ($mod_perl) {
541     my $r;
542     if ($ENV{MOD_PERL_API_VERSION} && $ENV{MOD_PERL_API_VERSION} == 2) {
543       $mod_perl = 2;
544       require Apache2::RequestRec;
545       require Apache2::RequestIO;
546       require Apache2::RequestUtil;
547       require APR::Pool;
548       require ModPerl::Util;
549       require Apache2::Response;
550       $r = Apache2::RequestUtil->request;
551     }
552     else {
553       $r = Apache->request;
554     }
555     # If bytes have already been sent, then
556     # we print the message out directly.
557     # Otherwise we make a custom error
558     # handler to produce the doc for us.
559     if ($r->bytes_sent) {
560       $r->print($mess);
561       $mod_perl == 2 ? ModPerl::Util::exit(0) : $r->exit;
562     } else {
563       # MSIE won't display a custom 500 response unless it is >512 bytes!
564       if ($ENV{HTTP_USER_AGENT} =~ /MSIE/) {
565         $mess = "<!-- " . (' ' x 513) . " -->\n$mess";
566       }
567       $r->custom_response(500,$mess);
568     }
569   } else {
570     my $bytes_written = eval{tell STDOUT};
571     if (defined $bytes_written && $bytes_written > 0) {
572         print STDOUT $mess;
573     }
574     else {
575         print STDOUT "Status: 500\n";
576         print STDOUT "Content-type: text/html\n\n";
577         print STDOUT $mess;
578     }
579   }
580
581   warningsToBrowser(1);    # emit warnings before dying
582 }
583
584 # Cut and paste from CGI.pm so that we don't have the overhead of
585 # always loading the entire CGI module.
586 sub to_filehandle {
587     my $thingy = shift;
588     return undef unless $thingy;
589     return $thingy if UNIVERSAL::isa($thingy,'GLOB');
590     return $thingy if UNIVERSAL::isa($thingy,'FileHandle');
591     if (!ref($thingy)) {
592         my $caller = 1;
593         while (my $package = caller($caller++)) {
594             my($tmp) = $thingy=~/[\':]/ ? $thingy : "$package\:\:$thingy"; 
595             return $tmp if defined(fileno($tmp));
596         }
597     }
598     return undef;
599 }
600
601 1;