email_in.pl 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. #!/usr/bin/env perl -w
  2. # -*- Mode: perl; indent-tabs-mode: nil -*-
  3. #
  4. # The contents of this file are subject to the Mozilla Public
  5. # License Version 1.1 (the "License"); you may not use this file
  6. # except in compliance with the License. You may obtain a copy of
  7. # the License at http://www.mozilla.org/MPL/
  8. #
  9. # Software distributed under the License is distributed on an "AS
  10. # IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
  11. # implied. See the License for the specific language governing
  12. # rights and limitations under the License.
  13. #
  14. # The Original Code is the Bugzilla Inbound Email System.
  15. #
  16. # The Initial Developer of the Original Code is Akamai Technologies, Inc.
  17. # Portions created by Akamai are Copyright (C) 2006 Akamai Technologies,
  18. # Inc. All Rights Reserved.
  19. #
  20. # Contributor(s): Max Kanat-Alexander <mkanat@bugzilla.org>
  21. use strict;
  22. use warnings;
  23. # MTAs may call this script from any directory, but it should always
  24. # run from this one so that it can find its modules.
  25. BEGIN {
  26. require File::Basename;
  27. chdir(File::Basename::dirname($0));
  28. }
  29. use lib qw(. lib);
  30. use Data::Dumper;
  31. use Email::Address;
  32. use Email::Reply qw(reply);
  33. use Email::MIME;
  34. use Email::MIME::Attachment::Stripper;
  35. use Getopt::Long qw(:config bundling);
  36. use Pod::Usage;
  37. use Encode;
  38. use Bugzilla;
  39. use Bugzilla::Bug qw(ValidateBugID);
  40. use Bugzilla::Constants qw(USAGE_MODE_EMAIL);
  41. use Bugzilla::Error;
  42. use Bugzilla::Mailer;
  43. use Bugzilla::User;
  44. use Bugzilla::Util;
  45. use Bugzilla::Token;
  46. #############
  47. # Constants #
  48. #############
  49. # This is the USENET standard line for beginning a signature block
  50. # in a message. RFC-compliant mailers use this.
  51. use constant SIGNATURE_DELIMITER => '-- ';
  52. # $input_email is a global so that it can be used in die_handler.
  53. our ($input_email, %switch);
  54. ####################
  55. # Main Subroutines #
  56. ####################
  57. sub parse_mail {
  58. my ($mail_text) = @_;
  59. debug_print('Parsing Email');
  60. $input_email = Email::MIME->new($mail_text);
  61. my %fields;
  62. # Email::Address->parse returns an array
  63. my ($reporter) = Email::Address->parse($input_email->header('From'));
  64. $fields{'reporter'} = $reporter->address;
  65. my $summary = $input_email->header('Subject');
  66. if ($summary =~ /\[Bug (\d+)\](.*)/i) {
  67. $fields{'bug_id'} = $1;
  68. $summary = trim($2);
  69. }
  70. my ($body, $attachments) = get_body_and_attachments($input_email);
  71. if (@$attachments) {
  72. $fields{'attachments'} = $attachments;
  73. }
  74. debug_print("Body:\n" . $body, 3);
  75. $body = remove_leading_blank_lines($body);
  76. my @body_lines = split(/\r?\n/s, $body);
  77. # If there are fields specified.
  78. if ($body =~ /^\s*@/s) {
  79. my $current_field;
  80. while (my $line = shift @body_lines) {
  81. # If the sig is starting, we want to keep this in the
  82. # @body_lines so that we don't keep the sig as part of the
  83. # comment down below.
  84. if ($line eq SIGNATURE_DELIMITER) {
  85. unshift(@body_lines, $line);
  86. last;
  87. }
  88. # Otherwise, we stop parsing fields on the first blank line.
  89. $line = trim($line);
  90. last if !$line;
  91. if ($line =~ /^@(\S+)\s*=\s*(.*)\s*/) {
  92. $current_field = lc($1);
  93. # It's illegal to pass the reporter field as you could
  94. # override the "From:" field of the message and bypass
  95. # authentication checks, such as PGP.
  96. if ($current_field eq 'reporter') {
  97. # We reset the $current_field variable to something
  98. # post_bug and process_bug will ignore, in case the
  99. # attacker splits the reporter field on several lines.
  100. $current_field = 'illegal_field';
  101. next;
  102. }
  103. $fields{$current_field} = $2;
  104. }
  105. else {
  106. $fields{$current_field} .= " $line";
  107. }
  108. }
  109. }
  110. # The summary line only affects us if we're doing a post_bug.
  111. # We have to check it down here because there might have been
  112. # a bug_id specified in the body of the email.
  113. if (!$fields{'bug_id'} && !$fields{'short_desc'}) {
  114. $fields{'short_desc'} = $summary;
  115. }
  116. my $comment = '';
  117. # Get the description, except the signature.
  118. foreach my $line (@body_lines) {
  119. last if $line eq SIGNATURE_DELIMITER;
  120. $comment .= "$line\n";
  121. }
  122. $fields{'comment'} = $comment;
  123. debug_print("Parsed Fields:\n" . Dumper(\%fields), 2);
  124. return \%fields;
  125. }
  126. sub post_bug {
  127. my ($fields_in) = @_;
  128. my %fields = %$fields_in;
  129. debug_print('Posting a new bug...');
  130. my $cgi = Bugzilla->cgi;
  131. foreach my $field (keys %fields) {
  132. $cgi->param(-name => $field, -value => $fields{$field});
  133. }
  134. $cgi->param(-name => 'inbound_email', -value => 1);
  135. require 'post_bug.cgi';
  136. }
  137. sub process_bug {
  138. my ($fields_in) = @_;
  139. my %fields = %$fields_in;
  140. my $bug_id = $fields{'bug_id'};
  141. $fields{'id'} = $bug_id;
  142. delete $fields{'bug_id'};
  143. debug_print("Updating Bug $fields{id}...");
  144. ValidateBugID($bug_id);
  145. my $bug = new Bugzilla::Bug($bug_id);
  146. if ($fields{'bug_status'}) {
  147. $fields{'knob'} = $fields{'bug_status'};
  148. }
  149. # If no status is given, then we only want to change the resolution.
  150. elsif ($fields{'resolution'}) {
  151. $fields{'knob'} = 'change_resolution';
  152. $fields{'resolution_knob_change_resolution'} = $fields{'resolution'};
  153. }
  154. if ($fields{'dup_id'}) {
  155. $fields{'knob'} = 'duplicate';
  156. }
  157. # Move @cc to @newcc as @cc is used by process_bug.cgi to remove
  158. # users from the CC list when @removecc is set.
  159. $fields{'newcc'} = delete $fields{'cc'} if $fields{'cc'};
  160. # Make it possible to remove CCs.
  161. if ($fields{'removecc'}) {
  162. $fields{'cc'} = [split(',', $fields{'removecc'})];
  163. $fields{'removecc'} = 1;
  164. }
  165. my $cgi = Bugzilla->cgi;
  166. foreach my $field (keys %fields) {
  167. $cgi->param(-name => $field, -value => $fields{$field});
  168. }
  169. $cgi->param('longdesclength', scalar $bug->longdescs);
  170. $cgi->param('token', issue_hash_token([$bug->id, $bug->delta_ts]));
  171. require 'process_bug.cgi';
  172. }
  173. ######################
  174. # Helper Subroutines #
  175. ######################
  176. sub debug_print {
  177. my ($str, $level) = @_;
  178. $level ||= 1;
  179. print STDERR "$str\n" if $level <= $switch{'verbose'};
  180. }
  181. sub get_body_and_attachments {
  182. my ($email) = @_;
  183. my $ct = $email->content_type || 'text/plain';
  184. debug_print("Splitting Body and Attachments [Type: $ct]...");
  185. my $body;
  186. my $attachments = [];
  187. if ($ct =~ /^multipart\/alternative/i) {
  188. $body = get_text_alternative($email);
  189. }
  190. else {
  191. my $stripper = new Email::MIME::Attachment::Stripper(
  192. $email, force_filename => 1);
  193. my $message = $stripper->message;
  194. $body = get_text_alternative($message);
  195. $attachments = [$stripper->attachments];
  196. }
  197. return ($body, $attachments);
  198. }
  199. sub get_text_alternative {
  200. my ($email) = @_;
  201. my @parts = $email->parts;
  202. my $body;
  203. foreach my $part (@parts) {
  204. my $ct = $part->content_type || 'text/plain';
  205. my $charset = 'iso-8859-1';
  206. # The charset may be quoted.
  207. if ($ct =~ /charset="?([^;"]+)/) {
  208. $charset= $1;
  209. }
  210. debug_print("Part Content-Type: $ct", 2);
  211. debug_print("Part Character Encoding: $charset", 2);
  212. if (!$ct || $ct =~ /^text\/plain/i) {
  213. $body = $part->body;
  214. if (Bugzilla->params->{'utf8'} && !utf8::is_utf8($body)) {
  215. $body = Encode::decode($charset, $body);
  216. }
  217. last;
  218. }
  219. }
  220. if (!defined $body) {
  221. # Note that this only happens if the email does not contain any
  222. # text/plain parts. If the email has an empty text/plain part,
  223. # you're fine, and this message does NOT get thrown.
  224. ThrowUserError('email_no_text_plain');
  225. }
  226. return $body;
  227. }
  228. sub remove_leading_blank_lines {
  229. my ($text) = @_;
  230. $text =~ s/^(\s*\n)+//s;
  231. return $text;
  232. }
  233. sub html_strip {
  234. my ($var) = @_;
  235. # Trivial HTML tag remover (this is just for error messages, really.)
  236. $var =~ s/<[^>]*>//g;
  237. # And this basically reverses the Template-Toolkit html filter.
  238. $var =~ s/\&amp;/\&/g;
  239. $var =~ s/\&lt;/</g;
  240. $var =~ s/\&gt;/>/g;
  241. $var =~ s/\&quot;/\"/g;
  242. $var =~ s/&#64;/@/g;
  243. # Also remove undesired newlines and consecutive spaces.
  244. $var =~ s/[\n\s]+/ /gms;
  245. return $var;
  246. }
  247. sub die_handler {
  248. my ($msg) = @_;
  249. # In Template-Toolkit, [% RETURN %] is implemented as a call to "die".
  250. # But of course, we really don't want to actually *die* just because
  251. # the user-error or code-error template ended. So we don't really die.
  252. return if $msg->isa('Template::Exception') && $msg->type eq 'return';
  253. # If this is inside an eval, then we should just act like...we're
  254. # in an eval (instead of printing the error and exiting).
  255. die(@_) if $^S;
  256. # We can't depend on the MTA to send an error message, so we have
  257. # to generate one properly.
  258. if ($input_email) {
  259. $msg =~ s/at .+ line.*$//ms;
  260. $msg =~ s/^Compilation failed in require.+$//ms;
  261. $msg = html_strip($msg);
  262. my $from = Bugzilla->params->{'mailfrom'};
  263. my $reply = reply(to => $input_email, from => $from, top_post => 1,
  264. body => "$msg\n");
  265. MessageToMTA($reply->as_string);
  266. }
  267. print STDERR "$msg\n";
  268. # We exit with a successful value, because we don't want the MTA
  269. # to *also* send a failure notice.
  270. exit;
  271. }
  272. ###############
  273. # Main Script #
  274. ###############
  275. $SIG{__DIE__} = \&die_handler;
  276. GetOptions(\%switch, 'help|h', 'verbose|v+');
  277. $switch{'verbose'} ||= 0;
  278. # Print the help message if that switch was selected.
  279. pod2usage({-verbose => 0, -exitval => 1}) if $switch{'help'};
  280. Bugzilla->usage_mode(USAGE_MODE_EMAIL);
  281. my @mail_lines = <STDIN>;
  282. my $mail_text = join("", @mail_lines);
  283. my $mail_fields = parse_mail($mail_text);
  284. my $username = $mail_fields->{'reporter'};
  285. # If emailsuffix is in use, we have to remove it from the email address.
  286. if (my $suffix = Bugzilla->params->{'emailsuffix'}) {
  287. $username =~ s/\Q$suffix\E$//i;
  288. }
  289. my $user = Bugzilla::User->new({ name => $username })
  290. || ThrowUserError('invalid_username', { name => $username });
  291. Bugzilla->set_user($user);
  292. if ($mail_fields->{'bug_id'}) {
  293. process_bug($mail_fields);
  294. }
  295. else {
  296. post_bug($mail_fields);
  297. }
  298. __END__
  299. =head1 NAME
  300. email_in.pl - The Bugzilla Inbound Email Interface
  301. =head1 SYNOPSIS
  302. ./email_in.pl [-vvv] < email.txt
  303. Reads an email on STDIN (the standard input).
  304. Options:
  305. --verbose (-v) - Make the script print more to STDERR.
  306. Specify multiple times to print even more.
  307. =head1 DESCRIPTION
  308. This script processes inbound email and creates a bug, or appends data
  309. to an existing bug.
  310. =head2 Creating a New Bug
  311. The script expects to read an email with the following format:
  312. From: account@domain.com
  313. Subject: Bug Summary
  314. @product = ProductName
  315. @component = ComponentName
  316. @version = 1.0
  317. This is a bug description. It will be entered into the bug exactly as
  318. written here.
  319. It can be multiple paragraphs.
  320. --
  321. This is a signature line, and will be removed automatically, It will not
  322. be included in the bug description.
  323. The C<@> labels can be any valid field name in Bugzilla that can be
  324. set on C<enter_bug.cgi>. For the list of required field names, see
  325. L<Bugzilla::WebService::Bug/Create>. Note, that there is some difference
  326. in the names of the required input fields between web and email interfaces,
  327. as listed below:
  328. =over
  329. =item *
  330. C<platform> in web is C<@rep_platform> in email
  331. =item *
  332. C<severity> in web is C<@bug_severity> in email
  333. =back
  334. For the list of all field names, see the C<fielddefs> table in the database.
  335. The values for the fields can be split across multiple lines, but
  336. note that a newline will be parsed as a single space, for the value.
  337. So, for example:
  338. @short_desc = This is a very long
  339. description
  340. Will be parsed as "This is a very long description".
  341. If you specify C<@short_desc>, it will override the summary you specify
  342. in the Subject header.
  343. C<account@domain.com> must be a valid Bugzilla account.
  344. Note that signatures must start with '-- ', the standard signature
  345. border.
  346. =head2 Modifying an Existing Bug
  347. Bugzilla determines what bug you want to modify in one of two ways:
  348. =over
  349. =item *
  350. Your subject starts with [Bug 123456] -- then it modifies bug 123456.
  351. =item *
  352. You include C<@bug_id = 123456> in the first lines of the email.
  353. =back
  354. If you do both, C<@bug_id> takes precedence.
  355. You send your email in the same format as for creating a bug, except
  356. that you only specify the fields you want to change. If the very
  357. first non-blank line of the email doesn't begin with C<@>, then it
  358. will be assumed that you are only adding a comment to the bug.
  359. Note that when updating a bug, the C<Subject> header is ignored,
  360. except for getting the bug ID. If you want to change the bug's summary,
  361. you have to specify C<@short_desc> as one of the fields to change.
  362. Please remember not to include any extra text in your emails, as that
  363. text will also be added as a comment. This includes any text that your
  364. email client automatically quoted and included, if this is a reply to
  365. another email.
  366. =head3 Adding/Removing CCs
  367. To add CCs, you can specify them in a comma-separated list in C<@cc>.
  368. For backward compatibility, C<@newcc> can also be used. If both are
  369. present, C<@cc> takes precedence.
  370. To remove CCs, specify them as a comma-separated list in C<@removecc>.
  371. =head2 Errors
  372. If your request cannot be completed for any reason, Bugzilla will
  373. send an email back to you. If your request succeeds, Bugzilla will
  374. not send you anything.
  375. If any part of your request fails, all of it will fail. No partial
  376. changes will happen.
  377. There is no attachment support yet.
  378. =head1 CAUTION
  379. The script does not do any validation that the user is who they say
  380. they are. That is, it accepts I<any> 'From' address, as long as it's
  381. a valid Bugzilla account. So make sure that your MTA validates that
  382. the message is actually coming from who it says it's coming from,
  383. and only allow access to the inbound email system from people you trust.
  384. =head1 LIMITATIONS
  385. Note that the email interface has the same limitations as the
  386. normal Bugzilla interface. So, for example, you cannot reassign
  387. a bug and change its status at the same time.
  388. The email interface only accepts emails that are correctly formatted
  389. perl RFC2822. If you send it an incorrectly formatted message, it
  390. may behave in an unpredictable fashion.
  391. You cannot send an HTML mail along with attachments. If you do, Bugzilla
  392. will reject your email, saying that it doesn't contain any text. This
  393. is a bug in L<Email::MIME::Attachment::Stripper> that we can't work
  394. around.
  395. You cannot modify Flags through the email interface.