]> git.donarmstrong.com Git - debbugs.git/blob - Debbugs/Mail.pm
* Add default_headers function to generate the default set of 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 =over
105
106 =item queue_file -- the queue file which will generate this set of
107 headers (refered to as $nn in lots of the code)
108
109 =item data -- the data of the bug which this message involves; can be
110 undefined if there is no bug involved.
111
112 =item msgid -- the Message-ID: of the message which will generate this
113 set of headers
114
115 =item msgtype -- the type of message that this is.
116
117 =item pr_msg -- the pr message field
118
119 =item headers -- a set of headers which will override the default
120 headers; these headers will be passed through (and may be reordered.)
121 If a particular header is undef, it overrides the default, but isn't
122 passed through.
123
124 =back
125
126 =cut
127
128 sub default_headers {
129     my %param = validate_with(params => \@_,
130                               spec   => {queue_file => {type => SCALAR,
131                                                         optional => 1,
132                                                        },
133                                          data       => {type => HASHREF,
134                                                         optional => 1,
135                                                        },
136                                          msgid      => {type => SCALAR,
137                                                         optional => 1,
138                                                        },
139                                          msgtype    => {type => SCALAR,
140                                                         default => 'misc',
141                                                         optional => 1,
142                                                        },
143                                          pr_msg     => {type => SCALAR,
144                                                         default => 'misc',
145                                                        },
146                                          headers    => {type => ARRAYREF,
147                                                         default => [],
148                                                        },
149                                         },
150                              );
151     my @header_order = (qw(X-Loop From To subject),
152                         qw(Message-ID In-Reply-To References));
153     my %header_order;
154     @header_order{map {lc $_} @header_order} = 0..$#header_order;
155     my %set_headers;
156     my @ordered_headers;
157     my @temp = @{$param{headers}};
158     my @other_headers;
159     while (my ($header,$value) = splice @temp,0,2) {
160         if (exists $header_order{lc($header)}) {
161             push @{$ordered_headers[$header_order{lc($header)}]},
162                 ($header,$value);
163         }
164         else {
165             push @other_headers,($header,$value);
166         }
167         $set_headers{lc($header)} = 1;
168     }
169
170     # calculate our headers
171     my $bug_num = exists $param{data} ? $param{data}{bug_num} : 'x';
172     my $nn = $param{queue_file};
173     # handle the user giving the actual queue filename instead of nn
174     $nn =~ s/^[a-zA-Z]([a-zA-Z])/$1/;
175     $nn = lc($nn);
176     my @msgids;
177     if (exists $param{msgid} and defined $param{msgid}) {
178         push @msgids, $param{msgid}
179     }
180     elsif (exists $param{data} and defined $param{data}{msgid}) {
181         push @msgids, $param{data}{msgid}
182     }
183     my %default_header;
184     $default_header{'X-Loop'} = $config{maintainer_email};
185     $default_header{From}     = "$config{maintainer_email} ($config{project} $config{ubug} Tracking System)";
186     $default_header{To}       = "Unknown recipients";
187     $default_header{Subject}  = "Unknown subject";
188     $default_header{'Message-ID'} = "<handler.${bug_num}.${nn}.$param{msgtype}\@$config{email_domain}>";
189     if (@msgids) {
190         $default_header{'In-Reply-To'} = $msgids[0];
191         $default_header{'References'} = join(' ',@msgids);
192     }
193     $default_header{Precedence} = 'bulk';
194     $default_header{"X-$config{project}-PR-Message"} = $param{pr_msg} . (exists $param{data} ? ' '.$param{data}{bug_num}:'');
195     $default_header{Date} = rfc822_date();
196     if (exists $param{data}) {
197         if (defined $param{data}{keywords}) {
198             $default_header{"X-$config{project}-PR-Keywords"} = $param{data}{keywords};
199         }
200         if (defined $param{data}{package}) {
201             $default_header{"X-$config{project}-PR-Package"} = $param{data}{package};
202             if ($param{data}{package} =~ /^src:(.+)$/) {
203                 $default_header{"X-$config{project}-PR-Source"} = $1;
204             }
205             else {
206                 my $pkg_src = getpkgsrc();
207                 $default_header{"X-$config{project}-PR-Source"} = $pkg_src->{$param{data}{package}};
208             }
209         }
210     }
211     for my $header (sort keys %default_header) {
212         next if $set_headers{lc($header)};
213         if (exists $header_order{lc($header)}) {
214             push @{$ordered_headers[$header_order{lc($header)}]},
215                 ($header,$default_header{$header});
216         }
217         else {
218             push @other_headers,($header,$header_order{lc($header)});
219         }
220     }
221     my @headers;
222     for my $hdr1 (@ordered_headers) {
223         next if not defined $hdr1;
224         my @temp = @{$hdr1};
225         while (my ($header,$value) = splice @temp,0,2) {
226             next if not defined $value;
227             push @headers,($header,$value);
228         }
229     }
230     push @headers,@other_headers;
231     if (wantarray) {
232         return @headers;
233     }
234     else {
235         my $headers = '';
236         while (my ($header,$value) = splice @headers,0,2) {
237             $headers .= "${header}: $value\n";
238         }
239         return $headers;
240     }
241 }
242
243
244
245 =head2 send_mail_message
246
247      send_mail_message(message    => $message,
248                        recipients => [@recipients],
249                        envelope_from => 'don@debian.org',
250                       );
251
252
253 =over
254
255 =item message -- message to send out
256
257 =item recipients -- recipients to send the message to. If undefed or
258 an empty arrayref, will use '-t' to parse the message for recipients.
259
260 =item envelope_from -- envelope_from for outgoing messages
261
262 =item encode_headers -- encode headers using RFC1522 (default)
263
264 =item parse_for_recipients -- use -t to parse the message for
265 recipients in addition to those specified. [Can be used to set Bcc
266 recipients, for example.]
267
268 =back
269
270 Returns true on success, false on failures. All errors are indicated
271 using warn.
272
273 =cut
274
275 sub send_mail_message{
276      my %param = validate_with(params => \@_,
277                                spec  => {sendmail_arguments => {type => ARRAYREF,
278                                                                 default => [qw(-odq -oem -oi)],
279                                                                },
280                                          parse_for_recipients => {type => BOOLEAN,
281                                                                   default => 0,
282                                                                  },
283                                          encode_headers       => {type => BOOLEAN,
284                                                                   default => 1,
285                                                                  },
286                                          message              => {type => SCALAR,
287                                                                  },
288                                          envelope_from        => {type => SCALAR,
289                                                                   optional => 1,
290                                                                  },
291                                          recipients           => {type => ARRAYREF|UNDEF,
292                                                                   optional => 1,
293                                                                  },
294                                         },
295                               );
296      my @sendmail_arguments = qw(-odq -oem -oi);
297      push @sendmail_arguments, '-f', $param{envelope_from} if exists $param{envelope_from};
298
299      my @recipients;
300      @recipients = @{$param{recipients}} if defined $param{recipients} and
301           ref($param{recipients}) eq 'ARRAY';
302      my %recipients;
303      @recipients{@recipients} = (1) x @recipients;
304      @recipients = keys %recipients;
305      # If there are no recipients, use -t to parse the message
306      if (@recipients == 0) {
307           $param{parse_for_recipients} = 1 unless exists $param{parse_for_recipients};
308      }
309      # Encode headers if necessary
310      $param{encode_headers} = 1 if not exists $param{encode_headers};
311      if ($param{encode_headers}) {
312           $param{message} = encode_headers($param{message});
313      }
314
315      # First, try to send the message as is.
316      eval {
317           _send_message($param{message},
318                         @sendmail_arguments,
319                         $param{parse_for_recipients}?q(-t):(),
320                         @recipients);
321      };
322      return 1 unless $@;
323      # If there's only one recipient, there's nothing more we can do,
324      # so bail out.
325      warn $@ and return 0 if $@ and @recipients == 0;
326      # If that fails, try to send the message to each of the
327      # recipients separately. We also send the -t option separately in
328      # case one of the @recipients is ok, but the addresses in the
329      # mail message itself are malformed.
330      my @errors;
331      for my $recipient ($param{parse_for_recipients}?q(-t):(),@recipients) {
332           eval {
333                _send_message($param{message},@sendmail_arguments,$recipient);
334           };
335           push @errors, "Sending to $recipient failed with $@" if $@;
336      }
337      # If it still fails, complain bitterly but don't die.
338      warn join(qq(\n),@errors) and return 0 if @errors;
339      return 1;
340 }
341
342 =head2 encode_headers
343
344      $message = encode_heeaders($message);
345
346 RFC 1522 encodes the headers of a message
347
348 =cut
349
350 sub encode_headers{
351      my ($message) = @_;
352
353      my ($header,$body) = split /\n\n/, $message, 2;
354      $header = encode_rfc1522($header);
355      return $header . qq(\n\n). $body;
356 }
357
358 =head2 rfc822_date
359
360      rfc822_date
361
362 Return the current date in RFC822 format in the UTC timezone
363
364 =cut
365
366 sub rfc822_date{
367      return scalar strftime "%a, %d %h %Y %T +0000", gmtime;
368 }
369
370 =head1 PRIVATE FUNCTIONS
371
372 =head2 _send_message
373
374      _send_message($message,@sendmail_args);
375
376 Private function that actually calls sendmail with @sendmail_args and
377 sends message $message.
378
379 dies with errors, so calls to this function in send_mail_message
380 should be wrapped in eval.
381
382 =cut
383
384 sub _send_message{
385      my ($message,@sendmail_args) = @_;
386
387      my ($wfh,$rfh);
388      my $pid = open3($wfh,$rfh,$rfh,$SENDMAIL,@sendmail_args)
389           or die "Unable to fork off $SENDMAIL: $!";
390      local $SIG{PIPE} = 'IGNORE';
391      eval {
392           print {$wfh} $message or die "Unable to write to $SENDMAIL: $!";
393           close $wfh or die "$SENDMAIL exited with $?";
394      };
395      if ($@) {
396           local $\;
397           # Reap the zombie
398           waitpid($pid,WNOHANG);
399           # This shouldn't block because the pipe closing is the only
400           # way this should be triggered.
401           my $message = <$rfh>;
402           die "$@$message";
403      }
404      # Wait for sendmail to exit for at most 30 seconds.
405      my $loop = 0;
406      while (waitpid($pid, WNOHANG) == 0 or $loop++ >= 600){
407           # sleep for a 20th of a second
408           usleep(50_000);
409      }
410      if ($loop >= 600) {
411           warn "$SENDMAIL didn't exit within 30 seconds";
412      }
413 }
414
415
416 1;
417
418
419 __END__
420
421
422
423
424
425