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 my $ctype = Mail::Field->new('Content-Type', $ARGV[0]);
72 $content_type = $ctype->type;
73 $charset = $ctype->charset;
74 $boundary = $ctype->boundary;
76 $content_type = 'text/plain';
77 $charset = 'us-ascii';
80 $encoding = $ARGV[1] eq "" ? '7bit' : lc($ARGV[1]);
81 $quoteprefix = $ARGV[2];
84 # Set up our output to be in our character set
87 binmode(STDOUT, ":encoding($outcharset)");
90 # The simplest case: if we have a single type of text/plain, send it
91 # to our format subroutine.
94 if ($content_type eq 'text/plain') {
95 process_text(\*STDIN, $encoding, $charset);
100 # Alright, here's what we need to do.
102 # Find any text/plain parts and decode them. Decode them via base64 or
103 # quoted-printable, and feed them to our formatting filter when appropriate.
104 # Put markers in the output for other content types.
107 ($type) = (split('/', $content_type));
109 if ($type eq 'multipart') {
112 # For multipart messages we have to do a little extra.
113 # Eat the MIME prologue (everything up until the first boundary)
116 if (! defined $boundary || $boundary eq '') {
117 print "No boundary in Content-Type header!\n";
123 last if match_boundary($_, $boundary);
127 print "Unable to find boundary in message\n";
134 process_part(\*STDIN, $content_type, $encoding, $charset, $boundary);
138 # Eat the MIME epilog
146 # Handled encoded text. I think we can assume if the encoding is q-p
147 # or base64 to feed it into a formatting filter.
150 sub process_text (*$$;$)
152 my ($input, $encoding, $charset, $boundary) = @_;
153 my $text, $filterpid, $prefixpid, $finread, $finwrite;
154 my $foutread, $foutwrite, $decoder, $ret, $filterflag;
155 my @text = ( '' ), $maxline = 0;
158 # In the simple case, just spit out the text prefixed by the
162 if ($encoding eq '7bit' || $encoding eq '8bit') {
164 # Switch the character set to whatever is specified by
167 binmode($input, ":encoding($charset)");
169 $ret = match_boundary($_, $boundary);
173 print $quoteprefix, $_;
178 # If we've got some other encoding, the input text is almost
182 binmode($input, ":encoding(us-ascii)");
184 $decoder = find_decoder($encoding);
185 if (! defined $decoder) {
191 # Okay, assume that the encoding will make it so that we MIGHT need
192 # to filter it. Read it in; if it's too long, filter it.
195 my $chardecode = find_encoding($charset);
200 last if ($ret = match_boundary($_, $boundary));
202 $line = $chardecode->decode(&$decoder($_));
204 if (substr($text[$#text], -1, 1) eq "\n") {
207 $text[$#text] .= $line;
209 if (($len = length($text[$#text])) > $maxline) {
214 if (! defined $ret) {
218 if ($maxline <= $maxcolwidth) {
220 # These are short enough; just output it now as-is
227 # We fork a copy of ourselves to read the output from the filter
228 # program and prefix the quote character.
231 pipe($finread, $finwrite) || die "pipe() failed: $!\n";
232 pipe($foutread, $foutwrite) || die "pipe() (second) failed: $!\n";
234 binmode($finread, ":encoding($outcharset)");
235 binmode($finwrite, ":encoding($outcharset)");
236 binmode($foutread, ":encoding($outcharset)");
237 binmode($foutwrite, ":encoding($outcharset)");
239 if ($filterpid = fork) {
241 # Close the pipes in the parent that we're not using
246 } elsif (defined $filterpid) {
248 # Close our ununsed filehandles
255 # Dup() down the filehandles to standard input and output
258 open(STDIN, "<&", $finread) ||
259 die "dup(filterin) failed: $!\n";
260 open(STDOUT, ">&", $foutwrite) ||
261 die "dup(filterout) failed: $!\n";
274 exec $filterprogram ||
275 die "Unable to exec $filterprogram: $!\n";
277 die "Fork for $filterprogram failed: $!\n";
281 # Fork our output handler.
284 if ($prefixpid = fork) {
286 # We don't need these anymore
290 } elsif (defined $prefixpid) {
292 # Read from foutwrite, and output (with prefix) to stdout
297 while (<$foutread>) {
298 print STDOUT $quoteprefix, $_;
305 # Send our input to the filter program
308 print $finwrite @text;
311 waitpid $filterpid, 0;
312 warn "Filter process exited with ", ($? >> 8), "\n" if $?;
313 waitpid $prefixpid, 0;
314 warn "Pipe reader process exited with ", ($? >> 8), "\n" if $?;
320 # Filter HTML through a converter program
323 sub process_html (*$$;$)
325 my ($input, $encoding, $charset, $boundary) = @_;
326 my $filterpid, $prefixpid, $finread, $finwrite;
327 my $foutread, $foutwrite, $decoder, $ret;
329 if (! defined($decoder = find_decoder($encoding))) {
334 # We fork a copy of ourselves to read the output from the filter
335 # program and prefix the quote character.
338 pipe($finread, $finwrite) || die "pipe() failed: $!\n";
339 pipe($foutread, $foutwrite) || die "pipe() (second) failed: $!\n";
341 binmode($finread, ":encoding($outcharset)");
342 binmode($finread, ":encoding($outcharset)");
343 binmode($foutread, ":encoding($outcharset)");
344 binmode($foutwrite, ":encoding($outcharset)");
346 if ($filterpid = fork) {
348 # Close the pipes in the parent that we're not using
353 } elsif (defined $filterpid) {
355 # Close our ununsed filehandles
362 # Dup() down the filehandles to standard input and output
365 open(STDIN, "<&", $finread) ||
366 die "dup(filterin) failed: $!\n";
367 open(STDOUT, ">&", $foutwrite) ||
368 die "dup(filterout) failed: $!\n";
382 die "Unable to exec $filterprogram: $!\n";
384 die "Fork for $htmlconv[0] failed: $!\n";
388 # Fork our output handler.
391 if ($prefixpid = fork) {
393 # We don't need these anymore
397 } elsif (defined $prefixpid) {
399 # Read from foutwrite, and output (with prefix) to stdout
404 while (<$foutread>) {
405 print STDOUT $quoteprefix, $_;
412 # Send our input to the filter program
416 last if ($ret = match_boundary($_, $boundary));
417 print $finwrite (&$decoder($_));
420 if (! defined $ret) {
425 waitpid $filterpid, 0;
426 warn "HTML converter process exited with ", scalar($? >> 8), "\n" if $?;
427 waitpid $prefixpid, 0;
428 warn "Pipe reader process exited with ", $? >> 8, "\n" if $?;
434 # Decide what to do, based on what kind of content it is.
437 sub process_part (*$$$$;$)
439 my ($input, $content_type, $encoding, $charset, $boundary, $name) = @_;
440 my ($type, $subtype) = (split('/', $content_type, -1), '');
442 if ($type eq 'text') {
444 # If this is a text part, right now we only deal with
445 # plain and HTML parts.
447 if ($subtype eq 'plain') {
448 return process_text($input, $encoding, $charset,
450 } elsif ($subtype eq 'html') {
451 return process_html($input, $encoding, $charset,
454 print ">>> $content_type content\n";
455 return eat_part($input, $boundary);
457 } elsif ($type eq 'multipart') {
458 return process_multipart($input, $subtype, $boundary);
461 # Other types we're not sure what to do with right now
462 # Just put a marker in there
465 print ">>> $content_type attachment";
467 print ", name=$name";
471 return eat_part($input, $boundary);
476 # Process a multipart message.
478 # When called, we should be right after the beginning of the first
479 # boundary marker. So we should be pointed at header lines which describe
480 # the content of this part
483 sub process_multipart ($$$)
485 my ($input, $subtype, $boundary) = @_;
489 my $encoding, $type, $end, $name, $charset;
492 # Use the Mail::Header package to read in any headers
493 # corresponding to this part
496 my $head = Mail::Header->new($input, (MailFrom => 'IGNORE'));
499 # Extract out any Content-Type, Content-Transfer-Encoding, and
500 # Content-Disposition headers
503 my $ctype = Mail::Field->extract('Content-Type', $head);
504 my $cte = Mail::Field->extract('Content-Transfer-Encoding',
506 my $cdispo = Mail::Field->extract('Content-Disposition', $head);
508 if (defined $ctype) {
509 $type = $ctype->type;
510 $charset = $ctype->charset;
512 $type = 'text/plain';
513 $charset = 'us-ascii';
516 $encoding = defined $cte ? $cte->param('_') : '7bit';
517 $name = defined $cdispo ? $cdispo->param('filename') : undef;
520 # Special handling for multipart/alternative; pick
521 # the "first" one we can handle (which is usually
522 # text/plain) and silently eat the rest, but output a
523 # warning if we can't handle anything.
527 $end = eat_part($input, $boundary);
529 my $subboundary = $boundary;
530 my $maintype = (split('/', $type))[0];
532 if ($maintype eq 'multipart') {
533 $subboundary = $ctype->boundary;
535 # Go until we find our beginning of this
538 my $subend = eat_part($input, $subboundary);
540 if ($subend ne 'EOP') {
541 print ">>> WARNING: malformed ",
542 "nested multipart\n";
547 $end = process_part($input, $type, $encoding,
548 $charset, $subboundary, $name);
550 if ($subtype eq 'alternative' && ! defined $altout &&
551 $type eq 'text/plain') {
556 # Since we changed the semantics of $boundary
557 # above for nested multiparts, if we are
558 # handling a nested multipart then find the end
559 # of our current part
562 if ($maintype eq 'multipart') {
563 $end = eat_part($input, $boundary);
568 if ($end eq 'EOM' || $end eq 'EOF') {
569 if ($subtype eq 'alternative' && !defined $altout) {
570 print ">>>multipart/alternative: no suitable ",
579 # "Eat" a MIME part; consume content until we hit the boundary or EOF
584 my ($input, $boundary) = @_;
588 # If we weren't given a boundary just eat input until EOF
591 if (! defined $boundary) {
597 # Otherwise, consume data until we hit our boundary
601 if ($ret = match_boundary($_, $boundary)) {
610 # Return the decoder subroutine to use
617 if ($encoding eq '7bit' || $encoding eq '8bit') {
618 return \&null_decoder;
619 } elsif ($encoding eq 'base64') {
620 return \&decode_base64;
621 } elsif ($encoding eq 'quoted-printable') {
624 warn "Unknown encoding: $encoding\n";
637 # Match a line against the boundary string
640 sub match_boundary($$)
642 my ($_, $boundary) = @_;
644 if (substr($_, 0, 2) eq '--') {
646 if ($_ eq "--$boundary") {
648 } elsif ($_ eq "--$boundary--") {