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