]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Inbox.pm
www: support publicinbox.imapserver
[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         # allow any combination of multi-line or comma-delimited hide entries
113         my $hide = {};
114         if (defined(my $h = $opts->{hide})) {
115                 foreach my $v (@$h) {
116                         $hide->{$_} = 1 foreach (split(/\s*,\s*/, $v));
117                 }
118                 $opts->{-hide} = $hide;
119         }
120         bless $opts, $class;
121 }
122
123 sub version {
124         $_[0]->{version} //= -f "$_[0]->{inboxdir}/inbox.lock" ? 2 : 1
125 }
126
127 sub git_epoch {
128         my ($self, $epoch) = @_; # v2-only, callers always supply $epoch
129         $self->{"$epoch.git"} ||= do {
130                 my $git_dir = "$self->{inboxdir}/git/$epoch.git";
131                 return unless -d $git_dir;
132                 my $g = PublicInbox::Git->new($git_dir);
133                 $g->{-httpbackend_limiter} = $self->{-httpbackend_limiter};
134                 # caller must manually cleanup when done
135                 $g;
136         };
137 }
138
139 sub git {
140         my ($self) = @_;
141         $self->{git} ||= do {
142                 my $git_dir = $self->{inboxdir};
143                 $git_dir .= '/all.git' if $self->version == 2;
144                 my $g = PublicInbox::Git->new($git_dir);
145                 $g->{-httpbackend_limiter} = $self->{-httpbackend_limiter};
146                 _cleanup_later($self);
147                 $g;
148         };
149 }
150
151 sub max_git_epoch {
152         my ($self) = @_;
153         return if $self->version < 2;
154         my $cur = $self->{-max_git_epoch};
155         my $changed;
156         if (!defined($cur) || ($changed = git($self)->alternates_changed)) {
157                 git_cleanup($self) if $changed;
158                 my $gits = "$self->{inboxdir}/git";
159                 if (opendir my $dh, $gits) {
160                         my $max = max(map {
161                                 substr($_, 0, -4) + 0; # drop ".git" suffix
162                         } grep(/\A[0-9]+\.git\z/, readdir($dh))) // return;
163                         $cur = $self->{-max_git_epoch} = $max;
164                 }
165         }
166         $cur;
167 }
168
169 sub mm {
170         my ($self, $req) = @_;
171         $self->{mm} //= eval {
172                 require PublicInbox::Msgmap;
173                 my $dir = $self->{inboxdir};
174                 if ($self->version >= 2) {
175                         PublicInbox::Msgmap->new_file("$dir/msgmap.sqlite3");
176                 } else {
177                         PublicInbox::Msgmap->new($dir);
178                 }
179         } // ($req ? croak("E: $@") : undef);
180 }
181
182 sub search {
183         my ($self) = @_;
184         my $srch = $self->{search} //= eval {
185                 _cleanup_later($self);
186                 require PublicInbox::Search;
187                 PublicInbox::Search->new($self);
188         };
189         (eval { $srch->xdb }) ? $srch : undef;
190 }
191
192 # isrch is preferred for read-only interfaces if available since it
193 # reduces kernel cache and FD overhead
194 sub isrch { $_[0]->{isrch} // search($_[0]) }
195
196 sub over {
197         my ($self, $req) = @_;
198         $self->{over} //= eval {
199                 my $srch = $self->{search} //= do {
200                         _cleanup_later($self);
201                         require PublicInbox::Search;
202                         PublicInbox::Search->new($self);
203                 };
204                 my $over = PublicInbox::Over->new("$srch->{xpfx}/over.sqlite3");
205                 $over->dbh; # may fail
206                 $over;
207         } // ($req ? croak("E: $@") : undef);
208 }
209
210 sub try_cat {
211         my ($path) = @_;
212         open(my $fh, '<', $path) or return '';
213         local $/;
214         <$fh> // '';
215 }
216
217 sub cat_desc ($) {
218         my $desc = try_cat($_[0]);
219         local $/ = "\n";
220         chomp $desc;
221         utf8::decode($desc);
222         $desc =~ s/\s+/ /smg;
223         $desc eq '' ? undef : $desc;
224 }
225
226 sub description {
227         my ($self) = @_;
228         ($self->{description} //= cat_desc("$self->{inboxdir}/description")) //
229                 '($INBOX_DIR/description missing)';
230 }
231
232 sub cloneurl {
233         my ($self) = @_;
234         ($self->{cloneurl} //= do {
235                 my $s = try_cat("$self->{inboxdir}/cloneurl");
236                 my @urls = split(/\s+/s, $s);
237                 scalar(@urls) ? \@urls : undef
238         }) // [];
239 }
240
241 sub base_url {
242         my ($self, $env) = @_; # env - PSGI env
243         if ($env && $env->{'psgi.url_scheme'}) {
244                 my $url = PublicInbox::Git::host_prefix_url($env, '');
245                 # for mount in Plack::Builder
246                 $url .= '/' if $url !~ m!/\z!;
247                 return $url .= $self->{name} . '/';
248         }
249         # called from a non-PSGI environment (e.g. NNTP/POP3):
250         $self->{-base_url} ||= do {
251                 my $url = $self->{url} // return undef;
252                 $url = $url->[0] // return undef;
253                 # expand protocol-relative URLs to HTTPS if we're
254                 # not inside a web server
255                 $url = "https:$url" if $url =~ m!\A//!;
256                 $url .= '/' if $url !~ m!/\z!;
257                 $url;
258         };
259 }
260
261 sub _x_url ($$$) {
262         my ($self, $x, $ctx) = @_; # $x is "nntp" or "imap"
263         # no checking for nntp_usable here, we can point entirely
264         # to non-local servers or users run by a different user
265         my $ns = $self->{"${x}server"} //
266                $ctx->{www}->{pi_cfg}->get_all("publicinbox.${x}server");
267         my $group = $self->{newsgroup};
268         my @urls;
269         if ($ns && $group) {
270                 @urls = map {
271                         my $u = m!\A${x}s?://! ? $_ : "$x://$_";
272                         $u .= '/' if $u !~ m!/\z!;
273                         $u.$group;
274                 } @$ns;
275         }
276         if (my $mirrors = $self->{"${x}mirror"}) {
277                 my @m;
278                 for (@$mirrors) {
279                         my $u = m!\A${x}s?://! ? $_ : "$x://$_";
280                         if ($u =~ m!\A${x}s?://[^/]+/?\z!) {
281                                 if ($group) {
282                                         $u .= '/' if $u !~ m!/\z!;
283                                         $u .= $group;
284                                 } else { # n.b. IMAP uses "newsgroup"
285                                         warn <<EOM;
286 publicinbox.$self->{name}.${x}mirror=$_ missing newsgroup name
287 EOM
288                                 }
289                         }
290                         # else: allow full URLs like:
291                         # nntp://news.example.com/alt.example
292                         push @m, $u;
293                 }
294
295                 # List::Util::uniq requires Perl 5.26+, maybe we
296                 # can use it by 2030 or so
297                 my %seen;
298                 @urls = grep { !$seen{$_}++ } (@urls, @m);
299         }
300         \@urls;
301 }
302
303 # my ($self, $ctx) = @_;
304 sub nntp_url { $_[0]->{-nntp_url} //= _x_url($_[0], 'nntp', $_[1]) }
305 sub imap_url { $_[0]->{-imap_url} //= _x_url($_[0], 'imap', $_[1]) }
306
307 sub nntp_usable {
308         my ($self) = @_;
309         my $ret = mm($self) && over($self);
310         $self->{mm} = $self->{over} = $self->{search} = undef;
311         $ret;
312 }
313
314 # for v1 users w/o SQLite only
315 sub msg_by_path ($$) {
316         my ($self, $path) = @_;
317         git($self)->cat_file('HEAD:'.$path);
318 }
319
320 sub msg_by_smsg ($$) {
321         my ($self, $smsg) = @_;
322
323         # ghosts may have undef smsg (from SearchThread.node) or
324         # no {blob} field
325         return unless defined $smsg;
326         defined(my $blob = $smsg->{blob}) or return;
327
328         $self->git->cat_file($blob);
329 }
330
331 sub smsg_eml {
332         my ($self, $smsg) = @_;
333         my $bref = msg_by_smsg($self, $smsg) or return;
334         my $eml = PublicInbox::Eml->new($bref);
335         $smsg->populate($eml) unless exists($smsg->{num}); # v1 w/o SQLite
336         $eml;
337 }
338
339 sub smsg_by_mid ($$) {
340         my ($self, $mid) = @_;
341         my $over = $self->over or return;
342         my $smsg;
343         if (my $mm = $self->mm) {
344                 # favor the Message-ID we used for the NNTP article number:
345                 defined(my $num = $mm->num_for($mid)) or return;
346                 $smsg = $over->get_art($num);
347         } else {
348                 my ($id, $prev);
349                 $smsg = $over->next_by_mid($mid, \$id, \$prev);
350         }
351         $smsg ? PublicInbox::Smsg::psgi_cull($smsg) : undef;
352 }
353
354 sub msg_by_mid ($$) {
355         my ($self, $mid) = @_;
356         my $smsg = smsg_by_mid($self, $mid);
357         $smsg ? msg_by_smsg($self, $smsg) : msg_by_path($self, mid2path($mid));
358 }
359
360 sub recent {
361         my ($self, $opts, $after, $before) = @_;
362         $self->over->recent($opts, $after, $before);
363 }
364
365 sub modified {
366         my ($self) = @_;
367         if (my $over = $self->over) {
368                 my $msgs = $over->recent({limit => 1});
369                 if (my $smsg = $msgs->[0]) {
370                         return $smsg->{ts};
371                 }
372                 return time;
373         }
374         git($self)->modified; # v1
375 }
376
377 # returns prefix => pathname mapping
378 # (pathname is NOT public, but prefix is used for Xapian queries)
379 sub altid_map ($) {
380         my ($self) = @_;
381         $self->{-altid_map} //= eval {
382                 require PublicInbox::AltId;
383                 my $altid = $self->{altid} or return {};
384                 my %h = map {;
385                         my $x = PublicInbox::AltId->new($self, $_);
386                         "$x->{prefix}" => $x->{filename}
387                 } @$altid;
388                 \%h;
389         } // {};
390 }
391
392 # $obj must respond to ->on_inbox_unlock, which takes Inbox ($self) as an arg
393 sub subscribe_unlock {
394         my ($self, $ident, $obj) = @_;
395         $self->{unlock_subs}->{$ident} = $obj;
396 }
397
398 sub unsubscribe_unlock {
399         my ($self, $ident) = @_;
400         delete $self->{unlock_subs}->{$ident};
401 }
402
403 sub check_inodes ($) {
404         my ($self) = @_;
405         for (qw(over mm)) { # TODO: search
406                 $self->{$_}->check_inodes if $self->{$_};
407         }
408 }
409
410 # called by inotify
411 sub on_unlock {
412         my ($self) = @_;
413         check_inodes($self);
414         my $subs = $self->{unlock_subs} or return;
415         for my $obj (values %$subs) {
416                 eval { $obj->on_inbox_unlock($self) };
417                 warn "E: $@ ($self->{inboxdir})\n" if $@;
418         }
419 }
420
421 sub uidvalidity { $_[0]->{uidvalidity} //= eval { $_[0]->mm->created_at } }
422
423 sub eidx_key { $_[0]->{newsgroup} // $_[0]->{inboxdir} }
424
425 sub mailboxid { # rfc 8474, 8620, 8621
426         my ($self, $imap_slice) = @_;
427         my $pfx = defined($imap_slice) ? $self->{newsgroup} : $self->{name};
428         utf8::encode($pfx); # to octets
429         # RFC 8620, 1.2 recommends not starting with dash or digits
430         # "A good solution to these issues is to prefix every id with a single
431         #  alphabetical character."
432         'M'.join('', map { sprintf('%02x', ord) } split(//, $pfx)) .
433                 (defined($imap_slice) ? sprintf('-%x', $imap_slice) : '') .
434                 sprintf('-%x', uidvalidity($self) // 0)
435 }
436
437 1;