]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Inbox.pm
imap+nntp: share COMPRESS implementation
[public-inbox.git] / lib / PublicInbox / Inbox.pm
1 # Copyright (C) all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 #
4 # Represents a public-inbox (which may have multiple mailing addresses)
5 package PublicInbox::Inbox;
6 use strict;
7 use v5.10.1;
8 use PublicInbox::Git;
9 use PublicInbox::MID qw(mid2path);
10 use PublicInbox::Eml;
11 use List::Util qw(max);
12 use Carp qw(croak);
13
14 # returns true if further checking is required
15 sub check_inodes ($) {
16         for (qw(over mm)) { $_[0]->{$_}->check_inodes if $_[0]->{$_} }
17 }
18
19 sub do_cleanup {
20         my ($ibx) = @_;
21         my $live;
22         if (defined $ibx->{git}) {
23                 $live = $ibx->isa(__PACKAGE__) ? $ibx->{git}->cleanup(1)
24                                         : $ibx->{git}->cleanup_if_unlinked;
25                 delete($ibx->{git}) unless $live;
26         }
27         if ($live) {
28                 check_inodes($ibx);
29         } else {
30                 delete(@$ibx{qw(over mm description cloneurl
31                                 -imap_url -nntp_url)});
32         }
33         my $srch = $ibx->{search} // $ibx;
34         delete @$srch{qw(xdb qp)};
35         for my $git (@{$ibx->{-repo_objs} // []}) {
36                 $live = 1 if $git->cleanup(1);
37         }
38         PublicInbox::DS::add_uniq_timer($ibx+0, 5, \&do_cleanup, $ibx) if $live;
39 }
40
41 sub _cleanup_later ($) {
42         # no need to require DS, here, if it were enabled another
43         # module would've require'd it, already
44         eval { PublicInbox::DS::in_loop() } and
45                 PublicInbox::DS::add_uniq_timer($_[0]+0, 30, \&do_cleanup, @_)
46 }
47
48 sub _set_limiter ($$$) {
49         my ($self, $pi_cfg, $pfx) = @_;
50         my $lkey = "-${pfx}_limiter";
51         $self->{$lkey} //= do {
52                 # full key is: publicinbox.$NAME.httpbackendmax
53                 my $mkey = $pfx.'max';
54                 my $val = $self->{$mkey} or return;
55                 my $lim;
56                 if ($val =~ /\A[0-9]+\z/) {
57                         require PublicInbox::Qspawn;
58                         $lim = PublicInbox::Qspawn::Limiter->new($val);
59                 } elsif ($val =~ /\A[a-z][a-z0-9]*\z/) {
60                         $lim = $pi_cfg->limiter($val);
61                         warn "$mkey limiter=$val not found\n" if !$lim;
62                 } else {
63                         warn "$mkey limiter=$val not understood\n";
64                 }
65                 $lim;
66         }
67 }
68
69 sub new {
70         my ($class, $opts) = @_;
71         my $v = $opts->{address} ||= [ 'public-inbox@example.com' ];
72         my $p = $opts->{-primary_address} = ref($v) eq 'ARRAY' ? $v->[0] : $v;
73         $opts->{domain} = ($p =~ /\@(\S+)\z/) ? $1 : 'localhost';
74         my $pi_cfg = delete $opts->{-pi_cfg};
75         _set_limiter($opts, $pi_cfg, 'httpbackend');
76         my $fmax = $opts->{feedmax};
77         if (defined($fmax) && $fmax =~ /\A[0-9]+\z/) {
78                 $opts->{feedmax} += 0;
79         } else {
80                 delete $opts->{feedmax};
81         }
82         # allow any combination of multi-line or comma-delimited hide entries
83         my $hide = {};
84         if (defined(my $h = $opts->{hide})) {
85                 foreach my $v (@$h) {
86                         $hide->{$_} = 1 foreach (split(/\s*,\s*/, $v));
87                 }
88                 $opts->{-hide} = $hide;
89         }
90         bless $opts, $class;
91 }
92
93 sub version {
94         $_[0]->{version} //= -f "$_[0]->{inboxdir}/inbox.lock" ? 2 : 1
95 }
96
97 sub git_epoch {
98         my ($self, $epoch) = @_; # v2-only, callers always supply $epoch
99         $self->{"$epoch.git"} //= do {
100                 my $git_dir = "$self->{inboxdir}/git/$epoch.git";
101                 return unless -d $git_dir;
102                 my $g = PublicInbox::Git->new($git_dir);
103                 my $lim = $self->{-httpbackend_limiter};
104                 $g->{-httpbackend_limiter} = $lim if $lim;
105                 # caller must manually cleanup when done
106                 $g;
107         };
108 }
109
110 sub git {
111         my ($self) = @_;
112         $self->{git} //= do {
113                 my $git_dir = $self->{inboxdir};
114                 $git_dir .= '/all.git' if $self->version == 2;
115                 my $g = PublicInbox::Git->new($git_dir);
116                 my $lim = $self->{-httpbackend_limiter};
117                 $g->{-httpbackend_limiter} = $lim if $lim;
118                 _cleanup_later($self);
119                 $g;
120         };
121 }
122
123 sub max_git_epoch {
124         my ($self) = @_;
125         return if $self->version < 2;
126         my $cur = $self->{-max_git_epoch};
127         my $changed;
128         if (!defined($cur) || ($changed = git($self)->alternates_changed)) {
129                 $self->{git}->cleanup if $changed;
130                 my $gits = "$self->{inboxdir}/git";
131                 if (opendir my $dh, $gits) {
132                         my $max = max(map {
133                                 substr($_, 0, -4) + 0; # drop ".git" suffix
134                         } grep(/\A[0-9]+\.git\z/, readdir($dh))) // return;
135                         $cur = $self->{-max_git_epoch} = $max;
136                 }
137         }
138         $cur;
139 }
140
141 sub mm_file {
142         my ($self) = @_;
143         my $d = $self->{inboxdir};
144         ($self->version >= 2 ? $d : "$d/public-inbox").'/msgmap.sqlite3';
145 }
146
147 sub mm {
148         my ($self, $req) = @_;
149         $self->{mm} //= eval {
150                 require PublicInbox::Msgmap;
151                 _cleanup_later($self);
152                 PublicInbox::Msgmap->new_file($self);
153         } // ($req ? croak("E: $@") : undef);
154 }
155
156 sub search {
157         my ($self) = @_;
158         $self->{search} // eval {
159                 _cleanup_later($self);
160                 require PublicInbox::Search;
161                 my $srch = PublicInbox::Search->new($self);
162                 (eval { $srch->xdb }) ? ($self->{search} = $srch) : undef;
163         };
164 }
165
166 # isrch is preferred for read-only interfaces if available since it
167 # reduces kernel cache and FD overhead
168 sub isrch { $_[0]->{isrch} // search($_[0]) }
169
170 sub over {
171         my ($self, $req) = @_;
172         $self->{over} // eval {
173                 my $srch = $self->{search} // do {
174                         require PublicInbox::Search;
175                         PublicInbox::Search->new($self);
176                 };
177                 _cleanup_later($self);
178                 my $over = PublicInbox::Over->new("$srch->{xpfx}/over.sqlite3");
179                 $over->dbh; # may fail
180                 $self->{over} = $over;
181         } // ($req ? croak("E: $@") : undef);
182 }
183
184 sub try_cat {
185         my ($path) = @_;
186         open(my $fh, '<', $path) or return '';
187         local $/;
188         <$fh> // '';
189 }
190
191 sub cat_desc ($) {
192         my $desc = try_cat($_[0]);
193         local $/ = "\n";
194         chomp $desc;
195         utf8::decode($desc);
196         $desc =~ s/\s+/ /smg;
197         $desc eq '' ? undef : $desc;
198 }
199
200 sub description {
201         my ($self) = @_;
202         ($self->{description} //= cat_desc("$self->{inboxdir}/description")) //
203                 '($INBOX_DIR/description missing)';
204 }
205
206 sub cloneurl {
207         my ($self) = @_;
208         $self->{cloneurl} // do {
209                 my $s = try_cat("$self->{inboxdir}/cloneurl");
210                 my @urls = split(/\s+/s, $s);
211                 scalar(@urls) ? ($self->{cloneurl} = \@urls) : undef;
212         } // [];
213 }
214
215 sub base_url {
216         my ($self, $env) = @_; # env - PSGI env
217         if ($env && $env->{'psgi.url_scheme'}) {
218                 my $url = PublicInbox::Git::host_prefix_url($env, '');
219                 # for mount in Plack::Builder
220                 $url .= '/' if $url !~ m!/\z!;
221                 return $url .= $self->{name} . '/';
222         }
223         # called from a non-PSGI environment (e.g. NNTP/POP3):
224         my $url = $self->{url} // return undef;
225         $url = $url->[0] // return undef;
226         # expand protocol-relative URLs to HTTPS if we're
227         # not inside a web server
228         substr($url, 0, 0, 'https:') if substr($url, 0, 2) eq '//';
229         $url .= '/' if substr($url, -1, 1) ne '/';
230         $url;
231 }
232
233 # imapserver, nntpserver, and pop3server configs are used here:
234 sub _x_url ($$$) {
235         my ($self, $x, $ctx) = @_; # $x is "imap", "nntp", or "pop3"
236         # no checking for nntp_usable here, we can point entirely
237         # to non-local servers or users run by a different user
238         my $ns = $self->{"${x}server"} //
239                $ctx->{www}->{pi_cfg}->get_all("publicinbox.${x}server");
240         my $group = $self->{newsgroup};
241         my @urls;
242         if ($ns && $group) {
243                 @urls = map {
244                         my $u = m!\A${x}s?://! ? $_ : "$x://$_";
245                         $u .= '/' if $u !~ m!/\z!;
246                         $u.$group;
247                 } @$ns;
248         }
249         if (my $mirrors = $self->{"${x}mirror"}) {
250                 my @m;
251                 for (@$mirrors) {
252                         my $u = m!\A${x}s?://! ? $_ : "$x://$_";
253                         if ($u =~ m!\A${x}s?://[^/]+/?\z!) {
254                                 if ($group) {
255                                         $u .= '/' if $u !~ m!/\z!;
256                                         $u .= $group;
257                                 } else { # n.b. IMAP and POP3 use "newsgroup"
258                                         warn <<EOM;
259 publicinbox.$self->{name}.${x}mirror=$_ missing newsgroup name
260 EOM
261                                 }
262                         }
263                         # else: allow full URLs like:
264                         # nntp://news.example.com/alt.example
265                         push @m, $u;
266                 }
267
268                 # List::Util::uniq requires Perl 5.26+, maybe we
269                 # can use it by 2030 or so
270                 my %seen;
271                 @urls = grep { !$seen{$_}++ } (@urls, @m);
272         }
273         \@urls;
274 }
275
276 # my ($self, $ctx) = @_;
277 sub imap_url { $_[0]->{-imap_url} //= _x_url($_[0], 'imap', $_[1]) }
278 sub nntp_url { $_[0]->{-nntp_url} //= _x_url($_[0], 'nntp', $_[1]) }
279 sub pop3_url { $_[0]->{-pop3_url} //= _x_url($_[0], 'pop3', $_[1]) }
280
281 sub nntp_usable {
282         my ($self) = @_;
283         my $ret = mm($self) && over($self);
284         delete @$self{qw(mm over search)};
285         $ret;
286 }
287
288 # for v1 users w/o SQLite only
289 sub msg_by_path ($$) {
290         my ($self, $path) = @_;
291         git($self)->cat_file('HEAD:'.$path);
292 }
293
294 sub msg_by_smsg ($$) {
295         my ($self, $smsg) = @_;
296
297         # ghosts may have undef smsg (from SearchThread.node) or
298         # no {blob} field
299         $smsg // return;
300         $self->git->cat_file($smsg->{blob} // return);
301 }
302
303 sub smsg_eml {
304         my ($self, $smsg) = @_;
305         my $bref = msg_by_smsg($self, $smsg) or return;
306         my $eml = PublicInbox::Eml->new($bref);
307         $smsg->{num} // $smsg->populate($eml);
308         $eml;
309 }
310
311 sub smsg_by_mid ($$) {
312         my ($self, $mid) = @_;
313         my $over = $self->over or return;
314         my $smsg;
315         if (my $mm = $self->mm) {
316                 # favor the Message-ID we used for the NNTP article number:
317                 my $num = $mm->num_for($mid) // return;
318                 $smsg = $over->get_art($num);
319         } else {
320                 my ($id, $prev);
321                 $smsg = $over->next_by_mid($mid, \$id, \$prev);
322         }
323         $smsg ? PublicInbox::Smsg::psgi_cull($smsg) : undef;
324 }
325
326 sub msg_by_mid ($$) {
327         my ($self, $mid) = @_;
328         my $smsg = smsg_by_mid($self, $mid);
329         $smsg ? msg_by_smsg($self, $smsg) : msg_by_path($self, mid2path($mid));
330 }
331
332 sub recent {
333         my ($self, $opts, $after, $before) = @_;
334         $self->over->recent($opts, $after, $before);
335 }
336
337 sub modified {
338         my ($self) = @_;
339         if (my $over = $self->over) {
340                 my $msgs = $over->recent({limit => 1});
341                 if (my $smsg = $msgs->[0]) {
342                         return $smsg->{ts};
343                 }
344                 return time;
345         }
346         git($self)->modified; # v1
347 }
348
349 # returns prefix => pathname mapping
350 # (pathname is NOT public, but prefix is used for Xapian queries)
351 sub altid_map ($) {
352         my ($self) = @_;
353         eval {
354                 require PublicInbox::AltId;
355                 my $altid = $self->{altid} or return {};
356                 my %h = map {;
357                         my $x = PublicInbox::AltId->new($self, $_);
358                         "$x->{prefix}" => $x->{filename}
359                 } @$altid;
360                 \%h;
361         } // {};
362 }
363
364 # $obj must respond to ->on_inbox_unlock, which takes Inbox ($self) as an arg
365 sub subscribe_unlock {
366         my ($self, $ident, $obj) = @_;
367         $self->{unlock_subs}->{$ident} = $obj;
368 }
369
370 sub unsubscribe_unlock {
371         my ($self, $ident) = @_;
372         delete $self->{unlock_subs}->{$ident};
373 }
374
375 # called by inotify
376 sub on_unlock {
377         my ($self) = @_;
378         check_inodes($self);
379         my $subs = $self->{unlock_subs} or return;
380         for my $obj (values %$subs) {
381                 eval { $obj->on_inbox_unlock($self) };
382                 warn "E: $@ ($self->{inboxdir})\n" if $@;
383         }
384 }
385
386 sub uidvalidity { $_[0]->{uidvalidity} //= eval { $_[0]->mm->created_at } }
387
388 sub eidx_key { $_[0]->{newsgroup} // $_[0]->{inboxdir} }
389
390 sub mailboxid { # rfc 8474, 8620, 8621
391         my ($self, $imap_slice) = @_;
392         my $pfx = defined($imap_slice) ? $self->{newsgroup} : $self->{name};
393         utf8::encode($pfx); # to octets
394         # RFC 8620, 1.2 recommends not starting with dash or digits
395         # "A good solution to these issues is to prefix every id with a single
396         #  alphabetical character."
397         'M'.join('', map { sprintf('%02x', ord) } split(//, $pfx)) .
398                 (defined($imap_slice) ? sprintf('-%x', $imap_slice) : '') .
399                 sprintf('-%x', uidvalidity($self) // 0)
400 }
401
402 1;