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