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