]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Config.pm
isearch: emulate per-inbox search with ->ALL
[public-inbox.git] / lib / PublicInbox / Config.pm
1 # Copyright (C) 2014-2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 #
4 # Used throughout the project for reading configuration
5 #
6 # Note: I hate camelCase; but git-config(1) uses it, but it's better
7 # than alllowercasewithoutunderscores, so use lc('configKey') where
8 # applicable for readability
9
10 package PublicInbox::Config;
11 use strict;
12 use v5.10.1;
13 use PublicInbox::Inbox;
14 use PublicInbox::Spawn qw(popen_rd);
15
16 sub _array ($) { ref($_[0]) eq 'ARRAY' ? $_[0] : [ $_[0] ] }
17
18 # returns key-value pairs of config directives in a hash
19 # if keys may be multi-value, the value is an array ref containing all values
20 sub new {
21         my ($class, $file) = @_;
22         $file //= default_file();
23         my $self;
24         if (ref($file) eq 'SCALAR') { # used by some tests
25                 open my $fh, '<', $file or die;  # PerlIO::scalar
26                 $self = config_fh_parse($fh, "\n", '=');
27         } else {
28                 $self = git_config_dump($file);
29         }
30         bless $self, $class;
31         # caches
32         $self->{-by_addr} = {};
33         $self->{-by_list_id} = {};
34         $self->{-by_name} = {};
35         $self->{-by_newsgroup} = {};
36         $self->{-by_eidx_key} = {};
37         $self->{-no_obfuscate} = {};
38         $self->{-limiters} = {};
39         $self->{-code_repos} = {}; # nick => PublicInbox::Git object
40         $self->{-cgitrc_unparsed} = $self->{'publicinbox.cgitrc'};
41
42         if (my $no = delete $self->{'publicinbox.noobfuscate'}) {
43                 $no = _array($no);
44                 my @domains;
45                 foreach my $n (@$no) {
46                         my @n = split(/\s+/, $n);
47                         foreach (@n) {
48                                 if (/\S+@\S+/) { # full address
49                                         $self->{-no_obfuscate}->{lc $_} = 1;
50                                 } else {
51                                         # allow "example.com" or "@example.com"
52                                         s/\A@//;
53                                         push @domains, quotemeta($_);
54                                 }
55                         }
56                 }
57                 my $nod = join('|', @domains);
58                 $self->{-no_obfuscate_re} = qr/(?:$nod)\z/i;
59         }
60         if (my $css = delete $self->{'publicinbox.css'}) {
61                 $self->{css} = _array($css);
62         }
63
64         $self;
65 }
66
67 sub noop {}
68 sub fill_all ($) { each_inbox($_[0], \&noop) }
69
70 sub _lookup_fill ($$$) {
71         my ($self, $cache, $key) = @_;
72         $self->{$cache}->{$key} // do {
73                 fill_all($self);
74                 $self->{$cache}->{$key};
75         }
76 }
77
78 sub lookup {
79         my ($self, $recipient) = @_;
80         _lookup_fill($self, '-by_addr', lc($recipient));
81 }
82
83 sub lookup_list_id {
84         my ($self, $list_id) = @_;
85         _lookup_fill($self, '-by_list_id', lc($list_id));
86 }
87
88 sub lookup_name ($$) {
89         my ($self, $name) = @_;
90         $self->{-by_name}->{$name} // _fill($self, "publicinbox.$name");
91 }
92
93 sub lookup_ei {
94         my ($self, $name) = @_;
95         $self->{-ei_by_name}->{$name} //= _fill_ei($self, "extindex.$name");
96 }
97
98 # special case for [extindex "all"]
99 sub ALL { lookup_ei($_[0], 'all') }
100
101 sub each_inbox {
102         my ($self, $cb, @arg) = @_;
103         # may auto-vivify if config file is non-existent:
104         foreach my $section (@{$self->{-section_order}}) {
105                 next if $section !~ m!\Apublicinbox\.([^/]+)\z!;
106                 my $ibx = lookup_name($self, $1) or next;
107                 $cb->($ibx, @arg);
108         }
109 }
110
111 sub lookup_newsgroup {
112         my ($self, $ng) = @_;
113         _lookup_fill($self, '-by_newsgroup', lc($ng));
114 }
115
116 sub limiter {
117         my ($self, $name) = @_;
118         $self->{-limiters}->{$name} //= do {
119                 require PublicInbox::Qspawn;
120                 my $max = $self->{"publicinboxlimiter.$name.max"} || 1;
121                 my $limiter = PublicInbox::Qspawn::Limiter->new($max);
122                 $limiter->setup_rlimit($name, $self);
123                 $limiter;
124         };
125 }
126
127 sub config_dir { $ENV{PI_DIR} // "$ENV{HOME}/.public-inbox" }
128
129 sub default_file {
130         $ENV{PI_CONFIG} // (config_dir() . '/config');
131 }
132
133 sub config_fh_parse ($$$) {
134         my ($fh, $rs, $fs) = @_;
135         my %rv;
136         my (%section_seen, @section_order);
137         local $/ = $rs;
138         while (defined(my $line = <$fh>)) {
139                 chomp $line;
140                 my ($k, $v) = split($fs, $line, 2);
141                 my ($section) = ($k =~ /\A(\S+)\.[^\.]+\z/);
142                 unless (defined $section_seen{$section}) {
143                         $section_seen{$section} = 1;
144                         push @section_order, $section;
145                 }
146
147                 my $cur = $rv{$k};
148                 if (defined $cur) {
149                         if (ref($cur) eq "ARRAY") {
150                                 push @$cur, $v;
151                         } else {
152                                 $rv{$k} = [ $cur, $v ];
153                         }
154                 } else {
155                         $rv{$k} = $v;
156                 }
157         }
158         $rv{-section_order} = \@section_order;
159
160         \%rv;
161 }
162
163 sub git_config_dump {
164         my ($file) = @_;
165         return {} unless -e $file;
166         my @cmd = (qw/git config -z -l --includes/, "--file=$file");
167         my $cmd = join(' ', @cmd);
168         my $fh = popen_rd(\@cmd);
169         my $rv = config_fh_parse($fh, "\0", "\n");
170         close $fh or die "failed to close ($cmd) pipe: $?";
171         $rv;
172 }
173
174 sub valid_inbox_name ($) {
175         my ($name) = @_;
176
177         # Similar rules found in git.git/remote.c::valid_remote_nick
178         # and git.git/refs.c::check_refname_component
179         # We don't reject /\.lock\z/, however, since we don't lock refs
180         if ($name eq '' || $name =~ /\@\{/ ||
181             $name =~ /\.\./ || $name =~ m![/:\?\[\]\^~\s\f[:cntrl:]\*]! ||
182             $name =~ /\A\./ || $name =~ /\.\z/) {
183                 return 0;
184         }
185
186         # Note: we allow URL-unfriendly characters; users may configure
187         # non-HTTP-accessible inboxes
188         1;
189 }
190
191 # XXX needs testing for cgit compatibility
192 # cf. cgit/scan-tree.c::add_repo
193 sub cgit_repo_merge ($$$) {
194         my ($self, $base, $repo) = @_;
195         my $path = $repo->{dir};
196         if (defined(my $se = $self->{-cgit_strict_export})) {
197                 return unless -e "$path/$se";
198         }
199         return if -e "$path/noweb";
200         # this comes from the cgit config, and AFAIK cgit only allows
201         # repos to have one URL, but that's just the PATH_INFO component,
202         # not the Host: portion
203         # $repo = { url => 'foo.git', dir => '/path/to/foo.git' }
204         my $rel = $repo->{url};
205         unless (defined $rel) {
206                 my $off = index($path, $base, 0);
207                 if ($off != 0) {
208                         $rel = $path;
209                 } else {
210                         $rel = substr($path, length($base) + 1);
211                 }
212
213                 $rel =~ s!/\.git\z!! or
214                         $rel =~ s!/+\z!!;
215
216                 $self->{-cgit_remove_suffix} and
217                         $rel =~ s!/?\.git\z!!;
218         }
219         $self->{"coderepo.$rel.dir"} //= $path;
220         $self->{"coderepo.$rel.cgiturl"} //= _array($rel);
221 }
222
223 sub is_git_dir ($) {
224         my ($git_dir) = @_;
225         -d "$git_dir/objects" && -f "$git_dir/HEAD";
226 }
227
228 # XXX needs testing for cgit compatibility
229 sub scan_path_coderepo {
230         my ($self, $base, $path) = @_;
231         opendir(my $dh, $path) or do {
232                 warn "error opening directory: $path\n";
233                 return
234         };
235         my $git_dir = $path;
236         if (is_git_dir($git_dir) || is_git_dir($git_dir .= '/.git')) {
237                 my $repo = { dir => $git_dir };
238                 cgit_repo_merge($self, $base, $repo);
239                 return;
240         }
241         while (defined(my $dn = readdir $dh)) {
242                 next if $dn eq '.' || $dn eq '..';
243                 if (index($dn, '.') == 0 && !$self->{-cgit_scan_hidden_path}) {
244                         next;
245                 }
246                 my $dir = "$path/$dn";
247                 scan_path_coderepo($self, $base, $dir) if -d $dir;
248         }
249 }
250
251 sub scan_tree_coderepo ($$) {
252         my ($self, $path) = @_;
253         scan_path_coderepo($self, $path, $path);
254 }
255
256 sub scan_projects_coderepo ($$$) {
257         my ($self, $list, $path) = @_;
258         open my $fh, '<', $list or do {
259                 warn "failed to open cgit projectlist=$list: $!\n";
260                 return;
261         };
262         while (<$fh>) {
263                 chomp;
264                 scan_path_coderepo($self, $path, "$path/$_");
265         }
266 }
267
268 sub parse_cgitrc {
269         my ($self, $cgitrc, $nesting) = @_;
270         if ($nesting == 0) {
271                 # defaults:
272                 my %s = map { $_ => 1 } qw(/cgit.css /cgit.png
273                                                 /favicon.ico /robots.txt);
274                 $self->{-cgit_static} = \%s;
275         }
276
277         # same limit as cgit/configfile.c::parse_configfile
278         return if $nesting > 8;
279
280         open my $fh, '<', $cgitrc or do {
281                 warn "failed to open cgitrc=$cgitrc: $!\n";
282                 return;
283         };
284
285         # FIXME: this doesn't support macro expansion via $VARS, yet
286         my $repo;
287         while (<$fh>) {
288                 chomp;
289                 if (m!\Arepo\.url=(.+?)/*\z!) {
290                         my $nick = $1;
291                         cgit_repo_merge($self, $repo->{dir}, $repo) if $repo;
292                         $repo = { url => $nick };
293                 } elsif (m!\Arepo\.path=(.+)\z!) {
294                         if (defined $repo) {
295                                 $repo->{dir} = $1;
296                         } else {
297                                 warn "$_ without repo.url\n";
298                         }
299                 } elsif (m!\Ainclude=(.+)\z!) {
300                         parse_cgitrc($self, $1, $nesting + 1);
301                 } elsif (m!\A(scan-hidden-path|remove-suffix)=([0-9]+)\z!) {
302                         my ($k, $v) = ($1, $2);
303                         $k =~ tr/-/_/;
304                         $self->{"-cgit_$k"} = $v;
305                 } elsif (m!\A(project-list|strict-export)=(.+)\z!) {
306                         my ($k, $v) = ($1, $2);
307                         $k =~ tr/-/_/;
308                         $self->{"-cgit_$k"} = $v;
309                 } elsif (m!\Ascan-path=(.+)\z!) {
310                         if (defined(my $list = $self->{-cgit_project_list})) {
311                                 scan_projects_coderepo($self, $list, $1);
312                         } else {
313                                 scan_tree_coderepo($self, $1);
314                         }
315                 } elsif (m!\A(?:css|favicon|logo|repo\.logo)=(/.+)\z!) {
316                         # absolute paths for static files via PublicInbox::Cgit
317                         $self->{-cgit_static}->{$1} = 1;
318                 }
319         }
320         cgit_repo_merge($self, $repo->{dir}, $repo) if $repo;
321 }
322
323 # parse a code repo
324 # Only git is supported at the moment, but SVN and Hg are possibilities
325 sub _fill_code_repo {
326         my ($self, $nick) = @_;
327         my $pfx = "coderepo.$nick";
328
329         # TODO: support gitweb and other repository viewers?
330         if (defined(my $cgitrc = delete $self->{-cgitrc_unparsed})) {
331                 parse_cgitrc($self, $cgitrc, 0);
332         }
333         my $dir = $self->{"$pfx.dir"}; # aka "GIT_DIR"
334         unless (defined $dir) {
335                 warn "$pfx.dir unset\n";
336                 return;
337         }
338
339         my $git = PublicInbox::Git->new($dir);
340         foreach my $t (qw(blob commit tree tag)) {
341                 $git->{$t.'_url_format'} =
342                                 _array($self->{lc("$pfx.${t}UrlFormat")});
343         }
344
345         if (defined(my $cgits = $self->{"$pfx.cgiturl"})) {
346                 $git->{cgit_url} = $cgits = _array($cgits);
347                 $self->{"$pfx.cgiturl"} = $cgits;
348
349                 # cgit supports "/blob/?id=%s", but it's only a plain-text
350                 # display and requires an unabbreviated id=
351                 foreach my $t (qw(blob commit tag)) {
352                         $git->{$t.'_url_format'} //= map {
353                                 "$_/$t/?id=%s"
354                         } @$cgits;
355                 }
356         }
357
358         $git;
359 }
360
361 sub git_bool {
362         my ($val) = $_[-1]; # $_[0] may be $self, or $val
363         if ($val =~ /\A(?:false|no|off|[\-\+]?(?:0x)?0+)\z/i) {
364                 0;
365         } elsif ($val =~ /\A(?:true|yes|on|[\-\+]?(?:0x)?[0-9]+)\z/i) {
366                 1;
367         } else {
368                 undef;
369         }
370 }
371
372 sub _fill {
373         my ($self, $pfx) = @_;
374         my $ibx = {};
375
376         for my $k (qw(watch nntpserver)) {
377                 my $v = $self->{"$pfx.$k"};
378                 $ibx->{$k} = $v if defined $v;
379         }
380         for my $k (qw(filter inboxdir newsgroup replyto httpbackendmax feedmax
381                         indexlevel indexsequentialshard)) {
382                 if (defined(my $v = $self->{"$pfx.$k"})) {
383                         if (ref($v) eq 'ARRAY') {
384                                 warn <<EOF;
385 W: $pfx.$k has multiple values, only using `$v->[-1]'
386 EOF
387                                 $ibx->{$k} = $v->[-1];
388                         } else {
389                                 $ibx->{$k} = $v;
390                         }
391                 }
392         }
393
394         # backwards compatibility:
395         $ibx->{inboxdir} //= $self->{"$pfx.mainrepo"};
396         if (($ibx->{inboxdir} // '') =~ /\n/s) {
397                 warn "E: `$ibx->{inboxdir}' must not contain `\\n'\n";
398                 return;
399         }
400         foreach my $k (qw(obfuscate)) {
401                 my $v = $self->{"$pfx.$k"};
402                 defined $v or next;
403                 if (defined(my $bval = git_bool($v))) {
404                         $ibx->{$k} = $bval;
405                 } else {
406                         warn "Ignoring $pfx.$k=$v in config, not boolean\n";
407                 }
408         }
409         # TODO: more arrays, we should support multi-value for
410         # more things to encourage decentralization
411         foreach my $k (qw(address altid nntpmirror coderepo hide listid url
412                         infourl watchheader)) {
413                 if (defined(my $v = $self->{"$pfx.$k"})) {
414                         $ibx->{$k} = _array($v);
415                 }
416         }
417
418         return unless defined($ibx->{inboxdir});
419         my $name = $pfx;
420         $name =~ s/\Apublicinbox\.//;
421
422         if (!valid_inbox_name($name)) {
423                 warn "invalid inbox name: '$name'\n";
424                 return;
425         }
426
427         $ibx->{name} = $name;
428         $ibx->{-pi_config} = $self;
429         $ibx = PublicInbox::Inbox->new($ibx);
430         foreach (@{$ibx->{address}}) {
431                 my $lc_addr = lc($_);
432                 $self->{-by_addr}->{$lc_addr} = $ibx;
433                 $self->{-no_obfuscate}->{$lc_addr} = 1;
434         }
435         if (my $listids = $ibx->{listid}) {
436                 # RFC2919 section 6 stipulates "case insensitive equality"
437                 foreach my $list_id (@$listids) {
438                         $self->{-by_list_id}->{lc($list_id)} = $ibx;
439                 }
440         }
441         if (my $ngname = $ibx->{newsgroup}) {
442                 if (ref($ngname)) {
443                         delete $ibx->{newsgroup};
444                         warn 'multiple newsgroups not supported: '.
445                                 join(', ', @$ngname). "\n";
446                 # Newsgroup name needs to be compatible with RFC 3977
447                 # wildmat-exact and RFC 3501 (IMAP) ATOM-CHAR.
448                 # Leave out a few chars likely to cause problems or conflicts:
449                 # '|', '<', '>', ';', '#', '$', '&',
450                 } elsif ($ngname =~ m![^A-Za-z0-9/_\.\-\~\@\+\=:]!) {
451                         delete $ibx->{newsgroup};
452                         warn "newsgroup name invalid: `$ngname'\n";
453                 } else {
454                         # PublicInbox::NNTPD does stricter ->nntp_usable
455                         # checks, keep this lean for startup speed
456                         $self->{-by_newsgroup}->{$ngname} = $ibx;
457                 }
458         }
459         $self->{-by_name}->{$name} = $ibx;
460         if ($ibx->{obfuscate}) {
461                 $ibx->{-no_obfuscate} = $self->{-no_obfuscate};
462                 $ibx->{-no_obfuscate_re} = $self->{-no_obfuscate_re};
463                 fill_all($self); # noop to populate -no_obfuscate
464         }
465
466         if (my $ibx_code_repos = $ibx->{coderepo}) {
467                 my $code_repos = $self->{-code_repos};
468                 my $repo_objs = $ibx->{-repo_objs} = [];
469                 foreach my $nick (@$ibx_code_repos) {
470                         my @parts = split(m!/!, $nick);
471                         my $valid = 0;
472                         $valid += valid_inbox_name($_) foreach (@parts);
473                         $valid == scalar(@parts) or next;
474
475                         my $repo = $code_repos->{$nick} //=
476                                                 _fill_code_repo($self, $nick);
477                         push @$repo_objs, $repo if $repo;
478                 }
479         }
480         if (my $es = ALL($self)) {
481                 require PublicInbox::Isearch;
482                 $ibx->{isrch} = PublicInbox::Isearch->new($ibx, $es);
483         }
484         $self->{-by_eidx_key}->{$ibx->eidx_key} = $ibx;
485 }
486
487 sub _fill_ei ($$) {
488         my ($self, $pfx) = @_;
489         require PublicInbox::ExtSearch;
490         my $d = $self->{"$pfx.topdir"};
491         defined($d) && -d $d ? PublicInbox::ExtSearch->new($d) : undef;
492 }
493
494 sub urlmatch {
495         my ($self, $key, $url) = @_;
496         state $urlmatch_broken; # requires git 1.8.5
497         return if $urlmatch_broken;
498         my $file = default_file();
499         my $cmd = [qw/git config -z --includes --get-urlmatch/,
500                 "--file=$file", $key, $url ];
501         my $fh = popen_rd($cmd);
502         local $/ = "\0";
503         my $val = <$fh>;
504         if (close($fh)) {
505                 chomp($val);
506                 $val;
507         } else {
508                 $urlmatch_broken = 1 if (($? >> 8) != 1);
509                 undef;
510         }
511 }
512
513 sub json {
514         state $json;
515         $json //= do {
516                 for my $mod (qw(Cpanel::JSON::XS JSON::MaybeXS JSON JSON::PP)) {
517                         eval "require $mod" or next;
518                         # ->ascii encodes non-ASCII to "\uXXXX"
519                         $json = $mod->new->ascii(1) and last;
520                 }
521                 $json;
522         };
523 }
524
525 1;