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