Error.pm 9.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
# -*- Mode: perl; indent-tabs-mode: nil -*-
#
# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is the Bugzilla Bug Tracking System.
#
# The Initial Developer of the Original Code is Netscape Communications
# Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s): Bradley Baetz <bbaetz@acm.org>
21
#                 Marc Schumann <wurblzap@gmail.com>
22
#                 Frédéric Buclin <LpSolit@gmail.com>
23 24 25

package Bugzilla::Error;

26
use strict;
27 28
use base qw(Exporter);

29
@Bugzilla::Error::EXPORT = qw(ThrowCodeError ThrowTemplateError ThrowUserError);
30

31
use Bugzilla::Constants;
32
use Bugzilla::WebService::Constants;
33
use Bugzilla::Hook;
34 35

use Carp;
36
use Data::Dumper;
37
use Date::Format;
38

39 40 41 42 43 44 45 46 47 48 49
# We cannot use $^S to detect if we are in an eval(), because mod_perl
# already eval'uates everything, so $^S = 1 in all cases under mod_perl!
sub _in_eval {
    my $in_eval = 0;
    for (my $stack = 1; my $sub = (caller($stack))[3]; $stack++) {
        last if $sub =~ /^ModPerl/;
        $in_eval = 1 if $sub =~ /^\(eval\)/;
    }
    return $in_eval;
}

50
sub _throw_error {
51
    my ($name, $error, $vars) = @_;
52
    my $dbh = Bugzilla->dbh;
53 54 55 56
    $vars ||= {};

    $vars->{error} = $error;

57 58
    # Make sure any transaction is rolled back (if supported).
    # If we are within an eval(), do not roll back transactions as we are
59
    # eval'uating some test on purpose.
60
    $dbh->bz_rollback_transaction() if ($dbh->bz_in_transaction() && !_in_eval());
61

62
    my $datadir = bz_locations()->{'datadir'};
63 64
    # If a writable $datadir/errorlog exists, log error details there.
    if (-w "$datadir/errorlog") {
65
        require Bugzilla::Util;
66 67 68 69 70
        require Data::Dumper;
        my $mesg = "";
        for (1..75) { $mesg .= "-"; };
        $mesg .= "\n[$$] " . time2str("%D %H:%M:%S ", time());
        $mesg .= "$name $error ";
71
        $mesg .= Bugzilla::Util::remote_ip();
72
        $mesg .= Bugzilla->user->login;
73
        $mesg .= (' actually ' . Bugzilla->sudoer->login) if Bugzilla->sudoer;
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
        $mesg .= "\n";
        my %params = Bugzilla->cgi->Vars;
        $Data::Dumper::Useqq = 1;
        for my $param (sort keys %params) {
            my $val = $params{$param};
            # obscure passwords
            $val = "*****" if $param =~ /password/i;
            # limit line length
            $val =~ s/^(.{512}).*$/$1\[CHOP\]/;
            $mesg .= "[$$] " . Data::Dumper->Dump([$val],["param($param)"]);
        }
        for my $var (sort keys %ENV) {
            my $val = $ENV{$var};
            $val = "*****" if $val =~ /password|http_pass/i;
            $mesg .= "[$$] " . Data::Dumper->Dump([$val],["env($var)"]);
        }
90
        open(ERRORLOGFID, ">>$datadir/errorlog");
91 92 93 94
        print ERRORLOGFID "$mesg\n";
        close ERRORLOGFID;
    }

95
    my $template = Bugzilla->template;
96 97 98 99 100
    if (Bugzilla->error_mode == ERROR_MODE_WEBPAGE) {
        print Bugzilla->cgi->header();
        $template->process($name, $vars)
          || ThrowTemplateError($template->error());
    }
101 102 103 104 105 106
    # There are some tests that throw and catch a lot of errors,
    # and calling $template->process over and over for those errors
    # is too slow. So instead, we just "die" with a dump of the arguments.
    elsif (Bugzilla->error_mode == ERROR_MODE_TEST) {
        die Dumper($vars);
    }
107
    else {
108 109 110
        my $message;
        $template->process($name, $vars, \$message)
          || ThrowTemplateError($template->error());
111 112 113
        if (Bugzilla->error_mode == ERROR_MODE_DIE) {
            die("$message\n");
        }
114 115 116
        elsif (Bugzilla->error_mode == ERROR_MODE_DIE_SOAP_FAULT
               || Bugzilla->error_mode == ERROR_MODE_JSON_RPC)
        {
117 118
            # Clone the hash so we aren't modifying the constant.
            my %error_map = %{ WS_ERROR_CODE() };
119
            Bugzilla::Hook::process('webservice_error_codes', 
120 121
                                    { error_map => \%error_map });
            my $code = $error_map{$error};
122 123 124 125
            if (!$code) {
                $code = ERROR_UNKNOWN_FATAL if $name =~ /code/i;
                $code = ERROR_UNKNOWN_TRANSIENT if $name =~ /user/i;
            }
126 127 128 129 130 131 132 133 134 135

            if (Bugzilla->error_mode == ERROR_MODE_DIE_SOAP_FAULT) {
                die SOAP::Fault->faultcode($code)->faultstring($message);
            }
            else {
                my $server = Bugzilla->_json_server;
                # Technically JSON-RPC isn't allowed to have error numbers
                # higher than 999, but we do this to avoid conflicts with
                # the internal JSON::RPC error codes.
                $server->raise_error(code    => 100000 + $code,
136 137 138
                                     message => $message,
                                     id      => $server->{_bz_request_id},
                                     version => $server->version);
139 140 141
                # Most JSON-RPC Throw*Error calls happen within an eval inside
                # of JSON::RPC. So, in that circumstance, instead of exiting,
                # we die with no message. JSON::RPC checks raise_error before
142
                # it checks $@, so it returns the proper error.
143 144
                die if _in_eval();
                $server->response($server->error_response_header);
145
            }
146
        }
147
    }
148 149 150
    exit;
}

151 152 153 154 155
sub ThrowUserError {
    _throw_error("global/user-error.html.tmpl", @_);
}

sub ThrowCodeError {
156 157 158 159 160 161 162 163 164 165
    my (undef, $vars) = @_;

    # Don't show function arguments, in case they contain
    # confidential data.
    local $Carp::MaxArgNums = -1;
    # Don't show the error as coming from Bugzilla::Error, show it
    # as coming from the caller.
    local $Carp::CarpInternal{'Bugzilla::Error'} = 1;
    $vars->{traceback} = Carp::longmess();

166 167 168 169 170
    _throw_error("global/code-error.html.tmpl", @_);
}

sub ThrowTemplateError {
    my ($template_err) = @_;
171
    my $dbh = Bugzilla->dbh;
172

173 174
    # Make sure the transaction is rolled back (if supported).
    $dbh->bz_rollback_transaction() if $dbh->bz_in_transaction();
175

176
    my $vars = {};
177
    if (Bugzilla->error_mode == ERROR_MODE_DIE) {
178 179
        die("error: template error: $template_err");
    }
180 181 182 183 184 185 186 187 188

    $vars->{'template_error_msg'} = $template_err;
    $vars->{'error'} = "template_error";

    my $template = Bugzilla->template;

    # Try a template first; but if this one fails too, fall back
    # on plain old print statements.
    if (!$template->process("global/code-error.html.tmpl", $vars)) {
189 190
        require Bugzilla::Util;
        import Bugzilla::Util qw(html_quote);
191 192 193
        my $maintainer = Bugzilla->params->{'maintainer'};
        my $error = html_quote($vars->{'template_error_msg'});
        my $error2 = html_quote($template->error());
194 195 196 197 198 199 200 201
        print <<END;
        <tt>
          <p>
            Bugzilla has suffered an internal error. Please save this page and 
            send it to $maintainer with details of what you were doing at the 
            time this message appeared.
          </p>
          <script type="text/javascript"> <!--
202 203 204 205
          document.write("<p>URL: " + 
                          document.location.href.replace(/&/g,"&amp;")
                                                .replace(/</g,"&lt;")
                                                .replace(/>/g,"&gt;") + "</p>");
206 207 208 209 210 211 212 213 214 215 216
          // -->
          </script>
          <p>Template->process() failed twice.<br>
          First error: $error<br>
          Second error: $error2</p>
        </tt>
END
    }
    exit;
}

217 218 219 220 221 222 223 224 225 226 227 228 229 230
1;

__END__

=head1 NAME

Bugzilla::Error - Error handling utilities for Bugzilla

=head1 SYNOPSIS

  use Bugzilla::Error;

  ThrowUserError("error_tag",
                 { foo => 'bar' });
231

232 233 234 235
=head1 DESCRIPTION

Various places throughout the Bugzilla codebase need to report errors to the
user. The C<Throw*Error> family of functions allow this to be done in a
236
generic and localizable manner.
237

238 239 240 241
These functions automatically unlock the database tables, if there were any
locked. They will also roll back the transaction, if it is supported by
the underlying DB.

242 243 244 245 246 247 248 249 250 251 252
=head1 FUNCTIONS

=over 4

=item C<ThrowUserError>

This function takes an error tag as the first argument, and an optional hashref
of variables as a second argument. These are used by the
I<global/user-error.html.tmpl> template to format the error, using the passed
in variables as required.

253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
=item C<ThrowCodeError>

This function is used when an internal check detects an error of some sort.
This usually indicates a bug in Bugzilla, although it can occur if the user
manually constructs urls without correct parameters.

This function's behaviour is similar to C<ThrowUserError>, except that the
template used to display errors is I<global/code-error.html.tmpl>. In addition
if the hashref used as the optional second argument contains a key I<variables>
then the contents of the hashref (which is expected to be another hashref) will
be displayed after the error message, as a debugging aid.

=item C<ThrowTemplateError>

This function should only be called if a C<template-<gt>process()> fails.
It tries another template first, because often one template being
broken or missing doesn't mean that they all are. But it falls back to
a print statement as a last-ditch error.

272 273 274 275 276
=back

=head1 SEE ALSO

L<Bugzilla|Bugzilla>