366f830db8c788be3d7e9d4f90cf33500e125e57
[PerlMail.git] / perlmail-sendmail
1 #! /usr/bin/perl
2 #
3 # $Id$
4
5 use vars qw($VERSION);
6 $VERSION=do { my @r=(q$Revision$=~/\d+/g); sprintf "%d.".("%03d"x$#r),@r; };
7 use strict;
8 use warnings;
9
10 use PerlMail::Config;
11
12 require Getopt::Long;
13 use POSIX qw(WIFEXITED WEXITSTATUS WIFSIGNALED WTERMSIG WIFSTOPPED WSTOPSIG);
14 require MIME::Head;     # inherits Mail::Header
15 require Mail::Address;
16 require File::Basename;
17 require Mail::Alias;
18
19
20 # FIXME: modularized unification with 'perlmail-accept'
21 # BEGIN perlmail-accept
22 our %muttrc_pending=();
23 sub muttrc
24 {
25 my($muttrc)=@_;
26
27         $muttrc||="$HOME/.muttrc";
28         $muttrc=~s/^\~/$HOME/;
29         do { warn "Looping muttrc, ignoring: $muttrc"; return (); } if $muttrc_pending{$muttrc};
30         local $muttrc_pending{$muttrc}=1;
31         local *MUTTRC;
32         open MUTTRC,$muttrc or do { warn "open \"$muttrc\": $!"; return (); };
33         local $/="\n";
34         local $_;
35         my @r=();
36         # far emulation mutt/init.c/mutt_parse_rc_line()
37         while (<MUTTRC>) {
38                 s/^[\s;]*//s;
39                 s/[#;].*$//s;
40                 s/\s*$//s;
41                 next if !/^(\S+)\s*/s;
42                 if ($1 eq "source") {
43                         $_=$';
44                         do { warn "Wrong 'source' parameters at $muttrc:$.: $_"; next; } if !/^\S+$/;
45                         push @r,muttrc($_);
46                         next;
47                         }
48                 push @r,$_;
49                 }
50         close MUTTRC or warn "close \"$muttrc\": $!";
51         return wantarray() ? @r : join("",map("$_\n",@r));
52 }
53
54 my %mutteval_charmap=(          # WARNING: Don't use "" or "0" here, see below for "|| warn"!
55                 '\\'=>"\\",
56                 'r'=>"\r",
57                 'n'=>"\n",
58                 't'=>"\t",
59                 'f'=>"\f",
60                 'e'=>"\e",
61                 );
62 # mutt/init.c/mutt_extract_token()
63 sub mutteval
64 {
65         local $_=$_[0];
66         return $_ if !s/^"//;
67         do { warn "Missing trailing quote in: $_"; return $_; } if !s/"$//;
68         s/\\(.)/$mutteval_charmap{$1} || warn "Undefined '\\$1' sequence in: $_";/ges;
69         return $_;
70 }
71
72 sub muttrc_get
73 {
74 my(@headers)=@_;
75
76         my @r=map({ (ref $_ ? $_ : qr/^\s*set\s+\Q$_\E\s*=\s*(.*?)\s*$/si); } @headers);
77         my %r=map(($_=>undef()),@r);
78         for (muttrc()) {
79                 for my $ritem (@r) {
80                         /$ritem/si or next;
81                         $r{$ritem}=mutteval $1;
82                         }
83                 }
84         for my $var (grep { !defined($r{$_}) } @r) {
85                 warn "Variable '$var' not found in muttrc";
86                 return undef();
87                 }
88         return wantarray() ? %r : $r{$r[0]};
89 }
90 # END perlmail-accept
91
92
93 sub sendmail_show { return "\"$sendmail_orig\" ".join(",",map("\"$_\"",@ARGV)); }
94
95 sub sendmail_orig_exec
96 {
97         exec {$sendmail_orig} $0,@ARGV or die "exec(".sendmail_show()."): $!";
98         die "NOTREACHED";
99 }
100
101 Getopt::Long::Configure(
102                 "no_ignorecase",
103                 "no_getopt_compat",
104                 "bundling",
105                 # FIXME: workaround: 'unknown options' are considered the same as 'arguments'
106                 # None of ($REQUIRE_ORDER, $PERMUTE, $RETURN_IN_ORDER) can help us.
107                 # No preprocessing possible as it is hard to find option arguments.
108                 "permute",
109                 "pass_through",
110                 );
111
112 my $opt_b;
113 my $opt_Q;
114 my $opt_q;
115 my $opt_t;
116 our $opt_f;
117 our $opt_F;     # from PerlMail::Config;
118 my $opt_perlmail_dry_run;
119 my @ARGV_save=@ARGV;    # for non-bm mode
120 die if !Getopt::Long::GetOptions(
121                 "b=s"              ,\$opt_b,
122                 "Q:s"              ,\$opt_Q,
123                 "q:s"              ,\$opt_q,
124                 "t"                ,\$opt_t,
125                 "f=s"              ,\$opt_f,
126                 "F=s"              ,\$opt_F,
127                 "perlmail-dry-run+",\$opt_perlmail_dry_run,
128                 );
129 if (0
130                 # RedHat sendmail-8.12.5-7/sendmail/main.c/\QDo a quick prescan of the argument list.\E
131                 || grep({ File::Basename::basename($0) eq $_; } "newaliases","mailq","smtpd","hoststat","purgestat")
132                 # -bm: Deliver mail in the usual way (default).
133                 || (defined($opt_b) && $opt_b ne "m")
134                 || defined $opt_q       # MD_QUEUERUN
135                 || defined $opt_Q       # MD_QUEUERUN
136                 ) {
137         @ARGV=@ARGV_save;
138         sendmail_orig_exec();
139         die "NOTREACHED";
140         }
141
142 # RedHat sendmail-8.9.3-20/src/main.c/main()/\Qif (FullName != NULL)\E
143 #   for $opt_F is implemented by Mail::Address in our &FromAddress
144
145 my $head=MIME::Head->new(\*STDIN);
146 # options leave in @ARGV, addresses to @addr:
147 my @args=@ARGV; # temporary
148 @ARGV=();       # options
149 my @addr=();    # addresses
150 push @{(/^-./ ? \@ARGV : \@addr)},$_ for (@args);
151 if ($opt_t) {
152         for my $addrobj (map({ Mail::Address->parse($_); } map({ ($head->get($_)); } @h_rcpt))) {
153                 if (!$addrobj->address()) {
154                         # bogus, shouldn't happen
155                         warn "->address() not found in \"".$addrobj->format()."\"";
156                         next;
157                 }
158                 push @addr,$addrobj;
159                 }
160         }
161
162 # return: Mail::Address instance or undef()
163 sub parseone
164 {
165 my($line)=@_;
166
167         return undef() if !defined $line;
168         my @r=Mail::Address->parse($line);
169         warn "Got ".scalar(@r)." addresses while wanting just one; when parsing: $line" if 1!=@r;
170         return $r[0];
171 }
172
173 sub matches
174 {
175         return 
176 }
177
178 my $from_headername;
179 {
180         my $muttrc_From=parseone(scalar muttrc_get("from"));    # may get undef()!; parseone() may be redundant
181         $muttrc_From=$muttrc_From->address() if $muttrc_From;
182         $opt_f=undef() if defined($opt_f) && $muttrc_From && lc($opt_f) eq lc($muttrc_From);
183         for (@h_from) {
184                 $from_headername=$_;    # leave last item in $from_headername
185                 next if !(my @from_val=$head->get($from_headername));
186                 @from_val=map({ ($_->address()); } map({ (Mail::Address->parse($_)); } @from_val));
187                 $from_headername=undef() if !(1==@from_val && $muttrc_From && lc($from_val[0]) eq lc($muttrc_From));
188                 last;
189                 }       # fallthru with $from_headername remaining set if last headername did not exist
190         # now $from_headername contains the header name to be replaced w/substituted value
191         }
192
193 # to be utilized later by &FromAddress
194 our $is_pgp;    # from PerlMail::Config;
195 $is_pgp=(1
196                 && do { local $_=$head->mime_attr("Content-Type");          $_ && ~m#^multipart/(?:signed|encrypted)$#; }
197                 && do { local $_=$head->mime_attr("Content-Type.protocol"); $_ && ~m#^application/pgp\b#; }
198                 );
199
200 my $exitcode=0;
201 # !defined($rcpt) if we have no recipients
202 # make the list unique to prevent dupes being normally filtered by sendmail(8)
203 # one '{' is block-wrapper, another '{' is hash-indirection!
204 # hash keys are just strings, never refs!
205 # unify the list as Mail::Address instances
206 my @rcpts=(!@addr ? (undef()) : values(%{{ map({
207                 my $obj=$_;
208                 $obj=parseone $obj if !ref $obj;
209                 (!defined $obj ? () : (lc($obj->address())=>$obj));
210                 } @addr) }}));
211
212 my $stdin_body=(@rcpts<=1 ? undef() : do {      # store input data only if it will be used multiple times
213                 local $/=undef();
214                 <STDIN>;
215                 });
216 for my $rcpt (@rcpts) {
217         local @ARGV=@ARGV;
218         local $opt_f=$opt_f;
219
220         if (defined $rcpt) {    # !defined($rcpt) if we have no recipients
221                 local $_;
222                 $opt_f=FromAddress($rcpt,1)->address() if !defined $opt_f;
223                 $head->replace($from_headername,FromAddress($rcpt,0)->format()) if $from_headername;
224                 }
225
226         1;      # drop '-bm' if present as it is default anyway
227         1;      # drop '-t' if present as we are looping now for it
228         push @ARGV,"-f",$opt_f if defined $opt_f;
229         # we don't handle "Full-Name" header thus pass "-F"
230         # "From/Resent-From" should be handled by our &FromAddress
231         push @ARGV,"-F",$opt_F if defined $opt_F;
232         push @ARGV,$rcpt->address() if defined $rcpt;
233         push @ARGV,@addr_addon;
234
235         local $SIG{"PIPE"}=sub { die "Got SIGPIPE from ".sendmail_show(); };
236         local *SENDMAIL;
237         if ($opt_perlmail_dry_run) {
238                 print sendmail_show()."\n";
239                 *SENDMAIL=\*STDOUT;
240                 }
241         else {
242                 defined (my $pid=open SENDMAIL,"|-") or die "Cannot fork to spawn ".sendmail_show().": $!";
243                 sendmail_orig_exec() if !$pid; # child
244                 }
245         $head->print(\*SENDMAIL);
246         print SENDMAIL "\n";    # MIME::Head->print() eats the empty line but it doesn't print it
247         if (defined($stdin_body)) {
248                 print SENDMAIL $stdin_body;
249                 }
250         else {
251                 local $_;
252                 while (<STDIN>) {
253                         print SENDMAIL $_;
254                         }
255                 }
256
257         next if $opt_perlmail_dry_run;  # don't close our STDOUT as it is aliased to *SENDMAIL
258         close SENDMAIL or warn "close(".sendmail_show()."): $?=".join(",",
259                         (!WIFEXITED($?)   ? () : ("EXITSTATUS(".WEXITSTATUS($?).")")),
260                         (!WIFSIGNALED($?) ? () : ("TERMSIG("   .WTERMSIG($?)   .")")),
261                         (!WIFSTOPPED($?)  ? () : ("STOPSIG("   .WSTOPSIG($?)   .")")),
262                         );
263         my $gotcode=(!WIFEXITED($?) ? 99 : WEXITSTATUS($?));
264         $exitcode=$gotcode if $gotcode>$exitcode;
265         }
266 exit $exitcode;