CGI.pm 20.3 KB
Newer Older
1 2 3
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
#
5 6
# This Source Code Form is "Incompatible With Secondary Licenses", as
# defined by the Mozilla Public License, v. 2.0.
7

8
package Bugzilla::CGI;
9
use strict;
10
use base qw(CGI);
11

12 13 14
use Bugzilla::Constants;
use Bugzilla::Error;
use Bugzilla::Util;
15
use Bugzilla::Search::Recent;
16

17 18
use File::Basename;

19
BEGIN {
20
    if (ON_WINDOWS) {
21 22 23 24
        # Help CGI find the correct temp directory as the default list
        # isn't Windows friendly (Bug 248988)
        $ENV{'TMPDIR'} = $ENV{'TEMP'} || $ENV{'TMP'} || "$ENV{'WINDIR'}\\TEMP";
    }
25
    *AUTOLOAD = \&CGI::AUTOLOAD;
26 27
}

28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
sub _init_bz_cgi_globals {
    my $invocant = shift;
    # We need to disable output buffering - see bug 179174
    $| = 1;

    # Ignore SIGTERM and SIGPIPE - this prevents DB corruption. If the user closes
    # their browser window while a script is running, the web server sends these
    # signals, and we don't want to die half way through a write.
    $SIG{TERM} = 'IGNORE';
    $SIG{PIPE} = 'IGNORE';

    # We don't precompile any functions here, that's done specially in
    # mod_perl code.
    $invocant->_setup_symbols(qw(:no_xhtml :oldstyle_urls :private_tempfiles
                                 :unique_headers));
}

BEGIN { __PACKAGE__->_init_bz_cgi_globals() if i_am_cgi(); }

47 48 49 50
sub new {
    my ($invocant, @args) = @_;
    my $class = ref($invocant) || $invocant;

51 52 53 54
    # Under mod_perl, CGI's global variables get reset on each request,
    # so we need to set them up again every time.
    $class->_init_bz_cgi_globals() if $ENV{MOD_PERL};

55 56
    my $self = $class->SUPER::new(@args);

57 58 59
    # Make sure our outgoing cookie list is empty on each invocation
    $self->{Bugzilla_cookie_list} = [];

60
    # Path-Info is of no use for Bugzilla and interacts badly with IIS.
61
    # Moreover, it causes unexpected behaviors, such as totally breaking
62 63 64
    # the rendering of pages. Skip it!
    print $self->redirect($self->url(-path => 0, -query => 1)) if $self->path_info;

65
    # Send appropriate charset
66
    $self->charset(Bugzilla->params->{'utf8'} ? 'UTF-8' : '');
67

68
    # Redirect to urlbase/sslbase if we are not viewing an attachment.
69 70 71
    my $script = basename($0);
    if ($self->url_is_attachment_base and $script ne 'attachment.cgi') {
        $self->redirect_to_urlbase();
72 73
    }

74 75 76 77 78 79 80 81 82 83 84
    # Check for errors
    # All of the Bugzilla code wants to do this, so do it here instead of
    # in each script

    my $err = $self->cgi_error;

    if ($err) {
        # Note that this error block is only triggered by CGI.pm for malformed
        # multipart requests, and so should never happen unless there is a
        # browser bug.

85 86 87 88 89 90 91 92 93 94 95 96
        print $self->header(-status => $err);

        # ThrowCodeError wants to print the header, so it grabs Bugzilla->cgi
        # which creates a new Bugzilla::CGI object, which fails again, which
        # ends up here, and calls ThrowCodeError, and then recurses forever.
        # So don't use it.
        # In fact, we can't use templates at all, because we need a CGI object
        # to determine the template lang as well as the current url (from the
        # template)
        # Since this is an internal error which indicates a severe browser bug,
        # just die.
        die "CGI parsing error: $err";
97 98 99 100 101 102 103 104 105 106 107 108 109
    }

    return $self;
}

# We want this sorted plus the ability to exclude certain params
sub canonicalise_query {
    my ($self, @exclude) = @_;

    # Reconstruct the URL by concatenating the sorted param=value pairs
    my @parameters;
    foreach my $key (sort($self->param())) {
        # Leave this key out if it's in the exclude list
110
        next if grep { $_ eq $key } @exclude;
111

112 113 114 115
        # Remove the Boolean Charts for standard query.cgi fields
        # They are listed in the query URL already
        next if $key =~ /^(field|type|value)(-\d+){3}$/;

116 117 118
        my $esc_key = url_quote($key);

        foreach my $value ($self->param($key)) {
119
            if (defined($value)) {
120 121 122 123 124 125 126 127 128 129
                my $esc_value = url_quote($value);

                push(@parameters, "$esc_key=$esc_value");
            }
        }
    }

    return join("&", @parameters);
}

130 131
sub clean_search_url {
    my $self = shift;
132
    # Delete any empty URL parameter.
133 134 135 136 137 138 139 140
    my @cgi_params = $self->param;

    foreach my $param (@cgi_params) {
        if (defined $self->param($param) && $self->param($param) eq '') {
            $self->delete($param);
            $self->delete("${param}_type");
        }

141 142 143 144 145 146 147 148 149 150 151 152
        # Custom Search stuff is empty if it's "noop". We also keep around
        # the old Boolean Chart syntax for backwards-compatibility.
        if (($param =~ /\d-\d-\d/ || $param =~ /^[[:alpha:]]\d+$/)
            && defined $self->param($param) && $self->param($param) eq 'noop')
        {
            $self->delete($param);
        }
        
        # Any "join" for custom search that's an AND can be removed, because
        # that's the default.
        if (($param =~ /^j\d+$/ || $param eq 'j_top')
            && $self->param($param) eq 'AND')
153 154 155 156 157
        {
            $self->delete($param);
        }
    }

158 159 160
    # Delete leftovers from the login form
    $self->delete('Bugzilla_remember', 'GoAheadAndLogIn');

161
    foreach my $num (1,2,3) {
162 163
        # If there's no value in the email field, delete the related fields.
        if (!$self->param("email$num")) {
164
            foreach my $field (qw(type assigned_to reporter qa_contact cc longdesc)) {
165 166 167 168 169 170 171 172
                $self->delete("email$field$num");
            }
        }
    }

    # chfieldto is set to "Now" by default in query.cgi. But if none
    # of the other chfield parameters are set, it's meaningless.
    if (!defined $self->param('chfieldfrom') && !$self->param('chfield')
173 174
        && !defined $self->param('chfieldvalue') && $self->param('chfieldto')
        && lc($self->param('chfieldto')) eq 'now')
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
    {
        $self->delete('chfieldto');
    }

    # cmdtype "doit" is the default from query.cgi, but it's only meaningful
    # if there's a remtype parameter.
    if (defined $self->param('cmdtype') && $self->param('cmdtype') eq 'doit'
        && !defined $self->param('remtype'))
    {
        $self->delete('cmdtype');
    }

    # "Reuse same sort as last time" is actually the default, so we don't
    # need it in the URL.
    if ($self->param('order') 
        && $self->param('order') eq 'Reuse same sort as last time')
    {
        $self->delete('order');
    }

195 196
    # list_id is added in buglist.cgi after calling clean_search_url,
    # and doesn't need to be saved in saved searches.
197 198 199 200
    $self->delete('list_id');

    # no_redirect is used internally by redirect_search_url().
    $self->delete('no_redirect');
201

202 203 204 205 206
    # And now finally, if query_format is our only parameter, that
    # really means we have no parameters, so we should delete query_format.
    if ($self->param('query_format') && scalar($self->param()) == 1) {
        $self->delete('query_format');
    }
207 208
}

209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
sub check_etag {
    my ($self, $valid_etag) = @_;

    # ETag support.
    my $if_none_match = $self->http('If-None-Match');
    return if !$if_none_match;

    my @if_none = split(/[\s,]+/, $if_none_match);
    foreach my $possible_etag (@if_none) {
        # remove quotes from begin and end of the string
        $possible_etag =~ s/^\"//g;
        $possible_etag =~ s/\"$//g;
        if ($possible_etag eq $valid_etag or $possible_etag eq '*') {
            print $self->header(-ETag => $possible_etag,
                                -status => '304 Not Modified');
            exit;
        }
    }
}

229 230 231
# Have to add the cookies in.
sub multipart_start {
    my $self = shift;
232 233 234
    
    my %args = @_;

235
    # CGI.pm::multipart_start doesn't honour its own charset information, so
236
    # we do it ourselves here
237
    if (defined $self->charset() && defined $args{-type}) {
238 239 240
        # Remove any existing charset specifier
        $args{-type} =~ s/;.*$//;
        # and add the specified one
241
        $args{-type} .= '; charset=' . $self->charset();
242 243 244
    }
        
    my $headers = $self->SUPER::multipart_start(%args);
245 246 247 248 249 250 251 252 253 254 255 256
    # Eliminate the one extra CRLF at the end.
    $headers =~ s/$CGI::CRLF$//;
    # Add the cookies. We have to do it this way instead of
    # passing them to multpart_start, because CGI.pm's multipart_start
    # doesn't understand a '-cookie' argument pointing to an arrayref.
    foreach my $cookie (@{$self->{Bugzilla_cookie_list}}) {
        $headers .= "Set-Cookie: ${cookie}${CGI::CRLF}";
    }
    $headers .= $CGI::CRLF;
    return $headers;
}

257 258 259 260
# Override header so we can add the cookies in
sub header {
    my $self = shift;

261 262 263 264 265 266
    # If there's only one parameter, then it's a Content-Type.
    if (scalar(@_) == 1) {
        # Since we're adding parameters below, we have to name it.
        unshift(@_, '-type' => shift(@_));
    }

267 268 269 270 271
    # Add the cookies in if we have any
    if (scalar(@{$self->{Bugzilla_cookie_list}})) {
        unshift(@_, '-cookie' => $self->{Bugzilla_cookie_list});
    }

272
    # Add Strict-Transport-Security (STS) header if this response
273
    # is over SSL and the strict_transport_security param is turned on.
274 275 276
    if ($self->https && !$self->url_is_attachment_base
        && Bugzilla->params->{'strict_transport_security'} ne 'off') 
    {
277
        my $sts_opts = 'max-age=' . MAX_STS_AGE;
278 279 280
        if (Bugzilla->params->{'strict_transport_security'} 
            eq 'include_subdomains')
        {
281 282 283
            $sts_opts .= '; includeSubDomains';
        }
        unshift(@_, '-strict_transport_security' => $sts_opts);
284 285
    }

286 287 288 289 290 291
    # Add X-Frame-Options header to prevent framing and subsequent
    # possible clickjacking problems.
    unless ($self->url_is_attachment_base) {
        unshift(@_, '-x_frame_options' => 'SAMEORIGIN');
    }

292 293 294 295
    # Add X-XSS-Protection header to prevent simple XSS attacks
    # and enforce the blocking (rather than the rewriting) mode.
    unshift(@_, '-x_xss_protection' => '1; mode=block');

296 297 298 299
    # Add X-Content-Type-Options header to prevent browsers sniffing
    # the MIME type away from the declared Content-Type.
    unshift(@_, '-x_content_type_options' => 'nosniff');

300
    return $self->SUPER::header(@_) || "";
301 302
}

303 304
sub param {
    my $self = shift;
305 306 307 308 309 310 311 312

    # When we are just requesting the value of a parameter...
    if (scalar(@_) == 1) {
        my @result = $self->SUPER::param(@_); 

        # Also look at the URL parameters, after we look at the POST 
        # parameters. This is to allow things like login-form submissions
        # with URL parameters in the form's "target" attribute.
313 314 315
        if (!scalar(@result)
            && $self->request_method && $self->request_method eq 'POST')
        {
316 317 318
            # Some servers fail to set the QUERY_STRING parameter, which
            # causes undef issues
            $ENV{'QUERY_STRING'} = '' unless exists $ENV{'QUERY_STRING'};
319
            @result = $self->SUPER::url_param(@_);
320
        }
321 322 323 324

        # Fix UTF-8-ness of input parameters.
        if (Bugzilla->params->{'utf8'}) {
            @result = map { _fix_utf8($_) } @result;
325
        }
326 327

        return wantarray ? @result : $result[0];
328
    }
329 330 331 332 333 334 335 336 337 338 339
    # And for various other functions in CGI.pm, we need to correctly
    # return the URL parameters in addition to the POST parameters when
    # asked for the list of parameters.
    elsif (!scalar(@_) && $self->request_method 
           && $self->request_method eq 'POST') 
    {
        my @post_params = $self->SUPER::param;
        my @url_params  = $self->url_param;
        my %params = map { $_ => 1 } (@post_params, @url_params);
        return keys %params;
    }
340

341 342 343 344 345 346 347 348 349 350
    return $self->SUPER::param(@_);
}

sub _fix_utf8 {
    my $input = shift;
    # The is_utf8 is here in case CGI gets smart about utf8 someday.
    utf8::decode($input) if defined $input && !utf8::is_utf8($input);
    return $input;
}

351 352 353 354 355 356 357 358
sub should_set {
    my ($self, $param) = @_;
    my $set = (defined $self->param($param) 
               or defined $self->param("defined_$param"))
              ? 1 : 0;
    return $set;
}

359
# The various parts of Bugzilla which create cookies don't want to have to
360
# pass them around to all of the callers. Instead, store them locally here,
361
# and then output as required from |header|.
362 363 364
sub send_cookie {
    my $self = shift;

365 366 367 368 369 370 371
    # Move the param list into a hash for easier handling.
    my %paramhash;
    my @paramlist;
    my ($key, $value);
    while ($key = shift) {
        $value = shift;
        $paramhash{$key} = $value;
372
    }
373

374 375 376 377 378 379
    # Complain if -value is not given or empty (bug 268146).
    if (!exists($paramhash{'-value'}) || !$paramhash{'-value'}) {
        ThrowCodeError('cookies_need_value');
    }

    # Add the default path and the domain in.
380 381 382
    $paramhash{'-path'} = Bugzilla->params->{'cookiepath'};
    $paramhash{'-domain'} = Bugzilla->params->{'cookiedomain'}
        if Bugzilla->params->{'cookiedomain'};
383 384 385 386 387 388 389 390

    # Move the param list back into an array for the call to cookie().
    foreach (keys(%paramhash)) {
        unshift(@paramlist, $_ => $paramhash{$_});
    }

    push(@{$self->{'Bugzilla_cookie_list'}}, $self->cookie(@paramlist));
}
391

392 393 394 395 396 397 398 399 400 401
# Cookies are removed by setting an expiry date in the past.
# This method is a send_cookie wrapper doing exactly this.
sub remove_cookie {
    my $self = shift;
    my ($cookiename) = (@_);

    # Expire the cookie, giving a non-empty dummy value (bug 268146).
    $self->send_cookie('-name'    => $cookiename,
                       '-expires' => 'Tue, 15-Sep-1998 21:49:00 GMT',
                       '-value'   => 'X');
402 403
}

404 405 406 407
# This helps implement Bugzilla::Search::Recent, and also shortens search
# URLs that get POSTed to buglist.cgi.
sub redirect_search_url {
    my $self = shift;
408 409 410 411

    # If there is no parameter, there is nothing to do.
    return unless $self->param;

412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
    # If we're retreiving an old list, we never need to redirect or
    # do anything related to Bugzilla::Search::Recent.
    return if $self->param('regetlastlist');

    my $user = Bugzilla->user;

    if ($user->id) {
        # There are two conditions that could happen here--we could get a URL
        # with no list id, and we could get a URL with a list_id that isn't
        # ours.
        my $list_id = $self->param('list_id');
        if ($list_id) {
            # If we have a valid list_id, no need to redirect or clean.
            return if Bugzilla::Search::Recent->check_quietly(
                { id => $list_id });
        }
    }
    elsif ($self->request_method ne 'POST') {
        # Logged-out users who do a GET don't get a list_id, don't get
        # their URLs cleaned, and don't get redirected.
        return;
    }

435
    my $no_redirect = $self->param('no_redirect');
436 437
    $self->clean_search_url();

438 439 440
    # Make sure we still have params still after cleaning otherwise we 
    # do not want to store a list_id for an empty search.
    if ($user->id && $self->param) {
441 442 443 444 445 446 447 448
        # Insert a placeholder Bugzilla::Search::Recent, so that we know what
        # the id of the resulting search will be. This is then pulled out
        # of the Referer header when viewing show_bug.cgi to know what
        # bug list we came from.
        my $recent_search = Bugzilla::Search::Recent->create_placeholder;
        $self->param('list_id', $recent_search->id);
    }

449 450 451 452
    # Browsers which support history.replaceState do not need to be
    # redirected. We can fix the URL on the fly.
    return if $no_redirect;

453 454 455 456 457 458 459 460 461
    # GET requests that lacked a list_id are always redirected. POST requests
    # are only redirected if they're under the CGI_URI_LIMIT though.
    my $uri_length = length($self->self_url());
    if ($self->request_method() ne 'POST' or $uri_length < CGI_URI_LIMIT) {
        print $self->redirect(-url => $self->self_url());
        exit;
    }
}

462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
sub redirect_to_https {
    my $self = shift;
    my $sslbase = Bugzilla->params->{'sslbase'};
    # If this is a POST, we don't want ?POSTDATA in the query string.
    # We expect the client to re-POST, which may be a violation of
    # the HTTP spec, but the only time we're expecting it often is
    # in the WebService, and WebService clients usually handle this
    # correctly.
    $self->delete('POSTDATA');
    my $url = $sslbase . $self->url('-path_info' => 1, '-query' => 1, 
                                    '-relative' => 1);

    # XML-RPC clients (SOAP::Lite at least) require a 301 to redirect properly
    # and do not work with 302. Our redirect really is permanent anyhow, so
    # it doesn't hurt to make it a 301.
    print $self->redirect(-location => $url, -status => 301);

479 480 481
    # When using XML-RPC with mod_perl, we need the headers sent immediately.
    $self->r->rflush if $ENV{MOD_PERL};
    exit;
482
}
483

484 485 486 487 488 489 490 491
# Redirect to the urlbase version of the current URL.
sub redirect_to_urlbase {
    my $self = shift;
    my $path = $self->url('-path_info' => 1, '-query' => 1, '-relative' => 1);
    print $self->redirect('-location' => correct_urlbase() . $path);
    exit;
}

492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
sub url_is_attachment_base {
    my ($self, $id) = @_;
    return 0 if !use_attachbase() or !i_am_cgi();
    my $attach_base = Bugzilla->params->{'attachment_base'};
    # If we're passed an id, we only want one specific attachment base
    # for a particular bug. If we're not passed an ID, we just want to
    # know if our current URL matches the attachment_base *pattern*.
    my $regex;
    if ($id) {
        $attach_base =~ s/\%bugid\%/$id/;
        $regex = quotemeta($attach_base);
    }
    else {
        # In this circumstance we run quotemeta first because we need to
        # insert an active regex meta-character afterward.
        $regex = quotemeta($attach_base);
        $regex =~ s/\\\%bugid\\\%/\\d+/;
    }
    $regex = "^$regex";
    return ($self->self_url =~ $regex) ? 1 : 0;
}

514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
##########################
# Vars TIEHASH Interface #
##########################

# Fix the TIEHASH interface (scalar $cgi->Vars) to return and accept 
# arrayrefs.
sub STORE {
    my $self = shift;
    my ($param, $value) = @_;
    if (defined $value and ref $value eq 'ARRAY') {
        return $self->param(-name => $param, -value => $value);
    }
    return $self->SUPER::STORE(@_);
}

sub FETCH {
    my ($self, $param) = @_;
    return $self if $param eq 'CGI'; # CGI.pm did this, so we do too.
    my @result = $self->param($param);
    return undef if !scalar(@result);
    return $result[0] if scalar(@result) == 1;
    return \@result;
}

# For the Vars TIEHASH interface: the normal CGI.pm DELETE doesn't return 
# the value deleted, but Perl's "delete" expects that value.
sub DELETE {
    my ($self, $param) = @_;
    my $value = $self->FETCH($param);
    $self->delete($param);
    return $value;
}

547 548 549 550 551 552
1;

__END__

=head1 NAME

553
Bugzilla::CGI - CGI handling for Bugzilla
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587

=head1 SYNOPSIS

  use Bugzilla::CGI;

  my $cgi = new Bugzilla::CGI();

=head1 DESCRIPTION

This package inherits from the standard CGI module, to provide additional
Bugzilla-specific functionality. In general, see L<the CGI.pm docs|CGI> for
documention.

=head1 CHANGES FROM L<CGI.PM|CGI>

Bugzilla::CGI has some differences from L<CGI.pm|CGI>.

=over 4

=item C<cgi_error> is automatically checked

After creating the CGI object, C<Bugzilla::CGI> automatically checks
I<cgi_error>, and throws a CodeError if a problem is detected.

=back

=head1 ADDITIONAL FUNCTIONS

I<Bugzilla::CGI> also includes additional functions.

=over 4

=item C<canonicalise_query(@exclude)>

588
This returns a sorted string of the parameters, suitable for use in a url.
589 590
Values in C<@exclude> are not included in the result.

591 592
=item C<send_cookie>

593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
This routine is identical to the cookie generation part of CGI.pm's C<cookie>
routine, except that it knows about Bugzilla's cookie_path and cookie_domain
parameters and takes them into account if necessary.
This should be used by all Bugzilla code (instead of C<cookie> or the C<-cookie>
argument to C<header>), so that under mod_perl the headers can be sent
correctly, using C<print> or the mod_perl APIs as appropriate.

To remove (expire) a cookie, use C<remove_cookie>.

=item C<remove_cookie>

This is a wrapper around send_cookie, setting an expiry date in the past,
effectively removing the cookie.

As its only argument, it takes the name of the cookie to expire.
608

609
=item C<redirect_to_https>
610

611 612
This routine redirects the client to the https version of the page that
they're looking at, using the C<sslbase> parameter for the redirection.
613

614 615
Generally you should use L<Bugzilla::Util/do_ssl_redirect_if_required>
instead of calling this directly.
616

617 618 619 620
=item C<redirect_to_urlbase>

Redirects from the current URL to one prefixed by the urlbase parameter.

621
=back
622 623 624 625

=head1 SEE ALSO

L<CGI|CGI>, L<CGI::Cookie|CGI::Cookie>