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