email_in.pl 20.2 KB
Newer Older
1
#!/usr/bin/perl -T
2 3 4
# 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/.
5
#
6 7
# This Source Code Form is "Incompatible With Secondary Licenses", as
# defined by the Mozilla Public License, v. 2.0.
8

9
use 5.10.1;
10 11 12 13 14
use strict;
use warnings;

# MTAs may call this script from any directory, but it should always
# run from this one so that it can find its modules.
15 16
use Cwd qw(abs_path);
use File::Basename qw(dirname);
17

18
BEGIN {
19 20 21
  # Untaint the abs_path.
  my ($a) = abs_path($0) =~ /^(.*)$/;
  chdir dirname($a);
22
}
23

24 25
use lib qw(. lib);

26 27 28 29 30
use Data::Dumper;
use Email::Address;
use Email::Reply qw(reply);
use Email::MIME;
use Getopt::Long qw(:config bundling);
31
use HTML::FormatText::WithLinks;
32
use Pod::Usage;
33
use Encode;
34
use Scalar::Util qw(blessed);
35
use List::MoreUtils qw(firstidx);
36 37

use Bugzilla;
38
use Bugzilla::Attachment;
39
use Bugzilla::Bug;
40
use Bugzilla::BugMail;
41
use Bugzilla::Constants;
42
use Bugzilla::Error;
43
use Bugzilla::Field;
44
use Bugzilla::Mailer;
45
use Bugzilla::Token;
46 47
use Bugzilla::User;
use Bugzilla::Util;
48
use Bugzilla::Hook;
49 50 51 52 53 54 55 56 57

#############
# Constants #
#############

# This is the USENET standard line for beginning a signature block
# in a message. RFC-compliant mailers use this.
use constant SIGNATURE_DELIMITER => '-- ';

58 59 60
# These MIME types represent a "body" of an email if they have an
# "inline" Content-Disposition (or no content disposition).
use constant BODY_TYPES => qw(
61 62 63 64
  text/plain
  text/html
  application/xhtml+xml
  multipart/alternative
65 66
);

67 68 69 70 71 72 73 74
# $input_email is a global so that it can be used in die_handler.
our ($input_email, %switch);

####################
# Main Subroutines #
####################

sub parse_mail {
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
  my ($mail_text) = @_;
  debug_print('Parsing Email');
  $input_email = Email::MIME->new($mail_text);

  my %fields = %{$switch{'default'} || {}};
  Bugzilla::Hook::process('email_in_before_parse',
    {mail => $input_email, fields => \%fields});

  my $summary = $input_email->header('Subject');
  if ($summary =~ /\[\S+ (\d+)\](.*)/i) {
    $fields{'bug_id'} = $1;
    $summary = trim($2);
  }

  # Ignore automatic replies.
  # XXX - Improve the way to detect such subjects in different languages.
  my $auto_submitted = $input_email->header('Auto-Submitted') || '';
  if ($summary =~ /out of( the)? office/i || $auto_submitted eq 'auto-replied') {
    debug_print("Automatic reply detected: $summary");
    exit;
  }

  my ($body, $attachments) = get_body_and_attachments($input_email);

  debug_print("Body:\n" . $body, 3);

  $body = remove_leading_blank_lines($body);
  my @body_lines = split(/\r?\n/s, $body);

  # If there are fields specified.
  if ($body =~ /^\s*@/s) {
    my $current_field;
    while (my $line = shift @body_lines) {

      # If the sig is starting, we want to keep this in the
      # @body_lines so that we don't keep the sig as part of the
      # comment down below.
      if ($line eq SIGNATURE_DELIMITER) {
        unshift(@body_lines, $line);
        last;
      }

      # Otherwise, we stop parsing fields on the first blank line.
      $line = trim($line);
      last if !$line;
      if ($line =~ /^\@(\w+)\s*(?:=|\s|$)\s*(.*)\s*/) {
        $current_field = lc($1);
        $fields{$current_field} = $2;
      }
      else {
        $fields{$current_field} .= " $line";
      }
127
    }
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
  }

  %fields = %{Bugzilla::Bug::map_fields(\%fields)};

  my ($reporter) = Email::Address->parse($input_email->header('From'));
  $fields{'reporter'} = $reporter->address;

  # The summary line only affects us if we're doing a post_bug.
  # We have to check it down here because there might have been
  # a bug_id specified in the body of the email.
  if (!$fields{'bug_id'} && !$fields{'short_desc'}) {
    $fields{'short_desc'} = $summary;
  }

  # The Importance/X-Priority headers are only used when creating a new bug.
  # 1) If somebody specifies a priority, use it.
  # 2) If there is an Importance or X-Priority header, use it as
  #    something that is relative to the default priority.
  #    If the value is High or 1, increase the priority by 1.
  #    If the value is Low or 5, decrease the priority by 1.
  # 3) Otherwise, use the default priority.
  # Note: this will only work if the 'letsubmitterchoosepriority'
  # parameter is enabled.
  my $importance
    = $input_email->header('Importance') || $input_email->header('X-Priority');
  if (!$fields{'bug_id'} && !$fields{'priority'} && $importance) {
    my @legal_priorities = @{get_legal_field_values('priority')};
    my $i
      = firstidx { $_ eq Bugzilla->params->{'defaultpriority'} } @legal_priorities;
    if ($importance =~ /(high|[12])/i) {
      $i-- unless $i == 0;
159
    }
160 161
    elsif ($importance =~ /(low|[45])/i) {
      $i++ unless $i == $#legal_priorities;
162
    }
163 164
    $fields{'priority'} = $legal_priorities[$i];
  }
165

166
  my $comment = '';
167

168 169 170 171 172 173
  # Get the description, except the signature.
  foreach my $line (@body_lines) {
    last if $line eq SIGNATURE_DELIMITER;
    $comment .= "$line\n";
  }
  $fields{'comment'} = $comment;
174

175 176 177 178
  my %override = %{$switch{'override'} || {}};
  foreach my $key (keys %override) {
    $fields{$key} = $override{$key};
  }
179

180
  debug_print("Parsed Fields:\n" . Dumper(\%fields), 2);
181

182 183 184 185
  debug_print("Attachments:\n" . Dumper($attachments), 3);
  if (@$attachments) {
    $fields{'attachments'} = $attachments;
  }
186

187
  return \%fields;
188 189
}

190
sub check_email_fields {
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
  my ($fields) = @_;

  my ($retval, $non_conclusive_fields) = Bugzilla::User::match_field(
    {
      'assigned_to' => {'type' => 'single'},
      'qa_contact'  => {'type' => 'single'},
      'cc'          => {'type' => 'multi'},
      'newcc'       => {'type' => 'multi'}
    },
    $fields,
    MATCH_SKIP_CONFIRM
  );

  if ($retval != USER_MATCH_SUCCESS) {
    ThrowUserError('user_match_too_many', {fields => $non_conclusive_fields});
  }
207 208 209
}

sub post_bug {
210 211
  my ($fields) = @_;
  debug_print('Posting a new bug...');
212

213
  my $user = Bugzilla->user;
214

215
  check_email_fields($fields);
216

217 218 219
  my $bug = Bugzilla::Bug->create($fields);
  debug_print("Created bug " . $bug->id);
  return ($bug, $bug->comments->[0]);
220 221
}

222
sub process_bug {
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
  my ($fields_in) = @_;
  my %fields = %$fields_in;

  my $bug_id = $fields{'bug_id'};
  $fields{'id'} = $bug_id;
  delete $fields{'bug_id'};

  debug_print("Updating Bug $fields{id}...");

  my $bug = Bugzilla::Bug->check($bug_id);

  if ($fields{'bug_status'}) {
    $fields{'knob'} = $fields{'bug_status'};
  }

  # If no status is given, then we only want to change the resolution.
  elsif ($fields{'resolution'}) {
    $fields{'knob'}                              = 'change_resolution';
    $fields{'resolution_knob_change_resolution'} = $fields{'resolution'};
  }
  if ($fields{'dup_id'}) {
    $fields{'knob'} = 'duplicate';
  }

  # Move @cc to @newcc as @cc is used by process_bug.cgi to remove
  # users from the CC list when @removecc is set.
  $fields{'newcc'} = delete $fields{'cc'} if $fields{'cc'};

  # Make it possible to remove CCs.
  if ($fields{'removecc'}) {
    $fields{'cc'} = [split(',', $fields{'removecc'})];
    $fields{'removecc'} = 1;
  }

  check_email_fields(\%fields);

  my $cgi = Bugzilla->cgi;
  foreach my $field (keys %fields) {
    $cgi->param(-name => $field, -value => $fields{$field});
  }
  $cgi->param('token', issue_hash_token([$bug->id, $bug->delta_ts]));

  require 'process_bug.cgi';
  debug_print("Bug processed.");

  my $added_comment;
  if (trim($fields{'comment'})) {

    # The "old" bug object doesn't contain the comment we just added.
    $added_comment = Bugzilla::Bug->check($bug_id)->comments->[-1];
  }
  return ($bug, $added_comment);
275 276 277
}

sub handle_attachments {
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
  my ($bug, $attachments, $comment) = @_;
  return if !$attachments;
  debug_print("Handling attachments...");
  my $dbh = Bugzilla->dbh;
  $dbh->bz_start_transaction();
  my ($update_comment, $update_bug);
  foreach my $attachment (@$attachments) {
    debug_print("Inserting Attachment: " . Dumper($attachment), 3);
    my $type = $attachment->content_type || 'application/octet-stream';

    # MUAs add stuff like "name=" to content-type that we really don't
    # want.
    $type =~ s/;.*//;
    my $obj = Bugzilla::Attachment->create({
      bug         => $bug,
      description => $attachment->filename(1),
      filename    => $attachment->filename(1),
      mimetype    => $type,
      data        => $attachment->body,
    });

    # If we added a comment, and our comment does not already have a type,
    # and this is our first attachment, then we make the comment an
    # "attachment created" comment.
    if ($comment and !$comment->type and !$update_comment) {
      $comment->set_all({type => CMT_ATTACHMENT_CREATED, extra_data => $obj->id});
      $update_comment = 1;
    }
    else {
      $bug->add_comment('', {type => CMT_ATTACHMENT_CREATED, extra_data => $obj->id});
      $update_bug = 1;
309
    }
310 311 312 313 314 315 316 317
  }

  # We only update the comments and bugs at the end of the transaction,
  # because doing so modifies bugs_fulltext, which is a non-transactional
  # table.
  $bug->update()     if $update_bug;
  $comment->update() if $update_comment;
  $dbh->bz_commit_transaction();
318 319
}

320 321 322 323 324
######################
# Helper Subroutines #
######################

sub debug_print {
325 326 327
  my ($str, $level) = @_;
  $level ||= 1;
  print STDERR "$str\n" if $level <= $switch{'verbose'};
328 329 330
}

sub get_body_and_attachments {
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
  my ($email) = @_;

  my $ct = $email->content_type || 'text/plain';
  debug_print("Splitting Body and Attachments [Type: $ct]...", 2);

  my ($bodies, $attachments) = split_body_and_attachments($email);
  debug_print(
        scalar(@$bodies)
      . " body part(s) and "
      . scalar(@$attachments)
      . " attachment part(s).");
  debug_print('Bodies: ' . Dumper($bodies), 3);

  # Get the first part of the email that contains a text body,
  # and make all the other pieces into attachments. (This handles
  # people or MUAs who accidentally attach text files as an "inline"
  # attachment.)
  my $body;
  while (@$bodies) {
    my $possible = shift @$bodies;
    $body = get_text_alternative($possible);
    if (defined $body) {
      unshift(@$attachments, @$bodies);
      last;
355
    }
356
  }
357

358 359 360 361 362 363 364 365 366
  if (!defined $body) {

    # Note that this only happens if the email does not contain any
    # text/plain parts. If the email has an empty text/plain part,
    # you're fine, and this message does NOT get thrown.
    ThrowUserError('email_no_body');
  }

  debug_print("Picked Body:\n$body", 2);
367

368
  return ($body, $attachments);
369 370 371
}

sub get_text_alternative {
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
  my ($email) = @_;

  my @parts = $email->parts;
  my $body;
  foreach my $part (@parts) {
    my $ct = $part->content_type || 'text/plain';
    my $charset = 'iso-8859-1';

    # The charset may be quoted.
    if ($ct =~ /charset="?([^;"]+)/) {
      $charset = $1;
    }
    debug_print("Alternative Part Content-Type: $ct",            2);
    debug_print("Alternative Part Character Encoding: $charset", 2);

    # If we find a text/plain body here, return it immediately.
    if (!$ct || $ct =~ m{^text/plain}i) {
      return _decode_body($charset, $part->body);
    }

    # If we find a text/html body, decode it, but don't return
    # it immediately, because there might be a text/plain alternative
    # later. This could be any HTML type.
    if ($ct =~ m{^application/xhtml\+xml}i or $ct =~ m{text/html}i) {
      my $parser = HTML::FormatText::WithLinks->new(

        # Put footnnote indicators after the text, not before it.
        before_link => '',
        after_link  => '[%n]',

        # Convert bold and italics, use "*" for bold instead of "_".
        with_emphasis => 1,
        bold_marker   => '*',

        # If the same link appears multiple times, only create
        # one footnote.
        unique_links => 1,

        # If the link text is the URL, don't create a footnote.
        skip_linked_urls => 1,
      );
      $body = _decode_body($charset, $part->body);
      $body = $parser->parse($body);
415
    }
416
  }
417

418
  return $body;
419 420
}

421
sub _decode_body {
422 423 424 425 426
  my ($charset, $body) = @_;
  if (Bugzilla->params->{'utf8'} && !utf8::is_utf8($body)) {
    return Encode::decode($charset, $body);
  }
  return $body;
427 428
}

429
sub remove_leading_blank_lines {
430 431 432
  my ($text) = @_;
  $text =~ s/^(\s*\n)+//s;
  return $text;
433 434 435
}

sub html_strip {
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
  my ($var) = @_;

  # Trivial HTML tag remover (this is just for error messages, really.)
  $var =~ s/<[^>]*>//g;

  # And this basically reverses the Template-Toolkit html filter.
  $var =~ s/\&amp;/\&/g;
  $var =~ s/\&lt;/</g;
  $var =~ s/\&gt;/>/g;
  $var =~ s/\&quot;/\"/g;
  $var =~ s/&#64;/@/g;

  # Also remove undesired newlines and consecutive spaces.
  $var =~ s/[\n\s]+/ /gms;
  return $var;
451 452
}

453
sub split_body_and_attachments {
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
  my ($email) = @_;

  my (@body, @attachments);
  foreach my $part ($email->parts) {
    my $ct = lc($part->content_type || 'text/plain');
    my $disposition = lc($part->header('Content-Disposition') || 'inline');

    # Remove the charset, etc. from the content-type, we don't care here.
    $ct =~ s/;.*//;
    debug_print("Part Content-Type: [$ct]",         2);
    debug_print("Part Disposition: [$disposition]", 2);

    if ($disposition eq 'inline' and grep($_ eq $ct, BODY_TYPES)) {
      push(@body, $part);
      next;
469 470
    }

471 472 473 474 475 476 477 478 479 480 481 482 483
    if (scalar($part->parts) == 1) {
      push(@attachments, $part);
      next;
    }

    # If this part has sub-parts, analyze them similarly to how we
    # did above and return the relevant pieces.
    my ($add_body, $add_attachments) = split_body_and_attachments($part);
    push(@body,        @$add_body);
    push(@attachments, @$add_attachments);
  }

  return (\@body, \@attachments);
484 485
}

486 487

sub die_handler {
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
  my ($msg) = @_;

  # In Template-Toolkit, [% RETURN %] is implemented as a call to "die".
  # But of course, we really don't want to actually *die* just because
  # the user-error or code-error template ended. So we don't really die.
  return
       if blessed($msg)
    && $msg->isa('Template::Exception')
    && $msg->type eq 'return';

  # If this is inside an eval, then we should just act like...we're
  # in an eval (instead of printing the error and exiting).
  die @_ if ($^S // Bugzilla::Error::_in_eval());

  # We can't depend on the MTA to send an error message, so we have
  # to generate one properly.
  if ($input_email) {
    $msg =~ s/at .+ line.*$//ms;
    $msg =~ s/^Compilation failed in require.+$//ms;
    $msg = html_strip($msg);
    my $from = Bugzilla->params->{'mailfrom'};
    my $reply
      = reply(to => $input_email, from => $from, top_post => 1, body => "$msg\n");
    MessageToMTA($reply->as_string);
  }
  print STDERR "$msg\n";

  # We exit with a successful value, because we don't want the MTA
  # to *also* send a failure notice.
  exit;
518 519 520 521 522 523 524 525
}

###############
# Main Script #
###############

$SIG{__DIE__} = \&die_handler;

526
GetOptions(\%switch, 'help|h', 'verbose|v+', 'default=s%', 'override=s%');
527 528 529 530 531 532 533
$switch{'verbose'} ||= 0;

# Print the help message if that switch was selected.
pod2usage({-verbose => 0, -exitval => 1}) if $switch{'help'};

Bugzilla->usage_mode(USAGE_MODE_EMAIL);

534 535
my @mail_lines  = <STDIN>;
my $mail_text   = join("", @mail_lines);
536
my $mail_fields = parse_mail($mail_text);
537

538
Bugzilla::Hook::process('email_in_after_parse', {fields => $mail_fields});
539

540
my $attachments = delete $mail_fields->{'attachments'};
541 542

my $username = $mail_fields->{'reporter'};
543

544 545
# If emailsuffix is in use, we have to remove it from the email address.
if (my $suffix = Bugzilla->params->{'emailsuffix'}) {
546
  $username =~ s/\Q$suffix\E$//i;
547 548
}

549
my $user = Bugzilla::User->check($username);
550 551
Bugzilla->set_user($user);

552
my ($bug, $comment);
553
if ($mail_fields->{'bug_id'}) {
554
  ($bug, $comment) = process_bug($mail_fields);
555 556
}
else {
557
  ($bug, $comment) = post_bug($mail_fields);
558
}
559

560 561 562 563 564 565 566 567 568
handle_attachments($bug, $attachments, $comment);

# This is here for post_bug and handle_attachments, so that when posting a bug
# with an attachment, any comment goes out as an attachment comment.
#
# Eventually this should be sending the mail for process_bug, too, but we have
# to wait for $bug->update() to be fully used in email_in.pl first. So
# currently, process_bug.cgi does the mail sending for bugs, and this does
# any mail sending for attachments after the first one.
569
Bugzilla::BugMail::Send($bug->id, {changer => Bugzilla->user});
570 571 572
debug_print("Sent bugmail");


573 574 575 576 577 578 579 580
__END__

=head1 NAME

email_in.pl - The Bugzilla Inbound Email Interface

=head1 SYNOPSIS

581 582 583 584 585 586 587 588
./email_in.pl [-vvv] [--default name=value] [--override name=value] < email.txt

Reads an email on STDIN (the standard input).

Options:

   --verbose (-v)        - Make the script print more to STDERR.
                           Specify multiple times to print even more.
589

590 591 592
   --default name=value  - Specify defaults for field values, like
                           product=TestProduct. Can be specified multiple
                           times to specify defaults for multiple fields.
593

594 595 596
   --override name=value - Override field values specified in the email,
                           like product=TestProduct. Can be specified
                           multiple times to override multiple fields.
597 598 599 600 601 602 603 604 605 606 607 608 609

=head1 DESCRIPTION

This script processes inbound email and creates a bug, or appends data
to an existing bug.

=head2 Creating a New Bug

The script expects to read an email with the following format:

 From: account@domain.com
 Subject: Bug Summary

610 611 612
 @product ProductName
 @component ComponentName
 @version 1.0
613 614 615 616 617 618 619 620 621 622

 This is a bug description. It will be entered into the bug exactly as
 written here.

 It can be multiple paragraphs.

 -- 
 This is a signature line, and will be removed automatically, It will not
 be included in the bug description.

623 624 625 626
For the list of valid field names for the C<@> fields, including
a list of which ones are required, see L<Bugzilla::WebService::Bug/create>.
(Note, however, that you cannot specify C<@description> as a field--
you just add a comment by adding text after the C<@> fields.)
627 628 629 630 631

The values for the fields can be split across multiple lines, but
note that a newline will be parsed as a single space, for the value.
So, for example:

632
 @summary This is a very long
633 634 635 636
 description

Will be parsed as "This is a very long description".

637
If you specify C<@summary>, it will override the summary you specify
638 639
in the Subject header.

640 641
C<account@domain.com> (the value of the C<From> header) must be a valid
Bugzilla account.
642 643 644 645

Note that signatures must start with '-- ', the standard signature
border.

646 647 648 649 650 651 652 653 654 655 656 657
=head2 Modifying an Existing Bug

Bugzilla determines what bug you want to modify in one of two ways:

=over

=item *

Your subject starts with [Bug 123456] -- then it modifies bug 123456.

=item *

658
You include C<@id 123456> in the first lines of the email.
659 660 661

=back

662
If you do both, C<@id> takes precedence.
663 664 665 666 667 668 669 670

You send your email in the same format as for creating a bug, except
that you only specify the fields you want to change. If the very
first non-blank line of the email doesn't begin with C<@>, then it
will be assumed that you are only adding a comment to the bug.

Note that when updating a bug, the C<Subject> header is ignored,
except for getting the bug ID. If you want to change the bug's summary,
671
you have to specify C<@summary> as one of the fields to change.
672 673 674 675 676 677 678 679

Please remember not to include any extra text in your emails, as that
text will also be added as a comment. This includes any text that your
email client automatically quoted and included, if this is a reply to
another email.

=head3 Adding/Removing CCs

680
To add CCs, you can specify them in a comma-separated list in C<@cc>.
681 682 683

To remove CCs, specify them as a comma-separated list in C<@removecc>.

684 685 686 687 688 689 690
=head2 Errors

If your request cannot be completed for any reason, Bugzilla will
send an email back to you. If your request succeeds, Bugzilla will
not send you anything.

If any part of your request fails, all of it will fail. No partial
691 692
changes will happen.

693 694 695 696 697 698 699 700 701 702 703
=head1 CAUTION

The script does not do any validation that the user is who they say
they are. That is, it accepts I<any> 'From' address, as long as it's
a valid Bugzilla account. So make sure that your MTA validates that
the message is actually coming from who it says it's coming from,
and only allow access to the inbound email system from people you trust.

=head1 LIMITATIONS

The email interface only accepts emails that are correctly formatted
704
per RFC2822. If you send it an incorrectly formatted message, it
705 706 707
may behave in an unpredictable fashion.

You cannot modify Flags through the email interface.