]> git.donarmstrong.com Git - debbugs.git/blob - scripts/process
fix plural of {src,bin}packages? in updatesql
[debbugs.git] / scripts / process
1 #!/usr/bin/perl
2 # $Id: process.in,v 1.109 2006/02/09 22:02:04 don Exp $
3 #
4 # Usage: process nn
5 # Temps:  incoming/Pnn
6
7 use warnings;
8 use strict;
9
10 use locale;
11 use POSIX qw(strftime locale_h);
12 setlocale(LC_TIME, "C");
13
14 use IO::File;
15
16 use Getopt::Long;
17 use Pod::Usage;
18 use MIME::Parser;
19 use Debbugs::MIME qw(decode_rfc1522 create_mime_message getmailbody);
20 use Debbugs::Mail qw(send_mail_message encode_headers get_addresses);
21 use Debbugs::Packages qw(getpkgsrc binary_to_source);
22 use Debbugs::User qw(read_usertags write_usertags);
23 use Debbugs::Common qw(:lock get_hashname buglog package_maintainer overwritefile make_list);
24 use Debbugs::Status qw(writebug isstrongseverity lockreadbugmerge lockreadbug new_bug read_bug splitpackages  :versions);
25
26 use Debbugs::CGI qw(html_escape bug_links);
27
28 use Debbugs::Log qw(:misc :write);
29
30 use Debbugs::Text qw(:templates);
31
32 use Debbugs::Config qw(:globals :config);
33
34 use Debbugs::Control qw(append_action_to_log);
35 use Debbugs::Control::Service qw(valid_control control_line);
36 use Debbugs::Recipients qw(determine_recipients);
37 use Encode qw(encode_utf8 decode);
38
39 =head1 NAME
40
41 process - Handle e-mails emails sent to bugs
42
43 =head1 SYNOPSIS
44
45 process nn
46
47  Options:
48   --debug, -d debugging level (Default 0)
49
50 =head1 OPTIONS
51
52 =over
53
54 =item <--debug,-d>
55
56 Debugging level (default 0)
57
58 =back
59
60 =cut
61
62 use vars qw($DEBUG);
63
64 my %options = (debug           => 0,
65                help            => 0,
66                man             => 0,
67               );
68
69 GetOptions(\%options,
70            'debug|d+','help|h|?','man|m');
71
72 pod2usage() if $options{help};
73 pod2usage({verbose=>2}) if $options{man};
74
75
76 $DEBUG=$options{debug};
77 my $debugfh = IO::File->new('/dev/null','w') or
78     die "Unable to open /dev/null for writing; $!";
79 if ($DEBUG > 0) {
80     $debugfh = \*STDERR;
81 }
82 binmode($debugfh,':raw:encoding(UTF-8)');
83
84 # these are the valid bug addresses
85 my %baddress = (B => 'submit',
86                 M => 'maintonly',
87                 Q => 'quiet',
88                 F => 'forwarded',
89                 D => 'done',
90                 U => 'submitter',
91                 L => 'list',
92                );
93 my $valid_codeletters = join('',keys %baddress);
94
95
96 chdir($config{spool_dir}) or die "Unable to chdir to spool ($config{spool_dir}): $!";
97
98 umask(002);
99
100 my $intdate = time or die "failed to get time: $!";
101
102 my ($nn) = @ARGV;
103 my ($codeletter,$tryref) =
104     $nn =~ m/^([$valid_codeletters])(\d*)\.\d+$/
105     or die "bad argument: $_";
106 $tryref = undef unless length ($tryref) and
107     $tryref > 0;
108
109 if (!rename("incoming/G$nn","incoming/P$nn"))  {
110     my $error = $!;
111     $error = '' if not defined $error;
112     # this is very fragile, but we should probably die here anyway
113     if ($error =~ m/no such file or directory/i) {
114         exit 0;
115     }
116     die "Unable to rename incoming/G$nn to lock: $error";
117 }
118
119 # die here to avoid continuously processing this mail
120 if (not exists $baddress{$codeletter}) {
121     die "bad codeletter $codeletter";
122 }
123
124 my $baddress = $baddress{$codeletter};
125 if ($baddress eq 'list') {
126     bug_list_forward($nn) if $codeletter eq 'L';
127 }
128
129
130 my $baddressroot= $baddress;
131 $baddress= "$tryref-$baddress" if defined $tryref;
132
133 my $msg;
134 my @msg;
135
136 {
137     my $log = IO::File->new("incoming/P$nn",'r') or
138         die "Unable to open 'incoming/P$nn' for reading; $!";
139     local $/;
140     $msg=<$log>;
141     @msg = split /\n/, $msg;
142     close($log);
143 }
144
145
146 my $tdate = strftime "%a, %d %h %Y %T +0000", gmtime;
147 my $fwd= "Received: via spool by $baddress\@$gEmailDomain id=$nn\n".
148     "          (code $codeletter".(defined($tryref)?" ref $tryref":'')."); $tdate\n";
149
150 # header and decoded body respectively
151 my (@headerlines, @bodylines);
152
153 # whether maintainer addresses have been checked
154 our $maintainerschecked = 0;
155 #maintainer address for this message
156 our @maintaddrs;
157 # other src addresses
158 our @addsrcaddrs;
159 our @resentccs;
160 our @bccs;
161
162 my $resentccexplain='';
163
164 # whether there's a new reference with this email
165 our $newref = 0;
166
167 our $brokenness = '';
168
169 my $parser_output = Debbugs::MIME::parse($msg);
170
171 @headerlines = @{$parser_output->{header}};
172 @bodylines = @{$parser_output->{body}};
173
174 my %header;
175
176 my @common_headers;
177 for my $hdr (@headerlines) {
178     my $orig_hdr = $hdr;
179     $hdr = decode_rfc1522($hdr);
180     $_ = $hdr;
181     s/\n\s/ /g;
182     finish() if m/^x-loop: (\S+)$/i && $1 eq "$gMaintainerEmail";
183     my $ins = !m/^(?:(?:subject|reply-to|return-path|mail-followup-to):
184                  |From\s|X-Debbugs-)/xi;
185     $fwd .= encode_utf8($hdr)."\n" if $ins;
186     # print {$debugfh} ">$_<\n";
187     if (s/^(\S+):\s*//) {
188         my $v = lc $1;
189         if ($v eq 'x-loop') {
190             push @common_headers, 'X-Loop',$_;
191         }
192         print {$debugfh} ">$v=$_<\n";
193         $header{$v} = $_;
194     } else {
195         print {$debugfh} "!>$_<\n";
196     }
197 }
198 $header{'message-id'} = '' if not defined $header{'message-id'};
199
200 push @common_headers, 'X-Loop',$gMaintainerEmail;
201
202 # remove blank lines
203 shift @bodylines while @bodylines and $bodylines[0] !~ /\S/;
204
205 # Strip off RFC2440-style PGP clearsigning.
206 if (@bodylines and $bodylines[0] =~ /^-----BEGIN PGP SIGNED/) {
207     shift @bodylines while @bodylines and length $bodylines[0];
208     shift @bodylines while @bodylines and $bodylines[0] !~ /\S/;
209     for my $findsig (0 .. $#bodylines) {
210         if ($bodylines[$findsig] =~ /^-----BEGIN PGP SIGNATURE/) {
211             $#bodylines = $findsig - 1;
212             last;
213         }
214     }
215     map { s/^- // } @bodylines;
216 }
217
218 #psuedoheaders
219 my %pheader;
220 my @control_bits;
221 # extract pseudo-headers
222 for my $phline (@bodylines)
223 {
224     # Remove BOM markers from UTF-8 strings
225     # Fixes #488554
226     $phline =~ s/\xef\xbb\xbf//g;
227     $phline =~ s/\N{U+FEFF}//g;
228     last if $phline !~ m/^([\w-]+): # psuedoheader
229                          (?:\s|\N{U+00A0})* # zero or more spaces, including
230                                             # non-breaking space
231                          (\S.*)/x; # pseudoheader value
232     my ($fn, $fv) = ($1, $2);
233     $fv =~ s/\s*$//;
234     # pluralize tag/usertag
235     $fn = $fn.'s' if $fn =~ /^(?:tag|usertag)$/;
236     print {$debugfh} ">$fn|$fv|\n";
237     $fn = lc $fn;
238     if ($fn =~ /^control$/) {
239         push @control_bits,$fv;
240     } else {
241         # Don't lc owner or forwarded
242         $fv = lc $fv unless $fn =~ /^(?:owner|forwarded|usertags|version|source-version)$/;
243         $pheader{$fn} = $fv;
244     }
245     print {$debugfh} ">$fn~$fv<\n";
246 }
247
248 # Allow pseudo headers to set x-debbugs- stuff [#179340]
249 for my $key (grep /X-Debbugs-.*/i, keys %pheader) {
250      $header{$key} = $pheader{$key} if not exists $header{$key};
251 }
252
253 # set $i to beginning of encoded body data, so we can dump it out
254 # verbatim later
255 my $i = 0;
256 ++$i while $i <= $#msg and $msg[$i] =~ /./;
257 $fwd .= join("\n",@msg[$i..$#msg]);
258
259 binmode($debugfh,':raw');
260 print {$debugfh} "***\n$fwd\n***\n";
261 binmode($debugfh,':raw:encoding(UTF-8)');
262
263 if (defined $header{'resent-from'} && !defined $header{'from'}) {
264     $header{'from'} = $header{'resent-from'};
265 }
266 defined($header{'from'}) || die "no From header";
267
268 my $replyto = $header{'reply-to'};
269 $replyto = '' unless defined $replyto;
270 $replyto =~ s/^ +//;
271 $replyto =~ s/ +$//;
272 unless (length $replyto) {
273     $replyto = $header{'from'};
274 }
275
276 my $subject = '(no subject)';
277 if (!defined($header{'subject'})) 
278 {
279         $brokenness.= fill_template('mail/process_broken_subject');
280
281 } else { 
282     $subject= $header{'subject'}; 
283 }
284
285 my $ref=-1;
286 # remove Re: from the subject line
287 $subject =~ s/^Re:\s*//i;
288 # remove remaining mailing list name markers from the subject line if
289 # this appears to be a message that has traversed a mailing list
290 if (exists $header{'list-id'} or exists $header{'list-subscribe'} or
291     (exists $header{'precedence'} and defined $header{'precedence'} and
292      $header{'precedence'} eq 'bulk') or
293     exists $header{'mailing-list'} or exists $header{'list-processor-version'}
294    ){
295     # if a mailing list didn't match any of the above, it's probably
296     # so horribly configured that we wouldn't be able to figure it out
297     # anyway.
298     $subject =~ s/^\[.*\]\s*//i;
299 }
300 $_= $subject."\n";
301 if (not defined $tryref and m/^Bug ?\#(\d+)\D/i) {
302     $tryref = $1 if $1 > 0;
303 }
304 my $locks = 0;
305 my $data;
306 if (defined $tryref) {
307      my $locks_recv;
308      ($locks_recv, $data)= &lockreadbugmerge($tryref);
309      $locks += $locks_recv;
310     if ($locks_recv and not $data->{archived}) {
311         $ref= $tryref;
312     } else {
313         &sendmessage(create_mime_message(
314           [From          => "$gMaintainerEmail ($gProject $gBug Tracking System)",
315            To            => $replyto,
316            Subject       => "Unknown problem report $gBug#$tryref ($subject)",
317            'Message-ID'  => "<handler.x.$nn.unknown\@$gEmailDomain>",
318            'In-Reply-To' => $header{'message-id'},
319            References    => join(' ',grep {defined $_} $header{'message-id'},$data->{msgid}),
320            Precedence    => 'bulk',
321            "X-$gProject-PR-Message" => 'error',
322            @common_headers,
323           ],message_body_template('mail/process_unknown_bug_number',
324                                   {subject => $subject,
325                                    date    => $header{date},
326                                    baddress => $baddress,
327                                    tryref   => $tryref,
328                                    messageid => $header{'message-id'},
329                                   },
330                                  )),'');
331         appendlog($ref,$msg);
332         finish();
333     }
334 } else { 
335     &filelock('lock/-1'); 
336 }
337
338 # Attempt to determine which source package this is
339 my $source_pr_header = '';
340 my $source_package = '';
341 if (defined $pheader{source}) {
342      $source_package = $pheader{source};
343 }
344 elsif (defined $data->{package} or defined $pheader{package}) {
345      $source_package = binary_to_source(binary => $data->{package} // $pheader{package});
346 }
347 $source_pr_header = "X-$gProject-PR-Source: $source_package\n"
348      if defined $source_package and length $source_package;
349
350 # Done and Forwarded Bugs
351 if ($codeletter eq 'D' || $codeletter eq 'F') 
352 {
353     if ($replyto =~ m/$gBounceFroms/o ||
354         $header{'from'} =~ m/$gBounceFroms/o)
355     {
356          print STDERR "bounce detected !  Mwaap! Mwaap!";
357          exit 1;
358     }
359     my $markedby= $header{'from'} eq $replyto ? $replyto :
360                "$header{'from'} (reply to $replyto)";
361     my @generalcc;
362     my $receivedat;
363     my $markaswhat;
364     my $set_forwarded;
365     my $generalcc;
366     my $set_done;
367     if ($codeletter eq 'F') { # Forwarded
368         (appendlog($ref,$msg),finish()) if defined $data->{forwarded} and length($data->{forwarded});
369         $receivedat= "forwarded\@$gEmailDomain";
370         $markaswhat= 'forwarded';
371         $set_forwarded= $header{'to'};
372         # Dissallow forwarded being set to this bug tracking system
373         if (defined $set_forwarded and $set_forwarded =~ /\Q$gEmailDomain\E/) {
374              undef $set_forwarded;
375         }
376         if ( length( $gListDomain ) > 0 && length( $gForwardList ) > 0 ) {
377             push @generalcc, "$gForwardList\@$gListDomain";
378             $generalcc= "$gForwardList\@$gListDomain";
379         } else { 
380             $generalcc='';
381         }
382     } else { # Done
383         if (defined $data->{done} and length($data->{done}) and
384                 not defined $pheader{'source-version'} and
385                 not defined $pheader{'version'}) {
386             appendlog($ref,$msg);
387             finish();
388         }
389         $receivedat= "done\@$gEmailDomain";
390         $markaswhat= 'done';
391         $set_done= $header{'from'};
392         if ( length( $gListDomain ) > 0 && length( $gDoneList ) > 0 ) {
393             $generalcc= "$gDoneList\@$gListDomain";
394             push @generalcc, "$gDoneList\@$gListDomain";
395         } else { 
396             $generalcc=''; 
397         }
398     }
399     if (defined $gStrongList and isstrongseverity($data->{severity})) {
400         $generalcc = join ', ', $generalcc, "$gStrongList\@$gListDomain";
401         push @generalcc,"$gStrongList\@$gListDomain";
402     }
403     if ($ref<0) {
404         &sendmessage(create_mime_message(
405           [From          => "$gMaintainerEmail ($gProject $gBug Tracking System)",
406            To            => $replyto,
407            Subject       => "Message with no $gBug number ignored by $receivedat ($subject)",
408            'Message-ID'  => "<handler.x.$nn.warnignore\@$gEmailDomain>",
409            'In-Reply-To' => $header{'message-id'},
410            References    => join(' ',grep {defined $_} $header{'message-id'},$data->{msgid}),
411            Precedence    => 'bulk',
412            "X-$gProject-PR-Message" => 'error',
413            @common_headers,
414           ],message_body_template('mail/process_no_bug_number',
415                                   {subject => $subject,
416                                    date    => $header{date},
417                                    markaswhat => $markaswhat,
418                                    receivedat => $receivedat,
419                                    messageid => $header{'message-id'},
420                                   },
421                                  )),'');
422         appendlog($ref,$msg);
423         finish();
424     }
425
426     &checkmaintainers;
427
428     my @noticecc = grep($_ ne $replyto,@maintaddrs);
429     my $noticeccval.= join(', ', grep($_ ne $replyto,@maintaddrs));
430     $noticeccval =~ s/\s+\n\s+/ /g; 
431     $noticeccval =~ s/^\s+/ /; $noticeccval =~ s/\s+$//;
432
433     my @process= ($ref,split(/ /,$data->{mergedwith}));
434     my $orgref= $ref;
435
436     for $ref (@process) {
437         if ($ref != $orgref) {
438             &unfilelock;
439             $locks--;
440             $data = &lockreadbug($ref)
441                 || die "huh ? $ref from $orgref out of ".join(' ',@process);
442             $locks++;
443         }
444         $data->{done}= $set_done if defined($set_done);
445         $data->{forwarded}= $set_forwarded if defined($set_forwarded);
446         if ($codeletter eq 'D') {
447             $data->{keywords} = join ' ', grep $_ ne 'pending',
448                                      split ' ', $data->{keywords};
449             if (defined $pheader{'source-version'}) {
450                  if ($pheader{'source-version'} !~ m/^$config{package_version_re}$/) {
451                       $brokenness .= fill_template('mail/invalid_version',
452                                                    {version => $pheader{'source-version'}},
453                                                   );
454                  }
455                  else {
456                       addfixedversions($data, $pheader{source}, $pheader{'source-version'}, '');
457                  }
458             } elsif (defined $pheader{version}) {
459                  if ($pheader{version} !~ m/^$config{package_version_re}$/) {
460                       $brokenness .= fill_template('mail/invalid_version',
461                                                    {version => $pheader{version}},
462                                                   );
463                  }
464                  else {
465                       addfixedversions($data, $pheader{package}, $pheader{version}, '');
466                  }
467             }
468         }
469
470         # Add bug mailing list to $generalbcc as appropriate
471         # This array is used to specify bcc in the cases where we're using create_mime_message.
472         my @generalbcc = @generalcc;
473         if (defined $config{subscription_domain} and length $config{subscription_domain}) {
474             @generalbcc = (@generalbcc, @addsrcaddrs);
475         }
476         if (defined $config{bug_subscription_domain} and length $config{bug_subscription_domain}) {
477             @generalbcc = (@generalbcc, "bugs=$ref\@$config{bug_subscription_domain}");
478         }
479         my $generalbcc = join(', ', @generalbcc);
480         $generalbcc =~ s/\s+\n\s+/ /g;
481         $generalbcc =~ s/^\s+/ /; $generalbcc =~ s/\s+$//;
482         if (length $generalbcc) {$generalbcc = "Bcc: $generalbcc\n"};
483
484         writebug($ref, $data);
485
486         my $hash = get_hashname($ref);
487         my $orig_report_fh = IO::File->new("db-h/$hash/$ref.report") or
488             die "Unable to read original report: $!";
489         my $orig_report;
490         { local $/; $orig_report = <$orig_report_fh>;}
491         close($orig_report_fh) or
492             die "Unable to close original report filehandle: $!";
493         if ($codeletter eq 'F') {
494             &htmllog("Reply","sent",$replyto,"You have marked $gBug as forwarded.");
495             &sendmessage(create_mime_message(
496              [@common_headers,
497               From          => "$gMaintainerEmail ($gProject $gBug Tracking System)",
498               To            => "$replyto",
499               Subject       => "$gBug#$ref: marked as forwarded ($data->{subject})",
500               "Message-ID"  => "<header.$ref.$nn.ackfwdd\@$gEmailDomain>",
501               "In-Reply-To" => $header{'message-id'},
502               References    => join(' ',grep {defined $_} $header{'message-id'},$data->{msgid}),
503               Precedence    => 'bulk',
504               "X-$gProject-PR-Message"  => "forwarded $ref",
505               "X-$gProject-PR-Package"  => $data->{package},
506               "X-$gProject-PR-Keywords" => $data->{keywords},
507               # Only have a X-$gProject-PR-Source when we know the source package
508               (defined($source_package) and length($source_package))?("X-$gProject-PR-Source" => $source_package):(),
509               "Reply-To"                => "$ref\@$gEmailDomain",
510               "Content-Type"            => 'text/plain; charset="utf-8"',
511              ],message_body_template('mail/process_mark_as_forwarded',
512                                      {date => $header{date},
513                                       messageid => $header{'message-id'},
514                                       data      => $data,
515                                      },
516                                     ),
517              [join("\n",@msg)]),'',[$replyto,@generalbcc,@noticecc],1);
518         } else {
519             &htmllog("Reply","sent",$replyto,"You have taken responsibility.");
520             &sendmessage(create_mime_message(
521              [@common_headers,
522               From          => "$gMaintainerEmail ($gProject $gBug Tracking System)",
523               To            => $replyto,
524               Subject       => "$gBug#$ref: marked as done ($data->{subject})",
525               "Message-ID"  => "<handler.$ref.$nn.ackdone\@$gEmailDomain>",
526               "In-Reply-To" => $header{'message-id'},
527               References    => join(' ',grep {defined $_} $header{'message-id'},$data->{msgid}),
528               Precedence    => 'bulk',
529               "X-$gProject-PR-Message"  => "closed $ref",
530               "X-$gProject-PR-Package"  => $data->{package},
531               "X-$gProject-PR-Keywords" => $data->{keywords},
532               # Only have a X-$gProject-PR-Source when we know the source package
533               (defined($source_package) and length($source_package))?("X-$gProject-PR-Source" => $source_package):(),
534               "Reply-To"                => "$ref\@$gEmailDomain",
535               "Content-Type"            => 'text/plain; charset="utf-8"',
536              ],message_body_template('mail/process_mark_as_done',
537                                      {date => $header{date},
538                                       messageid => $header{'message-id'},
539                                       subject   => $header{subject},
540                                       data      => $data,
541                                      },
542                                     ),
543              [$orig_report,join("\n",@msg)]),'',[$replyto,@generalbcc,@noticecc],1);
544             &htmllog("Notification","sent",$data->{originator},
545                 "$gBug acknowledged by developer.");
546             &sendmessage(create_mime_message(
547              [@common_headers,
548               From          => "$gMaintainerEmail ($gProject $gBug Tracking System)",
549               To            => "$data->{originator}",
550               Subject       => "$gBug#$ref closed by $markedby ($header{'subject'})",
551               "Message-ID"  => "<handler.$ref.$nn.notifdone\@$gEmailDomain>",
552               (defined $data->{msgid})?("In-Reply-To" => $data->{msgid}):(),
553               References    => join(' ',grep {defined $_} ($header{'message-id'},$data->{msgid},'')),
554               "X-$gProject-PR-Message"  => "they-closed $ref",
555               (defined $data->{package})?("X-$gProject-PR-Package"  => $data->{package}):(),
556               (defined $data->{keywords})?("X-$gProject-PR-Keywords" => $data->{keywords}):(),
557               # Only have a X-$gProject-PR-Source when we know the source package
558               (defined($source_package) and length($source_package))?("X-$gProject-PR-Source" => $source_package):(),
559               "Reply-To"                => "$ref\@$gEmailDomain",
560               "Content-Type"            => 'text/plain; charset="utf-8"',
561              ],message_body_template('mail/process_your_bug_done',
562                                      {data      => $data,
563                                       markedby  => $markedby,
564                                       messageid => $header{'message-id'},
565                                       subject   => $header{subject},
566                                      },
567                                     ),
568              [join("\n",@msg),$orig_report]),'',undef,1);
569         }
570         appendlog($ref,$msg);
571     }
572     finish();
573 }
574
575 if ($ref<0) { # new bug report
576     if ($codeletter eq 'U') { # -submitter
577         &sendmessage(create_mime_message(
578           [@common_headers,
579            From          => "$gMaintainerEmail ($gProject $gBug Tracking System)",
580            To            => $replyto,
581            Subject       => "Message with no $gBug number cannot be sent to submitter! ($subject)",
582            'Message-ID'  => "<handler.x.$nn.nonumnosub\@$gEmailDomain>",
583            'In-Reply-To' => $header{'message-id'},
584            References    => join(' ',grep {defined $_} $header{'message-id'},$data->{msgid}),
585            Precedence    => 'bulk',
586            "X-$gProject-PR-Message" => 'error',
587           ],message_body_template('mail/process_no_bug_number',
588                                   {subject => $subject,
589                                    date    => $header{date},
590                                    markaswhat => 'submitter',
591                                    receivedat => "$baddress\@$gEmailDomain",
592                                    messageid => $header{'message-id'},
593                                   },
594                                  )),'');
595         appendlog($ref,$msg);
596         finish();
597     }
598
599     $data->{found_versions} = [];
600     $data->{fixed_versions} = [];
601
602     if (defined $pheader{source}) {
603         # source packages are identified by the src: prefix
604         $data->{package} = $pheader{source};
605         $data->{package} =~ s/(^|,\s*)/${1}src:/g;
606     } elsif (defined $pheader{package}) {
607         $data->{package} = $pheader{package};
608         if ($data->{package} =~ /^src:(.+)/) {
609             $pheader{source} = $1;
610         }
611     } elsif (defined $config{default_package}) {
612         $data->{package} = $config{default_package},
613     }
614     else {
615         my $body = message_body_template('mail/process_no_package',
616                                         );
617         &sendmessage(create_mime_message(
618                        [@common_headers,
619                         From          => "$gMaintainerEmail ($gProject $gBug Tracking System)",
620                         To            => $replyto,
621                         Subject       => "Message with no Package: tag cannot be processed! ($subject)",
622                         "Message-ID"  => "<handler.x.$nn.nonumnosub\@$gEmailDomain>",
623                         "In-Reply-To" => $header{'message-id'},
624                         References    => join(' ',grep {defined $_} $header{'message-id'},$data->{msgid}),
625                         Precedence    => 'bulk',
626                         "X-$gProject-PR-Message" => 'error'
627                        ],
628            message_body_template('mail/process_no_package',
629                                  {date => $header{date},
630                                   subject => $subject,
631                                   messageid => $header{'message-id'},
632                                   baddress => $baddress,
633                                  },
634                                 ),[join("\n", @msg)]), '',undef,1);
635         appendlog($ref,$msg);
636         finish();
637     }
638
639     if (defined $config{default_package}) {
640          &checkmaintainers;
641          # if there are no maintainers for this package, assign it to the default package
642          if (not @maintaddrs) {
643               $data->{package} = $config{default_package};
644               $brokenness.= fill_template('mail/process_default_package_selected',
645                                           {old_package => $pheader{source} || $pheader{package} || 'No package',
646                                            new_package => $data->{package},
647                                           }
648                                          );
649               # force the maintainers to be rechecked
650               $maintainerschecked = 0;
651               &checkmaintainers;
652          }
653     }
654
655     $data->{keywords}= '';
656     if (defined($pheader{'keywords'})) {
657         $data->{keywords}= $pheader{'keywords'};
658     } elsif (defined($pheader{'tags'})) {
659         $data->{keywords}= $pheader{'tags'};
660     }
661     if (length($data->{keywords})) {
662         my @kws;
663         my %gkws = map { ($_, 1) } @gTags;
664         foreach my $kw (sort split(/[,\s]+/, lc($data->{keywords}))) {
665             push @kws, $kw if (defined $gkws{$kw});
666         }
667         $data->{keywords} = join(" ", @kws);
668     }
669     $data->{severity}= '';
670     if (defined($pheader{'severity'}) || defined($pheader{'priority'})) {
671         $data->{severity}= $pheader{'severity'};
672         $data->{severity}= $pheader{'priority'} unless ($data->{severity});
673         $data->{severity} =~ s/^\s*(.+)\s*$/$1/;
674
675         if (!grep($_ eq $data->{severity}, @gSeverityList, "$gDefaultSeverity")) {
676             $brokenness.= fill_template('mail/invalid_severity',
677                                         {severity=>$data->{severity}}
678                                        );
679             $data->{severity}= '';
680         }
681     }
682     if (defined($pheader{owner})) {
683         $data->{owner}= $pheader{owner};
684     }
685     if (defined($pheader{forwarded})) {
686         $data->{forwarded} = $pheader{forwarded};
687     }
688     $ref = new_bug();
689     $newref = $ref;
690     my $hash = get_hashname($ref);
691     $data->{originator} = $replyto;
692     $data->{date} = $intdate;
693     $data->{subject} = $subject;
694     $data->{msgid} = $header{'message-id'};
695     writebug($ref, $data);
696     # Deal with usertags
697     if (exists $pheader{usertags}) {
698          my $user = $replyto;
699          $user = $pheader{user} if exists $pheader{user};
700          $user =~ s/,.*//;
701          $user =~ s/^.*<(.*)>.*$/$1/;
702          $user =~ s/[(].*[)]//;
703          $user =~ s/^\s*(\S+)\s+.*$/$1/;
704          if ($user ne '' and Debbugs::User::is_valid_user($user)) {
705               $pheader{usertags} =~ s/(?:^\s+|\s+$)//g;
706               my %user_tags;
707               read_usertags(\%user_tags,$user);
708               for my $tag (split /[,\s]+/, $pheader{usertags}) {
709                    if ($tag =~ /^[a-zA-Z0-9.+\@-]+/) {
710                         my %bugs_with_tag; 
711                         @bugs_with_tag{@{$user_tags{$tag}||[]}} = (1) x @{$user_tags{$tag}||[]};
712                         $bugs_with_tag{$ref} = 1;
713                         $user_tags{$tag} = [keys %bugs_with_tag];
714                    }
715               }
716               write_usertags(\%user_tags,$user);
717          }
718          else {
719               $brokenness .= fill_template('mail/invalid_user',
720                                            {user => $user}
721                                           );
722          }
723     }
724     overwritefile("db-h/$hash/$ref.report",
725                   map {"$_\n"} @msg);
726 }
727
728 &checkmaintainers;
729
730 print {$debugfh} "maintainers >".join(' ',@maintaddrs)."<\n";
731
732 my $orgsender= defined($header{'sender'}) ? "Original-Sender: $header{'sender'}\n" : '';
733 my $newsubject= $subject;  $newsubject =~ s/^$gBug#$ref:*\s*//;
734
735 my $xcchdr= $header{ 'x-debbugs-cc' } || '';
736 if ($xcchdr =~ m/\S/) {
737     push(@resentccs,get_addresses($xcchdr));
738     $resentccexplain.= fill_template('mail/xdebbugscc',
739                                      {xcchdr => $xcchdr},
740                                     );
741 }
742
743 if (@maintaddrs && ($codeletter eq 'B' || $codeletter eq 'M')) {
744     push(@resentccs,@maintaddrs);
745     $resentccexplain.= fill_template('mail/maintainercc',
746                                      {maintaddrs => \@maintaddrs,
747                                      },
748                                     );
749 }
750
751 @bccs = @addsrcaddrs;
752 if (defined $gStrongList and isstrongseverity($data->{severity})) {
753     push @bccs, "$gStrongList\@$gListDomain";
754 }
755
756 # Send mail to the per bug list subscription too
757 if (defined $config{bug_subscription_domain} and length $config{bug_subscription_domain}) {
758     push @bccs, "bugs=$ref\@$config{bug_subscription_domain}";
759 }
760
761 if (defined $pheader{source}) {
762     # Prefix source versions with the name of the source package. They
763     # appear that way in version trees so that we can deal with binary
764     # packages moving from one source package to another.
765     if (defined $pheader{'source-version'}) {
766          if ($pheader{'source-version'} !~ m/^$config{package_version_re}$/) {
767               $brokenness .= fill_template('mail/invalid_version',
768                                            {version => $pheader{'source-version'}},
769                                           );
770          }
771          else {
772               addfoundversions($data, $pheader{source}, $pheader{'source-version'}, '');
773          }
774     } elsif (defined $pheader{version}) {
775          if ($pheader{version} !~ m/^$config{package_version_re}$/) {
776               $brokenness .= fill_template('mail/invalid_version',
777                                            {version => $pheader{version}},
778                                           );
779          }
780          else {
781               addfoundversions($data, $pheader{source}, $pheader{version}, '');
782          }
783     }
784     writebug($ref, $data);
785 } elsif (defined $pheader{package}) {
786     # TODO: could handle Source-Version: by looking up the source package?
787      if (defined $pheader{version}) {
788           if ($pheader{version} !~ m/^$config{package_version_re}$/) {
789                $brokenness .= fill_template('mail/invalid_version',
790                                             {version => $pheader{version}},
791                                            );
792           }
793           else {
794                addfoundversions($data, $pheader{package}, $pheader{version}, 'binary');
795           }
796      }
797      writebug($ref, $data);
798 }
799
800 my $veryquiet= $codeletter eq 'Q';
801 if ($codeletter eq 'M' && !@maintaddrs) {
802     $veryquiet= 1;
803     $brokenness.= fill_template('mail/invalid_maintainer',
804                                 {},
805                                );
806 }
807
808 my $resentccval.= join(', ',@resentccs);
809 $resentccval =~ s/\s+\n\s+/ /g; $resentccval =~ s/^\s+/ /; $resentccval =~ s/\s+$//;
810 my $resentcc = '';
811 if (length($resentccval)) { 
812     $resentcc= "Resent-CC: $resentccval\n"; 
813 }
814
815 my $common_headers='';
816 {
817     my @tmp = @common_headers;
818     while (my ($key,$value) = splice(@tmp, 0,2)) {
819         $common_headers .= qq($key: $value\n);
820     }
821 }
822 if ($codeletter eq 'U') { # sent to -submitter
823     &htmllog("Message", "sent on", $data->{originator}, "$gBug#$ref.");
824     my $enc_msg=<<END;
825 Subject: $gBug#$ref: $newsubject
826 Reply-To: $replyto, $ref-quiet\@$gEmailDomain
827 ${orgsender}Resent-To: $data->{originator}
828 ${resentcc}${common_headers}Resent-Date: $tdate
829 Resent-Message-ID: <handler.$ref.$nn\@$gEmailDomain>
830 Resent-Sender: $gMaintainerEmail
831 X-$gProject-PR-Message: report $ref
832 X-$gProject-PR-Package: $data->{package}
833 X-$gProject-PR-Keywords: $data->{keywords}
834 ${source_pr_header}
835 END
836     chomp $enc_msg;
837     $enc_msg = encode_utf8($enc_msg).$fwd."\n";
838     &sendmessage($enc_msg,[$data->{originator},@resentccs],[@bccs]);
839 } elsif ($codeletter eq 'B') { # Sent to submit
840     my $report_followup = $newref ? 'report' : 'followup';
841     &htmllog($newref ? "Report" : "Information", "forwarded",
842              join(', ',"$gSubmitList\@$gListDomain",@resentccs),
843              "<code>$gBug#$ref</code>".
844              (length($data->{package})? "; Package <code>".html_escape($data->{package})."</code>" : '').
845              ".");
846     my $enc_msg=<<END;
847 Subject: $gBug#$ref: $newsubject
848 Reply-To: $replyto, $ref\@$gEmailDomain
849 Resent-From: $header{'from'}
850 ${orgsender}Resent-To: $gSubmitList\@$gListDomain
851 ${resentcc}${common_headers}Resent-Date: $tdate
852 Resent-Message-ID: <handler.$ref.$nn\@$gEmailDomain>
853 Resent-Sender: $gMaintainerEmail
854 X-$gProject-PR-Message: $report_followup $ref
855 X-$gProject-PR-Package: $data->{package}
856 X-$gProject-PR-Keywords: $data->{keywords}
857 ${source_pr_header}
858 END
859     chomp $enc_msg;
860     $enc_msg = encode_utf8($enc_msg).$fwd."\n";
861     &sendmessage($enc_msg,["$gSubmitList\@$gListDomain",@resentccs],[@bccs]);
862 } elsif (@resentccs or @bccs) { # Quiet or Maintainer
863     # D and F done far earlier; B just done - so this must be M or Q
864     # We preserve whichever it was in the Reply-To (possibly adding
865     # the $gBug#).
866     my $report_followup = $newref ? 'report' : 'followup';
867     if (@resentccs) {
868         &htmllog($newref ? "Report" : "Information", "forwarded",
869                  $resentccval,
870                  "<code>$gBug#$ref</code>".
871                  (length($data->{package}) ? "; Package <code>".html_escape($data->{package})."</code>" : '').
872                  ".");
873     } else {
874         &htmllog($newref ? "Report" : "Information", "stored",
875                  "",
876                  "<code>$gBug#$ref</code>".
877                  (length($data->{package}) ? "; Package <code>".html_escape($data->{package})."</code>" : '').
878                  ".");
879     }
880     my $enc_msg=<<END;
881 Subject: $gBug#$ref: $newsubject
882 Reply-To: $replyto, $ref-$baddressroot\@$gEmailDomain
883 Resent-From: $header{'from'}
884 ${orgsender}Resent-To: $resentccval
885 Resent-Date: $tdate
886 Resent-Message-ID: <handler.$ref.$nn\@$gEmailDomain>
887 Resent-Sender: $gMaintainerEmail
888 ${common_headers}X-$gProject-PR-Message: $report_followup $ref
889 X-$gProject-PR-Package: $data->{package}
890 X-$gProject-PR-Keywords: $data->{keywords}
891 ${source_pr_header}
892 END
893     chomp $enc_msg;
894     $enc_msg = encode_utf8($enc_msg).$fwd."\n";
895     &sendmessage($enc_msg,[@resentccs],[@bccs]);
896 }
897
898 my $htmlbreak= length($brokenness) ? "<p>\n".html_escape($brokenness)."\n<p>\n" : '';
899 $htmlbreak =~ s/\n\n/\n<P>\n\n/g;
900 if (length($resentccval)) {
901     $htmlbreak = "  Copy sent to <code>".html_escape($resentccval)."</code>.".
902         $htmlbreak;
903 }
904
905 # Should we send an ack out?
906 if (not exists $header{'x-debbugs-no-ack'} and
907     ($newref or
908      ($codeletter ne 'U' and
909       (not defined $header{precedence} or
910        $header{'precedence'} !~ /\b(?:bulk|junk|list)\b/
911       )
912      )
913     )
914    ){
915
916      # figure out forward explanation
917      my $forwardexplain = '';
918      my $thanks = '';
919      my $extra_vars;
920      # will contain info and -info in moreinfo messages
921      my $info = '';
922      my $infod = '';
923      # temporary headers
924      my %t_h;
925      if ($newref) {
926           &htmllog("Acknowledgement","sent",$replyto,
927                    ($veryquiet ?
928                     "New $gBug report received and filed, but not forwarded." :
929                     "New $gBug report received and forwarded."). $htmlbreak);
930           $thanks = fill_template('mail/process_ack_thanks_new');
931      }
932      else {
933           &htmllog("Acknowledgement","sent",$replyto,
934                    ($veryquiet ? "Extra info received and filed, but not forwarded." :
935                     $codeletter eq 'M' ? "Extra info received and forwarded to maintainer." :
936                     "Extra info received and forwarded to list."). $htmlbreak);
937           $thanks = fill_template('mail/process_ack_thanks_additional');
938           $info = 'info';
939           $infod = '-info';
940      }
941      if ($veryquiet) {
942           $forwardexplain = fill_template('mail/forward_veryquiet',
943                                          );
944           # these are the headers that quiet messages override
945           $t_h{messageid}  = "<handler.$ref.$nn.ack${info}quiet\@$gEmailDomain>";
946           $t_h{pr_message} = "ack${infod}-quiet $ref";
947           $t_h{reply_to}   = "$ref-quiet\@$gEmailDomain";
948           $extra_vars->{refreplyto} = "$ref-quiet\@$gEmailDomain";
949           $t_h{subject}    = length($info)?
950                "$gBug#$ref: Info received and FILED only ($subject)":
951                "$gBug#$ref: Acknowledgement of QUIET report ($subject)";
952      }
953      elsif ($codeletter eq 'M') {
954           $forwardexplain = fill_template('mail/forward_maintonly',
955                                          );
956           # these are the headers that maintonly messages override
957           $t_h{messageid}  = "<handler.$ref.$nn.ack{$info}maintonly\@$gEmailDomain>";
958           $t_h{pr_message} = "ack${infod}-maintonly $ref";
959           $t_h{reply_to}   = "$ref-maintonly\@$gEmailDomain";
960           $extra_vars->{refreplyto} = "$ref-maintonly\@$gEmailDomain";
961           $t_h{subject}    = length($info)?
962                "$gBug#$ref: Info received for maintainer only ($subject)":
963                "$gBug#$ref: Acknowledgement of maintainer-only report ($subject)";
964      }
965      else {
966           $forwardexplain = fill_template('mail/forward_normal',
967                                          );
968           $t_h{messageid}  = "<handler.$ref.$nn.ack${info}\@$gEmailDomain>";
969           $t_h{pr_message} = "ack${infod} $ref";
970           $t_h{reply_to}   = "$ref\@$gEmailDomain";
971           $extra_vars->{refreplyto} = "$ref\@$gEmailDomain";
972           $t_h{subject}    = (defined $info and length($info))?
973                "$gBug#$ref: Info received ($subject)" :
974                "$gBug#$ref: Acknowledgement ($subject)";
975      }
976      my $body = message_body_template('mail/process_ack',
977                                       {forwardexplain  => $forwardexplain,
978                                        resentccexplain => $resentccexplain,
979                                        thanks          => $thanks,
980                                        %{$extra_vars}
981                                       }
982                                      );
983      &sendmessage(create_mime_message(
984                        [@common_headers,
985                         From          => "$gMaintainerEmail ($gProject $gBug Tracking System)",
986                         To            => $replyto,
987                         Subject       => $t_h{subject},
988                         "Message-ID"  => $t_h{messageid},
989                         "In-Reply-To" => $header{'message-id'},
990                         References    => $header{'message-id'},
991                         Precedence    => 'bulk',
992                         "X-$gProject-PR-Message"  => $t_h{pr_message} || "ack $ref",
993                         "X-$gProject-PR-Package"  => $data->{package},
994                         "X-$gProject-PR-Keywords" => $data->{keywords},
995                         # Only have a X-$gProject-PR-Source when we know the source package
996                         (defined($source_package) and length($source_package))?("X-$gProject-PR-Source" => $source_package):(),
997                         "Reply-To"                => $t_h{reply_to} || "$ref\@$gEmailDomain",
998                        ],$body,[]), '',undef,1);
999 }
1000
1001 appendlog($ref,$msg);
1002 # unlock the locks we have received
1003 while ($locks--) {unfilelock();}
1004
1005 ## handle control messages at this point, immediately before finishing
1006 my %clonebugs = (-1 => $ref);
1007 my %bug_affected;
1008 if (@control_bits) {
1009     my $transcript_scalar = '';
1010     open my $transcript, ">:scalar:utf8", \$transcript_scalar or
1011         die "Unable to create transcript scalar: $!";
1012     print {$transcript} "Processing control commands:\n\n";
1013     my %affected_packages;
1014     my %recipients;
1015     # this is the hashref which is passed to all control calls
1016     my %limit = ();
1017     my $errors = 0;
1018     my $unknowns = 0;
1019
1020     my @common_control_options =
1021         (transcript        => $transcript,
1022          requester         => $header{from},
1023          request_addr      => $baddress.'@'.$config{email_domain},
1024          request_msgid     => $header{'message-id'},
1025          request_subject   => $header{subject},
1026          request_nn        => $nn,
1027          request_replyto   => $replyto,
1028          message           => [$msg],
1029          affected_bugs     => \%bug_affected,
1030          affected_packages => \%affected_packages,
1031          recipients        => \%recipients,
1032          limit             => \%limit,
1033         );
1034     if (@gExcludeFromControl and grep {$replyto =~ m/\Q$_\E/} @gExcludeFromControl) {
1035         print {$transcript} fill_template('mail/excluded_from_control');
1036         print {$transcript} "Stopping processing here.\n\n";
1037     } else {
1038         for my $control_bit (@control_bits) {
1039             $control_bit =~ s/\xef\xbb\xbf//g;
1040             next unless $control_bit =~ m/\S/;
1041             eval {
1042                 my $temp = decode("utf8",$control_bit,Encode::FB_CROAK);
1043                 $control_bit = $temp;
1044             };
1045             print {$transcript} "> $control_bit\n";
1046             next if $control_bit =~ /^\s*\#/;
1047             my $action = '';
1048             my $ok;
1049             if (defined valid_control($control_bit)) {
1050                 my ($new_errors,$terminate_control) =
1051                     control_line(line => $control_bit,
1052                                  clonebugs => \%clonebugs,
1053                                  limit => \%limit,
1054                                  common_control_options => \@common_control_options,
1055                                  errors => \$errors,
1056                                  transcript => $transcript,
1057                                  debug => 0,
1058                                  ok => \$ok,
1059                                  replyto => $replyto,
1060                                 );
1061                 if ($terminate_control) {
1062                     last;
1063                 }
1064             }
1065             else {
1066                 print {$transcript} "Unknown command or malformed arguments to command.\n\n";
1067                 $errors++;
1068                 if (++$unknowns >= 5) {
1069                     print {$transcript} "Too many unknown commands, stopping here.\n\n";
1070                     last;
1071                 }
1072             }
1073         }
1074     }
1075     my $temp_transcript = $transcript_scalar;
1076     eval{
1077         $temp_transcript = decode("utf8",$temp_transcript,Encode::FB_CROAK);
1078     };
1079     my @maintccs = determine_recipients(recipients => \%recipients,
1080                                         address_only => 1,
1081                                         cc => 1,
1082                                        );
1083     my $error_text = $errors > 0 ? " (with $errors error" . ($errors > 1 ? "s" : "") . ")" : "";
1084     my $reply =
1085         create_mime_message(['X-Loop'      => $gMaintainerEmail,
1086                              From          => "$gMaintainerEmail ($gProject $gBug Tracking System)",
1087                              To            => $replyto,
1088                              @maintccs ? (Cc => join(', ',@maintccs)):(),
1089                              Subject       => "Processed${error_text}: $header{subject}",
1090                              'Message-ID'  => "<handler.s.$nn.transcript\@$gEmailDomain>",
1091                              'In-Reply-To' => $header{'message-id'},
1092                              References    => join(' ',grep {defined $_} $header{'message-id'},$data->{msgid}),
1093                              Precedence    => 'bulk',
1094                              keys %affected_packages ?("X-${gProject}-PR-Package" => join(' ',keys %affected_packages)):(),
1095                              keys %affected_packages ?("X-${gProject}-PR-Source" =>
1096                                                        join(' ',
1097                                                             map {defined $_ ?(ref($_)?@{$_}:$_):()}
1098                                                             binary_to_source(binary => [keys %affected_packages],
1099                                                                              source_only => 1))):(),
1100                              "X-$gProject-PR-Message" => 'transcript',
1101                              @common_headers,
1102                             ],
1103                             fill_template('mail/message_body',
1104                                           {body => $temp_transcript},
1105                                          ));
1106
1107     utime(time,time,"db-h");
1108
1109     send_mail_message(message => $reply,
1110                       recipients => [exists $header{'x-debbugs-no-ack'}?():$replyto,
1111                                      make_list(values %{{determine_recipients(recipients => \%recipients,
1112                                                                               address_only => 1,
1113                                                                              )}}
1114                                               ),
1115                                     ]
1116                      );
1117
1118 }
1119
1120
1121 finish();
1122
1123 sub appendlog {
1124     my ($ref,$msg) = @_;
1125     my $log_location = buglog($ref);
1126     die "Unable to find .log for $ref"
1127         if not defined $log_location;
1128     my $logfh = IO::File->new(">>$log_location") or
1129         die "Unable to open $log_location for appending: $!";
1130     write_log_records(logfh => $logfh,
1131                       records => [{type => 'incoming-recv',
1132                                    text => $msg,
1133                                   }]);
1134     close ($logfh) or die "Unable to close $log_location: $!";
1135 }
1136
1137 sub finish {
1138     my ($exit) = @_;
1139     $exit ||= 0;
1140     utime(time,time,"db");
1141     # cleanups are run in an end block now.
1142     #my ($u);
1143     #while ($u= $cleanups[$#cleanups]) { &$u; }
1144     unlink("incoming/P$nn") || die "unlinking incoming/P$nn: $!";
1145     exit $exit;
1146 }
1147
1148 die "wot no exit";
1149
1150 sub htmllog {
1151     my ($whatobj,$whatverb,$where,$desc) = @_;
1152     append_action_to_log(bug => $ref,
1153                          action => "$whatobj $whatverb",
1154                          requester => '',
1155                          request_addr => $where,
1156                          desc         => $desc,
1157                          get_lock     => 0,
1158                         );
1159 }
1160
1161 sub stripbccs {
1162     my $msg = shift;
1163     my $ret = '';
1164     my $bcc = 0;
1165     while ($msg =~ s/(.*\n)//) {
1166         local $_ = $1;
1167         if (/^$/) {
1168             $ret .= $_;
1169             last;
1170         }
1171         if ($bcc) {
1172             # strip continuation lines too
1173             next if /^\s/;
1174             $bcc = 0;
1175         }
1176         if (/^Bcc:/i) {
1177             $bcc = 1;
1178         } else {
1179             $ret .= $_;
1180         }
1181     }
1182     return $ret . $msg;
1183 }
1184
1185 =head2 send_message
1186
1187      send_message($the_message,\@recipients,\@bcc,$do_not_encode)
1188
1189 The first argument is the scalar message, the second argument is the
1190 arrayref of recipients, the third is the arrayref of Bcc:'ed
1191 recipients.
1192
1193 The final argument turns off header encoding and the addition of the
1194 X-Loop header if true, defaults to false.
1195
1196 =cut
1197
1198
1199 sub sendmessage {
1200     my ($msg,$recips,$bcc,$no_encode) = @_;
1201     if (not defined $recips or (!ref($recips) && $recips eq '')
1202         or @$recips == 0) {
1203         $recips = ['-t'];
1204     }
1205     # This is suboptimal. The right solution is to send headers
1206     # separately from the rest of the message and encode them rather
1207     # than doing this.
1208     $msg = "X-Loop: $gMaintainerEmail\n" . $msg unless $no_encode;
1209     # The original message received is written out in appendlog, so
1210     # before writing out the other messages we've sent out, we need to
1211     # RFC1522 encode the header.
1212     $msg = encode_headers($msg) unless $no_encode;
1213
1214     my $hash = get_hashname($ref);
1215     #save email to the log
1216     my $logfh = IO::File->new(">>db-h/${hash}/${ref}.log") or
1217         die "opening db-h/$hash/${ref}.log: $!";
1218     write_log_records(logfh => $logfh,
1219                       records => {text => stripbccs($msg),
1220                                   type => 'recips',
1221                                   recips => [map {encode_utf8($_)} @{$recips}],
1222                                  },
1223                      );
1224     if (ref($bcc)) {
1225         shift @$recips if $recips->[0] eq '-t';
1226         push @$recips, @$bcc;
1227     }
1228
1229     send_mail_message(message        => $msg,
1230                       # Because we encode the headers above, we do not want to encode them here
1231                       encode_headers => 0,
1232                       recipients     => $recips);
1233 }
1234
1235 =head2 message_body_template
1236
1237      message_body_template('mail/ack',{ref=>'foo'});
1238
1239 Creates a message body using a template
1240
1241 =cut
1242
1243 sub message_body_template{
1244      my ($template,$extra_var) = @_;
1245      $extra_var ||={};
1246      my $body = fill_template($template,$extra_var);
1247      return fill_template('mail/message_body',
1248                           {%{$extra_var},
1249                            body => $body,
1250                           },
1251                          );
1252 }
1253
1254 =head2 fill_template
1255
1256      fill_template('mail/foo',{foo=>'bar'});
1257
1258 Calls fill_in_template with a default set of variables and any extras
1259 added in.
1260
1261 =cut
1262
1263 sub fill_template{
1264      my ($template,$extra_var) = @_;
1265      $extra_var ||={};
1266      my $variables = {config => \%config,
1267                       defined($ref)?(ref    => $ref):(),
1268                       defined($data)?(data  => $data):(),
1269                       refs => [map {exists $clonebugs{$_}?$clonebugs{$_}:$_} keys %bug_affected],
1270                       %{$extra_var},
1271                      };
1272      my $hole_var = {'&bugurl' =>
1273                      sub{"$_[0]: ".
1274                               $config{cgi_domain}.'/'.
1275                                    Debbugs::CGI::bug_links(bug=>$_[0],
1276                                                            links_only => 1,
1277                                                           );
1278                     }
1279                     };
1280      return fill_in_template(template => $template,
1281                              variables => $variables,
1282                              hole_var  => $hole_var,
1283                             );
1284 }
1285
1286
1287 # this shole routine is *bad*; will be changed to use
1288 # Debbugs::Recipients and stuff therin in short order.
1289 sub checkmaintainers {
1290     return if $maintainerschecked++;
1291     return if !length($data->{package});
1292
1293     my $anymaintfound=0; my $anymaintnotfound=0;
1294     for my $p (splitpackages($data->{package})) {
1295         $p =~ y/A-Z/a-z/;
1296         $p =~ /((?:src:)?[a-z0-9.+-]+)/;
1297         $p = $1;
1298         next unless defined $p;
1299         if (defined $config{subscription_domain} and length $config{subscription_domain}) {
1300             my @source = binary_to_source(binary => $p,
1301                                           source_only => 1,
1302                                          );
1303             if (@source) {
1304                 push @addsrcaddrs,
1305                     map {"$_\@$config{subscription_domain}"} @source;
1306             } else {
1307                 push @addsrcaddrs, "$p\@$config{subscription_domain}";
1308             }
1309         }
1310         # this is utter hackery until we switch to Debbugs::Recipients
1311         my @maints = package_maintainer(binary => $p);
1312         if (@maints) {
1313             print {$debugfh} "maintainer add >$p|".join(',',@maints)."<\n";
1314             my %temp;
1315             @temp{@maintaddrs} = @maintaddrs;
1316             push(@maintaddrs,
1317                  grep {$_ ne $replyto and
1318                            not exists $temp{$_}} @maints);
1319             $anymaintfound++;
1320         } else {
1321             print {$debugfh} "maintainer none >$p<\n";
1322             push(@maintaddrs,$gUnknownMaintainerEmail) unless $anymaintnotfound;
1323             $anymaintnotfound++;
1324             last;
1325         }
1326     }
1327
1328     if (defined $data->{owner} and length $data->{owner}) {
1329         print {$debugfh} "owner add >$data->{package}|$data->{owner}<\n";
1330         my $addmaint = $data->{owner};
1331         push(@maintaddrs, $addmaint) unless
1332             $addmaint eq $replyto or grep($_ eq $addmaint, @maintaddrs);
1333     }
1334 }
1335
1336 =head2 bug_list_forward
1337
1338      bug_list_forward($spool_filename) if $codeletter eq 'L';
1339
1340
1341 Given the spool file, will forward a bug to the per bug mailing list
1342 subscription system.
1343
1344 =cut
1345
1346 sub bug_list_forward{
1347      my ($bug_fn) = @_;
1348      # Read the bug information and package information for passing to
1349      # the mailing list
1350      my $bug_fh = IO::File->new("incoming/P$bug_fn",'r') or
1351           die "Unable to open incoming/P$bug_fn $!";
1352
1353      if (not defined $config{bug_subscription_domain} or not
1354          length $config{bug_subscription_domain}) {
1355           unlink("incoming/P$bug_fn") or
1356                die "unlinking incoming/P$bug_fn: $!";
1357           exit 0;
1358      }
1359
1360      my ($bug_number) = $bug_fn =~ /^L(\d+)\./;
1361      my $data = read_bug(bug => $bug_number);
1362
1363      local $/ = undef;
1364      my $bug_message = <$bug_fh>;
1365      my ($bug_address) = $bug_message =~ /^Received: \(at ([^\)]+)\) by/;
1366      my ($envelope_from) = $bug_message =~ s/\nFrom\s+([^\s]+)[^\n]+\n/\n/;
1367      if (not defined $envelope_from) {
1368           # Try to use the From: header or something to set it 
1369           ($envelope_from) = $bug_message =~ /\nFrom:\s+(.+?)\n/;
1370           # Kludgy, and should really be using a full scale header
1371           # parser to do this.
1372           $envelope_from =~ s/^.+?<([^>]+)>.+$/$1/;
1373      }
1374      my ($header,$body) = split /\n\n/, $bug_message, 2;
1375      # Add X-$gProject-PR-Message: list bug_number, package name, and bug title headers
1376      $header .= qq(\nX-$gProject-PR-Message: list $bug_number\n).
1377           qq(X-$gProject-PR-Package: $data->{package}\n).
1378                qq(X-$gProject-PR-Title: $data->{subject})
1379                if defined $data;
1380      print STDERR "Tried to loop me with $envelope_from\n"
1381           and exit 1 if $envelope_from =~ /\Q$gListDomain\E|\Q$gEmailDomain\E/;
1382      print {$debugfh} $envelope_from,qq(\n);
1383      # If we don't have a bug address, something has gone horribly wrong.
1384      print STDERR "Doesn't match: $bug_address\n" and exit 1 unless defined $bug_address;
1385      $bug_address =~ s/\@.+//;
1386      print {$debugfh} "Sending message to bugs=$bug_address\@$config{bug_subscription_domain}\n";
1387      print {$debugfh} $header.qq(\n\n).$body;
1388      send_mail_message(message        => $header.qq(\n\n).$body,
1389                        recipients     => ["bugs=$bug_address\@$config{bug_subscription_domain}"],
1390                        envelope_from  => $envelope_from,
1391                        encode_headers => 0,
1392                       );
1393      unlink("incoming/P$bug_fn") || die "unlinking incoming/P$bug_fn: $!";
1394      exit 0;
1395 }