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