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