1 # Copyright (C) 2016-2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # Represents a public-inbox (which may have multiple mailing addresses)
5 package PublicInbox::Inbox;
8 use PublicInbox::MID qw(mid2path);
10 use List::Util qw(max);
15 my $git = $self->{git} // return undef;
16 # normal inboxes have low startup cost and there may be many, so
17 # keep process+pipe counts in check. ExtSearch may have high startup
18 # cost (e.g. ->ALL) and but likely one per-daemon, so cleanup only
19 # if there's unlinked files
20 my $live = $self->isa(__PACKAGE__) ? $git->cleanup(1)
21 : $git->cleanup_if_unlinked;
22 delete($self->{git}) unless $live;
26 # returns true if further checking is required
27 sub cleanup_shards { $_[0]->{search} ? $_[0]->{search}->cleanup_shards : undef }
31 my $live = git_cleanup($ibx);
32 $ibx->cleanup_shards and $live = 1;
33 for my $git (@{$ibx->{-repo_objs}}) {
34 $live = 1 if $git->cleanup(1);
36 delete @$ibx{qw(over mm)};
37 PublicInbox::DS::add_uniq_timer($ibx+0, 5, \&do_cleanup, $ibx) if $live;
40 sub _cleanup_later ($) {
41 # no need to require DS, here, if it were enabled another
42 # module would've require'd it, already
43 eval { PublicInbox::DS::in_loop() } and
44 PublicInbox::DS::add_uniq_timer($_[0]+0, 30, \&do_cleanup, @_)
47 sub _set_limiter ($$$) {
48 my ($self, $pi_cfg, $pfx) = @_;
49 my $lkey = "-${pfx}_limiter";
50 $self->{$lkey} ||= do {
51 # full key is: publicinbox.$NAME.httpbackendmax
52 my $mkey = $pfx.'max';
53 my $val = $self->{$mkey} or return;
55 if ($val =~ /\A[0-9]+\z/) {
56 require PublicInbox::Qspawn;
57 $lim = PublicInbox::Qspawn::Limiter->new($val);
58 } elsif ($val =~ /\A[a-z][a-z0-9]*\z/) {
59 $lim = $pi_cfg->limiter($val);
60 warn "$mkey limiter=$val not found\n" if !$lim;
62 warn "$mkey limiter=$val not understood\n";
69 my ($class, $opts) = @_;
70 my $v = $opts->{address} ||= [ 'public-inbox@example.com' ];
71 my $p = $opts->{-primary_address} = ref($v) eq 'ARRAY' ? $v->[0] : $v;
72 $opts->{domain} = ($p =~ /\@(\S+)\z/) ? $1 : 'localhost';
73 my $pi_cfg = delete $opts->{-pi_cfg};
74 _set_limiter($opts, $pi_cfg, 'httpbackend');
75 my $fmax = $opts->{feedmax};
76 if (defined($fmax) && $fmax =~ /\A[0-9]+\z/) {
77 $opts->{feedmax} += 0;
79 delete $opts->{feedmax};
81 # allow any combination of multi-line or comma-delimited hide entries
83 if (defined(my $h = $opts->{hide})) {
85 $hide->{$_} = 1 foreach (split(/\s*,\s*/, $v));
87 $opts->{-hide} = $hide;
93 $_[0]->{version} //= -f "$_[0]->{inboxdir}/inbox.lock" ? 2 : 1
97 my ($self, $epoch) = @_; # v2-only, callers always supply $epoch
98 $self->{"$epoch.git"} //= do {
99 my $git_dir = "$self->{inboxdir}/git/$epoch.git";
100 return unless -d $git_dir;
101 my $g = PublicInbox::Git->new($git_dir);
102 my $lim = $self->{-httpbackend_limiter};
103 $g->{-httpbackend_limiter} = $lim if $lim;
104 # caller must manually cleanup when done
111 $self->{git} //= do {
112 my $git_dir = $self->{inboxdir};
113 $git_dir .= '/all.git' if $self->version == 2;
114 my $g = PublicInbox::Git->new($git_dir);
115 my $lim = $self->{-httpbackend_limiter};
116 $g->{-httpbackend_limiter} = $lim if $lim;
117 _cleanup_later($self);
124 return if $self->version < 2;
125 my $cur = $self->{-max_git_epoch};
127 if (!defined($cur) || ($changed = git($self)->alternates_changed)) {
128 git_cleanup($self) if $changed;
129 my $gits = "$self->{inboxdir}/git";
130 if (opendir my $dh, $gits) {
132 substr($_, 0, -4) + 0; # drop ".git" suffix
133 } grep(/\A[0-9]+\.git\z/, readdir($dh))) // return;
134 $cur = $self->{-max_git_epoch} = $max;
141 my ($self, $req) = @_;
142 $self->{mm} //= eval {
143 require PublicInbox::Msgmap;
144 _cleanup_later($self);
145 my $dir = $self->{inboxdir};
146 if ($self->version >= 2) {
147 PublicInbox::Msgmap->new_file("$dir/msgmap.sqlite3");
149 PublicInbox::Msgmap->new($dir);
151 } // ($req ? croak("E: $@") : undef);
156 $self->{search} // eval {
157 _cleanup_later($self);
158 require PublicInbox::Search;
159 my $srch = PublicInbox::Search->new($self);
160 (eval { $srch->xdb }) ? ($self->{search} = $srch) : undef;
164 # isrch is preferred for read-only interfaces if available since it
165 # reduces kernel cache and FD overhead
166 sub isrch { $_[0]->{isrch} // search($_[0]) }
169 my ($self, $req) = @_;
170 $self->{over} // eval {
171 my $srch = $self->{search} // do {
172 require PublicInbox::Search;
173 PublicInbox::Search->new($self);
175 _cleanup_later($self);
176 my $over = PublicInbox::Over->new("$srch->{xpfx}/over.sqlite3");
177 $over->dbh; # may fail
178 $self->{over} = $over;
179 } // ($req ? croak("E: $@") : undef);
184 open(my $fh, '<', $path) or return '';
190 my $desc = try_cat($_[0]);
194 $desc =~ s/\s+/ /smg;
195 $desc eq '' ? undef : $desc;
200 ($self->{description} //= cat_desc("$self->{inboxdir}/description")) //
201 '($INBOX_DIR/description missing)';
206 $self->{cloneurl} // do {
207 my $s = try_cat("$self->{inboxdir}/cloneurl");
208 my @urls = split(/\s+/s, $s);
209 scalar(@urls) ? ($self->{cloneurl} = \@urls) : undef;
214 my ($self, $env) = @_; # env - PSGI env
215 if ($env && $env->{'psgi.url_scheme'}) {
216 my $url = PublicInbox::Git::host_prefix_url($env, '');
217 # for mount in Plack::Builder
218 $url .= '/' if $url !~ m!/\z!;
219 return $url .= $self->{name} . '/';
221 # called from a non-PSGI environment (e.g. NNTP/POP3):
222 $self->{-base_url} ||= do {
223 my $url = $self->{url} // return undef;
224 $url = $url->[0] // return undef;
225 # expand protocol-relative URLs to HTTPS if we're
226 # not inside a web server
227 $url = "https:$url" if $url =~ m!\A//!;
228 $url .= '/' if $url !~ m!/\z!;
234 my ($self, $x, $ctx) = @_; # $x is "nntp" or "imap"
235 # no checking for nntp_usable here, we can point entirely
236 # to non-local servers or users run by a different user
237 my $ns = $self->{"${x}server"} //
238 $ctx->{www}->{pi_cfg}->get_all("publicinbox.${x}server");
239 my $group = $self->{newsgroup};
243 my $u = m!\A${x}s?://! ? $_ : "$x://$_";
244 $u .= '/' if $u !~ m!/\z!;
248 if (my $mirrors = $self->{"${x}mirror"}) {
251 my $u = m!\A${x}s?://! ? $_ : "$x://$_";
252 if ($u =~ m!\A${x}s?://[^/]+/?\z!) {
254 $u .= '/' if $u !~ m!/\z!;
256 } else { # n.b. IMAP uses "newsgroup"
258 publicinbox.$self->{name}.${x}mirror=$_ missing newsgroup name
262 # else: allow full URLs like:
263 # nntp://news.example.com/alt.example
267 # List::Util::uniq requires Perl 5.26+, maybe we
268 # can use it by 2030 or so
270 @urls = grep { !$seen{$_}++ } (@urls, @m);
275 # my ($self, $ctx) = @_;
276 sub nntp_url { $_[0]->{-nntp_url} //= _x_url($_[0], 'nntp', $_[1]) }
277 sub imap_url { $_[0]->{-imap_url} //= _x_url($_[0], 'imap', $_[1]) }
281 my $ret = mm($self) && over($self);
282 delete @$self{qw(mm over search)};
286 # for v1 users w/o SQLite only
287 sub msg_by_path ($$) {
288 my ($self, $path) = @_;
289 git($self)->cat_file('HEAD:'.$path);
292 sub msg_by_smsg ($$) {
293 my ($self, $smsg) = @_;
295 # ghosts may have undef smsg (from SearchThread.node) or
297 return unless defined $smsg;
298 defined(my $blob = $smsg->{blob}) or return;
300 $self->git->cat_file($blob);
304 my ($self, $smsg) = @_;
305 my $bref = msg_by_smsg($self, $smsg) or return;
306 my $eml = PublicInbox::Eml->new($bref);
307 $smsg->populate($eml) unless exists($smsg->{num}); # v1 w/o SQLite
311 sub smsg_by_mid ($$) {
312 my ($self, $mid) = @_;
313 my $over = $self->over or return;
315 if (my $mm = $self->mm) {
316 # favor the Message-ID we used for the NNTP article number:
317 defined(my $num = $mm->num_for($mid)) or return;
318 $smsg = $over->get_art($num);
321 $smsg = $over->next_by_mid($mid, \$id, \$prev);
323 $smsg ? PublicInbox::Smsg::psgi_cull($smsg) : undef;
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));
333 my ($self, $opts, $after, $before) = @_;
334 $self->over->recent($opts, $after, $before);
339 if (my $over = $self->over) {
340 my $msgs = $over->recent({limit => 1});
341 if (my $smsg = $msgs->[0]) {
346 git($self)->modified; # v1
349 # returns prefix => pathname mapping
350 # (pathname is NOT public, but prefix is used for Xapian queries)
353 $self->{-altid_map} //= eval {
354 require PublicInbox::AltId;
355 my $altid = $self->{altid} or return {};
357 my $x = PublicInbox::AltId->new($self, $_);
358 "$x->{prefix}" => $x->{filename}
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;
370 sub unsubscribe_unlock {
371 my ($self, $ident) = @_;
372 delete $self->{unlock_subs}->{$ident};
375 sub check_inodes ($) {
378 $self->{$_}->check_inodes if $self->{$_};
386 my $subs = $self->{unlock_subs} or return;
387 for my $obj (values %$subs) {
388 eval { $obj->on_inbox_unlock($self) };
389 warn "E: $@ ($self->{inboxdir})\n" if $@;
393 sub uidvalidity { $_[0]->{uidvalidity} //= eval { $_[0]->mm->created_at } }
395 sub eidx_key { $_[0]->{newsgroup} // $_[0]->{inboxdir} }
397 sub mailboxid { # rfc 8474, 8620, 8621
398 my ($self, $imap_slice) = @_;
399 my $pfx = defined($imap_slice) ? $self->{newsgroup} : $self->{name};
400 utf8::encode($pfx); # to octets
401 # RFC 8620, 1.2 recommends not starting with dash or digits
402 # "A good solution to these issues is to prefix every id with a single
403 # alphabetical character."
404 'M'.join('', map { sprintf('%02x', ord) } split(//, $pfx)) .
405 (defined($imap_slice) ? sprintf('-%x', $imap_slice) : '') .
406 sprintf('-%x', uidvalidity($self) // 0)