Util.pm 37.8 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 9

package Bugzilla::Util;

10
use 5.10.1;
11
use strict;
12

13
use parent qw(Exporter);
14
@Bugzilla::Util::EXPORT = qw(trick_taint detaint_natural detaint_signed
15
                             html_quote url_quote xml_quote
16
                             css_class_quote html_light_quote
17 18
                             i_am_cgi i_am_webservice correct_urlbase remote_ip
                             validate_ip do_ssl_redirect_if_required use_attachbase
19
                             diff_arrays on_main_db
20
                             trim wrap_hard wrap_comment find_wrap_point
21
                             format_time validate_date validate_time datetime_from
22
                             is_7bit_clean bz_crypt generate_random_password
23
                             validate_email_syntax check_email_syntax clean_text
24
                             get_text template_var display_value disable_utf8
25 26
                             detect_encoding email_filter
                             join_activity_entries);
27

28
use Bugzilla::Constants;
29
use Bugzilla::RNG qw(irand);
30
use Bugzilla::Error;
31

32 33
use Date::Parse;
use Date::Format;
34
use Digest;
35
use Email::Address;
36
use List::Util qw(first);
37
use Scalar::Util qw(tainted blessed);
38
use Text::Wrap;
39 40
use Encode qw(encode decode resolve_alias);
use Encode::Guess;
41 42

sub trick_taint {
43 44
    require Carp;
    Carp::confess("Undef to trick_taint") unless defined $_[0];
45 46
    my $match = $_[0] =~ /^(.*)$/s;
    $_[0] = $match ? $1 : undef;
47 48 49 50
    return (defined($_[0]));
}

sub detaint_natural {
51
    my $match = $_[0] =~ /^(\d+)$/;
52
    $_[0] = $match ? int($1) : undef;
53 54 55
    return (defined($_[0]));
}

56
sub detaint_signed {
57
    my $match = $_[0] =~ /^([-+]?\d+)$/;
58 59
    # The "int()" call removes any leading plus sign.
    $_[0] = $match ? int($1) : undef;
60 61 62
    return (defined($_[0]));
}

63 64 65
# Bug 120030: Override html filter to obscure the '@' in user
#             visible strings.
# Bug 319331: Handle BiDi disruptions.
66
sub html_quote {
67 68 69 70 71
    my $var = shift;
    $var =~ s/&/&/g;
    $var =~ s/</&lt;/g;
    $var =~ s/>/&gt;/g;
    $var =~ s/"/&quot;/g;
72 73
    # Obscure '@'.
    $var =~ s/\@/\&#64;/g;
74 75 76 77

    state $use_utf8 = Bugzilla->params->{'utf8'};

    if ($use_utf8) {
78 79 80 81
        # Remove control characters if the encoding is utf8.
        # Other multibyte encodings may be using this range; so ignore if not utf8.
        $var =~ s/(?![\t\r\n])[[:cntrl:]]//g;

82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
        # Remove the following characters because they're
        # influencing BiDi:
        # --------------------------------------------------------
        # |Code  |Name                      |UTF-8 representation|
        # |------|--------------------------|--------------------|
        # |U+202a|Left-To-Right Embedding   |0xe2 0x80 0xaa      |
        # |U+202b|Right-To-Left Embedding   |0xe2 0x80 0xab      |
        # |U+202c|Pop Directional Formatting|0xe2 0x80 0xac      |
        # |U+202d|Left-To-Right Override    |0xe2 0x80 0xad      |
        # |U+202e|Right-To-Left Override    |0xe2 0x80 0xae      |
        # --------------------------------------------------------
        #
        # The following are characters influencing BiDi, too, but
        # they can be spared from filtering because they don't
        # influence more than one character right or left:
        # --------------------------------------------------------
        # |Code  |Name                      |UTF-8 representation|
        # |------|--------------------------|--------------------|
        # |U+200e|Left-To-Right Mark        |0xe2 0x80 0x8e      |
        # |U+200f|Right-To-Left Mark        |0xe2 0x80 0x8f      |
        # --------------------------------------------------------
103
        $var =~ tr/\x{202a}-\x{202e}//d;
104
    }
105 106 107
    return $var;
}

108 109
sub html_light_quote {
    my ($text) = @_;
110 111 112
    # admin/table.html.tmpl calls |FILTER html_light| many times.
    # There is no need to recreate the HTML::Scrubber object again and again.
    my $scrubber = Bugzilla->process_cache->{html_scrubber};
113 114 115

    # List of allowed HTML elements having no attributes.
    my @allow = qw(b strong em i u p br abbr acronym ins del cite code var
116 117
                   dfn samp kbd big small sub sup tt dd dt dl ul li ol
                   fieldset legend);
118

119
    if (!Bugzilla->feature('html_desc')) {
120 121 122 123 124 125 126 127 128 129 130 131 132 133
        my $safe = join('|', @allow);
        my $chr = chr(1);

        # First, escape safe elements.
        $text =~ s#<($safe)>#$chr$1$chr#go;
        $text =~ s#</($safe)>#$chr/$1$chr#go;
        # Now filter < and >.
        $text =~ s#<#&lt;#g;
        $text =~ s#>#&gt;#g;
        # Restore safe elements.
        $text =~ s#$chr/($safe)$chr#</$1>#go;
        $text =~ s#$chr($safe)$chr#<$1>#go;
        return $text;
    }
134
    elsif (!$scrubber) {
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
        # We can be less restrictive. We can accept elements with attributes.
        push(@allow, qw(a blockquote q span));

        # Allowed protocols.
        my $safe_protocols = join('|', SAFE_PROTOCOLS);
        my $protocol_regexp = qr{(^(?:$safe_protocols):|^[^:]+$)}i;

        # Deny all elements and attributes unless explicitly authorized.
        my @default = (0 => {
                             id    => 1,
                             name  => 1,
                             class => 1,
                             '*'   => 0, # Reject all other attributes.
                            }
                       );

        # Specific rules for allowed elements. If no specific rule is set
        # for a given element, then the default is used.
        my @rules = (a => {
154 155 156 157 158 159 160
                           href   => $protocol_regexp,
                           target => qr{^(?:_blank|_parent|_self|_top)$}i,
                           title  => 1,
                           id     => 1,
                           name   => 1,
                           class  => 1,
                           '*'    => 0, # Reject all other attributes.
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
                          },
                     blockquote => {
                                    cite => $protocol_regexp,
                                    id    => 1,
                                    name  => 1,
                                    class => 1,
                                    '*'  => 0, # Reject all other attributes.
                                   },
                     'q' => {
                             cite => $protocol_regexp,
                             id    => 1,
                             name  => 1,
                             class => 1,
                             '*'  => 0, # Reject all other attributes.
                          },
                    );

178 179 180 181 182 183
        Bugzilla->process_cache->{html_scrubber} = $scrubber =
          HTML::Scrubber->new(default => \@default,
                              allow   => \@allow,
                              rules   => \@rules,
                              comment => 0,
                              process => 0);
184
    }
185
    return $scrubber->scrub($text);
186 187
}

188 189 190 191 192 193 194 195 196 197 198 199 200 201
sub email_filter {
    my ($toencode) = @_;
    if (!Bugzilla->user->id) {
        my @emails = Email::Address->parse($toencode);
        if (scalar @emails) {
            my @hosts = map { quotemeta($_->host) } @emails;
            my $hosts_re = join('|', @hosts);
            $toencode =~ s/\@(?:$hosts_re)//g;
            return $toencode;
        }
    }
    return $toencode;
}

202
# This originally came from CGI.pm, by Lincoln D. Stein
203 204
sub url_quote {
    my ($toencode) = (@_);
205 206
    utf8::encode($toencode) # The below regex works only on bytes
        if Bugzilla->params->{'utf8'} && utf8::is_utf8($toencode);
207 208 209 210
    $toencode =~ s/([^a-zA-Z0-9_\-.])/uc sprintf("%%%02x",ord($1))/eg;
    return $toencode;
}

211 212
sub css_class_quote {
    my ($toencode) = (@_);
213
    $toencode =~ s#[ /]#_#g;
214 215 216 217
    $toencode =~ s/([^a-zA-Z0-9_\-.])/uc sprintf("&#x%x;",ord($1))/eg;
    return $toencode;
}

218 219 220 221 222 223 224
sub xml_quote {
    my ($var) = (@_);
    $var =~ s/\&/\&amp;/g;
    $var =~ s/</\&lt;/g;
    $var =~ s/>/\&gt;/g;
    $var =~ s/\"/\&quot;/g;
    $var =~ s/\'/\&apos;/g;
225 226 227 228 229 230 231
    
    # the following nukes characters disallowed by the XML 1.0
    # spec, Production 2.2. 1.0 declares that only the following 
    # are valid:
    # (#x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF])
    $var =~ s/([\x{0001}-\x{0008}]|
               [\x{000B}-\x{000C}]|
232
               [\x{000E}-\x{001F}]|
233 234
               [\x{D800}-\x{DFFF}]|
               [\x{FFFE}-\x{FFFF}])//gx;
235 236 237
    return $var;
}

238
sub i_am_cgi {
239 240 241 242 243
    # I use SERVER_SOFTWARE because it's required to be
    # defined for all requests in the CGI spec.
    return exists $ENV{'SERVER_SOFTWARE'} ? 1 : 0;
}

244 245 246 247 248 249 250
sub i_am_webservice {
    my $usage_mode = Bugzilla->usage_mode;
    return $usage_mode == USAGE_MODE_XMLRPC
           || $usage_mode == USAGE_MODE_JSON
           || $usage_mode == USAGE_MODE_REST;
}

251 252 253 254 255 256
# This exists as a separate function from Bugzilla::CGI::redirect_to_https
# because we don't want to create a CGI object during XML-RPC calls
# (doing so can mess up XML-RPC).
sub do_ssl_redirect_if_required {
    return if !i_am_cgi();
    return if !Bugzilla->params->{'ssl_redirect'};
257

258 259 260 261 262 263 264
    my $sslbase = Bugzilla->params->{'sslbase'};
    
    # If we're already running under SSL, never redirect.
    return if uc($ENV{HTTPS} || '') eq 'ON';
    # Never redirect if there isn't an sslbase.
    return if !$sslbase;
    Bugzilla->cgi->redirect_to_https();
265 266
}

267
sub correct_urlbase {
268 269
    my $ssl = Bugzilla->params->{'ssl_redirect'};
    my $urlbase = Bugzilla->params->{'urlbase'};
270 271
    my $sslbase = Bugzilla->params->{'sslbase'};

272 273 274 275 276 277 278 279 280 281
    if (!$sslbase) {
        return $urlbase;
    }
    elsif ($ssl) {
        return $sslbase;
    }
    else {
        # Return what the user currently uses.
        return (uc($ENV{HTTPS} || '') eq 'ON') ? $sslbase : $urlbase;
    }
282 283
}

284 285 286
sub remote_ip {
    my $ip = $ENV{'REMOTE_ADDR'} || '127.0.0.1';
    my @proxies = split(/[\s,]+/, Bugzilla->params->{'inbound_proxies'});
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303

    # If the IP address is one of our trusted proxies, then we look at
    # the X-Forwarded-For header to determine the real remote IP address.
    if ($ENV{'HTTP_X_FORWARDED_FOR'} && first { $_ eq $ip } @proxies) {
        my @ips = split(/[\s,]+/, $ENV{'HTTP_X_FORWARDED_FOR'});
        # This header can contain several IP addresses. We want the
        # IP address of the machine which connected to our proxies as
        # all other IP addresses may be fake or internal ones.
        # Note that this may block a whole external proxy, but we have
        # no way to determine if this proxy is malicious or trustable.
        foreach my $remote_ip (reverse @ips) {
            if (!first { $_ eq $remote_ip } @proxies) {
                # Keep the original IP address if the remote IP is invalid.
                $ip = validate_ip($remote_ip) || $ip;
                last;
            }
        }
304 305 306 307
    }
    return $ip;
}

308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
sub validate_ip {
    my $ip = shift;
    return is_ipv4($ip) || is_ipv6($ip);
}

# Copied from Data::Validate::IP::is_ipv4().
sub is_ipv4 {
    my $ip = shift;
    return unless defined $ip;

    my @octets = $ip =~ /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
    return unless scalar(@octets) == 4;

    foreach my $octet (@octets) {
        return unless ($octet >= 0 && $octet <= 255 && $octet !~ /^0\d{1,2}$/);
    }

    # The IP address is valid and can now be detainted.
    return join('.', @octets);
}

# Copied from Data::Validate::IP::is_ipv6().
sub is_ipv6 {
    my $ip = shift;
    return unless defined $ip;

    # If there is a :: then there must be only one :: and the length
    # can be variable. Without it, the length must be 8 groups.
    my @chunks = split(':', $ip);

    # Need to check if the last chunk is an IPv4 address, if it is we
    # pop it off and exempt it from the normal IPv6 checking and stick
    # it back on at the end. If there is only one chunk and it's an IPv4
    # address, then it isn't an IPv6 address.
    my $ipv4;
    my $expected_chunks = 8;
    if (@chunks > 1 && is_ipv4($chunks[$#chunks])) {
        $ipv4 = pop(@chunks);
        $expected_chunks--;
    }

    my $empty = 0;
    # Workaround to handle trailing :: being valid.
    if ($ip =~ /[0-9a-f]{1,4}::$/) {
        $empty++;
    # Single trailing ':' is invalid.
    } elsif ($ip =~ /:$/) {
        return;
    }

    foreach my $chunk (@chunks) {
        return unless $chunk =~ /^[0-9a-f]{0,4}$/i;
        $empty++ if $chunk eq '';
    }
    # More than one :: block is bad, but if it starts with :: it will
    # look like two, so we need an exception.
    if ($empty == 2 && $ip =~ /^::/) {
        # This is ok
    } elsif ($empty > 1) {
        return;
    }

    push(@chunks, $ipv4) if $ipv4;
    # Need 8 chunks, or we need an empty section that could be filled
    # to represent the missing '0' sections.
    return unless (@chunks == $expected_chunks || @chunks < $expected_chunks && $empty);

    my $ipv6 = join(':', @chunks);
    # The IP address is valid and can now be detainted.
    trick_taint($ipv6);

    # Need to handle the exception of trailing :: being valid.
    return "${ipv6}::" if $ip =~ /::$/;
    return $ipv6;
}

384 385 386 387 388 389 390
sub use_attachbase {
    my $attachbase = Bugzilla->params->{'attachment_base'};
    return ($attachbase ne ''
            && $attachbase ne Bugzilla->params->{'urlbase'}
            && $attachbase ne Bugzilla->params->{'sslbase'}) ? 1 : 0;
}

391
sub diff_arrays {
392 393
    my ($old_ref, $new_ref, $attrib) = @_;
    $attrib ||= 'name';
394

395 396 397 398 399 400 401 402 403 404 405 406 407 408
    my (%counts, %pos);
    # We are going to alter the old array.
    my @old = @$old_ref;
    my $i = 0;

    # $counts{foo}-- means old, $counts{foo}++ means new.
    # If $counts{foo} becomes positive, then we are adding new items,
    # else we simply cancel one old existing item. Remaining items
    # in the old list have been removed.
    foreach (@old) {
        next unless defined $_;
        my $value = blessed($_) ? $_->$attrib : $_;
        $counts{$value}--;
        push @{$pos{$value}}, $i++;
409
    }
410
    my @added;
411 412 413 414 415 416 417 418 419 420 421 422 423
    foreach (@$new_ref) {
        next unless defined $_;
        my $value = blessed($_) ? $_->$attrib : $_;
        if (++$counts{$value} > 0) {
            # Ignore empty strings, but objects having an empty string
            # as attribute are fine.
            push(@added, $_) unless ($value eq '' && !blessed($_));
        }
        else {
            my $old_pos = shift @{$pos{$value}};
            $old[$old_pos] = undef;
        }
    }
424
    # Ignore canceled items as well as empty strings.
425
    my @removed = grep { defined $_ && $_ ne '' } @old;
426 427 428
    return (\@removed, \@added);
}

429 430
sub trim {
    my ($str) = @_;
431 432 433 434
    if ($str) {
      $str =~ s/^\s+//g;
      $str =~ s/\s+$//g;
    }
435 436 437
    return $str;
}

438
sub wrap_comment {
439
    my ($comment, $cols) = @_;
440 441 442
    my $wrappedcomment = "";

    # Use 'local', as recommended by Text::Wrap's perldoc.
443
    local $Text::Wrap::columns = $cols || COMMENT_COLS;
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
    # Make words that are longer than COMMENT_COLS not wrap.
    local $Text::Wrap::huge    = 'overflow';
    # Don't mess with tabs.
    local $Text::Wrap::unexpand = 0;

    # If the line starts with ">", don't wrap it. Otherwise, wrap.
    foreach my $line (split(/\r\n|\r|\n/, $comment)) {
      if ($line =~ qr/^>/) {
        $wrappedcomment .= ($line . "\n");
      }
      else {
        $wrappedcomment .= (wrap('', '', $line) . "\n");
      }
    }

459
    chomp($wrappedcomment); # Text::Wrap adds an extra newline at the end.
460
    return $wrappedcomment;
461 462
}

463
sub find_wrap_point {
464 465 466 467
    my ($string, $maxpos) = @_;
    if (!$string) { return 0 }
    if (length($string) < $maxpos) { return length($string) }
    my $wrappoint = rindex($string, ",", $maxpos); # look for comma
468
    if ($wrappoint <= 0) {  # can't find comma
469
        $wrappoint = rindex($string, " ", $maxpos); # look for space
470
        if ($wrappoint <= 0) {  # can't find space
471
            $wrappoint = rindex($string, "-", $maxpos); # look for hyphen
472
            if ($wrappoint <= 0) {  # can't find hyphen
473 474 475 476 477 478 479 480 481
                $wrappoint = $maxpos;  # just truncate it
            } else {
                $wrappoint++; # leave hyphen on the left side
            }
        }
    }
    return $wrappoint;
}

482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
sub join_activity_entries {
    my ($field, $current_change, $new_change) = @_;
    # We need to insert characters as these were removed by old
    # LogActivityEntry code.

    return $new_change if $current_change eq '';

    # Buglists and see_also need the comma restored
    if ($field eq 'dependson' || $field eq 'blocked' || $field eq 'see_also') {
        if (substr($new_change, 0, 1) eq ',' || substr($new_change, 0, 1) eq ' ') {
            return $current_change . $new_change;
        } else {
            return $current_change . ', ' . $new_change;
        }
    }

    # Assume bug_file_loc contain a single url, don't insert a delimiter
    if ($field eq 'bug_file_loc') {
        return $current_change . $new_change;
    }

503 504 505
    # All other fields get a space unless the first character of the second
    # string is a comma or space
    if (substr($new_change, 0, 1) eq ',' || substr($new_change, 0, 1) eq ' ') {
506 507 508 509 510 511
        return $current_change . $new_change;
    } else {
        return $current_change . ' ' . $new_change;
    }
}

512 513 514 515 516 517 518 519 520 521 522
sub wrap_hard {
    my ($string, $columns) = @_;
    local $Text::Wrap::columns = $columns;
    local $Text::Wrap::unexpand = 0;
    local $Text::Wrap::huge = 'wrap';
    
    my $wrapped = wrap('', '', $string);
    chomp($wrapped);
    return $wrapped;
}

523
sub format_time {
524
    my ($date, $format, $timezone) = @_;
525

526 527
    # If $format is not set, try to guess the correct date format.
    if (!$format) {
528 529 530
        if (!ref $date
            && $date =~ /^(\d{4})[-\.](\d{2})[-\.](\d{2}) (\d{2}):(\d{2})(:(\d{2}))?$/) 
        {
531 532
            my $sec = $7;
            if (defined $sec) {
533
                $format = "%Y-%m-%d %T %Z";
534
            } else {
535
                $format = "%Y-%m-%d %R %Z";
536 537
            }
        } else {
538 539
            # Default date format. See DateTime for other formats available.
            $format = "%Y-%m-%d %R %Z";
540
        }
541
    }
542

543 544 545 546 547 548 549 550
    my $dt = ref $date ? $date : datetime_from($date, $timezone);
    $date = defined $dt ? $dt->strftime($format) : '';
    return trim($date);
}

sub datetime_from {
    my ($date, $timezone) = @_;

551 552 553
    # In the database, this is the "0" date.
    return undef if $date =~ /^0000/;

554 555
    # strptime($date) returns an empty array if $date has an invalid
    # date format.
556 557
    my @time = strptime($date);

558
    unless (scalar @time) {
559 560 561
        # If an unknown timezone is passed (such as MSK, for Moskow),
        # strptime() is unable to parse the date. We try again, but we first
        # remove the timezone.
562 563 564 565
        $date =~ s/\s+\S+$//;
        @time = strptime($date);
    }

566 567 568 569
    return undef if !@time;

    # strptime() counts years from 1900, and months from 0 (January).
    # We have to fix both values.
570
    my %args = (
571 572 573 574 575 576 577
        year   => $time[5] + 1900,
        month  => $time[4] + 1,
        day    => $time[3],
        hour   => $time[2],
        minute => $time[1],
        # DateTime doesn't like fractional seconds.
        # Also, sometimes seconds are undef.
578
        second => defined($time[0]) ? int($time[0]) : undef,
579 580 581 582
        # If a timezone was specified, use it. Otherwise, use the
        # local timezone.
        time_zone => Bugzilla->local_timezone->offset_as_string($time[6]) 
                     || Bugzilla->local_timezone,
583 584 585 586 587 588 589 590 591
    );

    # If something wasn't specified in the date, it's best to just not
    # pass it to DateTime at all. (This is important for doing datetime_from
    # on the deadline field, which is usually just a date with no time.)
    foreach my $arg (keys %args) {
        delete $args{$arg} if !defined $args{$arg};
    }

592 593 594
    # This module takes time to load and is only used here, so we
    # |require| it here rather than |use| it.
    require DateTime;
595
    my $dt = new DateTime(\%args);
596 597 598 599 600

    # Now display the date using the given timezone,
    # or the user's timezone if none is given.
    $dt->set_time_zone($timezone || Bugzilla->user->timezone);
    return $dt;
601 602
}

603
sub bz_crypt {
604 605
    my ($password, $salt) = @_;

606
    my $algorithm;
607
    if (!defined $salt) {
608 609 610 611 612 613 614 615
        # If you don't use a salt, then people can create tables of
        # hashes that map to particular passwords, and then break your
        # hashing very easily if they have a large-enough table of common
        # (or even uncommon) passwords. So we generate a unique salt for
        # each password in the database, and then just prepend it to
        # the hash.
        $salt = generate_random_password(PASSWORD_SALT_LENGTH);
        $algorithm = PASSWORD_DIGEST_ALGORITHM;
616 617
    }

618 619 620 621 622 623 624
    # We append the algorithm used to the string. This is good because then
    # we can change the algorithm being used, in the future, without 
    # disrupting the validation of existing passwords. Also, this tells
    # us if a password is using the old "crypt" method of hashing passwords,
    # because the algorithm will be missing from the string.
    if ($salt =~ /{([^}]+)}$/) {
        $algorithm = $1;
625
    }
626

627 628 629 630 631
    # Wide characters cause crypt and Digest to die.
    if (Bugzilla->params->{'utf8'}) {
        utf8::encode($password) if utf8::is_utf8($password);
    }

632 633 634 635 636 637 638
    my $crypted_password;
    if (!$algorithm) {
        # Crypt the password.
        $crypted_password = crypt($password, $salt);
    }
    else {
        my $hasher = Digest->new($algorithm);
639 640
        # Newly created salts won't yet have a comma.
        ($salt) = $salt =~ /^([^,]+),?/;
641
        $hasher->add($password, $salt);
642
        $crypted_password = $salt . ',' . $hasher->b64digest . "{$algorithm}";
643
    }
644

645
    # Return the crypted password.
646
    return $crypted_password;
647 648
}

649 650 651 652 653 654
# If you want to understand the security of strings generated by this
# function, here's a quick formula that will help you estimate:
# We pick from 62 characters, which is close to 64, which is 2^6.
# So 8 characters is (2^6)^8 == 2^48 combinations. Just multiply 6
# by the number of characters you generate, and that gets you the equivalent
# strength of the string in bits.
655 656
sub generate_random_password {
    my $size = shift || 10; # default to 10 chars if nothing specified
657
    return join("", map{ ('0'..'9','a'..'z','A'..'Z')[irand 62] } (1..$size));
658 659
}

660 661
sub validate_email_syntax {
    my ($addr) = @_;
662
    my $match = Bugzilla->params->{'emailregexp'};
663 664 665 666 667 668 669
    my $email = $addr . Bugzilla->params->{'emailsuffix'};
    # This regexp follows RFC 2822 section 3.4.1.
    my $addr_spec = $Email::Address::addr_spec;
    # RFC 2822 section 2.1 specifies that email addresses must
    # be made of US-ASCII characters only.
    # Email::Address::addr_spec doesn't enforce this.
    my $ret = ($addr =~ /$match/ && $email !~ /\P{ASCII}/ && $email =~ /^$addr_spec$/);
670 671 672 673
    if ($ret) {
        # We assume these checks to suffice to consider the address untainted.
        trick_taint($_[0]);
    }
674
    return $ret ? 1 : 0;
675 676
}

677 678 679 680 681 682 683 684 685
sub check_email_syntax {
    my ($addr) = @_;

    unless (validate_email_syntax(@_)) {
        my $email = $addr . Bugzilla->params->{'emailsuffix'};
        ThrowUserError('illegal_email_address', { addr => $email });
    }
}

686 687
sub validate_date {
    my ($date) = @_;
688
    my $date2;
689

690 691 692 693
    # $ts is undefined if the parser fails.
    my $ts = str2time($date);
    if ($ts) {
        $date2 = time2str("%Y-%m-%d", $ts);
694

695 696 697
        $date =~ s/(\d+)-0*(\d+?)-0*(\d+?)/$1-$2-$3/; 
        $date2 =~ s/(\d+)-0*(\d+?)-0*(\d+?)/$1-$2-$3/;
    }
698 699
    my $ret = ($ts && $date eq $date2);
    return $ret ? 1 : 0;
700 701
}

702 703 704 705 706 707 708 709
sub validate_time {
    my ($time) = @_;
    my $time2;

    # $ts is undefined if the parser fails.
    my $ts = str2time($time);
    if ($ts) {
        $time2 = time2str("%H:%M:%S", $ts);
710 711
        if ($time =~ /^(\d{1,2}):(\d\d)(?::(\d\d))?$/) {
            $time = sprintf("%02d:%02d:%02d", $1, $2, $3 || 0);
712
        }
713 714 715 716 717
    }
    my $ret = ($ts && $time eq $time2);
    return $ret ? 1 : 0;
}

718 719 720 721
sub is_7bit_clean {
    return $_[0] !~ /[^\x20-\x7E\x0A\x0D]/;
}

722
sub clean_text {
723 724 725 726 727
    my $dtext = shift;
    if ($dtext) {
        # change control characters into a space
        $dtext =~ s/[\x00-\x1F\x7F]+/ /g;
    }
728
    return trim($dtext);
729 730
}

731 732 733 734 735 736 737 738
sub on_main_db (&) {
    my $code = shift;
    my $original_dbh = Bugzilla->dbh;
    Bugzilla->request_cache->{dbh} = Bugzilla->dbh_main;
    $code->();
    Bugzilla->request_cache->{dbh} = $original_dbh;
}

739 740
sub get_text {
    my ($name, $vars) = @_;
741
    my $template = Bugzilla->template_inner;
742 743 744
    $vars ||= {};
    $vars->{'message'} = $name;
    my $message;
745 746 747
    $template->process('global/message.txt.tmpl', $vars, \$message)
      || ThrowTemplateError($template->error());

748 749 750 751 752
    # Remove the indenting that exists in messages.html.tmpl.
    $message =~ s/^    //gm;
    return $message;
}

753 754
sub template_var {
    my $name = shift;
755 756
    my $request_cache = Bugzilla->request_cache;
    my $cache = $request_cache->{util_template_var} ||= {};
757
    my $lang = $request_cache->{template_current_lang}->[0] || '';
758
    return $cache->{$lang}->{$name} if defined $cache->{$lang};
759 760

    my $template = Bugzilla->template_inner($lang);
761 762 763
    my %vars;
    # Note: If we suddenly start needing a lot of template_var variables,
    # they should move into their own template, not field-descs.
764 765 766 767
    $template->process('global/field-descs.none.tmpl',
                       { vars => \%vars, in_template_var => 1 })
      || ThrowTemplateError($template->error());

768 769 770 771
    $cache->{$lang} = \%vars;
    return $vars{$name};
}

772 773
sub display_value {
    my ($field, $value) = @_;
774
    return template_var('value_descs')->{$field}->{$value} // $value;
775 776
}

777 778
sub disable_utf8 {
    if (Bugzilla->params->{'utf8'}) {
779
        binmode STDOUT, ':bytes'; # Turn off UTF8 encoding.
780 781 782
    }
}

783 784 785 786 787
use constant UTF8_ACCIDENTAL => qw(shiftjis big5-eten euc-kr euc-jp);

sub detect_encoding {
    my $data = shift;

788
    Bugzilla->feature('detect_charset')
789
      || ThrowUserError('feature_disabled', { feature => 'detect_charset' });
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809

    require Encode::Detect::Detector;
    import Encode::Detect::Detector 'detect';

    my $encoding = detect($data);
    $encoding = resolve_alias($encoding) if $encoding;

    # Encode::Detect is bad at detecting certain charsets, but Encode::Guess
    # is better at them. Here's the details:

    # shiftjis, big5-eten, euc-kr, and euc-jp: (Encode::Detect
    # tends to accidentally mis-detect UTF-8 strings as being
    # these encodings.)
    if ($encoding && grep($_ eq $encoding, UTF8_ACCIDENTAL)) {
        $encoding = undef;
        my $decoder = guess_encoding($data, UTF8_ACCIDENTAL);
        $encoding = $decoder->name if ref $decoder;
    }

    # Encode::Detect sometimes mis-detects various ISO encodings as iso-8859-8,
810 811
    # or cp1255, but Encode::Guess can usually tell which one it is.
    if ($encoding && ($encoding eq 'iso-8859-8' || $encoding eq 'cp1255')) {
812 813 814
        my $decoded_as = _guess_iso($data, 'iso-8859-8', 
            # These are ordered this way because it gives the most 
            # accurate results.
815
            qw(cp1252 iso-8859-7 iso-8859-2));
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836
        $encoding = $decoded_as if $decoded_as;
    }

    return $encoding;
}

# A helper for detect_encoding.
sub _guess_iso {
    my ($data, $versus, @isos) = (shift, shift, shift);

    my $encoding;
    foreach my $iso (@isos) {
        my $decoder = guess_encoding($data, ($iso, $versus));
        if (ref $decoder) {
            $encoding = $decoder->name if ref $decoder;
            last;
        }
    }
    return $encoding;
}

837 838 839 840
1;

__END__

841 842 843 844 845 846 847 848 849 850 851
=head1 NAME

Bugzilla::Util - Generic utility functions for bugzilla

=head1 SYNOPSIS

  use Bugzilla::Util;

  # Functions for dealing with variable tainting
  trick_taint($var);
  detaint_natural($var);
852
  detaint_signed($var);
853 854 855

  # Functions for quoting
  html_quote($var);
856
  url_quote($var);
857
  xml_quote($var);
858
  email_filter($var);
859

860
  # Functions that tell you about your environment
861
  my $is_cgi   = i_am_cgi();
862
  my $is_webservice = i_am_webservice();
863
  my $urlbase  = correct_urlbase();
864

865 866 867
  # Data manipulation
  ($removed, $added) = diff_arrays(\@old, \@new);

868
  # Functions for manipulating strings
869
  $val = trim(" abc ");
870
  $wrapped = wrap_comment($comment);
871

872 873
  # Functions for formatting time
  format_time($time);
874
  datetime_from($time, $timezone);
875

876 877
  # Cryptographic Functions
  $crypted_password = bz_crypt($password);
878
  $new_password = generate_random_password($password_length);
879

880
  # Validation Functions
881
  validate_email_syntax($email);
882
  check_email_syntax($email);
883
  validate_date($date);
884

885 886 887 888 889
  # DB-related functions
  on_main_db {
     ... code here ...
  };

890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918
=head1 DESCRIPTION

This package contains various utility functions which do not belong anywhere
else.

B<It is not intended as a general dumping group for something which
people feel might be useful somewhere, someday>. Do not add methods to this
package unless it is intended to be used for a significant number of files,
and it does not belong anywhere else.

=head1 FUNCTIONS

This package provides several types of routines:

=head2 Tainting

Several functions are available to deal with tainted variables. B<Use these
with care> to avoid security holes.

=over 4

=item C<trick_taint($val)>

Tricks perl into untainting a particular variable.

Use trick_taint() when you know that there is no way that the data
in a scalar can be tainted, but taint mode still bails on it.

B<WARNING!! Using this routine on data that really could be tainted defeats
919 920
the purpose of taint mode.  It should only be used on variables that have been
sanity checked in some way and have been determined to be OK.>
921 922 923 924 925 926 927

=item C<detaint_natural($num)>

This routine detaints a natural number. It returns a true value if the
value passed in was a valid natural number, else it returns false. You
B<MUST> check the result of this routine to avoid security holes.

928 929 930 931 932 933
=item C<detaint_signed($num)>

This routine detaints a signed integer. It returns a true value if the
value passed in was a valid signed integer, else it returns false. You
B<MUST> check the result of this routine to avoid security holes.

934 935 936 937 938 939 940 941 942 943 944
=back

=head2 Quoting

Some values may need to be quoted from perl. However, this should in general
be done in the template where possible.

=over 4

=item C<html_quote($val)>

945 946 947
Returns a value quoted for use in HTML, with &, E<lt>, E<gt>, E<34> and @ being
replaced with their appropriate HTML entities.  Also, Unicode BiDi controls are
deleted.
948

949 950 951 952 953 954
=item C<html_light_quote($val)>

Returns a string where only explicitly allowed HTML elements and attributes
are kept. All HTML elements and attributes not being in the whitelist are either
escaped (if HTML::Scrubber is not installed) or removed.

955 956 957 958
=item C<url_quote($val)>

Quotes characters so that they may be included as part of a url.

959 960 961
=item C<css_class_quote($val)>

Quotes characters so that they may be used as CSS class names. Spaces
962
and forward slashes are replaced by underscores.
963

964 965 966 967 968 969
=item C<xml_quote($val)>

This is similar to C<html_quote>, except that ' is escaped to &apos;. This
is kept separate from html_quote partly for compatibility with previous code
(for &apos;) and partly for future handling of non-ASCII characters.

970 971 972 973 974 975
=item C<email_filter>

Removes the hostname from email addresses in the string, if the user
currently viewing Bugzilla is logged out. If the user is logged-in,
this filter just returns the input string.

976 977 978 979 980 981 982 983
=back

=head2 Environment and Location

Functions returning information about your environment or location.

=over 4

984 985 986 987 988 989
=item C<i_am_cgi()>

Tells you whether or not you are being run as a CGI script in a web
server. For example, it would return false if the caller is running
in a command-line script.

990 991 992 993 994
=item C<i_am_webservice()>

Tells you whether or not the current usage mode is WebServices related
such as JSONRPC, XMLRPC, or REST.

995 996 997
=item C<correct_urlbase()>

Returns either the C<sslbase> or C<urlbase> parameter, depending on the
998
current setting for the C<ssl_redirect> parameter.
999

1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
=item C<remote_ip()>

Returns the IP address of the remote client. If Bugzilla is behind
a trusted proxy, it will get the remote IP address by looking at the
X-Forwarded-For header.

=item C<validate_ip($ip)>

Returns the sanitized IP address if it is a valid IPv4 or IPv6 address,
else returns undef.

1011 1012 1013 1014 1015
=item C<use_attachbase()>

Returns true if an alternate host is used to display attachments; false
otherwise.

1016 1017
=back

1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
=head2 Data Manipulation

=over 4

=item C<diff_arrays(\@old, \@new)>

 Description: Takes two arrayrefs, and will tell you what it takes to 
              get from @old to @new.
 Params:      @old = array that you are changing from
              @new = array that you are changing to
 Returns:     A list of two arrayrefs. The first is a reference to an 
              array containing items that were removed from @old. The
              second is a reference to an array containing items
              that were added to @old. If both returned arrays are 
              empty, @old and @new contain the same values.

=back

1036
=head2 String Manipulation
1037 1038 1039 1040 1041 1042 1043 1044

=over 4

=item C<trim($str)>

Removes any leading or trailing whitespace from a string. This routine does not
modify the existing string.

1045 1046 1047 1048 1049
=item C<wrap_hard($string, $size)>

Wraps a string, so that a line is I<never> longer than C<$size>.
Returns the string, wrapped.

1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
=item C<wrap_comment($comment)>

Takes a bug comment, and wraps it to the appropriate length. The length is
currently specified in C<Bugzilla::Constants::COMMENT_COLS>. Lines beginning
with ">" are assumed to be quotes, and they will not be wrapped.

The intended use of this function is to wrap comments that are about to be
displayed or emailed. Generally, wrapped text should not be stored in the
database.

1060 1061 1062 1063 1064 1065
=item C<find_wrap_point($string, $maxpos)>

Search for a comma, a whitespace or a hyphen to split $string, within the first
$maxpos characters. If none of them is found, just split $string at $maxpos.
The search starts at $maxpos and goes back to the beginning of the string.

1066 1067 1068 1069 1070 1071
=item C<join_activity_entries($field, $current_change, $new_change)>

Joins two strings together so they appear as one. The field name is specified
as the method of joining the two strings depends on this. Returns the
combined string.

1072 1073 1074 1075 1076
=item C<is_7bit_clean($str)>

Returns true is the string contains only 7-bit characters (ASCII 32 through 126,
ASCII 10 (LineFeed) and ASCII 13 (Carrage Return).

1077 1078 1079 1080
=item C<disable_utf8()>

Disable utf8 on STDOUT (and display raw data instead).

1081 1082 1083 1084 1085 1086
=item C<detect_encoding($str)>

Guesses what encoding a given data is encoded in, returning the canonical name
of the detected encoding (which may be different from the MIME charset 
specification).

1087 1088 1089 1090
=item C<clean_text($str)>
Returns the parameter "cleaned" by exchanging non-printable characters with spaces.
Specifically characters (ASCII 0 through 31) and (ASCII 127) will become ASCII 32 (Space).

1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
=item C<get_text>

=over

=item B<Description>

This is a method of getting localized strings within Bugzilla code.
Use this when you don't want to display a whole template, you just
want a particular string.

It uses the F<global/message.txt.tmpl> template to return a string.

=item B<Params>

=over

=item C<$message> - The identifier for the message.

=item C<$vars> - A hashref. Any variables you want to pass to the template.

=back

=item B<Returns>

A string.

=back

1119 1120 1121 1122 1123 1124 1125 1126

=item C<template_var>

This is a method of getting the value of a variable from a template in
Perl code. The available variables are in the C<global/field-descs.none.tmpl>
template. Just pass in the name of the variable that you want the value of.


1127 1128
=back

1129 1130 1131 1132 1133 1134
=head2 Formatting Time

=over 4

=item C<format_time($time)>

1135 1136 1137
Takes a time and converts it to the desired format and timezone.
If no format is given, the routine guesses the correct one and returns
an empty array if it cannot. If no timezone is given, the user's timezone
1138
is used, as defined in their preferences.
1139 1140

This routine is mainly called from templates to filter dates, see
1141
"FILTER time" in L<Bugzilla::Template>.
1142

1143 1144 1145 1146 1147 1148 1149 1150 1151
=item C<datetime_from($time, $timezone)>

Returns a DateTime object given a date string. If the string is not in some
valid date format that C<strptime> understands, we return C<undef>.

You can optionally specify a timezone for the returned date. If not
specified, defaults to the currently-logged-in user's timezone, or
the Bugzilla server's local timezone if there isn't a logged-in user.

1152 1153
=back

1154 1155 1156 1157
=head2 Cryptography

=over 4

1158
=item C<bz_crypt($password, $salt)>
1159

1160 1161
Takes a string and returns a hashed (encrypted) value for it, using a
random salt. An optional salt string may also be passed in.
1162

1163 1164 1165
Please always use this function instead of the built-in perl C<crypt>
function, when checking or setting a password. Bugzilla does not use
C<crypt>.
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176

=begin undocumented

Random salts are generated because the alternative is usually
to use the first two characters of the password itself, and since
the salt appears in plaintext at the beginning of the encrypted
password string this has the effect of revealing the first two
characters of the password to anyone who views the encrypted version.

=end undocumented

1177 1178 1179 1180 1181 1182
=item C<generate_random_password($password_length)>

Returns an alphanumeric string with the specified length
(10 characters by default). Use this function to generate passwords
and tokens.

1183
=back
1184 1185 1186 1187 1188

=head2 Validation

=over 4

1189 1190 1191 1192
=item C<validate_email_syntax($email)>

Do a syntax checking for a legal email address and returns 1 if
the check is successful, else returns 0.
1193
Untaints C<$email> if successful.
1194

1195 1196 1197 1198 1199 1200
=item C<check_email_syntax($email)>

Do a syntax checking for a legal email address and throws an error
if the check fails.
Untaints C<$email> if successful.

1201
=item C<validate_date($date)>
1202

1203 1204
Make sure the date has the correct format and returns 1 if
the check is successful, else returns 0.
1205 1206

=back
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222

=head2 Database

=over

=item C<on_main_db>

Runs a block of code always on the main DB. Useful for when you're inside
a subroutine and need to do some writes to the database, but don't know
if Bugzilla is currently using the shadowdb or not. Used like:

 on_main_db {
     my $dbh = Bugzilla->dbh;
     $dbh->do("INSERT ...");
 }

1223
=back
1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239

=head1 B<Methods in need of POD>

=over

=item do_ssl_redirect_if_required

=item validate_time

=item is_ipv4

=item is_ipv6

=item display_value

=back