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);
13 # Long-running "git-cat-file --batch" processes won't notice
14 # unlinked packs, so we need to restart those processes occasionally.
15 # Xapian and SQLite file handles are mostly stable, but sometimes an
16 # admin will attempt to replace them atomically after compact/vacuum
17 # and we need to be prepared for that.
19 my $cleanup_avail = -1; # 0, or 1
21 my $CLEANUP = {}; # string(inbox) -> inbox
25 my $git = $self->{git} or return;
30 $cleanup_timer = undef;
32 for my $ibx (values %$CLEANUP) {
34 if ($have_devel_peek) {
35 foreach my $f (qw(search)) {
36 # we bump refcnt by assigning tmp, here:
37 my $tmp = $ibx->{$f} or next;
38 next if Devel::Peek::SvREFCNT($tmp) > 2;
40 # refcnt is zero when tmp is out-of-scope
44 if (my $gits = $ibx->{-repo_objs}) {
45 foreach my $git (@$gits) {
46 $again = 1 if $git->cleanup;
50 if ($have_devel_peek) {
51 $again ||= !!$ibx->{search};
53 $next->{"$ibx"} = $ibx if $again;
58 sub cleanup_possible () {
59 # no need to require DS, here, if it were enabled another
60 # module would've require'd it, already
61 eval { PublicInbox::DS::in_loop() } or return 0;
64 require Devel::Peek; # needs separate package in Fedora
70 sub _cleanup_later ($) {
72 $cleanup_avail = cleanup_possible() if $cleanup_avail < 0;
73 return if $cleanup_avail != 1;
74 $cleanup_timer //= PublicInbox::DS::later(\&cleanup_task);
75 $CLEANUP->{"$self"} = $self;
78 sub _set_limiter ($$$) {
79 my ($self, $pi_cfg, $pfx) = @_;
80 my $lkey = "-${pfx}_limiter";
81 $self->{$lkey} ||= do {
82 # full key is: publicinbox.$NAME.httpbackendmax
83 my $mkey = $pfx.'max';
84 my $val = $self->{$mkey} or return;
86 if ($val =~ /\A[0-9]+\z/) {
87 require PublicInbox::Qspawn;
88 $lim = PublicInbox::Qspawn::Limiter->new($val);
89 } elsif ($val =~ /\A[a-z][a-z0-9]*\z/) {
90 $lim = $pi_cfg->limiter($val);
91 warn "$mkey limiter=$val not found\n" if !$lim;
93 warn "$mkey limiter=$val not understood\n";
100 my ($class, $opts) = @_;
101 my $v = $opts->{address} ||= [ 'public-inbox@example.com' ];
102 my $p = $opts->{-primary_address} = ref($v) eq 'ARRAY' ? $v->[0] : $v;
103 $opts->{domain} = ($p =~ /\@(\S+)\z/) ? $1 : 'localhost';
104 my $pi_cfg = delete $opts->{-pi_cfg};
105 _set_limiter($opts, $pi_cfg, 'httpbackend');
106 my $fmax = $opts->{feedmax};
107 if (defined($fmax) && $fmax =~ /\A[0-9]+\z/) {
108 $opts->{feedmax} += 0;
110 delete $opts->{feedmax};
112 # allow any combination of multi-line or comma-delimited hide entries
114 if (defined(my $h = $opts->{hide})) {
115 foreach my $v (@$h) {
116 $hide->{$_} = 1 foreach (split(/\s*,\s*/, $v));
118 $opts->{-hide} = $hide;
124 $_[0]->{version} //= -f "$_[0]->{inboxdir}/inbox.lock" ? 2 : 1
128 my ($self, $epoch) = @_; # v2-only, callers always supply $epoch
129 $self->{"$epoch.git"} //= do {
130 my $git_dir = "$self->{inboxdir}/git/$epoch.git";
131 return unless -d $git_dir;
132 my $g = PublicInbox::Git->new($git_dir);
133 my $lim = $self->{-httpbackend_limiter};
134 $g->{-httpbackend_limiter} = $lim if $lim;
135 # caller must manually cleanup when done
142 $self->{git} //= do {
143 my $git_dir = $self->{inboxdir};
144 $git_dir .= '/all.git' if $self->version == 2;
145 my $g = PublicInbox::Git->new($git_dir);
146 my $lim = $self->{-httpbackend_limiter};
147 $g->{-httpbackend_limiter} = $lim if $lim;
148 _cleanup_later($self);
155 return if $self->version < 2;
156 my $cur = $self->{-max_git_epoch};
158 if (!defined($cur) || ($changed = git($self)->alternates_changed)) {
159 git_cleanup($self) if $changed;
160 my $gits = "$self->{inboxdir}/git";
161 if (opendir my $dh, $gits) {
163 substr($_, 0, -4) + 0; # drop ".git" suffix
164 } grep(/\A[0-9]+\.git\z/, readdir($dh))) // return;
165 $cur = $self->{-max_git_epoch} = $max;
172 my ($self, $req) = @_;
173 $self->{mm} //= eval {
174 require PublicInbox::Msgmap;
175 my $dir = $self->{inboxdir};
176 if ($self->version >= 2) {
177 PublicInbox::Msgmap->new_file("$dir/msgmap.sqlite3");
179 PublicInbox::Msgmap->new($dir);
181 } // ($req ? croak("E: $@") : undef);
186 my $srch = $self->{search} //= eval {
187 _cleanup_later($self);
188 require PublicInbox::Search;
189 PublicInbox::Search->new($self);
191 (eval { $srch->xdb }) ? $srch : undef;
194 # isrch is preferred for read-only interfaces if available since it
195 # reduces kernel cache and FD overhead
196 sub isrch { $_[0]->{isrch} // search($_[0]) }
199 my ($self, $req) = @_;
200 $self->{over} //= eval {
201 my $srch = $self->{search} //= do {
202 _cleanup_later($self);
203 require PublicInbox::Search;
204 PublicInbox::Search->new($self);
206 my $over = PublicInbox::Over->new("$srch->{xpfx}/over.sqlite3");
207 $over->dbh; # may fail
209 } // ($req ? croak("E: $@") : undef);
214 open(my $fh, '<', $path) or return '';
220 my $desc = try_cat($_[0]);
224 $desc =~ s/\s+/ /smg;
225 $desc eq '' ? undef : $desc;
230 ($self->{description} //= cat_desc("$self->{inboxdir}/description")) //
231 '($INBOX_DIR/description missing)';
236 ($self->{cloneurl} //= do {
237 my $s = try_cat("$self->{inboxdir}/cloneurl");
238 my @urls = split(/\s+/s, $s);
239 scalar(@urls) ? \@urls : undef
244 my ($self, $env) = @_; # env - PSGI env
245 if ($env && $env->{'psgi.url_scheme'}) {
246 my $url = PublicInbox::Git::host_prefix_url($env, '');
247 # for mount in Plack::Builder
248 $url .= '/' if $url !~ m!/\z!;
249 return $url .= $self->{name} . '/';
251 # called from a non-PSGI environment (e.g. NNTP/POP3):
252 $self->{-base_url} ||= do {
253 my $url = $self->{url} // return undef;
254 $url = $url->[0] // return undef;
255 # expand protocol-relative URLs to HTTPS if we're
256 # not inside a web server
257 $url = "https:$url" if $url =~ m!\A//!;
258 $url .= '/' if $url !~ m!/\z!;
264 my ($self, $x, $ctx) = @_; # $x is "nntp" or "imap"
265 # no checking for nntp_usable here, we can point entirely
266 # to non-local servers or users run by a different user
267 my $ns = $self->{"${x}server"} //
268 $ctx->{www}->{pi_cfg}->get_all("publicinbox.${x}server");
269 my $group = $self->{newsgroup};
273 my $u = m!\A${x}s?://! ? $_ : "$x://$_";
274 $u .= '/' if $u !~ m!/\z!;
278 if (my $mirrors = $self->{"${x}mirror"}) {
281 my $u = m!\A${x}s?://! ? $_ : "$x://$_";
282 if ($u =~ m!\A${x}s?://[^/]+/?\z!) {
284 $u .= '/' if $u !~ m!/\z!;
286 } else { # n.b. IMAP uses "newsgroup"
288 publicinbox.$self->{name}.${x}mirror=$_ missing newsgroup name
292 # else: allow full URLs like:
293 # nntp://news.example.com/alt.example
297 # List::Util::uniq requires Perl 5.26+, maybe we
298 # can use it by 2030 or so
300 @urls = grep { !$seen{$_}++ } (@urls, @m);
305 # my ($self, $ctx) = @_;
306 sub nntp_url { $_[0]->{-nntp_url} //= _x_url($_[0], 'nntp', $_[1]) }
307 sub imap_url { $_[0]->{-imap_url} //= _x_url($_[0], 'imap', $_[1]) }
311 my $ret = mm($self) && over($self);
312 $self->{mm} = $self->{over} = $self->{search} = undef;
316 # for v1 users w/o SQLite only
317 sub msg_by_path ($$) {
318 my ($self, $path) = @_;
319 git($self)->cat_file('HEAD:'.$path);
322 sub msg_by_smsg ($$) {
323 my ($self, $smsg) = @_;
325 # ghosts may have undef smsg (from SearchThread.node) or
327 return unless defined $smsg;
328 defined(my $blob = $smsg->{blob}) or return;
330 $self->git->cat_file($blob);
334 my ($self, $smsg) = @_;
335 my $bref = msg_by_smsg($self, $smsg) or return;
336 my $eml = PublicInbox::Eml->new($bref);
337 $smsg->populate($eml) unless exists($smsg->{num}); # v1 w/o SQLite
341 sub smsg_by_mid ($$) {
342 my ($self, $mid) = @_;
343 my $over = $self->over or return;
345 if (my $mm = $self->mm) {
346 # favor the Message-ID we used for the NNTP article number:
347 defined(my $num = $mm->num_for($mid)) or return;
348 $smsg = $over->get_art($num);
351 $smsg = $over->next_by_mid($mid, \$id, \$prev);
353 $smsg ? PublicInbox::Smsg::psgi_cull($smsg) : undef;
356 sub msg_by_mid ($$) {
357 my ($self, $mid) = @_;
358 my $smsg = smsg_by_mid($self, $mid);
359 $smsg ? msg_by_smsg($self, $smsg) : msg_by_path($self, mid2path($mid));
363 my ($self, $opts, $after, $before) = @_;
364 $self->over->recent($opts, $after, $before);
369 if (my $over = $self->over) {
370 my $msgs = $over->recent({limit => 1});
371 if (my $smsg = $msgs->[0]) {
376 git($self)->modified; # v1
379 # returns prefix => pathname mapping
380 # (pathname is NOT public, but prefix is used for Xapian queries)
383 $self->{-altid_map} //= eval {
384 require PublicInbox::AltId;
385 my $altid = $self->{altid} or return {};
387 my $x = PublicInbox::AltId->new($self, $_);
388 "$x->{prefix}" => $x->{filename}
394 # $obj must respond to ->on_inbox_unlock, which takes Inbox ($self) as an arg
395 sub subscribe_unlock {
396 my ($self, $ident, $obj) = @_;
397 $self->{unlock_subs}->{$ident} = $obj;
400 sub unsubscribe_unlock {
401 my ($self, $ident) = @_;
402 delete $self->{unlock_subs}->{$ident};
405 sub check_inodes ($) {
407 for (qw(over mm)) { # TODO: search
408 $self->{$_}->check_inodes if $self->{$_};
416 my $subs = $self->{unlock_subs} or return;
417 for my $obj (values %$subs) {
418 eval { $obj->on_inbox_unlock($self) };
419 warn "E: $@ ($self->{inboxdir})\n" if $@;
423 sub uidvalidity { $_[0]->{uidvalidity} //= eval { $_[0]->mm->created_at } }
425 sub eidx_key { $_[0]->{newsgroup} // $_[0]->{inboxdir} }
427 sub mailboxid { # rfc 8474, 8620, 8621
428 my ($self, $imap_slice) = @_;
429 my $pfx = defined($imap_slice) ? $self->{newsgroup} : $self->{name};
430 utf8::encode($pfx); # to octets
431 # RFC 8620, 1.2 recommends not starting with dash or digits
432 # "A good solution to these issues is to prefix every id with a single
433 # alphabetical character."
434 'M'.join('', map { sprintf('%02x', ord) } split(//, $pfx)) .
435 (defined($imap_slice) ? sprintf('-%x', $imap_slice) : '') .
436 sprintf('-%x', uidvalidity($self) // 0)