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