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