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