$head now uses: Mail::Header -> MIME::Head
[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 require Getopt::Long;
11 use POSIX qw(WIFEXITED WEXITSTATUS WIFSIGNALED WTERMSIG WIFSTOPPED WSTOPSIG);
12 require MIME::Head;     # inherits Mail::Header
13 require Mail::Address;
14 require File::Basename;
15 require Mail::Alias;
16
17 my $sendmail_orig=(-x ($_="/usr/sbin/sendmail-orig") ? $_ : "/usr/sbin/sendmail");
18 my $HOME="/home/short";
19 # Mail-Alias-1.12 defaults to "/etc/mail/aliases" which does not exist on RedHat sendmail-8.12.5-7
20 # Mail-Alias-1.12 will clutter $_ !
21 my @addr_addon=(Mail::Alias->new("/etc/aliases")->exists("sentout") ? ("sentout") : ());
22 my $opt_F;
23 my $is_pgp;
24 sub FromAddress
25 {
26 my($rcpt,$iserror)=@_;
27
28         my $phrase=(defined $opt_F ? $opt_F : "Jan Kratochvil");
29         {
30                 last if !$is_pgp;
31                 last if $iserror;
32                 local *F;
33                 local $_;
34                 my $filename="$HOME/.gnupg/options";
35                 open F,$filename or do { warn "Open \"$filename\": $!"; last; };
36                 local $/="\n";
37                 my @keys=map((/^\s*default-key\s+(\S+)\s*$/),<F>);
38                 @keys==1 or do { warn "Found ".scalar(@keys)." 'default-key's in your \"$filename\", ignoring"; last; };
39                 close F or warn "Close \"$filename\": $!";
40                 my $default_key=$keys[0];
41                 $default_key=~/^[[:xdigit:]]{8}$/ or do { warn "Invalid 'default-key', ignoring: $default_key"; last; };
42                 return Mail::Address->new(
43                                 $phrase,
44                                 'pgp-'.uc($default_key).'@jankratochvil.net',
45                                 );
46                 }
47         # !$is_pgp or fallback
48         return Mail::Address->new(
49                         $phrase,
50                         (!$iserror ? 'rcpt' : 'rcpterr')
51                                         .'-'
52                                         .(defined($rcpt->user()) ? $rcpt->user() : "NOUSER")
53                                         .".AT."
54                                         .(defined($rcpt->host()) ? $rcpt->host() : "LOCAL")
55                                         .'@jankratochvil.net',
56                         );
57 }
58
59 # RedHat sendmail-8.9.3-20/src/conf.c/HdrInfo[]/\Q/* destination fields */\E
60 # FIXME: Recognize "Resent-$_" headers for -t but when we are in 'resent' mode?
61 my @h_rcpt=(    # case in-sensitive!
62                 "To",
63                 "Cc",
64                 "Bcc",
65                 "Apparently-To",
66                 );
67
68 # ordering matters; first header found is substituted
69 # last header is subsituted if no one is found
70 my @h_from=(
71                 "Resent-From",
72                 "From",
73                 );
74
75
76 # FIXME: modularized unification with 'lacemail-accept'
77 # BEGIN lacemail-accept
78 our %muttrc_pending=();
79 sub muttrc
80 {
81 my($muttrc)=@_;
82
83         $muttrc||="$HOME/.muttrc";
84         $muttrc=~s/^\~/$HOME/;
85         do { warn "Looping muttrc, ignoring: $muttrc"; return (); } if $muttrc_pending{$muttrc};
86         local $muttrc_pending{$muttrc}=1;
87         local *MUTTRC;
88         open MUTTRC,$muttrc or do { warn "open \"$muttrc\": $!"; return (); };
89         local $/="\n";
90         local $_;
91         my @r=();
92         # far emulation mutt/init.c/mutt_parse_rc_line()
93         while (<MUTTRC>) {
94                 s/^[\s;]*//s;
95                 s/[#;].*$//s;
96                 s/\s*$//s;
97                 next if !/^(\S+)\s*/s;
98                 if ($1 eq "source") {
99                         $_=$';
100                         do { warn "Wrong 'source' parameters at $muttrc:$.: $_"; next; } if !/^\S+$/;
101                         push @r,muttrc($_);
102                         next;
103                         }
104                 push @r,$_;
105                 }
106         close MUTTRC or warn "close \"$muttrc\": $!";
107         return wantarray() ? @r : join("",map("$_\n",@r));
108 }
109
110 my %mutteval_charmap=(          # WARNING: Don't use "" or "0" here, see below for "|| warn"!
111                 '\\'=>"\\",
112                 'r'=>"\r",
113                 'n'=>"\n",
114                 't'=>"\t",
115                 'f'=>"\f",
116                 'e'=>"\e",
117                 );
118 # mutt/init.c/mutt_extract_token()
119 sub mutteval
120 {
121         local $_=$_[0];
122         return $_ if !s/^"//;
123         do { warn "Missing trailing quote in: $_"; return $_; } if !s/"$//;
124         s/\\(.)/$mutteval_charmap{$1} || warn "Undefined '\\$1' sequence in: $_";/ges;
125         return $_;
126 }
127
128 sub muttrc_get
129 {
130 my(@headers)=@_;
131
132         my @r=map({ (ref $_ ? $_ : qr/^\s*set\s+\Q$_\E\s*=\s*(.*?)\s*$/si); } @headers);
133         my %r=map(($_=>undef()),@r);
134         for (muttrc()) {
135                 for my $ritem (@r) {
136                         /$ritem/si or next;
137                         $r{$ritem}=mutteval $1;
138                         }
139                 }
140         for my $var (grep { !defined($r{$_}) } @r) {
141                 warn "Variable '$var' not found in muttrc";
142                 return undef();
143                 }
144         return wantarray() ? %r : $r{$r[0]};
145 }
146 # END lacemail-accept
147
148
149 sub sendmail_show { return "\"$sendmail_orig\" ".join(",",map("\"$_\"",@ARGV)); }
150
151 sub sendmail_orig_exec
152 {
153         exec {$sendmail_orig} $0,@ARGV or die "exec(".sendmail_show()."): $!";
154         die "NOTREACHED";
155 }
156
157 Getopt::Long::Configure(
158                 "no_ignorecase",
159                 "no_getopt_compat",
160                 "bundling",
161                 # FIXME: workaround: 'unknown options' are considered the same as 'arguments'
162                 # None of ($REQUIRE_ORDER, $PERMUTE, $RETURN_IN_ORDER) can help us.
163                 # No preprocessing possible as it is hard to find option arguments.
164                 "permute",
165                 "pass_through",
166                 );
167
168 my $opt_b;
169 my $opt_Q;
170 my $opt_q;
171 my $opt_t;
172 our $opt_f;
173 #my $opt_F;     # declared before &FromAddress already
174 my $opt_lacemail_dry_run;
175 my @ARGV_save=@ARGV;    # for non-bm mode
176 die if !Getopt::Long::GetOptions(
177                 "b=s"              ,\$opt_b,
178                 "Q:s"              ,\$opt_Q,
179                 "q:s"              ,\$opt_q,
180                 "t"                ,\$opt_t,
181                 "f=s"              ,\$opt_f,
182                 "F=s"              ,\$opt_F,
183                 "lacemail-dry-run+",\$opt_lacemail_dry_run,
184                 );
185 if (0
186                 # RedHat sendmail-8.12.5-7/sendmail/main.c/\QDo a quick prescan of the argument list.\E
187                 || grep({ File::Basename::basename($0) eq $_; } "newaliases","mailq","smtpd","hoststat","purgestat")
188                 # -bm: Deliver mail in the usual way (default).
189                 || (defined($opt_b) && $opt_b ne "m")
190                 || defined $opt_q       # MD_QUEUERUN
191                 || defined $opt_Q       # MD_QUEUERUN
192                 ) {
193         @ARGV=@ARGV_save;
194         sendmail_orig_exec();
195         die "NOTREACHED";
196         }
197
198 # RedHat sendmail-8.9.3-20/src/main.c/main()/\Qif (FullName != NULL)\E
199 #   for $opt_F is implemented by Mail::Address in our &FromAddress
200
201 my $head=MIME::Head->new(\*STDIN);
202 # We may (=will) change the contents and send it multiple times
203 if (defined(my $msgid=$head->get("Message-ID"))) {
204         $head->delete("Message-ID");
205         $head->replace("X-LaceMail-sendmail-Message-ID",$msgid);
206         }
207 # options leave in @ARGV, addresses to @addr:
208 my @args=@ARGV; # temporary
209 @ARGV=();       # options
210 my @addr=();    # addresses
211 push @{(/^-./ ? \@ARGV : \@addr)},$_ for (@args);
212 if ($opt_t) {
213         for my $addrobj (map({ Mail::Address->parse($_); } map({ ($head->get($_)); } @h_rcpt))) {
214                 if (!$addrobj->address()) {
215                         # bogus, shouldn't happen
216                         warn "->address() not found in \"".$addrobj->format()."\"";
217                         next;
218                 }
219                 push @addr,$addrobj;
220                 }
221         }
222
223 # return: Mail::Address instance or undef()
224 sub parseone
225 {
226 my($line)=@_;
227
228         return undef() if !defined $line;
229         my @r=Mail::Address->parse($line);
230         warn "Got ".scalar(@r)." addresses while wanting just one; when parsing: $line" if 1!=@r;
231         return $r[0];
232 }
233
234 sub matches
235 {
236         return 
237 }
238
239 my $from_headername;
240 {
241         my $muttrc_From=parseone(scalar muttrc_get("from"));    # may get undef()!; parseone() may be redundant
242         $muttrc_From=$muttrc_From->address() if $muttrc_From;
243         $opt_f=undef() if defined($opt_f) && $muttrc_From && lc($opt_f) eq lc($muttrc_From);
244         for (@h_from) {
245                 $from_headername=$_;    # leave last item in $from_headername
246                 next if !(my @from_val=$head->get($from_headername));
247                 @from_val=map({ ($_->address()); } map({ (Mail::Address->parse($_)); } @from_val));
248                 $from_headername=undef() if !(1==@from_val && $muttrc_From && lc($from_val[0]) eq lc($muttrc_From));
249                 last;
250                 }       # fallthru with $from_headername remaining set if last headername did not exist
251         # now $from_headername contains the header name to be replaced w/substituted value
252         }
253
254 # to be utilized later by &FromAddress
255 $is_pgp=(1
256                 && do { local $_=$head->mime_attr("Content-Type");          $_ && ~m#^multipart/(?:signed|encrypted)$#; }
257                 && do { local $_=$head->mime_attr("Content-Type.protocol"); $_ && ~m#^application/pgp\b#; }
258                 );
259
260 my $exitcode=0;
261 # !defined($rcpt) if we have no recipients
262 # make the list unique to prevent dupes being normally filtered by sendmail(8)
263 # one '{' is block-wrapper, another '{' is hash-indirection!
264 # hash keys are just strings, never refs!
265 # unify the list as Mail::Address instances
266 my @rcpts=(!@addr ? (undef()) : values(%{{ map({
267                 my $obj=$_;
268                 $obj=parseone $obj if !ref $obj;
269                 (!defined $obj ? () : (lc($obj->address())=>$obj));
270                 } @addr) }}));
271
272 my $stdin_body=(@rcpts<=1 ? undef() : do {      # store input data only if it will be used multiple times
273                 local $/=undef();
274                 <STDIN>;
275                 });
276 for my $rcpt (@rcpts) {
277         local @ARGV=@ARGV;
278         local $opt_f=$opt_f;
279
280         if (defined $rcpt) {    # !defined($rcpt) if we have no recipients
281                 local $_;
282                 $opt_f=FromAddress($rcpt,1)->address() if !defined $opt_f;
283                 $head->replace($from_headername,FromAddress($rcpt,0)->format()) if $from_headername;
284                 }
285
286         1;      # drop '-bm' if present as it is default anyway
287         1;      # drop '-t' if present as we are looping now for it
288         push @ARGV,"-f",$opt_f if defined $opt_f;
289         # we don't handle "Full-Name" header thus pass "-F"
290         # "From/Resent-From" should be handled by our &FromAddress
291         push @ARGV,"-F",$opt_F if defined $opt_F;
292         push @ARGV,$rcpt->address() if defined $rcpt;
293         push @ARGV,@addr_addon;
294
295         local $SIG{"PIPE"}=sub { die "Got SIGPIPE from ".sendmail_show(); };
296         local *SENDMAIL;
297         if ($opt_lacemail_dry_run) {
298                 print sendmail_show()."\n";
299                 *SENDMAIL=\*STDOUT;
300                 }
301         else {
302                 defined (my $pid=open SENDMAIL,"|-") or die "Cannot fork to spawn ".sendmail_show().": $!";
303                 sendmail_orig_exec() if !$pid; # child
304                 }
305         $head->print(\*SENDMAIL);
306         print SENDMAIL "\n";    # MIME::Head->print() eats the empty line but it doesn't print it
307         if (defined($stdin_body)) {
308                 print SENDMAIL $stdin_body;
309                 }
310         else {
311                 local $_;
312                 while (<STDIN>) {
313                         print SENDMAIL $_;
314                         }
315                 }
316
317         next if $opt_lacemail_dry_run;  # don't close our STDOUT as it is aliased to *SENDMAIL
318         close SENDMAIL or warn "close(".sendmail_show()."): $?=".join(",",
319                         (!WIFEXITED($?)   ? () : ("EXITSTATUS(".WEXITSTATUS($?).")")),
320                         (!WIFSIGNALED($?) ? () : ("TERMSIG("   .WTERMSIG($?)   .")")),
321                         (!WIFSTOPPED($?)  ? () : ("STOPSIG("   .WSTOPSIG($?)   .")")),
322                         );
323         my $gotcode=(!WIFEXITED($?) ? 99 : WEXITSTATUS($?));
324         $exitcode=$gotcode if $gotcode>$exitcode;
325         }
326 exit $exitcode;