]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Inbox.pm
msgmap: ->new_file to supports $ibx arg, drop ->new
[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 # returns true if further checking is required
14 sub check_inodes ($) {
15         for (qw(over mm)) { $_[0]->{$_}->check_inodes if $_[0]->{$_} }
16 }
17
18 sub do_cleanup {
19         my ($ibx) = @_;
20         my $live;
21         if (defined $ibx->{git}) {
22                 $live = $ibx->isa(__PACKAGE__) ? $ibx->{git}->cleanup(1)
23                                         : $ibx->{git}->cleanup_if_unlinked;
24                 delete($ibx->{git}) unless $live;
25         }
26         if ($live) {
27                 check_inodes($ibx);
28         } else {
29                 delete(@$ibx{qw(over mm description cloneurl
30                                 -imap_url -nntp_url)});
31         }
32         my $srch = $ibx->{search} // $ibx;
33         delete @$srch{qw(xdb qp)};
34         for my $git (@{$ibx->{-repo_objs} // []}) {
35                 $live = 1 if $git->cleanup(1);
36         }
37         PublicInbox::DS::add_uniq_timer($ibx+0, 5, \&do_cleanup, $ibx) if $live;
38 }
39
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, @_)
45 }
46
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;
54                 my $lim;
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;
61                 } else {
62                         warn "$mkey limiter=$val not understood\n";
63                 }
64                 $lim;
65         }
66 }
67
68 sub new {
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;
78         } else {
79                 delete $opts->{feedmax};
80         }
81         # allow any combination of multi-line or comma-delimited hide entries
82         my $hide = {};
83         if (defined(my $h = $opts->{hide})) {
84                 foreach my $v (@$h) {
85                         $hide->{$_} = 1 foreach (split(/\s*,\s*/, $v));
86                 }
87                 $opts->{-hide} = $hide;
88         }
89         bless $opts, $class;
90 }
91
92 sub version {
93         $_[0]->{version} //= -f "$_[0]->{inboxdir}/inbox.lock" ? 2 : 1
94 }
95
96 sub git_epoch {
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
105                 $g;
106         };
107 }
108
109 sub git {
110         my ($self) = @_;
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);
118                 $g;
119         };
120 }
121
122 sub max_git_epoch {
123         my ($self) = @_;
124         return if $self->version < 2;
125         my $cur = $self->{-max_git_epoch};
126         my $changed;
127         if (!defined($cur) || ($changed = git($self)->alternates_changed)) {
128                 $self->{git}->cleanup if $changed;
129                 my $gits = "$self->{inboxdir}/git";
130                 if (opendir my $dh, $gits) {
131                         my $max = max(map {
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;
135                 }
136         }
137         $cur;
138 }
139
140 sub mm_file {
141         my ($self) = @_;
142         my $d = $self->{inboxdir};
143         ($self->version >= 2 ? $d : "$d/public-inbox").'/msgmap.sqlite3';
144 }
145
146 sub mm {
147         my ($self, $req) = @_;
148         $self->{mm} //= eval {
149                 require PublicInbox::Msgmap;
150                 _cleanup_later($self);
151                 PublicInbox::Msgmap->new_file($self);
152         } // ($req ? croak("E: $@") : undef);
153 }
154
155 sub search {
156         my ($self) = @_;
157         $self->{search} // eval {
158                 _cleanup_later($self);
159                 require PublicInbox::Search;
160                 my $srch = PublicInbox::Search->new($self);
161                 (eval { $srch->xdb }) ? ($self->{search} = $srch) : undef;
162         };
163 }
164
165 # isrch is preferred for read-only interfaces if available since it
166 # reduces kernel cache and FD overhead
167 sub isrch { $_[0]->{isrch} // search($_[0]) }
168
169 sub over {
170         my ($self, $req) = @_;
171         $self->{over} // eval {
172                 my $srch = $self->{search} // do {
173                         require PublicInbox::Search;
174                         PublicInbox::Search->new($self);
175                 };
176                 _cleanup_later($self);
177                 my $over = PublicInbox::Over->new("$srch->{xpfx}/over.sqlite3");
178                 $over->dbh; # may fail
179                 $self->{over} = $over;
180         } // ($req ? croak("E: $@") : undef);
181 }
182
183 sub try_cat {
184         my ($path) = @_;
185         open(my $fh, '<', $path) or return '';
186         local $/;
187         <$fh> // '';
188 }
189
190 sub cat_desc ($) {
191         my $desc = try_cat($_[0]);
192         local $/ = "\n";
193         chomp $desc;
194         utf8::decode($desc);
195         $desc =~ s/\s+/ /smg;
196         $desc eq '' ? undef : $desc;
197 }
198
199 sub description {
200         my ($self) = @_;
201         ($self->{description} //= cat_desc("$self->{inboxdir}/description")) //
202                 '($INBOX_DIR/description missing)';
203 }
204
205 sub cloneurl {
206         my ($self) = @_;
207         $self->{cloneurl} // do {
208                 my $s = try_cat("$self->{inboxdir}/cloneurl");
209                 my @urls = split(/\s+/s, $s);
210                 scalar(@urls) ? ($self->{cloneurl} = \@urls) : undef;
211         } // [];
212 }
213
214 sub base_url {
215         my ($self, $env) = @_; # env - PSGI env
216         if ($env && $env->{'psgi.url_scheme'}) {
217                 my $url = PublicInbox::Git::host_prefix_url($env, '');
218                 # for mount in Plack::Builder
219                 $url .= '/' if $url !~ m!/\z!;
220                 return $url .= $self->{name} . '/';
221         }
222         # called from a non-PSGI environment (e.g. NNTP/POP3):
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         substr($url, 0, 0, 'https:') if substr($url, 0, 2) eq '//';
228         $url .= '/' if substr($url, -1, 1) ne '/';
229         $url;
230 }
231
232 sub _x_url ($$$) {
233         my ($self, $x, $ctx) = @_; # $x is "nntp" or "imap"
234         # no checking for nntp_usable here, we can point entirely
235         # to non-local servers or users run by a different user
236         my $ns = $self->{"${x}server"} //
237                $ctx->{www}->{pi_cfg}->get_all("publicinbox.${x}server");
238         my $group = $self->{newsgroup};
239         my @urls;
240         if ($ns && $group) {
241                 @urls = map {
242                         my $u = m!\A${x}s?://! ? $_ : "$x://$_";
243                         $u .= '/' if $u !~ m!/\z!;
244                         $u.$group;
245                 } @$ns;
246         }
247         if (my $mirrors = $self->{"${x}mirror"}) {
248                 my @m;
249                 for (@$mirrors) {
250                         my $u = m!\A${x}s?://! ? $_ : "$x://$_";
251                         if ($u =~ m!\A${x}s?://[^/]+/?\z!) {
252                                 if ($group) {
253                                         $u .= '/' if $u !~ m!/\z!;
254                                         $u .= $group;
255                                 } else { # n.b. IMAP uses "newsgroup"
256                                         warn <<EOM;
257 publicinbox.$self->{name}.${x}mirror=$_ missing newsgroup name
258 EOM
259                                 }
260                         }
261                         # else: allow full URLs like:
262                         # nntp://news.example.com/alt.example
263                         push @m, $u;
264                 }
265
266                 # List::Util::uniq requires Perl 5.26+, maybe we
267                 # can use it by 2030 or so
268                 my %seen;
269                 @urls = grep { !$seen{$_}++ } (@urls, @m);
270         }
271         \@urls;
272 }
273
274 # my ($self, $ctx) = @_;
275 sub nntp_url { $_[0]->{-nntp_url} //= _x_url($_[0], 'nntp', $_[1]) }
276 sub imap_url { $_[0]->{-imap_url} //= _x_url($_[0], 'imap', $_[1]) }
277
278 sub nntp_usable {
279         my ($self) = @_;
280         my $ret = mm($self) && over($self);
281         delete @$self{qw(mm over search)};
282         $ret;
283 }
284
285 # for v1 users w/o SQLite only
286 sub msg_by_path ($$) {
287         my ($self, $path) = @_;
288         git($self)->cat_file('HEAD:'.$path);
289 }
290
291 sub msg_by_smsg ($$) {
292         my ($self, $smsg) = @_;
293
294         # ghosts may have undef smsg (from SearchThread.node) or
295         # no {blob} field
296         return unless defined $smsg;
297         defined(my $blob = $smsg->{blob}) or return;
298
299         $self->git->cat_file($blob);
300 }
301
302 sub smsg_eml {
303         my ($self, $smsg) = @_;
304         my $bref = msg_by_smsg($self, $smsg) or return;
305         my $eml = PublicInbox::Eml->new($bref);
306         $smsg->populate($eml) unless exists($smsg->{num}); # v1 w/o SQLite
307         $eml;
308 }
309
310 sub smsg_by_mid ($$) {
311         my ($self, $mid) = @_;
312         my $over = $self->over or return;
313         my $smsg;
314         if (my $mm = $self->mm) {
315                 # favor the Message-ID we used for the NNTP article number:
316                 defined(my $num = $mm->num_for($mid)) or return;
317                 $smsg = $over->get_art($num);
318         } else {
319                 my ($id, $prev);
320                 $smsg = $over->next_by_mid($mid, \$id, \$prev);
321         }
322         $smsg ? PublicInbox::Smsg::psgi_cull($smsg) : undef;
323 }
324
325 sub msg_by_mid ($$) {
326         my ($self, $mid) = @_;
327         my $smsg = smsg_by_mid($self, $mid);
328         $smsg ? msg_by_smsg($self, $smsg) : msg_by_path($self, mid2path($mid));
329 }
330
331 sub recent {
332         my ($self, $opts, $after, $before) = @_;
333         $self->over->recent($opts, $after, $before);
334 }
335
336 sub modified {
337         my ($self) = @_;
338         if (my $over = $self->over) {
339                 my $msgs = $over->recent({limit => 1});
340                 if (my $smsg = $msgs->[0]) {
341                         return $smsg->{ts};
342                 }
343                 return time;
344         }
345         git($self)->modified; # v1
346 }
347
348 # returns prefix => pathname mapping
349 # (pathname is NOT public, but prefix is used for Xapian queries)
350 sub altid_map ($) {
351         my ($self) = @_;
352         eval {
353                 require PublicInbox::AltId;
354                 my $altid = $self->{altid} or return {};
355                 my %h = map {;
356                         my $x = PublicInbox::AltId->new($self, $_);
357                         "$x->{prefix}" => $x->{filename}
358                 } @$altid;
359                 \%h;
360         } // {};
361 }
362
363 # $obj must respond to ->on_inbox_unlock, which takes Inbox ($self) as an arg
364 sub subscribe_unlock {
365         my ($self, $ident, $obj) = @_;
366         $self->{unlock_subs}->{$ident} = $obj;
367 }
368
369 sub unsubscribe_unlock {
370         my ($self, $ident) = @_;
371         delete $self->{unlock_subs}->{$ident};
372 }
373
374 # called by inotify
375 sub on_unlock {
376         my ($self) = @_;
377         check_inodes($self);
378         my $subs = $self->{unlock_subs} or return;
379         for my $obj (values %$subs) {
380                 eval { $obj->on_inbox_unlock($self) };
381                 warn "E: $@ ($self->{inboxdir})\n" if $@;
382         }
383 }
384
385 sub uidvalidity { $_[0]->{uidvalidity} //= eval { $_[0]->mm->created_at } }
386
387 sub eidx_key { $_[0]->{newsgroup} // $_[0]->{inboxdir} }
388
389 sub mailboxid { # rfc 8474, 8620, 8621
390         my ($self, $imap_slice) = @_;
391         my $pfx = defined($imap_slice) ? $self->{newsgroup} : $self->{name};
392         utf8::encode($pfx); # to octets
393         # RFC 8620, 1.2 recommends not starting with dash or digits
394         # "A good solution to these issues is to prefix every id with a single
395         #  alphabetical character."
396         'M'.join('', map { sprintf('%02x', ord) } split(//, $pfx)) .
397                 (defined($imap_slice) ? sprintf('-%x', $imap_slice) : '') .
398                 sprintf('-%x', uidvalidity($self) // 0)
399 }
400
401 1;