spamassassin package is now assumed system-wide.
[PerlMail.git] / perlmail-accept
1 #! /usr/bin/perl
2
3 #       $Id$
4 # Copyright (C) 2002-2003 Jan Kratochvil <project-PerlMail@jankratochvil.net>
5
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19
20
21 use vars qw($VERSION);
22 $VERSION=do { my @r=(q$Revision$=~/\d+/g); sprintf "%d.".("%03d"x$#r),@r; };
23 use strict;
24 use warnings;
25
26
27 INIT {
28         require Sys::Syslog;
29         Sys::Syslog::openlog("perlmail","pid","mail");
30         my @syslogging_stack;
31         sub syslogging_on_save
32         {
33                 push @syslogging_stack,$SIG{"__WARN__"},$SIG{"__DIE__" };
34                 $SIG{"__WARN__"}=sub { Sys::Syslog::syslog("warning","WARN: %s",$_[0]); };      # disabled: print STDERR $_[0];
35                 $SIG{"__DIE__" }=sub { Sys::Syslog::syslog("crit"   ,"DIE: %s" ,$_[0]); };
36         }
37         syslogging_on_save();
38         sub syslogging_restore
39         {
40                 $SIG{"__DIE__" }=pop @syslogging_stack;
41                 $SIG{"__WARN__"}=pop @syslogging_stack;
42         }
43         }
44
45
46 use File::Basename;
47 BEGIN {
48         use lib $ENV{"PERLMAIL_BASEDIR"} || File::Basename::dirname($0);
49         use PerlMail::Config;
50         use PerlMail::Lib;
51         }
52
53 use Mail::Audit qw(MAPS);
54 require IO::Handle;
55 use Carp qw(cluck confess);
56 use POSIX qw(WIFEXITED WEXITSTATUS WIFSIGNALED WTERMSIG WIFSTOPPED WSTOPSIG);
57 require POSIX;  # for ceil
58 use User::Utmp;
59 use Getopt::Long;
60 require Mail::Address;
61 require MIME::Words;
62 require Cz::Cstocs;
63 require HTML::Entities;
64 require MIME::Head;
65 require Lingua::EN::Squeeze;
66 require Mail::Mailer;
67 require HTTP::Cookies;
68 require HTTP::Request;
69 require LWP::UserAgent;
70 use URI::Escape 'uri_escape';
71 require WWW::SMS;
72 require Authen::SASL;   # Sanity check for &Net::SMTP::auth
73 use MIME::Base64;
74 use IPC::Open3;
75 use POSIX ":sys_wait_h";
76
77
78 our($Message,@AuditStored,$DoBell);
79 my %alternates_host;    # from @alternates_host
80 my %dnsbl_whitelist;    # from @dnsbl_whitelist
81
82 # from RedHat "procmail-3.22-5"
83 # /i should be only $procmailFROM_DAEMON but how it can hurt to /i all?
84 our $procmailTO_        =qr'^((Original-)?(Resent-)?(To|Cc|Bcc)|(X-Envelope|Apparently(-Resent)?)-To):(.*[^-a-zA-Z0-9_.])?'mio;
85 our $procmailTO         =qr'^((Original-)?(Resent-)?(To|Cc|Bcc)|(X-Envelope|Apparently(-Resent)?)-To):(.*[^a-zA-Z])?'mio;
86 our $procmailFROM_DAEMON=qr'^(Mailing-List:|Precedence:.*(junk|bulk|list)|To: Multiple recipients of |(((Resent-)?(From|Sender)|X-Envelope-From):|>?From )([^>]*[^(.%@a-z0-9])?(Post(ma?(st(e?r)?|n)|office)|(send)?Mail(er)?|daemon|m(mdf|ajordomo)|n?uucp|LIST(SERV|proc)|NETSERV|o(wner|ps)|r(e(quest|sponse)|oot)|b(ounce|bs\.smtp)|echo|mirror|s(erv(ices?|er)|mtp(error)?|ystem)|A(dmin(istrator)?|MMGR|utoanswer))(([^).!:a-z0-9][-_a-z0-9]*)?[%@>        ][^<)]*(\(.*\).*)?)?$([^>]|$))'mio;
87 $procmailFROM_MAILER=qr'^(((Resent-)?(From|Sender)|X-Envelope-From):|>?From )[^>]*\b(Post(ma(st(er)?|n)|office)|(send)?Mail(er)?|daemon|mmdf|n?uucp|ops|r(esponse|oot)|(bbs\.)?smtp(error)?|s(erv(ices?|er)|ystem)|A(dmin(istrator)?|MMGR))(([^).!:a-z0-9][-_a-z0-9]*)?[%@>      ][^<)]*(\(.*\).*)?)?$([^>]|$)'mio;
88 # perl-5.8.0 does not cope w/original FROM_MAILER on the third '?' character
89 # Thus we did '([^>]*[^(.%@a-z0-9])?' -> '[^>]*\b', I hope it is somehow similiar
90 # original FROM_MAILER  =qr'^(((Resent-)?(From|Sender)|X-Envelope-From):|>?From )([^>]*[^(.%@a-z0-9])?(Post(ma(st(er)?|n)|office)|(send)?Mail(er)?|daemon|mmdf|n?uucp|ops|r(esponse|oot)|(bbs\.)?smtp(error)?|s(erv(ices?|er)|ystem)|A(dmin(istrator)?|MMGR))(([^).!:a-z0-9][-_a-z0-9]*)?[%@>    ][^<)]*(\(.*\).*)?)?$([^>]|$)'mio;
91
92 my $opt_mode;
93 my $opt_smstest;        # 1 or $smscount
94 my $opt_idle;
95 my $opt_dry;
96 my $opt_single;
97
98
99 sub process;
100
101 sub stdin
102 {
103         syslogging_restore();   # This is more a debugging session
104         local $/="\n";
105         my $message="";
106         local $_;
107         while (<>) {
108                 die "Invalid 'From ' line: $_" if $message eq "" && !/^From /;
109                 if (!$opt_single && /^From / && $message) {
110                         process $message;
111                         $message="";
112                         }
113                 $message.=$_;
114                 }
115         process $message if $message;
116         exit 0;
117 }
118
119 # FIXME: separate 'perlmail'-transfer together with perlmail-submit away
120 sub inetd
121 {
122         die "Excessive arguments" if @ARGV;
123
124         IO::Handle::autoflush STDOUT 1;
125
126         while (1) {
127                 local $/="\n";
128                 my $length=<STDIN>;
129                 confess "Unexpected EOF" if !defined $length;
130                 confess "Missing EOL" if $length!~s/\n$//s;
131                 exit 0 if $length eq "BYE";
132                 confess "Unrecognized length: $length" if $length!~/^\d+$/;
133                 my $message;
134                 local $_;
135                 $length==($_=read STDIN,$message,$length) or confess "Got $_ out of required $length bytes";
136                 $length==length $message or confess "False read return ".length($message)." instead of $length";
137                 {
138                         # Do not: local *STDOUT;        # FIXME: fd's inherited by spawned processes are not closed this way!
139                         #         local *STDERR;        # FIXME: fd's inherited by spawned processes are not closed this way!
140                         # as IPC::Open3 and IPC::Open2 will not redirect the output
141                         # and send it to the original socket instead!
142                         local $DoBell=0;
143                         process $message;
144                         if ($DoBell) {
145                                 bell() or warn "Unable to BELL";
146                                 }
147                         }
148                 print STDOUT "1";
149                 }
150         die "NOTREACHED";
151 }
152
153 sub bell
154 {
155         local *BELL;
156         open BELL,">/dev/tty11" or return 0;
157         print BELL "\x07";
158         close BELL or return 0;
159         return 1;
160 }
161
162 sub useridle
163 {
164         return 0 if ! -e "$HOME/away";
165         my %valid_users=map(($_=>1),@ValidUsers);
166         my($idlebest,$linebest);
167         for my $utmp (User::Utmp::getut(),{ "ut_line"=>"psaux" }) {
168                 local $_;
169                 next if defined($_=$utmp->{"ut_type"}) && $_!=User::Utmp::USER_PROCESS;
170                 next if defined($_=$utmp->{"ut_user"}) && !$valid_users{$_};
171                 my $line="/dev/".$utmp->{"ut_line"};
172                 my $atime=(stat $line)[8];
173                 my $what="user \"".($utmp->{"ut_user"} || "<local>")."\", line \"$line\"";
174                 warn "Unable to stat $what" and next if !$atime;
175                 my $idle=time()-$atime;
176                 warn "atime in future for $what" and next if $idle<0;
177                 next if $idle>$IdleMax;
178                 next if defined $idlebest && $idlebest<=$idle;
179                 $idlebest=$idle;
180                 $linebest=$line;
181                 }
182         return !wantarray() ? $idlebest : ($idlebest,$linebest);
183 }
184
185 # return only the very (recursive) first part
186 sub body_first
187 {
188         return $Audit if !$Audit->is_mime();
189         my $first=$Audit;
190         local $_;
191         $first=$_ while $_=$first->parts(0);
192         return $first;
193 }
194
195 sub is_multipart
196 {
197         return 0 if !$Audit->is_mime();
198         return $Audit->is_multipart();
199 }
200
201 sub mimehead
202 {
203 my($part)=@_;
204
205         return $Audit->is_mime() ? $part->head()
206                         : MIME::Head->new([ split "\n",$Audit->head()->as_string() ])
207                         ;
208 }
209
210 sub mimebody
211 {
212 my($part)=@_;
213
214         # be vary cautious here as most of $part methods will encode it!
215         return join "",@{$Audit->body()} if !$Audit->is_mime();
216         my $bodyhandle=$part->bodyhandle();
217         # If MIME is corrupted we don't get bodyhandle() for this part
218         # It may occur when "boundary" is specified by header but no such boundary is found in the body
219         return $bodyhandle->as_string() if $bodyhandle;
220         warn "MIME corrupted, adapting";
221         return $part->body_as_string();
222 }
223
224 sub mime_type
225 {
226 my($part)=@_;
227
228         return $Audit->is_mime() ? $part->effective_type() : mimehead($part)->mime_type();
229 }
230
231 sub body_simple
232 {
233         my $first=body_first();
234         my $r=mimebody($first);
235         my $mime_type=mime_type($first);
236            if ($mime_type eq "text/html") {
237                 # HTML::FormatText just does a useless text layouts
238                 # PerlIO::via::StripHTML probably needs PerlIO input (?)
239                 $r=~s/<[^>]*>//gs;
240                 $r=HTML::Entities::decode($r);
241                 # FIXME: detect charset from <meta> tag: "Content-type: text/html; charset=<???>"
242                 }
243         elsif ($mime_type eq "application/pgp-encrypted"
244                && (my $filename=mimehead($first)->mime_attr("Content-Disposition.filename"))
245                ) {
246                 # first part contains just "Version: 1" as of GnuPG v1.0.4 (GNU/Linux)
247                 $r="pgp($filename)";
248                 }
249         if ((my $charset=mimehead($first)->mime_attr("Content-Type.charset"))) {
250                 my $cstocs=Cz::Cstocs->new($charset,"ascii");
251                 $r=&$cstocs($r) if $cstocs;     # charset may be unknown
252                 }
253         return $r;
254 }
255
256 sub parts_linear
257 {
258 my($part)=@_;
259
260         return $Audit if !$part && !$Audit->is_mime();
261         $part||=$Audit;
262         # don't use '!$part->parts()' as even 0-parts-multiparts are still multiparts
263         return $part if $part->bodyhandle();
264         return map { (parts_linear($_)); } $part->parts();
265 }
266
267 sub smsbuild
268 {
269 my($smsi,$smscount)=@_;
270
271         return "$smsi/$smscount:" if $smscount>1;
272         return "";
273 }
274
275 sub smslens
276 {
277 my($ignorenewmail,$smscount,%args)=@_;
278
279         return map({
280                         my $l=160;
281                         if (!$ignorenewmail) {  # send by mail
282                                 $l-=length("Z emailu FIXME SMSmailError: ");
283                                 $l-=length(smsbuild($_,$smscount));
284                                 }
285                         else {  # send by web
286                                 $l-=6;  # 154 is the max length before split; why?
287                                 }
288                         $l;
289                         } (0..$smscount-1));
290 }
291
292 sub smssend_web
293 {
294 my($squeezed,$smscount,@lens)=@_;
295
296         $smscount=POSIX::ceil($smscount/5);
297         for my $smsi (0..$smscount-1) {
298                 my $len=$lens[$smsi];
299                 $squeezed=~/^.{0,$len}/s;
300                 my $frag=$&;
301                 $squeezed=$';
302                 return 0 if 3!=@SMSwebRcpt;
303                 local *F;
304                 open F,"$HOME/priv/WWW-SMS-$SMSwebRcpt_username.pwd" or return 0;
305                 my $pwd=<F>;
306                 chomp $pwd;
307                 close F;
308                 my $sms=WWW::SMS->new(@SMSwebRcpt,$frag,"username"=>$SMSwebRcpt_username,"passwd"=>$pwd);
309                 for ($sms->gateways("sorted"=>"reliability")) {
310                         last if $sms->send($_);
311                         Sys::Syslog::syslog("warning","Web SMS send failed: %s",$WWW::SMS::Error);
312                         my $void=$WWW::SMS::Error;      # Prevent: Name "WWW::SMS::Error" used only once
313                         }
314                 }
315         return 1;
316 }
317
318 sub smssend_mail
319 {
320 my($squeezed,$smscount,@lens)=@_;
321
322         return 0;
323 }
324
325 sub smssend
326 {
327 my($ignorenewmail,$smscount,%args)=@_;
328
329         my $text=PerlMail::Config::audit_sms(
330                         "subject"=>unmime($Audit->subject()),
331                         "from"=>[ Mail::Address->parse(unmime($Audit->from())) ],
332                         "body"=>substr(body_simple(),0,$MaxBodySMS*(1+0.25*$smscount)),
333                         %args);
334         my $texthead="";
335         ($texthead,$text)=@$text if ref $text;
336         do { print "$texthead\n$text\n"; return; } if $opt_smstest;
337         my @lens=smslens($ignorenewmail,$smscount,%args);
338         my $maxlen=0;
339         $maxlen+=$_ for (@lens);
340         my $squeezed;
341         for my $squeeze (@sms_squeezes) {
342                 local $_;
343                  Lingua::EN::Squeeze::SqueezeControl($_)    if defined ($_=$squeeze->{"SqueezeControl"});
344                 $Lingua::EN::Squeeze::SQZ_OPTIMIZE_LEVEL or 1;  # prevent: Name "$_" used only once: possible typo
345                 $Lingua::EN::Squeeze::SQZ_OPTIMIZE_LEVEL=$_ if defined ($_=$squeeze->{"SQZ_OPTIMIZE_LEVEL"});
346                 $squeezed=Lingua::EN::Squeeze::SqueezeText($text);
347                 chomp $squeezed;
348                 last if $maxlen>=length($texthead.$squeezed);
349                 }
350         $squeezed=substr $texthead.$squeezed,0,$maxlen; # strip if we passed thru last for() above
351         my $recalclen=0;
352         for ($smscount=0;$recalclen<length $squeezed;$smscount++) {
353                 $recalclen+=$lens[$smscount];
354                 }
355         my $func=($ignorenewmail ? \&smssend_web : \&smssend_mail);
356         &$func($squeezed,$smscount,@lens);
357 }
358
359 sub smssend_tryall
360 {
361 my($ignorenewmail,@args)=@_;
362
363         return if !$opt_smstest && !$opt_idle && defined useridle();
364         local $_;
365         return $_ if                     $_=smssend(1,@args);   # web
366         return $_ if !$ignorenewmail && ($_=smssend(0,@args));  # mail
367         warn "Unable to SMSsend the mail";
368         return 0;
369 }
370
371 sub cut
372 {
373         local $_=$_[0];
374         return "<???>" if !defined($_) || /^\s*$/s;
375         s/^\s*//s;
376         s/\s*$//s;
377         return $_ if length($_)<128;
378         return substr($_,0,128)."...";
379 }
380
381 our $profile_eval_depth=0;
382 # ($name || @$name)
383 sub profile_eval
384 {
385 my($name)=@_;
386
387         die "Nesting profile: $name" if 0x10<=(local $profile_eval_depth=$profile_eval_depth+1);
388         return @$name if ref $name;
389         die "Profile not found: $name" if !exists $audit_profile{$name};
390         my @this=@{$audit_profile{$name}};
391         return (profile_eval($'),@this[1..$#this]) if $this[0] && $this[0]=~/^=/;
392         return @this;
393 }
394
395 sub address_show
396 {
397 my($text)=@_;
398
399         return join(",",map({ $_->name() or $_->address(); } Mail::Address->parse($text)));
400 }
401
402 sub unmime
403 {
404 my($text)=@_;
405
406         return join "",map({
407                         my $cstocs;
408                         for (${$_}[1],"iso-8859-2") {
409                                 last if $_ && ($cstocs=Cz::Cstocs->new($_,"ascii"));
410                                 }
411                         &$cstocs(${$_}[0]);
412                         } MIME::Words::decode_mimewords($text));
413 }
414
415 # $folder: "$folder; comment"
416 # $profile as profile_eval($name)
417 sub store
418 {
419 my($folder,$profile,%args)=@_;
420
421         $profile=$store_profile if !$profile;
422         my %do=map({ (!/=/ ? ($_=>1) : ($`=>$')); } profile_eval($profile));
423         Sys::Syslog::syslog("info","%s%s%s: %s: %s",
424                                         (!$opt_dry ? "" : "--dry: "),
425                                         (!$store_ignore ? "" : "IGNORED[$store_ignore]: "),
426                                         map({ cut($_); } $folder,address_show(unmime($Audit->from())),unmime($Audit->subject())),
427                                         )
428                         if $do{"syslog"} || $opt_dry;
429         $folder=~s/;.*$//s;
430         $folder="$Mail/".$' if $folder=~/^=/;
431         push @AuditStored,$folder if $do{"did"};
432         return if $store_ignore || $opt_dry;
433         $DoBell++ if $do{"bell"};
434         write_message($folder) or die;
435         smssend_tryall $store_ignorenewmail,$do{"sms"},%args if $do{"sms"};
436 }
437
438 our $did_last=0;
439
440 # no &$funcref=>did smth in this block
441 # &$funcref,@funcargs
442 sub did
443 {
444 my($funcref,@funcargs)=@_;
445
446         return @AuditStored!=$did_last if !$funcref;
447         local $did_last=@AuditStored;
448         &$funcref(@funcargs);
449         return @AuditStored!=$did_last;
450 }
451
452 # Never use Mail::Audit->store() as it will reformat MIME bodies and possibly corrupt OpenPGP!
453 sub write_message
454 {
455 my($folder)=@_;
456
457         return 1 if $opt_dry;   # simulate OK
458         local *F;
459         open F,">>$folder" or do { warn "Append \"$folder\": $!"; return 0; };
460         {
461                 local $_;
462                 ($_=Mail::Audit::audit_get_lock(\*F,$folder)) and do { warn "Lock \"$folder\": $!"; last; };
463                 seek F,0,IO::Handle::SEEK_END or do { warn "Seek-end \"$folder\": $!"; last; };
464                 # FIXME: Check for '^From ' to not to rely on our network peer
465                 print F $Message or do { warn "Write to \"$folder\": $!"; last; };
466                 do { print F "\n"; warn "Missing trailing newline, fixed"; } if $Message!~/\n$/s;
467                 close F or do { warn "Close \"$folder\""; last; };
468                 return 1;       # OK
469                 }
470         warn "MAIL DROPPED for folder: $folder";
471         close F;
472         return 0;       # failed
473 }
474
475 sub process
476 {
477 my($message)=@_;
478
479         local $_=$_;
480         my $save_=$_;
481         $message=~s/(\n)(From )/$1>$2/sg;
482         local $Message=$message;
483         # Cannot call 'local' for our-imported variable:
484         my $Audit_save=$Audit;
485         $Audit=Mail::Audit->new(
486                         "emergency"=>"$Mail/emergency",
487                         "data"=>[map("$_\n",split("\n",$message))],
488                         "log"=>"$HOME/.perlmail.log",
489                         "loglevel"=>99,
490                         );
491         local @AuditStored=();
492         do { smssend 0,$opt_smstest; return; } if $opt_smstest;
493         write_message("$Mail/input") or die;
494         PerlMail::Config::audit();
495         warn 'Corrupted $_, repaired' if defined($save_)!=defined($_) || (defined($_) && $save_ ne $_);
496         # restore:
497         $Audit=$Audit_save;
498 }
499
500 # utility functions:
501
502 sub _spamchildcode
503 {
504 my($err,$isspam)=@_;
505
506         $err=$? if !defined $err;
507         return undef()    if !WIFEXITED($?);
508         return undef()    if  WIFSIGNALED($?);
509         return undef()    if  WIFSTOPPED($?);
510         return 0 if !WEXITSTATUS($?);
511         return $isspam||1 if 1==WEXITSTATUS($?);        # isspam
512         cluck "Possible FIXME or your system is broken (WEXITSTATUS==".WEXITSTATUS($?).")";
513         return 0;       # simulate as not spam
514 }
515
516 # return: true (error-message or "1") if is spam
517 sub spamassassin
518 {
519 my($cmd)=@_;
520
521         $cmd||="spamassassin --exit-code 1";
522         # spamassassin has the specified exit code if IS spam, code 0 if NOT spam
523         # See &_spamchildcode for the code 1.
524         local *CHILD;
525         local $SIG{"PIPE"}=sub { warn "spamassassin gave me SIGPIPE: broken pipe"; };
526         # prevent Razor2's: Can't call method "log" on unblessed reference at Razor2/Client/Agent.pm line 212.
527         local $ENV{"HOME"}=$HOME;
528         # 2>/dev/null to prevent error messages to corrupt inetd() output of perlmail-accept(1)
529         open CHILD,"|$cmd --mbox >/dev/null 2>/dev/null"
530                         or return 0;
531         print CHILD $Message;
532         close CHILD;
533         return _spamchildcode;
534 }
535
536 # NOTE: returns undef() if !wantarray and the first header is unrecognized
537 # Returns always HOST:IP pair(s).
538 sub Received_for
539 {
540         my @r=();
541         for my $hdr ($Audit->head->get("Received")) {
542                 my($for)=($hdr=~/\bfor\s+\<?(\S+)\>?\b/);
543                 return $for if !wantarray();
544                 push @r,$for if $for;
545                 my($from,$fromaddr)=($hdr=~/\bfrom\s+(?:(\S+)\b.*?)??\[((?:\d{1,3}\.){3}\d{1,3})\]/);
546                 $from=$fromaddr if !defined $from;
547                 push @r,"$from:$fromaddr" if $from;
548                 }
549         return @r;
550 }
551
552 # Extended Mail::Audit::MAPS
553 # $domain,$full,[$timeout]
554 # Returns false if valid, code if spam detected.
555 sub dnsbl
556 {
557 my($domain,$full,$timeout)=@_;
558
559         $timeout||=30;  # sec
560         $Mail::Audit::MAPS::host=$domain;
561         for my $host (Received_for()) {
562                 next if $host!~/^([^:@]*):/;
563                 my $ip=$';
564                 # $1 is DNS name, $ip is IP address
565                 next if $alternates_host{$1};   # leave only foreign hosts
566                 next if $dnsbl_whitelist{$ip};
567                 {
568                         package My::Audit::Faked;
569                         sub received { return @{$_[0]->{"received"}}; }
570                         }
571                 my $self_faked={
572                                 "received"=>["[$ip]"],
573                                 };
574                 bless $self_faked,"My::Audit::Faked";
575                 my $code=Mail::Audit::rblcheck($self_faked,$timeout);
576                 next if !$code;
577                 # Some 0.0.0.0 etc. found for <linux-kernel@>, see: &Mail::Audit::MAPS::_checkit
578                 # Do not: $code!='1 Invalid IP address '
579                 # as it causes warn.
580                 return $code if $code ne '1 Invalid IP address ';
581                 return if !$full;
582                 }
583 }
584
585 # Returns true if IS virus; the message will contain the virus name
586 sub clamscan
587 {
588 my($cmd)=@_;
589
590         $cmd||='clamscan --no-summary -';
591         # clamscan has exit code 1 if IS virus , code 0 if NOT virus
592         # Do not use IPC::Open2 as it would try to use our STDERR which is not valid by: local *STDERR;
593         local(*WR,*RD,*ERR);
594         local $SIG{"PIPE"}=sub { warn "clamscan '$cmd' gave me SIGPIPE: broken pipe"; };
595         my $pid=open3(\*WR,\*RD,\*ERR,$cmd.' 2>&1')
596                         or do { cluck "IPC::Open3 $cmd: $!"; return 0; };
597         print WR $Message;
598         close WR or do { cluck "close WR of $cmd: $!"; return 0; };
599         my $status=do { local $/=undef(); <RD>; };
600         close RD or do { cluck "close RD of $cmd: $!"; return 0; };
601         # Do not: $status.=do { local $/=undef(); <ERR>; };
602         #         close ERR or do { cluck "close ERR of $cmd: $!"; return 0; };
603         # (FIXME) as it causes: Use of uninitialized value in <HANDLE>
604         # waitpid fills $? for: &_spamchildcode
605         local $SIG{"ALRM"}=sub { warn "Timeout $clamscan_waitpid_timeout sec waiting for child $cmd"; };
606         alarm $clamscan_waitpid_timeout;
607         # Do not: WNOHANG
608         # as it would not be enough for clamscan(1) even after all close-s above.
609         my $pidcheck=waitpid($pid,0);
610         alarm 0;
611         my $err=$?;
612         $pidcheck && $pidcheck==$pid
613                         or do { cluck "waitpid for $cmd returned $pidcheck!=$pid"; return 0; };
614         $status=~s/^stdin: //mg;
615         # Prevent: LibClamAV Warning: PGP encoded attachment not scanned
616         $status=~s/^.*\bwarning:.*\n//img;
617         $status=~s/\n$//;
618         return $status if $status ne "OK" && $status;
619         return _spamchildcode $err,$status;
620 }
621
622 sub muttrc_aliases
623 {
624         my %r=();
625         for (muttrc()) {
626                 next if !(my $key=(/^alias\s+(\S+)\s+/)[0]);
627                 for my $addrobj (Mail::Address->parse($')) {
628                         my $addr=$addrobj->address();
629                         my $ref=\$r{"\L$addr"};
630                         $$ref=$key if !$$ref;   # use always the first occurence to prefer nicks
631                         }
632                 }
633         return %r;
634 }
635
636 # FIXME: host may get multiple recipients and thus not showing "for <...>"
637 # FIXME: muttrc_get("from") is too strict
638 sub store_muttrc_alternates
639 {
640 my($prefix,$profile)=@_;
641
642         my $alternates=muttrc_get("alternates") or return;
643         my $alternatesre=qr/$alternates/si;
644         my $From=muttrc_get("from") or return;
645         my $Fromre=qr/^\Q$From\E$/si;
646         my $Fromobj=parseone $From or return;
647         warn "'From' \"$From\" not matched by 'alternates': $alternatesre"
648                         if $From!~/$alternates/si;
649         for my $for (reverse Received_for()) {
650                 $for=~s/:.*$//; # strip IP address here
651                 my $forobj=parseone $for;
652                 if ($forobj && $forobj->host()) {
653                         # it is 'for' our primary address
654                         next if lc($forobj->host()) eq lc($Fromobj->host());    # or 'return'? shouldn't matter
655                         }
656                 next if !$alternates_host{lc $for} && $for!~/$alternatesre/si;
657                 store "$prefix\L$for",($profile || []);
658                 return;
659                 }
660 }
661
662 # $header: ref CODE
663 # $header: !ref => $Audit->get($header)
664 # $maybeaddress: qr/regex/i
665 # $maybeaddress: "string"
666 # $maybeaddress: "<Regexp:regex>"       # hack :-(
667 # $maybeaddress: "<user@host>"
668 # $maybeaddress: "<user@>"
669 # $maybeaddress: "<@host>"
670 sub _headercore
671 {
672 my($re,$justone,$header,$maybeaddress)=@_;
673
674         if (ref $header) {
675                 $header=join(",",&$header());
676                 }
677         else {
678                 $header=$Audit->get($header);
679                 }
680         return 0 if !$header;
681         return $header=~/$maybeaddress/i if "Regexp" eq ref $maybeaddress;
682         return $header=~/$re/i if !defined(my $want=($maybeaddress=~/^\<(.*)\>$/)[0]);
683         my @parsed=Mail::Address->parse($header);
684         warn "'mailto:' forbidden in pattern: $want" if $want=~/^\Qmailto:\E/;
685         return 0 if $justone && 1!=@parsed;
686         return grep {
687                            if ($want=~/^Regexp:/)
688                                 { $_->address()=~/$'/i; }
689                         elsif ($want=~/\@$/)
690                                 { $_->user()   =~/^(?:\Qmailto:\E)?\Q$`\E/i; }
691                         elsif ($want=~/^\@/)
692                                 { $_->host()   =~/^\Q$'\E/i; }
693                         else
694                                 { $_->address()=~/^(?:\Qmailto:\E)?\Q$want\E/i; }
695                         } @parsed;
696 }
697
698 sub headerhas
699 {
700 my($header,$substr)=@_;
701
702         return _headercore(qr/\Q$substr\E/i,0,$header,$substr);
703 }
704
705 sub headeris
706 {
707 my($header,$string)=@_;
708
709         return _headercore(qr/\Q$string\E/i,1,$header,$string);
710 }
711
712 # $header,%$map
713 sub header_remap
714 {
715 my($header,$map)=@_;
716
717         my $text=$Audit->get($header);
718         my $orig=$text;
719         while (my($from,$to)=each(%$map)) {
720                 $text=~s/\b\Q$from\E\b/$to/gsi;
721                 }
722         return if $text eq $orig;
723         $Audit->put_header("X-PerlMail-header_remap-$header",$orig);
724         $Audit->replace_header($header,$text);
725 }
726
727 # LMTP engine:
728 use Net::Cmd qw(CMD_OK CMD_MORE);
729 {
730         package My::Net::SMTP::LMTP;
731         require Net::SMTP;
732         our @ISA=qw(Net::SMTP);
733         use Net::SMTP;
734         use Net::Cmd qw(CMD_OK);
735         use Carp qw(confess cluck);
736
737         # Do not: sub _HELO
738         # as it would not set {'net_smtp_esmtp'}
739         sub _EHLO { shift->command("LHLO", @_)->response()  == CMD_OK }
740
741         sub clucked
742         {
743         my($self,$func,@args)=@_;
744
745                 do { return $_ if defined $_; } for $self->$func(@args);
746                 cluck $func;
747                 return;
748         }
749 }
750
751
752 sub lmtp_deliver
753 {
754 my($admin_user,$admin_pwd,$user_from,$user_to)=@_;
755
756         my $lmtp=My::Net::SMTP::LMTP->clucked("new","localhost","Port"=>"lmtp",
757 #                       "Debug"=>1,
758                         ) or return;
759         bless $lmtp,"My::Net::SMTP::LMTP";
760 # Prevent:
761 # due to:
762 #       $lmtp->auth(Authen::SASL->new(
763 #                       "mechanism"=>"PLAIN",
764 #                       "callback"=>{
765 #                                       "user"=>$admin_user,
766 #                                       "pass"=>$admin_pwd,
767 #                                       # Prevent: "authname"=>$admin_user
768 #                                       # as it causes: DIE: Unknown callback: 'authname'. (user|auth|language|pass)
769 #                                       }));
770         # FIXME: Authentication hack:
771         $lmtp->command("AUTH PLAIN")->response()==CMD_MORE
772                         or do { cluck "auth announce"; return; };
773         $lmtp->clucked("command",encode_base64($user_from."\x00".$admin_user."\x00".$admin_pwd)) or return;
774         $lmtp->clucked("mail",$user_from) or return;
775         $lmtp->clucked("to",$user_to) or return;
776         $lmtp->clucked("data"); # Do not: or return;
777         # Prevent: 554 5.6.0 Message contains invalid header
778         (my $data=$Message)=~s/\AFrom .*\r?\n//;
779         $lmtp->clucked("datasend",$data) or return;
780         $lmtp->clucked("dataend") or return;
781         $lmtp->clucked("quit") or return;
782 }
783
784
785 # MAIN
786
787 $Getopt::Long::ignorecase=0;
788 die "GetOptions error" if !Getopt::Long::GetOptions(
789                   "inetd"    ,sub { $opt_mode=\&inetd; },
790                   "stdin"    ,sub { $opt_mode=\&stdin; },
791                   "single!"  ,\$opt_single,
792                   "dry"      ,\$opt_dry,
793                   "smstest:s",sub { $opt_mode=\&stdin; $opt_smstest=($_[1] || 1); },
794                   "idle!"    ,\$opt_idle,
795                   "idletest" ,sub { syslogging_restore(); print((defined($_=useridle()) ? $_ : "<undef>")."\n"); exit 0; },
796                   "muttrc"   ,sub { syslogging_restore(); print scalar muttrc(); exit 0; },
797                 );
798 # "Excessive arguments" checked in &inetd
799 die "Missing mode" if !$opt_mode;
800
801 %alternates_host=map((lc($_)=>1),@alternates_host);
802 %dnsbl_whitelist=map((   $_ =>1),@dnsbl_whitelist);
803
804 &$opt_mode();
805 die "NOTREACHED";