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