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