]> git.donarmstrong.com Git - debbugs.git/blob - Debbugs/Mail.pm
e4c8bf7da825e53ce64b3f0849079237e07745fa
[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 Exporter qw(import);
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 convert_to_utf8);
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                      reply     => [qw(reply_headers)],
65                     );
66      @EXPORT_OK = ();
67      Exporter::export_ok_tags(keys %EXPORT_TAGS);
68      $EXPORT_TAGS{all} = [@EXPORT_OK];
69 }
70
71 # We set this here so it can be overridden for testing purposes
72 our $SENDMAIL = $config{sendmail};
73
74 =head2 get_addresses
75
76      my @addresses = get_addresses('don@debian.org blars@debian.org
77                                     kamion@debian.org ajt@debian.org');
78
79 Given a string containing some e-mail addresses, parses the string
80 using Mail::Address->parse and returns a list of the addresses.
81
82 =cut
83
84 sub get_addresses {
85      return map { $_->address() } map { Mail::Address->parse($_) } @_;
86 }
87
88
89 =head2 default_headers
90
91       my @head = default_headers(queue_file => 'foo',
92                                  data       => $data,
93                                  msgid      => $header{'message-id'},
94                                  msgtype    => 'error',
95                                  headers    => [...],
96                                 );
97       create_mime_message(\@headers,
98                          ...
99                          );
100
101 This function is generally called to generate the headers for
102 create_mime_message (and anything else that needs a set of default
103 headers.)
104
105 In list context, returns an array of headers. In scalar context,
106 returns headers for shoving in a mail message after encoding using
107 encode_headers.
108
109 =head3 options
110
111 =over
112
113 =item queue_file -- the queue file which will generate this set of
114 headers (refered to as $nn in lots of the code)
115
116 =item data -- the data of the bug which this message involves; can be
117 undefined if there is no bug involved.
118
119 =item msgid -- the Message-ID: of the message which will generate this
120 set of headers
121
122 =item msgtype -- the type of message that this is.
123
124 =item pr_msg -- the pr message field
125
126 =item headers -- a set of headers which will override the default
127 headers; these headers will be passed through (and may be reordered.)
128 If a particular header is undef, it overrides the default, but isn't
129 passed through.
130
131 =back
132
133 =head3 default headers
134
135 =over
136
137 =item X-Loop -- set to the maintainer e-mail
138
139 =item From -- set to the maintainer e-mail
140
141 =item To -- set to Unknown recipients
142
143 =item Subject -- set to Unknown subject
144
145 =item Message-ID -- set appropriately (see code)
146
147 =item Precedence -- set to bulk
148
149 =item References -- set to the full set of message ids that are known
150 (from data and the msgid option)
151
152 =item In-Reply-To -- set to msg id or the msgid from data
153
154 =item X-Project-PR-Message -- set to pr_msg with the bug number appended
155
156 =item X-Project-PR-Package -- set to the package of the bug
157
158 =item X-Project-PR-Keywords -- set to the keywords of the bug
159
160 =item X-Project-PR-Source -- set to the source of the bug
161
162 =back
163
164 =cut
165
166 sub default_headers {
167     my %param = validate_with(params => \@_,
168                               spec   => {queue_file => {type => SCALAR|UNDEF,
169                                                         optional => 1,
170                                                        },
171                                          data       => {type => HASHREF,
172                                                         optional => 1,
173                                                        },
174                                          msgid      => {type => SCALAR|UNDEF,
175                                                         optional => 1,
176                                                        },
177                                          msgtype    => {type => SCALAR|UNDEF,
178                                                         default => 'misc',
179                                                        },
180                                          pr_msg     => {type => SCALAR|UNDEF,
181                                                         default => 'misc',
182                                                        },
183                                          headers    => {type => ARRAYREF,
184                                                         default => [],
185                                                        },
186                                         },
187                              );
188     my @header_order = (qw(X-Loop From To subject),
189                         qw(Message-ID In-Reply-To References));
190     # handle various things being undefined
191     if (not exists $param{queue_file} or
192         not defined $param{queue_file}) {
193         $param{queue_file} = join('',gettimeofday())
194     }
195     for (qw(msgtype pr_msg)) {
196         if (not exists $param{$_} or
197             not defined $param{$_}) {
198             $param{$_} = 'misc';
199         }
200     }
201     my %header_order;
202     @header_order{map {lc $_} @header_order} = 0..$#header_order;
203     my %set_headers;
204     my @ordered_headers;
205     my @temp = @{$param{headers}};
206     my @other_headers;
207     while (my ($header,$value) = splice @temp,0,2) {
208         if (exists $header_order{lc($header)}) {
209             push @{$ordered_headers[$header_order{lc($header)}]},
210                 ($header,$value);
211         }
212         else {
213             push @other_headers,($header,$value);
214         }
215         $set_headers{lc($header)} = 1;
216     }
217
218     # calculate our headers
219     my $bug_num = exists $param{data} ? $param{data}{bug_num} : 'x';
220     my $nn = $param{queue_file};
221     # handle the user giving the actual queue filename instead of nn
222     $nn =~ s/^[a-zA-Z]([a-zA-Z])/$1/;
223     $nn = lc($nn);
224     my @msgids;
225     if (exists $param{msgid} and defined $param{msgid}) {
226         push @msgids, $param{msgid}
227     }
228     elsif (exists $param{data} and defined $param{data}{msgid}) {
229         push @msgids, $param{data}{msgid}
230     }
231     my %default_header;
232     $default_header{'X-Loop'} = $config{maintainer_email};
233     $default_header{From}     = "$config{maintainer_email} ($config{project} $config{ubug} Tracking System)";
234     $default_header{To}       = "Unknown recipients";
235     $default_header{Subject}  = "Unknown subject";
236     $default_header{'Message-ID'} = "<handler.${bug_num}.${nn}.$param{msgtype}\@$config{email_domain}>";
237     if (@msgids) {
238         $default_header{'In-Reply-To'} = $msgids[0];
239         $default_header{'References'} = join(' ',@msgids);
240     }
241     $default_header{Precedence} = 'bulk';
242     $default_header{"X-$config{project}-PR-Message"} = $param{pr_msg} . (exists $param{data} ? ' '.$param{data}{bug_num}:'');
243     $default_header{Date} = rfc822_date();
244     if (exists $param{data}) {
245         if (defined $param{data}{keywords}) {
246             $default_header{"X-$config{project}-PR-Keywords"} = $param{data}{keywords};
247         }
248         if (defined $param{data}{package}) {
249             $default_header{"X-$config{project}-PR-Package"} = $param{data}{package};
250             if ($param{data}{package} =~ /^src:(.+)$/) {
251                 $default_header{"X-$config{project}-PR-Source"} = $1;
252             }
253             else {
254                 my $pkg_src = Debbugs::Packages::getpkgsrc();
255                 $default_header{"X-$config{project}-PR-Source"} = $pkg_src->{$param{data}{package}};
256             }
257         }
258     }
259     for my $header (sort keys %default_header) {
260         next if $set_headers{lc($header)};
261         if (exists $header_order{lc($header)}) {
262             push @{$ordered_headers[$header_order{lc($header)}]},
263                 ($header,$default_header{$header});
264         }
265         else {
266             push @other_headers,($header,$default_header{$header});
267         }
268     }
269     my @headers;
270     for my $hdr1 (@ordered_headers) {
271         next if not defined $hdr1;
272         my @temp = @{$hdr1};
273         while (my ($header,$value) = splice @temp,0,2) {
274             next if not defined $value;
275             push @headers,($header,$value);
276         }
277     }
278     push @headers,@other_headers;
279     if (wantarray) {
280         return @headers;
281     }
282     else {
283         my $headers = '';
284         while (my ($header,$value) = splice @headers,0,2) {
285             $headers .= "${header}: $value\n";
286         }
287         return $headers;
288     }
289 }
290
291
292
293 =head2 send_mail_message
294
295      send_mail_message(message    => $message,
296                        recipients => [@recipients],
297                        envelope_from => 'don@debian.org',
298                       );
299
300
301 =over
302
303 =item message -- message to send out
304
305 =item recipients -- recipients to send the message to. If undefed or
306 an empty arrayref, will use '-t' to parse the message for recipients.
307
308 =item envelope_from -- envelope_from for outgoing messages
309
310 =item encode_headers -- encode headers using RFC1522 (default)
311
312 =item parse_for_recipients -- use -t to parse the message for
313 recipients in addition to those specified. [Can be used to set Bcc
314 recipients, for example.]
315
316 =back
317
318 Returns true on success, false on failures. All errors are indicated
319 using warn.
320
321 =cut
322
323 sub send_mail_message{
324      my %param = validate_with(params => \@_,
325                                spec  => {sendmail_arguments => {type => ARRAYREF,
326                                                                 default => $config{sendmail_arguments},
327                                                                },
328                                          parse_for_recipients => {type => BOOLEAN,
329                                                                   default => 0,
330                                                                  },
331                                          encode_headers       => {type => BOOLEAN,
332                                                                   default => 1,
333                                                                  },
334                                          message              => {type => SCALAR,
335                                                                  },
336                                          envelope_from        => {type => SCALAR,
337                                                                   default => $config{envelope_from},
338                                                                  },
339                                          recipients           => {type => ARRAYREF|UNDEF,
340                                                                   optional => 1,
341                                                                  },
342                                         },
343                               );
344      my @sendmail_arguments = @{$param{sendmail_arguments}};
345      push @sendmail_arguments, '-f', $param{envelope_from} if
346          exists $param{envelope_from} and
347          defined $param{envelope_from} and
348          length $param{envelope_from};
349
350      my @recipients;
351      @recipients = @{$param{recipients}} if defined $param{recipients} and
352           ref($param{recipients}) eq 'ARRAY';
353      my %recipients;
354      @recipients{@recipients} = (1) x @recipients;
355      @recipients = keys %recipients;
356      # If there are no recipients, use -t to parse the message
357      if (@recipients == 0) {
358           $param{parse_for_recipients} = 1 unless exists $param{parse_for_recipients};
359      }
360      # Encode headers if necessary
361      $param{encode_headers} = 1 if not exists $param{encode_headers};
362      if ($param{encode_headers}) {
363           $param{message} = encode_headers($param{message});
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). encode_utf8_safely($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 =head2 reply_headers
422
423      reply_headers(MIME::Parser->new()->parse_data(\$data));
424
425 Generates suggested headers and a body for replies. Primarily useful
426 for use in RFC2368 mailto: entries.
427
428 =cut
429
430 sub reply_headers{
431     my ($entity) = @_;
432
433     my $head = $entity->head;
434     # build reply link
435     my %r_l;
436     $r_l{subject} = $head->get('Subject');
437     $r_l{subject} //= 'Your mail';
438     $r_l{subject} = 'Re: '. $r_l{subject} unless $r_l{subject} =~ /(?:^|\s)Re:\s+/;
439     $r_l{subject} =~ s/(?:^\s*|\s*$)//g;
440     $r_l{'In-Reply-To'} = $head->get('Message-Id');
441     $r_l{'In-Reply-To'} =~ s/(?:^\s*|\s*$)//g if defined $r_l{'In-Reply-To'};
442     delete $r_l{'In-Reply-To'} unless defined $r_l{'In-Reply-To'};
443     $r_l{References} = ($head->get('References')//''). ' '.($head->get('Message-Id')//'');
444     $r_l{References} =~ s/(?:^\s*|\s*$)//g;
445     my $date = $head->get('Date') // 'some date';
446     $date =~ s/(?:^\s*|\s*$)//g;
447     my $who = $head->get('From') // $head->get('Reply-To') // 'someone';
448     $who =~ s/(?:^\s*|\s*$)//g;
449
450     my $body = "On $date $who wrote:\n";
451     my $i = 60;
452     my $b_h;
453     # Default to UTF-8.
454     my $charset="utf-8";
455     ## find the first part which has a defined body handle and appears
456     ## to be text
457     if (defined $entity->bodyhandle) {
458         my $this_charset =
459             $entity->head->mime_attr("content-type.charset");
460         $charset = $this_charset if
461             defined $this_charset and
462             length $this_charset;
463         $b_h = $entity->bodyhandle;
464     } elsif ($entity->parts) {
465         my @parts = $entity->parts;
466         while (defined(my $part = shift @parts)) {
467             if ($part->parts) {
468                 push @parts,$part->parts;
469             }
470             if (defined $part->bodyhandle and
471                 $part->effective_type =~ /text/) {
472                 my $this_charset =
473                     $part->head->mime_attr("content-type.charset");
474                 $charset =  $this_charset if
475                     defined $this_charset and
476                     length $this_charset;
477                 $b_h = $part->bodyhandle;
478                 last;
479             }
480         }
481     }
482     if (defined $b_h) {
483         eval {
484             my $IO = $b_h->open("r");
485             while (defined($_ = $IO->getline)) {
486                 $i--;
487                 last if $i < 0;
488                 $body .= '> '. convert_to_utf8($_,$charset);
489             }
490             $IO->close();
491         };
492     }
493     $r_l{body} = $body;
494     return \%r_l;
495 }
496
497 =head1 PRIVATE FUNCTIONS
498
499 =head2 _send_message
500
501      _send_message($message,@sendmail_args);
502
503 Private function that actually calls sendmail with @sendmail_args and
504 sends message $message.
505
506 dies with errors, so calls to this function in send_mail_message
507 should be wrapped in eval.
508
509 =cut
510
511 sub _send_message{
512      my ($message,@sendmail_args) = @_;
513
514      my ($wfh,$rfh);
515      my $pid = open3($wfh,$rfh,$rfh,$SENDMAIL,@sendmail_args)
516           or die "Unable to fork off $SENDMAIL: $!";
517      local $SIG{PIPE} = 'IGNORE';
518      eval {
519           print {$wfh} $message or die "Unable to write to $SENDMAIL: $!";
520           close $wfh or die "$SENDMAIL exited with $?";
521      };
522      if ($@) {
523           local $\;
524           # Reap the zombie
525           waitpid($pid,WNOHANG);
526           # This shouldn't block because the pipe closing is the only
527           # way this should be triggered.
528           my $message = <$rfh>;
529           die "$@$message";
530      }
531      # Wait for sendmail to exit for at most 30 seconds.
532      my $loop = 0;
533      while (waitpid($pid, WNOHANG) == 0 or $loop++ >= 600){
534           # sleep for a 20th of a second
535           usleep(50_000);
536      }
537      if ($loop >= 600) {
538           warn "$SENDMAIL didn't exit within 30 seconds";
539      }
540 }
541
542
543 1;
544
545
546 __END__
547
548
549
550
551
552