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