1 # Copyright (C) all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # For retrieving attachments from messages in the WWW interface
5 package PublicInbox::WwwAttach; # internal package
8 use parent qw(PublicInbox::GzipFilter);
11 sub referer_match ($) {
13 my $env = $ctx->{env};
14 return 1 if $env->{REQUEST_METHOD} eq 'POST';
15 my $referer = lc($env->{HTTP_REFERER} // '');
16 return 1 if $referer eq ''; # no referer is always OK for wget/curl
18 # prevent deep-linking from other domains on some browsers (Firefox)
19 # n.b.: $ctx->{ibx}->base_url($env) with INBOX_URL won't work
20 # with dillo, we can only match "$url_scheme://$HTTP_HOST/" without
22 my $base_url = lc($env->{'psgi.url_scheme'} . '://' .
24 "$env->{SERVER_NAME}:$env->{SERVER_PORT}") . '/');
25 index($referer, $base_url) == 0;
28 sub get_attach_i { # ->each_part callback
29 my ($part, $depth, $idx) = @{$_[0]};
31 return if $idx ne $ctx->{idx}; # [0-9]+(?:\.[0-9]+)+
32 my $res = $ctx->{res};
35 if ($ct && (($ct->{type} || '') eq 'text')) {
36 # display all text as text/plain:
37 my $cset = $ct->{attributes}->{charset};
38 if ($cset && ($cset =~ /\A[a-zA-Z0-9_\-]+\z/)) {
39 $res->[1]->[1] .= qq(; charset=$cset);
41 $ctx->{gz} = PublicInbox::GzipFilter::gz_or_noop($res->[1],
43 $part = $ctx->zflush($part->body);
44 } else { # TODO: allow user to configure safe types
45 if (referer_match($ctx)) {
46 $res->[1]->[1] = 'application/octet-stream';
50 $res->[1]->[1] = 'text/html';
52 <html><head><title>download
53 attachment</title><body><pre>Deep-linking prevented</pre><form
54 method=post\naction=""><input type=submit value="Download attachment"
55 /></form></body></html>
59 push @{$res->[1]}, 'Content-Length', length($part);
60 $res->[2]->[0] = $part;
63 sub async_eml { # for async_blob_cb
65 eval { $eml->each_part(\&get_attach_i, $ctx, 1) };
67 $ctx->{res}->[0] = 500;
74 my $ctx = $http->{forward} or return; # client aborted
75 # finally, we call the user-supplied callback
76 eval { $ctx->{wcb}->($ctx->{res}) };
80 sub scan_attach ($) { # public-inbox-httpd only
82 $ctx->{env}->{'psgix.io'}->{forward} = $ctx;
83 $ctx->smsg_blob($ctx->{smsg});
86 # /$LISTNAME/$MESSAGE_ID/$IDX-$FILENAME
87 sub get_attach ($$$) {
88 my ($ctx, $idx, $fn) = @_;
89 $ctx->{res} = [ 404, [ 'Content-Type' => 'text/plain' ],
92 bless $ctx, __PACKAGE__;
94 if ($ctx->{smsg} = $ctx->{ibx}->smsg_by_mid($ctx->{mid})) {
95 return sub { # public-inbox-httpd-only
98 } if $ctx->{env}->{'pi-httpd.async'};
100 $eml = $ctx->{ibx}->smsg_eml($ctx->{smsg});
101 } elsif (!$ctx->{ibx}->over) {
102 if (my $bref = $ctx->{ibx}->msg_by_mid($ctx->{mid})) {
103 $eml = PublicInbox::Eml->new($bref);
106 $eml->each_part(\&get_attach_i, $ctx, 1) if $eml;