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