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 $opts->{nntpserver} ||= $pi_cfg->{'publicinbox.nntpserver'};
114 # allow any combination of multi-line or comma-delimited hide entries
116 if (defined(my $h = $opts->{hide})) {
117 foreach my $v (@$h) {
118 $hide->{$_} = 1 foreach (split(/\s*,\s*/, $v));
120 $opts->{-hide} = $hide;
126 $_[0]->{version} //= -f "$_[0]->{inboxdir}/inbox.lock" ? 2 : 1
130 my ($self, $epoch) = @_; # v2-only, callers always supply $epoch
131 $self->{"$epoch.git"} ||= do {
132 my $git_dir = "$self->{inboxdir}/git/$epoch.git";
133 return unless -d $git_dir;
134 my $g = PublicInbox::Git->new($git_dir);
135 $g->{-httpbackend_limiter} = $self->{-httpbackend_limiter};
136 # caller must manually cleanup when done
143 $self->{git} ||= do {
144 my $git_dir = $self->{inboxdir};
145 $git_dir .= '/all.git' if $self->version == 2;
146 my $g = PublicInbox::Git->new($git_dir);
147 $g->{-httpbackend_limiter} = $self->{-httpbackend_limiter};
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!;
265 $self->{-nntp_url} ||= do {
266 # no checking for nntp_usable here, we can point entirely
267 # to non-local servers or users run by a different user
268 my $ns = $self->{nntpserver};
269 my $group = $self->{newsgroup};
272 $ns = [ $ns ] if ref($ns) ne 'ARRAY';
274 my $u = m!\Anntps?://! ? $_ : "nntp://$_";
275 $u .= '/' if $u !~ m!/\z!;
280 my $mirrors = $self->{nntpmirror};
283 foreach (@$mirrors) {
284 my $u = m!\Anntps?://! ? $_ : "nntp://$_";
285 if ($u =~ m!\Anntps?://[^/]+/?\z!) {
287 $u .= '/' if $u !~ m!/\z!;
291 "publicinbox.$self->{name}.nntpmirror=$_ missing newsgroup name\n";
294 # else: allow full URLs like:
295 # nntp://news.example.com/alt.example
299 # List::Util::uniq requires Perl 5.26+, maybe we
300 # can use it by 2030 or so
302 @urls = grep { !$seen{$_}++ } (@urls, @m);
310 my $ret = mm($self) && over($self);
311 $self->{mm} = $self->{over} = $self->{search} = undef;
315 # for v1 users w/o SQLite only
316 sub msg_by_path ($$) {
317 my ($self, $path) = @_;
318 git($self)->cat_file('HEAD:'.$path);
321 sub msg_by_smsg ($$) {
322 my ($self, $smsg) = @_;
324 # ghosts may have undef smsg (from SearchThread.node) or
326 return unless defined $smsg;
327 defined(my $blob = $smsg->{blob}) or return;
329 $self->git->cat_file($blob);
333 my ($self, $smsg) = @_;
334 my $bref = msg_by_smsg($self, $smsg) or return;
335 my $eml = PublicInbox::Eml->new($bref);
336 $smsg->populate($eml) unless exists($smsg->{num}); # v1 w/o SQLite
340 sub smsg_by_mid ($$) {
341 my ($self, $mid) = @_;
342 my $over = $self->over or return;
344 if (my $mm = $self->mm) {
345 # favor the Message-ID we used for the NNTP article number:
346 defined(my $num = $mm->num_for($mid)) or return;
347 $smsg = $over->get_art($num);
350 $smsg = $over->next_by_mid($mid, \$id, \$prev);
352 $smsg ? PublicInbox::Smsg::psgi_cull($smsg) : undef;
355 sub msg_by_mid ($$) {
356 my ($self, $mid) = @_;
357 my $smsg = smsg_by_mid($self, $mid);
358 $smsg ? msg_by_smsg($self, $smsg) : msg_by_path($self, mid2path($mid));
362 my ($self, $opts, $after, $before) = @_;
363 $self->over->recent($opts, $after, $before);
368 if (my $over = $self->over) {
369 my $msgs = $over->recent({limit => 1});
370 if (my $smsg = $msgs->[0]) {
375 git($self)->modified; # v1
378 # returns prefix => pathname mapping
379 # (pathname is NOT public, but prefix is used for Xapian queries)
382 $self->{-altid_map} //= eval {
383 require PublicInbox::AltId;
384 my $altid = $self->{altid} or return {};
386 my $x = PublicInbox::AltId->new($self, $_);
387 "$x->{prefix}" => $x->{filename}
393 # $obj must respond to ->on_inbox_unlock, which takes Inbox ($self) as an arg
394 sub subscribe_unlock {
395 my ($self, $ident, $obj) = @_;
396 $self->{unlock_subs}->{$ident} = $obj;
399 sub unsubscribe_unlock {
400 my ($self, $ident) = @_;
401 delete $self->{unlock_subs}->{$ident};
404 sub check_inodes ($) {
406 for (qw(over mm)) { # TODO: search
407 $self->{$_}->check_inodes if $self->{$_};
415 my $subs = $self->{unlock_subs} or return;
416 for my $obj (values %$subs) {
417 eval { $obj->on_inbox_unlock($self) };
418 warn "E: $@ ($self->{inboxdir})\n" if $@;
422 sub uidvalidity { $_[0]->{uidvalidity} //= eval { $_[0]->mm->created_at } }
424 sub eidx_key { $_[0]->{newsgroup} // $_[0]->{inboxdir} }
426 sub mailboxid { # rfc 8474, 8620, 8621
427 my ($self, $imap_slice) = @_;
428 my $pfx = defined($imap_slice) ? $self->{newsgroup} : $self->{name};
429 utf8::encode($pfx); # to octets
430 # RFC 8620, 1.2 recommends not starting with dash or digits
431 # "A good solution to these issues is to prefix every id with a single
432 # alphabetical character."
433 'M'.join('', map { sprintf('%02x', ord) } split(//, $pfx)) .
434 (defined($imap_slice) ? sprintf('-%x', $imap_slice) : '') .
435 sprintf('-%x', uidvalidity($self) // 0)