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