]> git.deb.at Git - pkg/t-prot.git/blob - t-prot
Imported Upstream version 2.3
[pkg/t-prot.git] / t-prot
1 #!/usr/bin/perl -w
2 # $Id: t-prot,v 1.250 2006/12/19 13:13:57 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.3';
9 use constant REV            => '';
10 use constant REL            => q$Revision: 1.250 $=~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=DIRECTORY    ad footer directory, treat ad footers as signature
90   -a              remove ad footers; requires -A
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]+\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 (index($$L[$X], "gpg: $gpg_WARNING")==0 ||
315                 index($$L[$X], "gpg: $gpg_Warning")==0 ||
316                 index($$L[$X], "gpg: $gpg_bad")==0 ||
317                 index($$L[$X], "gpg: $gpg_Cantcheck")==0 ||
318                 index($$L[$X], "gpg: $gpg_expired")==0 ||
319                 index($$L[$X], "gpg: $gpg_bug")==0)
320                 { return 0; }
321             if (index($$L[$X], "gpg: $gpg_good")==0)
322                 { $ok = 1; }
323             $X++;
324         }
325
326         return $ok;
327     }
328
329     my $L = shift;        # message body
330     my $V = shift;        # verbatim list
331     my $H = shift;        # headers
332
333     my @tmp = ();
334     my $tmp = 0;
335
336     for (my $x=0; $x<scalar(@$L); $x++) {
337         if ($$V[$x]) { next; }
338
339         if ($$L[$x]=~/^(?:\e[^\a]+\a)?(?:\Q$mutt_pgpoutstart\E)/o)
340         {
341             my $from;
342             for (my $m=0; $m<scalar(@$H); $m++) {
343                 if (index($$H[$m], 'From:')==0) {
344                     $from = $$H[$m];
345                     $m++;
346                     while (exists($$H[$m]) && $$H[$m] =~ /^\s/) { $from .= $$H[$m]; $m++; }
347                     last;
348                 }
349             }
350             ($from) = $from=~m/(\w[\w.+-]*@(?:[\w.+-]+\.)+[A-Za-z]{2,})/;
351
352             my $uid = 1;
353
354             for (my $i=$x+1; $i<scalar(@$L); $i++) {
355                 if ($pgpshort && index($$L[$i], "gpg: $gpg_aka")==0)
356                     { $uid++; }
357
358                 if ($pgpshort && $uid>1 &&
359                     index($$L[$i], "gpg: $gpg_aka")==0 &&
360                     index($$L[$i], $from)<0)
361                 { 
362                     splice(@$L, $i, 1);
363                     splice(@$V, $i, 1);
364                     $i--;
365                 }
366                 elsif ($$L[$i]=~/^(?:\e[^\a]+\a)?(?:\Q$mutt_pgpoutend\E)/o)
367                 {
368                     if ($pgpmove ||
369                         ($pgpmovevrf && (!$sigint) && verified($L, $x+1, $i)))
370                     {
371                         push(@{$tmp[++$tmp]}, "\n", @$L[$x..($i+1)]);
372                         splice(@$L, $x, $i-$x+2);
373                         splice(@$V, $x, $i-$x+2);
374                         $i -= $#{$tmp[$tmp]}-2;
375                     }
376                     $x = $i;
377                     last;
378                 }
379             }
380         }
381         elsif ($tmp &&
382             $$L[$x] =~ /^
383                         (?:\e[^\a]+\a)?
384                         (?:\Q$mutt_pgpencrypted\E  |
385                            \Q$mutt_pgpclearsigned\E|
386                            \Q$mutt_pgpsigned\E)
387                        /ox)
388         {
389             splice(@$L, $x+1, 0, @{$tmp[$tmp]});
390             for (my $i=$x; $i<scalar(@{$tmp[$tmp]}); $i++) {
391                 splice(@$V, $x+1, 0, (0));
392             }
393             $x += scalar(@{$tmp[$tmp--]});
394             pop(@tmp);
395         }
396     }
397
398     while ($tmp>0) {
399         push(@$L, @{$tmp[$tmp--]});
400         pop(@tmp);
401         for (my $i=$#$V; $i<$#$L; $i++) { push(@$V, 0); }
402     }
403 }
404
405 # write_msg(): output
406 sub write_msg {
407     my $O = shift;
408     my $l;
409
410     if ((!$lax) && ($O =~ /^>(.*)/) && ($1 ne '-')) {
411         if (!sysopen(OUT, $1, O_EXCL|O_CREAT|O_WRONLY)) { 
412             print STDERR "Could not open $1: $!\n"; exit(EX_IOERR);
413         }
414     }
415     elsif (!open(OUT, $O)) { 
416         print STDERR "Could not open $O: $!\n"; exit(EX_IOERR);
417     }
418     while (scalar(@_)) {
419         $l = shift;
420         if (defined $l) {
421             $^W = 0;
422             print OUT @$l;
423             $^W = 1;
424         }
425     }
426     close OUT;
427 }
428
429 # process_msg(): This one proc does *everything* what has to be done with
430 # the lines of the message
431 sub process_msg {
432     my $lines = shift;
433
434     my ($j, $x, $verb) = (0, 0, 0);
435     my (@ads, @hdr, @bo1, @bo2, @ftr, @sig, @vrb, @att) = 
436         ((), (), (), (), (), (), (), (), ());
437
438     # First, remove and store lines we might need later...
439     # Remove headers:
440     if (!$nohdr) {
441         for ($x=0; $x<$#$lines; $x++) { if (@$lines[$x] =~ /^$/) { last; }; }
442         @hdr = @$lines[0..$x];
443         splice(@$lines, 0, $x+1);
444     }
445     # remember the original body lines count
446     my $linecount = scalar(@$lines);
447
448     # Remove ML footers:
449     remove_footers($lines, \@ftr, $footers, undef, $ftr_ml);
450
451     # Remove ad footers:
452     remove_footers($lines, \@ads, $ads, undef, $ftr_ad);
453
454     # See if we have a multipart content type. If yes, see if it is already
455     # ripped (e.g. by you MUA, assuming it does not get special treatment with
456     # --mua=foo), otherwise only leave the first part if it is plain text (if
457     # not, we are done - non-text messages are not our business).
458     if ($mua ne 'mutt') { 
459         for ($x=0; $x<scalar(@hdr); $x++) {
460             if ($hdr[$x] =~ /^Content-[Tt]ype:\s+(.*)$/) {
461                 my $foo = $1;
462
463                 if ($foo =~ m!^multipart/!) {
464                     undef $foo;
465
466                     if ($hdr[$x] =~ /\Wboundary="([^"]+)"/i) { $foo = $1; }
467                     else { 
468                         for (my $z=1; $x+$z<@hdr && $hdr[$x+$z]=~/^\s/; $z++) {
469                             if ($hdr[$x] =~ /\Wboundary="?([^"\s]+)"?$/i) { 
470                                 $foo = $1;
471                                 last;
472                             }
473                         }
474                     }
475
476                     if (defined $foo) {
477                         for (my $x=0; $x<scalar(@$lines); $x++) {
478                             if (index($$lines[$x], '--'.$foo)!=0) { next; }
479
480                             my $bar = 'text/plain';
481                             for ($x++; $x<@$lines && $$lines[$x]!~/^$/; $x++)
482                             {
483                                 if ($$lines[$x] =~ /^Content-[Tt]ype:\s+(.*)/) { 
484                                     $bar = $1;
485                                 }
486                             }
487                             if ($x>=scalar(@$lines)) { exit(EX_DATAERR); }
488
489                             if ($bar =~ m!^text/plain!) {
490                                 my $z;
491                                 for ($z=1; $x+$z<@$lines; $z++) {
492                                     if (index($$lines[$x+$z], '--'.$foo)==0) {
493                                         last;
494                                     }
495                                 }
496                                 if ($x+$z>=scalar(@$lines)) { exit(EX_DATAERR); }
497
498                                 @bo2 = @$lines[$x+$z..$#$lines];
499                                 splice(@$lines, $x+$z);
500                                 if ($$lines[$#$lines] =~ /^\s*$/) {
501                                     unshift(@bo2, pop @$lines);
502                                 }
503                                 @bo1 = @$lines[0..$x];
504                                 splice(@$lines, 0, $x+1);
505
506                                 # remove mailing list and ad footers within this
507                                 # attachment:
508                                 remove_footers($lines, \@ftr, $footers, undef, $ftr_ml);
509                                 remove_footers($lines, \@ads, $ads, undef, $ftr_ad);
510
511                                 last;
512                             }
513                             else { 
514                                 write_msg(($mda?'|'.SENDMAIL." $mda":">$ofile"),
515                                     ($hdrs?undef:\@hdr), $lines);
516                                 exit;
517                             }
518                         }
519                     }
520                 }
521                 last;
522             }
523         } 
524     }
525
526
527     # Protect verbatims:
528     $verb = 0;
529     for ($x=0; $x<scalar(@$lines); $x++) {
530         if ($$lines[$x] =~ /^\s*#v([+-])$/) { 
531             $verb = $1 eq '+' ? 1 : 0;
532             $vrb[$x] = 1;
533         } else { $vrb[$x] = $verb; }
534     }
535
536     # Calculate quoting ratio (with respect to verbatims):
537     if ($check && scalar(@$lines)) {
538         my ($y, $z) = (0, 0);
539         for ($x=0; $x<scalar(@$lines); $x++) {
540             if (!$vrb[$x]) {
541                 $z++;
542                 if (index($$lines[$x], $indent)==0) { $y++; }
543             }
544         }
545         $y = $y/$z;
546
547         if ($y>=$check_ratio) {
548             print $msg_ratio;
549             exit EX_UNAVAILABLE;
550         }
551     }
552
553     if ($mua eq 'mutt') {
554         # See if we find pgp output generated by mutt before we scramble
555         # the thing. If yes, see if we can beautify it.
556         if ($pgpshort || $pgpmove || $pgpmovevrf) { pgp($lines, \@vrb, \@hdr); }
557
558         # Remove all but the first attachment (if this is text/plain)
559         # mutt did introduce (bah!). Remember, all this ugliness could
560         # be replaced with a proper and clean edit_filter patch in 
561         # mutt(1) itself...
562         for ($x=$#$lines; $x>=0; $x--) {
563             if ($vrb[$x]) { next; }
564             # The following regexp's are quite ugly because for most users
565             # these lines are coloured using termcap... (bah!)
566             if (($$lines[$x] =~
567                      /^(?:\e[^\a]+\a)?\Q$mutt_attachment\E(\d+)/o &&
568                     (($1 ne '1') ||
569                     ($x<$#$lines &&
570                         $$lines[$x+1] !~ m!^
571                             (?:\e[^\a]+\a)?
572                             (?:\Q$mutt_contenttype\E)
573                             (?:text/plain|application/pgp)
574                         !ox))) ||
575                 ($$lines[$x] =~ /^
576                     (?:\e[^\a]+\a)?
577                     (?:\Q$mutt_pgpsigned\E     |
578                        \Q$mutt_pgpclearsigned\E|
579                        \Q$mutt_pgpencrypted\E)
580                 /ox))
581             { 
582                 # Strip attachments to prepare further processing
583                 unshift(@att, @$lines[$x..$#$lines]);
584                 splice(@$lines, $x);
585                 # Try to fix trailing empty lines
586                 while (scalar(@$lines) && $$lines[$#$lines] =~
587                     /^(?:\e[^\a]+\a)?\s*$/) { 
588                     unshift(@att, pop(@$lines));
589                 }
590
591                 # Remove ML and ad footers within attachments:
592                 my @tmp;
593                 if ($ml) { remove_footers($lines, \@tmp, $footers, undef); }
594                 if ($ad) { remove_footers($lines, \@tmp, $ads,     undef); }
595                 $x = scalar(@$lines);
596             }
597         }
598
599         # care about the rest
600         if (scalar(@att)) {
601             for ($x=0; $x<$#att; $x++) {
602                 if ($vrb[scalar(@$lines)+$x]) { next; }
603
604                 # Pipe message/rfc822 parts to another instance of
605                 # process_msg() for further processing.
606                 # Please note that we cannot see what a hierarchy the
607                 # original message had -- if there were message/rfc822
608                 # parts within other message/rfc822 parts constellations
609                 # can occur which we cannot resolve. Therefore we simply
610                 # do not even try to be smart. This should work for most
611                 # situations.
612                 # The following regexp is quite ugly because for most
613                 # users the line is coloured using termcap... (bah!)
614                 if ($att[$x] =~
615                         /^(?:\e[^\a]+\a)?\Q$mutt_attachment\E\d+/o &&
616                     $att[$x+1] =~ m!^
617                         (?:\e[^\a]+\a)?
618                         (?:\Q$mutt_contenttype\E) (?:message/rfc822|multipart/alternative)
619                     !ox)
620                 {
621                     $x += 2;
622                     while ($att[$x] !~ /^\s*$/) { $x++; }
623                     $x++;
624
625                     my @tmp = @att[$x..$#att];
626                     process_msg(\@tmp);
627                     splice(@att, $x, scalar(@att)-$x, @tmp);
628                     $x += scalar(@tmp);
629                 }
630             }
631         }
632     }
633
634     # Remove signature:
635     if (scalar(@$lines)) { 
636         my $sn = 0;
637         my $chk_empty = 1;
638         my $empty = 0;
639
640         for ($x = $#$lines; $x>=0; $x--) {
641             if (!$vrb[$x]) {
642                 if ($$lines[$x] =~ /^-- $/) {
643                     if ($diff) {
644                         for (my $i=1; $x+$i+1<scalar(@$lines); $i++) {
645                             if ($$lines[$x+$i] =~ /^-{3}\s+\S/ &&
646                                 $$lines[$x+$i+1] =~ /^\+{3}\s+\S/)
647                             {
648                                 $sig = 0;
649                                 unshift(@sig, @$lines[$x..$#$lines]);
650                                 splice(@$lines, $x);
651                                 last;
652                             }
653                         }
654                         if (scalar(@sig)) {
655                             if (defined($sign) && ++$sn==$sign) { last; } else { next; }
656                         }
657                     }
658
659                     if ($sig || ($lsig && ($#$lines-$x-$empty>$lsig))) {
660                         if ($lsig && !$sig) {
661                             unshift(@sig, "[---=| Overlong signature removed by $0: " .
662                                 (scalar(@$lines)-$x) . " lines snipped |=---]\n");
663                         }
664                         splice(@$lines, $x);
665                     }
666                     else {
667                         unshift(@sig, @$lines[$x..$#$lines]);
668                         splice(@$lines, $x);
669                     }
670                     if (defined($sign) && ++$sn==$sign) { last; } else { next; }
671                 }
672                 # any trailing newlines?
673                 elsif ($chk_empty && $$lines[$x] =~ /^\s*$/) { $empty++; }
674                 elsif ($chk_empty) { $chk_empty = 0; }
675             }
676         }
677     }
678
679     # See if there is some Kammquoting to fix:
680     if ($kamm) { decomb($lines, \@vrb); }
681
682     # Now care about TOFU.
683     # One common mispractice is M$ style TOFU:
684     if ($ms) {
685         # bloat this array if you want more internationalization:
686         my @tofu = ('Original Message',
687                     'Original-Nachricht',
688                     'Ursprüngliche Nachricht',
689                     'Ursprungliche Nachricht',
690                     'Mensagem original',
691                     'Ursprungligt meddelande',
692                     'Oorspronkelijk bericht',
693                     'Message d\'origine',
694                     'Forwarded message',
695                     'Weitergeleitete Nachricht / Forwarded Message');
696         my $k = 0;    # any text above?
697         my $tmp = 0;  # flagged if inside PGP output
698
699         DONE: for ($x=0; $x<scalar(@$lines); $x++) { 
700             if (!$vrb[$x]) {
701                 foreach my $tmp (@tofu) {
702                     if ($$lines[$x] =~ /^-+\s?$tmp\s?-+/) { 
703                         $x++;
704                         $trad = 0;
705                         $bigqn = 0;
706                         last DONE; 
707                     }
708                 }
709
710                 if ((!$k) && $$lines[$x] !~ /^\s*$/o &&
711                     ((!$mua) ||
712                      ($mua eq 'mutt' &&
713                          $$lines[$x] !~
714                              /^(?:\e[^\a]+\a)?(?:\Q$mutt_attachment\E)/o &&
715                          $$lines[$x] !~
716                              /^(?:\e[^\a]+\a)?(?:\Q$mutt_contenttype\E)/o)) &&
717                     ((!$spass) || index($$lines[$x], $spass_prefix)!=0))
718                 {
719                     if ($mua eq 'mutt' && (!$tmp) &&
720                         $$lines[$x] =~
721                              /^(?:\e[^\a]+\a)?(?:\Q$mutt_pgpoutstart\E)/o) {
722                         $tmp = 1; 
723                     } elsif ($mua eq 'mutt' && $tmp && 
724                         ($$lines[$x] =~
725                              /^(?:\e[^\a]+\a)?(?:\Q$mutt_beginsigned\E)/o ||
726                          $$lines[$x] =~
727                              /^(?:\e[^\a]+\a)?(?:\Q$mutt_pgpclearsigstart\E)/o)) {
728                         $tmp = 0;
729                     } elsif (!$tmp) {
730                         $k = 1;
731                     }
732                 }
733             }
734         }
735
736         # try to avoid false positives and only delete m$ style tofu if
737         # there is text above
738         if ($k) {
739             if (!$ms_smart) { goto CLEAN; }
740
741             # first, see if there is pgp stuff inside the tofu:
742             my $p = 0;    # levels of pgp signed parts
743
744             for (my $i=$x+1; $i<scalar(@$lines); $i++) {
745                 if ($$lines[$i] =~
746                         /^(?:\e[^\a]+\a)?(?:\Q$mutt_pgpclearsigstart\E)/o) {
747                     $p++;
748                 }
749             }
750             if ($p) {
751                 STAIRS: for (my $i=0; $i<scalar(@att); $i++) {
752                     if ($p==0 && $att[$i] =~ /^(?:\e[^\a]+\a)?\[-- /o) {
753                         splice(@att, 0, $i);
754                         unshift(@att, "\n");
755                         goto CLEAN;
756                     } elsif ($att[$i] =~
757                             /^(?:\e[^\a]+\a)?(?:\Q$mutt_pgpclearsigned\E)/o) {
758                         splice(@att, 0, $i+1);
759                         $p--;
760                         goto STAIRS;
761                     }
762                 }
763                 splice(@att);
764             }
765
766             # now removing is safe:
767             CLEAN: $j = scalar(@$lines)-$x;
768             splice(@$lines, $x);
769         }
770     }
771
772     # Nothing? Then try traditional TOFU (deleting M$ style TOFU is done
773     # much more aggressively, so we won't need to search any more if we
774     # did find some):
775     if ($trad && (!$j) && !$vrb[$#$lines]) {
776         if (scalar(@$lines) && $$lines[$#$lines] =~ /^\s*$/) { 
777             unshift(@sig, pop(@$lines));
778         }
779
780         my $k;
781         my $x = 1;
782
783         for (my $i=$#$lines; $i>=0; $i--) {
784             if ($$lines[$i] =~ /^$indent/o) {
785                 $j++;
786                 $k = $i;
787             }
788             elsif ($$lines[$i] !~ /^\s*$/) { last; }
789         }
790
791         if ($j) {
792             # if there is no text above, we will assume the message is meant
793             # as forwarding and therefore OK
794             for (my $i=$k-1; $i>=0; $i--) {
795                 if ($$lines[$i] !~ /^\s*$/o) {
796                    $x = 0;
797                    last;
798                 }
799             }
800             if ($x) {
801                 $j = 0;
802             } else {
803                 splice(@$lines, $k);
804             }
805         }
806     }
807
808     # OK, if we found TOFU, we will leave a message that we were here...
809     if ($j) { 
810         # make sendmail bounce if we shall be picky 
811         # and indeed found something:
812         if ($mda) { 
813             if ($mda ne '1') { 
814                 print STDERR $boun;
815
816                 if ($sysl) {
817                     eval { require Sys::Syslog; }; 
818                     if ($@) { warn $@; } else {
819                         Sys::Syslog::setlogsock('unix');
820                         Sys::Syslog::openlog("$0[$$]", 'pid', 'mail');
821                         Sys::Syslog::syslog('debug', 'bounced message %s', $hdr[0]);
822                         Sys::Syslog::closelog();
823                     }
824                 }
825             }
826
827             exit EX_BOUNCE;
828         }
829
830         # if we were invoked just for checking and indeed found something,
831         # print out the error message and quit:
832         if ($check) {
833             print $msg_quote;
834             exit EX_UNAVAILABLE;
835         }
836
837         push(@$lines, "[---=| TOFU protection by $0: " .
838             "$j lines snipped |=---]\n");
839     }
840     elsif ($mda eq '1') { exit EX_OK; }
841
842     # Care for huge blocks of quoted original message:
843     if ($bigqn) { debigq($lines, \@vrb); }
844
845     # Care for trailing whitespaces:
846     if ($trsp) {
847         for ($x=0; $x<scalar(@$lines); $x++) { 
848             if (!$vrb[$x]) { $$lines[$x] =~ s/[\ \t]+$//; }
849         }
850     }
851
852     # Care for punctuation abuse:
853     if ($elli) {
854         for ($x=0; $x<scalar(@$lines); $x++) { 
855             if (!$vrb[$x]) { $$lines[$x] =~ s/(([.?!])\2\2)\2+/$1/g; }
856         }
857     }
858
859     # (Nearly) at last care for multiple blank lines. (Do not do this
860     # earlier -- the way it is done right now would screw up the verbatim
861     # list)
862     if ($cr) {
863         my $t = 0;
864         for ($x=scalar(@$lines)-1; $x>=0; $x--) {
865             if ((!$vrb[$x]) && $$lines[$x] =~ /^\s*$/) { 
866                 if ($t<2) { $t++; } else { splice(@$lines, $x, 1); }
867             }
868             else { $t = 0; }
869         }
870     }
871
872     # Everything changing the body is done now. Time to fix the line count
873     # header so naive clients do not get confused. Just to be sure, append
874     # the old line count to X-headers.
875     my $l = scalar(@bo1) + scalar(@$lines) + scalar(@att) + scalar(@bo2) +
876                 (!$sig?scalar(@sig):0) + (!$ml?scalar(@ftr):0) + 
877                 (!$ad?scalar(@ads):0);
878     if ($linecount-$l!=0) {
879         for ($x=0; $x<scalar(@hdr); $x++) {
880             if ($hdr[$x] =~ 
881                 s/^(Lines:\s+)(\d+)/$1.($2-$linecount+$l)/e)
882             { 
883                 $hdr[$#hdr] = "X-Old-Lines: $2\n";
884                 push(@hdr, "\n");
885             }
886         }
887     }
888
889     # Finally, before leaving we put everything back in right order.
890     unshift(@$lines, (!$hdrs?@hdr:()), @bo1);
891     push(@$lines, (!$sig?@sig:()), (!$ad?@ads:()), (!$ml?@ftr:()), @att,
892         @bo2);
893 }
894
895
896 # environment
897 my $locale = $ENV{'LC_ALL'}?$ENV{'LC_ALL'}:($ENV{'LC_MESSAGES'}?$ENV{'LC_MESSAGES'}:$ENV{'LANG'});
898
899 # command line switches
900 ($ad, $ads, $bigqn, $bigqx, $check, $cr, $sysl, $diff, $elli, $footers, $lax,
901     $ml, $ms, $ms_smart, $mda, $mua, $hdrs, $kamm, $lsig, $nohdr, $sig, $sigint,
902     $spass, $trad, $trsp) =
903     (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
904 my $ifile   = '-';    # use STDIN if nothing specified
905
906 # get command line params:
907 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'.
908     ' s t v w bigq:s body check:s debug>d diff ftr-ad ftr-ml help>h'.
909     ' kminl=i kmaxl=i kdiff=i lax-security locale=s ms-smart mua>M'.
910     ' pgp-short pgp-move pgp-move-vrf sigsmax:i spass version>v');
911 while (my ($opt, $val, $pretty) = nextOption()) {
912     if    ($opt eq 'a')     { $ad = 1; }
913     elsif ($opt eq 'A')     { $ads = $val; }
914     elsif ($opt eq 'bigq')  { 
915         if ($val !~ /^(?:(\d+)(?:,(\d+))?)?$/) { help(); }
916         $bigqn = $1?$1:30; 
917         $bigqx = $2?$2:10;
918         if ($bigqn<=0 || $bigqx<=0 || $bigqn<=$bigqx) { help(); }
919     }
920     elsif ($opt eq 'body')  { $nohdr = 1; $hdrs = 1; }
921     elsif ($opt eq 'c')     { $cr = 1; }
922     elsif ($opt eq 'check') {
923         $check = 1;
924         while ($val && $val =~ s/^([^,\s]+)(?:,(\S+))?$/$2/) {
925             my $foo = $1;
926
927             if ($foo =~ /^ratio=(0?\.\d+)$/) {
928                 $check_ratio = $1?$1:1;
929             }
930         }
931     }
932     elsif ($opt eq 'd')     { $sysl = 1; }
933     elsif ($opt eq 'diff')  { $diff = 1; }
934     elsif ($opt eq 'e')     { $elli = 1; }
935     elsif ($opt eq 'ftr-ad') { $ftr_ad = 1; $ad = 1; }
936     elsif ($opt eq 'ftr-ml') { $ftr_ml = 1; $ml = 1; }
937     elsif ($opt eq 'i')     { $ifile = $val; }
938     elsif ($opt eq 'k')     { $kamm = 1; }
939     elsif ($opt eq 'kminl') { $kminl = $val; $kamm = 1; }
940     elsif ($opt eq 'kmaxl') { $kmaxl = $val; $kamm = 1; }
941     elsif ($opt eq 'kdiff') { $kdiff = $val; $kamm = 1; }
942     elsif ($opt eq 'L')     { $footers = $val; }
943     elsif ($opt eq 'l')     { $ml = 1; }
944     elsif ($opt eq 'lax-security') { $lax = 1; }
945     elsif ($opt eq 'locale') { $locale = $val; }
946     elsif ($opt eq 'm')     { $ms = 1; }
947     elsif ($opt eq 'ms-smart') { $ms_smart = 1; $ms = 1; }
948     elsif ($opt eq 'M') {
949         $mua = lc($val);
950
951         if ($mua eq 'mutt') {
952             # mutt still displays the message when ^C'ing pgp verification:
953             $SIG{'INT'} = 'sigint_handler';
954         }
955     }
956     elsif ($opt eq 'o')     { $ofile = $val; }
957     elsif ($opt eq 'P')     { $boun = $val; }
958     elsif ($opt eq 'p')     { $mda = $val ? $val : '1'; }
959     elsif ($opt eq 'pgp-short') { $pgpshort = 1; }
960     elsif ($opt eq 'pgp-move') { $pgpmove = 1; }
961     elsif ($opt eq 'pgp-move-vrf') { $pgpmovevrf = 1; }
962     elsif ($opt eq 'r')     { $hdrs = 1; }
963     elsif ($opt eq 'S')     { $lsig = $val ? $val : $maxsig; }
964     elsif ($opt eq 's')     { $sig = 1; }
965     elsif ($opt eq 'sigsmax') { $sign = $val ? $val : undef; }
966     elsif ($opt eq 'spass') { $spass = 1; }
967     elsif ($opt eq 't')     { $trad = 1; }
968     elsif ($opt eq 'v')     { version(); }
969     elsif ($opt eq 'w')     { $trsp = 1; }
970     else                    { help(); }
971 }
972 Getopt::Mixed::cleanup();
973 if (($ml && $footers eq '')||    # no -l without -L
974     ($ad && $ads eq '')||        # no -a without -A
975     ($nohdr && $pgpshort)||      # --body and --pgp-short are like oil and water
976     ($ifile eq '')||             # no empty -i
977     ($ofile eq ''))              # no empty -o
978 { help(); }
979
980
981 if ($mua eq 'mutt') {
982     if (defined $locale && $locale ne '' && $locale ne 'C' && $locale ne 'POSIX') {
983         eval { require Locale::gettext; };
984         if ($@) { warn $@; exit(EX_SOFTWARE); } else {
985             Locale::gettext::textdomain('mutt');
986             ($mutt_attachment) =
987                 Locale::gettext::gettext("[-- Attachment #%d") =~
988                 m/^([^%]*)/;
989             ($mutt_contenttype) =
990                 Locale::gettext::gettext("[-- Type: %s/%s, Encoding: %s, Size: %s --]\n") =~
991                 m/^([^%]*)/;
992             ($mutt_pgpsigned) =
993                 Locale::gettext::gettext("[-- End of signed data --]\n")  =~
994                 m/^(.*)\n/m;
995             ($mutt_beginsigned) =
996                 Locale::gettext::gettext("[-- The following data is signed --]\n\n") =~
997                 m/^(.*)\n/m;
998             ($mutt_pgpclearsigned) =
999                 Locale::gettext::gettext("[-- END PGP SIGNED MESSAGE --]\n") =~
1000                 m/^(.*)\n/m;
1001             ($mutt_pgpclearsigstart) =
1002                 Locale::gettext::gettext("[-- BEGIN PGP SIGNED MESSAGE --]\n") =~
1003                 m/^(.*)\n/m;
1004             ($mutt_pgpencrypted) =
1005                 Locale::gettext::gettext("[-- End of PGP/MIME encrypted data --]\n") =~
1006                 m/^(.*)\n/m;
1007             ($mutt_pgpoutstart) =
1008                 Locale::gettext::gettext("[-- PGP output follows (current time: %c) --]\n") =~
1009                 m/^([^%]*)/;
1010             ($mutt_pgpoutend) =
1011                 Locale::gettext::gettext("[-- End of PGP output --]\n") =~
1012                 m/^(.*)\n/m;
1013
1014             Locale::gettext::textdomain('gnupg');
1015             ($gpg_WARNING) =
1016                 Locale::gettext::gettext("WARNING: using insecure random number generator!!\n") =~
1017                 m/^([^:]*: )/;
1018             ($gpg_Warning) =
1019                 Locale::gettext::gettext("WARNING: message was encrypted with a weak key in the symmetric cipher.\n") =~
1020                 m/^([^:]*: )/;
1021             ($gpg_Cantcheck) =
1022                 Locale::gettext::gettext("Can't check signature: %s\n") =~
1023                 m/^([^%]*)/;
1024             ($gpg_aka) =
1025                 Locale::gettext::gettext((' 'x16).'aka "%s"') =~
1026                 m/^([^"«%]*)["«%]/;
1027             ($gpg_bad) =
1028                 Locale::gettext::gettext('BAD signature from "%s"') =~
1029                 m/^([^"«%]*)["«%]/;
1030             ($gpg_expired) =
1031                 Locale::gettext::gettext("Note: This key has expired!\n") =~
1032                 m/^(.*)\n/m;
1033             ($gpg_good) =
1034                 Locale::gettext::gettext('Good signature from "%s"') =~
1035                 m/^(([^"«%]*))["«%]/;
1036             ($gpg_bug) =
1037                 Locale::gettext::gettext("... this is a bug (%s:%d:%s)\n") =~
1038                 m/^([^%]*)/;
1039         }
1040     }
1041
1042 }
1043 else {
1044     if ($ms_smart || $pgpshort || $pgpmove || $pgpmovevrf) { help(); }
1045 }
1046
1047
1048 # Read message:
1049 if (!open(IN, $ifile)) { print STDERR "Could not open $ifile: $!\n"; exit(EX_IOERR); }
1050 my @message = <IN>;
1051 close IN;
1052
1053 # this should be self-explanatory:
1054 process_msg(\@message);
1055
1056 # Finally, print clean lines:
1057 if ($ofile ne 'NONE') {
1058     write_msg(($mda?'|'.SENDMAIL." $mda":">$ofile"), \@message);
1059 }
1060
1061 # vim600:set foldmethod=marker:
1062 # eof