]> git.donarmstrong.com Git - debbugs.git/blob - Debbugs/Mail.pm
document the default headers
[debbugs.git] / Debbugs / Mail.pm
1 # This module is part of debbugs, and is released
2 # under the terms of the GPL version 2, or any later
3 # version at your option.
4 # See the file README and COPYING for more information.
5 #
6 # Copyright 2004-7 by Don Armstrong <don@donarmstrong.com>.
7
8 package Debbugs::Mail;
9
10 =head1 NAME
11
12 Debbugs::Mail -- Outgoing Mail Handling
13
14 =head1 SYNOPSIS
15
16 use Debbugs::Mail qw(send_mail_message get_addresses);
17
18 my @addresses = get_addresses('blah blah blah foo@bar.com')
19 send_mail_message(message => <<END, recipients=>[@addresses]);
20 To: $addresses[0]
21 Subject: Testing
22
23 Testing 1 2 3
24 END
25
26 =head1 EXPORT TAGS
27
28 =over
29
30 =item :all -- all functions that can be exported
31
32 =back
33
34 =head1 FUNCTIONS
35
36
37 =cut
38
39 use warnings;
40 use strict;
41 use vars qw($VERSION $DEBUG %EXPORT_TAGS @EXPORT_OK @EXPORT);
42 use base qw(Exporter);
43
44 use IPC::Open3;
45 use POSIX qw(:sys_wait_h strftime);
46 use Time::HiRes qw(usleep);
47 use Mail::Address ();
48 use Debbugs::MIME qw(encode_rfc1522);
49 use Debbugs::Config qw(:config);
50 use Params::Validate qw(:types validate_with);
51
52 BEGIN{
53      ($VERSION) = q$Revision: 1.1 $ =~ /^Revision:\s+([^\s+])/;
54      $DEBUG = 0 unless defined $DEBUG;
55
56      @EXPORT = ();
57      %EXPORT_TAGS = (addresses => qw(get_addresses),
58                      misc      => qw(rfc822_date),
59                      mail      => qw(send_mail_message encode_headers default_headers),
60                     );
61      @EXPORT_OK = ();
62      Exporter::export_ok_tags(keys %EXPORT_TAGS);
63      $EXPORT_TAGS{all} = [@EXPORT_OK];
64 }
65
66 # We set this here so it can be overridden for testing purposes
67 our $SENDMAIL = $config{sendmail};
68
69 =head2 get_addresses
70
71      my @addresses = get_addresses('don@debian.org blars@debian.org
72                                     kamion@debian.org ajt@debian.org');
73
74 Given a string containing some e-mail addresses, parses the string
75 using Mail::Address->parse and returns a list of the addresses.
76
77 =cut
78
79 sub get_addresses {
80      return map { $_->address() } map { Mail::Address->parse($_) } @_;
81 }
82
83
84 =head2 default_headers
85
86       my @head = default_headers(queue_file => 'foo',
87                                  data       => $data,
88                                  msgid      => $header{'message-id'},
89                                  msgtype    => 'error',
90                                  headers    => [...],
91                                 );
92       create_mime_message(\@headers,
93                          ...
94                          );
95
96 This function is generally called to generate the headers for
97 create_mime_message (and anything else that needs a set of default
98 headers.)
99
100 In list context, returns an array of headers. In scalar context,
101 returns headers for shoving in a mail message after encoding using
102 encode_headers.
103
104 =head3 options
105
106 =over
107
108 =item queue_file -- the queue file which will generate this set of
109 headers (refered to as $nn in lots of the code)
110
111 =item data -- the data of the bug which this message involves; can be
112 undefined if there is no bug involved.
113
114 =item msgid -- the Message-ID: of the message which will generate this
115 set of headers
116
117 =item msgtype -- the type of message that this is.
118
119 =item pr_msg -- the pr message field
120
121 =item headers -- a set of headers which will override the default
122 headers; these headers will be passed through (and may be reordered.)
123 If a particular header is undef, it overrides the default, but isn't
124 passed through.
125
126 =back
127
128 =head3 default headers
129
130 =over
131
132 =item X-Loop -- set to the maintainer e-mail
133
134 =item From -- set to the maintainer e-mail
135
136 =item To -- set to Unknown recipients
137
138 =item Subject -- set to Unknown subject
139
140 =item Message-ID -- set appropriately (see code)
141
142 =item Precedence -- set to bulk
143
144 =item References -- set to the full set of message ids that are known
145 (from data and the msgid option)
146
147 =item In-Reply-To -- set to msg id or the msgid from data
148
149 =item X-Project-PR-Message -- set to pr_msg with the bug number appended
150
151 =item X-Project-PR-Package -- set to the package of the bug
152
153 =item X-Project-PR-Keywords -- set to the keywords of the bug
154
155 =item X-Project-PR-Source -- set to the source of the bug
156
157 =back
158
159 =cut
160
161 sub default_headers {
162     my %param = validate_with(params => \@_,
163                               spec   => {queue_file => {type => SCALAR,
164                                                         optional => 1,
165                                                        },
166                                          data       => {type => HASHREF,
167                                                         optional => 1,
168                                                        },
169                                          msgid      => {type => SCALAR,
170                                                         optional => 1,
171                                                        },
172                                          msgtype    => {type => SCALAR,
173                                                         default => 'misc',
174                                                         optional => 1,
175                                                        },
176                                          pr_msg     => {type => SCALAR,
177                                                         default => 'misc',
178                                                        },
179                                          headers    => {type => ARRAYREF,
180                                                         default => [],
181                                                        },
182                                         },
183                              );
184     my @header_order = (qw(X-Loop From To subject),
185                         qw(Message-ID In-Reply-To References));
186     my %header_order;
187     @header_order{map {lc $_} @header_order} = 0..$#header_order;
188     my %set_headers;
189     my @ordered_headers;
190     my @temp = @{$param{headers}};
191     my @other_headers;
192     while (my ($header,$value) = splice @temp,0,2) {
193         if (exists $header_order{lc($header)}) {
194             push @{$ordered_headers[$header_order{lc($header)}]},
195                 ($header,$value);
196         }
197         else {
198             push @other_headers,($header,$value);
199         }
200         $set_headers{lc($header)} = 1;
201     }
202
203     # calculate our headers
204     my $bug_num = exists $param{data} ? $param{data}{bug_num} : 'x';
205     my $nn = $param{queue_file};
206     # handle the user giving the actual queue filename instead of nn
207     $nn =~ s/^[a-zA-Z]([a-zA-Z])/$1/;
208     $nn = lc($nn);
209     my @msgids;
210     if (exists $param{msgid} and defined $param{msgid}) {
211         push @msgids, $param{msgid}
212     }
213     elsif (exists $param{data} and defined $param{data}{msgid}) {
214         push @msgids, $param{data}{msgid}
215     }
216     my %default_header;
217     $default_header{'X-Loop'} = $config{maintainer_email};
218     $default_header{From}     = "$config{maintainer_email} ($config{project} $config{ubug} Tracking System)";
219     $default_header{To}       = "Unknown recipients";
220     $default_header{Subject}  = "Unknown subject";
221     $default_header{'Message-ID'} = "<handler.${bug_num}.${nn}.$param{msgtype}\@$config{email_domain}>";
222     if (@msgids) {
223         $default_header{'In-Reply-To'} = $msgids[0];
224         $default_header{'References'} = join(' ',@msgids);
225     }
226     $default_header{Precedence} = 'bulk';
227     $default_header{"X-$config{project}-PR-Message"} = $param{pr_msg} . (exists $param{data} ? ' '.$param{data}{bug_num}:'');
228     $default_header{Date} = rfc822_date();
229     if (exists $param{data}) {
230         if (defined $param{data}{keywords}) {
231             $default_header{"X-$config{project}-PR-Keywords"} = $param{data}{keywords};
232         }
233         if (defined $param{data}{package}) {
234             $default_header{"X-$config{project}-PR-Package"} = $param{data}{package};
235             if ($param{data}{package} =~ /^src:(.+)$/) {
236                 $default_header{"X-$config{project}-PR-Source"} = $1;
237             }
238             else {
239                 my $pkg_src = getpkgsrc();
240                 $default_header{"X-$config{project}-PR-Source"} = $pkg_src->{$param{data}{package}};
241             }
242         }
243     }
244     for my $header (sort keys %default_header) {
245         next if $set_headers{lc($header)};
246         if (exists $header_order{lc($header)}) {
247             push @{$ordered_headers[$header_order{lc($header)}]},
248                 ($header,$default_header{$header});
249         }
250         else {
251             push @other_headers,($header,$header_order{lc($header)});
252         }
253     }
254     my @headers;
255     for my $hdr1 (@ordered_headers) {
256         next if not defined $hdr1;
257         my @temp = @{$hdr1};
258         while (my ($header,$value) = splice @temp,0,2) {
259             next if not defined $value;
260             push @headers,($header,$value);
261         }
262     }
263     push @headers,@other_headers;
264     if (wantarray) {
265         return @headers;
266     }
267     else {
268         my $headers = '';
269         while (my ($header,$value) = splice @headers,0,2) {
270             $headers .= "${header}: $value\n";
271         }
272         return $headers;
273     }
274 }
275
276
277
278 =head2 send_mail_message
279
280      send_mail_message(message    => $message,
281                        recipients => [@recipients],
282                        envelope_from => 'don@debian.org',
283                       );
284
285
286 =over
287
288 =item message -- message to send out
289
290 =item recipients -- recipients to send the message to. If undefed or
291 an empty arrayref, will use '-t' to parse the message for recipients.
292
293 =item envelope_from -- envelope_from for outgoing messages
294
295 =item encode_headers -- encode headers using RFC1522 (default)
296
297 =item parse_for_recipients -- use -t to parse the message for
298 recipients in addition to those specified. [Can be used to set Bcc
299 recipients, for example.]
300
301 =back
302
303 Returns true on success, false on failures. All errors are indicated
304 using warn.
305
306 =cut
307
308 sub send_mail_message{
309      my %param = validate_with(params => \@_,
310                                spec  => {sendmail_arguments => {type => ARRAYREF,
311                                                                 default => [qw(-odq -oem -oi)],
312                                                                },
313                                          parse_for_recipients => {type => BOOLEAN,
314                                                                   default => 0,
315                                                                  },
316                                          encode_headers       => {type => BOOLEAN,
317                                                                   default => 1,
318                                                                  },
319                                          message              => {type => SCALAR,
320                                                                  },
321                                          envelope_from        => {type => SCALAR,
322                                                                   optional => 1,
323                                                                  },
324                                          recipients           => {type => ARRAYREF|UNDEF,
325                                                                   optional => 1,
326                                                                  },
327                                         },
328                               );
329      my @sendmail_arguments = qw(-odq -oem -oi);
330      push @sendmail_arguments, '-f', $param{envelope_from} if exists $param{envelope_from};
331
332      my @recipients;
333      @recipients = @{$param{recipients}} if defined $param{recipients} and
334           ref($param{recipients}) eq 'ARRAY';
335      my %recipients;
336      @recipients{@recipients} = (1) x @recipients;
337      @recipients = keys %recipients;
338      # If there are no recipients, use -t to parse the message
339      if (@recipients == 0) {
340           $param{parse_for_recipients} = 1 unless exists $param{parse_for_recipients};
341      }
342      # Encode headers if necessary
343      $param{encode_headers} = 1 if not exists $param{encode_headers};
344      if ($param{encode_headers}) {
345           $param{message} = encode_headers($param{message});
346      }
347
348      # First, try to send the message as is.
349      eval {
350           _send_message($param{message},
351                         @sendmail_arguments,
352                         $param{parse_for_recipients}?q(-t):(),
353                         @recipients);
354      };
355      return 1 unless $@;
356      # If there's only one recipient, there's nothing more we can do,
357      # so bail out.
358      warn $@ and return 0 if $@ and @recipients == 0;
359      # If that fails, try to send the message to each of the
360      # recipients separately. We also send the -t option separately in
361      # case one of the @recipients is ok, but the addresses in the
362      # mail message itself are malformed.
363      my @errors;
364      for my $recipient ($param{parse_for_recipients}?q(-t):(),@recipients) {
365           eval {
366                _send_message($param{message},@sendmail_arguments,$recipient);
367           };
368           push @errors, "Sending to $recipient failed with $@" if $@;
369      }
370      # If it still fails, complain bitterly but don't die.
371      warn join(qq(\n),@errors) and return 0 if @errors;
372      return 1;
373 }
374
375 =head2 encode_headers
376
377      $message = encode_heeaders($message);
378
379 RFC 1522 encodes the headers of a message
380
381 =cut
382
383 sub encode_headers{
384      my ($message) = @_;
385
386      my ($header,$body) = split /\n\n/, $message, 2;
387      $header = encode_rfc1522($header);
388      return $header . qq(\n\n). $body;
389 }
390
391 =head2 rfc822_date
392
393      rfc822_date
394
395 Return the current date in RFC822 format in the UTC timezone
396
397 =cut
398
399 sub rfc822_date{
400      return scalar strftime "%a, %d %h %Y %T +0000", gmtime;
401 }
402
403 =head1 PRIVATE FUNCTIONS
404
405 =head2 _send_message
406
407      _send_message($message,@sendmail_args);
408
409 Private function that actually calls sendmail with @sendmail_args and
410 sends message $message.
411
412 dies with errors, so calls to this function in send_mail_message
413 should be wrapped in eval.
414
415 =cut
416
417 sub _send_message{
418      my ($message,@sendmail_args) = @_;
419
420      my ($wfh,$rfh);
421      my $pid = open3($wfh,$rfh,$rfh,$SENDMAIL,@sendmail_args)
422           or die "Unable to fork off $SENDMAIL: $!";
423      local $SIG{PIPE} = 'IGNORE';
424      eval {
425           print {$wfh} $message or die "Unable to write to $SENDMAIL: $!";
426           close $wfh or die "$SENDMAIL exited with $?";
427      };
428      if ($@) {
429           local $\;
430           # Reap the zombie
431           waitpid($pid,WNOHANG);
432           # This shouldn't block because the pipe closing is the only
433           # way this should be triggered.
434           my $message = <$rfh>;
435           die "$@$message";
436      }
437      # Wait for sendmail to exit for at most 30 seconds.
438      my $loop = 0;
439      while (waitpid($pid, WNOHANG) == 0 or $loop++ >= 600){
440           # sleep for a 20th of a second
441           usleep(50_000);
442      }
443      if ($loop >= 600) {
444           warn "$SENDMAIL didn't exit within 30 seconds";
445      }
446 }
447
448
449 1;
450
451
452 __END__
453
454
455
456
457
458