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 if ($self->isa(__PACKAGE__)) {
26 # normal Inbox; low startup cost, and likely to have many
27 # many so this keeps process/pipe counts in check
28 $self->{git}->cleanup if $self->{git};
30 # ExtSearch, high startup cost if ->ALL, and probably
31 # only one per-daemon, so teardown only if required:
32 $self->git->cleanup_if_unlinked;
37 $cleanup_timer = undef;
39 for my $ibx (values %$CLEANUP) {
41 if ($have_devel_peek) {
42 foreach my $f (qw(search)) {
43 # we bump refcnt by assigning tmp, here:
44 my $tmp = $ibx->{$f} or next;
45 next if Devel::Peek::SvREFCNT($tmp) > 2;
47 # refcnt is zero when tmp is out-of-scope
51 if (my $gits = $ibx->{-repo_objs}) {
52 foreach my $git (@$gits) {
53 $again = 1 if $git->cleanup;
57 if ($have_devel_peek) {
58 $again ||= !!$ibx->{search};
60 $next->{"$ibx"} = $ibx if $again;
65 sub cleanup_possible () {
66 # no need to require DS, here, if it were enabled another
67 # module would've require'd it, already
68 eval { PublicInbox::DS::in_loop() } or return 0;
71 require Devel::Peek; # needs separate package in Fedora
77 sub _cleanup_later ($) {
79 $cleanup_avail = cleanup_possible() if $cleanup_avail < 0;
80 return if $cleanup_avail != 1;
81 $cleanup_timer //= PublicInbox::DS::later(\&cleanup_task);
82 $CLEANUP->{"$self"} = $self;
85 sub _set_limiter ($$$) {
86 my ($self, $pi_cfg, $pfx) = @_;
87 my $lkey = "-${pfx}_limiter";
88 $self->{$lkey} ||= do {
89 # full key is: publicinbox.$NAME.httpbackendmax
90 my $mkey = $pfx.'max';
91 my $val = $self->{$mkey} or return;
93 if ($val =~ /\A[0-9]+\z/) {
94 require PublicInbox::Qspawn;
95 $lim = PublicInbox::Qspawn::Limiter->new($val);
96 } elsif ($val =~ /\A[a-z][a-z0-9]*\z/) {
97 $lim = $pi_cfg->limiter($val);
98 warn "$mkey limiter=$val not found\n" if !$lim;
100 warn "$mkey limiter=$val not understood\n";
107 my ($class, $opts) = @_;
108 my $v = $opts->{address} ||= [ 'public-inbox@example.com' ];
109 my $p = $opts->{-primary_address} = ref($v) eq 'ARRAY' ? $v->[0] : $v;
110 $opts->{domain} = ($p =~ /\@(\S+)\z/) ? $1 : 'localhost';
111 my $pi_cfg = delete $opts->{-pi_cfg};
112 _set_limiter($opts, $pi_cfg, 'httpbackend');
113 my $fmax = $opts->{feedmax};
114 if (defined($fmax) && $fmax =~ /\A[0-9]+\z/) {
115 $opts->{feedmax} += 0;
117 delete $opts->{feedmax};
119 # allow any combination of multi-line or comma-delimited hide entries
121 if (defined(my $h = $opts->{hide})) {
122 foreach my $v (@$h) {
123 $hide->{$_} = 1 foreach (split(/\s*,\s*/, $v));
125 $opts->{-hide} = $hide;
131 $_[0]->{version} //= -f "$_[0]->{inboxdir}/inbox.lock" ? 2 : 1
135 my ($self, $epoch) = @_; # v2-only, callers always supply $epoch
136 $self->{"$epoch.git"} //= do {
137 my $git_dir = "$self->{inboxdir}/git/$epoch.git";
138 return unless -d $git_dir;
139 my $g = PublicInbox::Git->new($git_dir);
140 my $lim = $self->{-httpbackend_limiter};
141 $g->{-httpbackend_limiter} = $lim if $lim;
142 # caller must manually cleanup when done
149 $self->{git} //= do {
150 my $git_dir = $self->{inboxdir};
151 $git_dir .= '/all.git' if $self->version == 2;
152 my $g = PublicInbox::Git->new($git_dir);
153 my $lim = $self->{-httpbackend_limiter};
154 $g->{-httpbackend_limiter} = $lim if $lim;
155 _cleanup_later($self);
162 return if $self->version < 2;
163 my $cur = $self->{-max_git_epoch};
165 if (!defined($cur) || ($changed = git($self)->alternates_changed)) {
166 git_cleanup($self) if $changed;
167 my $gits = "$self->{inboxdir}/git";
168 if (opendir my $dh, $gits) {
170 substr($_, 0, -4) + 0; # drop ".git" suffix
171 } grep(/\A[0-9]+\.git\z/, readdir($dh))) // return;
172 $cur = $self->{-max_git_epoch} = $max;
179 my ($self, $req) = @_;
180 $self->{mm} //= eval {
181 require PublicInbox::Msgmap;
182 my $dir = $self->{inboxdir};
183 if ($self->version >= 2) {
184 PublicInbox::Msgmap->new_file("$dir/msgmap.sqlite3");
186 PublicInbox::Msgmap->new($dir);
188 } // ($req ? croak("E: $@") : undef);
193 my $srch = $self->{search} //= eval {
194 _cleanup_later($self);
195 require PublicInbox::Search;
196 PublicInbox::Search->new($self);
198 (eval { $srch->xdb }) ? $srch : undef;
201 # isrch is preferred for read-only interfaces if available since it
202 # reduces kernel cache and FD overhead
203 sub isrch { $_[0]->{isrch} // search($_[0]) }
206 my ($self, $req) = @_;
207 $self->{over} //= eval {
208 my $srch = $self->{search} //= do {
209 _cleanup_later($self);
210 require PublicInbox::Search;
211 PublicInbox::Search->new($self);
213 my $over = PublicInbox::Over->new("$srch->{xpfx}/over.sqlite3");
214 $over->dbh; # may fail
216 } // ($req ? croak("E: $@") : undef);
221 open(my $fh, '<', $path) or return '';
227 my $desc = try_cat($_[0]);
231 $desc =~ s/\s+/ /smg;
232 $desc eq '' ? undef : $desc;
237 ($self->{description} //= cat_desc("$self->{inboxdir}/description")) //
238 '($INBOX_DIR/description missing)';
243 ($self->{cloneurl} //= do {
244 my $s = try_cat("$self->{inboxdir}/cloneurl");
245 my @urls = split(/\s+/s, $s);
246 scalar(@urls) ? \@urls : undef
251 my ($self, $env) = @_; # env - PSGI env
252 if ($env && $env->{'psgi.url_scheme'}) {
253 my $url = PublicInbox::Git::host_prefix_url($env, '');
254 # for mount in Plack::Builder
255 $url .= '/' if $url !~ m!/\z!;
256 return $url .= $self->{name} . '/';
258 # called from a non-PSGI environment (e.g. NNTP/POP3):
259 $self->{-base_url} ||= do {
260 my $url = $self->{url} // return undef;
261 $url = $url->[0] // return undef;
262 # expand protocol-relative URLs to HTTPS if we're
263 # not inside a web server
264 $url = "https:$url" if $url =~ m!\A//!;
265 $url .= '/' if $url !~ m!/\z!;
271 my ($self, $x, $ctx) = @_; # $x is "nntp" or "imap"
272 # no checking for nntp_usable here, we can point entirely
273 # to non-local servers or users run by a different user
274 my $ns = $self->{"${x}server"} //
275 $ctx->{www}->{pi_cfg}->get_all("publicinbox.${x}server");
276 my $group = $self->{newsgroup};
280 my $u = m!\A${x}s?://! ? $_ : "$x://$_";
281 $u .= '/' if $u !~ m!/\z!;
285 if (my $mirrors = $self->{"${x}mirror"}) {
288 my $u = m!\A${x}s?://! ? $_ : "$x://$_";
289 if ($u =~ m!\A${x}s?://[^/]+/?\z!) {
291 $u .= '/' if $u !~ m!/\z!;
293 } else { # n.b. IMAP uses "newsgroup"
295 publicinbox.$self->{name}.${x}mirror=$_ missing newsgroup name
299 # else: allow full URLs like:
300 # nntp://news.example.com/alt.example
304 # List::Util::uniq requires Perl 5.26+, maybe we
305 # can use it by 2030 or so
307 @urls = grep { !$seen{$_}++ } (@urls, @m);
312 # my ($self, $ctx) = @_;
313 sub nntp_url { $_[0]->{-nntp_url} //= _x_url($_[0], 'nntp', $_[1]) }
314 sub imap_url { $_[0]->{-imap_url} //= _x_url($_[0], 'imap', $_[1]) }
318 my $ret = mm($self) && over($self);
319 $self->{mm} = $self->{over} = $self->{search} = undef;
323 # for v1 users w/o SQLite only
324 sub msg_by_path ($$) {
325 my ($self, $path) = @_;
326 git($self)->cat_file('HEAD:'.$path);
329 sub msg_by_smsg ($$) {
330 my ($self, $smsg) = @_;
332 # ghosts may have undef smsg (from SearchThread.node) or
334 return unless defined $smsg;
335 defined(my $blob = $smsg->{blob}) or return;
337 $self->git->cat_file($blob);
341 my ($self, $smsg) = @_;
342 my $bref = msg_by_smsg($self, $smsg) or return;
343 my $eml = PublicInbox::Eml->new($bref);
344 $smsg->populate($eml) unless exists($smsg->{num}); # v1 w/o SQLite
348 sub smsg_by_mid ($$) {
349 my ($self, $mid) = @_;
350 my $over = $self->over or return;
352 if (my $mm = $self->mm) {
353 # favor the Message-ID we used for the NNTP article number:
354 defined(my $num = $mm->num_for($mid)) or return;
355 $smsg = $over->get_art($num);
358 $smsg = $over->next_by_mid($mid, \$id, \$prev);
360 $smsg ? PublicInbox::Smsg::psgi_cull($smsg) : undef;
363 sub msg_by_mid ($$) {
364 my ($self, $mid) = @_;
365 my $smsg = smsg_by_mid($self, $mid);
366 $smsg ? msg_by_smsg($self, $smsg) : msg_by_path($self, mid2path($mid));
370 my ($self, $opts, $after, $before) = @_;
371 $self->over->recent($opts, $after, $before);
376 if (my $over = $self->over) {
377 my $msgs = $over->recent({limit => 1});
378 if (my $smsg = $msgs->[0]) {
383 git($self)->modified; # v1
386 # returns prefix => pathname mapping
387 # (pathname is NOT public, but prefix is used for Xapian queries)
390 $self->{-altid_map} //= eval {
391 require PublicInbox::AltId;
392 my $altid = $self->{altid} or return {};
394 my $x = PublicInbox::AltId->new($self, $_);
395 "$x->{prefix}" => $x->{filename}
401 # $obj must respond to ->on_inbox_unlock, which takes Inbox ($self) as an arg
402 sub subscribe_unlock {
403 my ($self, $ident, $obj) = @_;
404 $self->{unlock_subs}->{$ident} = $obj;
407 sub unsubscribe_unlock {
408 my ($self, $ident) = @_;
409 delete $self->{unlock_subs}->{$ident};
412 sub check_inodes ($) {
414 for (qw(over mm)) { # TODO: search
415 $self->{$_}->check_inodes if $self->{$_};
423 my $subs = $self->{unlock_subs} or return;
424 for my $obj (values %$subs) {
425 eval { $obj->on_inbox_unlock($self) };
426 warn "E: $@ ($self->{inboxdir})\n" if $@;
430 sub uidvalidity { $_[0]->{uidvalidity} //= eval { $_[0]->mm->created_at } }
432 sub eidx_key { $_[0]->{newsgroup} // $_[0]->{inboxdir} }
434 sub mailboxid { # rfc 8474, 8620, 8621
435 my ($self, $imap_slice) = @_;
436 my $pfx = defined($imap_slice) ? $self->{newsgroup} : $self->{name};
437 utf8::encode($pfx); # to octets
438 # RFC 8620, 1.2 recommends not starting with dash or digits
439 # "A good solution to these issues is to prefix every id with a single
440 # alphabetical character."
441 'M'.join('', map { sprintf('%02x', ord) } split(//, $pfx)) .
442 (defined($imap_slice) ? sprintf('-%x', $imap_slice) : '') .
443 sprintf('-%x', uidvalidity($self) // 0)