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>
4 # Used throughout the project for reading configuration
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
10 package PublicInbox::Config;
13 use PublicInbox::Inbox;
14 use PublicInbox::Spawn qw(popen_rd);
16 sub _array ($) { ref($_[0]) eq 'ARRAY' ? $_[0] : [ $_[0] ] }
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
21 my ($class, $file) = @_;
22 $file //= default_file();
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", '=');
29 $self = git_config_dump($class, $file);
30 $self->{'-f'} = $file;
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'};
43 if (my $no = delete $self->{'publicinbox.noobfuscate'}) {
46 foreach my $n (@$no) {
47 my @n = split(/\s+/, $n);
49 if (/\S+@\S+/) { # full address
50 $self->{-no_obfuscate}->{lc $_} = 1;
52 # allow "example.com" or "@example.com"
54 push @domains, quotemeta($_);
58 my $nod = join('|', @domains);
59 $self->{-no_obfuscate_re} = qr/(?:$nod)\z/i;
61 if (my $css = delete $self->{'publicinbox.css'}) {
62 $self->{css} = _array($css);
69 sub fill_all ($) { each_inbox($_[0], \&noop) }
71 sub _lookup_fill ($$$) {
72 my ($self, $cache, $key) = @_;
73 $self->{$cache}->{$key} // do {
75 $self->{$cache}->{$key};
80 my ($self, $recipient) = @_;
81 _lookup_fill($self, '-by_addr', lc($recipient));
85 my ($self, $list_id) = @_;
86 _lookup_fill($self, '-by_list_id', lc($list_id));
89 sub lookup_name ($$) {
90 my ($self, $name) = @_;
91 $self->{-by_name}->{$name} // _fill_ibx($self, $name);
95 my ($self, $name) = @_;
96 $self->{-ei_by_name}->{$name} //= _fill_ei($self, $name);
99 # special case for [extindex "all"]
100 sub ALL { lookup_ei($_[0], 'all') }
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;
112 sub lookup_newsgroup {
113 my ($self, $ng) = @_;
114 _lookup_fill($self, '-by_newsgroup', lc($ng));
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);
128 sub config_dir { $ENV{PI_DIR} // "$ENV{HOME}/.public-inbox" }
131 $ENV{PI_CONFIG} // (config_dir() . '/config');
134 sub config_fh_parse ($$$) {
135 my ($fh, $rs, $fs) = @_;
136 my (%rv, %seen, @section_order, $line, $k, $v, $section, $cur, $i);
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);
145 if (defined($cur = $rv{$k})) {
146 if (ref($cur) eq "ARRAY") {
149 $rv{$k} = [ $cur, $v ];
155 $rv{-section_order} = \@section_order;
160 sub git_config_dump {
161 my ($class, $file) = @_;
162 return bless {}, $class 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: $?";
170 sub valid_foo_name ($;$) {
171 my ($name, $pfx) = @_;
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;
183 # Note: we allow URL-unfriendly characters; users may configure
184 # non-HTTP-accessible inboxes
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";
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);
207 $rel = substr($path, length($base) + 1);
210 $rel =~ s!/\.git\z!! or
213 $self->{-cgit_remove_suffix} and
214 $rel =~ s!/?\.git\z!!;
216 $self->{"coderepo.$rel.dir"} //= $path;
217 $self->{"coderepo.$rel.cgiturl"} //= _array($rel);
222 -d "$git_dir/objects" && -f "$git_dir/HEAD";
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";
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);
238 while (defined(my $dn = readdir $dh)) {
239 next if $dn eq '.' || $dn eq '..';
240 if (index($dn, '.') == 0 && !$self->{-cgit_scan_hidden_path}) {
243 my $dir = "$path/$dn";
244 scan_path_coderepo($self, $base, $dir) if -d $dir;
248 sub scan_tree_coderepo ($$) {
249 my ($self, $path) = @_;
250 scan_path_coderepo($self, $path, $path);
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";
261 scan_path_coderepo($self, $path, "$path/$_");
266 my ($self, $cgitrc, $nesting) = @_;
269 my %s = map { $_ => 1 } qw(/cgit.css /cgit.png
270 /favicon.ico /robots.txt);
271 $self->{-cgit_static} = \%s;
274 # same limit as cgit/configfile.c::parse_configfile
275 return if $nesting > 8;
277 open my $fh, '<', $cgitrc or do {
278 warn "failed to open cgitrc=$cgitrc: $!\n";
282 # FIXME: this doesn't support macro expansion via $VARS, yet
286 if (m!\Arepo\.url=(.+?)/*\z!) {
288 cgit_repo_merge($self, $repo->{dir}, $repo) if $repo;
289 $repo = { url => $nick };
290 } elsif (m!\Arepo\.path=(.+)\z!) {
294 warn "$_ without repo.url\n";
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);
301 $self->{"-cgit_$k"} = $v;
302 } elsif (m!\A(project-list|strict-export)=(.+)\z!) {
303 my ($k, $v) = ($1, $2);
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);
310 scan_tree_coderepo($self, $1);
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;
317 cgit_repo_merge($self, $repo->{dir}, $repo) if $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";
326 my $dir = $self->{"$pfx.dir"}; # aka "GIT_DIR"
327 unless (defined $dir) {
328 warn "$pfx.dir unset\n";
332 my $git = PublicInbox::Git->new($dir);
333 foreach my $t (qw(blob commit tree tag)) {
334 $git->{$t.'_url_format'} =
335 _array($self->{lc("$pfx.${t}UrlFormat")});
338 if (defined(my $cgits = $self->{"$pfx.cgiturl"})) {
339 $git->{cgit_url} = $cgits = _array($cgits);
340 $self->{"$pfx.cgiturl"} = $cgits;
342 # cgit supports "/blob/?id=%s", but it's only a plain-text
343 # display and requires an unabbreviated id=
344 foreach my $t (qw(blob commit tag)) {
345 $git->{$t.'_url_format'} //= map {
355 my ($self, $key) = @_;
356 my $v = $self->{$key} // return;
361 my ($val) = $_[-1]; # $_[0] may be $self, or $val
362 if ($val =~ /\A(?:false|no|off|[\-\+]?(?:0x)?0+)\z/i) {
364 } elsif ($val =~ /\A(?:true|yes|on|[\-\+]?(?:0x)?[0-9]+)\z/i) {
371 # abs_path resolves symlinks, so we want to avoid it if rel2abs
372 # is sufficient and doesn't leave "/.." or "/../"
373 sub rel2abs_collapsed {
375 my $p = File::Spec->rel2abs($_[-1]);
376 return $p if substr($p, -3, 3) ne '/..' && index($p, '/../') < 0;
382 my ($self, $pfx, $k) = @_;
383 my $v = $self->{"$pfx.$k"} // return;
384 return $v if !ref($v);
385 warn "W: $pfx.$k has multiple values, only using `$v->[-1]'\n";
390 my ($self, $ibxish) = @_;
391 my $ibx_code_repos = $ibxish->{coderepo} or return;
392 $ibxish->{-repo_objs} //= do {
393 my $code_repos = $self->{-code_repos};
395 for my $nick (@$ibx_code_repos) {
396 my @parts = split(m!/!, $nick);
398 @parts = () unless valid_foo_name($_);
401 warn "invalid coderepo name: `$nick'\n";
404 my $repo = $code_repos->{$nick} //=
405 _fill_code_repo($self, $nick);
406 push @repo_objs, $repo if $repo;
408 if (scalar @repo_objs) {
411 delete $ibxish->{coderepo};
418 my ($self, $name) = @_;
419 my $pfx = "publicinbox.$name";
421 for my $k (qw(watch nntpserver)) {
422 my $v = $self->{"$pfx.$k"};
423 $ibx->{$k} = $v if defined $v;
425 for my $k (qw(filter inboxdir newsgroup replyto httpbackendmax feedmax
426 indexlevel indexsequentialshard)) {
427 my $v = _one_val($self, $pfx, $k) // next;
431 # "mainrepo" is backwards compatibility:
432 my $dir = $ibx->{inboxdir} //= $self->{"$pfx.mainrepo"} // return;
433 if (index($dir, "\n") >= 0) {
434 warn "E: `$dir' must not contain `\\n'\n";
437 for my $k (qw(obfuscate)) {
438 my $v = $self->{"$pfx.$k"} // next;
439 if (defined(my $bval = git_bool($v))) {
442 warn "Ignoring $pfx.$k=$v in config, not boolean\n";
445 # TODO: more arrays, we should support multi-value for
446 # more things to encourage decentralization
447 for my $k (qw(address altid nntpmirror coderepo hide listid url
448 infourl watchheader)) {
449 my $v = $self->{"$pfx.$k"} // next;
450 $ibx->{$k} = _array($v);
453 return unless valid_foo_name($name, 'publicinbox');
454 $ibx->{name} = $name;
455 $ibx->{-pi_cfg} = $self;
456 $ibx = PublicInbox::Inbox->new($ibx);
457 foreach (@{$ibx->{address}}) {
458 my $lc_addr = lc($_);
459 $self->{-by_addr}->{$lc_addr} = $ibx;
460 $self->{-no_obfuscate}->{$lc_addr} = 1;
462 if (my $listids = $ibx->{listid}) {
463 # RFC2919 section 6 stipulates "case insensitive equality"
464 foreach my $list_id (@$listids) {
465 $self->{-by_list_id}->{lc($list_id)} = $ibx;
468 if (defined(my $ngname = $ibx->{newsgroup})) {
470 delete $ibx->{newsgroup};
471 warn 'multiple newsgroups not supported: '.
472 join(', ', @$ngname). "\n";
473 # Newsgroup name needs to be compatible with RFC 3977
474 # wildmat-exact and RFC 3501 (IMAP) ATOM-CHAR.
475 # Leave out a few chars likely to cause problems or conflicts:
476 # '|', '<', '>', ';', '#', '$', '&',
477 } elsif ($ngname =~ m![^A-Za-z0-9/_\.\-\~\@\+\=:]! ||
479 delete $ibx->{newsgroup};
480 warn "newsgroup name invalid: `$ngname'\n";
482 # PublicInbox::NNTPD does stricter ->nntp_usable
483 # checks, keep this lean for startup speed
484 $self->{-by_newsgroup}->{$ngname} = $ibx;
487 unless (defined $ibx->{newsgroup}) { # for ->eidx_key
488 my $abs = rel2abs_collapsed($dir);
490 warn "W: `$dir' canonicalized to `$abs'\n";
491 $ibx->{inboxdir} = $abs;
494 $self->{-by_name}->{$name} = $ibx;
495 if ($ibx->{obfuscate}) {
496 $ibx->{-no_obfuscate} = $self->{-no_obfuscate};
497 $ibx->{-no_obfuscate_re} = $self->{-no_obfuscate_re};
498 fill_all($self); # noop to populate -no_obfuscate
500 if (my $es = ALL($self)) {
501 require PublicInbox::Isearch;
502 $ibx->{isrch} = PublicInbox::Isearch->new($ibx, $es);
504 $self->{-by_eidx_key}->{$ibx->eidx_key} = $ibx;
508 my ($self, $name) = @_;
509 eval { require PublicInbox::ExtSearch } or return;
510 my $pfx = "extindex.$name";
511 my $d = $self->{"$pfx.topdir"} // return;
513 if (index($d, "\n") >= 0) {
514 warn "E: `$d' must not contain `\\n'\n";
517 my $es = PublicInbox::ExtSearch->new($d);
518 for my $k (qw(indexlevel indexsequentialshard)) {
519 my $v = _one_val($self, $pfx, $k) // next;
522 for my $k (qw(altid coderepo hide url infourl)) {
523 my $v = $self->{"$pfx.$k"} // next;
524 $es->{$k} = _array($v);
526 return unless valid_foo_name($name, 'extindex');
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);
545 $urlmatch_broken = 1 if (($? >> 8) != 1);
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;
562 sub squote_maybe ($) {
564 if ($val =~ m{([^\w@\./,\%\+\-])}) {
565 $val =~ s/(['!])/'\\$1'/g; # '!' for csh