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