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