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