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