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