]> 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.277 2010/02/06 03:29:23 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.13';
9 use constant REV            => '';
10 use constant REL            => q$Revision: 1.277 $=~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; 
130                   default is $maxsig if n not specified
131   -s              delete signature
132   --sigsmax[=n]   max number of sigs tolerated, no value for unlimited
133   --spass         enable SpamAssassin workaround
134   -t              delete traditional style TOFU
135   -v, --version   show version string and exit
136   -w              delete trailing whitespaces\n";
137     exit(EX_USAGE);
138 }
139
140 # version(): print version info and exit with appropriate exit code
141 sub version {
142     print "$0 v".VER.REV." (Rev. ".REL."), Jochen Striepe <t-prot\@tolot.escape.de>
143 Get the latest version at <http://www.escape.de/users/tolot/mutt/>\n";
144     exit(EX_OK);
145 }
146
147 # sigint_handler(): what to do if we receive a single SIGINT
148 sub sigint_handler {
149     $sigint = 1;
150 }
151
152 # remove_footers(): remove any trailing appearance of footers contained
153 # in the given directory.
154 sub remove_footers {
155     my $L = shift;        # array of message lines
156     my $S = shift;        # array to store removed lines in
157     my $F = shift;        # footers dir name
158     my $O = shift;        # remove only one footer?
159     my $V = shift;        # allow footers match before end of message
160     my $off;
161
162     if (!defined $V) {
163         for ($off = 0; $#$L>=$off && $$L[$#$L-$off] =~ /^\s*$/; $off++) {;};
164     }
165
166     if ($F && scalar(@$L)) {
167         if (!opendir(DIR, $F))
168             { print STDERR "Could not open $F: $!\n"; exit(EX_IOERR); }
169         my @feet = grep { /^[^.]/ && -f "$F/$_" } readdir DIR;
170         closedir DIR;
171
172         foreach my $f (@feet) {
173             if (!open(IN, "$F/$f"))
174                 { print STDERR "Could not open $F/$f: $!\n"; exit(EX_IOERR); }
175             my @l = <IN>;
176             close IN;
177
178             if (!scalar(@l)) { next; }
179             for (my $z=0; $z<=$#l; $z++) { chomp($l[$z]); }
180
181             if (defined $V) {
182                 WIPE: for (my $z=scalar(@$L)-scalar(@l); $z>=0; $z--) {
183                     if (scalar(@l)+$z<=scalar(@$L)) {
184                         my $y = 0;
185                         for(my $x=1; $x<=scalar(@l); $x++) {
186                             if (index($$L[scalar(@$L)-$x-$z],
187                                           $l[scalar(@l)-$x])!=0) {
188                                 $y = 1;
189                             }
190                         }
191                         if (!$y) {
192                             unshift(@$S, @$L[$#$L-$#l-$z..$#$L]);
193                             splice(@$L, $#$L-$#l-$z);
194                             while (scalar(@$L) && $$L[$#$L] =~ /^\s*$/) {
195                                 unshift(@$S, pop(@$L));
196                             }
197                             if ($O) { last; } else { goto WIPE; }
198                         }
199                     }
200                 }
201             }
202             else {
203                 while (scalar(@l)<=scalar(@$L)) {
204                     for(my $x=1; $x<=scalar(@l); $x++) {
205                         if (index($$L[scalar(@$L)-$x-$off], $l[scalar(@l)-$x])!=0) { 
206                             goto FINISH;
207                         }
208                     }
209                     unshift(@$S, @$L[$#$L-$off-$#l..$#$L]);
210                     splice(@$L, $#$L-$off-$#l);
211                     while (scalar(@$L) && $$L[$#$L] =~ /^\s*$/) {
212                         unshift(@$S, pop(@$L));
213                     }
214                     if ($O) { last; }
215                 }
216                 FINISH:
217             }
218         }
219     }
220 }
221
222 # decomb(): Try to detect and fix zig-zag shaped quoting (a.k.a. German
223 # "Kammquoting").
224 sub decomb {
225     my $L = shift;        # array of message lines
226     my $V = shift;        # array with verbatim list
227     my $max = 0;        # plausible wraparound pos
228
229     # We scan the whole message first for a plausible common maximum line
230     # length where longer lines would be wrapped.
231     for (my $x=0; $x<$#$L; $x++) {
232         if ($$V[$x]!=1 && $max<length($$L[$x])) { $max = length($$L[$x]); }
233     }
234
235     # Next we see if there are plausible wraparounds.    
236     for (my $x=0; $x+1<$#$L; $x++) {
237
238         # OK, 
239         # * it must not be verbatim,
240         # * the 2nd line must not be quoted nor empty nor just 
241         #   underlining some part of the line above (using '^')
242         #   nor begin with a whitespace,
243         # * the 1st line must not end with a hyphen,
244         # * the 2nd line must not indicate content was deleted,
245         # * the 2nd line must not be some mutt(1) commentary,
246         # * there must not be a valid word wrap to produce a longer
247         #   1st line (if not quoted),
248         # * the 1st and 2nd line together must not be longer than some
249         #   magical upper limit nor shorter than some magical lower
250         #   bound nor nearly of the same length, and
251         # * the 3rd line must not be empty.
252         # With all that odds should be quite good that we have an
253         # automatedly wrapped line. Please send a note if you have
254         # additional good criteria. Thanks.
255         if (($$V[$x]!=1 && $$V[$x+1]!=1) &&
256             (index($$L[$x+1], $indent)!=0) &&
257             ($$L[$x+1] !~ /^$/) &&
258             ($$L[$x+1] !~ /^[\s^]/) &&
259             ($$L[$x]   !~ /-$/) &&
260             ($$L[$x+1] !~ /^\Q[...]\E\s*$/) &&
261             ($mua ne 'mutt' || $$L[$x+1] !~ /^(?:\e[^\a]+\a)?\[-- /) &&
262             (length($$L[$x])+index($$L[$x+1], ' ')>$max ||
263                 (index($$L[$x+1], ' ')<0 &&
264                  length($$L[$x])+length($$L[$x+1])>$max)) &&
265             (length($$L[$x])+length($$L[$x+1])<$kmaxl) &&
266             (length($$L[$x])+length($$L[$x+1])>$kminl) &&
267             (length($$L[$x])-length($$L[$x+1])>$kdiff) &&
268             ($$L[$x+2] !~ /^\s*$/))
269         {
270             $$L[$x] =~ s/\s*$/' ' . $$L[$x+1]/e;
271             splice(@$L, $x+1, 1);
272             splice(@$V, $x+1, 1);
273         }
274     }
275 }
276
277 # debigq(): Finds big quotes (more than $n lines quoted) and deletes all
278 # but $x lines of them.
279 sub debigq {
280     my $L = shift;        # array of message lines
281     my $V = shift;        # array with verbatim list
282     my $k = 0;
283
284     for (my $i=0; $i<=$#$L; $i++) {
285
286         if ($$V[$i]) { 
287             $k = 0;
288             next;
289         }
290
291         if (index($$L[$i], $indent)==0) { $k++; } else { 
292             if ($k>$bigqn) {
293                 my $x = $k-$bigqx;
294                 $i -= $k;
295
296                 $$L[$i] = "[---=| Quote block shrinked by $0: " .
297                     "$x lines snipped |=---]\n";
298                 $i++;
299                 splice(@$L, $i, $x-1);
300                 splice(@$V, $i, $x-1);
301
302                 $i++;
303             }
304             $k = 0;
305         }
306     }
307 }
308
309 # pgp(): treat mutt(1)'s pgp/gpg output contained in signed or encrypted
310 # messages
311 sub pgp {
312
313     sub verified {
314         my $L = shift;    # message body
315         my $X = shift;    # start line
316         my $Z = shift;    # end line
317
318                 my $ok = 0;
319
320         while ($X<$Z) {
321             if (index($$L[$X], "gpg: $gpg_WARNING")==0 ||
322                 index($$L[$X], "gpg: $gpg_Warning")==0 ||
323                 index($$L[$X], "gpg: $gpg_bad")==0 ||
324                 index($$L[$X], "gpg: $gpg_Cantcheck")==0 ||
325                 index($$L[$X], "gpg: $gpg_expired")==0 ||
326                 index($$L[$X], "gpg: $gpg_bug")==0)
327                 { return 0; }
328             if (index($$L[$X], "gpg: $gpg_good")==0)
329                 { $ok = 1; }
330             $X++;
331         }
332
333         return $ok;
334     }
335
336     my $L = shift;        # message body
337     my $V = shift;        # verbatim list
338     my $H = shift;        # headers
339
340     my @tmp = ();
341     my $tmp = 0;
342
343     for (my $x=0; $x<scalar(@$L); $x++) {
344         if ($$V[$x]) { next; }
345
346         if ($$L[$x]=~/^(?:\e[^\a]+\a)?(?:\Q$mutt_pgpoutstart\E)/o)
347         {
348             my $from;
349             for (my $m=0; $m<scalar(@$H); $m++) {
350                 if (index($$H[$m], 'From:')==0) {
351                     $from = $$H[$m];
352                     $m++;
353                     while (exists($$H[$m]) && $$H[$m] =~ /^\s/)
354                         { $from .= $$H[$m]; $m++; }
355                     last;
356                 }
357             }
358             ($from) = $from=~m/(\w[\w.+-]*@(?:[\w.+-]+\.)+[A-Za-z]{2,})/;
359
360             my $uid = 1;
361
362             for (my $i=$x+1; $i<scalar(@$L); $i++) {
363                 if ($pgpshort && index($$L[$i], "gpg: $gpg_aka")==0)
364                     { $uid++; }
365
366                 if ($pgpshort && $uid>1 &&
367                     index($$L[$i], "gpg: $gpg_aka")==0 &&
368                     index($$L[$i], $from)<0)
369                 { 
370                     splice(@$L, $i, 1);
371                     splice(@$V, $i, 1);
372                     $i--;
373                 }
374                 elsif ($$L[$i]=~/^(?:\e[^\a]+\a)?(?:\Q$mutt_pgpoutend\E)/o)
375                 {
376                     if ($pgpmove ||
377                         ($pgpmovevrf && (!$sigint) && verified($L, $x+1, $i)))
378                     {
379                         push(@{$tmp[++$tmp]}, "\n", @$L[$x..($i+1)]);
380                         splice(@$L, $x, $i-$x+2);
381                         splice(@$V, $x, $i-$x+2);
382                         $i -= $#{$tmp[$tmp]}-2;
383                     }
384                     $x = $i;
385                     last;
386                 }
387             }
388         }
389         elsif ($tmp &&
390             $$L[$x] =~ /^
391                         (?:\e[^\a]+\a)?
392                         (?:\Q$mutt_pgpencrypted\E  |
393                            \Q$mutt_pgpclearsigned\E|
394                            \Q$mutt_pgpsigned\E)
395                        /ox)
396         {
397             splice(@$L, $x+1, 0, @{$tmp[$tmp]});
398             for (my $i=$x; $i<scalar(@{$tmp[$tmp]}); $i++) {
399                 splice(@$V, $x+1, 0, (0));
400             }
401             $x += scalar(@{$tmp[$tmp--]});
402             pop(@tmp);
403         }
404     }
405
406     while ($tmp>0) {
407         push(@$L, @{$tmp[$tmp--]});
408         pop(@tmp);
409         for (my $i=$#$V; $i<$#$L; $i++) { push(@$V, 0); }
410     }
411 }
412
413 # write_msg(): output
414 sub write_msg {
415     my $O = shift;
416     my $l;
417
418     if ((!$lax) && ($O =~ /^>(.*)/) && ($1 ne '-')) {
419         if (!sysopen(OUT, $1, O_EXCL|O_CREAT|O_WRONLY)) { 
420             print STDERR "Could not open $1: $!\n"; exit(EX_IOERR);
421         }
422     }
423     elsif (!open(OUT, $O)) { 
424         print STDERR "Could not open $O: $!\n"; exit(EX_IOERR);
425     }
426     while (scalar(@_)) {
427         $l = shift;
428         if (defined $l) {
429             $^W = 0;
430             print OUT @$l;
431             $^W = 1;
432         }
433     }
434     close OUT;
435 }
436
437 # process_msg(): This one proc does *everything* what has to be done with
438 # the lines of the message
439 sub process_msg {
440     my $lines = shift;
441
442     my ($j, $x, $verb) = (0, 0, 0);
443     my (@ads, @hdr, @bo1, @bo2, @ftr, @sig, @vrb, @att) = 
444         ((), (), (), (), (), (), (), (), ());
445
446     # Remove and store lines we might need later...
447     # Remove headers:
448     if (!$nohdr) {
449         for ($x=0; $x<$#$lines; $x++) { if (@$lines[$x] =~ /^$/) { last; }; }
450         @hdr = @$lines[0..$x];
451         splice(@$lines, 0, $x+1);
452     }
453     # remember the original body lines count
454     my $linecount = scalar(@$lines);
455
456     # Remove ML footers:
457     remove_footers($lines, \@ftr, $footers, undef, $ftr_ml);
458
459     # Remove ad footers:
460     remove_footers($lines, \@ads, $ads, undef, $ftr_ad);
461
462     # See if we have a multipart content type. If yes, see if it is already
463     # ripped (e.g. by you MUA, assuming it does not get special treatment with
464     # --mua=foo), otherwise only leave the first part if it is plain text (if
465     # not, we are done - non-text messages are not our business).
466     if ($mua ne 'mutt') { 
467         for ($x=0; $x<scalar(@hdr); $x++) {
468             if ($hdr[$x] =~ /^Content-[Tt]ype:\s+(.*)$/) {
469                 my $foo = $1;
470
471                 if ($foo =~ m!^multipart/!) {
472                     undef $foo;
473
474                     if ($hdr[$x] =~ /\Wboundary="([^"]+)"/i) { $foo = $1; }
475                     else { 
476                         for (my $z=1; $x+$z<@hdr && $hdr[$x+$z]=~/^\s/; $z++) {
477                             if ($hdr[$x] =~ /\Wboundary="?([^"\s]+)"?$/i) { 
478                                 $foo = $1;
479                                 last;
480                             }
481                         }
482                     }
483
484                     if (defined $foo) {
485                         for (my $x=0; $x<scalar(@$lines); $x++) {
486                             if (index($$lines[$x], '--'.$foo)!=0) { next; }
487
488                             my $bar = 'text/plain';
489                             for ($x++; $x<@$lines && $$lines[$x]!~/^$/; $x++)
490                             {
491                                 if ($$lines[$x] =~ /^Content-[Tt]ype:\s+(.*)/) { 
492                                     $bar = $1;
493                                 }
494                             }
495                             if ($x>=scalar(@$lines)) { exit(EX_DATAERR); }
496
497                             if ($bar =~ m!^text/plain!) {
498                                 my $z;
499                                 for ($z=1; $x+$z<@$lines; $z++) {
500                                     if (index($$lines[$x+$z], '--'.$foo)==0) {
501                                         last;
502                                     }
503                                 }
504                                 if ($x+$z>=scalar(@$lines)) { exit(EX_DATAERR); }
505
506                                 @bo2 = @$lines[$x+$z..$#$lines];
507                                 splice(@$lines, $x+$z);
508                                 if ($$lines[$#$lines] =~ /^\s*$/) {
509                                     unshift(@bo2, pop @$lines);
510                                 }
511                                 @bo1 = @$lines[0..$x];
512                                 splice(@$lines, 0, $x+1);
513
514                                 # remove mailing list and ad footers within this
515                                 # attachment:
516                                 remove_footers($lines, \@ftr, $footers, undef, $ftr_ml);
517                                 remove_footers($lines, \@ads, $ads, undef, $ftr_ad);
518
519                                 last;
520                             }
521                             else { 
522                                 write_msg(($mda?'|'.SENDMAIL." $mda":">$ofile"),
523                                     ($hdrs?undef:\@hdr), $lines);
524                                 exit;
525                             }
526                         }
527                     }
528                 }
529                 last;
530             }
531         } 
532     }
533
534
535     # Protect verbatims:
536     $verb = 0;
537     for ($x=0; $x<scalar(@$lines); $x++) {
538         if ($$lines[$x] =~ /^\s*#v([+-])$/) { 
539             $verb = $1 eq '+' ? 1 : 0;
540             $vrb[$x] = 1;
541         } else { $vrb[$x] = $verb; }
542     }
543
544     # Calculate quoting ratio (with respect to verbatims):
545     if ($check && scalar(@$lines)) {
546         my ($y, $z) = (0, 0);
547         for ($x=0; $x<scalar(@$lines); $x++) {
548             if (!$vrb[$x]) {
549                 $z++;
550                 if (index($$lines[$x], $indent)==0) { $y++; }
551             }
552         }
553
554         if ($y/$z>=$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                          # this line seems not necessary since mutt-1.5.18:
725                          $$lines[$x] !~ /^\e[^\a]+\a$/o &&
726                          $$lines[$x] !~
727                              /^(?:\e[^\a]+\a)?(?:\Q$mutt_attachment\E)/o &&
728                          $$lines[$x] !~
729                              /^(?:\e[^\a]+\a)?(?:\Q$mutt_contenttype\E)/o)) &&
730                     ((!$spass) || index($$lines[$x], $spass_prefix)!=0))
731                 {
732                     if ($mua eq 'mutt' && (!$tmp) &&
733                         $$lines[$x] =~
734                              /^(?:\e[^\a]+\a)?(?:\Q$mutt_pgpoutstart\E)/o) {
735                         $tmp = 1; 
736                     } elsif ($mua eq 'mutt' && $tmp && 
737                         ($$lines[$x] =~
738                              /^(?:\e[^\a]+\a)?(?:\Q$mutt_beginsigned\E)/o ||
739                          $$lines[$x] =~
740                              /^(?:\e[^\a]+\a)?(?:\Q$mutt_pgpclearsigstart\E)/o)) {
741                         $tmp = 0;
742                     } elsif (!$tmp) {
743                         $k = 1;
744                     }
745                 }
746             }
747         }
748
749         # try to avoid false positives and only delete m$ style tofu if
750         # there is text above
751         if ($k) {
752             if (!$ms_smart) { goto CLEAN; }
753
754             # first, see if there is pgp stuff inside the tofu:
755             my $p = 0;    # levels of pgp signed parts
756
757             for (my $i=$x+1; $i<scalar(@$lines); $i++) {
758                 if ($$lines[$i] =~
759                         /^(?:\e[^\a]+\a)?(?:\Q$mutt_pgpclearsigstart\E)/o) {
760                     $p++;
761                 }
762             }
763             if ($p) {
764                 STAIRS: for (my $i=0; $i<scalar(@att); $i++) {
765                     if ($p==0 && $att[$i] =~ /^(?:\e[^\a]+\a)?\[-- /o) {
766                         splice(@att, 0, $i);
767                         unshift(@att, "\n");
768                         goto CLEAN;
769                     } elsif ($att[$i] =~
770                             /^(?:\e[^\a]+\a)?(?:\Q$mutt_pgpclearsigned\E)/o) {
771                         splice(@att, 0, $i+1);
772                         $p--;
773                         goto STAIRS;
774                     }
775                 }
776                 splice(@att);
777             }
778
779             # now removing is safe:
780             CLEAN: $j = scalar(@$lines)-$x;
781             splice(@$lines, $x);
782         }
783     }
784
785     # Nothing? Then try traditional TOFU (deleting M$ style TOFU is done
786     # much more aggressively, so we won't need to search any more if we
787     # did find some):
788     if ($trad && (!$j) && !$vrb[$#$lines]) {
789         if (scalar(@$lines) && $$lines[$#$lines] =~ /^\s*$/) { 
790             unshift(@sig, pop(@$lines));
791         }
792
793         my $k;
794         my $x = 1;
795
796         for (my $i=$#$lines; $i>=0; $i--) {
797             if ($$lines[$i] =~ /^$indent/o) {
798                 $j++;
799                 $k = $i;
800             }
801             elsif ($$lines[$i] !~ /^\s*$/) { last; }
802         }
803
804         if ($j) {
805             # if there is no text above, we will assume the message is meant
806             # as forwarding and therefore OK
807             for (my $i=$k-1; $i>=0; $i--) {
808                 if ($$lines[$i] !~ /^\s*$/o) {
809                    $x = 0;
810                    last;
811                 }
812             }
813             if ($x) {
814                 $j = 0;
815             } else {
816                 splice(@$lines, $k);
817             }
818         }
819     }
820
821     # OK, if we found TOFU, we will leave a message that we were here...
822     if ($j) { 
823         # make sendmail bounce if we shall be picky 
824         # and indeed found something:
825         if ($mda) { 
826             if ($mda ne '1') { 
827                 print STDERR $boun;
828
829                 if ($sysl) {
830                     eval { require Sys::Syslog; }; 
831                     if ($@) { warn $@; } else {
832                         Sys::Syslog::setlogsock('unix');
833                         Sys::Syslog::openlog("$0[$$]", 'pid', 'mail');
834                         Sys::Syslog::syslog('debug', 'bounced message %s', $hdr[0]);
835                         Sys::Syslog::closelog();
836                     }
837                 }
838             }
839
840             exit EX_BOUNCE;
841         }
842
843         # if we were invoked just for checking and indeed found something,
844         # print out the error message and quit:
845         if ($check) {
846             print $msg_quote;
847             exit EX_UNAVAILABLE;
848         }
849
850         push(@$lines, "[---=| TOFU protection by $0: " .
851             "$j lines snipped |=---]\n");
852     }
853     elsif ($mda eq '1') { exit EX_OK; }
854
855     # Care for huge blocks of quoted original message:
856     if ($bigqn) { debigq($lines, \@vrb); }
857
858     # Care for trailing whitespaces:
859     if ($trsp) {
860         for ($x=0; $x<scalar(@$lines); $x++) { 
861             if (!$vrb[$x]) { $$lines[$x] =~ s/[\ \t]+$//; }
862         }
863     }
864
865     # Care for punctuation abuse:
866     if ($elli) {
867         for ($x=0; $x<scalar(@$lines); $x++) { 
868             if (!$vrb[$x]) { $$lines[$x] =~ s/(([.?!])\2\2)\2+/$1/g; }
869         }
870     }
871
872     # (Nearly) at last care for multiple blank lines. (Do not do this
873     # earlier -- the way it is done right now would screw up the verbatim
874     # list)
875     if ($cr) {
876         my $t = 0;
877         for ($x=scalar(@$lines)-1; $x>=0; $x--) {
878             if ((!$vrb[$x]) && $$lines[$x] =~ /^\s*$/) { 
879                 if ($t<2) { $t++; } else { splice(@$lines, $x, 1); }
880             }
881             else { $t = 0; }
882         }
883     }
884
885     # Everything changing the body is done now. Time to fix the line count
886     # header so naive clients do not get confused. Just to be sure, append
887     # the old line count to X-headers.
888     my $l = scalar(@bo1) + scalar(@$lines) + scalar(@att) + scalar(@bo2) +
889                 (!$sig?scalar(@sig):0) + (!$ml?scalar(@ftr):0) + 
890                 (!$ad?scalar(@ads):0);
891     if ($linecount-$l!=0) {
892         for ($x=0; $x<scalar(@hdr); $x++) {
893             if ($hdr[$x] =~ 
894                 s/^(Lines:\s+)(\d+)/$1.($2-$linecount+$l)/e)
895             { 
896                 $hdr[$#hdr] = "X-Old-Lines: $2\n";
897                 push(@hdr, "\n");
898             }
899         }
900     }
901
902     # Finally, before leaving we put everything back in right order.
903     unshift(@$lines, (!$hdrs?@hdr:()), @bo1);
904     push(@$lines, (!$sig?@sig:()), (!$ad?@ads:()), (!$ml?@ftr:()), @att,
905         @bo2);
906 }
907
908
909 # environment
910 my $locale = $ENV{'LC_ALL'}?$ENV{'LC_ALL'}:
911                  ($ENV{'LC_MESSAGES'}?$ENV{'LC_MESSAGES'}:$ENV{'LANG'});
912
913 # command line switches
914 ($ad, $ads, $bigqn, $bigqx, $check, $cr, $sysl, $diff, $elli, $footers, $lax,
915     $ml, $gw, $ms, $ms_smart, $mda, $mua, $hdrs, $kamm, $lsig, $nohdr, $sig,
916     $sigint, $spass, $trad, $trsp) =
917     (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
918 my $ifile   = '-';    # use STDIN if nothing specified
919
920 # get command line params:
921 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'.
922     ' s t v w bigq:s body check:s debug>d diff ftr-ad ftr-ml groupwise'.
923     ' help>h kminl=i kmaxl=i kdiff=i lax-security locale=s max-lines=i'.
924     ' ms-smart mua>M pgp-short pgp-move pgp-move-vrf sigsmax:i spass'.
925     ' version>v');
926 while (my ($opt, $val, $pretty) = nextOption()) {
927     if    ($opt eq 'a')     { $ad = 1; }
928     elsif ($opt eq 'A')     { $ads = $val; }
929     elsif ($opt eq 'bigq')  { 
930         if ($val !~ /^(?:(\d+)(?:,(\d+))?)?$/) { help(); }
931         $bigqn = $1?$1:30; 
932         $bigqx = $2?$2:10;
933         if ($bigqn<=0 || $bigqx<=0 || $bigqn<=$bigqx) { help(); }
934     }
935     elsif ($opt eq 'body')  { $nohdr = 1; $hdrs = 1; }
936     elsif ($opt eq 'c')     { $cr = 1; }
937     elsif ($opt eq 'check') {
938         $check = 1;
939         while ($val && $val =~ /^([^,\s]+)(?:,(\S+))?$/) {
940             my $foo = $1;
941             $val = $2;
942
943             if ($foo =~ /^ratio(?:=(0?\.\d+))?$/) {
944                 $check_ratio = $1?$1:0.75;
945             }
946         }
947     }
948     elsif ($opt eq 'd')     { $sysl = 1; }
949     elsif ($opt eq 'diff')  { $diff = 1; }
950     elsif ($opt eq 'e')     { $elli = 1; }
951     elsif ($opt eq 'ftr-ad') { $ftr_ad = 1; $ad = 1; }
952     elsif ($opt eq 'ftr-ml') { $ftr_ml = 1; $ml = 1; }
953     elsif ($opt eq 'groupwise') { $gw = 1; }
954     elsif ($opt eq 'i')     { $ifile = $val; }
955     elsif ($opt eq 'k')     { $kamm = 1; }
956     elsif ($opt eq 'kminl') { $kminl = $val; $kamm = 1; }
957     elsif ($opt eq 'kmaxl') { $kmaxl = $val; $kamm = 1; }
958     elsif ($opt eq 'kdiff') { $kdiff = $val; $kamm = 1; }
959     elsif ($opt eq 'L')     { $footers = $val; }
960     elsif ($opt eq 'l')     { $ml = 1; }
961     elsif ($opt eq 'lax-security') { $lax = 1; }
962     elsif ($opt eq 'locale') { $locale = $val; }
963     elsif ($opt eq 'm')     { $ms = 1; }
964     elsif ($opt eq 'max-lines') { $maxlines = $val; }
965     elsif ($opt eq 'ms-smart') { $ms_smart = 1; $ms = 1; }
966     elsif ($opt eq 'M') {
967         $mua = lc($val);
968
969         if ($mua eq 'mutt') {
970             # mutt still displays the message when ^C'ing pgp verification:
971             $SIG{'INT'} = 'sigint_handler';
972         }
973     }
974     elsif ($opt eq 'o')     { $ofile = $val; }
975     elsif ($opt eq 'P')     { $boun = $val; }
976     elsif ($opt eq 'p')     { $mda = $val ? $val : '1'; }
977     elsif ($opt eq 'pgp-short') { $pgpshort = 1; }
978     elsif ($opt eq 'pgp-move') { $pgpmove = 1; }
979     elsif ($opt eq 'pgp-move-vrf') { $pgpmovevrf = 1; }
980     elsif ($opt eq 'r')     { $hdrs = 1; }
981     elsif ($opt eq 'S')     { $lsig = $val ? $val : $maxsig; }
982     elsif ($opt eq 's')     { $sig = 1; }
983     elsif ($opt eq 'sigsmax') { $sign = $val ? $val : undef; }
984     elsif ($opt eq 'spass') { $spass = 1; }
985     elsif ($opt eq 't')     { $trad = 1; }
986     elsif ($opt eq 'v')     { version(); }
987     elsif ($opt eq 'w')     { $trsp = 1; }
988     else                    { help(); }
989 }
990 Getopt::Mixed::cleanup();
991 if (($ml && $footers eq '')||    # no -l without -L
992     ($ad && $ads eq '')||        # no -a without -A
993     ($nohdr && $pgpshort)||      # --body and --pgp-short are like oil and water
994     ($ifile eq '')||             # no empty -i
995     ($ofile eq ''))              # no empty -o
996 { help(); }
997
998
999 if ($mua eq 'mutt') {
1000     if (defined $locale && $locale ne '' && $locale ne 'C' && $locale ne 'POSIX') {
1001         eval { require Locale::gettext; };
1002         if ($@) { warn $@; exit(EX_SOFTWARE); } else {
1003             Locale::gettext::textdomain('mutt');
1004             ($mutt_attachment) =
1005                 Locale::gettext::gettext("[-- Attachment #%d") =~
1006                 m/^([^%]*)/;
1007             ($mutt_contenttype) =
1008                 Locale::gettext::gettext("[-- Type: %s/%s, Encoding: %s, Size: %s --]\n") =~
1009                 m/^([^%]*)/;
1010             ($mutt_pgpsigned) =
1011                 Locale::gettext::gettext("[-- End of signed data --]\n")  =~
1012                 m/^(.*)\n/m;
1013             ($mutt_beginsigned) =
1014                 Locale::gettext::gettext("[-- The following data is signed --]\n\n") =~
1015                 m/^(.*)\n/m;
1016             ($mutt_pgpclearsigned) =
1017                 Locale::gettext::gettext("[-- END PGP SIGNED MESSAGE --]\n") =~
1018                 m/^(.*)\n/m;
1019             ($mutt_pgpclearsigstart) =
1020                 Locale::gettext::gettext("[-- BEGIN PGP SIGNED MESSAGE --]\n") =~
1021                 m/^(.*)\n/m;
1022             ($mutt_pgpencrypted) =
1023                 Locale::gettext::gettext("[-- End of PGP/MIME encrypted data --]\n") =~
1024                 m/^(.*)\n/m;
1025             ($mutt_pgpoutstart) =
1026                 Locale::gettext::gettext("[-- PGP output follows (current time: %c) --]\n") =~
1027                 m/^([^%]*)/;
1028             ($mutt_pgpoutend) =
1029                 Locale::gettext::gettext("[-- End of PGP output --]\n") =~
1030                 m/^(.*)\n/m;
1031
1032             Locale::gettext::textdomain('gnupg');
1033             ($gpg_WARNING) =
1034                 Locale::gettext::gettext("WARNING: using insecure random number generator!!\n") =~
1035                 m/^([^:]*: )/;
1036             ($gpg_Warning) =
1037                 Locale::gettext::gettext("WARNING: message was encrypted with a weak key in the symmetric cipher.\n") =~
1038                 m/^([^:]*: )/;
1039             ($gpg_Cantcheck) =
1040                 Locale::gettext::gettext("Can't check signature: %s\n") =~
1041                 m/^([^%]*)/;
1042             ($gpg_aka) =
1043                 Locale::gettext::gettext((' 'x16).'aka "%s"') =~
1044                 m/^([^"«%]*)["«%]/;
1045             ($gpg_bad) =
1046                 Locale::gettext::gettext('BAD signature from "%s"') =~
1047                 m/^([^"«%]*)["«%]/;
1048             ($gpg_expired) =
1049                 Locale::gettext::gettext("Note: This key has expired!\n") =~
1050                 m/^(.*)\n/m;
1051             ($gpg_good) =
1052                 Locale::gettext::gettext('Good signature from "%s"') =~
1053                 m/^(([^"«%]*))["«%]/;
1054             ($gpg_bug) =
1055                 Locale::gettext::gettext("... this is a bug (%s:%d:%s)\n") =~
1056                 m/^([^%]*)/;
1057         }
1058     }
1059
1060 }
1061 elsif ($ms_smart || $pgpshort || $pgpmove || $pgpmovevrf) { help(); }
1062
1063
1064 # Read message:
1065 if (!open(IN, $ifile))
1066     { print STDERR "Could not open $ifile: $!\n"; exit(EX_IOERR); }
1067 my @message = <IN>;
1068 close IN;
1069
1070 # First, check msg length and stop processing if msg is too long:
1071 if ((defined $maxlines) && (@message > $maxlines)) {
1072     if ($ofile ne 'NONE') {
1073         if ($mua eq 'mutt') {
1074             my $x = 0;
1075             if (!$nohdr) {
1076                 do { $x++; } while ($x<$#message && $message[$x]!~/^$/);
1077                 $x++;
1078             }
1079             splice(@message, $x, 0,
1080                 ("[---=| Processing by $0 skipped: message too long |=---]\n\n"));
1081         }
1082
1083         write_msg(($mda?'|'.SENDMAIL." $mda":">$ofile"), \@message);
1084     }
1085     if ($mua eq 'mutt') { exit(EX_OK); }
1086     exit(EX_DATAERR);
1087 }
1088
1089 # this should be self-explanatory:
1090 process_msg(\@message);
1091
1092 # Finally, print clean lines:
1093 if ($ofile ne 'NONE') {
1094     write_msg(($mda?'|'.SENDMAIL." $mda":">$ofile"), \@message);
1095 }
1096
1097 # vim600:set foldmethod=marker:
1098 # eof