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