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