]> git.donarmstrong.com Git - debbugs.git/blob - scripts/service
Apply fix for ! in owner et al; fixes #681853 Thanks to jwilk for reporting
[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                          replyto => $replyto,
477                         );
478         if ($terminate_control) {
479             last;
480         }
481     } else {
482         $errors++;
483         if (++$unknowns >= 5) {
484             print {$transcript} "Too many unknown commands, stopping here.\n\n";
485             last;
486         }
487     }
488 }
489 if ($procline>$#bodylines) {
490     print {$transcript} ">\nEnd of message, stopping processing here.\n\n";
491 }
492 if (!$ok && !$quickabort) {
493     $errors++;
494     print {$transcript} "No commands successfully parsed; sending the help text(s).\n";
495     &sendhelp;
496     print {$transcript} "\n";
497 }
498
499 my @maintccs = determine_recipients(recipients => \%recipients,
500                                     address_only => 1,
501                                     cc => 1,
502                                    );
503 if (!defined $header{'subject'} || $header{'subject'} eq "") {
504   $header{'subject'} = "your mail";
505 }
506
507 # Error text here advertises how many errors there were
508 my $error_text = $errors > 0 ? " (with $errors errors)":'';
509
510 my @common_headers;
511 push @common_headers, 'X-Loop',$gMaintainerEmail;
512
513 my $temp_transcript = $transcript_scalar;
514 eval{
515     $temp_transcript = decode("utf8",$temp_transcript,Encode::FB_CROAK);
516 };
517 my $reply =
518     create_mime_message([From          => "$gMaintainerEmail ($gProject $gBug Tracking System)",
519                          To            => $replyto,
520                          @maintccs ? (Cc => join(', ',@maintccs)):(),
521                          Subject       => "Processed${error_text}: $header{subject}",
522                          'Message-ID'  => "<handler.s.$nn.transcript\@$gEmailDomain>",
523                          'In-Reply-To' => $header{'message-id'},
524                          References    => join(' ',grep {defined $_} $header{'message-id'},$data->{msgid}),
525                          Precedence    => 'bulk',
526                          keys %affected_packages ?("X-${gProject}-PR-Package" => join(' ',keys %affected_packages)):(),
527                          keys %affected_packages ?("X-${gProject}-PR-Source" =>
528                                                    join(' ',
529                                                         map {defined $_ ?(ref($_)?@{$_}:$_):()}
530                                                         binary_to_source(binary => [keys %affected_packages],
531                                                                          source_only => 1))):(),
532                          "X-$gProject-PR-Message" => 'transcript',
533                          @common_headers,
534                         ],
535                         fill_template('mail/message_body',
536                                       {body => "${temp_transcript}Please contact me if you need assistance."},
537                                      ));
538
539 my $repliedshow= join(', ',$replyto,
540                       determine_recipients(recipients => \%recipients,
541                                            cc => 1,
542                                            address_only => 1,
543                                           )
544                      );
545
546 utime(time,time,"db-h");
547
548 &sendmailmessage($reply,
549                  exists $header{'x-debbugs-no-ack'}?():$replyto,
550                  make_list(values %{{determine_recipients(recipients => \%recipients,
551                                                           address_only => 1,
552                                                          )}}
553                           ),
554                 );
555
556 unlink("incoming/P$nn") || die "unlinking incoming/P$nn: $!";
557
558 sub sendmailmessage {
559     my ($message,@recips) = @_;
560     $message = "X-Loop: $gMaintainerEmail\n" . $message;
561     send_mail_message(message    => $message,
562                       recipients => \@recips,
563                      );
564     $midix++;
565 }
566
567 sub fill_template{
568      my ($template,$extra_var) = @_;
569      $extra_var ||={};
570      my $variables = {config => \%config,
571                       defined($ref)?(ref    => $ref):(),
572                       defined($data)?(data  => $data):(),
573                       refs => [map {exists $clonebugs{$_}?$clonebugs{$_}:$_} keys %bug_affected],
574                       %{$extra_var},
575                      };
576      my $hole_var = {'&bugurl' =>
577                      sub{"$_[0]: ".
578                               'http://'.$config{cgi_domain}.'/'.
579                                    Debbugs::CGI::bug_links(bug=>$_[0],
580                                                            links_only => 1,
581                                                           );
582                     }
583                     };
584      return fill_in_template(template => $template,
585                              variables => $variables,
586                              hole_var  => $hole_var,
587                             );
588 }
589
590 =head2 message_body_template
591
592      message_body_template('mail/ack',{ref=>'foo'});
593
594 Creates a message body using a template
595
596 =cut
597
598 sub message_body_template{
599      my ($template,$extra_var) = @_;
600      $extra_var ||={};
601      my $body = fill_template($template,$extra_var);
602      return fill_template('mail/message_body',
603                           {%{$extra_var},
604                            body => $body,
605                           },
606                          );
607 }
608
609 sub sendhelp {
610      if ($control) {
611           &sendtxthelpraw("bug-maint-mailcontrol.txt","instructions for control\@$gEmailDomain")
612      }
613      else {
614           &sendtxthelpraw("bug-log-mailserver.txt","instructions for request\@$gEmailDomain");
615      }
616 }
617
618 #sub unimplemented {
619 #    print {$transcript} "Sorry, command $_[0] not yet implemented.\n\n";
620 #}
621 our %checkmatch_values;
622 sub checkmatch {
623     my ($string,$mvarname,$svarvalue,@newmergelist) = @_;
624     my ($mvarvalue);
625     if (@newmergelist) {
626         $mvarvalue = $checkmatch_values{$mvarname};
627         print {$transcript} "D| checkmatch \`$string' /$mvarname/$mvarvalue/$svarvalue/\n"
628             if $dl;
629         $mismatch .=
630             "Values for \`$string' don't match:\n".
631             " #$newmergelist[0] has \`$mvarvalue';\n".
632             " #$ref has \`$svarvalue'\n"
633             if $mvarvalue ne $svarvalue;
634     } else {
635          print {$transcript} "D| setupmatch \`$string' /$mvarname/$svarvalue/\n"
636               if $dl;
637          $checkmatch_values{$mvarname} = $svarvalue;
638     }
639 }
640
641 sub checkpkglimit {
642     if (keys %limit_pkgs and not defined $limit_pkgs{$data->{package}}) {
643         print {$transcript} "$gBug number $ref belongs to package $data->{package}, skipping.\n\n";
644         $errors++;
645         return 0;
646     }
647     return 1;
648 }
649
650 sub manipset {
651     my $list = shift;
652     my $elt = shift;
653     my $add = shift;
654
655     my %h = map { $_ => 1 } split ' ', $list;
656     if ($add) {
657         $h{$elt}=1;
658     }
659     else {
660         delete $h{$elt};
661     }
662     return join ' ', sort keys %h;
663 }
664
665 # High-level bug manipulation calls
666 # Do announcements themselves
667 #
668 # Possible calling sequences:
669 #    setbug (returns 0)
670 #    
671 #    setbug (returns 1)
672 #    &transcript(something)
673 #    nochangebug
674 #
675 #    setbug (returns 1)
676 #    $action= (something)
677 #    do {
678 #      (modify s_* variables)
679 #    } while (getnextbug);
680
681 our $manybugs;
682
683 sub nochangebug {
684     &dlen("nochangebug");
685     $state eq 'single' || $state eq 'multiple' || die "$state ?";
686     &cancelbug;
687     &endmerge if $manybugs;
688     $state= 'idle';
689     &dlex("nochangebug");
690 }
691
692 our $sref;
693 our @thisbugmergelist;
694
695 sub setbug {
696     &dlen("setbug $ref");
697     if ($ref =~ m/^-\d+/) {
698         if (!defined $clonebugs{$ref}) {
699             &notfoundbug;
700             &dlex("setbug => noclone");
701             return 0;
702         }
703         $ref = $clonebugs{$ref};
704     }
705     $state eq 'idle' || die "$state ?";
706     if (!&getbug) {
707         &notfoundbug;
708         &dlex("setbug => 0s");
709         return 0;
710     }
711
712     if (!&checkpkglimit) {
713         &cancelbug;
714         return 0;
715     }
716
717     @thisbugmergelist= split(/ /,$data->{mergedwith});
718     if (!@thisbugmergelist) {
719         &foundbug;
720         $manybugs= 0;
721         $state= 'single';
722         $sref=$ref;
723         &dlex("setbug => 1s");
724         return 1;
725     }
726     &cancelbug;
727     &getmerge;
728     $manybugs= 1;
729     if (!&getbug) {
730         &notfoundbug;
731         &endmerge;
732         &dlex("setbug => 0mc");
733         return 0;
734     }
735     &foundbug;
736     $state= 'multiple'; $sref=$ref;
737     &dlex("setbug => 1m");
738     return 1;
739 }
740
741 sub getnextbug {
742     &dlen("getnextbug");
743     $state eq 'single' || $state eq 'multiple' || die "$state ?";
744     &savebug;
745     if (!$manybugs || !@thisbugmergelist) {
746         length($action) || die;
747         print {$transcript} "$action\n$extramessage\n";
748         &endmerge if $manybugs;
749         $state= 'idle';
750         &dlex("getnextbug => 0");
751         return 0;
752     }
753     $ref= shift(@thisbugmergelist);
754     &getbug || die "bug $ref disappeared";
755     &foundbug;
756     &dlex("getnextbug => 1");
757     return 1;
758 }
759
760 # Low-level bug-manipulation calls
761 # Do no announcements
762 #
763 #    getbug (returns 0)
764 #
765 #    getbug (returns 1)
766 #    cancelbug
767 #
768 #    getmerge
769 #    $action= (something)
770 #    getbug (returns 1)
771 #    savebug/cancelbug
772 #    getbug (returns 1)
773 #    savebug/cancelbug
774 #    [getbug (returns 0)]
775 #    &transcript("$action\n\n")
776 #    endmerge
777
778 sub notfoundbug { print {$transcript} "$gBug number $ref not found. (Is it archived?)\n\n"; }
779 sub foundbug { print {$transcript} "$gBug#$ref: $data->{subject}\n"; }
780
781 sub getmerge {
782     &dlen("getmerge");
783     $mergelowstate eq 'idle' || die "$mergelowstate ?";
784     &filelock('lock/merge');
785     $mergelowstate='locked';
786     &dlex("getmerge");
787 }
788
789 sub endmerge {
790     &dlen("endmerge");
791     $mergelowstate eq 'locked' || die "$mergelowstate ?";
792     &unfilelock;
793     $mergelowstate='idle';
794     &dlex("endmerge");
795 }
796
797 sub getbug {
798     &dlen("getbug $ref");
799     $lowstate eq 'idle' || die "$state ?";
800     # Only use unmerged bugs here
801     if (($data = &lockreadbug($ref,'db-h'))) {
802         $sref= $ref;
803         $lowstate= "open";
804         &dlex("getbug => 1");
805         $extramessage='';
806         return 1;
807     }
808     $lowstate= 'idle';
809     &dlex("getbug => 0");
810     return 0;
811 }
812
813 sub cancelbug {
814     &dlen("cancelbug");
815     $lowstate eq 'open' || die "$state ?";
816     &unfilelock;
817     $lowstate= 'idle';
818     &dlex("cancelbug");
819 }
820
821 sub savebug {
822     &dlen("savebug $ref");
823     $lowstate eq 'open' || die "$lowstate ?";
824     length($action) || die;
825     $ref == $sref || die "read $sref but saving $ref ?";
826     append_action_to_log(bug => $ref,
827                          action => $action,
828                          requester => $header{from},
829                          request_addr => $controlrequestaddr,
830                          message => \@log,
831                          get_lock => 0,
832                         );
833     unlockwritebug($ref, $data);
834     $lowstate= "idle";
835     &dlex("savebug");
836 }
837
838 sub dlen {
839     return if !$dl;
840     print {$transcript} "C> @_ ($state $lowstate $mergelowstate)\n";
841 }
842
843 sub dlex {
844     return if !$dl;
845     print {$transcript} "R> @_ ($state $lowstate $mergelowstate)\n";
846 }
847
848 sub urlsanit {
849     my $url = shift;
850     $url =~ s/%/%25/g;
851     $url =~ s/\+/%2b/g;
852     my %saniarray = ('<','lt', '>','gt', '&','amp', '"','quot');
853     $url =~ s/([<>&"])/\&$saniarray{$1};/g;
854     return $url;
855 }
856
857 sub sendlynxdoc {
858     &sendlynxdocraw;
859     print {$transcript} "\n";
860     $ok++;
861 }
862
863 sub sendtxthelp {
864     &sendtxthelpraw;
865     print {$transcript} "\n";
866     $ok++;
867 }
868
869
870 our $doc;
871 sub sendtxthelpraw {
872     my ($relpath,$description) = @_;
873     $doc='';
874     if (not -e "$gDocDir/$relpath") {
875         print {$transcript} "Unfortunatly, the help text doesn't exist, so it wasn't sent.\n";
876         warn "Help text $gDocDir/$relpath not found";
877         return;
878     }
879     open(D,"$gDocDir/$relpath") || die "open doc file $relpath: $!";
880     while(<D>) { $doc.=$_; }
881     close(D);
882     print {$transcript} "Sending $description in separate message.\n";
883     &sendmailmessage(<<END.$doc,$replyto);
884 From: $gMaintainerEmail ($gProject $gBug Tracking System)
885 To: $replyto
886 Subject: $gProject $gBug help: $description
887 References: $header{'message-id'}
888 In-Reply-To: $header{'message-id'}
889 Message-ID: <handler.s.$nn.help.$midix\@$gEmailDomain>
890 Precedence: bulk
891 X-$gProject-PR-Message: doc-text $relpath
892
893 END
894     $ok++;
895 }
896
897 sub sendlynxdocraw {
898     my ($relpath,$description) = @_;
899     $doc='';
900     open(L,"lynx -nolist -dump http://$gCGIDomain/\Q$relpath\E 2>&1 |") || die "fork for lynx: $!";
901     while(<L>) { $doc.=$_; }
902     $!=0; close(L);
903     if ($? == 255 && $doc =~ m/^\n*lynx: Can\'t access start file/) {
904         print {$transcript} "Information ($description) is not available -\n".
905              "perhaps the $gBug does not exist or is not on the WWW yet.\n";
906          $ok++;
907     } elsif ($?) {
908         print {$transcript} "Error getting $description (code $? $!):\n$doc\n";
909     } else {
910         print {$transcript} "Sending $description.\n";
911         &sendmailmessage(<<END.$doc,$replyto);
912 From: $gMaintainerEmail ($gProject $gBug Tracking System)
913 To: $replyto
914 Subject: $gProject $gBugs information: $description
915 References: $header{'message-id'}
916 In-Reply-To: $header{'message-id'}
917 Message-ID: <handler.s.$nn.info.$midix\@$gEmailDomain>
918 Precedence: bulk
919 X-$gProject-PR-Message: doc-html $relpath
920
921 END
922          $ok++;
923     }
924 }
925
926
927 sub sendinfo {
928     my ($wherefrom,$path,$description) = @_;
929     if ($wherefrom eq "ftp.d.o") {
930       $doc = `lynx -nolist -dump http://ftp.debian.org/debian/indices/$path.gz 2>&1 | gunzip -cf` or die "fork for lynx/gunzip: $!";
931       $! = 0;
932       if ($? == 255 && $doc =~ m/^\n*lynx: Can\'t access start file/) {
933           print {$transcript} "$description is not available.\n";
934           $ok++; return;
935       } elsif ($?) {
936           print {$transcript} "Error getting $description (code $? $!):\n$doc\n";
937           return;
938       }
939     } elsif ($wherefrom eq "local") {
940       open P, "$path";
941       $doc = do { local $/; <P> };
942       close P;
943     } else {
944       print {$transcript} "internal errror: info files location unknown.\n";
945       $ok++; return;
946     }
947     print {$transcript} "Sending $description.\n";
948     &sendmailmessage(<<END.$doc,$replyto);
949 From: $gMaintainerEmail ($gProject $gBug Tracking System)
950 To: $replyto
951 Subject: $gProject $gBugs information: $description
952 References: $header{'message-id'}
953 In-Reply-To: $header{'message-id'}
954 Message-ID: <handler.s.$nn.info.$midix\@$gEmailDomain>
955 Precedence: bulk
956 X-$gProject-PR-Message: getinfo
957
958 $description follows:
959
960 END
961     $ok++;
962     print {$transcript} "\n";
963 }