1 # Copyright (C) 2016-2021 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 my $referer = $env->{HTTP_REFERER} // '';
15 return 1 if $referer eq ''; # no referer is always OK for wget/curl
17 # prevent deep-linking from other domains on some browsers (Firefox)
18 # n.b.: $ctx->{ibx}->base_url($env) with INBOX_URL won't work
19 # with dillo, we can only match "$url_scheme://$HTTP_HOST/" without
21 my $base_url = $env->{'psgi.url_scheme'} . '://' .
23 "$env->{SERVER_NAME}:$env->{SERVER_PORT}") . '/';
24 index($referer, $base_url) == 0;
27 sub get_attach_i { # ->each_part callback
28 my ($part, $depth, $idx) = @{$_[0]};
30 return if $idx ne $ctx->{idx}; # [0-9]+(?:\.[0-9]+)+
31 my $res = $ctx->{res};
34 if ($ct && (($ct->{type} || '') eq 'text')) {
35 # display all text as text/plain:
36 my $cset = $ct->{attributes}->{charset};
37 if ($cset && ($cset =~ /\A[a-zA-Z0-9_\-]+\z/)) {
38 $res->[1]->[1] .= qq(; charset=$cset);
40 $ctx->{gz} = PublicInbox::GzipFilter::gz_or_noop($res->[1],
42 $part = $ctx->zflush($part->body);
43 } else { # TODO: allow user to configure safe types
44 if (referer_match($ctx)) {
45 $res->[1]->[1] = 'application/octet-stream';
49 $res->[1]->[1] = 'text/plain';
50 $part = "Deep-linking prevented\n";
53 push @{$res->[1]}, 'Content-Length', length($part);
54 $res->[2]->[0] = $part;
57 sub async_eml { # for async_blob_cb
59 eval { $eml->each_part(\&get_attach_i, $ctx, 1) };
61 $ctx->{res}->[0] = 500;
68 my $ctx = $http->{forward} or return; # client aborted
69 # finally, we call the user-supplied callback
70 eval { $ctx->{wcb}->($ctx->{res}) };
74 sub scan_attach ($) { # public-inbox-httpd only
76 $ctx->{env}->{'psgix.io'}->{forward} = $ctx;
77 $ctx->smsg_blob($ctx->{smsg});
80 # /$LISTNAME/$MESSAGE_ID/$IDX-$FILENAME
81 sub get_attach ($$$) {
82 my ($ctx, $idx, $fn) = @_;
83 $ctx->{res} = [ 404, [ 'Content-Type' => 'text/plain' ],
86 bless $ctx, __PACKAGE__;
88 if ($ctx->{smsg} = $ctx->{ibx}->smsg_by_mid($ctx->{mid})) {
89 return sub { # public-inbox-httpd-only
92 } if $ctx->{env}->{'pi-httpd.async'};
94 $eml = $ctx->{ibx}->smsg_eml($ctx->{smsg});
95 } elsif (!$ctx->{ibx}->over) {
96 if (my $bref = $ctx->{ibx}->msg_by_mid($ctx->{mid})) {
97 $eml = PublicInbox::Eml->new($bref);
100 $eml->each_part(\&get_attach_i, $ctx, 1) if $eml;