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