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