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