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