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