]> git.donarmstrong.com Git - debbugs.git/blob - scripts/service
Remove obsolute @maintcc and $packagepr bits
[debbugs.git] / scripts / service
1 #!/usr/bin/perl
2 # $Id: service.in,v 1.118 2005/10/19 01:22:14 don Exp $
3 #
4 # Usage: service <code>.nn
5 # Temps:  incoming/P<code>.nn
6
7 use warnings;
8 use strict;
9
10
11 use Debbugs::Config qw(:globals :config);
12
13 use File::Copy;
14 use MIME::Parser;
15
16 use Params::Validate qw(:types validate_with);
17
18 use Debbugs::Common qw(:util :quit :misc :lock);
19
20 use Debbugs::Status qw(:read :status :write :versions :hook);
21 use Debbugs::Packages qw(binary_to_source);
22
23 use Debbugs::MIME qw(decode_rfc1522 encode_rfc1522 create_mime_message);
24 use Debbugs::Mail qw(send_mail_message);
25 use Debbugs::User;
26 use Debbugs::Recipients qw(:all);
27 use HTML::Entities qw(encode_entities);
28 use Debbugs::Versions::Dpkg;
29
30 use Debbugs::Status qw(splitpackages);
31
32 use Debbugs::CGI qw(html_escape);
33 use Debbugs::Control qw(:all);
34 use Debbugs::Control::Service qw(:all);
35 use Debbugs::Log qw(:misc);
36 use Debbugs::Text qw(:templates);
37
38 use Scalar::Util qw(looks_like_number);
39
40 use List::Util qw(first);
41
42 use Mail::RFC822::Address;
43 use Encode qw(decode encode);
44
45 chdir($config{spool_dir}) or
46      die "Unable to chdir to spool_dir '$config{spool_dir}': $!";
47
48 my $debug = 0;
49 umask(002);
50
51 my ($nn,$control) = $ARGV[0] =~ m/^(([RC])\.\d+)$/;
52 if (not defined $control or not defined $nn) {
53      die "Bad argument to service.in";
54 }
55 if (!rename("incoming/G$nn","incoming/P$nn")) {
56     defined $! and $! =~ m/no such file or directory/i and exit 0;
57     die "Failed to rename incoming/G$nn to incoming/P$nn: $!";
58 }
59
60 my $log_fh = IO::File->new("incoming/P$nn",'r') or
61      die "Unable to open incoming/P$nn for reading: $!";
62 my @log=<$log_fh>;
63 my @msg=@log;
64 close($log_fh);
65
66 chomp @msg;
67
68 print "###\n",join("##\n",@msg),"\n###\n" if $debug;
69
70 # Bug numbers to send e-mail to, hash so that we don't send to the
71 # same bug twice.
72 my (%bug_affected);
73
74 my (@headerlines,@bodylines);
75
76 my $parse_output = Debbugs::MIME::parse(join('',@log));
77 @headerlines = @{$parse_output->{header}};
78 @bodylines = @{$parse_output->{body}};
79
80 my %header;
81 for (@headerlines) {
82     $_ = decode_rfc1522($_);
83     s/\n\s/ /g;
84     print ">$_<\n" if $debug;
85     if (s/^(\S+):\s*//) {
86         my $v = lc $1;
87         print ">$v=$_<\n" if $debug;
88         $header{$v} = $_;
89     } else {
90         print "!>$_<\n" if $debug;
91     }
92 }
93 $header{'message-id'} ||= '';
94 $header{subject} ||= '';
95
96 grep(s/\s+$//,@bodylines);
97
98 print "***\n",join("\n",@bodylines),"\n***\n" if $debug;
99
100 if (defined $header{'resent-from'} && !defined $header{'from'}) {
101     $header{'from'} = $header{'resent-from'};
102 }
103
104 defined($header{'from'}) || die "no From header";
105
106 delete $header{'reply-to'} 
107         if ( defined($header{'reply-to'}) && $header{'reply-to'} =~ m/^\s*$/ );
108
109 my $replyto;
110 if ( defined($header{'reply-to'}) && $header{'reply-to'} ne "" ) {
111     $replyto = $header{'reply-to'};
112 } else {
113     $replyto = $header{'from'};
114 }
115
116 # This is an error counter which should be incremented every time there is an error.
117 my $errors = 0;
118 my $controlrequestaddr= ($control ? 'control' : 'request').'@'.$config{email_domain};
119 my $transcript_scalar = '';
120 open my $transcript, ">:scalar:utf8", \$transcript_scalar or
121      die "Unable to create transcript scalar: $!";
122 print {$transcript} "Processing commands for $controlrequestaddr:\n\n";
123
124
125 my $dl = 0;
126 my %affected_packages;
127 my %recipients;
128 # this is the hashref which is passed to all control calls
129 my %limit = ();
130
131
132 my @common_control_options =
133     (transcript        => $transcript,
134      requester         => $header{from},
135      request_addr      => $controlrequestaddr,
136      request_msgid     => $header{'message-id'},
137      request_subject   => $header{subject},
138      request_nn        => $nn,
139      request_replyto   => $replyto,
140      message           => \@log,
141      affected_bugs     => \%bug_affected,
142      affected_packages => \%affected_packages,
143      recipients        => \%recipients,
144      limit             => \%limit,
145     );
146
147 my $state= 'idle';
148 my $lowstate= 'idle';
149 my $mergelowstate= 'idle';
150 my $midix=0;
151
152 my $user = $replyto;
153 $user =~ s/,.*//;
154 $user =~ s/^.*<(.*)>.*$/$1/;
155 $user =~ s/[(].*[)]//;
156 $user =~ s/^\s*(\S+)\s+.*$/$1/;
157 $user = "" unless (Debbugs::User::is_valid_user($user));
158 my $indicated_user = 0;
159
160 my $quickabort = 0;
161
162
163 if (@gExcludeFromControl and grep {$replyto =~ m/\Q$_\E/} @gExcludeFromControl) {
164         print {$transcript} fill_template('mail/excluded_from_control');
165         $quickabort = 1;
166 }
167
168 my %limit_pkgs = ();
169 my %clonebugs = ();
170 my %bcc = ();
171
172
173 our $data;
174 our $message;
175 our $extramessage;
176 our $ref;
177
178 our $mismatch;
179 our $action;
180
181
182 my $ok = 0;
183 my $unknowns = 0;
184 my $procline=0;
185 for ($procline=0; $procline<=$#bodylines; $procline++) {
186     my $noriginator;
187     my $newsubmitter;
188     my $oldsubmitter;
189     my $newowner;
190     $state eq 'idle' || print "state: $state ?\n";
191     $lowstate eq 'idle' || print "lowstate: $lowstate ?\n";
192     $mergelowstate eq 'idle' || print "mergelowstate: $mergelowstate ?\n";
193     if ($quickabort) {
194          print {$transcript} "Stopping processing here.\n\n";
195          last;
196     }
197     $_= $bodylines[$procline]; s/\s+$//;
198     # Remove BOM markers from UTF-8 strings
199     # Fixes #488554
200     s/\xef\xbb\xbf//g;
201     next unless m/\S/;
202     eval {
203         my $temp = decode("utf8",$_,Encode::FB_CROAK);
204         $_ = $temp;
205     };
206     print {$transcript} "> $_\n";
207     next if m/^\s*\#/;
208     $action= '';
209     if (m/^(?:stop|quit|--|thank(?:s|\s*you)?|kthxbye)\.*\s*$/i) {
210         print {$transcript} "Stopping processing here.\n\n";
211         last;
212     } elsif (m/^debug\s+(\d+)$/i && $1 >= 0 && $1 <= 1000) {
213         $dl= $1+0;
214         if ($dl > 0 and not grep /debug/,@common_control_options) {
215             push @common_control_options,(debug => $transcript);
216         }
217         print {$transcript} "Debug level $dl.\n\n";
218     } elsif (m/^(send|get)\s+\#?(\d{2,})$/i) {
219         $ref= $2+0;
220         &sendlynxdoc("bugreport.cgi?bug=$ref","logs for $gBug#$ref");
221     } elsif (m/^send-detail\s+\#?(\d{2,})$/i) {
222         $ref= $1+0;
223         &sendlynxdoc("bugreport.cgi?bug=$ref&boring=yes",
224                      "detailed logs for $gBug#$ref");
225     } elsif (m/^index(\s+full)?$/i) {
226         print {$transcript} "This BTS function is currently disabled, sorry.\n\n";
227         $errors++;
228         $ok++; # well, it's not really ok, but it fixes #81224 :)
229     } elsif (m/^index-summary\s+by-package$/i) {
230         print {$transcript} "This BTS function is currently disabled, sorry.\n\n";
231         $errors++;
232         $ok++; # well, it's not really ok, but it fixes #81224 :)
233     } elsif (m/^index-summary(\s+by-number)?$/i) {
234         print {$transcript} "This BTS function is currently disabled, sorry.\n\n";
235         $errors++;
236         $ok++; # well, it's not really ok, but it fixes #81224 :)
237     } elsif (m/^index(\s+|-)pack(age)?s?$/i) {
238         &sendlynxdoc("pkgindex.cgi?indexon=pkg",'index of packages');
239     } elsif (m/^index(\s+|-)maints?$/i) {
240         &sendlynxdoc("pkgindex.cgi?indexon=maint",'index of maintainers');
241     } elsif (m/^index(\s+|-)maint\s+(\S+)$/i) {
242         my $maint = $2;
243         &sendlynxdoc("pkgreport.cgi?maint=" . urlsanit($maint),
244                      "$gBug list for maintainer \`$maint'");
245         $ok++;
246     } elsif (m/^index(\s+|-)pack(age)?s?\s+(\S.*\S)$/i) {
247         my $package = $+;
248         &sendlynxdoc("pkgreport.cgi?pkg=" . urlsanit($package),
249                      "$gBug list for package $package");
250         $ok++;
251     } elsif (m/^send-unmatched(\s+this|\s+-?0)?$/i) {
252         print {$transcript} "This BTS function is currently disabled, sorry.\n\n";
253         $errors++;
254         $ok++; # well, it's not really ok, but it fixes #81224 :)
255     } elsif (m/^send-unmatched\s+(last|-1)$/i) {
256         print {$transcript} "This BTS function is currently disabled, sorry.\n\n";
257         $errors++;
258         $ok++; # well, it's not really ok, but it fixes #81224 :)
259     } elsif (m/^send-unmatched\s+(old|-2)$/i) {
260         print {$transcript} "This BTS function is currently disabled, sorry.\n\n";
261         $errors++;
262         $ok++; # well, it's not really ok, but it fixes #81224 :)
263     } elsif (m/^getinfo\s+([\w.-]+)$/i) {
264         # the following is basically a Debian-specific kludge, but who cares
265         my $req = $1;
266         if ($req =~ /^maintainers$/i && -f "$gConfigDir/Maintainers") {
267             &sendinfo("local", "$gConfigDir/Maintainers", "Maintainers file");
268         } elsif ($req =~ /^override\.(\w+)\.([\w.-]+)$/i) {
269             $req =~ s/.gz$//;
270             &sendinfo("ftp.d.o", "$req", "override file for $2 part of $1 distribution");
271         } elsif ($req =~ /^pseudo-packages\.(description|maintainers)$/i && -f "$gConfigDir/$req") {
272             &sendinfo("local", "$gConfigDir/$req", "$req file");
273         } else {
274             print {$transcript} "Info file $req does not exist.\n\n";
275         }
276     } elsif (m/^help/i) {
277         &sendhelp;
278         print {$transcript} "\n";
279         $ok++;
280     } elsif (m/^refcard/i) {
281         &sendtxthelp("bug-mailserver-refcard.txt","mail servers' reference card");
282     } elsif (m/^subscribe/i) {
283         print {$transcript} <<END;
284 There is no $gProject $gBug mailing list.  If you wish to review bug reports
285 please do so via http://$gWebDomain/ or ask this mail server
286 to send them to you.
287 soon: MAILINGLISTS_TEXT
288 END
289     } elsif (m/^unsubscribe/i) {
290         print {$transcript} <<END;
291 soon: UNSUBSCRIBE_TEXT
292 soon: MAILINGLISTS_TEXT
293 END
294     } elsif (m/^user\s+(\S+)\s*$/i) {
295         my $newuser = $1;
296         if (Debbugs::User::is_valid_user($newuser)) {
297             my $olduser = ($user ne "" ? " (was $user)" : "");
298             print {$transcript} "Setting user to $newuser$olduser.\n";
299             $user = $newuser;
300             $indicated_user = 1;
301         } else {
302             print {$transcript} "Selected user id ($newuser) invalid, sorry\n";
303             $errors++;
304             $user = "";
305             $indicated_user = 1;
306         }
307     } elsif (m/^usercategory\s+(\S+)(\s+\[hidden\])?\s*$/i) {
308         $ok++;
309         my $catname = $1;
310         my $hidden = (defined $2 and $2 ne "");
311
312         my $prefix = "";
313         my @cats;
314         my $bad = 0;
315         my $catsec = 0;
316         if ($user eq "") {
317             print {$transcript} "No valid user selected\n";
318             $errors++;
319             next;
320         }
321         if (not $indicated_user and defined $user) {
322              print {$transcript} "User is $user\n";
323              $indicated_user = 1;
324         }
325         my @ords = ();
326         while (++$procline <= $#bodylines) {
327             unless ($bodylines[$procline] =~ m/^\s*([*+])\s*(\S.*)$/) {
328                 $procline--;
329                 last;
330             }
331             print {$transcript} "> $bodylines[$procline]\n";
332             next if $bad;
333             my ($o, $txt) = ($1, $2);
334             if ($#cats == -1 && $o eq "+") {
335                 print {$transcript} "User defined category specification must start with a category name. Skipping.\n\n";
336                 $errors++;
337                 $bad = 1;
338                 next;
339             }
340             if ($o eq "+") {
341                 unless (ref($cats[-1]) eq "HASH") {
342                     $cats[-1] = { "nam" => $cats[-1], 
343                                   "pri" => [], "ttl" => [] };
344                 }
345                 $catsec++;
346                 my ($desc, $ord, $op);
347                 if ($txt =~ m/^(.*\S)\s*\[((\d+):\s*)?\]\s*$/) {
348                     $desc = $1; $ord = $3; $op = "";
349                 } elsif ($txt =~ m/^(.*\S)\s*\[((\d+):\s*)?(\S+)\]\s*$/) {
350                     $desc = $1; $ord = $3; $op = $4;
351                 } elsif ($txt =~ m/^([^[\s]+)\s*$/) {
352                     $desc = ""; $op = $1;
353                 } else {
354                     print {$transcript} "Unrecognised syntax for category section. Skipping.\n\n";
355                     $errors++;
356                     $bad = 1;
357                     next;
358                 }
359                 $ord = 999 unless defined $ord;
360
361                 if ($op) {
362                     push @{$cats[-1]->{"pri"}}, $prefix . $op;
363                     push @{$cats[-1]->{"ttl"}}, $desc;
364                     push @ords, "$ord $catsec";
365                 } else {
366                     $cats[-1]->{"def"} = $desc;
367                     push @ords, "$ord DEF";
368                     $catsec--;
369                 }
370                 @ords = sort {
371                     my ($a1, $a2, $b1, $b2) = split / /, "$a $b";
372                     ((looks_like_number($a1) and looks_like_number($a2))?$a1 <=> $b1:$a1 cmp $b1) ||
373                     ((looks_like_number($a2) and looks_like_number($b2))?$a2 <=> $b2:$a2 cmp $b2);
374                 } @ords;
375                 $cats[-1]->{"ord"} = [map { m/^.* (\S+)/; $1 eq "DEF" ? $catsec + 1 : $1 } @ords];
376             } elsif ($o eq "*") {
377                 $catsec = 0;
378                 my ($name);
379                 if ($txt =~ m/^(.*\S)(\s*\[(\S+)\])\s*$/) {
380                     $name = $1; $prefix = $3;
381                 } else {
382                     $name = $txt; $prefix = "";
383                 }
384                 push @cats, $name;
385             }
386         }
387         # XXX: got @cats, now do something with it
388         my $u = Debbugs::User::get_user($user);
389         if (@cats) {
390             print {$transcript} "Added usercategory $catname.\n\n";
391             $u->{"categories"}->{$catname} = [ @cats ];
392             if (not $hidden) {
393                  push @{$u->{visible_cats}},$catname;
394             }
395         } else {
396             print {$transcript} "Removed usercategory $catname.\n\n";
397             delete $u->{"categories"}->{$catname};
398             @{$u->{visible_cats}} = grep {$_ ne $catname} @{$u->{visible_cats}};
399         }
400         $u->write();
401     } elsif (m/^usertags?\s+\#?(-?\d+)\s+(([=+-])\s*)?(\S.*)?$/i) {
402         $ok++;
403         $ref = $1;
404         my $addsubcode = $3 || "+";
405         my $tags = $4;
406         if ($ref =~ m/^-\d+$/ && defined $clonebugs{$ref}) {
407              $ref = $clonebugs{$ref};
408         }
409         if ($user eq "") {
410             print {$transcript} "No valid user selected\n";
411             $errors++;
412             $indicated_user = 1;
413         } elsif (check_limit(data => read_bug(bug => $ref),
414                              limit => \%limit,
415                              transcript => $transcript)) {
416             if (not $indicated_user and defined $user) {
417                  print {$transcript} "User is $user\n";
418                  $indicated_user = 1;
419             }
420             my %ut;
421             Debbugs::User::read_usertags(\%ut, $user);
422             my @oldtags = (); my @newtags = (); my @badtags = ();
423             my %chtags;
424             if (defined $tags and length $tags) {
425                  for my $t (split /[,\s]+/, $tags) {
426                       if ($t =~ m/^[a-zA-Z0-9.+\@-]+$/) {
427                            $chtags{$t} = 1;
428                       } else {
429                            push @badtags, $t;
430                       }
431                  }
432             }
433             if (@badtags) {
434                 print {$transcript} "Ignoring illegal tag/s: ".join(', ', @badtags).".\nPlease use only alphanumerics, at, dot, plus and dash.\n";
435                 $errors++;
436             }
437             for my $t (keys %chtags) {
438                 $ut{$t} = [] unless defined $ut{$t};
439             }
440             for my $t (keys %ut) {
441                 my %res = map { ($_, 1) } @{$ut{$t}};
442                 push @oldtags, $t if defined $res{$ref};
443                 my $addop = ($addsubcode eq "+" or $addsubcode eq "=");
444                 my $del = (defined $chtags{$t} ? $addsubcode eq "-" 
445                                                : $addsubcode eq "=");
446                 $res{$ref} = 1 if ($addop && defined $chtags{$t});
447                 delete $res{$ref} if ($del);
448                 push @newtags, $t if defined $res{$ref};
449                 $ut{$t} = [ sort { $a <=> $b } (keys %res) ];
450             }
451             if (@oldtags == 0) {
452                 print {$transcript} "There were no usertags set.\n";
453             } else {
454                 print {$transcript} "Usertags were: " . join(" ", @oldtags) . ".\n";
455             }
456             print {$transcript} "Usertags are now: " . join(" ", @newtags) . ".\n";
457             Debbugs::User::write_usertags(\%ut, $user);
458         }
459     } elsif (!$control) {
460         print {$transcript} <<END;
461 Unknown command or malformed arguments to command.
462 (Use control\@$gEmailDomain to manipulate reports.)
463
464 END
465         #### "developer only" ones start here
466     } elsif (defined valid_control($_)) {
467         my ($new_errors,$terminate_control) =
468             control_line(line => $_,
469                          clonebugs => \%clonebugs,
470                          limit => \%limit,
471                          common_control_options => \@common_control_options,
472                          errors => \$errors,
473                          transcript => $transcript,
474                          debug => $debug,
475                          ok => \$ok,
476                         );
477         if ($terminate_control) {
478             last;
479         }
480     } else {
481         $errors++;
482         if (++$unknowns >= 5) {
483             print {$transcript} "Too many unknown commands, stopping here.\n\n";
484             last;
485         }
486     }
487 }
488 if ($procline>$#bodylines) {
489     print {$transcript} ">\nEnd of message, stopping processing here.\n\n";
490 }
491 if (!$ok && !$quickabort) {
492     $errors++;
493     print {$transcript} "No commands successfully parsed; sending the help text(s).\n";
494     &sendhelp;
495     print {$transcript} "\n";
496 }
497
498 my @maintccs = determine_recipients(recipients => \%recipients,
499                                     address_only => 1,
500                                     cc => 1,
501                                    );
502 if (!defined $header{'subject'} || $header{'subject'} eq "") {
503   $header{'subject'} = "your mail";
504 }
505
506 # Error text here advertises how many errors there were
507 my $error_text = $errors > 0 ? " (with $errors errors)":'';
508
509 my @common_headers;
510 push @common_headers, 'X-Loop',$gMaintainerEmail;
511
512 my $temp_transcript = ${transcript_scalar};
513 eval{
514     $temp_transcript = decode("utf8",$temp_transcript,Encode::FB_CROAK);
515 };
516 my $reply =
517     create_mime_message([From          => "$gMaintainerEmail ($gProject $gBug Tracking System)",
518                          To            => $replyto,
519                          @maintccs ? (Cc => join(', ',@maintccs)):(),
520                          Subject       => "Processed${error_text}: $header{subject}",
521                          'Message-ID'  => "<handler.s.$nn.transcript\@$gEmailDomain>",
522                          'In-Reply-To' => $header{'message-id'},
523                          References    => join(' ',grep {defined $_} $header{'message-id'},$data->{msgid}),
524                          Precedence    => 'bulk',
525                          keys %affected_packages ?("X-${gProject}-PR-Package" => join(' ',keys %affected_packages)):(),
526                          keys %affected_packages ?("X-${gProject}-PR-Source" =>
527                                                    join(' ',
528                                                         map {defined $_ ?(ref($_)?@{$_}:$_):()}
529                                                         binary_to_source(binary => [keys %affected_packages],
530                                                                          source_only => 1))):(),
531                          "X-$gProject-PR-Message" => 'transcript',
532                          @common_headers,
533                         ],
534                         fill_template('mail/message_body',
535                                       {body => "${temp_transcript}Please contact me if you need assistance."},
536                                      ));
537
538 my $repliedshow= join(', ',$replyto,
539                       determine_recipients(recipients => \%recipients,
540                                            cc => 1,
541                                            address_only => 1,
542                                           )
543                      );
544
545 # -1 is the service.in log
546 &filelock("lock/-1");
547 open(AP,">>db-h/-1.log") || die "open db-h/-1.log: $!";
548 print(AP
549       "\2\n$repliedshow\n\5\n$reply\n\3\n".
550       "\6\n".
551       "<strong>Request received</strong> from <code>".
552       html_escape($header{'from'})."</code>\n".
553       "to <code>".html_escape($controlrequestaddr)."</code>\n".
554       "\3\n".
555       "\7\n",escape_log(@log),"\n\3\n") || die "writing db-h/-1.log: $!";
556 close(AP) || die "open db-h/-1.log: $!";
557 &unfilelock;
558 utime(time,time,"db-h");
559
560 &sendmailmessage($reply,
561                  exists $header{'x-debbugs-no-ack'}?():$replyto,
562                  make_list(values %{{determine_recipients(recipients => \%recipients,
563                                                           address_only => 1,
564                                                          )}}
565                           ),
566                 );
567
568 unlink("incoming/P$nn") || die "unlinking incoming/P$nn: $!";
569
570 sub sendmailmessage {
571     my ($message,@recips) = @_;
572     $message = "X-Loop: $gMaintainerEmail\n" . $message;
573     send_mail_message(message    => $message,
574                       recipients => \@recips,
575                      );
576     $midix++;
577 }
578
579 sub fill_template{
580      my ($template,$extra_var) = @_;
581      $extra_var ||={};
582      my $variables = {config => \%config,
583                       defined($ref)?(ref    => $ref):(),
584                       defined($data)?(data  => $data):(),
585                       refs => [map {exists $clonebugs{$_}?$clonebugs{$_}:$_} keys %bug_affected],
586                       %{$extra_var},
587                      };
588      my $hole_var = {'&bugurl' =>
589                      sub{"$_[0]: ".
590                               'http://'.$config{cgi_domain}.'/'.
591                                    Debbugs::CGI::bug_links(bug=>$_[0],
592                                                            links_only => 1,
593                                                           );
594                     }
595                     };
596      return fill_in_template(template => $template,
597                              variables => $variables,
598                              hole_var  => $hole_var,
599                             );
600 }
601
602 =head2 message_body_template
603
604      message_body_template('mail/ack',{ref=>'foo'});
605
606 Creates a message body using a template
607
608 =cut
609
610 sub message_body_template{
611      my ($template,$extra_var) = @_;
612      $extra_var ||={};
613      my $body = fill_template($template,$extra_var);
614      return fill_template('mail/message_body',
615                           {%{$extra_var},
616                            body => $body,
617                           },
618                          );
619 }
620
621 sub sendhelp {
622      if ($control) {
623           &sendtxthelpraw("bug-maint-mailcontrol.txt","instructions for control\@$gEmailDomain")
624      }
625      else {
626           &sendtxthelpraw("bug-log-mailserver.txt","instructions for request\@$gEmailDomain");
627      }
628 }
629
630 #sub unimplemented {
631 #    print {$transcript} "Sorry, command $_[0] not yet implemented.\n\n";
632 #}
633 our %checkmatch_values;
634 sub checkmatch {
635     my ($string,$mvarname,$svarvalue,@newmergelist) = @_;
636     my ($mvarvalue);
637     if (@newmergelist) {
638         $mvarvalue = $checkmatch_values{$mvarname};
639         print {$transcript} "D| checkmatch \`$string' /$mvarname/$mvarvalue/$svarvalue/\n"
640             if $dl;
641         $mismatch .=
642             "Values for \`$string' don't match:\n".
643             " #$newmergelist[0] has \`$mvarvalue';\n".
644             " #$ref has \`$svarvalue'\n"
645             if $mvarvalue ne $svarvalue;
646     } else {
647          print {$transcript} "D| setupmatch \`$string' /$mvarname/$svarvalue/\n"
648               if $dl;
649          $checkmatch_values{$mvarname} = $svarvalue;
650     }
651 }
652
653 sub checkpkglimit {
654     if (keys %limit_pkgs and not defined $limit_pkgs{$data->{package}}) {
655         print {$transcript} "$gBug number $ref belongs to package $data->{package}, skipping.\n\n";
656         $errors++;
657         return 0;
658     }
659     return 1;
660 }
661
662 sub manipset {
663     my $list = shift;
664     my $elt = shift;
665     my $add = shift;
666
667     my %h = map { $_ => 1 } split ' ', $list;
668     if ($add) {
669         $h{$elt}=1;
670     }
671     else {
672         delete $h{$elt};
673     }
674     return join ' ', sort keys %h;
675 }
676
677 # High-level bug manipulation calls
678 # Do announcements themselves
679 #
680 # Possible calling sequences:
681 #    setbug (returns 0)
682 #    
683 #    setbug (returns 1)
684 #    &transcript(something)
685 #    nochangebug
686 #
687 #    setbug (returns 1)
688 #    $action= (something)
689 #    do {
690 #      (modify s_* variables)
691 #    } while (getnextbug);
692
693 our $manybugs;
694
695 sub nochangebug {
696     &dlen("nochangebug");
697     $state eq 'single' || $state eq 'multiple' || die "$state ?";
698     &cancelbug;
699     &endmerge if $manybugs;
700     $state= 'idle';
701     &dlex("nochangebug");
702 }
703
704 our $sref;
705 our @thisbugmergelist;
706
707 sub setbug {
708     &dlen("setbug $ref");
709     if ($ref =~ m/^-\d+/) {
710         if (!defined $clonebugs{$ref}) {
711             &notfoundbug;
712             &dlex("setbug => noclone");
713             return 0;
714         }
715         $ref = $clonebugs{$ref};
716     }
717     $state eq 'idle' || die "$state ?";
718     if (!&getbug) {
719         &notfoundbug;
720         &dlex("setbug => 0s");
721         return 0;
722     }
723
724     if (!&checkpkglimit) {
725         &cancelbug;
726         return 0;
727     }
728
729     @thisbugmergelist= split(/ /,$data->{mergedwith});
730     if (!@thisbugmergelist) {
731         &foundbug;
732         $manybugs= 0;
733         $state= 'single';
734         $sref=$ref;
735         &dlex("setbug => 1s");
736         return 1;
737     }
738     &cancelbug;
739     &getmerge;
740     $manybugs= 1;
741     if (!&getbug) {
742         &notfoundbug;
743         &endmerge;
744         &dlex("setbug => 0mc");
745         return 0;
746     }
747     &foundbug;
748     $state= 'multiple'; $sref=$ref;
749     &dlex("setbug => 1m");
750     return 1;
751 }
752
753 sub getnextbug {
754     &dlen("getnextbug");
755     $state eq 'single' || $state eq 'multiple' || die "$state ?";
756     &savebug;
757     if (!$manybugs || !@thisbugmergelist) {
758         length($action) || die;
759         print {$transcript} "$action\n$extramessage\n";
760         &endmerge if $manybugs;
761         $state= 'idle';
762         &dlex("getnextbug => 0");
763         return 0;
764     }
765     $ref= shift(@thisbugmergelist);
766     &getbug || die "bug $ref disappeared";
767     &foundbug;
768     &dlex("getnextbug => 1");
769     return 1;
770 }
771
772 # Low-level bug-manipulation calls
773 # Do no announcements
774 #
775 #    getbug (returns 0)
776 #
777 #    getbug (returns 1)
778 #    cancelbug
779 #
780 #    getmerge
781 #    $action= (something)
782 #    getbug (returns 1)
783 #    savebug/cancelbug
784 #    getbug (returns 1)
785 #    savebug/cancelbug
786 #    [getbug (returns 0)]
787 #    &transcript("$action\n\n")
788 #    endmerge
789
790 sub notfoundbug { print {$transcript} "$gBug number $ref not found. (Is it archived?)\n\n"; }
791 sub foundbug { print {$transcript} "$gBug#$ref: $data->{subject}\n"; }
792
793 sub getmerge {
794     &dlen("getmerge");
795     $mergelowstate eq 'idle' || die "$mergelowstate ?";
796     &filelock('lock/merge');
797     $mergelowstate='locked';
798     &dlex("getmerge");
799 }
800
801 sub endmerge {
802     &dlen("endmerge");
803     $mergelowstate eq 'locked' || die "$mergelowstate ?";
804     &unfilelock;
805     $mergelowstate='idle';
806     &dlex("endmerge");
807 }
808
809 sub getbug {
810     &dlen("getbug $ref");
811     $lowstate eq 'idle' || die "$state ?";
812     # Only use unmerged bugs here
813     if (($data = &lockreadbug($ref,'db-h'))) {
814         $sref= $ref;
815         $lowstate= "open";
816         &dlex("getbug => 1");
817         $extramessage='';
818         return 1;
819     }
820     $lowstate= 'idle';
821     &dlex("getbug => 0");
822     return 0;
823 }
824
825 sub cancelbug {
826     &dlen("cancelbug");
827     $lowstate eq 'open' || die "$state ?";
828     &unfilelock;
829     $lowstate= 'idle';
830     &dlex("cancelbug");
831 }
832
833 sub savebug {
834     &dlen("savebug $ref");
835     $lowstate eq 'open' || die "$lowstate ?";
836     length($action) || die;
837     $ref == $sref || die "read $sref but saving $ref ?";
838     append_action_to_log(bug => $ref,
839                          action => $action,
840                          requester => $header{from},
841                          request_addr => $controlrequestaddr,
842                          message => \@log,
843                          get_lock => 0,
844                         );
845     unlockwritebug($ref, $data);
846     $lowstate= "idle";
847     &dlex("savebug");
848 }
849
850 sub dlen {
851     return if !$dl;
852     print {$transcript} "C> @_ ($state $lowstate $mergelowstate)\n";
853 }
854
855 sub dlex {
856     return if !$dl;
857     print {$transcript} "R> @_ ($state $lowstate $mergelowstate)\n";
858 }
859
860 sub urlsanit {
861     my $url = shift;
862     $url =~ s/%/%25/g;
863     $url =~ s/\+/%2b/g;
864     my %saniarray = ('<','lt', '>','gt', '&','amp', '"','quot');
865     $url =~ s/([<>&"])/\&$saniarray{$1};/g;
866     return $url;
867 }
868
869 sub sendlynxdoc {
870     &sendlynxdocraw;
871     print {$transcript} "\n";
872     $ok++;
873 }
874
875 sub sendtxthelp {
876     &sendtxthelpraw;
877     print {$transcript} "\n";
878     $ok++;
879 }
880
881
882 our $doc;
883 sub sendtxthelpraw {
884     my ($relpath,$description) = @_;
885     $doc='';
886     if (not -e "$gDocDir/$relpath") {
887         print {$transcript} "Unfortunatly, the help text doesn't exist, so it wasn't sent.\n";
888         warn "Help text $gDocDir/$relpath not found";
889         return;
890     }
891     open(D,"$gDocDir/$relpath") || die "open doc file $relpath: $!";
892     while(<D>) { $doc.=$_; }
893     close(D);
894     print {$transcript} "Sending $description in separate message.\n";
895     &sendmailmessage(<<END.$doc,$replyto);
896 From: $gMaintainerEmail ($gProject $gBug Tracking System)
897 To: $replyto
898 Subject: $gProject $gBug help: $description
899 References: $header{'message-id'}
900 In-Reply-To: $header{'message-id'}
901 Message-ID: <handler.s.$nn.help.$midix\@$gEmailDomain>
902 Precedence: bulk
903 X-$gProject-PR-Message: doc-text $relpath
904
905 END
906     $ok++;
907 }
908
909 sub sendlynxdocraw {
910     my ($relpath,$description) = @_;
911     $doc='';
912     open(L,"lynx -nolist -dump http://$gCGIDomain/\Q$relpath\E 2>&1 |") || die "fork for lynx: $!";
913     while(<L>) { $doc.=$_; }
914     $!=0; close(L);
915     if ($? == 255 && $doc =~ m/^\n*lynx: Can\'t access start file/) {
916         print {$transcript} "Information ($description) is not available -\n".
917              "perhaps the $gBug does not exist or is not on the WWW yet.\n";
918          $ok++;
919     } elsif ($?) {
920         print {$transcript} "Error getting $description (code $? $!):\n$doc\n";
921     } else {
922         print {$transcript} "Sending $description.\n";
923         &sendmailmessage(<<END.$doc,$replyto);
924 From: $gMaintainerEmail ($gProject $gBug Tracking System)
925 To: $replyto
926 Subject: $gProject $gBugs information: $description
927 References: $header{'message-id'}
928 In-Reply-To: $header{'message-id'}
929 Message-ID: <handler.s.$nn.info.$midix\@$gEmailDomain>
930 Precedence: bulk
931 X-$gProject-PR-Message: doc-html $relpath
932
933 END
934          $ok++;
935     }
936 }
937
938
939 sub sendinfo {
940     my ($wherefrom,$path,$description) = @_;
941     if ($wherefrom eq "ftp.d.o") {
942       $doc = `lynx -nolist -dump http://ftp.debian.org/debian/indices/$path.gz 2>&1 | gunzip -cf` or die "fork for lynx/gunzip: $!";
943       $! = 0;
944       if ($? == 255 && $doc =~ m/^\n*lynx: Can\'t access start file/) {
945           print {$transcript} "$description is not available.\n";
946           $ok++; return;
947       } elsif ($?) {
948           print {$transcript} "Error getting $description (code $? $!):\n$doc\n";
949           return;
950       }
951     } elsif ($wherefrom eq "local") {
952       open P, "$path";
953       $doc = do { local $/; <P> };
954       close P;
955     } else {
956       print {$transcript} "internal errror: info files location unknown.\n";
957       $ok++; return;
958     }
959     print {$transcript} "Sending $description.\n";
960     &sendmailmessage(<<END.$doc,$replyto);
961 From: $gMaintainerEmail ($gProject $gBug Tracking System)
962 To: $replyto
963 Subject: $gProject $gBugs information: $description
964 References: $header{'message-id'}
965 In-Reply-To: $header{'message-id'}
966 Message-ID: <handler.s.$nn.info.$midix\@$gEmailDomain>
967 Precedence: bulk
968 X-$gProject-PR-Message: getinfo
969
970 $description follows:
971
972 END
973     $ok++;
974     print {$transcript} "\n";
975 }