]> git.donarmstrong.com Git - debbugs.git/blob - scripts/service.in
[project @ 2004-02-03 21:37:45 by cjwatson]
[debbugs.git] / scripts / service.in
1 #!/usr/bin/perl
2 # $Id: service.in,v 1.95 2004/02/03 21:37:45 cjwatson Exp $
3 #
4 # Usage: service <code>.nn
5 # Temps:  incoming/P<code>.nn
6
7 use File::Copy;
8 use MIME::Parser;
9
10 $config_path = '/etc/debbugs';
11 $lib_path = '/usr/lib/debbugs';
12
13 require "$config_path/config";
14 require "$lib_path/errorlib";
15 $ENV{'PATH'} = $lib_path.':'.$ENV{'PATH'};
16
17 chdir("$gSpoolDir") || die "chdir spool: $!\n";
18
19 # open(DEBUG,">&4");
20 open DEBUG, ">/dev/null";
21 $debug = 0;
22 umask(002);
23
24 $_=shift;
25 m/^[RC]\.\d+$/ || &quit("bad argument");
26 $control= m/C/;
27 $nn= $_;
28 if (!rename("incoming/G$nn","incoming/P$nn")) {
29     $_=$!.'';  m/no such file or directory/i && exit 0;
30     &quit("renaming to lock: $!");
31 }    
32
33 open(M,"incoming/P$nn");
34 @log=<M>;
35 @msg=@log;
36 close(M);
37
38 chomp @msg;
39
40 print "###\n",join("##\n",@msg),"\n###\n" if $debug;
41
42 my $parser = new MIME::Parser;
43 mkdir "$gSpoolDir/mime.tmp", 0777;
44 $parser->output_under("$gSpoolDir/mime.tmp");
45 my $entity = eval { $parser->parse_data(join('',@log)) };
46
47 # header and decoded body respectively
48 my (@headerlines, @bodylines);
49
50 if ($entity and $entity->head->tags) {
51     @headerlines = @{$entity->head->header};
52     chomp @headerlines;
53
54     my $entity_body = getmailbody($entity);
55     @bodylines = $entity_body ? $entity_body->as_lines() : ();
56     chomp @bodylines;
57 } else {
58     # Legacy pre-MIME code, kept around in case MIME::Parser fails.
59     my $i;
60     for ($i = 0; $i <= $#msg; $i++) {
61         $_ = $msg[$i];
62         last unless length($_);
63         while ($msg[$i+1] =~ m/^\s/) {
64             $i++;
65             $_ .= "\n".$msg[$i];
66         }
67         push @headerlines, $_;
68     }
69
70     @bodylines = @msg[$i..$#msg];
71 }
72
73 for (@headerlines) {
74     s/\n\s/ /g;
75     print ">$_<\n" if $debug;
76     if (s/^(\S+):\s*//) {
77         my $v = lc $1;
78         print ">$v=$_<\n" if $debug;
79         $header{$v} = $_;
80     } else {
81         print "!>$_<\n" if $debug;
82     }
83 }
84
85 # Strip off RFC2440-style PGP clearsigning.
86 if (@bodylines and $bodylines[0] =~ /^-----BEGIN PGP SIGNED/) {
87     shift @bodylines while @bodylines and length $bodylines[0];
88     shift @bodylines while @bodylines and $bodylines[0] !~ /\S/;
89     for my $findsig (0 .. $#bodylines) {
90         if ($bodylines[$findsig] =~ /^-----BEGIN PGP SIGNATURE/) {
91             $#bodylines = $findsig - 1;
92             last;
93         }
94     }
95     map { s/^- // } @bodylines;
96 }
97
98 grep(s/\s+$//,@bodylines);
99
100 print "***\n",join("\n",@bodylines),"\n***\n" if $debug;
101
102 if (defined $header{'resent-from'} && !defined $header{'from'}) {
103     $header{'from'} = $header{'resent-from'};
104 }
105
106 defined($header{'from'}) || &quit("no From header");
107
108 delete $header{'reply-to'} 
109         if ( defined($header{'reply-to'}) && $header{'reply-to'} =~ m/^\s*$/ );
110
111 if ( defined($header{'reply-to'}) && $header{'reply-to'} ne "" ) {
112     $replyto = $header{'reply-to'};
113 } else {
114     $replyto = $header{'from'};
115 }
116
117 $controlrequestaddr= $control ? "control\@$gEmailDomain" : "request\@$gEmailDomain";
118 $transcript='';
119 &transcript("Processing commands for $controlrequestaddr:\n\n");
120
121 $dl= 0;
122 $state= 'idle';
123 $lowstate= 'idle';
124 $mergelowstate= 'idle';
125 $midix=0;    
126 $extras="";
127
128 my $quickabort = 0;
129
130 my $fuckheads = "(" . join("|", @gFuckheads) . ")";
131 if (@gFuckheads and $replyto =~ m/$fuckheads/) {
132         &transcript("This service is unavailable.\n\n");
133         $quickabort = 1;
134 }
135
136 my %limit_pkgs = ();
137 my %clonebugs = ();
138 my @bcc = ();
139
140 sub addbcc {
141     push @bcc, $_[0] unless grep { $_ eq $_[0] } @bcc;
142 }
143
144 for ($procline=0; $procline<=$#bodylines; $procline++) {
145     $state eq 'idle' || print "$state ?\n";
146     $lowstate eq 'idle' || print "$lowstate ?\n";
147     $mergelowstate eq 'idle' || print "$mergelowstate ?\n";
148     if ($quickabort) {
149          &transcript("Stopping processing here.\n\n");
150          last;
151     }
152     $_= $bodylines[$procline]; s/\s+$//;
153     next unless m/\S/;
154     &transcript("> $_\n");
155     next if m/^\s*\#/;
156     $action= '';
157     if (m/^stop/i || m/^quit/i || m/^--/ || m/^thank/i) {
158         &transcript("Stopping processing here.\n\n");
159         last;
160     } elsif (m/^debug\s+(\d+)$/i && $1 >= 0 && $1 <= 1000) {
161         $dl= $1+0;
162         &transcript("Debug level $dl.\n\n");
163     } elsif (m/^(send|get)\s+\#?(\d{2,})$/i) {
164         $ref= $2+0;
165         &sendlynxdoc("bugreport.cgi?bug=$ref","logs for $gBug#$ref");
166     } elsif (m/^send-detail\s+\#?(\d{2,})$/i) {
167         $ref= $1+0;
168         &sendlynxdoc("bugreport.cgi?bug=$ref&boring=yes",
169                      "detailed logs for $gBug#$ref");
170     } elsif (m/^index(\s+full)?$/i) {
171         &transcript("This BTS function is currently disabled, sorry.\n\n");
172         $ok++; # well, it's not really ok, but it fixes #81224 :)
173     } elsif (m/^index-summary\s+by-package$/i) {
174         &transcript("This BTS function is currently disabled, sorry.\n\n");
175         $ok++; # well, it's not really ok, but it fixes #81224 :)
176     } elsif (m/^index-summary(\s+by-number)?$/i) {
177         &transcript("This BTS function is currently disabled, sorry.\n\n");
178         $ok++; # well, it's not really ok, but it fixes #81224 :)
179     } elsif (m/^index(\s+|-)pack(age)?s?$/i) {
180         &sendlynxdoc("pkgindex.cgi?indexon=pkg",'index of packages');
181     } elsif (m/^index(\s+|-)maints?$/i) {
182         &sendlynxdoc("pkgindex.cgi?indexon=maint",'index of maintainers');
183     } elsif (m/^index(\s+|-)maint\s+(\S+)$/i) {
184         $maint = $2;
185         &sendlynxdoc("pkgreport.cgi?maint=" . urlsanit($maint),
186                      "$gBug list for maintainer \`$maint'");
187         $ok++;
188     } elsif (m/^index(\s+|-)pack(age)?s?\s+(\S.*\S)$/i) {
189         $package = $+;
190         &sendlynxdoc("pkgreport.cgi?pkg=" . urlsanit($package),
191                      "$gBug list for package $package");
192         $ok++;
193     } elsif (m/^send-unmatched(\s+this|\s+-?0)?$/i) {
194         &transcript("This BTS function is currently disabled, sorry.\n\n");
195         $ok++; # well, it's not really ok, but it fixes #81224 :)
196     } elsif (m/^send-unmatched\s+(last|-1)$/i) {
197         &transcript("This BTS function is currently disabled, sorry.\n\n");
198         $ok++; # well, it's not really ok, but it fixes #81224 :)
199     } elsif (m/^send-unmatched\s+(old|-2)$/i) {
200         &transcript("This BTS function is currently disabled, sorry.\n\n");
201         $ok++; # well, it's not really ok, but it fixes #81224 :)
202     } elsif (m/^getinfo\s+([\w-.]+)$/i) {
203         # the following is basically a Debian-specific kludge, but who cares
204         $req = $1;
205         if ($req =~ /^maintainers$/i && -f "$gConfigDir/Maintainers") {
206             &sendinfo("local", "$gConfigDir/Maintainers", "Maintainers file");
207         } elsif ($req =~ /^override\.(\w+)\.([\w-.]+)$/i) {
208             $req =~ s/.gz$//;
209             &sendinfo("ftp.d.o", "$req", "override file for $2 part of $1 distribution");
210         } elsif ($req =~ /^pseudo-packages\.(description|maintainers)$/i && -f "$gConfigDir/$req") {
211             &sendinfo("local", "$gConfigDir/$req", "$req file");
212         } else {
213             &transcript("Info file $req does not exist.\n\n");
214         }
215     } elsif (m/^help/i) {
216         &sendhelp;
217         &transcript("\n");
218         $ok++;
219     } elsif (m/^refcard/i) {
220         &sendtxthelp("bug-mailserver-refcard.txt","mail servers' reference card");
221     } elsif (m/^subscribe/i) {
222         &transcript(<<END);
223 There is no $gProject $gBug mailing list.  If you wish to review bug reports
224 please do so via http://$gWebDomain/ or ask this mail server
225 to send them to you.
226 soon: MAILINGLISTS_TEXT
227 END
228     } elsif (m/^unsubscribe/i) {
229         &transcript(<<END);
230 soon: UNSUBSCRIBE_TEXT
231 soon: MAILINGLISTS_TEXT
232 END
233     } elsif (!$control) {
234         &transcript(<<END);
235 Unknown command or malformed arguments to command.
236 (Use control\@$gEmailDomain to manipulate reports.)
237
238 END
239         if (++$unknowns >= 3) {
240             &transcript("Too many unknown commands, stopping here.\n\n");
241             last;
242         }
243 #### interesting ones start here
244     } elsif (m/^close\s+\#?(-?\d+)$/i) {
245         $ok++;
246         $ref= $1;
247         if (&setbug) {
248             &transcript("'close' is deprecated; see http://$gWebDomain/Developer$gHTMLSuffix#closing.\n");
249             if (length($data->{done})) {
250                 &transcript("$gBug is already closed, cannot re-close.\n\n");
251                 &nochangebug;
252             } else {
253                 $action= "$gBug closed, send any further explanations to $data->{originator}";
254                 do {
255                     &addmaintainers($data);
256                                         if ( length( $gDoneList ) > 0 && length( $gListDomain ) >
257                                         0 ) { &addccaddress("$gDoneList\@$gListDomain"); }
258                     $data->{done}= $replyto;
259                     my @keywords= split ' ', $data->{keywords};
260                     if (grep $_ eq 'pending', @keywords) {
261                         $extramessage= "Removed pending tag.\n";
262                         $data->{keywords}= join ' ', grep $_ ne 'pending',
263                                                 @keywords;
264                     }
265
266                     $message= <<END;
267 From: $gMaintainerEmail ($gProject $gBug Tracking System)
268 To: $data->{originator}
269 Subject: $gBug#$ref acknowledged by developer
270          ($header{'subject'})
271 References: $header{'message-id'} $data->{msgid}
272 In-Reply-To: $data->{msgid}
273 Message-ID: <handler.$ref.$nn.notifdonectrl.$midix\@$gEmailDomain>
274 Reply-To: $ref\@$gEmailDomain
275
276 This is an automatic notification regarding your $gBug report
277 #$ref: $data->{subject},
278 which was filed against the $data->{package} package.
279
280 It has been marked as closed by one of the developers, namely
281 $replyto.
282
283 You should be hearing from them with a substantive response shortly,
284 in case you haven't already. If not, please contact them directly.
285
286 $gMaintainer
287 (administrator, $gProject $gBugs database)
288
289 END
290                     &sendmailmessage($message,$data->{originator});
291                 } while (&getnextbug);
292             }
293         }
294     } elsif (m/^reassign\s+\#?(-?\d+)\s+(\S.*\S)$/i) {
295         $ok++;
296         $ref= $1; $newpackage= $2;
297         $newpackage =~ y/A-Z/a-z/;
298         if (&setbug) {
299             if (length($data->{package})) {
300                 $action= "$gBug reassigned from package \`$data->{package}'".
301                          " to \`$newpackage'.";
302             } else {
303                 $action= "$gBug assigned to package \`$newpackage'.";
304             }
305             do {
306                 &addmaintainers($data);
307                 $data->{package}= $newpackage;
308                 &addmaintainers($data);
309             } while (&getnextbug);
310         }
311     } elsif (m/^reopen\s+\#?(-?\d+)$/i ? ($noriginator='', 1) :
312              m/^reopen\s+\#?(-?\d+)\s+\=$/i ? ($noriginator='', 1) :
313              m/^reopen\s+\#?(-?\d+)\s+\!$/i ? ($noriginator=$replyto, 1) :
314              m/^reopen\s+\#?(-?\d+)\s+(\S.*\S)$/i ? ($noriginator=$2, 1) : 0) {
315         $ok++;
316         $ref= $1;
317         if (&setbug) {
318             if (!length($data->{done})) {
319                 &transcript("$gBug is already open, cannot reopen.\n\n");
320                 &nochangebug;
321             } else {
322                 $action=
323                     $noriginator eq '' ? "$gBug reopened, originator not changed." :
324                         "$gBug reopened, originator set to $noriginator.";
325                 do {
326                     &addmaintainers($data);
327                     $data->{originator}= $noriginator eq '' ?  $data->{originator} : $noriginator;
328                     $data->{done}= '';
329                 } while (&getnextbug);
330             }
331         }
332     } elsif (m/^submitter\s+\#?(-?\d+)\s+\!$/i ? ($newsubmitter=$replyto, 1) :
333              m/^submitter\s+\#?(-?\d+)\s+(\S.*\S)$/i ? ($newsubmitter=$2, 1) : 0) {
334         $ok++;
335         $ref= $1;
336         if ($ref =~ m/^-\d+$/ && defined $clonebugs{$ref}) {
337             $ref = $clonebugs{$ref};
338         }
339         if (&getbug) {
340             &foundbug;
341             &addmaintainers($data);
342             $oldsubmitter= $data->{originator};
343             $data->{originator}= $newsubmitter;
344             $action= "Changed $gBug submitter from $oldsubmitter to $newsubmitter.";
345             &savebug;
346             &transcript("$action\n");
347             if (length($data->{done})) {
348                 &transcript("(By the way, that $gBug is currently marked as done.)\n");
349             }
350             &transcript("\n");
351             $message= <<END;
352 From: $gMaintainerEmail ($gProject $gBug Tracking System)
353 To: $oldsubmitter
354 Subject: $gBug#$ref submitter address changed
355          ($header{'subject'})
356 References: $header{'message-id'} $data->{msgid}
357 In-Reply-To: $data->{msgid}
358 Message-ID: <handler.$ref.$nn.newsubmitter.$midix\@$gEmailDomain>
359 Reply-To: $ref\@$gEmailDomain
360
361 The submitter address recorded for your $gBug report
362 #$ref: $data->{subject}
363 has been changed.
364
365 The new submitter address for this report is
366 $newsubmitter.
367
368 This change was made by
369 $replyto.
370 If it was incorrect, please contact them directly.
371
372 $gMaintainer
373 (administrator, $gProject $gBugs database)
374
375 END
376             &sendmailmessage($message,$oldsubmitter);
377         } else {
378             &notfoundbug;
379         }
380     } elsif (m/^forwarded\s+\#?(-?\d+)\s+(\S.*\S)$/i) {
381         $ok++;
382         $ref= $1; $whereto= $2;
383         if (&setbug) {
384             if (length($data->{forwarded})) {
385     $action= "Forwarded-to-address changed from $data->{forwarded} to $whereto.";
386             } else {
387     $action= "Noted your statement that $gBug has been forwarded to $whereto.";
388             }
389             if (length($data->{done})) {
390                 $extramessage= "(By the way, this $gBug is currently marked as done.)\n";
391             }
392             do {
393                 &addmaintainers($data);
394                 if (length($gForwardList)>0 && length($gListDomain)>0 ) {
395                      &addccaddress("$gForwardList\@$gListDomain"); 
396                 }
397                 $data->{forwarded}= $whereto;
398             } while (&getnextbug);
399         }
400     } elsif (m/^notforwarded\s+\#?(-?\d+)$/i) {
401         $ok++;
402         $ref= $1;
403         if (&setbug) {
404             if (!length($data->{forwarded})) {
405                 &transcript("$gBug is not marked as having been forwarded.\n\n");
406                 &nochangebug;
407             } else {
408     $action= "Removed annotation that $gBug had been forwarded to $data->{forwarded}.";
409                 do {
410                     &addmaintainers($data);
411                     $data->{forwarded}= '';
412                 } while (&getnextbug);
413             }
414         }
415     } elsif (m/^severity\s+\#?(-?\d+)\s+([-0-9a-z]+)$/i ||
416         m/^priority\s+\#?(-?\d+)\s+([-0-9a-z]+)$/i) {
417         $ok++;
418         $ref= $1;
419         $newseverity= $2;
420         if (!grep($_ eq $newseverity, @gSeverityList, "$gDefaultSeverity")) {
421             &transcript("Severity level \`$newseverity' is not known.\n".
422                         "Recognized are: $gShowSeverities.\n\n");
423         } elsif (exists $gObsoleteSeverities{$newseverity}) {
424             &transcript("Severity level \`$newseverity' is obsolete. " .
425                         "$gObsoleteSeverities{$newseverity}\n\n");
426         } elsif (&setbug) {
427             $printseverity= $data->{severity};
428             $printseverity= "$gDefaultSeverity" if $printseverity eq '';
429             $action= "Severity set to \`$newseverity'.";
430             do {
431                 &addmaintainers($data);
432                 if (defined $gStrongList and isstrongseverity($newseverity)) {
433                     addbcc("$gStrongList\@$gListDomain");
434                 }
435                 $data->{severity}= $newseverity;
436             } while (&getnextbug);
437         }
438     } elsif (m/^tags?\s+\#?(-?\d+)\s+(([=+-])\s*)?(\S.*)?$/i) {
439         $ok++;
440         $ref = $1; $addsubcode = $3; $tags = $4;
441         $addsub = "add";
442         if (defined $addsubcode) {
443             $addsub = "sub" if ($addsubcode eq "-");
444             $addsub = "add" if ($addsubcode eq "+");
445             $addsub = "set" if ($addsubcode eq "=");
446         }
447         my @okaytags = ();
448         my @badtags = ();
449         foreach my $t (split /[\s,]+/, $tags) {
450             if (!grep($_ eq $t, @gTags)) {
451                 push @badtags, $t;
452             } else {
453                 push @okaytags, $t;
454             }
455         }
456         if (@badtags) {
457             &transcript("Unknown tag/s: ".join(', ', @badtags).".\n".
458                         "Recognized are: ".join(' ', @gTags).".\n\n");
459         }
460         if (&setbug) {
461             if ($data->{keywords} eq '') {
462                 &transcript("There were no tags set.\n");
463             } else {
464                 &transcript("Tags were: $data->{keywords}\n");
465             }
466             if ($addsub eq "set") {
467                 $action= "Tags set to: " . join(", ", @okaytags);
468             } elsif ($addsub eq "add") {
469                 $action= "Tags added: " . join(", ", @okaytags);
470             } elsif ($addsub eq "sub") {
471                 $action= "Tags removed: " . join(", ", @okaytags);
472             }
473             do {
474                 &addmaintainers($data);
475                 $data->{keywords} = '' if ($addsub eq "set");
476                 if ($addsub eq "sub") {
477                     foreach my $t (@badtags) {
478                         $data->{keywords} = join ' ', grep $_ ne $t, 
479                             split ' ', $data->{keywords};
480                     }
481                 }
482                 foreach my $t (@okaytags) {
483                     $data->{keywords} = join ' ', grep $_ ne $t, 
484                         split ' ', $data->{keywords};
485                     $data->{keywords} = "$t $data->{keywords}" unless($addsub eq "sub");
486                 }
487                 $data->{keywords} =~ s/\s*$//;
488             } while (&getnextbug);
489         }
490     } elsif (m/^retitle\s+\#?(-?\d+)\s+(\S.*\S)\s*$/i) {
491         $ok++;
492         $ref= $1; $newtitle= $2;
493         if ($ref =~ m/^-\d+$/ && defined $clonebugs{$ref}) {
494             $ref = $clonebugs{$ref};
495         }
496         if (&getbug) {
497             &foundbug;
498             &addmaintainers($data);
499             $data->{subject}= $newtitle;
500             $action= "Changed $gBug title.";
501             &savebug;
502             &transcript("$action\n");
503             if (length($data->{done})) {
504                 &transcript("(By the way, that $gBug is currently marked as done.)\n");
505             }
506             &transcript("\n");
507         } else {
508             &notfoundbug;
509         }
510     } elsif (m/^unmerge\s+\#?(-?\d+)$/i) {
511         $ok++;
512         $ref= $1;
513         if (&setbug) {
514             if (!length($data->{mergedwith})) {
515                 &transcript("$gBug is not marked as being merged with any others.\n\n");
516                 &nochangebug;
517             } else {
518                 $mergelowstate eq 'locked' || die "$mergelowstate ?";
519                 $action= "Disconnected #$ref from all other report(s).";
520                 @newmergelist= split(/ /,$data->{mergedwith});
521                 $discref= $ref;
522                 do {
523                     &addmaintainers($data);
524                     $data->{mergedwith}= ($ref == $discref) ? ''
525                         : join(' ',grep($_ ne $ref,@newmergelist));
526                 } while (&getnextbug);
527             }
528         }
529     } elsif (m/^merge\s+#?(-?\d+(\s+#?-?\d+)+)\s*$/i) {
530         $ok++;
531         @tomerge= sort { $a <=> $b } split(/\s+#?/,$1);
532         @newmergelist= ();
533         my %tags = ();
534         &getmerge;
535         while (defined($ref= shift(@tomerge))) {
536             &transcript("D| checking merge $ref\n") if $dl;
537             $ref+= 0;
538             if ($ref =~ m/^-\d+$/ && defined $clonebugs{$ref}) {
539                 $ref = $clonebugs{$ref};
540             }
541             next if grep($_ eq $ref,@newmergelist);
542             if (!&getbug) { &notfoundbug; @newmergelist=(); last }
543             &foundbug;
544             &transcript("D| adding $ref ($data->{mergedwith})\n") if $dl;
545             $mismatch= '';
546             &checkmatch('package','m_package',$data->{package});
547             &checkmatch('forwarded addr','m_forwarded',$data->{forwarded});
548             $data->{severity} = '$gDefaultSeverity' if $data->{severity} eq '';
549             &checkmatch('severity','m_severity',$data->{severity});
550             &checkmatch('done mark','m_done',length($data->{done}) ? 'done' : 'open');
551             &checkmatch('owner','m_owner',$data->{owner});
552             foreach my $t (split /\s+/, $data->{keywords}) { $tags{$t} = 1; }
553             if (length($mismatch)) {
554                 &transcript("Mismatch - only $gBugs in same state can be merged:\n".
555                             $mismatch."\n");
556                 &cancelbug; @newmergelist=(); last;
557             }
558             push(@newmergelist,$ref);
559             push(@tomerge,split(/ /,$data->{mergedwith}));
560             &cancelbug;
561         }
562         if (@newmergelist) {
563             @newmergelist= sort { $a <=> $b } @newmergelist;
564             $action= "Merged @newmergelist.";
565             for $ref (@newmergelist) {
566                 &getbug || die "huh ?  $gBug $ref disappeared during merge";
567                 &addmaintainers($data);
568                 $data->{mergedwith}= join(' ',grep($_ ne $ref,@newmergelist));
569                 $data->{keywords}= join(' ', keys %tags);
570                 &savebug;
571             }
572             &transcript("$action\n\n");
573         }
574         &endmerge;
575     } elsif (m/^clone\s+#?(\d+)\s+((-\d+\s+)*-\d+)\s*$/i) {
576         $ok++;
577
578         $origref = $1;
579         @newclonedids = split /\s+/, $2;
580         $newbugsneeded = scalar(@newclonedids);
581
582         $ref = $origref;
583         if (&setbug) {
584             if (length($data->{mergedwith})) {
585                 &transcript("$gBug is marked as being merged with others.\n\n");
586                 &nochangebug;
587             } else {
588                 &filelock("nextnumber.lock");
589                 open(N,"nextnumber") || &quit("nextnumber: read: $!");
590                 $v=<N>; $v =~ s/\n$// || &quit("nextnumber bad format");
591                 $firstref= $v+0;  $v += $newbugsneeded;
592                 open(NN,">nextnumber"); print NN "$v\n"; close(NN);
593                 &unfilelock;
594
595                 $lastref = $firstref + $newbugsneeded - 1;
596
597                 if ($newbugsneeded == 1) {
598                     $action= "$gBug $origref cloned as bug $firstref.";
599                 } else {
600                     $action= "$gBug $origref cloned as bugs $firstref-$lastref.";
601                 }
602                 &getnextbug;
603                 my $ohash = get_hashname($origref);
604                 $ref = $firstref;
605                 for $newclonedid (@newclonedids) {
606                     $clonebugs{$newclonedid} = $ref;
607             
608                     my $hash = get_hashname($ref);
609                     copy("db-h/$ohash/$origref.log", "db-h/$hash/$ref.log");
610                     copy("db-h/$ohash/$origref.status", "db-h/$hash/$ref.status");
611                     copy("db-h/$ohash/$origref.summary", "db-h/$hash/$ref.summary");
612                     copy("db-h/$ohash/$origref.report", "db-h/$hash/$ref.report");
613                     &bughook('new', $ref, $data);
614
615                     $ref++;
616                 }
617             }
618         }
619     } elsif (m/^package\s+(\S.*\S)?\s*$/i) {
620         $ok++;
621         my @pkgs = split /\s+/, $1;
622         if (scalar(@pkgs) > 0) {
623                 %limit_pkgs = map { ($_, 1) } @pkgs;
624                 &transcript("Ignoring bugs not assigned to: " . 
625                         join(" ", keys(%limit_pkgs)) . "\n\n");
626         } else {
627                 %limit_pkgs = ();
628                 &transcript("Not ignoring any bugs.\n\n");
629         }
630     } elsif (m/^owner\s+\#?(-?\d+)\s+!$/i ? ($newowner = $replyto, 1) :
631              m/^owner\s+\#?(-?\d+)\s+(\S.*\S)$/i ? ($newowner = $2, 1) : 0) {
632         $ok++;
633         $ref = $1;
634         if (&setbug) {
635             if (length $data->{owner}) {
636                 $action = "Owner changed from $data->{owner} to $newowner.";
637             } else {
638                 $action = "Owner recorded as $newowner.";
639             }
640             if (length $data->{done}) {
641                 $extramessage = "(By the way, this $gBug is currently " .
642                                 "marked as done.)\n";
643             }
644             do {
645                 &addmaintainers($data);
646                 $data->{owner} = $newowner;
647             } while (&getnextbug);
648         }
649     } elsif (m/^noowner\s+\#?(-?\d+)$/i) {
650         $ok++;
651         $ref = $1;
652         if (&setbug) {
653             if (length $data->{owner}) {
654                 $action = "Removed annotation that $gBug was owned by " .
655                           "$data->{owner}.";
656                 do {
657                     &addmaintainers($data);
658                     $data->{owner} = '';
659                 } while (&getnextbug);
660             } else {
661                 &transcript("$gBug is not marked as having an owner.\n\n");
662                 &nochangebug;
663             }
664         }
665     } else {
666         &transcript("Unknown command or malformed arguments to command.\n\n");
667         if (++$unknowns >= 5) {
668             &transcript("Too many unknown commands, stopping here.\n\n");
669             last;
670         }
671     }
672 }
673 if ($procline>$#bodylines) {
674     &transcript(">\nEnd of message, stopping processing here.\n\n");
675 }
676 if (!$ok && !quickabort) {
677     &transcript("No commands successfully parsed; sending the help text(s).\n");
678     &sendhelp;
679     &transcript("\n");
680 }
681
682 &transcript("MC\n") if $dl>1;
683 @maintccs= ();
684 for $maint (keys %maintccreasons) {
685 &transcript("MM|$maint|\n") if $dl>1;
686     next if $maint eq $replyto;
687     $reasonstring= '';
688     $reasonsref= $maintccreasons{$maint};
689 &transcript("MY|$maint|\n") if $dl>2;
690     for $p (sort keys %$reasonsref) {
691 &transcript("MP|$p|\n") if $dl>2;
692         $reasonstring.= ', ' if length($reasonstring);
693         $reasonstring.= $p.' ' if length($p);
694         $reasonstring.= join(' ',map("#$_",sort keys %{$$reasonsref{$p}}));
695     }
696     if (length($reasonstring) > 40) {
697         (substr $reasonstring, 37) = "...";
698     }
699     $reasonstring = "" if (!defined($reasonstring));
700     push(@maintccs,"$maint ($reasonstring)");
701     push(@maintccaddrs,"$maint");
702 }
703
704 $maintccs = ""; 
705 if (@maintccs) {
706     &transcript("MC|@maintccs|\n") if $dl>2;
707     $maintccs .= "Cc: " . join(",\n    ",@maintccs) . "\n";
708 }
709
710 if (!defined $header{'subject'} || $header{'subject'} eq "") {
711   $header{'subject'} = "your mail";
712 }
713
714 $reply= <<END;
715 From: $gMaintainerEmail ($gProject $gBug Tracking System)
716 To: $replyto
717 ${maintccs}Subject: Processed: $header{'subject'}
718 In-Reply-To: $header{'message-id'}
719 References: $header{'message-id'}
720 Message-ID: <handler.s.$nn.transcript\@$gEmailDomain>
721 Precedence: bulk
722
723 ${transcript}Please contact me if you need assistance.
724
725 $gMaintainer
726 (administrator, $gProject $gBugs database)
727 $extras
728 END
729
730 $repliedshow= join(', ',$replyto,@maintccaddrs);
731 &filelock("lock/-1");
732 open(AP,">>db-h/-1.log") || &quit("open db-h/-1.log: $!");
733 print(AP
734       "\2\n$repliedshow\n\5\n$reply\n\3\n".
735       "\6\n".
736       "<strong>Request received</strong> from <code>".
737       &sani($header{'from'})."</code>\n".
738       "to <code>".&sani($controlrequestaddr)."</code>\n".
739       "\3\n".
740       "\7\n",@{escapelog(@log)},"\n\3\n") || &quit("writing db-h/-1.log: $!");
741 close(AP) || &quit("open db-h/-1.log: $!");
742 &unfilelock;
743 utime(time,time,"db-h");
744
745 &sendmailmessage($reply,$replyto,@maintccaddrs,@bcc);
746
747 unlink("incoming/P$nn") || &quit("unlinking incoming/P$nn: $!");
748
749 sub sendmailmessage {
750     local ($message,@recips) = @_;
751     $message = "X-Loop: $gMaintainerEmail\n" . $message;
752     print "mailing to >@recips<\n" if $debug;
753     $c= open(D,"|-");
754     defined($c) || &quit("mailing forking for sendmail: $!");
755     if (!$c) { # ie, we are the child process
756         exec '/usr/lib/sendmail','-f'."$gMaintainerEmail",'-odb','-oem','-oi',get_addresses(@recips);
757         die $!;
758     }
759     print(D $message) || &quit("writing to sendmail process: $!");
760     $!=0; close(D); $? && &quit("sendmail gave exit status $? ($!)");
761     $midix++;
762 }
763
764 sub sendhelp {
765         &sendtxthelpraw("bug-log-mailserver.txt","instructions for request\@$gEmailDomain");
766         &sendtxthelpraw("bug-maint-mailcontrol.txt","instructions for control\@$gEmailDomain")
767             if $control;
768 }
769
770 #sub unimplemented {
771 #    &transcript("Sorry, command $_[0] not yet implemented.\n\n");
772 #}
773
774 sub checkmatch {
775     local ($string,$mvarname,$svarvalue) = @_;
776     local ($mvarvalue);
777     if (@newmergelist) {
778         eval "\$mvarvalue= \$$mvarname";
779         &transcript("D| checkmatch \`$string' /$mvarname/$mvarvalue/$svarvalue/\n")
780             if $dl;
781         $mismatch .=
782             "Values for \`$string' don't match:\n".
783             " #$newmergelist[0] has \`$mvarvalue';\n".
784             " #$ref has \`$svarvalue'\n"
785             if $mvarvalue ne $svarvalue;
786     } else {
787         &transcript("D| setupmatch \`$string' /$mvarname/$svarvalue/\n")
788             if $dl;
789         eval "\$$mvarname= \$svarvalue";
790     }
791 }
792
793 # High-level bug manipulation calls
794 # Do announcements themselves
795 #
796 # Possible calling sequences:
797 #    setbug (returns 0)
798 #    
799 #    setbug (returns 1)
800 #    &transcript(something)
801 #    nochangebug
802 #
803 #    setbug (returns 1)
804 #    $action= (something)
805 #    do {
806 #      (modify s_* variables)
807 #    } while (getnextbug);
808
809 sub nochangebug {
810     &dlen("nochangebug");
811     $state eq 'single' || $state eq 'multiple' || die "$state ?";
812     &cancelbug;
813     &endmerge if $manybugs;
814     $state= 'idle';
815     &dlex("nochangebug");
816 }
817
818 sub setbug {
819     &dlen("setbug $ref");
820     if ($ref =~ m/^-\d+/) {
821         if (!defined $clonebugs{$ref}) {
822             &notfoundbug;
823             &dlex("setbug => noclone");
824             return 0;
825         }
826         $ref = $clonebugs{$ref};
827     }
828     $state eq 'idle' || die "$state ?";
829     if (!&getbug) {
830         &notfoundbug;
831         &dlex("setbug => 0s");
832         return 0;
833     }
834
835     if (keys(%limit_pkgs) && not defined $limit_pkgs{$data->{package}}) {
836         &transcript("$gBug number $ref belongs to package $data->{package}, skipping.\n\n");
837         &cancelbug;
838         return 0;
839     } 
840
841     @thisbugmergelist= split(/ /,$data->{mergedwith});
842     if (!@thisbugmergelist) {
843         &foundbug;
844         $manybugs= 0;
845         $state= 'single';
846         $sref=$ref;
847         &dlex("setbug => 1s");
848         return 1;
849     }
850     &cancelbug;
851     &getmerge;
852     $manybugs= 1;
853     if (!&getbug) {
854         &notfoundbug;
855         &endmerge;
856         &dlex("setbug => 0mc");
857         return 0;
858     }
859     &foundbug;
860     $state= 'multiple'; $sref=$ref;
861     &dlex("setbug => 1m");
862     return 1;
863 }
864
865 sub getnextbug {
866     &dlen("getnextbug");
867     $state eq 'single' || $state eq 'multiple' || die "$state ?";
868     &savebug;
869     if (!$manybugs || !@thisbugmergelist) {
870         length($action) || die;
871         &transcript("$action\n$extramessage\n");
872         &endmerge if $manybugs;
873         $state= 'idle';
874         &dlex("getnextbug => 0");
875         return 0;
876     }
877     $ref= shift(@thisbugmergelist);
878     &getbug || die "bug $ref disappeared";
879     &foundbug;
880     &dlex("getnextbug => 1");
881     return 1;
882 }
883
884 # Low-level bug-manipulation calls
885 # Do no announcements
886 #
887 #    getbug (returns 0)
888 #
889 #    getbug (returns 1)
890 #    cancelbug
891 #
892 #    getmerge
893 #    $action= (something)
894 #    getbug (returns 1)
895 #    savebug/cancelbug
896 #    getbug (returns 1)
897 #    savebug/cancelbug
898 #    [getbug (returns 0)]
899 #    &transcript("$action\n\n")
900 #    endmerge
901
902 sub notfoundbug { &transcript("$gBug number $ref not found.\n\n"); }
903 sub foundbug { &transcript("$gBug#$ref: $data->{subject}\n"); }
904
905 sub getmerge {
906     &dlen("getmerge");
907     $mergelowstate eq 'idle' || die "$mergelowstate ?";
908     &filelock('lock/merge');
909     $mergelowstate='locked';
910     &dlex("getmerge");
911 }
912
913 sub endmerge {
914     &dlen("endmerge");
915     $mergelowstate eq 'locked' || die "$mergelowstate ?";
916     &unfilelock;
917     $mergelowstate='idle';
918     &dlex("endmerge");
919 }
920
921 sub getbug {
922     &dlen("getbug $ref");
923     $lowstate eq 'idle' || die "$state ?";
924     if (($data = &lockreadbug($ref))) {
925         $sref= $ref;
926         $lowstate= "open";
927         &dlex("getbug => 1");
928         $extramessage='';
929         return 1;
930     }
931     $lowstate= 'idle';
932     &dlex("getbug => 0");
933     return 0;
934 }
935
936 sub cancelbug {
937     &dlen("cancelbug");
938     $lowstate eq 'open' || die "$state ?";
939     &unfilelock;
940     $lowstate= 'idle';
941     &dlex("cancelbug");
942 }
943
944 sub savebug {
945     &dlen("savebug $ref");
946     $lowstate eq 'open' || die "$lowstate ?";
947     length($action) || die;
948     $ref == $sref || die "read $sref but saving $ref ?";
949     my $hash = get_hashname($ref);
950     open(L,">>db-h/$hash/$ref.log") || &quit("opening db-h/$hash/$ref.log: $!");
951     print(L
952           "\6\n".
953           "<strong>".&sani($action)."</strong>\n".
954           "Request was from <code>".&sani($header{'from'})."</code>\n".
955           "to <code>".&sani($controlrequestaddr)."</code>. \n".
956           "\3\n".
957           "\7\n",@{escapelog(@log)},"\n\3\n") || &quit("writing db-h/$hash/$ref.log: $!");
958     close(L) || &quit("closing db-h/$hash/$ref.log: $!");
959     unlockwritebug($ref, $data);
960     $lowstate= "idle";
961     &dlex("savebug");
962 }
963
964 sub dlen {
965     return if !$dl;
966     &transcript("C> @_ ($state $lowstate $mergelowstate)\n");
967 }
968
969 sub dlex {
970     return if !$dl;
971     &transcript("R> @_ ($state $lowstate $mergelowstate)\n");
972 }
973
974 sub transcript {
975     print $_[0] if $debug;
976     $transcript.= $_[0];
977 }
978
979 sub urlsanit {
980     my $url = shift;
981     $url =~ s/%/%25/g;
982     $url =~ s/\+/%2b/g;
983     my %saniarray = ('<','lt', '>','gt', '&','amp', '"','quot');
984     $url =~ s/([<>&"])/\&$saniarray{$1};/g;
985     return $url;
986 }
987
988 sub sendlynxdoc {
989     &sendlynxdocraw;
990     &transcript("\n");
991     $ok++;
992 }
993
994 sub sendtxthelp {
995     &sendtxthelpraw;
996     &transcript("\n");
997     $ok++;
998 }
999
1000 sub sendtxthelpraw {
1001     local ($relpath,$description) = @_;
1002     $doc='';
1003     open(D,"$gDocDir/$relpath") || &quit("open doc file $relpath: $!");
1004     while(<D>) { $doc.=$_; }
1005     close(D);
1006     &transcript("Sending $description in separate message.\n");
1007     &sendmailmessage(<<END.$doc,$replyto);
1008 From: $gMaintainerEmail ($gProject $gBug Tracking System)
1009 To: $replyto
1010 Subject: $gProject $gBug help: $description
1011 References: $header{'message-id'}
1012 In-Reply-To: $header{'message-id'}
1013 Message-ID: <handler.s.$nn.help.$midix\@$gEmailDomain>
1014 Precedence: bulk
1015
1016 END
1017     $ok++;
1018 }
1019
1020 sub sendlynxdocraw {
1021     local ($relpath,$description) = @_;
1022     $doc='';
1023     open(L,"lynx -nolist -dump http://$gCGIDomain/\Q$relpath\E 2>&1 |") || &quit("fork for lynx: $!");
1024     while(<L>) { $doc.=$_; }
1025     $!=0; close(L);
1026     if ($? == 255 && $doc =~ m/^\n*lynx: Can\'t access start file/) {
1027         &transcript("Information ($description) is not available -\n".
1028                     "perhaps the $gBug does not exist or is not on the WWW yet.\n");
1029          $ok++;
1030     } elsif ($?) {
1031         &transcript("Error getting $description (code $? $!):\n$doc\n");
1032     } else {
1033         &transcript("Sending $description.\n");
1034         &sendmailmessage(<<END.$doc,$replyto);
1035 From: $gMaintainerEmail ($gProject $gBug Tracking System)
1036 To: $replyto
1037 Subject: $gProject $gBugs information: $description
1038 References: $header{'message-id'}
1039 In-Reply-To: $header{'message-id'}
1040 Message-ID: <handler.s.$nn.info.$midix\@$gEmailDomain>
1041 Precedence: bulk
1042
1043 END
1044          $ok++;
1045     }
1046 }
1047
1048 sub addccaddress {
1049     my ($cca) = @_;
1050     $maintccreasons{$cca}{''}{$ref}= 1;
1051 }
1052
1053 sub addmaintainers {
1054     # Data structure is:
1055     #   maintainer email address &c -> assoc of packages -> assoc of bug#'s
1056     my $data = shift;
1057     my ($p, $addmaint, $pshow);
1058     &ensuremaintainersloaded;
1059     $anymaintfound=0; $anymaintnotfound=0;
1060     for $p (split(m/[ \t?,():]+/, $data->{package})) {
1061         $p =~ y/A-Z/a-z/;
1062         $pshow= ($p =~ m/[-+.a-z0-9]+/ ? $& : '');
1063         if (defined $gSubscriptionDomain) {
1064             if (defined($pkgsrc{$p})) {
1065                 addbcc("$pkgsrc{$p}\@$gSubscriptionDomain");
1066             } else {
1067                 addbcc("$p\@$gSubscriptionDomain");
1068             }
1069         }
1070         if (defined $data->{severity} and defined $gStrongList and
1071                 isstrongseverity($data->{severity})) {
1072             addbcc("$gStrongList\@$gListDomain");
1073         }
1074         if (defined($maintainerof{$p})) {
1075             $addmaint= $maintainerof{$p};
1076             &transcript("MR|$addmaint|$p|$ref|\n") if $dl>2;
1077             $maintccreasons{$addmaint}{$p}{$ref}= 1;
1078             print "maintainer add >$p|$addmaint<\n" if $debug;
1079         } else { 
1080             print "maintainer none >$p<\n" if $debug; 
1081             &transcript("Warning: Unknown package '$p'\n");
1082             &transcript("MR|unknown-package|$p|$ref|\n") if $dl>2;
1083             $maintccreasons{$gUnknownMaintainerEmail}{$p}{$ref}= 1;
1084         }
1085     }
1086
1087     if (length $data->{owner}) {
1088         $addmaint = $data->{owner};
1089         &transcript("MO|$addmaint|$data->{package}|$ref|\n") if $dl>2;
1090         $maintccreasons{$addmaint}{$data->{package}}{$ref} = 1;
1091         print "owner add >$data->{package}|$addmaint<\n" if $debug;
1092     }
1093 }
1094
1095 sub ensuremaintainersloaded {
1096     my ($a,$b);
1097     return if $maintainersloaded++;
1098     open(MAINT,"$gMaintainerFile") || die &quit("maintainers open: $!");
1099     while (<MAINT>) {
1100         m/^\n$/ && next;
1101         m/^\s*$/ && next;
1102         m/^(\S+)\s+(\S.*\S)\s*\n$/ || &quit("maintainers bogus \`$_'");
1103         $a= $1; $b= $2; $a =~ y/A-Z/a-z/;
1104         $maintainerof{$1}= $2;
1105     }
1106     close(MAINT);
1107     open(MAINT,"$gMaintainerFileOverride") || die &quit("maintainers.override open: $!");
1108     while (<MAINT>) {
1109         m/^\n$/ && next;
1110         m/^\s*$/ && next;
1111         m/^(\S+)\s+(\S.*\S)\s*\n$/ || &quit("maintainers.override bogus \`$_'");
1112         $a= $1; $b= $2; $a =~ y/A-Z/a-z/;
1113         $maintainerof{$1}= $2;
1114     }
1115
1116     open(SOURCES, "$gPackageSource") || &quit("pkgsrc open: $!");
1117     while (<SOURCES>) {
1118         next unless m/^(\S+)\s+\S+\s+(\S.*\S)\s*$/;
1119         my ($a, $b) = ($1, $2);
1120         $pkgsrc{lc($a)} = $b;
1121     }
1122     close(SOURCES);
1123 }
1124
1125 sub sendinfo {
1126     local ($wherefrom,$path,$description) = @_;
1127     if ($wherefrom eq "ftp.d.o") {
1128       $doc = `lynx -nolist -dump http://ftp.debian.org/debian/indices/$path.gz 2>&1 | gunzip -cf` or &quit("fork for lynx/gunzip: $!");
1129       $! = 0;
1130       if ($? == 255 && $doc =~ m/^\n*lynx: Can\'t access start file/) {
1131           &transcript("$description is not available.\n");
1132           $ok++; return;
1133       } elsif ($?) {
1134           &transcript("Error getting $description (code $? $!):\n$doc\n");
1135           return;
1136       }
1137     } elsif ($wherefrom eq "local") {
1138       open P, "$path";
1139       $doc = do { local $/; <P> };
1140       close P;
1141     } else {
1142       &transcript("internal errror: info files location unknown.\n");
1143       $ok++; return;
1144     }
1145     &transcript("Sending $description.\n");
1146     &sendmailmessage(<<END.$doc,$replyto);
1147 From: $gMaintainerEmail ($gProject $gBug Tracking System)
1148 To: $replyto
1149 Subject: $gProject $gBugs information: $description
1150 References: $header{'message-id'}
1151 In-Reply-To: $header{'message-id'}
1152 Message-ID: <handler.s.$nn.info.$midix\@$gEmailDomain>
1153 Precedence: bulk
1154
1155 $description follows:
1156
1157 END
1158     $ok++;
1159     &transcript("\n");
1160 }