]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Inbox.pm
www: avoid potential auto-vivification on ibx->{url}
[public-inbox.git] / lib / PublicInbox / Inbox.pm
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>
3 #
4 # Represents a public-inbox (which may have multiple mailing addresses)
5 package PublicInbox::Inbox;
6 use strict;
7 use PublicInbox::Git;
8 use PublicInbox::MID qw(mid2path);
9 use PublicInbox::Eml;
10 use List::Util qw(max);
11 use Carp qw(croak);
12
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.
18 my $cleanup_timer;
19 my $cleanup_avail = -1; # 0, or 1
20 my $have_devel_peek;
21 my $CLEANUP = {}; # string(inbox) -> inbox
22
23 sub git_cleanup ($) {
24         my ($self) = @_;
25         my $git = $self->{git} or return;
26         $git->cleanup;
27 }
28
29 sub cleanup_task () {
30         $cleanup_timer = undef;
31         my $next = {};
32         for my $ibx (values %$CLEANUP) {
33                 my $again;
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;
39                                 delete $ibx->{$f};
40                                 # refcnt is zero when tmp is out-of-scope
41                         }
42                 }
43                 git_cleanup($ibx);
44                 if (my $gits = $ibx->{-repo_objs}) {
45                         foreach my $git (@$gits) {
46                                 $again = 1 if $git->cleanup;
47                         }
48                 }
49                 check_inodes($ibx);
50                 if ($have_devel_peek) {
51                         $again ||= !!$ibx->{search};
52                 }
53                 $next->{"$ibx"} = $ibx if $again;
54         }
55         $CLEANUP = $next;
56 }
57
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;
62
63         eval {
64                 require Devel::Peek; # needs separate package in Fedora
65                 $have_devel_peek = 1;
66         };
67         1;
68 }
69
70 sub _cleanup_later ($) {
71         my ($self) = @_;
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;
76 }
77
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;
85                 my $lim;
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;
92                 } else {
93                         warn "$mkey limiter=$val not understood\n";
94                 }
95                 $lim;
96         }
97 }
98
99 sub new {
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;
109         } else {
110                 delete $opts->{feedmax};
111         }
112         $opts->{nntpserver} ||= $pi_cfg->{'publicinbox.nntpserver'};
113
114         # allow any combination of multi-line or comma-delimited hide entries
115         my $hide = {};
116         if (defined(my $h = $opts->{hide})) {
117                 foreach my $v (@$h) {
118                         $hide->{$_} = 1 foreach (split(/\s*,\s*/, $v));
119                 }
120                 $opts->{-hide} = $hide;
121         }
122         bless $opts, $class;
123 }
124
125 sub version {
126         $_[0]->{version} //= -f "$_[0]->{inboxdir}/inbox.lock" ? 2 : 1
127 }
128
129 sub git_epoch {
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
137                 $g;
138         };
139 }
140
141 sub git {
142         my ($self) = @_;
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);
149                 $g;
150         };
151 }
152
153 sub max_git_epoch {
154         my ($self) = @_;
155         return if $self->version < 2;
156         my $cur = $self->{-max_git_epoch};
157         my $changed;
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) {
162                         my $max = max(map {
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;
166                 }
167         }
168         $cur;
169 }
170
171 sub mm {
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");
178                 } else {
179                         PublicInbox::Msgmap->new($dir);
180                 }
181         } // ($req ? croak("E: $@") : undef);
182 }
183
184 sub search {
185         my ($self) = @_;
186         my $srch = $self->{search} //= eval {
187                 _cleanup_later($self);
188                 require PublicInbox::Search;
189                 PublicInbox::Search->new($self);
190         };
191         (eval { $srch->xdb }) ? $srch : undef;
192 }
193
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]) }
197
198 sub over {
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);
205                 };
206                 my $over = PublicInbox::Over->new("$srch->{xpfx}/over.sqlite3");
207                 $over->dbh; # may fail
208                 $over;
209         } // ($req ? croak("E: $@") : undef);
210 }
211
212 sub try_cat {
213         my ($path) = @_;
214         open(my $fh, '<', $path) or return '';
215         local $/;
216         <$fh> // '';
217 }
218
219 sub cat_desc ($) {
220         my $desc = try_cat($_[0]);
221         local $/ = "\n";
222         chomp $desc;
223         utf8::decode($desc);
224         $desc =~ s/\s+/ /smg;
225         $desc eq '' ? undef : $desc;
226 }
227
228 sub description {
229         my ($self) = @_;
230         ($self->{description} //= cat_desc("$self->{inboxdir}/description")) //
231                 '($INBOX_DIR/description missing)';
232 }
233
234 sub cloneurl {
235         my ($self) = @_;
236         ($self->{cloneurl} //= do {
237                 my $s = try_cat("$self->{inboxdir}/cloneurl");
238                 my @urls = split(/\s+/s, $s);
239                 scalar(@urls) ? \@urls : undef
240         }) // [];
241 }
242
243 sub base_url {
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} . '/';
250         }
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!;
259                 $url;
260         };
261 }
262
263 sub nntp_url {
264         my ($self) = @_;
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};
270                 my @urls;
271                 if ($ns && $group) {
272                         $ns = [ $ns ] if ref($ns) ne 'ARRAY';
273                         @urls = map {
274                                 my $u = m!\Anntps?://! ? $_ : "nntp://$_";
275                                 $u .= '/' if $u !~ m!/\z!;
276                                 $u.$group;
277                         } @$ns;
278                 }
279
280                 my $mirrors = $self->{nntpmirror};
281                 if ($mirrors) {
282                         my @m;
283                         foreach (@$mirrors) {
284                                 my $u = m!\Anntps?://! ? $_ : "nntp://$_";
285                                 if ($u =~ m!\Anntps?://[^/]+/?\z!) {
286                                         if ($group) {
287                                                 $u .= '/' if $u !~ m!/\z!;
288                                                 $u .= $group;
289                                         } else {
290                                                 warn
291 "publicinbox.$self->{name}.nntpmirror=$_ missing newsgroup name\n";
292                                         }
293                                 }
294                                 # else: allow full URLs like:
295                                 # nntp://news.example.com/alt.example
296                                 push @m, $u;
297                         }
298
299                         # List::Util::uniq requires Perl 5.26+, maybe we
300                         # can use it by 2030 or so
301                         my %seen;
302                         @urls = grep { !$seen{$_}++ } (@urls, @m);
303                 }
304                 \@urls;
305         };
306 }
307
308 sub nntp_usable {
309         my ($self) = @_;
310         my $ret = mm($self) && over($self);
311         $self->{mm} = $self->{over} = $self->{search} = undef;
312         $ret;
313 }
314
315 # for v1 users w/o SQLite only
316 sub msg_by_path ($$) {
317         my ($self, $path) = @_;
318         git($self)->cat_file('HEAD:'.$path);
319 }
320
321 sub msg_by_smsg ($$) {
322         my ($self, $smsg) = @_;
323
324         # ghosts may have undef smsg (from SearchThread.node) or
325         # no {blob} field
326         return unless defined $smsg;
327         defined(my $blob = $smsg->{blob}) or return;
328
329         $self->git->cat_file($blob);
330 }
331
332 sub smsg_eml {
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
337         $eml;
338 }
339
340 sub smsg_by_mid ($$) {
341         my ($self, $mid) = @_;
342         my $over = $self->over or return;
343         my $smsg;
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);
348         } else {
349                 my ($id, $prev);
350                 $smsg = $over->next_by_mid($mid, \$id, \$prev);
351         }
352         $smsg ? PublicInbox::Smsg::psgi_cull($smsg) : undef;
353 }
354
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));
359 }
360
361 sub recent {
362         my ($self, $opts, $after, $before) = @_;
363         $self->over->recent($opts, $after, $before);
364 }
365
366 sub modified {
367         my ($self) = @_;
368         if (my $over = $self->over) {
369                 my $msgs = $over->recent({limit => 1});
370                 if (my $smsg = $msgs->[0]) {
371                         return $smsg->{ts};
372                 }
373                 return time;
374         }
375         git($self)->modified; # v1
376 }
377
378 # returns prefix => pathname mapping
379 # (pathname is NOT public, but prefix is used for Xapian queries)
380 sub altid_map ($) {
381         my ($self) = @_;
382         $self->{-altid_map} //= eval {
383                 require PublicInbox::AltId;
384                 my $altid = $self->{altid} or return {};
385                 my %h = map {;
386                         my $x = PublicInbox::AltId->new($self, $_);
387                         "$x->{prefix}" => $x->{filename}
388                 } @$altid;
389                 \%h;
390         } // {};
391 }
392
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;
397 }
398
399 sub unsubscribe_unlock {
400         my ($self, $ident) = @_;
401         delete $self->{unlock_subs}->{$ident};
402 }
403
404 sub check_inodes ($) {
405         my ($self) = @_;
406         for (qw(over mm)) { # TODO: search
407                 $self->{$_}->check_inodes if $self->{$_};
408         }
409 }
410
411 # called by inotify
412 sub on_unlock {
413         my ($self) = @_;
414         check_inodes($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 $@;
419         }
420 }
421
422 sub uidvalidity { $_[0]->{uidvalidity} //= eval { $_[0]->mm->created_at } }
423
424 sub eidx_key { $_[0]->{newsgroup} // $_[0]->{inboxdir} }
425
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)
436 }
437
438 1;