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