]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Mbox.pm
www: fix absolute URLs when mounted under a subdir
[public-inbox.git] / lib / PublicInbox / Mbox.pm
1 # Copyright (C) 2015-2019 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # Streaming (via getline) interface for formatting messages as an mboxrd.
5 # Used by the PSGI web interface.
6 #
7 # public-inbox-httpd favors "getline" response bodies to take a
8 # "pull"-based approach to feeding slow clients (as opposed to a
9 # more common "push" model)
10 package PublicInbox::Mbox;
11 use strict;
12 use warnings;
13 use PublicInbox::MID qw/mid_clean mid_escape/;
14 use PublicInbox::Hval qw/to_filename/;
15 use Email::Simple;
16 use Email::MIME::Encode;
17
18 sub subject_fn ($) {
19         my ($hdr) = @_;
20         my $fn = $hdr->header('Subject');
21         return 'no-subject' unless defined($fn);
22
23         # no need for full Email::MIME, here
24         if ($fn =~ /=\?/) {
25                 eval { $fn = Encode::decode('MIME-Header', $fn) };
26                 $fn = 'no-subject' if $@;
27         }
28         $fn =~ s/^re:\s+//i;
29         $fn = to_filename($fn);
30         $fn eq '' ? 'no-subject' : $fn;
31 }
32
33 sub mb_stream {
34         my ($more) = @_;
35         bless $more, 'PublicInbox::Mbox';
36 }
37
38 # called by PSGI server as body response
39 # this gets called twice for every message, once to return the header,
40 # once to retrieve the body
41 sub getline {
42         my ($more) = @_; # self
43         my ($ctx, $id, $prev, $next, $mref, $hdr) = @$more;
44         if ($hdr) { # first message hits this, only
45                 pop @$more; # $hdr
46                 return msg_hdr($ctx, $hdr);
47         }
48         if ($mref) { # all messages hit this
49                 pop @$more; # $mref
50                 return msg_body($$mref);
51         }
52         my $cur = $next or return;
53         my $ibx = $ctx->{-inbox};
54         $next = $ibx->over->next_by_mid($ctx->{mid}, \$id, \$prev);
55         $mref = $ibx->msg_by_smsg($cur) or return;
56         $hdr = Email::Simple->new($mref)->header_obj;
57         @$more = ($ctx, $id, $prev, $next, $mref); # $next may be undef, here
58         msg_hdr($ctx, $hdr); # all but first message hits this
59 }
60
61 sub close {} # noop
62
63 # /$INBOX/$MESSAGE_ID/raw
64 sub emit_raw {
65         my ($ctx) = @_;
66         my $mid = $ctx->{mid};
67         my $ibx = $ctx->{-inbox};
68         $ctx->{base_url} = $ibx->base_url($ctx->{env});
69         my ($mref, $more, $id, $prev, $next);
70         if (my $over = $ibx->over) {
71                 my $smsg = $over->next_by_mid($mid, \$id, \$prev) or return;
72                 $mref = $ibx->msg_by_smsg($smsg) or return;
73                 $next = $over->next_by_mid($mid, \$id, \$prev);
74         } else {
75                 $mref = $ibx->msg_by_mid($mid) or return;
76         }
77         my $hdr = Email::Simple->new($mref)->header_obj;
78         $more = [ $ctx, $id, $prev, $next, $mref, $hdr ]; # for ->getline
79         my $fn = subject_fn($hdr);
80         my @hdr = ('Content-Type');
81         if ($ibx->{obfuscate}) {
82                 # obfuscation is stupid, but maybe scrapers are, too...
83                 push @hdr, 'application/mbox';
84                 $fn .= '.mbox';
85         } else {
86                 push @hdr, 'text/plain';
87                 $fn .= '.txt';
88         }
89         push @hdr, 'Content-Disposition', "inline; filename=$fn";
90         [ 200, \@hdr, mb_stream($more) ];
91 }
92
93 sub msg_hdr ($$;$) {
94         my ($ctx, $header_obj, $mid) = @_;
95
96         # drop potentially confusing headers, ssoma already should've dropped
97         # Lines and Content-Length
98         foreach my $d (qw(Lines Bytes Content-Length Status)) {
99                 $header_obj->header_set($d);
100         }
101         my $ibx = $ctx->{-inbox};
102         my $base = $ctx->{base_url};
103         $mid = $ctx->{mid} unless defined $mid;
104         $mid = mid_escape($mid);
105         my @append = (
106                 'Archived-At', "<$base$mid/>",
107                 'List-Archive', "<$base>",
108                 'List-Post', "<mailto:$ibx->{-primary_address}>",
109         );
110         my $crlf = $header_obj->crlf;
111         my $buf = "From mboxrd\@z Thu Jan  1 00:00:00 1970\n" .
112                         $header_obj->as_string;
113         for (my $i = 0; $i < @append; $i += 2) {
114                 my $k = $append[$i];
115                 my $v = $append[$i + 1];
116                 my @v = $header_obj->header($k);
117                 foreach (@v) {
118                         if ($v eq $_) {
119                                 $v = undef;
120                                 last;
121                         }
122                 }
123                 $buf .= "$k: $v$crlf" if defined $v;
124         }
125         $buf .= $crlf;
126 }
127
128 sub msg_body ($) {
129         # mboxrd quoting style
130         # https://en.wikipedia.org/wiki/Mbox#Modified_mbox
131         # https://www.loc.gov/preservation/digital/formats/fdd/fdd000385.shtml
132         # https://web.archive.org/http://www.qmail.org/man/man5/mbox.html
133         $_[0] =~ s/^(>*From )/>$1/gm;
134         $_[0] .= "\n";
135 }
136
137 sub thread_mbox {
138         my ($ctx, $over, $sfx) = @_;
139         eval { require IO::Compress::Gzip };
140         return sub { need_gzip(@_) } if $@;
141         my $mid = $ctx->{mid};
142         my $msgs = $over->get_thread($mid, {});
143         return [404, [qw(Content-Type text/plain)], []] if !@$msgs;
144         my $prev = $msgs->[-1];
145         my $i = 0;
146         my $cb = sub {
147                 while (1) {
148                         if (my $smsg = $msgs->[$i++]) {
149                                 return $smsg;
150                         }
151                         # refill result set
152                         $msgs = $over->get_thread($mid, $prev);
153                         return unless @$msgs;
154                         $prev = $msgs->[-1];
155                         $i = 0;
156                 }
157         };
158         PublicInbox::MboxGz->response($ctx, $cb, $msgs->[0]->subject);
159 }
160
161 sub emit_range {
162         my ($ctx, $range) = @_;
163
164         my $query;
165         if ($range eq 'all') { # TODO: YYYY[-MM]
166                 $query = '';
167         } else {
168                 return [404, [qw(Content-Type text/plain)], []];
169         }
170         mbox_all($ctx, $query);
171 }
172
173 sub mbox_all_ids {
174         my ($ctx) = @_;
175         my $prev = 0;
176         my $ibx = $ctx->{-inbox};
177         my $ids = $ibx->mm->ids_after(\$prev) or return
178                 [404, [qw(Content-Type text/plain)], ["No results found\n"]];
179         my $i = 0;
180         my $over = $ibx->over or
181                 return PublicInbox::WWW::need($ctx, 'Overview');
182         my $cb = sub {
183                 do {
184                         while ((my $num = $ids->[$i++])) {
185                                 my $smsg = $over->get_art($num) or next;
186                                 return $smsg;
187                         }
188                         $ids = $ibx->mm->ids_after(\$prev);
189                         $i = 0;
190                 } while (@$ids);
191                 undef;
192         };
193         return PublicInbox::MboxGz->response($ctx, $cb, 'all');
194 }
195
196 sub mbox_all {
197         my ($ctx, $query) = @_;
198
199         eval { require IO::Compress::Gzip };
200         return sub { need_gzip(@_) } if $@;
201         return mbox_all_ids($ctx) if $query eq '';
202         my $opts = { mset => 2 };
203         my $srch = $ctx->{-inbox}->search or
204                 return PublicInbox::WWW::need($ctx, 'Search');;
205         my $mset = $srch->query($query, $opts);
206         $opts->{offset} = $mset->size or
207                         return [404, [qw(Content-Type text/plain)],
208                                 ["No results found\n"]];
209         my $i = 0;
210         my $cb = sub { # called by MboxGz->getline
211                 while (1) {
212                         while (my $mi = (($mset->items)[$i++])) {
213                                 my $doc = $mi->get_document;
214                                 my $smsg = $srch->retry_reopen(sub {
215                                         PublicInbox::SearchMsg->load_doc($doc);
216                                 }) or next;
217                                 return $smsg;
218                         }
219                         # refill result set
220                         $mset = $srch->query($query, $opts);
221                         my $size = $mset->size or return;
222                         $opts->{offset} += $size;
223                         $i = 0;
224                 }
225         };
226         PublicInbox::MboxGz->response($ctx, $cb, 'results-'.$query);
227 }
228
229 sub need_gzip {
230         my $fh = $_[0]->([501, ['Content-Type' => 'text/html']]);
231         my $title = 'gzipped mbox not available';
232         $fh->write(<<EOF);
233 <html><head><title>$title</title><body><pre>$title
234 The administrator needs to install the IO::Compress::Gzip Perl module
235 to support gzipped mboxes.
236 <a href="../">Return to index</a></pre></body></html>
237 EOF
238         $fh->close;
239 }
240
241 1;
242
243 package PublicInbox::MboxGz;
244 use strict;
245 use warnings;
246 use PublicInbox::Hval qw/to_filename/;
247
248 sub new {
249         my ($class, $ctx, $cb) = @_;
250         my $buf = '';
251         $ctx->{base_url} = $ctx->{-inbox}->base_url($ctx->{env});
252         bless {
253                 buf => \$buf,
254                 gz => IO::Compress::Gzip->new(\$buf, Time => 0),
255                 cb => $cb,
256                 ctx => $ctx,
257         }, $class;
258 }
259
260 sub response {
261         my ($class, $ctx, $cb, $fn) = @_;
262         my $body = $class->new($ctx, $cb);
263         # http://www.iana.org/assignments/media-types/application/gzip
264         my @h = qw(Content-Type application/gzip);
265         if ($fn) {
266                 $fn = to_filename($fn);
267                 push @h, 'Content-Disposition', "inline; filename=$fn.mbox.gz";
268         }
269         [ 200, \@h, $body ];
270 }
271
272 # called by Plack::Util::foreach or similar
273 sub getline {
274         my ($self) = @_;
275         my $ctx = $self->{ctx} or return;
276         my $gz = $self->{gz};
277         while (my $smsg = $self->{cb}->()) {
278                 my $mref = $ctx->{-inbox}->msg_by_smsg($smsg) or next;
279                 my $h = Email::Simple->new($mref)->header_obj;
280                 $gz->write(PublicInbox::Mbox::msg_hdr($ctx, $h, $smsg->{mid}));
281                 $gz->write(PublicInbox::Mbox::msg_body($$mref));
282
283                 my $bref = $self->{buf};
284                 if (length($$bref) >= 8192) {
285                         my $ret = $$bref; # copy :<
286                         ${$self->{buf}} = '';
287                         return $ret;
288                 }
289
290                 # be fair to other clients on public-inbox-httpd:
291                 return '';
292         }
293         delete($self->{gz})->close;
294         # signal that we're done and can return undef next call:
295         delete $self->{ctx};
296         ${delete $self->{buf}};
297 }
298
299 sub close {} # noop
300
301 1;