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