1 # Copyright (C) 2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # dumps using the ".dump" command of sqlite3(1)
5 package PublicInbox::WwwAltId;
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};
14 sub sqlite3_missing ($) {
15 html_oneshot($_[0], 501, \<<EOF);
16 <pre>sqlite3 not available
18 The administrator needs to install the sqlite3(1) binary
19 to support gzipped sqlite3 dumps.</pre>
25 my ($r, $bref, $ctx) = @_;
26 return html_oneshot($ctx, 500) if !defined($r);
28 my $err = eval { $ctx->{env}->{'psgi.errors'} } // \*STDERR;
29 $err->print("unexpected EOF from sqlite3\n");
30 return html_oneshot($ctx, 501);
32 [200, [ qw(Content-Type application/gzip), 'Content-Disposition',
33 "inline; filename=$ctx->{altid_pfx}.sql.gz" ] ]
36 # POST $INBOX/$prefix.sql.gz
37 # we use the sqlite3(1) binary here since that's where the ".dump"
38 # command is implemented, not (AFAIK) in the libsqlite3 library
39 # and thus not usable from DBD::SQLite.
41 my ($ctx, $altid_pfx) = @_;
42 my $env = $ctx->{env};
43 my $ibx = $ctx->{-inbox};
44 my $altid_map = $ibx->altid_map;
45 my $fn = $altid_map->{$altid_pfx};
46 unless (defined $fn) {
47 return html_oneshot($ctx, 404, \<<EOF);
48 <pre>`$altid_pfx' is not a valid altid for this inbox</pre>
52 if ($env->{REQUEST_METHOD} ne 'POST') {
53 my $url = $ibx->base_url($ctx->{env}) . "$altid_pfx.sql.gz";
54 return html_oneshot($ctx, 405, \<<EOF);
55 <pre>A POST request required to retrieve $altid_pfx.sql.gz
63 sqlite3 /path/to/$altid_pfx.sqlite3
68 $sqlite3 //= which('sqlite3');
69 if (!defined($sqlite3)) {
70 return html_oneshot($ctx, 501, \<<EOF);
71 <pre>sqlite3 not available
73 The administrator needs to install the sqlite3(1) binary
74 to support gzipped sqlite3 dumps.</pre>
79 # setup stdin, POSIX requires writes <= 512 bytes to succeed so
80 # we can close the pipe right away.
81 pipe(my ($r, $w)) or die "pipe: $!";
82 syswrite($w, ".dump\n") == 6 or die "write: $!";
83 close($w) or die "close: $!";
85 # TODO: use -readonly if available with newer sqlite3(1)
86 my $qsp = PublicInbox::Qspawn->new([$sqlite3, $fn], undef, { 0 => $r });
87 $ctx->{altid_pfx} = $altid_pfx;
88 $env->{'qspawn.filter'} = PublicInbox::GzipFilter->new;
89 $qsp->psgi_return($env, undef, \&check_output, $ctx);