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