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