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