Fixed (suppressed) bell if $store_ignore
[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("lacemail","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 Mail::Audit qw(MAPS);
31 require IO::Handle;
32 use Carp qw(cluck confess);
33 use POSIX qw(WIFEXITED WEXITSTATUS WIFSIGNALED WTERMSIG WIFSTOPPED WSTOPSIG);
34 require POSIX;  # for ceil
35 use User::Utmp;
36 require File::Basename;
37 use Getopt::Long;
38 require Mail::Address;
39 require MIME::Words;
40 require Cz::Cstocs;
41 require HTML::Entities;
42 require MIME::Head;
43 require Lingua::EN::Squeeze;
44 require Mail::Mailer;
45 require HTTP::Cookies;
46 require HTTP::Request;
47 require LWP::UserAgent;
48 use URI::Escape 'uri_escape';
49
50
51 my $HOME="/home/lace";
52 my $Mail="$HOME/Mail";
53 my @ValidUsers=qw(root lace short kratochvil _local);
54 my $IdleMax=60;
55 my $MaxBodySMS=0x1000;  # max bytes to pass to Lingua::EN::Squeeze
56 my $SMSmailError='short+err@ucw.cz';
57 my $SMSwebRcpt='00420602431329';
58 my $SMSmailRcpt=$SMSwebRcpt.'@sms.eurotel.cz';
59 my $SMScontact='<short@ucw.cz>';
60
61 our($Message,$Audit,@AuditStored,$store_ignore,$store_ignorenewmail,$store_profile,$DoBell);
62 our(%audit_profile,@sms_squeezes);      # imported
63
64 # from RedHat "procmail-3.22-5"
65 # /i should be only $procmailFROM_DAEMON but how it can hurt to /i all?
66 our $procmailTO_        =qr'^((Original-)?(Resent-)?(To|Cc|Bcc)|(X-Envelope|Apparently(-Resent)?)-To):(.*[^-a-zA-Z0-9_.])?'mio;
67 our $procmailTO         =qr'^((Original-)?(Resent-)?(To|Cc|Bcc)|(X-Envelope|Apparently(-Resent)?)-To):(.*[^a-zA-Z])?'mio;
68 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;
69 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;
70 # perl-5.8.0 does not cope w/original FROM_MAILER on the third '?' character
71 # Thus we did '([^>]*[^(.%@a-z0-9])?' -> '[^>]*\b', I hope it is somehow similiar
72 # 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;
73
74 my $opt_mode;
75 my $opt_smstest;        # 1 or $smscount
76 my $opt_idle;
77
78
79 sub process;
80
81 sub stdin
82 {
83         syslogging_restore();   # This is more a debugging session
84         local $/="\n";
85         my $message="";
86         local $_;
87         while (<>) {
88                 die "Invalid 'From ' line: $_" if $message eq "" && !/^From /;
89                 if (/^From / && $message) {
90                         process $message;
91                         $message="";
92                         }
93                 $message.=$_;
94                 }
95         process $message if $message;
96         exit 0;
97 }
98
99 # FIXME: separate 'lacemail'-transfer together with lacemail-submit away
100 sub inetd
101 {
102         die "Excessive arguments" if @ARGV;
103
104         IO::Handle::autoflush STDOUT 1;
105
106         while (1) {
107                 local $/="\n";
108                 my $length=<STDIN>;
109                 confess "Unexpected EOF" if !defined $length;
110                 confess "Missing EOL" if $length!~s/\n$//s;
111                 exit 0 if $length eq "BYE";
112                 confess "Unrecognized length: $length" if $length!~/^\d+$/;
113                 my $message;
114                 local $_;
115                 $length==($_=read STDIN,$message,$length) or confess "Got $_ out of required $length bytes";
116                 $length==length $message or confess "False read return ".length($message)." instead of $length";
117                 {
118                         local *STDOUT;
119                         local *STDERR;
120                         local $DoBell=0;
121                         process $message;
122                         if ($DoBell) {
123                                 bell() or warn "Unable to BELL";
124                                 }
125                         }
126                 print STDOUT "1";
127                 }
128         die "NOTREACHED";
129 }
130
131 sub bell
132 {
133         local *BELL;
134         open BELL,">/dev/tty11" or return 0;
135         print BELL "\x07";
136         close BELL or return 0;
137         return 1;
138 }
139
140 sub useridle
141 {
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 # FIXME: rewrite &send_cz_eurotel properly by own code
247 # patch for http://kiwi.ms.mff.cuni.cz/%7Etom/programming/src/sendsms.tar.gz/sendsms.pl
248 my $agent=LWP::UserAgent->new();
249 $agent->agent("LaceMail $VERSION; contact=$SMScontact; ");
250 my($request1,$response1);       # for &send_cz_eurotel
251 my($name,$value,$type,$disabled,$q2);
252
253 # &send_cz_eurotel returns: error
254 # BEGIN http://kiwi.ms.mff.cuni.cz/%7Etom/programming/src/sendsms.tar.gz/sendsms.pl
255 sub parse_inputs
256 {
257         my ($resp) = @_;
258         my @inputs;
259         my $ct;
260         my @c;
261         $ct=$resp->content();
262
263         @c=split '>', $ct;
264         grep {
265            if (/(<input|<select|<textarea)([^<>]*)(>|$)/i) { 
266              my $txt=$2, $name="", $value="", $type="x", $disabled=0;
267              my $ipoc;
268              if ($txt =~ /type="([^"]*)"/i) { $type=$1; }
269              elsif ($txt =~ /type=([^" ]*)[ >]/i) { $type=$1; }
270              if ($txt =~ /name="([^"]*)"/i) { $name=$1; }
271              elsif ($txt =~ /name=([^" ]*)[ >]/i) { $name=$1; }
272              if ($txt =~ /value="([^"]*)"/i) { $value=$1; }
273              elsif ($txt =~ /value=([^" ]*)[ >]/i) { $value=$1; }
274              if ($txt =~ /disabled/i) { $disabled=1; }
275              if ($name ne "" && $type ne "" && $type ne "button" && ! $disabled)
276              {
277                $ipoc=$#inputs;
278                $inputs[$ipoc+1][0]=$name;
279                $inputs[$ipoc+1][1]=$value;
280              }
281            }
282         0; } @c;
283         return @inputs;
284 }
285
286 sub make_query
287 {
288         my (@inputs) = @_;
289
290         my $i;
291         my $query = "";
292
293         for ($i=0; $i<=$#inputs; $i++)
294         {
295           my($q1, $q2);
296           if ($i>0) { $query="$query&"; }
297           $q1=uri_escape($inputs[$i][0]);
298           $q2=uri_escape($inputs[$i][1]);
299           $query="$query$q1=$q2";
300         }
301
302         #change @ and space back
303         $query=~ s/%20/+/g;
304         $query=~ s/%40/@/g;
305         return $query;
306 }
307
308 sub send_cz_eurotel
309 {
310         my ($id,$text,$mail,$directd) = @_;
311         my $src_url = "http://www2.eurotel.cz/sms/index.html";
312         my @inputs;
313         my $query = "";
314         my $cookie = HTTP::Cookies->new;
315         my $pref;
316
317         #check if correct number
318         if (substr($id,0,5)!="00420") { return -1; }
319         $pref=substr($id,5,3);
320         if (!($pref eq "601" || $pref eq "602" || $pref eq "606" || $pref eq "607"  || ($pref ge "720" && $pref le "729"))) { return -1; }
321         
322         #get form page, extract cookies
323         $request1=new HTTP::Request('GET', "$src_url?n_pagestyle=new");
324         $response1=$agent->request($request1);
325         if ($response1->code != 200) { return -3; }
326         $cookie->extract_cookies($response1);
327
328         #parse the form
329         @inputs=parse_inputs($response1);
330         
331         #fill the form
332         $inputs[2][1]=substr($id,5,3);
333         $inputs[3][1]=substr($id,8,6);
334         $inputs[4][1]=$mail;
335
336         #direct display
337         $inputs[6][1]="sms";
338         $inputs[6][1]="show" if ($directd>0);
339
340         $inputs[7][1]=$text;
341
342 #       for ($i=0; $i<=$#inputs; $i++) { print "[$i] $inputs[$i][0] $inputs[$i][1]\n"; } 
343
344         #make query
345         $query=make_query(@inputs);
346
347         #POST the form
348         my $header = new HTTP::Headers( 
349                 'Content-Length' => length($query),
350                 'Content-Type' => 'application/x-www-form-urlencoded',
351                 'Accept' => '*/*',
352                 'Referer' => $src_url
353         );
354         my $request2 = new HTTP::Request('POST',$src_url, $header, $query);
355         $cookie->add_cookie_header($request2);
356         my $response2 = $agent->request($request2);
357
358         if ($response2->code != 200) { return -3; }
359
360         #check for success
361         if ($response2->content() !~ /byla.*odesl.*na na SMS centrum/)
362         {
363           return -2;
364         }
365         return 0;
366 }
367 # END http://kiwi.ms.mff.cuni.cz/%7Etom/programming/src/sendsms.tar.gz/sendsms.pl
368
369 sub smslens
370 {
371 my($ignorenewmail,$smscount,%args)=@_;
372
373         return map({
374                         my $l=160;
375                         if (!$ignorenewmail) {  # send by mail
376                                 $l-=length("Z emailu $SMSmailError: ");
377                                 $l-=length(smsbuild($_,$smscount));
378                                 }
379                         else {  # send by web
380                                 $l-=length("Z WWW x/5: ");
381                                 $l-=length(smsbuild($_,POSIX::ceil($smscount/5)));
382                                 }
383                         $l;
384                         } (0..$smscount-1));
385 }
386
387 sub smssend_web
388 {
389 my($squeezed,$smscount,@lens)=@_;
390
391         $smscount=POSIX::ceil($smscount/5);
392         for my $smsi (0..$smscount-1) {
393                 my $len=$lens[$smsi];
394                 $squeezed=~/^.{0,$len}/s;
395                 my $frag=$&;
396                 $squeezed=$';
397                 return 0 if send_cz_eurotel($SMSwebRcpt,$frag,"",0);
398                 }
399         return 1;
400 }
401
402 sub smssend_mail
403 {
404 my($squeezed,$smscount,@lens)=@_;
405
406         my $recalclen=0;
407         for ($smscount=0;$recalclen<length $squeezed;$smscount++) {
408                 $recalclen+=$lens[$smscount];
409                 }
410         for my $smsi (0..$smscount-1) {
411                 my $len=$lens[$smsi];
412                 $squeezed=~/^.{0,$len}/s;
413                 my $frag=$&;
414                 $squeezed=$';
415                 my $mail=Mail::Mailer->new("sendmail","-f","$SMSmailError");
416                 $mail->open({
417                                 "To"=>$SMSmailRcpt,
418                                 "From"=>$SMSmailError,  # no longer displayed anyway
419                                 "X-LaceMail-Version"=>$VERSION,
420                                 "X-LaceMail-Contact"=>$SMScontact,
421                                 });
422                 print $mail smsbuild($smsi,$smscount).$frag."\n";
423                 # FIXME: check errors
424                 $mail->close();
425                 }
426         return 1;
427 }
428
429 sub smssend
430 {
431 my($ignorenewmail,$smscount,%args)=@_;
432
433         my %aliases=muttrc_aliases();
434         my $text=audit_sms(
435                         "subject"=>unmime($Audit->subject()),
436                         "from"=>[ map({ $_=$_->address(); $_="\L$_"; $aliases{$_} || $_; } Mail::Address->parse(unmime($Audit->from()))) ],
437                         "body"=>substr(body_simple(),0,$MaxBodySMS*(1+0.25*$smscount)),
438                         %args);
439         my $texthead="";
440         ($texthead,$text)=@$text if ref $text;
441         do { print "$texthead\n$text\n"; return; } if $opt_smstest;
442         my @lens=smslens($ignorenewmail,$smscount,%args);
443         my $maxlen=0;
444         $maxlen+=$_ for (@lens);
445         my $squeezed;
446         for my $squeeze (@sms_squeezes) {
447                 local $_;
448                  Lingua::EN::Squeeze::SqueezeControl($_)    if defined ($_=$squeeze->{"SqueezeControl"});
449                 $Lingua::EN::Squeeze::SQZ_OPTIMIZE_LEVEL or 1;  # prevent: Name "$_" used only once: possible typo
450                 $Lingua::EN::Squeeze::SQZ_OPTIMIZE_LEVEL=$_ if defined ($_=$squeeze->{"SQZ_OPTIMIZE_LEVEL"});
451                 $squeezed=Lingua::EN::Squeeze::SqueezeText($text);
452                 chomp $squeezed;
453                 last if $maxlen>=length($texthead.$squeezed);
454                 }
455         $squeezed=substr $texthead.$squeezed,0,$maxlen; # strip if we passed thru last for() above
456         my $recalclen=0;
457         for ($smscount=0;$recalclen<length $squeezed;$smscount++) {
458                 $recalclen+=$lens[$smscount];
459                 }
460         my $func=($ignorenewmail ? \&smssend_web : \&smssend_mail);
461         &$func($squeezed,$smscount,@lens);
462 }
463
464 sub smssend_tryall
465 {
466 my($ignorenewmail,@args)=@_;
467
468         return if !$opt_smstest && !$opt_idle && defined useridle();
469         local $_;
470         return $_ if                     $_=smssend(1,@args);   # web
471         return $_ if !$ignorenewmail && ($_=smssend(0,@args));  # mail
472         warn "Unable to SMSsend the mail";
473         return 0;
474 }
475
476 sub cut
477 {
478         local $_=$_[0];
479         return "<???>" if !defined($_) || /^\s*$/s;
480         s/^\s*//s;
481         s/\s*$//s;
482         return $_ if length($_)<64;
483         return substr($_,0,64)."...";
484 }
485
486 our $profile_eval_depth=0;
487 # ($name || @$name)
488 sub profile_eval
489 {
490 my($name)=@_;
491
492         die "Nesting profile: $name" if 0x10<=(local $profile_eval_depth=$profile_eval_depth+1);
493         return @$name if ref $name;
494         die "Profile not found: $name" if !exists $audit_profile{$name};
495         my @this=@{$audit_profile{$name}};
496         return (profile_eval($'),@this[1..$#this]) if $this[0] && $this[0]=~/^=/;
497         return @this;
498 }
499
500 sub address_show
501 {
502 my($text)=@_;
503
504         return join(",",map({ $_->name() or $_->address(); } Mail::Address->parse($text)));
505 }
506
507 sub unmime
508 {
509 my($text)=@_;
510
511         return join "",map({
512                         my $cstocs;
513                         for (${$_}[1],"iso-8859-2") {
514                                 last if $_ && ($cstocs=Cz::Cstocs->new($_,"ascii"));
515                                 }
516                         &$cstocs(${$_}[0]);
517                         } MIME::Words::decode_mimewords($text));
518 }
519
520 # $folder: "$folder; comment"
521 # $profile as profile_eval($name)
522 sub store
523 {
524 my($folder,$profile,%args)=@_;
525
526         $profile=$store_profile if !$profile;
527         my %do=map({ (!/=/ ? ($_=>1) : ($`=>$')); } profile_eval($profile));
528         Sys::Syslog::syslog("info","%s%s: %s: %s",
529                                         (!$store_ignore ? "" : "IGNORED[$store_ignore]: "),
530                                         map({ cut($_); } $folder,address_show(unmime($Audit->from())),unmime($Audit->subject())),
531                                         )
532                         if $do{"syslog"};
533         $folder=~s/;.*$//s;
534         $folder="$Mail/".$' if $folder=~/^=/;
535         push @AuditStored,$folder if $do{"did"};
536         return if $store_ignore;
537         $DoBell++ if $do{"bell"};
538         write_message($folder);
539         smssend_tryall $store_ignorenewmail,$do{"sms"},%args if $do{"sms"};
540 }
541
542 our $did_last=0;
543
544 # no &$funcref=>did smth in this block
545 # &$funcref,@funcargs
546 sub did
547 {
548 my($funcref,@funcargs)=@_;
549
550         return @AuditStored!=$did_last if !$funcref;
551         local $did_last=@AuditStored;
552         &$funcref(@funcargs);
553         return @AuditStored!=$did_last;
554 }
555
556 # Never use Mail::Audit->store() as it will reformat MIME bodies and possibly corrupt OpenPGP!
557 sub write_message
558 {
559 my($folder)=@_;
560
561         local *F;
562         open F,">>$folder" or do { warn "Append \"$folder\": $!"; return 0; };
563         {
564                 local $_;
565                 ($_=Mail::Audit::audit_get_lock(\*F,$folder)) and do { warn "Lock \"$folder\": $!"; last; };
566                 seek F,0,IO::Handle::SEEK_END or do { warn "Seek-end \"$folder\": $!"; last; };
567                 # FIXME: Check for '^From ' to not to rely on our network peer
568                 print F $Message or do { warn "Write to \"$folder\": $!"; last; };
569                 do { print F "\n"; warn "Missing trailing newline, fixed"; } if $Message!~/\n$/s;
570                 close F or do { warn "Close \"$folder\""; last; };
571                 return 1;       # OK
572                 }
573         warn "MAIL DROPPED for folder: $folder";
574         close F;
575         return 0;       # failed
576 }
577
578 sub process
579 {
580 my($message)=@_;
581
582         local $_=$_;
583         my $save_=$_;
584         local $Message=$message;
585         local $Audit=Mail::Audit->new(
586                         "emergency"=>"$Mail/emergency",
587                         "data"=>[map("$_\n",split("\n",$message))],
588                         );
589         local @AuditStored=();
590         do { smssend $opt_smstest; return; } if $opt_smstest;
591         write_message("$Mail/input");
592         audit();
593         warn 'Corrupted $_, repaired' if defined($save_)!=defined($_) || (defined($_) && $save_ ne $_);
594 }
595
596 # utility functions:
597
598 # return: true (error-message or "1") if is spam
599 sub razor2
600 {
601         # razor-check has exit code 1 if NOT spam, code 0 if IS spam
602         local *CHILD;
603         local $SIG{"PIPE"}=sub { warn "razor2 gave me SIGPIPE: broken pipe"; };
604         # prevent Razor2's: Can't call method "log" on unblessed reference at Razor2/Client/Agent.pm line 212.
605         local $ENV{"HOME"}=$HOME;
606         open CHILD,'|'
607                                         .'('.'(razor-check 2>&1;echo >&3 $?)'
608                                                         .'|sed "s/^/razor-check: /"'
609                                                         .'|logger -t "lacemail['.$$.']" -p mail.crit'
610                                                         .') 3>&1'
611                                         .'|exit `cat`'
612                         or return 0;
613         print CHILD $Message;
614         my $return;
615         {
616                 local $/=undef();
617                 $return=<CHILD> || 1;
618                 }
619         close CHILD;
620         return undef() if !WIFEXITED($?);
621         return undef() if  WIFSIGNALED($?);
622         return undef() if  WIFSTOPPED($?);
623         return undef() if WEXITSTATUS($?);
624         return $return; # is-spam
625 }
626
627 # NOTE: returns undef() if !wantarray and the first header is unrecognized
628 sub Received_for
629 {
630         my @r=();
631         for my $hdr ($Audit->head->get("Received")) {
632                 my($for)=($hdr=~/\bfor\s+\<?(\S+)\>?\b/);
633                 return $for if !wantarray();
634                 push @r,$for if $for;
635                 }
636         return @r;
637 }
638
639 our %muttrc_pending=();
640 sub muttrc
641 {
642 my($muttrc)=@_;
643
644         $muttrc||="$HOME/.muttrc";
645         $muttrc=~s/^\~/$HOME/;
646         do { warn "Looping muttrc, ignoring: $muttrc"; return (); } if $muttrc_pending{$muttrc};
647         local $muttrc_pending{$muttrc}=1;
648         local *MUTTRC;
649         open MUTTRC,$muttrc or do { warn "open \"$muttrc\": $!"; return (); };
650         local $/="\n";
651         local $_;
652         my @r=();
653         # far emulation mutt/init.c/mutt_parse_rc_line()
654         while (<MUTTRC>) {
655                 s/^[\s;]*//s;
656                 s/[#;].*$//s;
657                 s/\s*$//s;
658                 next if !/^(\S+)\s*/s;
659                 if ($1 eq "source") {
660                         $_=$';
661                         do { warn "Wrong 'source' parameters at $muttrc:$.: $_"; next; } if !/^\S+$/;
662                         push @r,muttrc($_);
663                         next;
664                         }
665                 push @r,$_;
666                 }
667         close MUTTRC or warn "close \"$muttrc\": $!";
668         return wantarray() ? @r : join("",map("$_\n",@r));
669 }
670
671 my %mutteval_charmap=(          # WARNING: Don't use "" or "0" here, see below for "|| warn"!
672                 '\\'=>"\\",
673                 'r'=>"\r",
674                 'n'=>"\n",
675                 't'=>"\t",
676                 'f'=>"\f",
677                 'e'=>"\e",
678                 );
679 # mutt/init.c/mutt_extract_token()
680 sub mutteval
681 {
682         local $_=$_[0];
683         return $_ if !s/^"//;
684         do { warn "Missing trailing quote in: $_"; return $_; } if !s/"$//;
685         s/\\(.)/$mutteval_charmap{$1} || warn "Undefined '\\$1' sequence in: $_";/ges;
686         return $_;
687 }
688
689 sub muttrc_get
690 {
691 my(@headers)=@_;
692
693         my @r=map({ (ref $_ ? $_ : qr/^\s*set\s+\Q$_\E\s*=\s*(.*?)\s*$/si); } @headers);
694         my %r=map(($_=>undef()),@r);
695         for (muttrc()) {
696                 for my $ritem (@r) {
697                         /$ritem/si or next;
698                         $r{$ritem}=mutteval $1;
699                         }
700                 }
701         for my $var (grep { !defined($r{$_}) } @r) {
702                 warn "Variable '$var' not found in muttrc";
703                 return undef();
704                 }
705         return wantarray() ? %r : $r{$r[0]};
706 }
707
708 sub muttrc_aliases
709 {
710         my %r=();
711         for (muttrc()) {
712                 next if !(my $key=(/^alias\s+(\S+)\s+/)[0]);
713                 for my $addrobj (Mail::Address->parse($')) {
714                         my $addr=$addrobj->address();
715                         my $ref=\$r{"\L$addr"};
716                         $$ref=$key if !$$ref;
717                         }
718                 }
719         return %r;
720 }
721
722 # FIXME: host may get multiple recipients and thus not showing "for <...>"
723 # FIXME: muttrc_get("from") is too strict
724 sub store_muttrc_alternates
725 {
726 my($prefix,$profile)=@_;
727
728         my $alternates=muttrc_get("alternates") or return;
729         my $alternatesre=qr/$alternates/si;
730         my $From=muttrc_get("from") or return;
731         my $Fromre=qr/^\Q$From\E$/si;
732         warn "'From' \"$From\" not matches by 'alternates': $alternatesre"
733                         if $From!~/$alternates/si;
734         for my $for (reverse Received_for()) {
735                 return if $for=~/$From/si;
736                 next if $for!~/$alternatesre/si;
737                 store "$prefix\L$for",($profile || []);
738                 return;
739                 }
740 }
741
742 # $header: ref CODE
743 # $header: !ref => $Audit->get($header)
744 # $maybeaddress: qr/regex/i
745 # $maybeaddress: "string"
746 # $maybeaddress: "<Regexp:regex>"       # hack :-(
747 # $maybeaddress: "<user@host>"
748 # $maybeaddress: "<user@>"
749 # $maybeaddress: "<@host>"
750 sub _headercore
751 {
752 my($re,$justone,$header,$maybeaddress)=@_;
753
754         if (ref $header) {
755                 $header=join(",",&$header());
756                 }
757         else {
758                 $header=$Audit->get($header);
759                 }
760         return 0 if !$header;
761         return $header=~/$maybeaddress/i if "Regexp" eq ref $maybeaddress;
762         return $header=~/$re/i if !defined(my $want=($maybeaddress=~/^\<(.*)\>$/)[0]);
763         my @parsed=Mail::Address->parse($header);
764         warn "'mailto:' forbidden in pattern: $want" if $want=~/^\Qmailto:\E/;
765         return 0 if $justone && 1!=@parsed;
766         return grep {
767                            if ($want=~/^Regexp:/)
768                                 { $_->address()=~/$'/i; }
769                         elsif ($want=~/\@$/)
770                                 { $_->user()   =~/^(?:\Qmailto:\E)?\Q$`\E/i; }
771                         elsif ($want=~/^\@/)
772                                 { $_->host()   =~/^\Q$'\E/i; }
773                         else
774                                 { $_->address()=~/^(?:\Qmailto:\E)?\Q$want\E/i; }
775                         } @parsed;
776 }
777
778 sub headerhas
779 {
780 my($header,$substr)=@_;
781
782         return _headercore(qr/\Q$substr\E/i,0,$header,$substr);
783 }
784
785 sub headeris
786 {
787 my($header,$string)=@_;
788
789         return _headercore(qr/\Q$string\E/i,1,$header,$string);
790 }
791
792 # $header,%$map
793 sub header_remap
794 {
795 my($header,$map)=@_;
796
797         my $text=$Audit->get($header);
798         my $orig=$text;
799         while (my($from,$to)=each(%$map)) {
800                 $text=~s/\b\Q$from\E\b/$to/gsi;
801                 }
802         return if $text eq $orig;
803         $Audit->put_header("X-LaceMail-header_remap-$header",$orig);
804         $Audit->replace_header($header,$text);
805 }
806
807
808 # MAIN
809
810 my $basedir=File::Basename::dirname($0);
811 $Getopt::Long::ignorecase=0;
812 die "GetOptions error" if !Getopt::Long::GetOptions(
813                   "inetd"    ,sub { $opt_mode=\&inetd; },
814                   "stdin"    ,sub { $opt_mode=\&stdin; },
815                   "smstest:s",sub { $opt_mode=\&stdin; $opt_smstest=($_[1] || 1); },
816                   "idle!"    ,\$opt_idle,
817                   "idletest" ,sub { syslogging_restore(); print((defined($_=useridle()) ? $_ : "<undef>")."\n"); exit 0; },
818                   "muttrc"   ,sub { syslogging_restore(); print scalar muttrc(); exit 0; },
819                 "d|basedir=s",\&basedir,
820                 );
821 # "Excessive arguments" checked in &inetd
822 die "Missing mode" if !$opt_mode;
823
824 my $filenameMyAudit="$basedir/My-Audit.pm";
825 open AUDIT,$filenameMyAudit or die "open \"$filenameMyAudit\": $!";
826 {
827         local $/=undef();
828         eval <AUDIT> or die "eval \"$filenameMyAudit\": $@";
829         audit_init();
830         }
831 close AUDIT or warn "close \"$filenameMyAudit\": $!";
832
833 &$opt_mode();
834 die "NOTREACHED";