]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Mbox.pm
895f828c520dd756460802e72fb95077dd643abb
[public-inbox.git] / lib / PublicInbox / Mbox.pm
1 # Copyright (C) 2015-2020 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_escape/;
14 use PublicInbox::Hval qw/to_filename/;
15 use PublicInbox::Smsg;
16 use PublicInbox::Eml;
17 use PublicInbox::GitAsyncCat;
18 use PublicInbox::GzipFilter qw(gzf_maybe);
19
20 # called by PSGI server as body response
21 # this gets called twice for every message, once to return the header,
22 # once to retrieve the body
23 sub getline {
24         my ($ctx) = @_; # ctx
25         my $smsg = $ctx->{smsg} or return;
26         my $ibx = $ctx->{-inbox};
27         my $eml = $ibx->smsg_eml($smsg) or return;
28         $ctx->{smsg} = $ibx->over->next_by_mid($ctx->{mid}, @{$ctx->{id_prev}});
29         msg_hdr($ctx, $eml, $smsg->{mid}) . msg_body($eml);
30 }
31
32 sub close { !!delete($_[0]->{http_out}) }
33
34 sub mbox_async_step ($) { # public-inbox-httpd-only
35         my ($ctx) = @_;
36         if (my $smsg = $ctx->{smsg}) {
37                 git_async_cat($ctx->{-inbox}->git, $smsg->{blob},
38                                 \&mbox_blob_cb, $ctx);
39         } elsif (my $out = delete $ctx->{http_out}) {
40                 $out->close;
41         }
42 }
43
44 # called by PublicInbox::DS::write
45 sub mbox_async_next {
46         my ($http) = @_; # PublicInbox::HTTP
47         my $ctx = $http->{forward} or return; # client aborted
48         eval {
49                 $ctx->{smsg} = $ctx->{-inbox}->over->next_by_mid(
50                                         $ctx->{mid}, @{$ctx->{id_prev}});
51                 mbox_async_step($ctx);
52         };
53 }
54
55 # this is public-inbox-httpd-specific
56 sub mbox_blob_cb { # git->cat_async callback
57         my ($bref, $oid, $type, $size, $ctx) = @_;
58         my $http = $ctx->{env}->{'psgix.io'} or return; # client abort
59         my $smsg = delete $ctx->{smsg} or die 'BUG: no smsg';
60         if (!defined($oid)) {
61                 # it's possible to have TOCTOU if an admin runs
62                 # public-inbox-(edit|purge), just move onto the next message
63                 return $http->next_step(\&mbox_async_next);
64         } else {
65                 $smsg->{blob} eq $oid or die "BUG: $smsg->{blob} != $oid";
66         }
67         my $eml = PublicInbox::Eml->new($bref);
68         $ctx->{http_out}->write(msg_hdr($ctx, $eml, $smsg->{mid}));
69         $ctx->{http_out}->write(msg_body($eml));
70         $http->next_step(\&mbox_async_next);
71 }
72
73 sub res_hdr ($$) {
74         my ($ctx, $subject) = @_;
75         my $fn = $subject // 'no-subject';
76         $fn =~ s/^re:\s+//i;
77         $fn = $fn eq '' ? 'no-subject' : to_filename($fn);
78         my @hdr = ('Content-Type');
79         if ($ctx->{-inbox}->{obfuscate}) {
80                 # obfuscation is stupid, but maybe scrapers are, too...
81                 push @hdr, 'application/mbox';
82                 $fn .= '.mbox';
83         } else {
84                 push @hdr, 'text/plain';
85                 $fn .= '.txt';
86         }
87         push @hdr, 'Content-Disposition', "inline; filename=$fn";
88         \@hdr;
89 }
90
91 # for rare cases where v1 inboxes aren't indexed w/ ->over at all
92 sub no_over_raw ($) {
93         my ($ctx) = @_;
94         my $mref = $ctx->{-inbox}->msg_by_mid($ctx->{mid}) or return;
95         my $eml = PublicInbox::Eml->new($mref);
96         [ 200, res_hdr($ctx, $eml->header_str('Subject')),
97                 [ msg_hdr($ctx, $eml, $ctx->{mid}) . msg_body($eml) ] ]
98 }
99
100 sub stream_raw { # MboxGz response callback
101         my ($ctx) = @_;
102         delete($ctx->{smsg}) //
103                 $ctx->{-inbox}->over->next_by_mid($ctx->{mid},
104                                                 @{$ctx->{id_prev}});
105 }
106
107 # /$INBOX/$MESSAGE_ID/raw
108 sub emit_raw {
109         my ($ctx) = @_;
110         my $env = $ctx->{env};
111         $ctx->{base_url} = $ctx->{-inbox}->base_url($env);
112         my $over = $ctx->{-inbox}->over or return no_over_raw($ctx);
113         my ($id, $prev);
114         my $smsg = $over->next_by_mid($ctx->{mid}, \$id, \$prev) or return;
115         $ctx->{smsg} = $smsg;
116         my $res_hdr = res_hdr($ctx, $smsg->{subject});
117         $ctx->{id_prev} = [ \$id, \$prev ];
118
119         if (my $gzf = gzf_maybe($res_hdr, $env)) {
120                 $ctx->{gz} = delete $gzf->{gz};
121                 require PublicInbox::MboxGz;
122                 PublicInbox::MboxGz::response($ctx, \&stream_raw, $res_hdr);
123         } elsif ($env->{'pi-httpd.async'}) {
124                 sub {
125                         my ($wcb) = @_; # -httpd provided write callback
126                         $ctx->{http_out} = $wcb->([200, $res_hdr]);
127                         $ctx->{env}->{'psgix.io'}->{forward} = $ctx;
128                         bless $ctx, __PACKAGE__;
129                         mbox_async_step($ctx); # start stepping
130                 };
131         } else { # generic PSGI code path
132                 bless $ctx, __PACKAGE__; # respond to ->getline
133                 [ 200, $res_hdr, $ctx ];
134         }
135 }
136
137 sub msg_hdr ($$;$) {
138         my ($ctx, $eml, $mid) = @_;
139         my $header_obj = $eml->header_obj;
140
141         # drop potentially confusing headers, ssoma already should've dropped
142         # Lines and Content-Length
143         foreach my $d (qw(Lines Bytes Content-Length Status)) {
144                 $header_obj->header_set($d);
145         }
146         my $ibx = $ctx->{-inbox};
147         my $base = $ctx->{base_url};
148         $mid = $ctx->{mid} unless defined $mid;
149         $mid = mid_escape($mid);
150         my @append = (
151                 'Archived-At', "<$base$mid/>",
152                 'List-Archive', "<$base>",
153                 'List-Post', "<mailto:$ibx->{-primary_address}>",
154         );
155         my $crlf = $header_obj->crlf;
156         my $buf = $header_obj->as_string;
157         # fixup old bug from import (pre-a0c07cba0e5d8b6a)
158         $buf =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
159         $buf = "From mboxrd\@z Thu Jan  1 00:00:00 1970" . $crlf . $buf;
160
161         for (my $i = 0; $i < @append; $i += 2) {
162                 my $k = $append[$i];
163                 my $v = $append[$i + 1];
164                 my @v = $header_obj->header_raw($k);
165                 foreach (@v) {
166                         if ($v eq $_) {
167                                 $v = undef;
168                                 last;
169                         }
170                 }
171                 $buf .= "$k: $v$crlf" if defined $v;
172         }
173         $buf .= $crlf;
174 }
175
176 sub msg_body ($) {
177         my $bdy = $_[0]->{bdy} // return "\n";
178         # mboxrd quoting style
179         # https://en.wikipedia.org/wiki/Mbox#Modified_mbox
180         # https://www.loc.gov/preservation/digital/formats/fdd/fdd000385.shtml
181         # https://web.archive.org/http://www.qmail.org/man/man5/mbox.html
182         $$bdy =~ s/^(>*From )/>$1/gm;
183         $$bdy .= "\n";
184 }
185
186 sub thread_cb {
187         my ($ctx) = @_;
188         my $msgs = $ctx->{msgs};
189         while (1) {
190                 if (my $smsg = shift @$msgs) {
191                         return $smsg;
192                 }
193                 # refill result set
194                 $ctx->{msgs} = $msgs = $ctx->{over}->get_thread($ctx->{mid},
195                                                                 $ctx->{prev});
196                 return unless @$msgs;
197                 $ctx->{prev} = $msgs->[-1];
198         }
199 }
200
201 sub thread_mbox {
202         my ($ctx, $over, $sfx) = @_;
203         my $msgs = $ctx->{msgs} = $over->get_thread($ctx->{mid}, {});
204         return [404, [qw(Content-Type text/plain)], []] if !@$msgs;
205         $ctx->{prev} = $msgs->[-1];
206         $ctx->{over} = $over; # bump refcnt
207         require PublicInbox::MboxGz;
208         PublicInbox::MboxGz::mbox_gz($ctx, \&thread_cb, $msgs->[0]->{subject});
209 }
210
211 sub emit_range {
212         my ($ctx, $range) = @_;
213
214         my $query;
215         if ($range eq 'all') { # TODO: YYYY[-MM]
216                 $query = '';
217         } else {
218                 return [404, [qw(Content-Type text/plain)], []];
219         }
220         mbox_all($ctx, $query);
221 }
222
223 sub all_ids_cb {
224         my ($ctx) = @_;
225         my $ids = $ctx->{ids};
226         do {
227                 while ((my $num = shift @$ids)) {
228                         my $smsg = $ctx->{over}->get_art($num) or next;
229                         return $smsg;
230                 }
231                 $ctx->{ids} = $ids = $ctx->{mm}->ids_after(\($ctx->{prev}));
232         } while (@$ids);
233 }
234
235 sub mbox_all_ids {
236         my ($ctx) = @_;
237         my $ibx = $ctx->{-inbox};
238         my $prev = 0;
239         my $mm = $ctx->{mm} = $ibx->mm;
240         my $ids = $mm->ids_after(\$prev) or return
241                 [404, [qw(Content-Type text/plain)], ["No results found\n"]];
242         $ctx->{over} = $ibx->over or
243                 return PublicInbox::WWW::need($ctx, 'Overview');
244         $ctx->{ids} = $ids;
245         $ctx->{prev} = $prev;
246         require PublicInbox::MboxGz;
247         PublicInbox::MboxGz::mbox_gz($ctx, \&all_ids_cb, 'all');
248 }
249
250 sub results_cb {
251         my ($ctx) = @_;
252         my $mset = $ctx->{mset};
253         my $srch = $ctx->{srch};
254         while (1) {
255                 while (my $mi = (($mset->items)[$ctx->{iter}++])) {
256                         my $smsg = PublicInbox::Smsg::from_mitem($mi,
257                                                                 $srch) or next;
258                         return $smsg;
259                 }
260                 # refill result set
261                 $mset = $ctx->{mset} = $srch->query($ctx->{query},
262                                                         $ctx->{qopts});
263                 my $size = $mset->size or return;
264                 $ctx->{qopts}->{offset} += $size;
265                 $ctx->{iter} = 0;
266         }
267 }
268
269 sub mbox_all {
270         my ($ctx, $query) = @_;
271
272         return mbox_all_ids($ctx) if $query eq '';
273         my $qopts = $ctx->{qopts} = { mset => 2 };
274         my $srch = $ctx->{srch} = $ctx->{-inbox}->search or
275                 return PublicInbox::WWW::need($ctx, 'Search');;
276         my $mset = $ctx->{mset} = $srch->query($query, $qopts);
277         $qopts->{offset} = $mset->size or
278                         return [404, [qw(Content-Type text/plain)],
279                                 ["No results found\n"]];
280         $ctx->{iter} = 0;
281         $ctx->{query} = $query;
282         require PublicInbox::MboxGz;
283         PublicInbox::MboxGz::mbox_gz($ctx, \&results_cb, 'results-'.$query);
284 }
285
286 1;