3 # replyfilter - A reply filter for nmh
5 # The idea behind this program is that it will act as a format filter
6 # for nmh. It will try to extract out all text/plain parts and format
7 # them if necessary using a filter program.
9 # To use this program, configure nmh in the following way (nmh 1.5 or later):
11 # - Put the path to this program in your .mh_profile under formatproc:
13 # formatproc: replyfilter
15 # - Create a mhl reply filter that consists of the following line:
17 # body:nocomponent,format,nowrap,formatarg="%(trim{content-type})%(putstr)",formatarg="%(trim{content-transfer-encoding})%(putstr)",formatarg=">"
19 # To decode this a bit:
21 # body - Output the "body" component
22 # nocomponent - Don't output a component prefix (normally here we use a
23 # component prefix of ">" as a quote character, but we're
24 # going to have replyfilter do that).
25 # nowrap - Don't wrap lines if they exceed the column width
26 # formatarg - Arguments to fmtproc. The first argument is the value of
27 # the Content-type header; the second is the value of the
28 # Content-Transfer-Encoding header. The last "formatarg"
29 # is used as your quoting prefix. Replace it with whatever
35 use MIME::QuotedPrint;
40 # The program we use to format "long" text
43 $filterprogram = 'par';
46 # Our output character set. This script assumes a UTF-8 locale, but if you
47 # want to run under a different locale the change it here.
50 $outcharset = 'utf-8';
53 # Maximum column width (used by the HTML converter and to decide if we need
54 # to invoke the filter program
60 # Out HTML converter program & arguments
63 @htmlconv = ('w3m', '-dump', '-cols', $maxcolwidth - 2, '-T', 'text/html',
67 die "Usage: $0 Content-type content-transfer-encoding quote-prefix\n"
71 $content_type = Mail::Field->new('Content-Type', $ARGV[0]);
74 $encoding = $ARGV[1] eq "" ? '7bit' : lc($ARGV[1]);
75 $quoteprefix = $ARGV[2];
78 # Set up our output to be in our character set
81 binmode(STDOUT, ":encoding($outcharset)");
84 # The simplest case: if we have a single type of text/plain, send it
85 # to our format subroutine.
88 if ($ARGV[0] eq "" || $content_type->type eq 'text/plain') {
89 process_text(\*STDIN, $encoding, $content_type->charset);
94 # Alright, here's what we need to do.
96 # Find any text/plain parts and decode them. Decode them via base64 or
97 # quoted-printable, and feed them to our formatting filter when appropriate.
98 # Put markers in the output for other content types.
101 ($type) = (split('/', $content_type->type));
103 if ($type eq 'multipart') {
106 # For multipart messages we have to do a little extra.
107 # Eat the MIME prologue (everything up until the first boundary)
110 $boundary = $content_type->boundary;
112 if ($boundary eq '') {
113 print "No boundary in Content-Type header!\n";
119 last if match_boundary($_, $boundary);
123 print "Unable to find boundary in message\n";
130 process_part(\*STDIN, $content_type->type, $encoding, $content_type->charset,
135 # Eat the MIME eplilog
143 # Handled encoded text. I think we can assume if the encoding is q-p
144 # or base64 to feed it into a formatting filter.
147 sub process_text (*$$;$)
149 my ($input, $encoding, $charset, $boundary) = @_;
150 my $text, $filterpid, $prefixpid, $finread, $finwrite;
151 my $foutread, $foutwrite, $decoder, $ret, $filterflag;
152 my @text = ( '' ), $maxline = 0;
155 # In the simple case, just spit out the text prefixed by the
159 if ($encoding eq '7bit' || $encoding ne '8bit') {
161 $ret = match_boundary($_, $boundary);
165 print $quoteprefix, $_;
169 $decoder = find_decoder($encoding);
170 if (! defined $decoder) {
176 # Okay, assume that the encoding will make it so that we MIGHT need
177 # to filter it. Read it in; if it's too long, filter it.
183 last if ($ret = match_boundary($_, $boundary));
185 $line = decode($charset, &$decoder($_));
187 if (substr($text[$#text], -1, 1) eq "\n") {
190 $text[$#text] .= $line;
192 if (($len = length($text[$#text])) > $maxline) {
197 if (! defined $ret) {
201 if ($maxline <= $maxcolwidth) {
203 # These are short enough; just output it now as-is
210 # We fork a copy of ourselves to read the output from the filter
211 # program and prefix the quote character.
214 pipe($finread, $finwrite) || die "pipe() failed: $!\n";
215 pipe($foutread, $foutwrite) || die "pipe() (second) failed: $!\n";
217 binmode($finread, ":encoding($outcharset)");
218 binmode($finread, ":encoding($outcharset)");
219 binmode($foutread, ":encoding($outcharset)");
220 binmode($foutwrite, ":encoding($outcharset)");
222 if ($filterpid = fork) {
224 # Close the pipes in the parent that we're not using
229 } elsif (defined $filterpid) {
231 # Close our ununsed filehandles
238 # Dup() down the filehandles to standard input and output
241 open(STDIN, "<&", $finread) ||
242 die "dup(filterin) failed: $!\n";
243 open(STDOUT, ">&", $foutwrite) ||
244 die "dup(filterout) failed: $!\n";
257 exec $filterprogram ||
258 die "Unable to exec $filterprogram: $!\n";
260 die "Fork for $filterprogram failed: $!\n";
264 # Fork our output handler.
267 if ($prefixpid = fork) {
269 # We don't need these anymore
273 } elsif (defined $prefixpid) {
275 # Read from foutwrite, and output (with prefix) to stdout
280 while (<$foutread>) {
281 print STDOUT $quoteprefix, $_;
288 # Send our input to the filter program
291 print $finwrite @text;
294 waitpid $filterpid, 0;
295 warn "Filter process exited with ", ($? >> 8), "\n" if $?;
296 waitpid $prefixpid, 0;
297 warn "Pipe reader process exited with ", ($? >> 8), "\n" if $?;
303 # Filter HTML through a converter program
306 sub process_html (*$$;$)
308 my ($input, $encoding, $charset, $boundary) = @_;
309 my $filterpid, $prefixpid, $finread, $finwrite;
310 my $foutread, $foutwrite, $decoder, $ret;
312 if (! defined($decoder = find_decoder($encoding))) {
317 # We fork a copy of ourselves to read the output from the filter
318 # program and prefix the quote character.
321 pipe($finread, $finwrite) || die "pipe() failed: $!\n";
322 pipe($foutread, $foutwrite) || die "pipe() (second) failed: $!\n";
324 binmode($finread, ":encoding($outcharset)");
325 binmode($finread, ":encoding($outcharset)");
326 binmode($foutread, ":encoding($outcharset)");
327 binmode($foutwrite, ":encoding($outcharset)");
329 if ($filterpid = fork) {
331 # Close the pipes in the parent that we're not using
336 } elsif (defined $filterpid) {
338 # Close our ununsed filehandles
345 # Dup() down the filehandles to standard input and output
348 open(STDIN, "<&", $finread) ||
349 die "dup(filterin) failed: $!\n";
350 open(STDOUT, ">&", $foutwrite) ||
351 die "dup(filterout) failed: $!\n";
365 die "Unable to exec $filterprogram: $!\n";
367 die "Fork for $htmlconv[0] failed: $!\n";
371 # Fork our output handler.
374 if ($prefixpid = fork) {
376 # We don't need these anymore
380 } elsif (defined $prefixpid) {
382 # Read from foutwrite, and output (with prefix) to stdout
387 while (<$foutread>) {
388 print STDOUT $quoteprefix, $_;
395 # Send our input to the filter program
399 last if ($ret = match_boundary($_, $boundary));
400 print $finwrite (&$decoder($_));
403 if (! defined $ret) {
408 waitpid $filterpid, 0;
409 warn "HTML converter process exited with ", scalar($? >> 8), "\n" if $?;
410 waitpid $prefixpid, 0;
411 warn "Pipe reader process exited with ", $? >> 8, "\n" if $?;
417 # Decide what to do, based on what kind of content it is.
420 sub process_part (*$$$$;$)
422 my ($input, $content_type, $encoding, $charset, $boundary, $name) = @_;
423 my ($type, $subtype) = (split('/', $content_type, -1), '');
425 if ($type eq 'text') {
427 # If this is a text part, right now we only deal with
428 # plain and HTML parts.
430 if ($subtype eq 'plain') {
431 return process_text($input, $encoding, $charset,
433 } elsif ($subtype eq 'html') {
434 return process_html($input, $encoding, $charset,
437 print ">>> $content_type content\n";
438 return eat_part($input, $boundary);
440 } elsif ($type eq 'multipart') {
441 return process_multipart($input, $subtype, $boundary);
444 # Other types we're not sure what to do with right now
445 # Just put a marker in there
448 print ">>> $content_type attachment";
450 print ", name=$name";
454 return eat_part($input, $boundary);
459 # Process a multipart message.
461 # When called, we should be right after the beginning of the first
462 # boundary marker. So we should be pointed at header lines which describe
463 # the content of this part
466 sub process_multipart ($$$)
468 my ($input, $subtype, $boundary) = @_;
472 my $encoding, $type, $end, $name, $charset;
475 # Use the Mail::Header package to read in any headers
476 # corresponding to this part
479 my $head = Mail::Header->new($input, (MailFrom => 'IGNORE'));
482 # Extract out any Content-Type, Content-Transfer-Encoding, and
483 # Content-Disposition headers
486 my $ctype = Mail::Field->extract('Content-Type', $head);
487 my $cte = Mail::Field->extract('Content-Transfer-Encoding',
489 my $cdispo = Mail::Field->extract('Content-Disposition', $head);
491 if (defined $ctype) {
492 $type = $ctype->type;
493 $charset = $ctype->charset;
495 $type = 'text/plain';
496 $charset = 'us-ascii';
499 $encoding = defined $cte ? $cte->param('_') : '7bit';
500 $name = defined $cdispo ? $cdispo->param('filename') : undef;
503 # Special handling for multipart/alternative; pick
504 # the "first" one we can handle (which is usually
505 # text/plain) and silently eat the rest, but output a
506 # warning if we can't handle anything.
510 $end = eat_part($input, $boundary);
512 my $subboundary = $boundary;
513 my $maintype = (split('/', $type))[0];
515 if ($maintype eq 'multipart') {
516 $subboundary = $ctype->boundary;
518 # Go until we find our beginning of this
521 my $subend = eat_part($input, $subboundary);
523 if ($subend ne 'EOP') {
524 print ">>> WARNING: malformed ",
525 "nested multipart\n";
530 $end = process_part($input, $type, $encoding,
531 $charset, $subboundary, $name);
533 if ($subtype eq 'alternative' && ! defined $altout &&
534 $type eq 'text/plain') {
539 # Since we changed the semantics of $boundary
540 # above for nested multiparts, if we are
541 # handling a nested multipart then find the end
542 # of our current part
545 if ($maintype eq 'multipart') {
546 $end = eat_part($input, $boundary);
551 if ($end eq 'EOM' || $end eq 'EOF') {
552 if ($subtype eq 'alternative' && !defined $altout) {
553 print ">>>multipart/alternative: no suitable ",
562 # "Eat" a MIME part; consume content until we hit the boundary or EOF
567 my ($input, $boundary) = @_;
571 # If we weren't given a boundary just eat input until EOF
574 if (! defined $boundary) {
580 # Otherwise, consume data until we hit our boundary
584 if ($ret = match_boundary($_, $boundary)) {
593 # Return the decoder subroutine to use
600 if ($encoding eq '7bit' || $encoding eq '8bit') {
601 return \&null_decoder;
602 } elsif ($encoding eq 'base64') {
603 return \&decode_base64;
604 } elsif ($encoding eq 'quoted-printable') {
607 warn "Unknown encoding: $encoding\n";
620 # Match a line against the boundary string
623 sub match_boundary($$)
625 my ($_, $boundary) = @_;
627 if (substr($_, 0, 2) eq '--') {
629 if ($_ eq "--$boundary") {
631 } elsif ($_ eq "--$boundary--") {