CGI.pl 37.8 KB
Newer Older
1 2
# -*- Mode: perl; indent-tabs-mode: nil -*-
#
3 4 5 6 7 8 9 10 11 12
# 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.
#
13
# The Original Code is the Bugzilla Bug Tracking System.
14
#
15
# The Initial Developer of the Original Code is Netscape Communications
16 17 18 19
# Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
20
# Contributor(s): Terry Weissman <terry@mozilla.org>
21
#                 Dan Mosedale <dmose@mozilla.org>
22
#                 Joe Robins <jmrobins@tgix.com>
23
#                 Dave Miller <justdave@syndicomm.com>
24
#                 Christopher Aillon <christopher@aillon.com>
25
#                 Gervase Markham <gerv@gerv.net>
26
#                 Christian Reis <kiko@async.com.br>
27 28 29 30 31

# Contains some global routines used throughout the CGI scripts of Bugzilla.

use diagnostics;
use strict;
32 33
use lib ".";

terry%mozilla.org's avatar
terry%mozilla.org committed
34
# use Carp;                       # for confess
35

36 37
use Bugzilla::Util;

38 39
# commented out the following snippet of code. this tosses errors into the
# CGI if you are perl 5.6, and doesn't if you have perl 5.003. 
40
# We want to check for the existence of the LDAP modules here.
41 42 43
# eval "use Mozilla::LDAP::Conn";
# my $have_ldap = $@ ? 0 : 1;

44 45
# Shut up misguided -w warnings about "used only once".  For some reason,
# "use vars" chokes on me when I try it here.
46

47
sub CGI_pl_sillyness {
48
    my $zz;
terry%mozilla.org's avatar
terry%mozilla.org committed
49
    $zz = %::MFORM;
50
    $zz = %::dontchange;
51 52
}

53 54 55 56
use CGI::Carp qw(fatalsToBrowser);

require 'globals.pl';

57 58
use vars qw($template $vars);

59 60 61 62 63
# If Bugzilla is shut down, do not go any further, just display a message
# to the user about the downtime.  (do)editparams.cgi is exempted from
# this message, of course, since it needs to be available in order for
# the administrator to open Bugzilla back up.
if (Param("shutdownhtml") && $0 !~ m:[\\/](do)?editparams.cgi$:) {
64
    $::vars->{'message'} = "shutdown";
65 66 67 68 69 70
    
    # Return the appropriate HTTP response headers.
    print "Content-Type: text/html\n\n";
    
    # Generate and return an HTML message about the downtime.
    $::template->process("global/message.html.tmpl", $::vars)
71
      || ThrowTemplateError($::template->error());
72 73 74
    exit;
}

75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
# Implementations of several of the below were blatently stolen from CGI.pm,
# by Lincoln D. Stein.

# Get rid of all the %xx encoding and the like from the given URL.
sub url_decode {
    my ($todecode) = (@_);
    $todecode =~ tr/+/ /;       # pluses become spaces
    $todecode =~ s/%([0-9a-fA-F]{2})/pack("c",hex($1))/ge;
    return $todecode;
}

# Quotify a string, suitable for putting into a URL.
sub url_quote {
    my($toencode) = (@_);
    $toencode=~s/([^a-zA-Z0-9_\-.])/uc sprintf("%%%02x",ord($1))/eg;
    return $toencode;
}

93 94 95 96
sub ParseUrlString {
    my ($buffer, $f, $m) = (@_);
    undef %$f;
    undef %$m;
97 98

    my %isnull;
99

100 101 102 103 104 105 106 107 108 109 110 111
    # We must make sure that the CGI params remain tainted.
    # This means that if for some reason you want to make this code
    # use a regexp and $1, $2, ... (or use a helper function which does so)
    # you must |use re 'taint'| _and_ make sure that you don't run into
    # http://bugs.perl.org/perlbug.cgi?req=bug_id&bug_id=20020704.001
    my @args = split('&', $buffer);
    foreach my $arg (@args) {
        my ($name, $value) = split('=', $arg, 2);
        $value = '' if not defined $value;

        $name = url_decode($name);
        $value = url_decode($value);
112

113 114 115 116 117 118 119 120 121
        if ($value ne "") {
            if (defined $f->{$name}) {
                $f->{$name} .= $value;
                my $ref = $m->{$name};
                push @$ref, $value;
            } else {
                $f->{$name} = $value;
                $m->{$name} = [$value];
            }
122 123 124 125
        } else {
            $isnull{$name} = 1;
        }
    }
126
    if (%isnull) {
127
        foreach my $name (keys(%isnull)) {
128 129 130
            if (!defined $f->{$name}) {
                $f->{$name} = "";
                $m->{$name} = [];
131 132 133 134 135
            }
        }
    }
}

136 137 138 139 140
sub ProcessFormFields {
    my ($buffer) = (@_);
    return ParseUrlString($buffer, \%::FORM, \%::MFORM);
}

141
sub ProcessMultipartFormFields {
142 143 144 145 146
    my ($boundary) = @_;

    # Initialize variables that store whether or not we are parsing a header,
    # the name of the part we are parsing, and its value (which is incomplete
    # until we finish parsing the part).
147
    my $inheader = 1;
148 149 150 151 152 153 154
    my $fieldname = "";
    my $fieldvalue = "";

    # Read the input stream line by line and parse it into a series of parts,
    # each one containing a single form field and its value and each one
    # separated from the next by the value of $boundary.
    my $remaining = $ENV{"CONTENT_LENGTH"};
155 156
    while ($remaining > 0 && ($_ = <STDIN>)) {
        $remaining -= length($_);
157 158 159

        # If the current input line is a boundary line, save the previous
        # form value and reset the storage variables.
160
        if ($_ =~ m/^-*\Q$boundary\E/) {
161 162 163 164 165
            if ( $fieldname ) {
                chomp($fieldvalue);
                $fieldvalue =~ s/\r$//;
                if ( defined $::FORM{$fieldname} ) {
                    $::FORM{$fieldname} .= $fieldvalue;
166
                    push @{$::MFORM{$fieldname}}, $fieldvalue;
167 168 169 170 171
                } else {
                    $::FORM{$fieldname} = $fieldvalue;
                    $::MFORM{$fieldname} = [$fieldvalue];
                }
            }
172

173 174 175 176 177 178 179 180 181 182
            $inheader = 1;
            $fieldname = "";
            $fieldvalue = "";

        # If the current input line is a header line, look for a blank line
        # (meaning the end of the headers), a Content-Disposition header
        # (containing the field name and, for uploaded file parts, the file 
        # name), or a Content-Type header (containing the content type for 
        # file parts).
        } elsif ( $inheader ) {
183 184
            if (m/^\s*$/) {
                $inheader = 0;
185 186
            } elsif (m/^Content-Disposition:\s*form-data\s*;\s*name\s*=\s*"([^\"]+)"/i) {
                $fieldname = $1;
187
                if (m/;\s*filename\s*=\s*"([^\"]+)"/i) {
188
                    $::FILE{$fieldname}->{'filename'} = $1;
189
                }
190 191
            } elsif ( m|^Content-Type:\s*([^/]+/[^\s;]+)|i ) {
                $::FILE{$fieldname}->{'contenttype'} = $1;
192
            }
193 194 195 196 197

        # If the current input line is neither a boundary line nor a header,
        # it must be part of the field value, so append it to the value.
        } else {
          $fieldvalue .= $_;
198 199 200 201
        }
    }
}

202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
# check and see if a given field exists, is non-empty, and is set to a 
# legal value.  assume a browser bug and abort appropriately if not.
# if $legalsRef is not passed, just check to make sure the value exists and 
# is non-NULL
sub CheckFormField (\%$;\@) {
    my ($formRef,                # a reference to the form to check (a hash)
        $fieldname,              # the fieldname to check
        $legalsRef               # (optional) ref to a list of legal values 
       ) = @_;

    if ( !defined $formRef->{$fieldname} ||
         trim($formRef->{$fieldname}) eq "" ||
         (defined($legalsRef) && 
          lsearch($legalsRef, $formRef->{$fieldname})<0) ){

217 218 219
        SendSQL("SELECT description FROM fielddefs WHERE name=" . SqlQuote($fieldname));
        my $result = FetchOneColumn();
        if ($result) {
220
            $vars->{'field'} = $result;
221 222
        }
        else {
223
            $vars->{'field'} = $fieldname;
224
        }
225 226
        
        ThrowCodeError("illegal_field", "abort");
227 228 229 230 231 232 233 234 235
      }
}

# check and see if a given field is defined, and abort if not
sub CheckFormFieldDefined (\%$) {
    my ($formRef,                # a reference to the form to check (a hash)
        $fieldname,              # the fieldname to check
       ) = @_;

236
    if (!defined $formRef->{$fieldname}) {
237 238 239
        $vars->{'field'} = $fieldname;  
        ThrowCodeError("undefined_field");
    }
240
}
241

242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
sub BugAliasToID {
    # Queries the database for the bug with a given alias, and returns
    # the ID of the bug if it exists or the undefined value if it doesn't.
    
    my ($alias) = @_;
    
    return undef unless Param("usebugaliases");
    
    PushGlobalSQLState();
    SendSQL("SELECT bug_id FROM bugs WHERE alias = " . SqlQuote($alias));
    my $id = FetchOneColumn();
    PopGlobalSQLState();
    
    return $id;
}

258
sub ValidateBugID {
259 260 261
    # Validates and verifies a bug ID, making sure the number is a 
    # positive integer, that it represents an existing bug in the
    # database, and that the user is authorized to access that bug.
262
    # We detaint the number here, too
263

264 265 266 267 268 269
    my ($id, $skip_authorization) = @_;
    
    # Get rid of white-space around the ID.
    $id = trim($id);
    
    # If the ID isn't a number, it might be an alias, so try to convert it.
270 271 272
    my $alias = $id;
    if (!detaint_natural($id)) {
        $id = BugAliasToID($alias);
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
        if (!$id) {
            my $html_id = html_quote($_[0]);
            my $alias_specific_message = Param("usebugaliases") ? 
              " (it is neither a bug number nor an alias to a bug number)" : "";
            DisplayError(qq|
              The bug number <em>$html_id</em> is invalid$alias_specific_message.
              If you are trying to use QuickSearch, you need to enable JavaScript 
              in your browser. To help us fix this limitation, add your comments 
              to <a href="http://bugzilla.mozilla.org/show_bug.cgi?id=70907">bug 
              70907</a>.
            |);
            exit;
        }
    }
    
    # Modify the calling code's original variable to contain the trimmed,
    # converted-from-alias ID.
    $_[0] = $id;
    
292 293 294 295 296
    # Get the values of the usergroupset and userid global variables
    # and write them to local variables for use within this function,
    # setting those local variables to the default value of zero if
    # the global variables are undefined.

297 298
    # First check that the bug exists
    SendSQL("SELECT bug_id FROM bugs WHERE bug_id = $id");
299

300 301 302
    FetchOneColumn()
      || DisplayError("Bug #$id does not exist.")
        && exit;
303

304 305
    return if $skip_authorization;
    
306
    return if CanSeeBug($id, $::userid, $::usergroupset);
307 308 309 310

    # The user did not pass any of the authorization tests, which means they
    # are not authorized to see the bug.  Display an error and stop execution.
    # The error the user sees depends on whether or not they are logged in
311 312
    # (i.e. $::userid contains the user's positive integer ID).
    if ($::userid) {
313 314 315 316
        DisplayError("You are not authorized to access bug #$id.");
    } else {
        DisplayError(
          qq|You are not authorized to access bug #$id.  To see this bug, you
317
          must first <a href="show_bug.cgi?id=$id&amp;GoAheadAndLogIn=1">log in 
318 319 320 321 322
          to an account</a> with the appropriate permissions.|
        );
    }
    exit;

323 324
}

325 326 327 328 329 330 331 332 333 334 335
sub ValidateComment {
    # Make sure a comment is not too large (greater than 64K).
    
    my ($comment) = @_;
    
    if (defined($comment) && length($comment) > 65535) {
        DisplayError("Comments cannot be longer than 65,535 characters.");
        exit;
    }
}

336
# Adds <link> elements for bug lists. These can be inserted into the header by
337 338
# using the "header_html" parameter to PutHeader, which inserts an arbitrary
# string into the header. This function is currently used only in
339
# template/en/default/bug/edit.html.tmpl.
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
sub navigation_links($) {
    my ($buglist) = @_;
    
    my $retval = "";
    
    # We need to be able to pass in a buglist because when you sort on a column
    # the bugs in the cookie you are given will still be in the old order.
    # If a buglist isn't passed, we just use the cookie.
    $buglist ||= $::COOKIE{"BUGLIST"};
    
    if (defined $buglist && $buglist ne "") {
    my @bugs = split(/:/, $buglist);
        
        if (defined $::FORM{'id'}) {
            # We are on an individual bug
            my $cur = lsearch(\@bugs, $::FORM{"id"});

            if ($cur > 0) {
358 359
                $retval .= "<link rel=\"First\" href=\"show_bug.cgi?id=$bugs[0]\">\n";
                $retval .= "<link rel=\"Prev\" href=\"show_bug.cgi?id=$bugs[$cur - 1]\">\n";
360 361
            } 
            if ($cur < $#bugs) {
362 363
                $retval .= "<link rel=\"Next\" href=\"show_bug.cgi?id=$bugs[$cur + 1]\">\n";
                $retval .= "<link rel=\"Last\" href=\"show_bug.cgi?id=$bugs[$#bugs]\">\n";
364 365
            }

366 367
            $retval .= "<link rel=\"Up\" href=\"buglist.cgi?regetlastlist=1\">\n";
            $retval .= "<link rel=\"Contents\" href=\"buglist.cgi?regetlastlist=1\">\n";
368 369
        } else {
            # We are on a bug list
370 371 372
            $retval .= "<link rel=\"First\" href=\"show_bug.cgi?id=$bugs[0]\">\n";
            $retval .= "<link rel=\"Next\" href=\"show_bug.cgi?id=$bugs[0]\">\n";
            $retval .= "<link rel=\"Last\" href=\"show_bug.cgi?id=$bugs[$#bugs]\">\n";
373 374 375 376 377 378
        }
    }
    
    return $retval;
} 

379 380
$::CheckOptionValues = 1;

381
# This sub is still used in reports.cgi.
382 383 384 385 386
sub make_options {
    my ($src,$default,$isregexp) = (@_);
    my $last = "";
    my $popup = "";
    my $found = 0;
387
    $default = "" if !defined $default;
388 389 390 391 392 393 394 395 396

    if ($src) {
        foreach my $item (@$src) {
            if ($item eq "-blank-" || $item ne $last) {
                if ($item eq "-blank-") {
                    $item = "";
                }
                $last = $item;
                if ($isregexp ? $item =~ $default : $default eq $item) {
397
                    $popup .= "<OPTION SELECTED VALUE=\"$item\">$item\n";
398 399
                    $found = 1;
                } else {
400
                    $popup .= "<OPTION VALUE=\"$item\">$item\n";
401
                }
402 403 404 405
            }
        }
    }
    if (!$found && $default ne "") {
406
      if ( $::CheckOptionValues &&
407 408
           ($default ne $::dontchange) && ($default ne "-All-") &&
           ($default ne "DUPLICATE") ) {
409 410 411 412
        print "Possible bug database corruption has been detected.  " .
              "Please send mail to " . Param("maintainer") . " with " .
              "details of what you were doing when this message " . 
              "appeared.  Thank you.\n";
413 414 415 416 417
        if (!$src) {
            $src = ["???null???"];
        }
        print "<pre>src = " . value_quote(join(' ', @$src)) . "\n";
        print "default = " . value_quote($default) . "</pre>";
418
        PutFooter();
terry%mozilla.org's avatar
terry%mozilla.org committed
419
#        confess "Gulp.";
420 421 422
        exit 0;
              
      } else {
423
        $popup .= "<OPTION SELECTED>$default\n";
424
      }
425 426 427 428 429 430 431
    }
    return $popup;
}

sub PasswordForLogin {
    my ($login) = (@_);
    SendSQL("select cryptpassword from profiles where login_name = " .
432
            SqlQuote($login));
433 434 435 436 437
    my $result = FetchOneColumn();
    if (!defined $result) {
        $result = "";
    }
    return $result;
438 439
}

440 441 442
sub quietly_check_login() {
    $::usergroupset = '0';
    my $loginok = 0;
443
    $::disabledreason = '';
444
    $::userid = 0;
445
    if (defined $::COOKIE{"Bugzilla_login"} &&
446
        defined $::COOKIE{"Bugzilla_logincookie"}) {
447 448
        SendSQL("SELECT profiles.userid, profiles.groupset, " .
                "profiles.login_name, " .
449
                "profiles.login_name = " .
450
                SqlQuote($::COOKIE{"Bugzilla_login"}) .
451 452
                " AND logincookies.ipaddr = " .
                SqlQuote($ENV{"REMOTE_ADDR"}) .
453
                ", profiles.disabledtext " .
454 455 456
                " FROM profiles, logincookies WHERE logincookies.cookie = " .
                SqlQuote($::COOKIE{"Bugzilla_logincookie"}) .
                " AND profiles.userid = logincookies.userid");
457 458
        my @row;
        if (@row = FetchSQLData()) {
459
            my ($userid, $groupset, $loginname, $ok, $disabledtext) = (@row);
460 461 462
            if ($ok) {
                if ($disabledtext eq '') {
                    $loginok = 1;
463
                    $::userid = $userid;
464 465 466 467
                    $::usergroupset = $groupset;
                    $::COOKIE{"Bugzilla_login"} = $loginname; # Makes sure case
                                                              # is in
                                                              # canonical form.
468 469
                    # We've just verified that this is ok
                    detaint_natural($::COOKIE{"Bugzilla_logincookie"});
470 471 472
                } else {
                    $::disabledreason = $disabledtext;
                }
473 474 475
            }
        }
    }
476 477 478 479 480
    # if 'who' is passed in, verify that it's a good value
    if ($::FORM{'who'}) {
        my $whoid = DBname_to_id($::FORM{'who'});
        delete $::FORM{'who'} unless $whoid;
    }
481 482 483
    if (!$loginok) {
        delete $::COOKIE{"Bugzilla_login"};
    }
484 485 486
                    
    $vars->{'user'} = GetUserInfo($::userid);
    
487 488 489
    return $loginok;
}

490 491 492 493 494 495 496 497 498 499 500 501 502
# Populate a hash with information about this user. 
sub GetUserInfo {
    my ($userid) = (@_);
    my %user;
    my @queries;
    my %groups;
    
    # No info if not logged in
    return \%user if ($userid == 0);
    
    $user{'login'} = $::COOKIE{"Bugzilla_login"};
    $user{'userid'} = $userid;
    
503 504 505 506
    SendSQL("SELECT mybugslink, realname, groupset, blessgroupset " . 
            "FROM profiles WHERE userid = $userid");
    ($user{'showmybugslink'}, $user{'realname'}, $user{'groupset'},
                                       $user{'blessgroupset'}) = FetchSQLData();
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529

    SendSQL("SELECT name, query, linkinfooter FROM namedqueries " .
            "WHERE userid = $userid");
    while (MoreSQLData()) {
        my %query;
        ($query{'name'}, $query{'query'}, $query{'linkinfooter'}) = 
                                                                 FetchSQLData();
        push(@queries, \%query);    
    }

    $user{'queries'} = \@queries;

    SendSQL("select name, (bit & $user{'groupset'}) != 0 from groups");
    while (MoreSQLData()) {
        my ($name, $bit) = FetchSQLData();    
        $groups{$name} = $bit;
    }

    $user{'groups'} = \%groups;

    return \%user;
}

530 531
sub CheckEmailSyntax {
    my ($addr) = (@_);
532
    my $match = Param('emailregexp');
533
    if ($addr !~ /$match/ || $addr =~ /[\\\(\)<>&,;:"\[\] \t\r\n]/) {
534 535
        $vars->{'addr'} = $addr;
        ThrowUserError("illegal_email_address");
536 537 538
    }
}

539 540 541
sub MailPassword {
    my ($login, $password) = (@_);
    my $urlbase = Param("urlbase");
542 543 544 545 546
    my $template = Param("passwordmail");
    my $msg = PerformSubsts($template,
                            {"mailaddress" => $login . Param('emailsuffix'),
                             "login" => $login,
                             "password" => $password});
547

548
    open SENDMAIL, "|/usr/lib/sendmail -t -i";
549 550 551 552
    print SENDMAIL $msg;
    close SENDMAIL;
}

553 554 555 556 557 558
sub confirm_login {
    my ($nexturl) = (@_);

# Uncommenting the next line can help debugging...
#    print "Content-type: text/plain\n\n";

559 560 561 562 563 564
    # I'm going to reorganize some of this stuff a bit.  Since we're adding
    # a second possible validation method (LDAP), we need to move some of this
    # to a later section.  -Joe Robins, 8/3/00
    my $enteredlogin = "";
    my $realcryptpwd = "";

565 566 567 568 569 570 571 572 573 574 575 576 577
    # If the form contains Bugzilla login and password fields, use Bugzilla's 
    # built-in authentication to authenticate the user (otherwise use LDAP below).
    if (defined $::FORM{"Bugzilla_login"} && defined $::FORM{"Bugzilla_password"}) {
        # Make sure the user's login name is a valid email address.
        $enteredlogin = $::FORM{"Bugzilla_login"};
        CheckEmailSyntax($enteredlogin);

        # Retrieve the user's ID and crypted password from the database.
        my $userid;
        SendSQL("SELECT userid, cryptpassword FROM profiles 
                 WHERE login_name = " . SqlQuote($enteredlogin));
        ($userid, $realcryptpwd) = FetchSQLData();

578 579 580 581 582 583
        # Make sure the user exists or throw an error (but do not admit it was a username
        # error to make it harder for a cracker to find account names by brute force).
        $userid
          || DisplayError("The username or password you entered is not valid.")
          && exit;

584 585 586
        # If this is a new user, generate a password, insert a record
        # into the database, and email their password to them.
        if ( defined $::FORM{"PleaseMailAPassword"} && !$userid ) {
587 588
            # Ensure the new login is valid
            if(!ValidateNewUser($enteredlogin)) {
589
                ThrowUserError("account_exists");
590 591
            }

592 593
            my $password = InsertNewUser($enteredlogin, "");
            MailPassword($enteredlogin, $password);
594 595 596 597 598 599
            
            $vars->{'login'} = $enteredlogin;
            
            print "Content-Type: text/html\n\n";
            $template->process("account/created.html.tmpl", $vars)
              || ThrowTemplateError($template->error());                 
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
        }

        # Otherwise, authenticate the user.
        else {
            # Get the salt from the user's crypted password.
            my $salt = $realcryptpwd;

            # Using the salt, crypt the password the user entered.
            my $enteredCryptedPassword = crypt( $::FORM{"Bugzilla_password"} , $salt );

            # Make sure the passwords match or throw an error.
            ($enteredCryptedPassword eq $realcryptpwd)
              || DisplayError("The username or password you entered is not valid.")
              && exit;

            # If the user has successfully logged in, delete any password tokens
            # lying around in the system for them.
            use Token;
            my $token = Token::HasPasswordToken($userid);
            while ( $token ) {
                Token::Cancel($token, "user logged in");
                $token = Token::HasPasswordToken($userid);
            }
        }
624 625 626 627 628 629

     } elsif (Param("useLDAP") &&
              defined $::FORM{"LDAP_login"} &&
              defined $::FORM{"LDAP_password"}) {
       # If we're using LDAP for login, we've got an entirely different
       # set of things to check.
630 631

# see comment at top of file near eval
632 633
       # First, if we don't have the LDAP modules available to us, we can't
       # do this.
634 635 636 637 638 639 640 641 642
#       if(!$have_ldap) {
#         print "Content-type: text/html\n\n";
#         PutHeader("LDAP not enabled");
#         print "The necessary modules for LDAP login are not installed on ";
#         print "this machine.  Please send mail to ".Param("maintainer");
#         print " and notify him of this problem.\n";
#         PutFooter();
#         exit;
#       }
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676

       # Next, we need to bind anonymously to the LDAP server.  This is
       # because we need to get the Distinguished Name of the user trying
       # to log in.  Some servers (such as iPlanet) allow you to have unique
       # uids spread out over a subtree of an area (such as "People"), so
       # just appending the Base DN to the uid isn't sufficient to get the
       # user's DN.  For servers which don't work this way, there will still
       # be no harm done.
       my $LDAPserver = Param("LDAPserver");
       if ($LDAPserver eq "") {
         print "Content-type: text/html\n\n";
         PutHeader("LDAP server not defined");
         print "The LDAP server for authentication has not been defined.  ";
         print "Please contact ".Param("maintainer")." ";
         print "and notify him of this problem.\n";
         PutFooter();
         exit;
       }

       my $LDAPport = "389";  #default LDAP port
       if($LDAPserver =~ /:/) {
         ($LDAPserver, $LDAPport) = split(":",$LDAPserver);
       }
       my $LDAPconn = new Mozilla::LDAP::Conn($LDAPserver,$LDAPport);
       if(!$LDAPconn) {
         print "Content-type: text/html\n\n";
         PutHeader("Unable to connect to LDAP server");
         print "I was unable to connect to the LDAP server for user ";
         print "authentication.  Please contact ".Param("maintainer");
         print " and notify him of this problem.\n";
         PutFooter();
         exit;
       }

677 678 679 680 681 682 683 684 685 686 687 688 689 690 691
       # if no password was provided, then fail the authentication
       # while it may be valid to not have an LDAP password, when you
       # bind without a password (regardless of the binddn value), you
       # will get an anonymous bind.  I do not know of a way to determine
       # whether a bind is anonymous or not without making changes to the
       # LDAP access control settings
       if ( ! $::FORM{"LDAP_password"} ) {
         print "Content-type: text/html\n\n";
         PutHeader("Login Failed");
         print "You did not provide a password.\n";
         print "Please click <b>Back</b> and try again.\n";
         PutFooter();
         exit;
       }

692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
       # We've got our anonymous bind;  let's look up this user.
       my $dnEntry = $LDAPconn->search(Param("LDAPBaseDN"),"subtree","uid=".$::FORM{"LDAP_login"});
       if(!$dnEntry) {
         print "Content-type: text/html\n\n";
         PutHeader("Login Failed");
         print "The username or password you entered is not valid.\n";
         print "Please click <b>Back</b> and try again.\n";
         PutFooter();
         exit;
       }

       # Now we get the DN from this search.  Once we've got that, we're
       # done with the anonymous bind, so we close it.
       my $userDN = $dnEntry->getDN;
       $LDAPconn->close;

       # Now we attempt to bind as the specified user.
       $LDAPconn = new Mozilla::LDAP::Conn($LDAPserver,$LDAPport,$userDN,$::FORM{"LDAP_password"});
       if(!$LDAPconn) {
         print "Content-type: text/html\n\n";
         PutHeader("Login Failed");
         print "The username or password you entered is not valid.\n";
         print "Please click <b>Back</b> and try again.\n";
         PutFooter();
         exit;
       }

       # And now we're going to repeat the search, so that we can get the
       # mail attribute for this user.
       my $userEntry = $LDAPconn->search(Param("LDAPBaseDN"),"subtree","uid=".$::FORM{"LDAP_login"});
       if(!$userEntry->exists(Param("LDAPmailattribute"))) {
         print "Content-type: text/html\n\n";
         PutHeader("LDAP authentication error");
         print "I was unable to retrieve the ".Param("LDAPmailattribute");
         print " attribute from the LDAP server.  Please contact ";
         print Param("maintainer")." and notify him of this error.\n";
         PutFooter();
         exit;
       }

       # Mozilla::LDAP::Entry->getValues returns an array for the attribute
       # requested, even if there's only one entry.
       $enteredlogin = ($userEntry->getValues(Param("LDAPmailattribute")))[0];

       # We're going to need the cryptpwd for this user from the database
       # so that we can set the cookie below, even though we're not going
       # to use it for authentication.
       $realcryptpwd = PasswordForLogin($enteredlogin);

       # If we don't get a result, then we've got a user who isn't in
       # Bugzilla's database yet, so we've got to add them.
       if($realcryptpwd eq "") {
         # We'll want the user's name for this.
         my $userRealName = ($userEntry->getValues("displayName"))[0];
         if($userRealName eq "") {
           $userRealName = ($userEntry->getValues("cn"))[0];
         }
         InsertNewUser($enteredlogin, $userRealName);
         $realcryptpwd = PasswordForLogin($enteredlogin);
       }
     } # end LDAP authentication

     # And now, if we've logged in via either method, then we need to set
     # the cookies.
     if($enteredlogin ne "") {
       $::COOKIE{"Bugzilla_login"} = $enteredlogin;
758
       SendSQL("insert into logincookies (userid,ipaddr) values (@{[DBNameToIdAndCheck($enteredlogin)]}, @{[SqlQuote($ENV{'REMOTE_ADDR'})]})");
759 760 761 762
       SendSQL("select LAST_INSERT_ID()");
       my $logincookie = FetchOneColumn();

       $::COOKIE{"Bugzilla_logincookie"} = $logincookie;
763 764 765
       my $cookiepath = Param("cookiepath");
       print "Set-Cookie: Bugzilla_login=$enteredlogin ; path=$cookiepath; expires=Sun, 30-Jun-2029 00:00:00 GMT\n";
       print "Set-Cookie: Bugzilla_logincookie=$logincookie ; path=$cookiepath; expires=Sun, 30-Jun-2029 00:00:00 GMT\n";
766 767
    }

768
    my $loginok = quietly_check_login();
769

770
    if ($loginok != 1) {
771
        if ($::disabledreason) {
772 773 774
            my $cookiepath = Param("cookiepath");
            print "Set-Cookie: Bugzilla_login= ; path=$cookiepath; expires=Sun, 30-Jun-80 00:00:00 GMT
Set-Cookie: Bugzilla_logincookie= ; path=$cookiepath; expires=Sun, 30-Jun-80 00:00:00 GMT
775 776 777
Content-type: text/html

";
778 779
            $vars->{'disabled_reason'} = $::disabledreason;
            ThrowUserError("account_disabled");
780
        }
781
        
782
        if (!defined $nexturl || $nexturl eq "") {
783 784
            # Sets nexturl to be argv0, stripping everything up to and
            # including the last slash (or backslash on Windows).
785 786
            $0 =~ m:([^/\\]*)$:;
            $nexturl = $1;
787
        }
788 789 790 791 792 793 794 795
        
        $vars->{'target'} = $nexturl;
        $vars->{'form'} = \%::FORM;
        
        print "Content-type: text/html\n\n";
        $template->process("account/login.html.tmpl", $vars)
          || ThrowTemplateError($template->error());
                
796 797 798
        # This seems like as good as time as any to get rid of old
        # crufty junk in the logincookies table.  Get rid of any entry
        # that hasn't been used in a month.
799 800 801 802
        if ($::dbwritesallowed) {
            SendSQL("DELETE FROM logincookies " .
                    "WHERE TO_DAYS(NOW()) - TO_DAYS(lastused) > 30");
        }
803 804 805 806 807

        exit;
    }

    # Update the timestamp on our logincookie, so it'll keep on working.
808 809 810 811
    if ($::dbwritesallowed) {
        SendSQL("UPDATE logincookies SET lastused = null " .
                "WHERE cookie = $::COOKIE{'Bugzilla_logincookie'}");
    }
812
    return $::userid;
813 814 815
}

sub PutHeader {
816
    ($vars->{'title'}, $vars->{'h1'}, $vars->{'h2'}) = (@_);
817 818 819
     
    $::template->process("global/header.html.tmpl", $::vars)
      || ThrowTemplateError($::template->error());
820 821
}

822
sub PutFooter {
823 824
    $::template->process("global/footer.html.tmpl", $::vars)
      || ThrowTemplateError($::template->error());
825 826
}

827 828 829 830 831 832 833
###############################################################################
# Error handling
#
# If you are doing incremental output, set $vars->{'header_done'} once you've
# done the header.
###############################################################################

834 835
# DisplayError is deprecated. Use ThrowCodeError, ThrowUserError or 
# ThrowTemplateError instead.
836
sub DisplayError {
837 838 839 840
  ($vars->{'error'}, $vars->{'title'}) = (@_);

  print "Content-type: text/html\n\n" if !$vars->{'header_done'};
  $template->process("global/user-error.html.tmpl", $vars)
841
    || ThrowTemplateError($template->error());   
842 843 844 845 846 847

  return 1;
}

# For "this shouldn't happen"-type places in the code.
# $vars->{'variables'} is a reference to a hash of useful debugging info.
848
sub ThrowCodeError {
849
  ($vars->{'error'}, my $unlock_tables, $vars->{'variables'}) = (@_);
850

851 852
  SendSQL("UNLOCK TABLES") if $unlock_tables;
  
853
  # We may one day log something to file here.
854
  
855 856
  print "Content-type: text/html\n\n" if !$vars->{'header_done'};
  $template->process("global/code-error.html.tmpl", $vars)
857
    || ThrowTemplateError($template->error());
858 859 860
    
  exit;
}
861

862
# For errors made by the user.
863 864 865 866
# The correct use of this function is to pass an error tag, defined in
# user-error.html.tmpl, as the first parameter, and then, optionally,
# undef as the second parameter and $unlock_tables as the third.
# The second parameter will eventually go away.
867
sub ThrowUserError {
868
  ($vars->{'error'}, my $unlock_tables) = (@_);
869

870 871 872 873
  SendSQL("UNLOCK TABLES") if $unlock_tables;
  
  print "Content-type: text/html\n\n" if !$vars->{'header_done'};
  $template->process("global/user-error.html.tmpl", $vars)
874
    || ThrowTemplateError($template->error());
875 876 877
    
  exit;
}
878

879 880 881 882
# This function should only be called if a template->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 on
# a print statement.
883
# The Content-Type will already have been printed.
884
sub ThrowTemplateError {
885 886
    ($vars->{'template_error_msg'}) = (@_);
    $vars->{'error'} = "template_error";
887
    
888 889 890 891
    # 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)) {
        my $maintainer = Param('maintainer');
892
        my $error = html_quote($vars->{'template_error_msg'});
893 894 895 896 897 898 899 900
        my $error2 = html_quote($template->error());
        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>
901
          <script type="text/javascript"> <!--
902 903 904 905 906 907 908
            document.write("<p>URL: " + document.location + "</p>");
          // -->
          </script>
          <p>Template->process() failed twice.<br>
          First error: $error<br>
          Second error: $error2</p>
        </tt>
909
END
910 911
    }
    
912
    exit;  
913 914
}

915 916 917 918 919
sub CheckIfVotedConfirmed {
    my ($id, $who) = (@_);
    SendSQL("SELECT bugs.votes, bugs.bug_status, products.votestoconfirm, " .
            "       bugs.everconfirmed " .
            "FROM bugs, products " .
920
            "WHERE bugs.bug_id = $id AND products.product_id = bugs.product_id");
921 922 923 924 925 926
    my ($votes, $status, $votestoconfirm, $everconfirmed) = (FetchSQLData());
    if ($votes >= $votestoconfirm && $status eq $::unconfirmedstate) {
        SendSQL("UPDATE bugs SET bug_status = 'NEW', everconfirmed = 1 " .
                "WHERE bug_id = $id");
        my $fieldid = GetFieldID("bug_status");
        SendSQL("INSERT INTO bugs_activity " .
927
                "(bug_id,who,bug_when,fieldid,removed,added) VALUES " .
928 929 930 931
                "($id,$who,now(),$fieldid,'$::unconfirmedstate','NEW')");
        if (!$everconfirmed) {
            $fieldid = GetFieldID("everconfirmed");
            SendSQL("INSERT INTO bugs_activity " .
932
                    "(bug_id,who,bug_when,fieldid,removed,added) VALUES " .
933 934
                    "($id,$who,now(),$fieldid,'0','1')");
        }
935
        
936
        AppendComment($id, DBID_to_name($who),
937
                      "*** This bug has been confirmed by popular vote. ***", 0);
938 939 940 941 942 943 944 945 946 947
                      
        $vars->{'type'} = "votes";
        $vars->{'id'} = $id;
        $vars->{'mail'} = "";
        open(PMAIL, "-|") or exec('./processmail', $id);
        $vars->{'mail'} .= $_ while <PMAIL>;
        close(PMAIL);
        
        $template->process("bug/process/results.html.tmpl", $vars)
          || ThrowTemplateError($template->error());
948 949 950 951
    }

}

952
sub GetBugActivity {
953 954
    my ($id, $starttime) = (@_);
    my $datepart = "";
955 956 957

    die "Invalid id: $id" unless $id=~/^\s*\d+\s*$/;

958
    if (defined $starttime) {
959
        $datepart = "and bugs_activity.bug_when > " . SqlQuote($starttime);
960
    }
961
    
962
    my $query = "
963 964
        SELECT IFNULL(fielddefs.description, bugs_activity.fieldid),
                bugs_activity.attach_id,
965
                bugs_activity.bug_when,
966
                bugs_activity.removed, bugs_activity.added,
967
                profiles.login_name
968 969 970
        FROM bugs_activity LEFT JOIN fielddefs ON 
                                     bugs_activity.fieldid = fielddefs.fieldid,
             profiles
971 972 973
        WHERE bugs_activity.bug_id = $id $datepart
              AND profiles.userid = bugs_activity.who
        ORDER BY bugs_activity.bug_when";
974 975 976

    SendSQL($query);
    
977 978 979
    my @operations;
    my $operation = {};
    my $changes = [];
980
    my $incomplete_data = 0;
981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
    
    while (my ($field, $attachid, $when, $removed, $added, $who) 
                                                               = FetchSQLData())
    {
        my %change;
        
        # This gets replaced with a hyperlink in the template.
        $field =~ s/^Attachment// if $attachid;

        # Check for the results of an old Bugzilla data corruption bug
        $incomplete_data = 1 if ($added =~ /^\?/ || $removed =~ /^\?/);
        
        # An operation, done by 'who' at time 'when', has a number of
        # 'changes' associated with it.
        # If this is the start of a new operation, store the data from the
        # previous one, and set up the new one.
        if ($operation->{'who'} 
            && ($who ne $operation->{'who'} 
                || $when ne $operation->{'when'})) 
        {
            $operation->{'changes'} = $changes;
            push (@operations, $operation);
            
            # Create new empty anonymous data structures.
            $operation = {};
            $changes = [];
        }  
        
        $operation->{'who'} = $who;
        $operation->{'when'} = $when;            
        
        $change{'field'} = $field;
        $change{'attachid'} = $attachid;
        $change{'removed'} = $removed;
        $change{'added'} = $added;
        push (@$changes, \%change);
1017
    }
1018 1019 1020 1021
    
    if ($operation->{'who'}) {
        $operation->{'changes'} = $changes;
        push (@operations, $operation);
1022
    }
1023 1024
    
    return(\@operations, $incomplete_data);
1025 1026
}

1027

1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
############# Live code below here (that is, not subroutine defs) #############

$| = 1;

# Uncommenting this next line can help debugging.
# print "Content-type: text/html\n\nHello mom\n";

# foreach my $k (sort(keys %ENV)) {
#     print "$k $ENV{$k}<br>\n";
# }

if (defined $ENV{"REQUEST_METHOD"}) {
    if ($ENV{"REQUEST_METHOD"} eq "GET") {
        if (defined $ENV{"QUERY_STRING"}) {
            $::buffer = $ENV{"QUERY_STRING"};
        } else {
            $::buffer = "";
        }
1046
        ProcessFormFields $::buffer;
1047
    } else {
1048
        if (exists($ENV{"CONTENT_TYPE"}) && $ENV{"CONTENT_TYPE"} =~
1049 1050 1051 1052 1053 1054 1055 1056
            m@multipart/form-data; boundary=\s*([^; ]+)@) {
            ProcessMultipartFormFields($1);
            $::buffer = "";
        } else {
            read STDIN, $::buffer, $ENV{"CONTENT_LENGTH"} ||
                die "Couldn't get form data";
            ProcessFormFields $::buffer;
        }
1057 1058 1059 1060
    }
}

if (defined $ENV{"HTTP_COOKIE"}) {
1061 1062
    # Don't trust anything which came in as a cookie
    use re 'taint';
1063
    foreach my $pair (split(/;/, $ENV{"HTTP_COOKIE"})) {
1064 1065 1066 1067 1068 1069
        $pair = trim($pair);
        if ($pair =~ /^([^=]*)=(.*)$/) {
            $::COOKIE{$1} = $2;
        } else {
            $::COOKIE{$pair} = "";
        }
1070 1071 1072 1073
    }
}

1;