]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/WwwAttach.pm
treewide: run update-copyrights from gnulib for 2019
[public-inbox.git] / lib / PublicInbox / WwwAttach.pm
1 # Copyright (C) 2016-2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # For retrieving attachments from messages in the WWW interface
5 package PublicInbox::WwwAttach; # internal package
6 use strict;
7 use warnings;
8 use bytes (); # only for bytes::length
9 use Email::MIME::ContentType qw(parse_content_type);
10 use PublicInbox::MIME;
11 use PublicInbox::MsgIter;
12
13 sub get_attach_i { # msg_iter callback
14         my ($part, $depth, @idx) = @{$_[0]};
15         my $res = $_[1];
16         return if join('.', @idx) ne $res->[3]; # $idx
17         $res->[0] = 200;
18         my $ct = $part->content_type;
19         $ct = parse_content_type($ct) if $ct;
20
21         # discrete == type, we remain Debian wheezy-compatible
22         if ($ct && (($ct->{discrete} || '') eq 'text')) {
23                 # display all text as text/plain:
24                 my $cset = $ct->{attributes}->{charset};
25                 if ($cset && ($cset =~ /\A[a-zA-Z0-9_\-]+\z/)) {
26                         $res->[1]->[1] .= qq(; charset=$cset);
27                 }
28         } else { # TODO: allow user to configure safe types
29                 $res->[1]->[1] = 'application/octet-stream';
30         }
31         $part = $part->body;
32         push @{$res->[1]}, 'Content-Length', bytes::length($part);
33         $res->[2]->[0] = $part;
34 }
35
36 # /$LISTNAME/$MESSAGE_ID/$IDX-$FILENAME
37 sub get_attach ($$$) {
38         my ($ctx, $idx, $fn) = @_;
39         my $res = [ 404, [ 'Content-Type', 'text/plain' ], [ "Not found\n" ] ];
40         my $mime = $ctx->{-inbox}->msg_by_mid($ctx->{mid}) or return $res;
41         $mime = PublicInbox::MIME->new($mime);
42         $res->[3] = $idx;
43         msg_iter($mime, \&get_attach_i, $res, 1);
44         pop @$res; # cleanup before letting PSGI server see it
45         $res
46 }
47
48 1;