]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Inbox.pm
No ext_urls
[public-inbox.git] / lib / PublicInbox / Inbox.pm
1 # Copyright (C) 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 -pop3_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 description {
185         my ($self) = @_;
186         ($self->{description} //=
187                 PublicInbox::Git::cat_desc("$self->{inboxdir}/description")) //
188                 '($INBOX_DIR/description missing)';
189 }
190
191 sub cloneurl {
192         my ($self) = @_;
193         $self->{cloneurl} // do {
194                 my @urls = split(/\s+/s,
195                   PublicInbox::Git::try_cat("$self->{inboxdir}/cloneurl"));
196                 scalar(@urls) ? ($self->{cloneurl} = \@urls) : undef;
197         } // [];
198 }
199
200 sub base_url {
201         my ($self, $env) = @_; # env - PSGI env
202         if ($env && $env->{'psgi.url_scheme'}) {
203                 my $url = PublicInbox::Git::host_prefix_url($env, '');
204                 # for mount in Plack::Builder
205                 $url .= '/' if $url !~ m!/\z!;
206                 return $url .= $self->{name} . '/';
207         }
208         # called from a non-PSGI environment or cross-inbox environment
209         # where multiple inboxes can have different domains
210         my $url = $self->{url} // return undef;
211         $url = $url->[0] // return undef;
212         # expand protocol-relative URLs to HTTPS if we're
213         # not inside a web server
214         substr($url, 0, 0, 'https:') if substr($url, 0, 2) eq '//';
215         $url .= '/' if substr($url, -1, 1) ne '/';
216         $url;
217 }
218
219 # imapserver, nntpserver configs are used here:
220 sub _x_url ($$$) {
221         my ($self, $x, $ctx) = @_; # $x is "imap" or "nntp"
222         # no checking for nntp_usable here, we can point entirely
223         # to non-local servers or users run by a different user
224         my $ns = $self->{"${x}server"} //
225                $ctx->{www}->{pi_cfg}->get_all("publicinbox.${x}server");
226         my $group = $self->{newsgroup};
227         my @urls;
228         if ($ns && $group) {
229                 @urls = map {
230                         my $u = m!\A${x}s?://! ? $_ : "$x://$_";
231                         $u .= '/' if $u !~ m!/\z!;
232                         $u.$group;
233                 } @$ns;
234         }
235         if (my $mirrors = $self->{"${x}mirror"}) {
236                 my @m;
237                 for (@$mirrors) {
238                         my $u = m!\A${x}s?://! ? $_ : "$x://$_";
239                         if ($u =~ m!\A${x}s?://[^/]+/?\z!) {
240                                 if ($group) {
241                                         $u .= '/' if $u !~ m!/\z!;
242                                         $u .= $group;
243                                 } else { # n.b. IMAP and POP3 use "newsgroup"
244                                         warn <<EOM;
245 publicinbox.$self->{name}.${x}mirror=$_ missing newsgroup name
246 EOM
247                                 }
248                         }
249                         # else: allow full URLs like:
250                         # nntp://news.example.com/alt.example
251                         push @m, $u;
252                 }
253
254                 # List::Util::uniq requires Perl 5.26+, maybe we
255                 # can use it by 2030 or so
256                 my %seen;
257                 @urls = grep { !$seen{$_}++ } (@urls, @m);
258         }
259         \@urls;
260 }
261
262 # my ($self, $ctx) = @_;
263 sub imap_url { $_[0]->{-imap_url} //= _x_url($_[0], 'imap', $_[1]) }
264 sub nntp_url { $_[0]->{-nntp_url} //= _x_url($_[0], 'nntp', $_[1]) }
265
266 sub pop3_url {
267         my ($self, $ctx) = @_;
268         $self->{-pop3_url} //= do {
269                 my $ps = $self->{'pop3server'} //
270                        $ctx->{www}->{pi_cfg}->get_all('publicinbox.pop3server');
271                 my $group = $self->{newsgroup};
272                 my @urls;
273                 ($ps && $group) and
274                         @urls = map { m!\Apop3?s?://! ? $_ : "pop3://$_" } @$ps;
275                 if (my $mi = $self->{'pop3mirror'}) {
276                         my @m = map { m!\Apop3?s?://! ? $_ : "pop3://$_" } @$mi;
277                         my %seen; # List::Util::uniq requires Perl 5.26+
278                         @urls = grep { !$seen{$_}++ } (@urls, @m);
279                 }
280                 my $n = 0;
281                 for (@urls) { $n += s!/+\z!! }
282                 warn <<EOM if $n;
283 W: pop3server and/or pop3mirror URLs should not end with trailing slash `/'
284 EOM
285                 \@urls;
286         }
287 }
288
289 sub nntp_usable {
290         my ($self) = @_;
291         my $ret = mm($self) && over($self);
292         delete @$self{qw(mm over search)};
293         $ret;
294 }
295
296 # for v1 users w/o SQLite only
297 sub msg_by_path ($$) {
298         my ($self, $path) = @_;
299         git($self)->cat_file('HEAD:'.$path);
300 }
301
302 sub msg_by_smsg ($$) {
303         my ($self, $smsg) = @_;
304
305         # ghosts may have undef smsg (from SearchThread.node) or
306         # no {blob} field
307         $smsg // return;
308         $self->git->cat_file($smsg->{blob} // return);
309 }
310
311 sub smsg_eml {
312         my ($self, $smsg) = @_;
313         my $bref = msg_by_smsg($self, $smsg) or return;
314         my $eml = PublicInbox::Eml->new($bref);
315         $smsg->{num} // $smsg->populate($eml);
316         $eml;
317 }
318
319 sub smsg_by_mid ($$) {
320         my ($self, $mid) = @_;
321         my $over = $self->over or return;
322         my $smsg;
323         if (my $mm = $self->mm) {
324                 # favor the Message-ID we used for the NNTP article number:
325                 my $num = $mm->num_for($mid) // return;
326                 $smsg = $over->get_art($num);
327         } else {
328                 my ($id, $prev);
329                 $smsg = $over->next_by_mid($mid, \$id, \$prev);
330         }
331         $smsg ? PublicInbox::Smsg::psgi_cull($smsg) : undef;
332 }
333
334 sub msg_by_mid ($$) {
335         my ($self, $mid) = @_;
336         my $smsg = smsg_by_mid($self, $mid);
337         $smsg ? msg_by_smsg($self, $smsg) : msg_by_path($self, mid2path($mid));
338 }
339
340 sub modified {
341         my ($self) = @_;
342         if (my $over = $self->over) {
343                 my $msgs = $over->recent({limit => 1});
344                 if (my $smsg = $msgs->[0]) {
345                         return $smsg->{ts};
346                 }
347                 return time;
348         }
349         git($self)->modified; # v1
350 }
351
352 # returns prefix => pathname mapping
353 # (pathname is NOT public, but prefix is used for Xapian queries)
354 sub altid_map ($) {
355         my ($self) = @_;
356         eval {
357                 require PublicInbox::AltId;
358                 my $altid = $self->{altid} or return {};
359                 my %h = map {;
360                         my $x = PublicInbox::AltId->new($self, $_);
361                         "$x->{prefix}" => $x->{filename}
362                 } @$altid;
363                 \%h;
364         } // {};
365 }
366
367 # $obj must respond to ->on_inbox_unlock, which takes Inbox ($self) as an arg
368 sub subscribe_unlock {
369         my ($self, $ident, $obj) = @_;
370         $self->{unlock_subs}->{$ident} = $obj;
371 }
372
373 sub unsubscribe_unlock {
374         my ($self, $ident) = @_;
375         delete $self->{unlock_subs}->{$ident};
376 }
377
378 # called by inotify
379 sub on_unlock {
380         my ($self) = @_;
381         check_inodes($self);
382         my $subs = $self->{unlock_subs} or return;
383         for my $obj (values %$subs) {
384                 eval { $obj->on_inbox_unlock($self) };
385                 warn "E: $@ ($self->{inboxdir})\n" if $@;
386         }
387 }
388
389 sub uidvalidity { $_[0]->{uidvalidity} //= eval { $_[0]->mm->created_at } }
390
391 sub eidx_key { $_[0]->{newsgroup} // $_[0]->{inboxdir} }
392
393 # only used by NNTP, so we need ->mm anyways
394 sub art_min { $_[0]->{-art_min} //= eval { $_[0]->mm(1)->min } }
395
396 # used by IMAP, too, which tries to avoid ->mm (but ->{mm} is likely
397 # faster since it's smaller iff available)
398 sub art_max {
399         $_[0]->{-art_max} //= eval { $_[0]->{mm}->max } //
400                                 eval { $_[0]->over(1)->max };
401 }
402
403 sub mailboxid { # rfc 8474, 8620, 8621
404         my ($self, $imap_slice) = @_;
405         my $pfx = defined($imap_slice) ? $self->{newsgroup} : $self->{name};
406         utf8::encode($pfx); # to octets
407         # RFC 8620, 1.2 recommends not starting with dash or digits
408         # "A good solution to these issues is to prefix every id with a single
409         #  alphabetical character."
410         'M'.join('', map { sprintf('%02x', ord) } split(//, $pfx)) .
411                 (defined($imap_slice) ? sprintf('-%x', $imap_slice) : '') .
412                 sprintf('-%x', uidvalidity($self) // 0)
413 }
414
415 sub thing_type { 'public inbox' }
416
417 1;