]> git.donarmstrong.com Git - bin.git/blob - delay_mail
fix pipe wait logic
[bin.git] / delay_mail
1 #! /usr/bin/perl
2 # delay_mail delays mail and requeus it, and is released
3 # under the terms of the GPL version 2, or any later version, at your
4 # option. See the file README and COPYING for more information.
5 # Copyright 2006 by Don Armstrong <don@donarmstrong.com>.
6 # $Id: perl_script 495 2006-08-10 08:02:01Z don $
7
8
9 use warnings;
10 use strict;
11
12 use Getopt::Long;
13 use Pod::Usage;
14
15 =head1 NAME
16
17 delay_mail - Delay mail to a specific time and send it back
18
19 =head1 SYNOPSIS
20
21  delay_mail [options] < mail_message
22
23  Options:
24   --enqueue enqueues a message for sending out later
25   --delay length of delay (suitable for passing to at)
26   --email pull delay out from email address
27   --list list emails in queue
28   --queue directory to use as a queue
29   --process sends out a specific message that was enqueued
30   --debug, -d debugging level (Default 0)
31   --help, -h display this help
32   --man, -m display manual
33
34 =head1 OPTIONS
35
36 =over
37
38 =item B<--enqueue>
39
40 Enqueue a message which should be sent out later
41
42 =item B<--delay>
43
44 Length of delay (man at for details of specification)
45
46 =item B<--email>
47
48 The delay option is actually an email address; apply the following
49 regex to parse it:
50
51     $delay =~ m/[+-]d(?:ela?y?)?[-+]([^\@]+)/;
52     $delay = $1; $delay =~ s/_/ /;
53
54 Thus, foo-delay-now+5_min@bar.baz becomes now+5 min
55
56 =item B<--list>
57
58 List entries which are in the queue
59
60 =item B<--dequeue>
61
62 Delete an entry from the queue
63
64 =item B<--mailto>
65
66 Who to mail the delayed mail to
67
68 =item B<--queue>
69
70 The queue directory to use; defaults to ~/.delay_mail_queue
71
72 =item B<--process>
73
74 Process a specific entry in the queue (this is called by at at the
75 appropriate time; you shouldn't need call it manually.)
76
77 =item B<--debug, -d>
78
79 Debug verbosity. (Default 0)
80
81 =item B<--help, -h>
82
83 Display brief useage information.
84
85 =item B<--man, -m>
86
87 Display this manual.
88
89 =back
90
91 =head1 EXAMPLES
92
93
94 =cut
95
96
97 use vars qw($DEBUG);
98
99 my %options = (debug           => 0,
100                help            => 0,
101                man             => 0,
102                email           => 0,
103               );
104
105 GetOptions(\%options,'debug|d+','help|h|?','man|m',
106            'list|l','dequeue=s','process|p=s','enqueue|e',
107            'delay|D=s','email|E',
108            'mailto|mail-to|M=s',
109           );
110
111 pod2usage() if $options{help};
112 pod2usage({verbose=>2}) if $options{man};
113
114 $DEBUG = $options{debug};
115
116 use List::Util qw(sum);
117 use MIME::WordDecoder;
118 use IO::File;
119 use IO::Dir;
120
121 my $ERROR = '';
122 if (1 < grep {exists $options{$_}} qw(enqueue list process dequeue)) {
123      $ERROR .= "Exactly one of --enque, --list, --process, or --dequeue must be specified\n";
124 }
125 if (not $options{enqueue} and ($options{email} or exists $options{delay})) {
126      $ERROR .= "Setting email or delay is nonsensical unless enqueuing\n";
127 }
128
129 pod2usage($ERROR) if length $ERROR;
130
131 # create queue directory if it doesn't already exist
132 if (not exists $options{queue}) {
133      $options{queue} = "$ENV{HOME}/.delay_mail_queue";
134 }
135 if (not -d $options{queue}) {
136      mkdir($options{queue}) or
137           die "Unable to create queue directory $options{queue}: $!";
138 }
139
140 if (not exists $options{mailto}) {
141      if (exists $ENV{EMAIL}) {
142           $options{mailto} = $ENV{EMAIL};
143      }
144      elsif (exists $ENV{USER}) {
145           $options{mailto} = $ENV{USER};
146      }
147      else {
148           $options{mailto} = qx(id -nu);
149      }
150 }
151 $options{mailto} =~ s/\n//g;
152
153 if (exists $options{enqueue}) {
154      # parse delay
155      my $delay = $options{delay};
156      $delay =~ s/\n//g;
157      if ($options{email}) {
158           $delay =~ m/[+-]d(?:ela?y?)?[-+]([^\@]+)/;
159           $delay = $1; $delay =~ s/_/ /;
160      }
161      # slurp email
162      local $/;
163      my $email = <STDIN>;
164      # rip subject out of email
165      # we cheat for now; this isn't correct at all.
166      my ($subject) = $email =~ /^Subject:\s*(.+)/mi;
167      $subject = decode_rfc1522($subject);
168      $subject =~ s/\n//g;
169      my $time = time;
170      # create a queue entry
171      my $queue_fn = $time . $$;
172      my $q_fh = IO::File->new("$options{queue}/$queue_fn",'w') or
173           die "Unable to open $options{queue}/$queue_fn for writing";
174      print {$q_fh} "delay: $delay\n";
175      print {$q_fh} "time: $time\n";
176      print {$q_fh} "mailto: $options{mailto}\n";
177      print {$q_fh} "entry: $queue_fn\n";
178      print {$q_fh} "subject: $subject\n";
179      print {$q_fh} "#####\n";
180      print {$q_fh} $email;
181      my $at_fh;
182      my $pid = open($at_fh,'|-','at',$delay) or exit 1;
183      print {$at_fh} "$0 '--queue' '$options{queue}' '--process' '$queue_fn';\n";
184      close $at_fh or exit $?
185      exit 0;
186 }
187 elsif ($options{list}) {
188      my $dir = IO::Dir->new($options{queue}) or
189           die "Unable to list contents of $options{queue}: $!";
190      my $entry;
191      my @queue;
192      while (defined($entry = $dir->read)) {
193           #valid queue entries are entirely numeric
194           print STDERR "Dealing with $entry\n" if $DEBUG;
195           last if not defined $entry;
196           next if $entry !~ /^\d+$/;
197           # they're also just readable files
198           next if not -f "$options{queue}/$entry" or not -r "$options{queue}/$entry";
199           print STDERR "Still dealing with $entry\n" if $DEBUG;
200           push @queue,parse_queue_entry($entry);
201      }
202      for my $q_e (@queue) {
203           $q_e->{time} ||='';
204           print "$q_e->{entry}: send $q_e->{subject} to $q_e->{mailto} at $q_e->{delay} ($q_e->{time})\n";
205      }
206 }
207 elsif ($options{dequeue}) {
208      if (-e "$options{queue}/$options{dequeue}") {
209           unlink("$options{queue}/$options{dequeue}") or
210                die "Unable to unlink $options{queue}/$options{dequeue}";
211      }
212      else {
213           print STDERR "$options{queue}/$options{dequeue} doesn't exist\n"
214      }
215 }
216 elsif ($options{process}) {
217      my $q_e;
218      if (-e "$options{queue}/$options{process}") {
219           my $q_e = parse_queue_entry($options{process});
220           if (not defined $q_e) {
221                die "Unable to parse $options{process}";
222           }
223           # munge the message id
224           my ($message_id) = $q_e->{email} =~ m/^Message-Id:\s*(.+)/;
225           if (not $message_id =~ s/\@/delay$q_e->{entry}@/){
226                $message_id =~ s/(\w)/delay$q_e->{entry}$1/;
227           }
228           $q_e->{email} =~ s/^(Message-Id:\s*)(.+)/$1$message_id/;
229           # send the message
230           my $sendmail_fh;
231           open($sendmail_fh,'|-','/usr/sbin/sendmail',$q_e->{mailto}) or
232                die "Unable to open sendmail to send message";
233           print {$sendmail_fh} $q_e->{email};
234           close($sendmail_fh);
235           waitpid(-1,0);
236           if ($?) {
237                print STDERR "Sendmail failed with $?\n";
238                exit $?;
239           }
240           unlink("$options{queue}/$options{process}");
241      }
242      else {
243           print STDERR "$options{queue}/$options{process} doesn't exist\n"
244      }
245 }
246
247
248 sub parse_queue_entry{
249      my ($entry) = @_;
250
251      my $entry_fh = IO::File->new("$options{queue}/$entry",'r') or
252           return undef;
253      my $queue_entry = {};
254      while (<$entry_fh>) {
255           last if /^#####/;
256           chomp;
257           my $line = $_;
258           my ($key,$value) = split /: /, $line,2;
259           $queue_entry->{$key} = $value;
260      }
261      local $/;
262      $queue_entry->{email} = <$entry_fh>;
263      return $queue_entry;
264 }
265
266
267 # These functions below I've jacked from Debbugs::MIME which I also
268 # wrote; probably should put them somewhere else eventually.
269
270 sub convert_to_utf8 {
271      my ($data, $charset) = @_;
272      # raw data just gets returned (that's the charset WordDecorder
273      # uses when it doesn't know what to do)
274      return $data if $charset eq 'raw' or is_utf8($data,1);
275      my $result;
276      eval {
277           # this encode/decode madness is to make sure that the data
278           # really is valid utf8 and that the is_utf8 flag is off.
279           $result = encode("utf8",decode($charset,$data))
280      };
281      if ($@) {
282           warn "Unable to decode charset; '$charset' and '$data': $@";
283           return $data;
284      }
285      return $result;
286 }
287
288
289 BEGIN {
290     # Set up the default RFC1522 decoder, which turns all charsets that
291     # are supported into the appropriate UTF-8 charset.
292     MIME::WordDecoder->default(new MIME::WordDecoder(
293         ['*' => \&convert_to_utf8,
294         ]));
295 }
296
297 sub decode_rfc1522
298 {
299     my ($string) = @_;
300
301     # this is craptacular, but leading space is hacked off by unmime.
302     # Save it.
303     my $leading_space = '';
304     $leading_space = $1 if $string =~ s/^(\s+)//;
305     # unmime calls the default MIME::WordDecoder handler set up at
306     # initialization time.
307     return $leading_space . MIME::WordDecoder::unmime($string);
308 }
309
310
311
312 __END__
313
314