]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/WwwAltId.pm
imap+nntp: share COMPRESS implementation
[public-inbox.git] / lib / PublicInbox / WwwAltId.pm
1 # Copyright (C) 2020-2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # dumps using the ".dump" command of sqlite3(1)
5 package PublicInbox::WwwAltId;
6 use strict;
7 use PublicInbox::Qspawn;
8 use PublicInbox::WwwStream qw(html_oneshot);
9 use PublicInbox::AltId;
10 use PublicInbox::Spawn qw(which);
11 use PublicInbox::GzipFilter;
12 our $sqlite3 = $ENV{SQLITE3};
13
14 sub check_output {
15         my ($r, $bref, $ctx) = @_;
16         return html_oneshot($ctx, 500) if !defined($r);
17         if ($r == 0) {
18                 warn 'unexpected EOF from sqlite3';
19                 return html_oneshot($ctx, 501);
20         }
21         [200, [ qw(Content-Type application/gzip), 'Content-Disposition',
22                 "inline; filename=$ctx->{altid_pfx}.sql.gz" ] ]
23 }
24
25 # POST $INBOX/$prefix.sql.gz
26 # we use the sqlite3(1) binary here since that's where the ".dump"
27 # command is implemented, not (AFAIK) in the libsqlite3 library
28 # and thus not usable from DBD::SQLite.
29 sub sqldump ($$) {
30         my ($ctx, $altid_pfx) = @_;
31         my $env = $ctx->{env};
32         my $ibx = $ctx->{ibx};
33         my $altid_map = $ibx->altid_map;
34         my $fn = $altid_map->{$altid_pfx};
35         unless (defined $fn) {
36                 return html_oneshot($ctx, 404, \<<EOF);
37 <pre>`$altid_pfx' is not a valid altid for this inbox</pre>
38 EOF
39         }
40
41         if ($env->{REQUEST_METHOD} ne 'POST') {
42                 my $url = $ibx->base_url($ctx->{env}) . "$altid_pfx.sql.gz";
43                 return html_oneshot($ctx, 405, \<<EOF);
44 <pre>A POST request is required to retrieve $altid_pfx.sql.gz
45
46         curl -d '' -O $url
47
48 or
49
50         curl -d '' $url | \\
51                 gzip -dc | \\
52                 sqlite3 /path/to/$altid_pfx.sqlite3
53 </pre>
54 EOF
55         }
56
57         $sqlite3 //= which('sqlite3') // return html_oneshot($ctx, 501, \<<EOF);
58 <pre>sqlite3 not available
59
60 The administrator needs to install the sqlite3(1) binary
61 to support gzipped sqlite3 dumps.</pre>
62 EOF
63
64         # setup stdin, POSIX requires writes <= 512 bytes to succeed so
65         # we can close the pipe right away.
66         pipe(my ($r, $w)) or die "pipe: $!";
67         syswrite($w, ".dump\n") == 6 or die "write: $!";
68         close($w) or die "close: $!";
69
70         # TODO: use -readonly if available with newer sqlite3(1)
71         my $qsp = PublicInbox::Qspawn->new([$sqlite3, $fn], undef, { 0 => $r });
72         $ctx->{altid_pfx} = $altid_pfx;
73         $env->{'qspawn.filter'} = PublicInbox::GzipFilter->new;
74         $qsp->psgi_return($env, undef, \&check_output, $ctx);
75 }
76
77 1;