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