]> git.donarmstrong.com Git - debbugs.git/blob - scripts/service.in
merge changes from dla source tree
[debbugs.git] / scripts / service.in
1 #!/usr/bin/perl
2 # $Id: service.in,v 1.118 2005/10/19 01:22:14 don Exp $
3 #
4 # Usage: service <code>.nn
5 # Temps:  incoming/P<code>.nn
6
7 use File::Copy;
8 use MIME::Parser;
9 use Debbugs::MIME qw(decode_rfc1522 encode_rfc1522);
10 use Debbugs::Mail qw(send_mail_message);
11 use Debbugs::User;
12 use HTML::Entities qw(encode_entities);
13
14 use Debbugs::Config qw(:globals :config);
15 use Debbugs::CGI qw(html_escape);
16 $lib_path = $gLibPath;
17 require "$lib_path/errorlib";
18 $ENV{'PATH'} = $lib_path.':'.$ENV{'PATH'};
19
20 chdir("$gSpoolDir") || die "chdir spool: $!\n";
21
22 # open(DEBUG,">&4");
23 open DEBUG, ">/dev/null";
24 $debug = 0;
25 umask(002);
26
27 $_=shift;
28 m/^[RC]\.\d+$/ || &quit("bad argument");
29 $control= m/C/;
30 $nn= $_;
31 if (!rename("incoming/G$nn","incoming/P$nn")) {
32     $_=$!.'';  m/no such file or directory/i && exit 0;
33     &quit("renaming to lock: $!");
34 }    
35
36 open(M,"incoming/P$nn");
37 @log=<M>;
38 @msg=@log;
39 close(M);
40
41 chomp @msg;
42
43 print "###\n",join("##\n",@msg),"\n###\n" if $debug;
44
45 my $parser = new MIME::Parser;
46 mkdir "$gSpoolDir/mime.tmp", 0777;
47 $parser->output_under("$gSpoolDir/mime.tmp");
48 my $entity = eval { $parser->parse_data(join('',@log)) };
49
50 # header and decoded body respectively
51 my (@headerlines, @bodylines);
52 # Bug numbers to send e-mail to, hash so that we don't send to the
53 # same bug twice.
54 my (%bug_affected);
55
56 if ($entity and $entity->head->tags) {
57     @headerlines = @{$entity->head->header};
58     chomp @headerlines;
59
60     my $entity_body = getmailbody($entity);
61     @bodylines = $entity_body ? $entity_body->as_lines() : ();
62     chomp @bodylines;
63 } else {
64     # Legacy pre-MIME code, kept around in case MIME::Parser fails.
65     my $i;
66     for ($i = 0; $i <= $#msg; $i++) {
67         $_ = $msg[$i];
68         last unless length($_);
69         while ($msg[$i+1] =~ m/^\s/) {
70             $i++;
71             $_ .= "\n".$msg[$i];
72         }
73         push @headerlines, $_;
74     }
75
76     @bodylines = @msg[$i..$#msg];
77 }
78
79 for (@headerlines) {
80     $_ = decode_rfc1522($_);
81     s/\n\s/ /g;
82     print ">$_<\n" if $debug;
83     if (s/^(\S+):\s*//) {
84         my $v = lc $1;
85         print ">$v=$_<\n" if $debug;
86         $header{$v} = $_;
87     } else {
88         print "!>$_<\n" if $debug;
89     }
90 }
91
92 # Strip off RFC2440-style PGP clearsigning.
93 if (@bodylines and $bodylines[0] =~ /^-----BEGIN PGP SIGNED/) {
94     shift @bodylines while @bodylines and length $bodylines[0];
95     shift @bodylines while @bodylines and $bodylines[0] !~ /\S/;
96     for my $findsig (0 .. $#bodylines) {
97         if ($bodylines[$findsig] =~ /^-----BEGIN PGP SIGNATURE/) {
98             $#bodylines = $findsig - 1;
99             last;
100         }
101     }
102     map { s/^- // } @bodylines;
103 }
104
105 grep(s/\s+$//,@bodylines);
106
107 print "***\n",join("\n",@bodylines),"\n***\n" if $debug;
108
109 if (defined $header{'resent-from'} && !defined $header{'from'}) {
110     $header{'from'} = $header{'resent-from'};
111 }
112
113 defined($header{'from'}) || &quit("no From header");
114
115 delete $header{'reply-to'} 
116         if ( defined($header{'reply-to'}) && $header{'reply-to'} =~ m/^\s*$/ );
117
118 if ( defined($header{'reply-to'}) && $header{'reply-to'} ne "" ) {
119     $replyto = $header{'reply-to'};
120 } else {
121     $replyto = $header{'from'};
122 }
123
124 # This is an error counter which should be incremented every time there is an error.
125 my $errors = 0;
126 $controlrequestaddr= $control ? "control\@$gEmailDomain" : "request\@$gEmailDomain";
127 $transcript='';
128 &transcript("Processing commands for $controlrequestaddr:\n\n");
129
130 $dl= 0;
131 $state= 'idle';
132 $lowstate= 'idle';
133 $mergelowstate= 'idle';
134 $midix=0;    
135 $extras="";
136
137 my $user = $replyto;
138 $user =~ s/,.*//;
139 $user =~ s/^.*<(.*)>.*$/$1/;
140 $user =~ s/[(].*[)]//;
141 $user =~ s/^\s*(\S+)\s+.*$/$1/;
142 $user = "" unless (Debbugs::User::is_valid_user($user));
143 my $indicated_user = 0;
144
145 my $quickabort = 0;
146
147 my $fuckheads = "(" . join("|", @gExcludeFromControl) . ")";
148 if (@gExcludeFromControl and $replyto =~ m/$fuckheads/) {
149         &transcript("You have been specifically excluded from using the\ncontrol interface.\n\n");
150         &transcript("Have a nice day\n\n.");
151         $quickabort = 1;
152 }
153
154 my %limit_pkgs = ();
155 my %clonebugs = ();
156 my @bcc = ();
157
158 sub addbcc {
159     push @bcc, $_[0] unless grep { $_ eq $_[0] } @bcc;
160 }
161
162 for ($procline=0; $procline<=$#bodylines; $procline++) {
163     $state eq 'idle' || print "$state ?\n";
164     $lowstate eq 'idle' || print "$lowstate ?\n";
165     $mergelowstate eq 'idle' || print "$mergelowstate ?\n";
166     if ($quickabort) {
167          &transcript("Stopping processing here.\n\n");
168          last;
169     }
170     $_= $bodylines[$procline]; s/\s+$//;
171     next unless m/\S/;
172     &transcript("> $_\n");
173     next if m/^\s*\#/;
174     $action= '';
175     if (m/^stop\s*$/i || m/^quit\s*$/i || m/^--\s*$/ || m/^thank(?:s|\s*you)?\s*$/i || m/^kthxbye\s*$/i) {
176         &transcript("Stopping processing here.\n\n");
177         last;
178     } elsif (m/^debug\s+(\d+)$/i && $1 >= 0 && $1 <= 1000) {
179         $dl= $1+0;
180         &transcript("Debug level $dl.\n\n");
181     } elsif (m/^(send|get)\s+\#?(\d{2,})$/i) {
182         $ref= $2+0;
183         &sendlynxdoc("bugreport.cgi?bug=$ref","logs for $gBug#$ref");
184     } elsif (m/^send-detail\s+\#?(\d{2,})$/i) {
185         $ref= $1+0;
186         &sendlynxdoc("bugreport.cgi?bug=$ref&boring=yes",
187                      "detailed logs for $gBug#$ref");
188     } elsif (m/^index(\s+full)?$/i) {
189         &transcript("This BTS function is currently disabled, sorry.\n\n");
190         $errors++;
191         $ok++; # well, it's not really ok, but it fixes #81224 :)
192     } elsif (m/^index-summary\s+by-package$/i) {
193         &transcript("This BTS function is currently disabled, sorry.\n\n");
194         $errors++;
195         $ok++; # well, it's not really ok, but it fixes #81224 :)
196     } elsif (m/^index-summary(\s+by-number)?$/i) {
197         &transcript("This BTS function is currently disabled, sorry.\n\n");
198         $errors++;
199         $ok++; # well, it's not really ok, but it fixes #81224 :)
200     } elsif (m/^index(\s+|-)pack(age)?s?$/i) {
201         &sendlynxdoc("pkgindex.cgi?indexon=pkg",'index of packages');
202     } elsif (m/^index(\s+|-)maints?$/i) {
203         &sendlynxdoc("pkgindex.cgi?indexon=maint",'index of maintainers');
204     } elsif (m/^index(\s+|-)maint\s+(\S+)$/i) {
205         $maint = $2;
206         &sendlynxdoc("pkgreport.cgi?maint=" . urlsanit($maint),
207                      "$gBug list for maintainer \`$maint'");
208         $ok++;
209     } elsif (m/^index(\s+|-)pack(age)?s?\s+(\S.*\S)$/i) {
210         $package = $+;
211         &sendlynxdoc("pkgreport.cgi?pkg=" . urlsanit($package),
212                      "$gBug list for package $package");
213         $ok++;
214     } elsif (m/^send-unmatched(\s+this|\s+-?0)?$/i) {
215         &transcript("This BTS function is currently disabled, sorry.\n\n");
216         $errors++;
217         $ok++; # well, it's not really ok, but it fixes #81224 :)
218     } elsif (m/^send-unmatched\s+(last|-1)$/i) {
219         &transcript("This BTS function is currently disabled, sorry.\n\n");
220         $errors++;
221         $ok++; # well, it's not really ok, but it fixes #81224 :)
222     } elsif (m/^send-unmatched\s+(old|-2)$/i) {
223         &transcript("This BTS function is currently disabled, sorry.\n\n");
224         $errors++;
225         $ok++; # well, it's not really ok, but it fixes #81224 :)
226     } elsif (m/^getinfo\s+([\w-.]+)$/i) {
227         # the following is basically a Debian-specific kludge, but who cares
228         $req = $1;
229         if ($req =~ /^maintainers$/i && -f "$gConfigDir/Maintainers") {
230             &sendinfo("local", "$gConfigDir/Maintainers", "Maintainers file");
231         } elsif ($req =~ /^override\.(\w+)\.([\w-.]+)$/i) {
232             $req =~ s/.gz$//;
233             &sendinfo("ftp.d.o", "$req", "override file for $2 part of $1 distribution");
234         } elsif ($req =~ /^pseudo-packages\.(description|maintainers)$/i && -f "$gConfigDir/$req") {
235             &sendinfo("local", "$gConfigDir/$req", "$req file");
236         } else {
237             &transcript("Info file $req does not exist.\n\n");
238         }
239     } elsif (m/^help/i) {
240         &sendhelp;
241         &transcript("\n");
242         $ok++;
243     } elsif (m/^refcard/i) {
244         &sendtxthelp("bug-mailserver-refcard.txt","mail servers' reference card");
245     } elsif (m/^subscribe/i) {
246         &transcript(<<END);
247 There is no $gProject $gBug mailing list.  If you wish to review bug reports
248 please do so via http://$gWebDomain/ or ask this mail server
249 to send them to you.
250 soon: MAILINGLISTS_TEXT
251 END
252     } elsif (m/^unsubscribe/i) {
253         &transcript(<<END);
254 soon: UNSUBSCRIBE_TEXT
255 soon: MAILINGLISTS_TEXT
256 END
257     } elsif (m/^user\s+(\S+)\s*$/i) {
258         my $newuser = $1;
259         if (Debbugs::User::is_valid_user($newuser)) {
260             my $olduser = ($user ne "" ? " (was $user)" : "");
261             &transcript("Setting user to $newuser$olduser.\n");
262             $user = $newuser;
263             $indicated_user = 1;
264         } else {
265             &transcript("Selected user id ($newuser) invalid, sorry\n");
266             $errors++;
267             $user = "";
268             $indicated_user = 1;
269         }
270     } elsif (m/^usercategory\s+(\S+)(\s+\[hidden\])?\s*$/i) {
271         $ok++;
272         my $catname = $1;
273         my $hidden = ($2 ne "");
274
275         my $prefix = "";
276         my @cats;
277         my $bad = 0;
278         my $catsec = 0;
279         if ($user eq "") {
280             &transcript("No valid user selected\n");
281             $errors++;
282             next;
283         }
284         if (not $indicated_user and defined $user) {
285              &transcript("User is $user");
286              $indicated_user = 1;
287         }
288         while (++$procline <= $#bodylines) {
289             unless ($bodylines[$procline] =~ m/^\s*([*+])\s*(\S.*)$/) {
290                 $procline--;
291                 last;
292             }
293             &transcript("> $bodylines[$procline]\n");
294             next if $bad;
295             my ($o, $txt) = ($1, $2);
296             if ($#cats == -1 && $o eq "+") {
297                 &transcript("User defined category specification must start with a category name. Skipping.\n\n");
298                 $errors++;
299                 $bad = 1;
300                 next;
301             }
302             if ($o eq "+") {
303                 unless (ref($cats[-1]) eq "HASH") {
304                     $cats[-1] = { "nam" => $cats[-1], 
305                                   "pri" => [], "ttl" => [] };
306                 }
307                 $catsec++;
308                 my ($desc, $ord, $op);
309                 if ($txt =~ m/^(.*\S)\s*\[((\d+):\s*)?\]\s*$/) {
310                     $desc = $1; $ord = $3; $op = "";
311                 } elsif ($txt =~ m/^(.*\S)\s*\[((\d+):\s*)?(\S+)\]\s*$/) {
312                     $desc = $1; $ord = $3; $op = $4;
313                 } elsif ($txt =~ m/^([^[\s]+)\s*$/) {
314                     $desc = ""; $op = $1;
315                 } else {
316                     &transcript("Unrecognised syntax for category section. Skipping.\n\n");
317                     $errors++;
318                     $bad = 1;
319                     next;
320                 }
321                 $ord = 999 unless defined $ord;
322
323                 if ($op) {
324                     push @{$cats[-1]->{"pri"}}, $prefix . $op;
325                     push @{$cats[-1]->{"ttl"}}, $desc;
326                     push @ords, "$ord $catsec";
327                 } else {
328                     @cats[-1]->{"def"} = $desc;
329                     push @ords, "$ord DEF";
330                     $catsec--;
331                 }
332                 @ords = sort { my ($a1, $a2, $b1, $b2) = split / /, "$a $b";
333                                $a1 <=> $b1 || $a2 <=> $b2; } @ords;
334                 $cats[-1]->{"ord"} = [map { m/^.* (\S+)/; $1 eq "DEF" ? $catsec + 1 : $1 } @ords];
335             } elsif ($o eq "*") {
336                 $catsec = 0;
337                 my ($name);
338                 if ($txt =~ m/^(.*\S)(\s*\[(\S+)\])\s*$/) {
339                     $name = $1; $prefix = $3;
340                 } else {
341                     $name = $txt; $prefix = "";
342                 }
343                 push @cats, $name;
344             }
345         }
346         # XXX: got @cats, now do something with it
347         my $u = Debbugs::User::get_user($user);
348         if (@cats) {
349             &transcript("Added usercategory $catname.\n\n");
350             $u->{"categories"}->{$catname} = [ @cats ];
351             if (not $hidden) {
352                  push @{$u->{visible_cats}},$catname;
353             }
354         } else {
355             &transcript("Removed usercategory $catname.\n\n");
356             delete $u->{"categories"}->{$catname};
357             @{$u->{visible_cats}} = grep {$_ ne $catname} @{$u->{visible_cats}};
358         }
359         $u->write();
360     } elsif (m/^usertags?\s+\#?(-?\d+)\s+(([=+-])\s*)?(\S.*)?$/i) {
361         $ok++;
362         $ref = $1; $addsubcode = $3 || "+"; $tags = $4;
363         if ($ref =~ m/^-\d+$/ && defined $clonebugs{$ref}) {
364              $ref = $clonebugs{$ref};
365         }
366         if ($user eq "") {
367             &transcript("No valid user selected\n");
368             $errors++;
369             $indicated_user = 1;
370         } elsif (&setbug) {
371             if (not $indicated_user and defined $user) {
372                  &transcript("User is $user");
373                  $indicated_user = 1;
374             }
375             &nochangebug;
376             my %ut;
377             Debbugs::User::read_usertags(\%ut, $user);
378             my @oldtags = (); my @newtags = (); my @badtags = ();
379             my %chtags;
380             for my $t (split /[,\s]+/, $tags) {
381                 if ($t =~ m/^[a-zA-Z0-9.+\@-]+$/) {
382                     $chtags{$t} = 1;
383                 } else {
384                     push @badtags, $t;
385                 }
386             }
387             if (@badtags) {
388                 &transcript("Ignoring illegal tag/s: ".join(', ', @badtags).".\nPlease use only alphanumerics, at, dot, plus and dash.\n");
389                 $errors++;
390             }
391             for my $t (keys %chtags) {
392                 $ut{$t} = [] unless defined $ut{$t};
393             }
394             for my $t (keys %ut) {
395                 my %res = map { ($_, 1) } @{$ut{$t}};
396                 push @oldtags, $t if defined $res{$ref};
397                 my $addop = ($addsubcode eq "+" or $addsubcode eq "=");
398                 my $del = (defined $chtags{$t} ? $addsubcode eq "-" 
399                                                : $addsubcode eq "=");
400                 $res{$ref} = 1 if ($addop && defined $chtags{$t});
401                 delete $res{$ref} if ($del);
402                 push @newtags, $t if defined $res{$ref};
403                 $ut{$t} = [ sort { $a <=> $b } (keys %res) ];
404             }
405             if (@oldtags == 0) {
406                 &transcript("There were no usertags set.\n");
407             } else {
408                 &transcript("Usertags were: " . join(" ", @oldtags) . ".\n");
409             }
410             &transcript("Usertags are now: " . join(" ", @newtags) . ".\n");
411             Debbugs::User::write_usertags(\%ut, $user);
412         }
413     } elsif (!$control) {
414         &transcript(<<END);
415 Unknown command or malformed arguments to command.
416 (Use control\@$gEmailDomain to manipulate reports.)
417
418 END
419         $errors++;
420         if (++$unknowns >= 3) {
421             &transcript("Too many unknown commands, stopping here.\n\n");
422             last;
423         }
424 #### "developer only" ones start here
425     } elsif (m/^close\s+\#?(-?\d+)(?:\s+(\d.*))?$/i) {
426         $ok++;
427         $ref= $1;
428         $bug_affected{$ref}=1;
429         $version= $2;
430         if (&setbug) {
431             &transcript("'close' is deprecated; see http://$gWebDomain/Developer$gHTMLSuffix#closing.\n");
432             if (length($data->{done}) and not defined($version)) {
433                 &transcript("$gBug is already closed, cannot re-close.\n\n");
434                 &nochangebug;
435             } else {
436                 $action= "$gBug " .
437                     (defined($version) ?
438                         "marked as fixed in version $version" :
439                         "closed") .
440                     ", send any further explanations to $data->{originator}";
441                 do {
442                     &addmaintainers($data);
443                                         if ( length( $gDoneList ) > 0 && length( $gListDomain ) >
444                                         0 ) { &addccaddress("$gDoneList\@$gListDomain"); }
445                     $data->{done}= $replyto;
446                     my @keywords= split ' ', $data->{keywords};
447                     if (grep $_ eq 'pending', @keywords) {
448                         $extramessage= "Removed pending tag.\n";
449                         $data->{keywords}= join ' ', grep $_ ne 'pending',
450                                                 @keywords;
451                     }
452                     addfixedversions($data, $data->{package}, $version, 'binary');
453
454                     $message= <<END;
455 From: $gMaintainerEmail ($gProject $gBug Tracking System)
456 To: $data->{originator}
457 Subject: $gBug#$ref acknowledged by developer
458          ($header{'subject'})
459 References: $header{'message-id'} $data->{msgid}
460 In-Reply-To: $data->{msgid}
461 Message-ID: <handler.$ref.$nn.notifdonectrl.$midix\@$gEmailDomain>
462 Reply-To: $ref\@$gEmailDomain
463 X-$gProject-PR-Message: they-closed-control $ref
464
465 This is an automatic notification regarding your $gBug report
466 #$ref: $data->{subject},
467 which was filed against the $data->{package} package.
468
469 It has been marked as closed by one of the developers, namely
470 $replyto.
471
472 You should be hearing from them with a substantive response shortly,
473 in case you haven't already. If not, please contact them directly.
474
475 $gMaintainer
476 (administrator, $gProject $gBugs database)
477
478 END
479                     &sendmailmessage($message,$data->{originator});
480                 } while (&getnextbug);
481             }
482         }
483     } elsif (m/^reassign\s+\#?(-?\d+)\s+(\S+)(?:\s+(\d.*))?$/i) {
484         $ok++;
485         $ref= $1; $newpackage= $2;
486         $bug_affected{$ref}=1;
487         $version= $3;
488         $newpackage =~ y/A-Z/a-z/;
489         if (&setbug) {
490             if (length($data->{package})) {
491                 $action= "$gBug reassigned from package \`$data->{package}'".
492                          " to \`$newpackage'.";
493             } else {
494                 $action= "$gBug assigned to package \`$newpackage'.";
495             }
496             do {
497                 &addmaintainers($data);
498                 $data->{package}= $newpackage;
499                 $data->{found_versions}= [];
500                 $data->{fixed_versions}= [];
501                 # TODO: what if $newpackage is a source package?
502                 addfoundversions($data, $data->{package}, $version, 'binary');
503                 &addmaintainers($data);
504             } while (&getnextbug);
505         }
506     } elsif (m/^reopen\s+\#?(-?\d+)$/i ? ($noriginator='', 1) :
507              m/^reopen\s+\#?(-?\d+)\s+\=$/i ? ($noriginator='', 1) :
508              m/^reopen\s+\#?(-?\d+)\s+\!$/i ? ($noriginator=$replyto, 1) :
509              m/^reopen\s+\#?(-?\d+)\s+(\S.*\S)$/i ? ($noriginator=$2, 1) : 0) {
510         $ok++;
511         $ref= $1;
512         $bug_affected{$ref}=1;
513         if (&setbug) {
514             if (@{$data->{fixed_versions}}) {
515                 &transcript("'reopen' may be inappropriate when a bug has been closed with a version;\nyou may need to use 'found' to remove fixed versions.\n");
516             }
517             if (!length($data->{done})) {
518                 &transcript("$gBug is already open, cannot reopen.\n\n");
519                 &nochangebug;
520             } else {
521                 $action=
522                     $noriginator eq '' ? "$gBug reopened, originator not changed." :
523                         "$gBug reopened, originator set to $noriginator.";
524                 do {
525                     &addmaintainers($data);
526                     $data->{originator}= $noriginator eq '' ?  $data->{originator} : $noriginator;
527                     $data->{fixed_versions}= [];
528                     $data->{done}= '';
529                 } while (&getnextbug);
530             }
531         }
532     } elsif (m{^found\s+\#?(-?\d+)
533                (?:\s+(?:$config{package_name_re}\/)?
534                     ($config{package_version_re}))?$}ix) {
535         $ok++;
536         $ref= $1;
537         $version= $2;
538         if (&setbug) {
539             if (!length($data->{done}) and not defined($version)) {
540                 &transcript("$gBug is already open, cannot reopen.\n\n");
541                 $errors++;
542                 &nochangebug;
543             } else {
544                 $action=
545                     defined($version) ?
546                         "$gBug marked as found in version $version." :
547                         "$gBug reopened.";
548                 do {
549                     &addmaintainers($data);
550                     # The 'done' field gets a bit weird with version
551                     # tracking, because a bug may be closed by multiple
552                     # people in different branches. Until we have something
553                     # more flexible, we set it every time a bug is fixed,
554                     # and clear it precisely when a found command is
555                     # received for the rightmost fixed-in version, which
556                     # equates to the most recent fixing of the bug, or when
557                     # a versionless found command is received.
558                     if (defined $version) {
559                         my $lastfixed = $data->{fixed_versions}[-1];
560                         # TODO: what if $data->{package} is a source package?
561                         addfoundversions($data, $data->{package}, $version, 'binary');
562                         if (defined $lastfixed and not grep { $_ eq $lastfixed } @{$data->{fixed_versions}}) {
563                             $data->{done} = '';
564                         }
565                     } else {
566                         # Versionless found; assume old-style "not fixed at
567                         # all".
568                         $data->{fixed_versions} = [];
569                         $data->{done} = '';
570                     }
571                 } while (&getnextbug);
572             }
573         }
574     } elsif (m/^notfound\s+\#?(-?\d+)\s+(\d.*)$/i) {
575         $ok++;
576         $ref= $1;
577         $version= $2;
578         if (&setbug) {
579             $action= "$gBug marked as not found in version $version.";
580             if (length($data->{done})) {
581                 $extramessage= "(By the way, this $gBug is currently marked as done.)\n";
582             }
583             do {
584                 &addmaintainers($data);
585                 removefoundversions($data, $data->{package}, $version, 'binary');
586             } while (&getnextbug);
587        }
588    }
589     elsif (m[^fixed\s+\#?(-?\d+)\s+
590              ((?:$config{package_name_re}\/)?
591                   $config{package_version_re})\s*$]ix) {
592         $ok++;
593         $ref= $1;
594         $version= $2;
595         if (&setbug) {
596              $action=
597                   defined($version) ?
598                        "$gBug marked as fixed in version $version." :
599                             "$gBug reopened.";
600                 do {
601                     &addmaintainers($data);
602                     addfixedversions($data, $data->{package}, $version, 'binary');
603                } while (&getnextbug);
604         }
605    }
606     elsif (m[^notfixed\s+\#?(-?\d+)\s+
607              ((?:$config{package_name_re}\/)?
608                   $config{package_version_re})\s*$]ix) {
609         $ok++;
610         $ref= $1;
611         $version= $2;
612         if (&setbug) {
613              $action=
614                   defined($version) ?
615                        "$gBug marked as not fixed in version $version." :
616                             "$gBug reopened.";
617                 do {
618                     &addmaintainers($data);
619                     removefixedversions($data, $data->{package}, $version, 'binary');
620                } while (&getnextbug);
621         }
622    }
623     elsif (m/^submitter\s+\#?(-?\d+)\s+\!$/i ? ($newsubmitter=$replyto, 1) :
624              m/^submitter\s+\#?(-?\d+)\s+(\S.*\S)$/i ? ($newsubmitter=$2, 1) : 0) {
625         $ok++;
626         $ref= $1;
627         $bug_affected{$ref}=1;
628         if ($ref =~ m/^-\d+$/ && defined $clonebugs{$ref}) {
629             $ref = $clonebugs{$ref};
630         }
631         if (&getbug) {
632             if (&checkpkglimit) {
633                 &foundbug;
634                 &addmaintainers($data);
635                 $oldsubmitter= $data->{originator};
636                 $data->{originator}= $newsubmitter;
637                 $action= "Changed $gBug submitter from $oldsubmitter to $newsubmitter.";
638                 &savebug;
639                 &transcript("$action\n");
640                 if (length($data->{done})) {
641                     &transcript("(By the way, that $gBug is currently marked as done.)\n");
642                 }
643                 &transcript("\n");
644                 $message= <<END;
645 From: $gMaintainerEmail ($gProject $gBug Tracking System)
646 To: $oldsubmitter
647 Subject: $gBug#$ref submitter address changed
648          ($header{'subject'})
649 References: $header{'message-id'} $data->{msgid}
650 In-Reply-To: $data->{msgid}
651 Message-ID: <handler.$ref.$nn.newsubmitter.$midix\@$gEmailDomain>
652 Reply-To: $ref\@$gEmailDomain
653 X-$gProject-PR-Message: submitter-changed $ref
654
655 The submitter address recorded for your $gBug report
656 #$ref: $data->{subject}
657 has been changed.
658
659 The old submitter address for this report was
660 $oldsubmitter.
661 The new submitter address is
662 $newsubmitter.
663
664 This change was made by
665 $replyto.
666 If it was incorrect, please contact them directly.
667
668 $gMaintainer
669 (administrator, $gProject $gBugs database)
670
671 END
672                 &sendmailmessage($message,$oldsubmitter);
673             } else {
674                 &cancelbug;
675             }
676         } else {
677             &notfoundbug;
678         }
679     } elsif (m/^forwarded\s+\#?(-?\d+)\s+(\S.*\S)$/i) {
680         $ok++;
681         $ref= $1; $whereto= $2;
682         $bug_affected{$ref}=1;
683         if (&setbug) {
684             if (length($data->{forwarded})) {
685     $action= "Forwarded-to-address changed from $data->{forwarded} to $whereto.";
686             } else {
687     $action= "Noted your statement that $gBug has been forwarded to $whereto.";
688             }
689             if (length($data->{done})) {
690                 $extramessage= "(By the way, this $gBug is currently marked as done.)\n";
691             }
692             do {
693                 &addmaintainers($data);
694                 if (length($gForwardList)>0 && length($gListDomain)>0 ) {
695                      &addccaddress("$gForwardList\@$gListDomain"); 
696                 }
697                 $data->{forwarded}= $whereto;
698             } while (&getnextbug);
699         }
700     } elsif (m/^notforwarded\s+\#?(-?\d+)$/i) {
701         $ok++;
702         $ref= $1;
703         $bug_affected{$ref}=1;
704         if (&setbug) {
705             if (!length($data->{forwarded})) {
706                 &transcript("$gBug is not marked as having been forwarded.\n\n");
707                 &nochangebug;
708             } else {
709     $action= "Removed annotation that $gBug had been forwarded to $data->{forwarded}.";
710                 do {
711                     &addmaintainers($data);
712                     $data->{forwarded}= '';
713                 } while (&getnextbug);
714             }
715         }
716     } elsif (m/^severity\s+\#?(-?\d+)\s+([-0-9a-z]+)$/i ||
717         m/^priority\s+\#?(-?\d+)\s+([-0-9a-z]+)$/i) {
718         $ok++;
719         $ref= $1;
720         $bug_affected{$ref}=1;
721         $newseverity= $2;
722         if (!grep($_ eq $newseverity, @gSeverityList, "$gDefaultSeverity")) {
723             &transcript("Severity level \`$newseverity' is not known.\n".
724                         "Recognized are: $gShowSeverities.\n\n");
725             $errors++;
726         } elsif (exists $gObsoleteSeverities{$newseverity}) {
727             &transcript("Severity level \`$newseverity' is obsolete. " .
728                         "Use $gObsoleteSeverities{$newseverity} instead.\n\n");
729                 $errors++;
730         } elsif (&setbug) {
731             $printseverity= $data->{severity};
732             $printseverity= "$gDefaultSeverity" if $printseverity eq '';
733             $action= "Severity set to \`$newseverity' from \`$printseverity'";
734             do {
735                 &addmaintainers($data);
736                 if (defined $gStrongList and isstrongseverity($newseverity)) {
737                     addbcc("$gStrongList\@$gListDomain");
738                 }
739                 $data->{severity}= $newseverity;
740             } while (&getnextbug);
741         }
742     } elsif (m/^tags?\s+\#?(-?\d+)\s+(([=+-])\s*)?(\S.*)?$/i) {
743         $ok++;
744         $ref = $1; $addsubcode = $3; $tags = $4;
745         $bug_affected{$ref}=1;
746         $addsub = "add";
747         if (defined $addsubcode) {
748             $addsub = "sub" if ($addsubcode eq "-");
749             $addsub = "add" if ($addsubcode eq "+");
750             $addsub = "set" if ($addsubcode eq "=");
751         }
752         my @okaytags = ();
753         my @badtags = ();
754         foreach my $t (split /[\s,]+/, $tags) {
755             if (!grep($_ eq $t, @gTags)) {
756                 push @badtags, $t;
757             } else {
758                 push @okaytags, $t;
759             }
760         }
761         if (@badtags) {
762             &transcript("Unknown tag/s: ".join(', ', @badtags).".\n".
763                         "Recognized are: ".join(' ', @gTags).".\n\n");
764             $errors++;
765         }
766         if (&setbug) {
767             if ($data->{keywords} eq '') {
768                 &transcript("There were no tags set.\n");
769             } else {
770                 &transcript("Tags were: $data->{keywords}\n");
771             }
772             if ($addsub eq "set") {
773                 $action= "Tags set to: " . join(", ", @okaytags);
774             } elsif ($addsub eq "add") {
775                 $action= "Tags added: " . join(", ", @okaytags);
776             } elsif ($addsub eq "sub") {
777                 $action= "Tags removed: " . join(", ", @okaytags);
778             }
779             do {
780                 &addmaintainers($data);
781                 $data->{keywords} = '' if ($addsub eq "set");
782                 # Allow removing obsolete tags.
783                 if ($addsub eq "sub") {
784                     foreach my $t (@badtags) {
785                         $data->{keywords} = join ' ', grep $_ ne $t, 
786                             split ' ', $data->{keywords};
787                     }
788                 }
789                 # Now process all other additions and subtractions.
790                 foreach my $t (@okaytags) {
791                     $data->{keywords} = join ' ', grep $_ ne $t, 
792                         split ' ', $data->{keywords};
793                     $data->{keywords} = "$t $data->{keywords}" unless($addsub eq "sub");
794                 }
795                 $data->{keywords} =~ s/\s*$//;
796             } while (&getnextbug);
797         }
798     } elsif (m/^(un)?block\s+\#?(-?\d+)\s+(by|with)\s+\s*(\S.*)?$/i) {
799         $ok++;
800         my $bugnum = $2; my $blockers = $4;
801         $addsub = "add";
802         $addsub = "sub" if ($1 eq "un");
803         if ($bugnum =~ m/^-\d+$/ && defined $clonebugs{$bugnum}) {
804              $bugnum = $clonebugs{$bugnum};
805         }
806
807         my @okayblockers;
808         my @badblockers;
809         foreach my $b (split /[\s,]+/, $blockers) {
810             $b=~s/^\#//;
811             if ($b=~/[0-9]+/) {
812                 $ref=$b;
813                 if ($ref =~ m/^-\d+$/ && defined $clonebugs{$ref}) {
814                      $ref = $clonebugs{$ref};
815                 }
816                 if (&getbug) {
817                     &foundbug;
818                     push @okayblockers, $ref;
819
820                     # add to the list all bugs that are merged with $b,
821                     # because all of their data must be kept in sync
822                     @thisbugmergelist= split(/ /,$data->{mergedwith});
823                     &cancelbug;
824
825                     foreach $ref (@thisbugmergelist) {
826                         if (&getbug) {
827                            push @okayblockers, $ref;
828                            &cancelbug;
829                         }
830                     }
831                 }
832                 else {
833                     &notfoundbug;
834                     push @badblockers, $ref;
835                 }
836             }
837             else {
838                 push @badblockers, $b;
839             }
840         }
841         if (@badblockers) {
842             &transcript("Unknown blocking bug/s: ".join(', ', @badblockers).".\n");
843             $errors++;
844         }
845         
846         $ref=$bugnum;
847         if (&setbug) {
848             if ($data->{blockedby} eq '') {
849                 &transcript("Was not blocked by any bugs.\n");
850             } else {
851                 &transcript("Was blocked by: $data->{blockedby}\n");
852             }
853             if ($addsub eq "set") {
854                 $action= "Blocking bugs of $bugnum set to: " . join(", ", @okayblockers);
855             } elsif ($addsub eq "add") {
856                 $action= "Blocking bugs of $bugnum added: " . join(", ", @okayblockers);
857             } elsif ($addsub eq "sub") {
858                 $action= "Blocking bugs of $bugnum removed: " . join(", ", @okayblockers);
859             }
860             my %removedblocks;
861             my %addedblocks;
862             do {
863                 &addmaintainers($data);
864                 my @oldblockerlist = split ' ', $data->{blockedby};
865                 $data->{blockedby} = '' if ($addsub eq "set");
866                 foreach my $b (@okayblockers) {
867                         $data->{blockedby} = manipset($data->{blockedby}, $b,
868                                 ($addsub ne "sub"));
869                 }
870
871                 foreach my $b (@oldblockerlist) {
872                         if (! grep { $_ eq $b } split ' ', $data->{blockedby}) {
873                                 push @{$removedblocks{$b}}, $ref;
874                         }
875                 }
876                 foreach my $b (split ' ', $data->{blockedby}) {
877                         if (! grep { $_ eq $b } @oldblockerlist) {
878                                 push @{$addedblocks{$b}}, $ref;
879                         }
880                 }
881             } while (&getnextbug);
882
883             # Now that the blockedby data is updated, change blocks data
884             # to match the changes.
885             foreach $ref (keys %addedblocks) {
886                 if (&getbug) {
887                     foreach my $b (@{$addedblocks{$ref}}) {
888                         $data->{blocks} = manipset($data->{blocks}, $b, 1);
889                     }
890                     &savebug;
891                 }
892             }
893             foreach $ref (keys %removedblocks) {
894                 if (&getbug) {
895                     foreach my $b (@{$removedblocks{$ref}}) {
896                         $data->{blocks} = manipset($data->{blocks}, $b, 0);
897                     }
898                     &savebug;
899                 }
900             }
901         }
902     } elsif (m/^retitle\s+\#?(-?\d+)\s+(\S.*\S)\s*$/i) {
903         $ok++;
904         $ref= $1; $newtitle= $2;
905         $bug_affected{$ref}=1;
906         if ($ref =~ m/^-\d+$/ && defined $clonebugs{$ref}) {
907             $ref = $clonebugs{$ref};
908         }
909         if (&getbug) {
910             if (&checkpkglimit) {
911                 &foundbug;
912                 &addmaintainers($data);
913                 my $oldtitle = $data->{subject};
914                 $data->{subject}= $newtitle;
915                 $action= "Changed $gBug title to `$newtitle' from `$oldtitle'.";
916                 &savebug;
917                 &transcript("$action\n");
918                 if (length($data->{done})) {
919                     &transcript("(By the way, that $gBug is currently marked as done.)\n");
920                 }
921                 &transcript("\n");
922             } else {
923                 &cancelbug;
924             }
925         } else {
926             &notfoundbug;
927         }
928     } elsif (m/^unmerge\s+\#?(-?\d+)$/i) {
929         $ok++;
930         $ref= $1;
931         $bug_affected{$ref} = 1;
932         if (&setbug) {
933             if (!length($data->{mergedwith})) {
934                 &transcript("$gBug is not marked as being merged with any others.\n\n");
935                 &nochangebug;
936             } else {
937                 $mergelowstate eq 'locked' || die "$mergelowstate ?";
938                 $action= "Disconnected #$ref from all other report(s).";
939                 @newmergelist= split(/ /,$data->{mergedwith});
940                 $discref= $ref;
941                 @bug_affected{@newmergelist} = 1 x @newmergelist;
942                 do {
943                     &addmaintainers($data);
944                     $data->{mergedwith}= ($ref == $discref) ? ''
945                         : join(' ',grep($_ ne $ref,@newmergelist));
946                 } while (&getnextbug);
947             }
948         }
949     } elsif (m/^merge\s+#?(-?\d+(\s+#?-?\d+)+)\s*$/i) {
950         $ok++;
951         my @tomerge= sort { $a <=> $b } split(/\s+#?/,$1);
952         my @newmergelist= ();
953         my %tags = ();
954         my %found = ();
955         my %fixed = ();
956         &getmerge;
957         while (defined($ref= shift(@tomerge))) {
958             &transcript("D| checking merge $ref\n") if $dl;
959             $ref+= 0;
960             if ($ref =~ m/^-\d+$/ && defined $clonebugs{$ref}) {
961                 $ref = $clonebugs{$ref};
962             }
963             next if grep($_ == $ref,@newmergelist);
964             if (!&getbug) { &notfoundbug; @newmergelist=(); last }
965             if (!&checkpkglimit) { &cancelbug; @newmergelist=(); last; }
966             &foundbug;
967             &transcript("D| adding $ref ($data->{mergedwith})\n") if $dl;
968             $mismatch= '';
969             &checkmatch('package','m_package',$data->{package},@newmergelist);
970             &checkmatch('forwarded addr','m_forwarded',$data->{forwarded},@newmergelist);
971             $data->{severity} = '$gDefaultSeverity' if $data->{severity} eq '';
972             &checkmatch('severity','m_severity',$data->{severity},@newmergelist);
973             &checkmatch('blocks','m_blocks',$data->{blocks},@newmergelist);
974             &checkmatch('blocked-by','m_blockedby',$data->{blockedby},@newmergelist);
975             &checkmatch('done mark','m_done',length($data->{done}) ? 'done' : 'open',@newmergelist);
976             &checkmatch('owner','m_owner',$data->{owner},@newmergelist);
977             foreach my $t (split /\s+/, $data->{keywords}) { $tags{$t} = 1; }
978             foreach my $f (@{$data->{found_versions}}) { $found{$f} = 1; }
979             foreach my $f (@{$data->{fixed_versions}}) { $fixed{$f} = 1; }
980             if (length($mismatch)) {
981                 &transcript("Mismatch - only $gBugs in same state can be merged:\n".
982                             $mismatch."\n");
983                 $errors++;
984                 &cancelbug; @newmergelist=(); last;
985             }
986             push(@newmergelist,$ref);
987             push(@tomerge,split(/ /,$data->{mergedwith}));
988             &cancelbug;
989         }
990         if (@newmergelist) {
991             @newmergelist= sort { $a <=> $b } @newmergelist;
992             $action= "Merged @newmergelist.";
993             delete @fixed{keys %found};
994             for $ref (@newmergelist) {
995                 &getbug || die "huh ?  $gBug $ref disappeared during merge";
996                 &addmaintainers($data);
997                 @bug_affected{@newmergelist} = 1 x @newmergelist;
998                 $data->{mergedwith}= join(' ',grep($_ != $ref,@newmergelist));
999                 $data->{keywords}= join(' ', keys %tags);
1000                 $data->{found_versions}= [sort keys %found];
1001                 $data->{fixed_versions}= [sort keys %fixed];
1002                 &savebug;
1003             }
1004             &transcript("$action\n\n");
1005         }
1006         &endmerge;
1007     } elsif (m/^forcemerge\s+\#?(-?\d+(?:\s+\#?-?\d+)+)\s*$/i) {
1008         $ok++;
1009         my @temp = split /\s+\#?/,$1;
1010         my $master_bug = shift @temp;
1011         my $master_bug_data;
1012         my @tomerge = sort { $a <=> $b } @temp;
1013         unshift @tomerge,$master_bug;
1014         &transcript("D| force merging ".join(',',@tomerge)."\n") if $dl;
1015         my @newmergelist= ();
1016         my %tags = ();
1017         my %found = ();
1018         my %fixed = ();
1019         # Here we try to do the right thing.
1020         # First, if the bugs are in the same package, we merge all of the found, fixed, and tags.
1021         # If not, we discard the found and fixed.
1022         # Everything else we set to the values of the first bug.
1023         &getmerge;
1024         while (defined($ref= shift(@tomerge))) {
1025             &transcript("D| checking merge $ref\n") if $dl;
1026             $ref+= 0;
1027             if ($ref =~ m/^-\d+$/ && defined $clonebugs{$ref}) {
1028                 $ref = $clonebugs{$ref};
1029             }
1030             next if grep($_ == $ref,@newmergelist);
1031             if (!&getbug) { &notfoundbug; @newmergelist=(); last }
1032             if (!&checkpkglimit) { &cancelbug; @newmergelist=(); last; }
1033             &foundbug;
1034             &transcript("D| adding $ref ($data->{mergedwith})\n") if $dl;
1035             $master_bug_data = $data if not defined $master_bug_data;
1036             if ($data->{package} ne $master_bug_data->{package}) {
1037                 &transcript("Mismatch - only $gBugs in the same package can be forcibly merged:\n".
1038                             "$gBug $ref is not in the same package as $master_bug\n");
1039                 $errors++;
1040                 &cancelbug; @newmergelist=(); last;
1041             }
1042             for my $t (split /\s+/,$data->{keywords}) {
1043                  $tags{$t} = 1;
1044             }
1045             @found{@{$data->{found_versions}}} = (1) x @{$data->{found_versions}};
1046             @fixed{@{$data->{fixed_versions}}} = (1) x @{$data->{fixed_versions}};
1047             push(@newmergelist,$ref);
1048             push(@tomerge,split(/ /,$data->{mergedwith}));
1049             &cancelbug;
1050         }
1051         if (@newmergelist) {
1052             @newmergelist= sort { $a <=> $b } @newmergelist;
1053             $action= "Forcibly Merged @newmergelist.";
1054             delete @fixed{keys %found};
1055             for $ref (@newmergelist) {
1056                 &getbug || die "huh ?  $gBug $ref disappeared during merge";
1057                 &addmaintainers($data);
1058                 @bug_affected{@newmergelist} = 1 x @newmergelist;
1059                 $data->{mergedwith}= join(' ',grep($_ != $ref,@newmergelist));
1060                 $data->{keywords}= join(' ', keys %tags);
1061                 $data->{found_versions}= [sort keys %found];
1062                 $data->{fixed_versions}= [sort keys %fixed];
1063                 my @field_list = qw(forwarded package severity blocks blockedby owner done);
1064                 @{$data}{@field_list} = @{$master_bug_data}{@field_list};
1065                 &savebug;
1066             }
1067             &transcript("$action\n\n");
1068         }
1069         &endmerge;
1070     } elsif (m/^clone\s+#?(\d+)\s+((-\d+\s+)*-\d+)\s*$/i) {
1071         $ok++;
1072
1073         $origref = $1;
1074         @newclonedids = split /\s+/, $2;
1075         $newbugsneeded = scalar(@newclonedids);
1076
1077         $ref = $origref;
1078         $bug_affected{$ref} = 1;
1079         if (&setbug) {
1080             if (length($data->{mergedwith})) {
1081                 &transcript("$gBug is marked as being merged with others. Use an existing clone.\n\n");
1082                 $errors++;
1083                 &nochangebug;
1084             } else {
1085                 &filelock("nextnumber.lock");
1086                 open(N,"nextnumber") || &quit("nextnumber: read: $!");
1087                 $v=<N>; $v =~ s/\n$// || &quit("nextnumber bad format");
1088                 $firstref= $v+0;  $v += $newbugsneeded;
1089                 open(NN,">nextnumber"); print NN "$v\n"; close(NN);
1090                 &unfilelock;
1091
1092                 $lastref = $firstref + $newbugsneeded - 1;
1093
1094                 if ($newbugsneeded == 1) {
1095                     $action= "$gBug $origref cloned as bug $firstref.";
1096                 } else {
1097                     $action= "$gBug $origref cloned as bugs $firstref-$lastref.";
1098                 }
1099
1100                 my $blocks = $data->{blocks};
1101                 my $blockedby = $data->{blockedby};
1102                 
1103                 &getnextbug;
1104                 my $ohash = get_hashname($origref);
1105                 my $clone = $firstref;
1106                 @bug_affected{@newclonedids} = 1 x @newclonedids;
1107                 for $newclonedid (@newclonedids) {
1108                     $clonebugs{$newclonedid} = $clone;
1109             
1110                     my $hash = get_hashname($clone);
1111                     copy("db-h/$ohash/$origref.log", "db-h/$hash/$clone.log");
1112                     copy("db-h/$ohash/$origref.status", "db-h/$hash/$clone.status");
1113                     copy("db-h/$ohash/$origref.summary", "db-h/$hash/$clone.summary");
1114                     copy("db-h/$ohash/$origref.report", "db-h/$hash/$clone.report");
1115                     &bughook('new', $clone, $data);
1116                 
1117                     # Update blocking info of bugs blocked by or blocking the
1118                     # cloned bug.
1119                     foreach $ref (split ' ', $blocks) {
1120                         &getbug;
1121                         $data->{blockedby} = manipset($data->{blockedby}, $clone, 1);
1122                         &savebug;
1123                     }
1124                     foreach $ref (split ' ', $blockedby) {
1125                         &getbug;
1126                         $data->{blocks} = manipset($data->{blocks}, $clone, 1);
1127                         &savebug;
1128                     }
1129
1130                     $clone++;
1131                 }
1132             }
1133         }
1134     } elsif (m/^package\:?\s+(\S.*\S)?\s*$/i) {
1135         $ok++;
1136         my @pkgs = split /\s+/, $1;
1137         if (scalar(@pkgs) > 0) {
1138                 %limit_pkgs = map { ($_, 1) } @pkgs;
1139                 &transcript("Ignoring bugs not assigned to: " . 
1140                         join(" ", keys(%limit_pkgs)) . "\n\n");
1141         } else {
1142                 %limit_pkgs = ();
1143                 &transcript("Not ignoring any bugs.\n\n");
1144         }
1145     } elsif (m/^owner\s+\#?(-?\d+)\s+!$/i ? ($newowner = $replyto, 1) :
1146              m/^owner\s+\#?(-?\d+)\s+(\S.*\S)$/i ? ($newowner = $2, 1) : 0) {
1147         $ok++;
1148         $ref = $1;
1149         $bug_affected{$ref} = 1;
1150         if (&setbug) {
1151             if (length $data->{owner}) {
1152                 $action = "Owner changed from $data->{owner} to $newowner.";
1153             } else {
1154                 $action = "Owner recorded as $newowner.";
1155             }
1156             if (length $data->{done}) {
1157                 $extramessage = "(By the way, this $gBug is currently " .
1158                                 "marked as done.)\n";
1159             }
1160             do {
1161                 &addmaintainers($data);
1162                 $data->{owner} = $newowner;
1163             } while (&getnextbug);
1164         }
1165     } elsif (m/^noowner\s+\#?(-?\d+)$/i) {
1166         $ok++;
1167         $ref = $1;
1168         $bug_affected{$ref} = 1;
1169         if (&setbug) {
1170             if (length $data->{owner}) {
1171                 $action = "Removed annotation that $gBug was owned by " .
1172                           "$data->{owner}.";
1173                 do {
1174                     &addmaintainers($data);
1175                     $data->{owner} = '';
1176                 } while (&getnextbug);
1177             } else {
1178                 &transcript("$gBug is not marked as having an owner.\n\n");
1179                 &nochangebug;
1180             }
1181         }
1182     } else {
1183         &transcript("Unknown command or malformed arguments to command.\n\n");
1184         $errors++;
1185         if (++$unknowns >= 5) {
1186             &transcript("Too many unknown commands, stopping here.\n\n");
1187             last;
1188         }
1189     }
1190 }
1191 if ($procline>$#bodylines) {
1192     &transcript(">\nEnd of message, stopping processing here.\n\n");
1193 }
1194 if (!$ok && !quickabort) {
1195     $errors++;
1196     &transcript("No commands successfully parsed; sending the help text(s).\n");
1197     &sendhelp;
1198     &transcript("\n");
1199 }
1200
1201 &transcript("MC\n") if $dl>1;
1202 @maintccs= ();
1203 for $maint (keys %maintccreasons) {
1204 &transcript("MM|$maint|\n") if $dl>1;
1205     next if $maint eq $replyto;
1206     $reasonstring= '';
1207     $reasonsref= $maintccreasons{$maint};
1208 &transcript("MY|$maint|\n") if $dl>2;
1209     for $p (sort keys %$reasonsref) {
1210 &transcript("MP|$p|\n") if $dl>2;
1211         $reasonstring.= ', ' if length($reasonstring);
1212         $reasonstring.= $p.' ' if length($p);
1213         $reasonstring.= join(' ',map("#$_",sort keys %{$$reasonsref{$p}}));
1214     }
1215     if (length($reasonstring) > 40) {
1216         (substr $reasonstring, 37) = "...";
1217     }
1218     $reasonstring = "" if (!defined($reasonstring));
1219     push(@maintccs,"$maint ($reasonstring)");
1220     push(@maintccaddrs,"$maint");
1221 }
1222
1223 $maintccs = ""; 
1224 if (@maintccs) {
1225     &transcript("MC|@maintccs|\n") if $dl>2;
1226     $maintccs .= "Cc: " . join(",\n    ",@maintccs) . "\n";
1227 }
1228
1229 my %packagepr;
1230 for my $maint (keys %maintccreasons) {
1231      for my $package (keys %{$maintccreasons{$maint}}) {
1232           next unless length $package;
1233           $packagepr{$package} = 1;
1234      }
1235 }
1236 my $packagepr = '';
1237 $packagepr = "X-${gProject}-PR-Package: " . join(keys %packagepr) . "\n" if keys %packagepr;
1238
1239 # Add Bcc's to subscribed bugs
1240 push @bcc, map {"bugs=$_\@$gListDomain"} keys %bug_affected;
1241
1242 if (!defined $header{'subject'} || $header{'subject'} eq "") {
1243   $header{'subject'} = "your mail";
1244 }
1245
1246 # Error text here advertises how many errors there were
1247 my $error_text = $errors > 0 ? " (with $errors errors)":'';
1248
1249 $reply= <<END;
1250 From: $gMaintainerEmail ($gProject $gBug Tracking System)
1251 To: $replyto
1252 ${maintccs}Subject: Processed${error_text}: $header{'subject'}
1253 In-Reply-To: $header{'message-id'}
1254 References: $header{'message-id'}
1255 Message-ID: <handler.s.$nn.transcript\@$gEmailDomain>
1256 Precedence: bulk
1257 ${packagepr}X-$gProject-PR-Message: transcript
1258
1259 ${transcript}Please contact me if you need assistance.
1260
1261 $gMaintainer
1262 (administrator, $gProject $gBugs database)
1263 $extras
1264 END
1265
1266 $repliedshow= join(', ',$replyto,@maintccaddrs);
1267 &filelock("lock/-1");
1268 open(AP,">>db-h/-1.log") || &quit("open db-h/-1.log: $!");
1269 print(AP
1270       "\2\n$repliedshow\n\5\n$reply\n\3\n".
1271       "\6\n".
1272       "<strong>Request received</strong> from <code>".
1273       html_escape($header{'from'})."</code>\n".
1274       "to <code>".html_escape($controlrequestaddr)."</code>\n".
1275       "\3\n".
1276       "\7\n",@{escapelog(@log)},"\n\3\n") || &quit("writing db-h/-1.log: $!");
1277 close(AP) || &quit("open db-h/-1.log: $!");
1278 &unfilelock;
1279 utime(time,time,"db-h");
1280
1281 &sendmailmessage($reply,exists $header{'x-debbugs-no-ack'}?():$replyto,@maintccaddrs,@bcc);
1282
1283 unlink("incoming/P$nn") || &quit("unlinking incoming/P$nn: $!");
1284
1285 sub sendmailmessage {
1286     local ($message,@recips) = @_;
1287     $message = "X-Loop: $gMaintainerEmail\n" . $message;
1288     send_mail_message(message    => $message,
1289                       recipients => \@recips,
1290                      );
1291     $midix++;
1292 }
1293
1294 sub sendhelp {
1295         &sendtxthelpraw("bug-log-mailserver.txt","instructions for request\@$gEmailDomain");
1296         &sendtxthelpraw("bug-maint-mailcontrol.txt","instructions for control\@$gEmailDomain")
1297             if $control;
1298 }
1299
1300 #sub unimplemented {
1301 #    &transcript("Sorry, command $_[0] not yet implemented.\n\n");
1302 #}
1303
1304 sub checkmatch {
1305     local ($string,$mvarname,$svarvalue,@newmergelist) = @_;
1306     local ($mvarvalue);
1307     if (@newmergelist) {
1308         eval "\$mvarvalue= \$$mvarname";
1309         &transcript("D| checkmatch \`$string' /$mvarname/$mvarvalue/$svarvalue/\n")
1310             if $dl;
1311         $mismatch .=
1312             "Values for \`$string' don't match:\n".
1313             " #$newmergelist[0] has \`$mvarvalue';\n".
1314             " #$ref has \`$svarvalue'\n"
1315             if $mvarvalue ne $svarvalue;
1316     } else {
1317         &transcript("D| setupmatch \`$string' /$mvarname/$svarvalue/\n")
1318             if $dl;
1319         eval "\$$mvarname= \$svarvalue";
1320     }
1321 }
1322
1323 sub checkpkglimit {
1324     if (keys %limit_pkgs and not defined $limit_pkgs{$data->{package}}) {
1325         &transcript("$gBug number $ref belongs to package $data->{package}, skipping.\n\n");
1326         $errors++;
1327         return 0;
1328     }
1329     return 1;
1330 }
1331
1332 sub manipset {
1333     my $list = shift;
1334     my $elt = shift;
1335     my $add = shift;
1336
1337     my %h = map { $_ => 1 } split ' ', $list;
1338     if ($add) {
1339         $h{$elt}=1;
1340     }
1341     else {
1342         delete $h{$elt};
1343     }
1344     return join ' ', sort keys %h;
1345 }
1346
1347 # High-level bug manipulation calls
1348 # Do announcements themselves
1349 #
1350 # Possible calling sequences:
1351 #    setbug (returns 0)
1352 #    
1353 #    setbug (returns 1)
1354 #    &transcript(something)
1355 #    nochangebug
1356 #
1357 #    setbug (returns 1)
1358 #    $action= (something)
1359 #    do {
1360 #      (modify s_* variables)
1361 #    } while (getnextbug);
1362
1363 sub nochangebug {
1364     &dlen("nochangebug");
1365     $state eq 'single' || $state eq 'multiple' || die "$state ?";
1366     &cancelbug;
1367     &endmerge if $manybugs;
1368     $state= 'idle';
1369     &dlex("nochangebug");
1370 }
1371
1372 sub setbug {
1373     &dlen("setbug $ref");
1374     if ($ref =~ m/^-\d+/) {
1375         if (!defined $clonebugs{$ref}) {
1376             &notfoundbug;
1377             &dlex("setbug => noclone");
1378             return 0;
1379         }
1380         $ref = $clonebugs{$ref};
1381     }
1382     $state eq 'idle' || die "$state ?";
1383     if (!&getbug) {
1384         &notfoundbug;
1385         &dlex("setbug => 0s");
1386         return 0;
1387     }
1388
1389     if (!&checkpkglimit) {
1390         &cancelbug;
1391         return 0;
1392     }
1393
1394     @thisbugmergelist= split(/ /,$data->{mergedwith});
1395     if (!@thisbugmergelist) {
1396         &foundbug;
1397         $manybugs= 0;
1398         $state= 'single';
1399         $sref=$ref;
1400         &dlex("setbug => 1s");
1401         return 1;
1402     }
1403     &cancelbug;
1404     &getmerge;
1405     $manybugs= 1;
1406     if (!&getbug) {
1407         &notfoundbug;
1408         &endmerge;
1409         &dlex("setbug => 0mc");
1410         return 0;
1411     }
1412     &foundbug;
1413     $state= 'multiple'; $sref=$ref;
1414     &dlex("setbug => 1m");
1415     return 1;
1416 }
1417
1418 sub getnextbug {
1419     &dlen("getnextbug");
1420     $state eq 'single' || $state eq 'multiple' || die "$state ?";
1421     &savebug;
1422     if (!$manybugs || !@thisbugmergelist) {
1423         length($action) || die;
1424         &transcript("$action\n$extramessage\n");
1425         &endmerge if $manybugs;
1426         $state= 'idle';
1427         &dlex("getnextbug => 0");
1428         return 0;
1429     }
1430     $ref= shift(@thisbugmergelist);
1431     &getbug || die "bug $ref disappeared";
1432     &foundbug;
1433     &dlex("getnextbug => 1");
1434     return 1;
1435 }
1436
1437 # Low-level bug-manipulation calls
1438 # Do no announcements
1439 #
1440 #    getbug (returns 0)
1441 #
1442 #    getbug (returns 1)
1443 #    cancelbug
1444 #
1445 #    getmerge
1446 #    $action= (something)
1447 #    getbug (returns 1)
1448 #    savebug/cancelbug
1449 #    getbug (returns 1)
1450 #    savebug/cancelbug
1451 #    [getbug (returns 0)]
1452 #    &transcript("$action\n\n")
1453 #    endmerge
1454
1455 sub notfoundbug { &transcript("$gBug number $ref not found. (Is it archived?)\n\n"); }
1456 sub foundbug { &transcript("$gBug#$ref: $data->{subject}\n"); }
1457
1458 sub getmerge {
1459     &dlen("getmerge");
1460     $mergelowstate eq 'idle' || die "$mergelowstate ?";
1461     &filelock('lock/merge');
1462     $mergelowstate='locked';
1463     &dlex("getmerge");
1464 }
1465
1466 sub endmerge {
1467     &dlen("endmerge");
1468     $mergelowstate eq 'locked' || die "$mergelowstate ?";
1469     &unfilelock;
1470     $mergelowstate='idle';
1471     &dlex("endmerge");
1472 }
1473
1474 sub getbug {
1475     &dlen("getbug $ref");
1476     $lowstate eq 'idle' || die "$state ?";
1477     if (($data = &lockreadbug($ref))) {
1478         $sref= $ref;
1479         $lowstate= "open";
1480         &dlex("getbug => 1");
1481         $extramessage='';
1482         return 1;
1483     }
1484     $lowstate= 'idle';
1485     &dlex("getbug => 0");
1486     return 0;
1487 }
1488
1489 sub cancelbug {
1490     &dlen("cancelbug");
1491     $lowstate eq 'open' || die "$state ?";
1492     &unfilelock;
1493     $lowstate= 'idle';
1494     &dlex("cancelbug");
1495 }
1496
1497 sub savebug {
1498     &dlen("savebug $ref");
1499     $lowstate eq 'open' || die "$lowstate ?";
1500     length($action) || die;
1501     $ref == $sref || die "read $sref but saving $ref ?";
1502     my $hash = get_hashname($ref);
1503     open(L,">>db-h/$hash/$ref.log") || &quit("opening db-h/$hash/$ref.log: $!");
1504     print(L
1505           "\6\n".
1506           "<!-- time:".time." -->\n".
1507           "<strong>".html_escape($action)."</strong>\n".
1508           "Request was from <code>".html_escape($header{'from'})."</code>\n".
1509           "to <code>".html_escape($controlrequestaddr)."</code>. \n".
1510           "\3\n".
1511           "\7\n",@{escapelog(@log)},"\n\3\n") || &quit("writing db-h/$hash/$ref.log: $!");
1512     close(L) || &quit("closing db-h/$hash/$ref.log: $!");
1513     unlockwritebug($ref, $data);
1514     $lowstate= "idle";
1515     &dlex("savebug");
1516 }
1517
1518 sub dlen {
1519     return if !$dl;
1520     &transcript("C> @_ ($state $lowstate $mergelowstate)\n");
1521 }
1522
1523 sub dlex {
1524     return if !$dl;
1525     &transcript("R> @_ ($state $lowstate $mergelowstate)\n");
1526 }
1527
1528 sub transcript {
1529     print $_[0] if $debug;
1530     $transcript.= $_[0];
1531 }
1532
1533 sub urlsanit {
1534     my $url = shift;
1535     $url =~ s/%/%25/g;
1536     $url =~ s/\+/%2b/g;
1537     my %saniarray = ('<','lt', '>','gt', '&','amp', '"','quot');
1538     $url =~ s/([<>&"])/\&$saniarray{$1};/g;
1539     return $url;
1540 }
1541
1542 sub sendlynxdoc {
1543     &sendlynxdocraw;
1544     &transcript("\n");
1545     $ok++;
1546 }
1547
1548 sub sendtxthelp {
1549     &sendtxthelpraw;
1550     &transcript("\n");
1551     $ok++;
1552 }
1553
1554 sub sendtxthelpraw {
1555     local ($relpath,$description) = @_;
1556     $doc='';
1557     open(D,"$gDocDir/$relpath") || &quit("open doc file $relpath: $!");
1558     while(<D>) { $doc.=$_; }
1559     close(D);
1560     &transcript("Sending $description in separate message.\n");
1561     &sendmailmessage(<<END.$doc,$replyto);
1562 From: $gMaintainerEmail ($gProject $gBug Tracking System)
1563 To: $replyto
1564 Subject: $gProject $gBug help: $description
1565 References: $header{'message-id'}
1566 In-Reply-To: $header{'message-id'}
1567 Message-ID: <handler.s.$nn.help.$midix\@$gEmailDomain>
1568 Precedence: bulk
1569 X-$gProject-PR-Message: doc-text $relpath
1570
1571 END
1572     $ok++;
1573 }
1574
1575 sub sendlynxdocraw {
1576     local ($relpath,$description) = @_;
1577     $doc='';
1578     open(L,"lynx -nolist -dump http://$gCGIDomain/\Q$relpath\E 2>&1 |") || &quit("fork for lynx: $!");
1579     while(<L>) { $doc.=$_; }
1580     $!=0; close(L);
1581     if ($? == 255 && $doc =~ m/^\n*lynx: Can\'t access start file/) {
1582         &transcript("Information ($description) is not available -\n".
1583                     "perhaps the $gBug does not exist or is not on the WWW yet.\n");
1584          $ok++;
1585     } elsif ($?) {
1586         &transcript("Error getting $description (code $? $!):\n$doc\n");
1587     } else {
1588         &transcript("Sending $description.\n");
1589         &sendmailmessage(<<END.$doc,$replyto);
1590 From: $gMaintainerEmail ($gProject $gBug Tracking System)
1591 To: $replyto
1592 Subject: $gProject $gBugs information: $description
1593 References: $header{'message-id'}
1594 In-Reply-To: $header{'message-id'}
1595 Message-ID: <handler.s.$nn.info.$midix\@$gEmailDomain>
1596 Precedence: bulk
1597 X-$gProject-PR-Message: doc-html $relpath
1598
1599 END
1600          $ok++;
1601     }
1602 }
1603
1604 sub addccaddress {
1605     my ($cca) = @_;
1606     $maintccreasons{$cca}{''}{$ref}= 1;
1607 }
1608
1609 sub addmaintainers {
1610     # Data structure is:
1611     #   maintainer email address &c -> assoc of packages -> assoc of bug#'s
1612     my $data = shift;
1613     my ($p, $addmaint);
1614     &ensuremaintainersloaded;
1615     $anymaintfound=0; $anymaintnotfound=0;
1616     for $p (split(m/[ \t?,():]+/, $data->{package})) {
1617         $p =~ y/A-Z/a-z/;
1618         $p =~ /([a-z0-9.+-]+)/;
1619         $p = $1;
1620         next unless defined $p;
1621         if (defined $gSubscriptionDomain) {
1622             if (defined($pkgsrc{$p})) {
1623                 addbcc("$pkgsrc{$p}\@$gSubscriptionDomain");
1624             } else {
1625                 addbcc("$p\@$gSubscriptionDomain");
1626             }
1627         }
1628         if (defined $data->{severity} and defined $gStrongList and
1629                 isstrongseverity($data->{severity})) {
1630             addbcc("$gStrongList\@$gListDomain");
1631         }
1632         if (defined($maintainerof{$p})) {
1633             $addmaint= $maintainerof{$p};
1634             &transcript("MR|$addmaint|$p|$ref|\n") if $dl>2;
1635             $maintccreasons{$addmaint}{$p}{$ref}= 1;
1636             print "maintainer add >$p|$addmaint<\n" if $debug;
1637         } else { 
1638             print "maintainer none >$p<\n" if $debug; 
1639             &transcript("Warning: Unknown package '$p'\n");
1640             &transcript("MR|unknown-package|$p|$ref|\n") if $dl>2;
1641             $maintccreasons{$gUnknownMaintainerEmail}{$p}{$ref}= 1;
1642         }
1643     }
1644
1645     if (length $data->{owner}) {
1646         $addmaint = $data->{owner};
1647         &transcript("MO|$addmaint|$data->{package}|$ref|\n") if $dl>2;
1648         $maintccreasons{$addmaint}{$data->{package}}{$ref} = 1;
1649         print "owner add >$data->{package}|$addmaint<\n" if $debug;
1650     }
1651 }
1652
1653 sub ensuremaintainersloaded {
1654     my ($a,$b);
1655     return if $maintainersloaded++;
1656     open(MAINT,"$gMaintainerFile") || die &quit("maintainers open: $!");
1657     while (<MAINT>) {
1658         m/^\n$/ && next;
1659         m/^\s*$/ && next;
1660         m/^(\S+)\s+(\S.*\S)\s*\n$/ || &quit("maintainers bogus \`$_'");
1661         $a= $1; $b= $2; $a =~ y/A-Z/a-z/;
1662         $maintainerof{$a}= $2;
1663     }
1664     close(MAINT);
1665     open(MAINT,"$gMaintainerFileOverride") || die &quit("maintainers.override open: $!");
1666     while (<MAINT>) {
1667         m/^\n$/ && next;
1668         m/^\s*$/ && next;
1669         m/^(\S+)\s+(\S.*\S)\s*\n$/ || &quit("maintainers.override bogus \`$_'");
1670         $a= $1; $b= $2; $a =~ y/A-Z/a-z/;
1671         $maintainerof{$a}= $2;
1672     }
1673
1674     open(SOURCES, "$gPackageSource") || &quit("pkgsrc open: $!");
1675     while (<SOURCES>) {
1676         next unless m/^(\S+)\s+\S+\s+(\S.*\S)\s*$/;
1677         my ($a, $b) = ($1, $2);
1678         $pkgsrc{lc($a)} = $b;
1679     }
1680     close(SOURCES);
1681 }
1682
1683 sub sendinfo {
1684     local ($wherefrom,$path,$description) = @_;
1685     if ($wherefrom eq "ftp.d.o") {
1686       $doc = `lynx -nolist -dump http://ftp.debian.org/debian/indices/$path.gz 2>&1 | gunzip -cf` or &quit("fork for lynx/gunzip: $!");
1687       $! = 0;
1688       if ($? == 255 && $doc =~ m/^\n*lynx: Can\'t access start file/) {
1689           &transcript("$description is not available.\n");
1690           $ok++; return;
1691       } elsif ($?) {
1692           &transcript("Error getting $description (code $? $!):\n$doc\n");
1693           return;
1694       }
1695     } elsif ($wherefrom eq "local") {
1696       open P, "$path";
1697       $doc = do { local $/; <P> };
1698       close P;
1699     } else {
1700       &transcript("internal errror: info files location unknown.\n");
1701       $ok++; return;
1702     }
1703     &transcript("Sending $description.\n");
1704     &sendmailmessage(<<END.$doc,$replyto);
1705 From: $gMaintainerEmail ($gProject $gBug Tracking System)
1706 To: $replyto
1707 Subject: $gProject $gBugs information: $description
1708 References: $header{'message-id'}
1709 In-Reply-To: $header{'message-id'}
1710 Message-ID: <handler.s.$nn.info.$midix\@$gEmailDomain>
1711 Precedence: bulk
1712 X-$gProject-PR-Message: getinfo
1713
1714 $description follows:
1715
1716 END
1717     $ok++;
1718     &transcript("\n");
1719 }