]> git.deb.at Git - pkg/t-prot.git/blob - t-prot
Merge branch 'upstream'
[pkg/t-prot.git] / t-prot
1 #!/usr/bin/perl -w
2 # $Id: t-prot,v 1.255 2007/09/19 11:32:58 jochen Exp $
3
4 require 5.006;
5 use strict;
6 use Fcntl qw(O_EXCL O_WRONLY O_CREAT);
7 use Getopt::Mixed qw(nextOption);
8 use constant VER            => '2.5';
9 use constant REV            => '';
10 use constant REL            => q$Revision: 1.255 $=~m/(\d+(?:\.\d+)+)/;
11 # MTA expecting mail on STDIN
12 # (you might have to adjust this if using a different MTA)
13 use constant SENDMAIL       => '/usr/sbin/sendmail -oi';
14 # From <sysexits.h>
15 # (you might have to adjust those if your libc wants different values)
16 use constant EX_OK          =>  0;
17 use constant EX_USAGE       => 64;
18 use constant EX_DATAERR     => 65;
19 use constant EX_UNAVAILABLE => 69;
20 use constant EX_SOFTWARE    => 70;
21 use constant EX_IOERR       => 74;
22 use constant EX_BOUNCE      => EX_UNAVAILABLE;
23 use vars qw(
24     $ad $ads $bigqn $bigqx $boun $check $check_ratio $cr $diff $elli
25     $footers $ftr_ad $ftr_ml $hdrs $indent $kamm $kdiff $kminl $kmaxl
26     $lax $lsig $maxsig $maxlines $mda $ml $gw $ms $ms_smart $msg_quote
27     $msg_ratio $mua $nohdr $ofile $pgpshort $pgpmove $pgpmovevrf $sig
28     $sigint $sign $spass $spass_prefix $sysl $trad $trsp
29
30     $gpg_WARNING $gpg_Warning $gpg_Cantcheck $gpg_aka $gpg_bad
31     $gpg_expired $gpg_good $gpg_bug
32
33     $mutt_attachment $mutt_contenttype $mutt_pgpsigned $mutt_beginsigned
34     $mutt_pgpclearsigned $mutt_pgpclearsigstart $mutt_pgpencrypted
35     $mutt_pgpoutstart $mutt_pgpoutend
36 );
37
38
39 # Please adjust these vals to your needs (they are no constants because
40 # command line can change them or they are used in rexexp's):
41 $0 =~ s!^.*/!!;
42 $maxsig         = 4;      # max. valid signature length
43 $maxlines       = undef;  # no limit of message lines
44 $indent         = '>';    # Indent string, regexp to identify a quoted line
45 $kminl          = 65;     # see decomb() for details
46 $kmaxl          = 80;
47 $kdiff          = 20;
48 $pgpshort       = 0;      # hide pgp key ids if set
49 $pgpmove        = 0;      # move pgp output to bottom if set
50 $pgpmovevrf     = 0;
51 $sign           = 1;      # max number of sigs tolerated, undef for no limit
52 $boun           = "Blocked by $0: This user does not accept TOFUed email. Please see <http://learn.to/quote/> and <http://www.escape.de/users/tolot/mutt/> for more info. Have a nice day!\n";
53 $ftr_ad         = undef;  # too hard on performance to be default
54 $ftr_ml         = undef;  # too hard on performance to be default
55 $ofile          = '-';    # use STDOUT if nothing is specified
56 $spass_prefix   = 'SPAM: ';
57 $check_ratio    = .75;    # 3/4 tofu is enough not to accept the message
58 $msg_quote      = "Blocked by $0: This message has been rejected because of a full quote. Please see http://learn.to/quote/ and http://www.escape.de/users/tolot/mutt/ for more info. Have a nice day!\n";
59 $msg_ratio      = "Blocked by $0: This message has been rejected because of excessive quoting. Please see http://learn.to/quote/ and http://www.escape.de/users/tolot/mutt/ for more info. Have a nice day!\n";
60 # end of user adjusted vals
61
62
63 # set the defaults to the C locale
64 $mutt_attachment        = '[-- Attachment #';
65 $mutt_contenttype       = '[-- Type: ';
66 $mutt_pgpsigned         = '[-- End of signed data --]';
67 $mutt_beginsigned       = '[-- The following data is signed --]';
68 $mutt_pgpclearsigstart  = '[-- BEGIN PGP SIGNED MESSAGE --]';
69 $mutt_pgpclearsigned    = '[-- END PGP SIGNED MESSAGE --]';
70 $mutt_pgpencrypted      = '[-- End of PGP/MIME encrypted data --]';
71 $mutt_pgpoutstart       = '[-- PGP output follows (current time:';
72 $mutt_pgpoutend         = '[-- End of PGP output --]';
73
74 # set the defaults to the C locale
75 $gpg_WARNING            = 'WARNING: ';
76 # (yes, the translations in gnupg's po files *are* braindamaged):
77 $gpg_Warning            = 'WARNING: ';
78 $gpg_Cantcheck          = 'Can\'t check signature: ';
79 $gpg_aka                = '                aka ';
80 $gpg_bad                = 'BAD signature from ';
81 $gpg_expired            = 'Note: This key has expired!';
82 $gpg_good               = 'Good signature from';
83 # (actually, this bugs me quite often since upgrading gpg from v1.0.7):
84 $gpg_bug                = '... this is a bug (';
85
86
87 # help(): print help text and exit with appropriate exit code
88 sub help {
89     print "Usage: $0 [options] 
90   -A=DIRECTORY    ad footer directory, treat ad footers as signature
91   -a              remove ad footers; requires -A
92   --bigq[=n[,x]]  remove all but x lines of quotes with more than n
93                   lines; default is n=30 and x=10
94   --body          input has no headers; does not work with --pgp-short;
95                   multipart messages will not be detected
96   -c              merge multiple blank lines
97   --check[=FLAGS] check various criteria, print error message and quit;
98                   see man page for details
99   -d, --debug     print notice to syslog when bouncing; requires -p
100   --diff          tolerate diffs appended *after* the signature
101   -e              force ellipsis for excessive punctuation
102   --ftr-ad        enable aggressive ad footer matching; requires -A
103   --ftr-ml        enable aggressive mailing list footer matching; req. -L
104   --groupwise     delete Novell Groupwise style TOFU
105   -h, --help      show this short help and exit
106   -i=INFILE       file to be read; '-' for STDIN (default)
107   -k              try to fix \"Kammquotes\"
108   --kminl=n       min. line length for wrapped line; requires -k
109   --kmaxl=n       max. line length for wrapped line; requires -k
110   --kdiff=n       max. length difference between wrapped lines; req. -k
111   -L=DIRECTORY    mailling list footer directory, treat mailing list
112                   footers as signature
113   -l              delete mailing list footer; requires -L
114   --lax-security  use unsafe writing method; USE ON YOUR OWN RISK!
115   --locale=LOCALE internationalization; currently only used with -Mmutt
116   -M, --mua=MUA   turn on special treatment for some mail user agents
117   -m              delete MS style TOFU; careful: might be too agressive
118   --max-lines=x   maximum number of message lines
119   --ms-smart      try to be smart with MS style TOFU; req. -Mmutt and -m
120   -o=OUTFILE      file to be written to; '-' for STDOUT (default), 'NONE'
121                   for no output at all
122   -P=MESSAGE      user defined bounce message; requires -p
123   -p[=ADDRESS]    redirect to ADDRESS if no TOFU was found
124   --pgp-move      move pgp verification output to bottom; requires -Mmutt
125   --pgp-move-vrf  move pgp output if verified and good; requires -Mmutt
126   --pgp-short     hide non-relevant pgp key uids; requires -Mmutt
127   -r              delete mail header lines
128   -S[=n]          supress signatures with more than n lines; 
129                   default is $maxsig if n not specified
130   -s              delete signature
131   --sigsmax[=n]   max number of sigs tolerated, no value for unlimited
132   --spass         enable SpamAssassin workaround
133   -t              delete traditional style TOFU
134   -v, --version   show version string and exit
135   -w              delete trailing whitespaces\n";
136     exit(EX_USAGE);
137 }
138
139 # version(): print version info and exit with appropriate exit code
140 sub version {
141     print "$0 v".VER.REV." (Rev. ".REL."), Jochen Striepe <t-prot\@tolot.escape.de>
142 Get the latest version at <http://www.escape.de/users/tolot/mutt/>\n";
143     exit(EX_OK);
144 }
145
146 # sigint_handler(): what to do if we receive a single SIGINT
147 sub sigint_handler {
148     $sigint = 1;
149 }
150
151 # remove_footers(): remove any trailing appearance of footers contained
152 # in the given directory.
153 sub remove_footers {
154     my $L = shift;        # array of message lines
155     my $S = shift;        # array to store removed lines in
156     my $F = shift;        # footers dir name
157     my $O = shift;        # remove only one footer?
158     my $V = shift;        # allow footers match before end of message
159     my $off;
160
161     if (!defined $V) {
162         for ($off = 0; $#$L>=$off && $$L[$#$L-$off] =~ /^\s*$/; $off++) {;};
163     }
164
165     if ($F && scalar(@$L)) {
166         if (!opendir(DIR, $F))
167             { print STDERR "Could not open $F: $!\n"; exit(EX_IOERR); }
168         my @feet = grep { /^[^.]/ && -f "$F/$_" } readdir DIR;
169         closedir DIR;
170
171         foreach my $f (@feet) {
172             if (!open(IN, "$F/$f"))
173                 { print STDERR "Could not open $F/$f: $!\n"; exit(EX_IOERR); }
174             my @l = <IN>;
175             close IN;
176
177             if (!scalar(@l)) { next; }
178             for (my $z=0; $z<=$#l; $z++) { chomp($l[$z]); }
179
180             if (defined $V) {
181                 WIPE: for (my $z=scalar(@$L)-scalar(@l); $z>=0; $z--)
182                 {
183                     if (scalar(@l)+$z<=scalar(@$L)) {
184                         my $y = 0;
185                         for(my $x=1; $x<=scalar(@l); $x++) {
186                             if (index($$L[scalar(@$L)-$x-$z], $l[scalar(@l)-$x])!=0) {
187                                 $y = 1;
188                             }
189                         }
190                         if (!$y) {
191                             unshift(@$S, @$L[$#$L-$#l-$z..$#$L]);
192                             splice(@$L, $#$L-$#l-$z);
193                             while (scalar(@$L) && $$L[$#$L] =~ /^\s*$/) {
194                                 unshift(@$S, pop(@$L));
195                             }
196                             if ($O) { last; } else { goto WIPE; }
197                         }
198                     }
199                 }
200             }
201             else {
202                 while (scalar(@l)<=scalar(@$L)) {
203                     for(my $x=1; $x<=scalar(@l); $x++) {
204                         if (index($$L[scalar(@$L)-$x-$off], $l[scalar(@l)-$x])!=0) { 
205                             goto FINISH;
206                         }
207                     }
208                     unshift(@$S, @$L[$#$L-$off-$#l..$#$L]);
209                     splice(@$L, $#$L-$off-$#l);
210                     while (scalar(@$L) && $$L[$#$L] =~ /^\s*$/) {
211                         unshift(@$S, pop(@$L));
212                     }
213                     if ($O) { last; }
214                 }
215                 FINISH:
216             }
217         }
218     }
219 }
220
221 # decomb(): Try to detect and fix zig-zag shaped quoting (a.k.a. German
222 # "Kammquoting").
223 sub decomb {
224     my $L = shift;        # array of message lines
225     my $V = shift;        # array with verbatim list
226     my $max = 0;        # plausible wraparound pos
227
228     # We scan the whole message first for a plausible common maximum line
229     # length where longer lines would be wrapped.
230     for (my $x=0; $x<$#$L; $x++) {
231         if ($$V[$x]!=1 && $max<length($$L[$x])) { $max = length($$L[$x]); }
232     }
233
234     # Next we see if there are plausible wraparounds.    
235     for (my $x=0; $x+1<$#$L; $x++) {
236
237         # OK, 
238         # * it must not be verbatim,
239         # * the 2nd line must not be quoted nor empty nor just 
240         #   underlining some part of the line above (using '^')
241         #   nor begin with a whitespace,
242         # * the 1st line must not end with a hyphen,
243         # * the 2nd line must not indicate content was deleted,
244         # * the 2nd line must not be some mutt(1) commentary,
245         # * there must not be a valid word wrap to produce a longer
246         #   1st line (if not quoted),
247         # * the 1st and 2nd line together must not be longer than some
248         #   magical upper limit nor shorter than some magical lower
249         #   bound nor nearly of the same length, and
250         # * the 3rd line must not be empty.
251         # With all that odds should be quite good that we have an
252         # automatedly wrapped line. Please send a note if you have
253         # additional good criteria. Thanks.
254         if (($$V[$x]!=1 && $$V[$x+1]!=1) &&
255             (index($$L[$x+1], $indent)!=0) &&
256             ($$L[$x+1] !~ /^$/) &&
257             ($$L[$x+1] !~ /^[\s^]/) &&
258             ($$L[$x] !~ /-$/) &&
259             ($$L[$x+1] !~ /^\Q[...]\E\s*$/) &&
260             ($mua ne 'mutt' || $$L[$x+1] !~ /^(?:\e[^\a]+\a)?\[-- /) &&
261             (length($$L[$x])+index($$L[$x+1], ' ')>$max ||
262                 (index($$L[$x+1], ' ')<0 && length($$L[$x])+length($$L[$x+1])>$max)) &&
263             (length($$L[$x])+length($$L[$x+1])<$kmaxl) &&
264             (length($$L[$x])+length($$L[$x+1])>$kminl) &&
265             (length($$L[$x])-length($$L[$x+1])>$kdiff) &&
266             ($$L[$x+2] !~ /^\s*$/))
267         {
268             $$L[$x] =~ s/\s*$/' ' . $$L[$x+1]/e;
269             splice(@$L, $x+1, 1);
270             splice(@$V, $x+1, 1);
271         }
272     }
273 }
274
275 # debigq(): Finds big quotes (more than $n lines quoted) and deletes all
276 # but $x lines of them.
277 sub debigq {
278     my $L = shift;        # array of message lines
279     my $V = shift;        # array with verbatim list
280     my $k = 0;
281
282     for (my $i=0; $i<=$#$L; $i++) {
283
284         if ($$V[$i]) { 
285             $k = 0;
286             next;
287         }
288
289         if (index($$L[$i], $indent)==0) { $k++; } else { 
290             if ($k>$bigqn) {
291                 my $x = $k-$bigqx;
292                 $i -= $k;
293
294                 $$L[$i] = "[---=| Quote block shrinked by $0: " .
295                     "$x lines snipped |=---]\n";
296                 $i++;
297                 splice(@$L, $i, $x-1);
298                 splice(@$V, $i, $x-1);
299
300                 $i++;
301             }
302             $k = 0;
303         }
304     }
305 }
306
307 # pgp(): treat mutt(1)'s pgp/gpg output contained in signed or encrypted
308 # messages
309 sub pgp {
310
311     sub verified {
312         my $L = shift;    # message body
313         my $X = shift;    # start line
314         my $Z = shift;    # end line
315
316                 my $ok = 0;
317
318         while ($X<$Z) {
319             if (index($$L[$X], "gpg: $gpg_WARNING")==0 ||
320                 index($$L[$X], "gpg: $gpg_Warning")==0 ||
321                 index($$L[$X], "gpg: $gpg_bad")==0 ||
322                 index($$L[$X], "gpg: $gpg_Cantcheck")==0 ||
323                 index($$L[$X], "gpg: $gpg_expired")==0 ||
324                 index($$L[$X], "gpg: $gpg_bug")==0)
325                 { return 0; }
326             if (index($$L[$X], "gpg: $gpg_good")==0)
327                 { $ok = 1; }
328             $X++;
329         }
330
331         return $ok;
332     }
333
334     my $L = shift;        # message body
335     my $V = shift;        # verbatim list
336     my $H = shift;        # headers
337
338     my @tmp = ();
339     my $tmp = 0;
340
341     for (my $x=0; $x<scalar(@$L); $x++) {
342         if ($$V[$x]) { next; }
343
344         if ($$L[$x]=~/^(?:\e[^\a]+\a)?(?:\Q$mutt_pgpoutstart\E)/o)
345         {
346             my $from;
347             for (my $m=0; $m<scalar(@$H); $m++) {
348                 if (index($$H[$m], 'From:')==0) {
349                     $from = $$H[$m];
350                     $m++;
351                     while (exists($$H[$m]) && $$H[$m] =~ /^\s/)
352                         { $from .= $$H[$m]; $m++; }
353                     last;
354                 }
355             }
356             ($from) = $from=~m/(\w[\w.+-]*@(?:[\w.+-]+\.)+[A-Za-z]{2,})/;
357
358             my $uid = 1;
359
360             for (my $i=$x+1; $i<scalar(@$L); $i++) {
361                 if ($pgpshort && index($$L[$i], "gpg: $gpg_aka")==0)
362                     { $uid++; }
363
364                 if ($pgpshort && $uid>1 &&
365                     index($$L[$i], "gpg: $gpg_aka")==0 &&
366                     index($$L[$i], $from)<0)
367                 { 
368                     splice(@$L, $i, 1);
369                     splice(@$V, $i, 1);
370                     $i--;
371                 }
372                 elsif ($$L[$i]=~/^(?:\e[^\a]+\a)?(?:\Q$mutt_pgpoutend\E)/o)
373                 {
374                     if ($pgpmove ||
375                         ($pgpmovevrf && (!$sigint) && verified($L, $x+1, $i)))
376                     {
377                         push(@{$tmp[++$tmp]}, "\n", @$L[$x..($i+1)]);
378                         splice(@$L, $x, $i-$x+2);
379                         splice(@$V, $x, $i-$x+2);
380                         $i -= $#{$tmp[$tmp]}-2;
381                     }
382                     $x = $i;
383                     last;
384                 }
385             }
386         }
387         elsif ($tmp &&
388             $$L[$x] =~ /^
389                         (?:\e[^\a]+\a)?
390                         (?:\Q$mutt_pgpencrypted\E  |
391                            \Q$mutt_pgpclearsigned\E|
392                            \Q$mutt_pgpsigned\E)
393                        /ox)
394         {
395             splice(@$L, $x+1, 0, @{$tmp[$tmp]});
396             for (my $i=$x; $i<scalar(@{$tmp[$tmp]}); $i++) {
397                 splice(@$V, $x+1, 0, (0));
398             }
399             $x += scalar(@{$tmp[$tmp--]});
400             pop(@tmp);
401         }
402     }
403
404     while ($tmp>0) {
405         push(@$L, @{$tmp[$tmp--]});
406         pop(@tmp);
407         for (my $i=$#$V; $i<$#$L; $i++) { push(@$V, 0); }
408     }
409 }
410
411 # write_msg(): output
412 sub write_msg {
413     my $O = shift;
414     my $l;
415
416     if ((!$lax) && ($O =~ /^>(.*)/) && ($1 ne '-')) {
417         if (!sysopen(OUT, $1, O_EXCL|O_CREAT|O_WRONLY)) { 
418             print STDERR "Could not open $1: $!\n"; exit(EX_IOERR);
419         }
420     }
421     elsif (!open(OUT, $O)) { 
422         print STDERR "Could not open $O: $!\n"; exit(EX_IOERR);
423     }
424     while (scalar(@_)) {
425         $l = shift;
426         if (defined $l) {
427             $^W = 0;
428             print OUT @$l;
429             $^W = 1;
430         }
431     }
432     close OUT;
433 }
434
435 # process_msg(): This one proc does *everything* what has to be done with
436 # the lines of the message
437 sub process_msg {
438     my $lines = shift;
439
440     my ($j, $x, $verb) = (0, 0, 0);
441     my (@ads, @hdr, @bo1, @bo2, @ftr, @sig, @vrb, @att) = 
442         ((), (), (), (), (), (), (), (), ());
443
444     # First, remove and store lines we might need later...
445     # Remove headers:
446     if (!$nohdr) {
447         for ($x=0; $x<$#$lines; $x++) { if (@$lines[$x] =~ /^$/) { last; }; }
448
449         # check body length and stop processing silently if msg is too long:
450         if ((defined $maxlines) && (@$lines-$x > $maxlines)) {
451             return;
452         }
453
454         @hdr = @$lines[0..$x];
455         splice(@$lines, 0, $x+1);
456     }
457     elsif ((defined $maxlines) && (@$lines > $maxlines)) {
458         # check body length and stop processing silently if msg is too long:
459         return;
460     }
461     # remember the original body lines count
462     my $linecount = scalar(@$lines);
463
464     # Remove ML footers:
465     remove_footers($lines, \@ftr, $footers, undef, $ftr_ml);
466
467     # Remove ad footers:
468     remove_footers($lines, \@ads, $ads, undef, $ftr_ad);
469
470     # See if we have a multipart content type. If yes, see if it is already
471     # ripped (e.g. by you MUA, assuming it does not get special treatment with
472     # --mua=foo), otherwise only leave the first part if it is plain text (if
473     # not, we are done - non-text messages are not our business).
474     if ($mua ne 'mutt') { 
475         for ($x=0; $x<scalar(@hdr); $x++) {
476             if ($hdr[$x] =~ /^Content-[Tt]ype:\s+(.*)$/) {
477                 my $foo = $1;
478
479                 if ($foo =~ m!^multipart/!) {
480                     undef $foo;
481
482                     if ($hdr[$x] =~ /\Wboundary="([^"]+)"/i) { $foo = $1; }
483                     else { 
484                         for (my $z=1; $x+$z<@hdr && $hdr[$x+$z]=~/^\s/; $z++) {
485                             if ($hdr[$x] =~ /\Wboundary="?([^"\s]+)"?$/i) { 
486                                 $foo = $1;
487                                 last;
488                             }
489                         }
490                     }
491
492                     if (defined $foo) {
493                         for (my $x=0; $x<scalar(@$lines); $x++) {
494                             if (index($$lines[$x], '--'.$foo)!=0) { next; }
495
496                             my $bar = 'text/plain';
497                             for ($x++; $x<@$lines && $$lines[$x]!~/^$/; $x++)
498                             {
499                                 if ($$lines[$x] =~ /^Content-[Tt]ype:\s+(.*)/) { 
500                                     $bar = $1;
501                                 }
502                             }
503                             if ($x>=scalar(@$lines)) { exit(EX_DATAERR); }
504
505                             if ($bar =~ m!^text/plain!) {
506                                 my $z;
507                                 for ($z=1; $x+$z<@$lines; $z++) {
508                                     if (index($$lines[$x+$z], '--'.$foo)==0) {
509                                         last;
510                                     }
511                                 }
512                                 if ($x+$z>=scalar(@$lines)) { exit(EX_DATAERR); }
513
514                                 @bo2 = @$lines[$x+$z..$#$lines];
515                                 splice(@$lines, $x+$z);
516                                 if ($$lines[$#$lines] =~ /^\s*$/) {
517                                     unshift(@bo2, pop @$lines);
518                                 }
519                                 @bo1 = @$lines[0..$x];
520                                 splice(@$lines, 0, $x+1);
521
522                                 # remove mailing list and ad footers within this
523                                 # attachment:
524                                 remove_footers($lines, \@ftr, $footers, undef, $ftr_ml);
525                                 remove_footers($lines, \@ads, $ads, undef, $ftr_ad);
526
527                                 last;
528                             }
529                             else { 
530                                 write_msg(($mda?'|'.SENDMAIL." $mda":">$ofile"),
531                                     ($hdrs?undef:\@hdr), $lines);
532                                 exit;
533                             }
534                         }
535                     }
536                 }
537                 last;
538             }
539         } 
540     }
541
542
543     # Protect verbatims:
544     $verb = 0;
545     for ($x=0; $x<scalar(@$lines); $x++) {
546         if ($$lines[$x] =~ /^\s*#v([+-])$/) { 
547             $verb = $1 eq '+' ? 1 : 0;
548             $vrb[$x] = 1;
549         } else { $vrb[$x] = $verb; }
550     }
551
552     # Calculate quoting ratio (with respect to verbatims):
553     if ($check && scalar(@$lines)) {
554         my ($y, $z) = (0, 0);
555         for ($x=0; $x<scalar(@$lines); $x++) {
556             if (!$vrb[$x]) {
557                 $z++;
558                 if (index($$lines[$x], $indent)==0) { $y++; }
559             }
560         }
561         $y = $y/$z;
562
563         if ($y>=$check_ratio) {
564             print $msg_ratio;
565             exit EX_UNAVAILABLE;
566         }
567     }
568
569     if ($mua eq 'mutt') {
570         # See if we find pgp output generated by mutt before we scramble
571         # the thing. If yes, see if we can beautify it.
572         if ($pgpshort || $pgpmove || $pgpmovevrf) { pgp($lines, \@vrb, \@hdr); }
573
574         # Remove all but the first attachment (if this is text/plain)
575         # mutt did introduce (bah!). Remember, all this ugliness could
576         # be replaced with a proper and clean edit_filter patch in 
577         # mutt(1) itself...
578         for ($x=$#$lines; $x>=0; $x--) {
579             if ($vrb[$x]) { next; }
580             # The following regexp's are quite ugly because for most users
581             # these lines are coloured using termcap... (bah!)
582             if (($$lines[$x] =~
583                      /^(?:\e[^\a]+\a)?\Q$mutt_attachment\E(\d+)/o &&
584                     (($1 ne '1') ||
585                     ($x<$#$lines &&
586                         $$lines[$x+1] !~ m!^
587                             (?:\e[^\a]+\a)?
588                             (?:\Q$mutt_contenttype\E)
589                             (?:text/plain|application/pgp)
590                         !ox))) ||
591                 ($$lines[$x] =~ /^
592                     (?:\e[^\a]+\a)?
593                     (?:\Q$mutt_pgpsigned\E     |
594                        \Q$mutt_pgpclearsigned\E|
595                        \Q$mutt_pgpencrypted\E)
596                 /ox))
597             { 
598                 # Strip attachments to prepare further processing
599                 unshift(@att, @$lines[$x..$#$lines]);
600                 splice(@$lines, $x);
601                 # Try to fix trailing empty lines
602                 while (scalar(@$lines) && $$lines[$#$lines] =~
603                     /^(?:\e[^\a]+\a)?\s*$/) { 
604                     unshift(@att, pop(@$lines));
605                 }
606
607                 # Remove ML and ad footers within attachments:
608                 my @tmp;
609                 if ($ml) { remove_footers($lines, \@tmp, $footers, undef); }
610                 if ($ad) { remove_footers($lines, \@tmp, $ads,     undef); }
611                 $x = scalar(@$lines);
612             }
613         }
614
615         # care about the rest
616         if (scalar(@att)) {
617             for ($x=0; $x<$#att; $x++) {
618                 if ($vrb[scalar(@$lines)+$x]) { next; }
619
620                 # Pipe message/rfc822 parts to another instance of
621                 # process_msg() for further processing.
622                 # Please note that we cannot see what a hierarchy the
623                 # original message had -- if there were message/rfc822
624                 # parts within other message/rfc822 parts constellations
625                 # can occur which we cannot resolve. Therefore we simply
626                 # do not even try to be smart. This should work for most
627                 # situations.
628                 # The following regexp is quite ugly because for most
629                 # users the line is coloured using termcap... (bah!)
630                 if ($att[$x] =~
631                         /^(?:\e[^\a]+\a)?\Q$mutt_attachment\E\d+/o &&
632                     $att[$x+1] =~ m!^
633                         (?:\e[^\a]+\a)?
634                         (?:\Q$mutt_contenttype\E) (?:message/rfc822|multipart/alternative)
635                     !ox)
636                 {
637                     $x += 2;
638                     while ($att[$x] !~ /^\s*$/) { $x++; }
639                     $x++;
640
641                     my @tmp = @att[$x..$#att];
642                     process_msg(\@tmp);
643                     splice(@att, $x, scalar(@att)-$x, @tmp);
644                     $x += scalar(@tmp);
645                 }
646             }
647         }
648     }
649
650     # Remove signature:
651     if (scalar(@$lines)) { 
652         my $sn = 0;
653         my $chk_empty = 1;
654         my $empty = 0;
655
656         for ($x = $#$lines; $x>=0; $x--) {
657             if (!$vrb[$x]) {
658                 if ($$lines[$x] =~ /^-- $/) {
659                     if ($diff) {
660                         for (my $i=1; $x+$i+1<scalar(@$lines); $i++) {
661                             if ($$lines[$x+$i] =~ /^-{3}\s+\S/ &&
662                                 $$lines[$x+$i+1] =~ /^\+{3}\s+\S/)
663                             {
664                                 $sig = 0;
665                                 unshift(@sig, @$lines[$x..$#$lines]);
666                                 splice(@$lines, $x);
667                                 last;
668                             }
669                         }
670                         if (scalar(@sig)) {
671                             if (defined($sign) && ++$sn==$sign) { last; } else { next; }
672                         }
673                     }
674
675                     if ($sig || ($lsig && ($#$lines-$x-$empty>$lsig))) {
676                         if ($lsig && !$sig) {
677                             unshift(@sig, "[---=| Overlong signature removed by $0: " .
678                                 (scalar(@$lines)-$x) . " lines snipped |=---]\n");
679                         }
680                         splice(@$lines, $x);
681                     }
682                     else {
683                         unshift(@sig, @$lines[$x..$#$lines]);
684                         splice(@$lines, $x);
685                     }
686                     if (defined($sign) && ++$sn==$sign) { last; } else { next; }
687                 }
688                 # any trailing newlines?
689                 elsif ($chk_empty && $$lines[$x] =~ /^\s*$/) { $empty++; }
690                 elsif ($chk_empty) { $chk_empty = 0; }
691             }
692         }
693     }
694
695     # See if there is some Kammquoting to fix:
696     if ($kamm) { decomb($lines, \@vrb); }
697
698     # Now care about TOFU.
699     # One common mispractice is M$ and Groupwise style TOFU:
700     if ($ms||$gw) {
701         # bloat this array if you want more internationalization:
702         my @tofu = ('Original Message',
703                     'Original-Nachricht',
704                     'Ursprüngliche Nachricht',
705                     'Ursprungliche Nachricht',
706                     'Mensagem original',
707                     'Ursprungligt meddelande',
708                     'Oorspronkelijk bericht',
709                     'Message d\'origine',
710                     'Forwarded message',
711                     'Weitergeleitete Nachricht / Forwarded Message');
712         my $k = 0;    # any text above?
713         my $tmp = 0;  # flagged if inside PGP output
714
715         DONE: for ($x=0; $x<scalar(@$lines); $x++) { 
716             if (!$vrb[$x]) {
717                 foreach my $tmp (@tofu) {
718                     if (($ms && $$lines[$x] =~ /^-+\s?$tmp\s?-+/) ||
719                         ($gw &&
720                             ($$lines[$x] =~ /^>>>[^\<]+<[^\>]+> \d\d?\/\d\d?\/\d\d? \d\d?:\d\d [AP]M >>>/ ||
721                              $$lines[$x] =~ /^>>> On [A-Z][a-z][a-z]?, [A-Z][a-z][a-z]? \d\d?, \d\d\d\d at [ \d]\d:\d\d [AP]M, in message/))) { 
722                         $x++;
723                         $trad = 0;
724                         $bigqn = 0;
725                         last DONE; 
726                     }
727                 }
728
729                 if ((!$k) && $$lines[$x] !~ /^\s*$/o &&
730                     ((!$mua) ||
731                      ($mua eq 'mutt' &&
732                          $$lines[$x] !~
733                              /^(?:\e[^\a]+\a)?(?:\Q$mutt_attachment\E)/o &&
734                          $$lines[$x] !~
735                              /^(?:\e[^\a]+\a)?(?:\Q$mutt_contenttype\E)/o)) &&
736                     ((!$spass) || index($$lines[$x], $spass_prefix)!=0))
737                 {
738                     if ($mua eq 'mutt' && (!$tmp) &&
739                         $$lines[$x] =~
740                              /^(?:\e[^\a]+\a)?(?:\Q$mutt_pgpoutstart\E)/o) {
741                         $tmp = 1; 
742                     } elsif ($mua eq 'mutt' && $tmp && 
743                         ($$lines[$x] =~
744                              /^(?:\e[^\a]+\a)?(?:\Q$mutt_beginsigned\E)/o ||
745                          $$lines[$x] =~
746                              /^(?:\e[^\a]+\a)?(?:\Q$mutt_pgpclearsigstart\E)/o)) {
747                         $tmp = 0;
748                     } elsif (!$tmp) {
749                         $k = 1;
750                     }
751                 }
752             }
753         }
754
755         # try to avoid false positives and only delete m$ style tofu if
756         # there is text above
757         if ($k) {
758             if (!$ms_smart) { goto CLEAN; }
759
760             # first, see if there is pgp stuff inside the tofu:
761             my $p = 0;    # levels of pgp signed parts
762
763             for (my $i=$x+1; $i<scalar(@$lines); $i++) {
764                 if ($$lines[$i] =~
765                         /^(?:\e[^\a]+\a)?(?:\Q$mutt_pgpclearsigstart\E)/o) {
766                     $p++;
767                 }
768             }
769             if ($p) {
770                 STAIRS: for (my $i=0; $i<scalar(@att); $i++) {
771                     if ($p==0 && $att[$i] =~ /^(?:\e[^\a]+\a)?\[-- /o) {
772                         splice(@att, 0, $i);
773                         unshift(@att, "\n");
774                         goto CLEAN;
775                     } elsif ($att[$i] =~
776                             /^(?:\e[^\a]+\a)?(?:\Q$mutt_pgpclearsigned\E)/o) {
777                         splice(@att, 0, $i+1);
778                         $p--;
779                         goto STAIRS;
780                     }
781                 }
782                 splice(@att);
783             }
784
785             # now removing is safe:
786             CLEAN: $j = scalar(@$lines)-$x;
787             splice(@$lines, $x);
788         }
789     }
790
791     # Nothing? Then try traditional TOFU (deleting M$ style TOFU is done
792     # much more aggressively, so we won't need to search any more if we
793     # did find some):
794     if ($trad && (!$j) && !$vrb[$#$lines]) {
795         if (scalar(@$lines) && $$lines[$#$lines] =~ /^\s*$/) { 
796             unshift(@sig, pop(@$lines));
797         }
798
799         my $k;
800         my $x = 1;
801
802         for (my $i=$#$lines; $i>=0; $i--) {
803             if ($$lines[$i] =~ /^$indent/o) {
804                 $j++;
805                 $k = $i;
806             }
807             elsif ($$lines[$i] !~ /^\s*$/) { last; }
808         }
809
810         if ($j) {
811             # if there is no text above, we will assume the message is meant
812             # as forwarding and therefore OK
813             for (my $i=$k-1; $i>=0; $i--) {
814                 if ($$lines[$i] !~ /^\s*$/o) {
815                    $x = 0;
816                    last;
817                 }
818             }
819             if ($x) {
820                 $j = 0;
821             } else {
822                 splice(@$lines, $k);
823             }
824         }
825     }
826
827     # OK, if we found TOFU, we will leave a message that we were here...
828     if ($j) { 
829         # make sendmail bounce if we shall be picky 
830         # and indeed found something:
831         if ($mda) { 
832             if ($mda ne '1') { 
833                 print STDERR $boun;
834
835                 if ($sysl) {
836                     eval { require Sys::Syslog; }; 
837                     if ($@) { warn $@; } else {
838                         Sys::Syslog::setlogsock('unix');
839                         Sys::Syslog::openlog("$0[$$]", 'pid', 'mail');
840                         Sys::Syslog::syslog('debug', 'bounced message %s', $hdr[0]);
841                         Sys::Syslog::closelog();
842                     }
843                 }
844             }
845
846             exit EX_BOUNCE;
847         }
848
849         # if we were invoked just for checking and indeed found something,
850         # print out the error message and quit:
851         if ($check) {
852             print $msg_quote;
853             exit EX_UNAVAILABLE;
854         }
855
856         push(@$lines, "[---=| TOFU protection by $0: " .
857             "$j lines snipped |=---]\n");
858     }
859     elsif ($mda eq '1') { exit EX_OK; }
860
861     # Care for huge blocks of quoted original message:
862     if ($bigqn) { debigq($lines, \@vrb); }
863
864     # Care for trailing whitespaces:
865     if ($trsp) {
866         for ($x=0; $x<scalar(@$lines); $x++) { 
867             if (!$vrb[$x]) { $$lines[$x] =~ s/[\ \t]+$//; }
868         }
869     }
870
871     # Care for punctuation abuse:
872     if ($elli) {
873         for ($x=0; $x<scalar(@$lines); $x++) { 
874             if (!$vrb[$x]) { $$lines[$x] =~ s/(([.?!])\2\2)\2+/$1/g; }
875         }
876     }
877
878     # (Nearly) at last care for multiple blank lines. (Do not do this
879     # earlier -- the way it is done right now would screw up the verbatim
880     # list)
881     if ($cr) {
882         my $t = 0;
883         for ($x=scalar(@$lines)-1; $x>=0; $x--) {
884             if ((!$vrb[$x]) && $$lines[$x] =~ /^\s*$/) { 
885                 if ($t<2) { $t++; } else { splice(@$lines, $x, 1); }
886             }
887             else { $t = 0; }
888         }
889     }
890
891     # Everything changing the body is done now. Time to fix the line count
892     # header so naive clients do not get confused. Just to be sure, append
893     # the old line count to X-headers.
894     my $l = scalar(@bo1) + scalar(@$lines) + scalar(@att) + scalar(@bo2) +
895                 (!$sig?scalar(@sig):0) + (!$ml?scalar(@ftr):0) + 
896                 (!$ad?scalar(@ads):0);
897     if ($linecount-$l!=0) {
898         for ($x=0; $x<scalar(@hdr); $x++) {
899             if ($hdr[$x] =~ 
900                 s/^(Lines:\s+)(\d+)/$1.($2-$linecount+$l)/e)
901             { 
902                 $hdr[$#hdr] = "X-Old-Lines: $2\n";
903                 push(@hdr, "\n");
904             }
905         }
906     }
907
908     # Finally, before leaving we put everything back in right order.
909     unshift(@$lines, (!$hdrs?@hdr:()), @bo1);
910     push(@$lines, (!$sig?@sig:()), (!$ad?@ads:()), (!$ml?@ftr:()), @att,
911         @bo2);
912 }
913
914
915 # environment
916 my $locale = $ENV{'LC_ALL'}?$ENV{'LC_ALL'}:
917                  ($ENV{'LC_MESSAGES'}?$ENV{'LC_MESSAGES'}:$ENV{'LANG'});
918
919 # command line switches
920 ($ad, $ads, $bigqn, $bigqx, $check, $cr, $sysl, $diff, $elli, $footers, $lax,
921     $ml, $gw, $ms, $ms_smart, $mda, $mua, $hdrs, $kamm, $lsig, $nohdr, $sig,
922     $sigint, $spass, $trad, $trsp) =
923     (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
924 my $ifile   = '-';    # use STDIN if nothing specified
925
926 # get command line params:
927 Getopt::Mixed::init('a A=s c d e h i=s k L=s l m M=s o=s P=s p:s r S:i'.
928     ' s t v w bigq:s body check:s debug>d diff ftr-ad ftr-ml groupwise'.
929     ' help>h kminl=i kmaxl=i kdiff=i lax-security locale=s max-lines=i'.
930     ' ms-smart mua>M pgp-short pgp-move pgp-move-vrf sigsmax:i spass'.
931     ' version>v');
932 while (my ($opt, $val, $pretty) = nextOption()) {
933     if    ($opt eq 'a')     { $ad = 1; }
934     elsif ($opt eq 'A')     { $ads = $val; }
935     elsif ($opt eq 'bigq')  { 
936         if ($val !~ /^(?:(\d+)(?:,(\d+))?)?$/) { help(); }
937         $bigqn = $1?$1:30; 
938         $bigqx = $2?$2:10;
939         if ($bigqn<=0 || $bigqx<=0 || $bigqn<=$bigqx) { help(); }
940     }
941     elsif ($opt eq 'body')  { $nohdr = 1; $hdrs = 1; }
942     elsif ($opt eq 'c')     { $cr = 1; }
943     elsif ($opt eq 'check') {
944         $check = 1;
945         while ($val && $val =~ s/^([^,\s]+)(?:,(\S+))?$/$2/) {
946             my $foo = $1;
947
948             if ($foo =~ /^ratio=(0?\.\d+)$/) {
949                 $check_ratio = $1?$1:1;
950             }
951         }
952     }
953     elsif ($opt eq 'd')     { $sysl = 1; }
954     elsif ($opt eq 'diff')  { $diff = 1; }
955     elsif ($opt eq 'e')     { $elli = 1; }
956     elsif ($opt eq 'ftr-ad') { $ftr_ad = 1; $ad = 1; }
957     elsif ($opt eq 'ftr-ml') { $ftr_ml = 1; $ml = 1; }
958     elsif ($opt eq 'groupwise') { $gw = 1; }
959     elsif ($opt eq 'i')     { $ifile = $val; }
960     elsif ($opt eq 'k')     { $kamm = 1; }
961     elsif ($opt eq 'kminl') { $kminl = $val; $kamm = 1; }
962     elsif ($opt eq 'kmaxl') { $kmaxl = $val; $kamm = 1; }
963     elsif ($opt eq 'kdiff') { $kdiff = $val; $kamm = 1; }
964     elsif ($opt eq 'L')     { $footers = $val; }
965     elsif ($opt eq 'l')     { $ml = 1; }
966     elsif ($opt eq 'lax-security') { $lax = 1; }
967     elsif ($opt eq 'locale') { $locale = $val; }
968     elsif ($opt eq 'm')     { $ms = 1; }
969     elsif ($opt eq 'max-lines') { $maxlines = $val; }
970     elsif ($opt eq 'ms-smart') { $ms_smart = 1; $ms = 1; }
971     elsif ($opt eq 'M') {
972         $mua = lc($val);
973
974         if ($mua eq 'mutt') {
975             # mutt still displays the message when ^C'ing pgp verification:
976             $SIG{'INT'} = 'sigint_handler';
977         }
978     }
979     elsif ($opt eq 'o')     { $ofile = $val; }
980     elsif ($opt eq 'P')     { $boun = $val; }
981     elsif ($opt eq 'p')     { $mda = $val ? $val : '1'; }
982     elsif ($opt eq 'pgp-short') { $pgpshort = 1; }
983     elsif ($opt eq 'pgp-move') { $pgpmove = 1; }
984     elsif ($opt eq 'pgp-move-vrf') { $pgpmovevrf = 1; }
985     elsif ($opt eq 'r')     { $hdrs = 1; }
986     elsif ($opt eq 'S')     { $lsig = $val ? $val : $maxsig; }
987     elsif ($opt eq 's')     { $sig = 1; }
988     elsif ($opt eq 'sigsmax') { $sign = $val ? $val : undef; }
989     elsif ($opt eq 'spass') { $spass = 1; }
990     elsif ($opt eq 't')     { $trad = 1; }
991     elsif ($opt eq 'v')     { version(); }
992     elsif ($opt eq 'w')     { $trsp = 1; }
993     else                    { help(); }
994 }
995 Getopt::Mixed::cleanup();
996 if (($ml && $footers eq '')||    # no -l without -L
997     ($ad && $ads eq '')||        # no -a without -A
998     ($nohdr && $pgpshort)||      # --body and --pgp-short are like oil and water
999     ($ifile eq '')||             # no empty -i
1000     ($ofile eq ''))              # no empty -o
1001 { help(); }
1002
1003
1004 if ($mua eq 'mutt') {
1005     if (defined $locale && $locale ne '' && $locale ne 'C' && $locale ne 'POSIX') {
1006         eval { require Locale::gettext; };
1007         if ($@) { warn $@; exit(EX_SOFTWARE); } else {
1008             Locale::gettext::textdomain('mutt');
1009             ($mutt_attachment) =
1010                 Locale::gettext::gettext("[-- Attachment #%d") =~
1011                 m/^([^%]*)/;
1012             ($mutt_contenttype) =
1013                 Locale::gettext::gettext("[-- Type: %s/%s, Encoding: %s, Size: %s --]\n") =~
1014                 m/^([^%]*)/;
1015             ($mutt_pgpsigned) =
1016                 Locale::gettext::gettext("[-- End of signed data --]\n")  =~
1017                 m/^(.*)\n/m;
1018             ($mutt_beginsigned) =
1019                 Locale::gettext::gettext("[-- The following data is signed --]\n\n") =~
1020                 m/^(.*)\n/m;
1021             ($mutt_pgpclearsigned) =
1022                 Locale::gettext::gettext("[-- END PGP SIGNED MESSAGE --]\n") =~
1023                 m/^(.*)\n/m;
1024             ($mutt_pgpclearsigstart) =
1025                 Locale::gettext::gettext("[-- BEGIN PGP SIGNED MESSAGE --]\n") =~
1026                 m/^(.*)\n/m;
1027             ($mutt_pgpencrypted) =
1028                 Locale::gettext::gettext("[-- End of PGP/MIME encrypted data --]\n") =~
1029                 m/^(.*)\n/m;
1030             ($mutt_pgpoutstart) =
1031                 Locale::gettext::gettext("[-- PGP output follows (current time: %c) --]\n") =~
1032                 m/^([^%]*)/;
1033             ($mutt_pgpoutend) =
1034                 Locale::gettext::gettext("[-- End of PGP output --]\n") =~
1035                 m/^(.*)\n/m;
1036
1037             Locale::gettext::textdomain('gnupg');
1038             ($gpg_WARNING) =
1039                 Locale::gettext::gettext("WARNING: using insecure random number generator!!\n") =~
1040                 m/^([^:]*: )/;
1041             ($gpg_Warning) =
1042                 Locale::gettext::gettext("WARNING: message was encrypted with a weak key in the symmetric cipher.\n") =~
1043                 m/^([^:]*: )/;
1044             ($gpg_Cantcheck) =
1045                 Locale::gettext::gettext("Can't check signature: %s\n") =~
1046                 m/^([^%]*)/;
1047             ($gpg_aka) =
1048                 Locale::gettext::gettext((' 'x16).'aka "%s"') =~
1049                 m/^([^"«%]*)["«%]/;
1050             ($gpg_bad) =
1051                 Locale::gettext::gettext('BAD signature from "%s"') =~
1052                 m/^([^"«%]*)["«%]/;
1053             ($gpg_expired) =
1054                 Locale::gettext::gettext("Note: This key has expired!\n") =~
1055                 m/^(.*)\n/m;
1056             ($gpg_good) =
1057                 Locale::gettext::gettext('Good signature from "%s"') =~
1058                 m/^(([^"«%]*))["«%]/;
1059             ($gpg_bug) =
1060                 Locale::gettext::gettext("... this is a bug (%s:%d:%s)\n") =~
1061                 m/^([^%]*)/;
1062         }
1063     }
1064
1065 }
1066 else {
1067     if ($ms_smart || $pgpshort || $pgpmove || $pgpmovevrf) { help(); }
1068 }
1069
1070
1071 # Read message:
1072 if (!open(IN, $ifile))
1073     { print STDERR "Could not open $ifile: $!\n"; exit(EX_IOERR); }
1074 my @message = <IN>;
1075 close IN;
1076
1077 # this should be self-explanatory:
1078 process_msg(\@message);
1079
1080 # Finally, print clean lines:
1081 if ($ofile ne 'NONE') {
1082     write_msg(($mda?'|'.SENDMAIL." $mda":">$ofile"), \@message);
1083 }
1084
1085 # vim600:set foldmethod=marker:
1086 # eof