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