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);
15 our $LD_PRELOAD = $ENV{LD_PRELOAD}; # only valid at startup
17 sub _array ($) { ref($_[0]) eq 'ARRAY' ? $_[0] : [ $_[0] ] }
19 # returns key-value pairs of config directives in a hash
20 # if keys may be multi-value, the value is an array ref containing all values
22 my ($class, $file, $errfh) = @_;
23 $file //= default_file();
25 if (ref($file) eq 'SCALAR') { # used by some tests
26 open my $fh, '<', $file or die; # PerlIO::scalar
27 $self = config_fh_parse($fh, "\n", '=');
30 $self = git_config_dump($class, $file, $errfh);
31 $self->{'-f'} = $file;
34 $self->{-by_addr} = {};
35 $self->{-by_list_id} = {};
36 $self->{-by_name} = {};
37 $self->{-by_newsgroup} = {};
38 $self->{-by_eidx_key} = {};
39 $self->{-no_obfuscate} = {};
40 $self->{-limiters} = {};
41 $self->{-code_repos} = {}; # nick => PublicInbox::Git object
42 $self->{-cgitrc_unparsed} = $self->{'publicinbox.cgitrc'};
44 if (my $no = delete $self->{'publicinbox.noobfuscate'}) {
47 foreach my $n (@$no) {
48 my @n = split(/\s+/, $n);
50 if (/\S+@\S+/) { # full address
51 $self->{-no_obfuscate}->{lc $_} = 1;
53 # allow "example.com" or "@example.com"
55 push @domains, quotemeta($_);
59 my $nod = join('|', @domains);
60 $self->{-no_obfuscate_re} = qr/(?:$nod)\z/i;
62 if (my $css = delete $self->{'publicinbox.css'}) {
63 $self->{css} = _array($css);
70 sub fill_all ($) { each_inbox($_[0], \&noop) }
72 sub _lookup_fill ($$$) {
73 my ($self, $cache, $key) = @_;
74 $self->{$cache}->{$key} // do {
76 $self->{$cache}->{$key};
81 my ($self, $recipient) = @_;
82 _lookup_fill($self, '-by_addr', lc($recipient));
86 my ($self, $list_id) = @_;
87 _lookup_fill($self, '-by_list_id', lc($list_id));
90 sub lookup_name ($$) {
91 my ($self, $name) = @_;
92 $self->{-by_name}->{$name} // _fill_ibx($self, $name);
96 my ($self, $name) = @_;
97 $self->{-ei_by_name}->{$name} //= _fill_ei($self, $name);
100 sub lookup_eidx_key {
101 my ($self, $eidx_key) = @_;
102 _lookup_fill($self, '-by_eidx_key', $eidx_key);
105 # special case for [extindex "all"]
106 sub ALL { lookup_ei($_[0], 'all') }
109 my ($self, $cb, @arg) = @_;
110 # may auto-vivify if config file is non-existent:
111 foreach my $section (@{$self->{-section_order}}) {
112 next if $section !~ m!\Apublicinbox\.([^/]+)\z!;
113 my $ibx = lookup_name($self, $1) or next;
118 sub lookup_newsgroup {
119 my ($self, $ng) = @_;
120 _lookup_fill($self, '-by_newsgroup', lc($ng));
124 my ($self, $name) = @_;
125 $self->{-limiters}->{$name} //= do {
126 require PublicInbox::Qspawn;
127 my $max = $self->{"publicinboxlimiter.$name.max"} || 1;
128 my $limiter = PublicInbox::Qspawn::Limiter->new($max);
129 $limiter->setup_rlimit($name, $self);
134 sub config_dir { $ENV{PI_DIR} // "$ENV{HOME}/.public-inbox" }
137 $ENV{PI_CONFIG} // (config_dir() . '/config');
140 sub config_fh_parse ($$$) {
141 my ($fh, $rs, $fs) = @_;
142 my (%rv, %seen, @section_order, $line, $k, $v, $section, $cur, $i);
144 while (defined($line = <$fh>)) { # perf critical with giant configs
145 $i = index($line, $fs);
146 $k = substr($line, 0, $i);
147 $v = substr($line, $i + 1, -1); # chop off $fs
148 $section = substr($k, 0, rindex($k, '.'));
149 $seen{$section} //= push(@section_order, $section);
151 if (defined($cur = $rv{$k})) {
152 if (ref($cur) eq "ARRAY") {
155 $rv{$k} = [ $cur, $v ];
161 $rv{-section_order} = \@section_order;
166 sub git_config_dump {
167 my ($class, $file, $errfh) = @_;
168 return bless {}, $class unless -e $file;
169 my $cmd = [ qw(git config -z -l --includes), "--file=$file" ];
170 my $fh = popen_rd($cmd, undef, { 2 => $errfh // 2 });
171 my $rv = config_fh_parse($fh, "\0", "\n");
172 close $fh or die "@$cmd failed: \$?=$?\n";
176 sub valid_foo_name ($;$) {
177 my ($name, $pfx) = @_;
179 # Similar rules found in git.git/remote.c::valid_remote_nick
180 # and git.git/refs.c::check_refname_component
181 # We don't reject /\.lock\z/, however, since we don't lock refs
182 if ($name eq '' || $name =~ /\@\{/ ||
183 $name =~ /\.\./ || $name =~ m![/:\?\[\]\^~\s\f[:cntrl:]\*]! ||
184 $name =~ /\A\./ || $name =~ /\.\z/) {
185 warn "invalid $pfx name: `$name'\n" if $pfx;
189 # Note: we allow URL-unfriendly characters; users may configure
190 # non-HTTP-accessible inboxes
194 # XXX needs testing for cgit compatibility
195 # cf. cgit/scan-tree.c::add_repo
196 sub cgit_repo_merge ($$$) {
197 my ($self, $base, $repo) = @_;
198 my $path = $repo->{dir};
199 if (defined(my $se = $self->{-cgit_strict_export})) {
200 return unless -e "$path/$se";
202 return if -e "$path/noweb";
203 # this comes from the cgit config, and AFAIK cgit only allows
204 # repos to have one URL, but that's just the PATH_INFO component,
205 # not the Host: portion
206 # $repo = { url => 'foo.git', dir => '/path/to/foo.git' }
207 my $rel = $repo->{url};
208 unless (defined $rel) {
209 my $off = index($path, $base, 0);
213 $rel = substr($path, length($base) + 1);
216 $rel =~ s!/\.git\z!! or
219 $self->{-cgit_remove_suffix} and
220 $rel =~ s!/?\.git\z!!;
222 $self->{"coderepo.$rel.dir"} //= $path;
223 $self->{"coderepo.$rel.cgiturl"} //= _array($rel);
228 -d "$git_dir/objects" && -f "$git_dir/HEAD";
231 # XXX needs testing for cgit compatibility
232 sub scan_path_coderepo {
233 my ($self, $base, $path) = @_;
234 opendir(my $dh, $path) or do {
235 warn "error opening directory: $path\n";
239 if (is_git_dir($git_dir) || is_git_dir($git_dir .= '/.git')) {
240 my $repo = { dir => $git_dir };
241 cgit_repo_merge($self, $base, $repo);
244 while (defined(my $dn = readdir $dh)) {
245 next if $dn eq '.' || $dn eq '..';
246 if (index($dn, '.') == 0 && !$self->{-cgit_scan_hidden_path}) {
249 my $dir = "$path/$dn";
250 scan_path_coderepo($self, $base, $dir) if -d $dir;
254 sub scan_tree_coderepo ($$) {
255 my ($self, $path) = @_;
256 scan_path_coderepo($self, $path, $path);
259 sub scan_projects_coderepo ($$$) {
260 my ($self, $list, $path) = @_;
261 open my $fh, '<', $list or do {
262 warn "failed to open cgit projectlist=$list: $!\n";
267 scan_path_coderepo($self, $path, "$path/$_");
272 my ($self, $cgitrc, $nesting) = @_;
275 my %s = map { $_ => 1 } qw(/cgit.css /cgit.png
276 /favicon.ico /robots.txt);
277 $self->{-cgit_static} = \%s;
280 # same limit as cgit/configfile.c::parse_configfile
281 return if $nesting > 8;
283 open my $fh, '<', $cgitrc or do {
284 warn "failed to open cgitrc=$cgitrc: $!\n";
288 # FIXME: this doesn't support macro expansion via $VARS, yet
292 if (m!\Arepo\.url=(.+?)/*\z!) {
294 cgit_repo_merge($self, $repo->{dir}, $repo) if $repo;
295 $repo = { url => $nick };
296 } elsif (m!\Arepo\.path=(.+)\z!) {
300 warn "$_ without repo.url\n";
302 } elsif (m!\Ainclude=(.+)\z!) {
303 parse_cgitrc($self, $1, $nesting + 1);
304 } elsif (m!\A(scan-hidden-path|remove-suffix)=([0-9]+)\z!) {
305 my ($k, $v) = ($1, $2);
307 $self->{"-cgit_$k"} = $v;
308 } elsif (m!\A(project-list|strict-export)=(.+)\z!) {
309 my ($k, $v) = ($1, $2);
311 $self->{"-cgit_$k"} = $v;
312 } elsif (m!\Ascan-path=(.+)\z!) {
313 if (defined(my $list = $self->{-cgit_project_list})) {
314 scan_projects_coderepo($self, $list, $1);
316 scan_tree_coderepo($self, $1);
318 } elsif (m!\A(?:css|favicon|logo|repo\.logo)=(/.+)\z!) {
319 # absolute paths for static files via PublicInbox::Cgit
320 $self->{-cgit_static}->{$1} = 1;
323 cgit_repo_merge($self, $repo->{dir}, $repo) if $repo;
327 # Only git is supported at the moment, but SVN and Hg are possibilities
328 sub _fill_code_repo {
329 my ($self, $nick) = @_;
330 my $pfx = "coderepo.$nick";
332 my $dir = $self->{"$pfx.dir"}; # aka "GIT_DIR"
333 unless (defined $dir) {
334 warn "$pfx.dir unset\n";
338 my $git = PublicInbox::Git->new($dir);
339 foreach my $t (qw(blob commit tree tag)) {
340 $git->{$t.'_url_format'} =
341 _array($self->{lc("$pfx.${t}UrlFormat")});
344 if (defined(my $cgits = $self->{"$pfx.cgiturl"})) {
345 $git->{cgit_url} = $cgits = _array($cgits);
346 $self->{"$pfx.cgiturl"} = $cgits;
348 # cgit supports "/blob/?id=%s", but it's only a plain-text
349 # display and requires an unabbreviated id=
350 foreach my $t (qw(blob commit tag)) {
351 $git->{$t.'_url_format'} //= map {
361 my ($self, $key) = @_;
362 my $v = $self->{$key} // return;
367 my ($val) = $_[-1]; # $_[0] may be $self, or $val
368 if ($val =~ /\A(?:false|no|off|[\-\+]?(?:0x)?0+)\z/i) {
370 } elsif ($val =~ /\A(?:true|yes|on|[\-\+]?(?:0x)?[0-9]+)\z/i) {
377 # abs_path resolves symlinks, so we want to avoid it if rel2abs
378 # is sufficient and doesn't leave "/.." or "/../"
379 sub rel2abs_collapsed {
381 my $p = File::Spec->rel2abs($_[-1]);
382 return $p if substr($p, -3, 3) ne '/..' && index($p, '/../') < 0;
388 my ($self, $key) = @_;
389 my $v = $self->{$key};
390 return $v if !ref($v);
391 warn "W: $key has multiple values, only using `$v->[-1]'\n";
396 my ($self, $ibxish) = @_;
397 my $ibx_code_repos = $ibxish->{coderepo} or return;
398 $ibxish->{-repo_objs} //= do {
399 my $code_repos = $self->{-code_repos};
401 for my $nick (@$ibx_code_repos) {
402 my @parts = split(m!/!, $nick);
404 @parts = () unless valid_foo_name($_);
407 warn "invalid coderepo name: `$nick'\n";
410 my $repo = $code_repos->{$nick} //=
411 _fill_code_repo($self, $nick);
412 push @repo_objs, $repo if $repo;
414 if (scalar @repo_objs) {
417 delete $ibxish->{coderepo};
424 my ($self, $name) = @_;
425 my $pfx = "publicinbox.$name";
427 for my $k (qw(watch)) {
428 my $v = $self->{"$pfx.$k"};
429 $ibx->{$k} = $v if defined $v;
431 for my $k (qw(filter inboxdir newsgroup replyto httpbackendmax feedmax
432 indexlevel indexsequentialshard boost)) {
433 my $v = get_1($self, "$pfx.$k") // next;
437 # "mainrepo" is backwards compatibility:
438 my $dir = $ibx->{inboxdir} //= $self->{"$pfx.mainrepo"} // return;
439 if (index($dir, "\n") >= 0) {
440 warn "E: `$dir' must not contain `\\n'\n";
443 for my $k (qw(obfuscate)) {
444 my $v = $self->{"$pfx.$k"} // next;
445 if (defined(my $bval = git_bool($v))) {
448 warn "Ignoring $pfx.$k=$v in config, not boolean\n";
451 # TODO: more arrays, we should support multi-value for
452 # more things to encourage decentralization
453 for my $k (qw(address altid nntpmirror imapmirror
454 coderepo hide listid url
455 infourl watchheader nntpserver imapserver)) {
456 my $v = $self->{"$pfx.$k"} // next;
457 $ibx->{$k} = _array($v);
460 return unless valid_foo_name($name, 'publicinbox');
461 $ibx->{name} = $name;
462 $ibx->{-pi_cfg} = $self;
463 $ibx = PublicInbox::Inbox->new($ibx);
464 foreach (@{$ibx->{address}}) {
465 my $lc_addr = lc($_);
466 $self->{-by_addr}->{$lc_addr} = $ibx;
467 $self->{-no_obfuscate}->{$lc_addr} = 1;
469 if (my $listids = $ibx->{listid}) {
470 # RFC2919 section 6 stipulates "case insensitive equality"
471 foreach my $list_id (@$listids) {
472 $self->{-by_list_id}->{lc($list_id)} = $ibx;
475 if (defined(my $ngname = $ibx->{newsgroup})) {
477 delete $ibx->{newsgroup};
478 warn 'multiple newsgroups not supported: '.
479 join(', ', @$ngname). "\n";
480 # Newsgroup name needs to be compatible with RFC 3977
481 # wildmat-exact and RFC 3501 (IMAP) ATOM-CHAR.
482 # Leave out a few chars likely to cause problems or conflicts:
483 # '|', '<', '>', ';', '#', '$', '&',
484 } elsif ($ngname =~ m![^A-Za-z0-9/_\.\-\~\@\+\=:]! ||
486 delete $ibx->{newsgroup};
487 warn "newsgroup name invalid: `$ngname'\n";
489 # PublicInbox::NNTPD does stricter ->nntp_usable
490 # checks, keep this lean for startup speed
491 $self->{-by_newsgroup}->{$ngname} = $ibx;
494 unless (defined $ibx->{newsgroup}) { # for ->eidx_key
495 my $abs = rel2abs_collapsed($dir);
497 warn "W: `$dir' canonicalized to `$abs'\n";
498 $ibx->{inboxdir} = $abs;
501 $self->{-by_name}->{$name} = $ibx;
502 if ($ibx->{obfuscate}) {
503 $ibx->{-no_obfuscate} = $self->{-no_obfuscate};
504 $ibx->{-no_obfuscate_re} = $self->{-no_obfuscate_re};
505 fill_all($self); # noop to populate -no_obfuscate
507 if (my $es = ALL($self)) {
508 require PublicInbox::Isearch;
509 $ibx->{isrch} = PublicInbox::Isearch->new($ibx, $es);
511 $self->{-by_eidx_key}->{$ibx->eidx_key} = $ibx;
515 my ($self, $name) = @_;
516 eval { require PublicInbox::ExtSearch } or return;
517 my $pfx = "extindex.$name";
518 my $d = $self->{"$pfx.topdir"} // return;
520 if (index($d, "\n") >= 0) {
521 warn "E: `$d' must not contain `\\n'\n";
524 my $es = PublicInbox::ExtSearch->new($d);
525 for my $k (qw(indexlevel indexsequentialshard)) {
526 my $v = get_1($self, "$pfx.$k") // next;
529 for my $k (qw(coderepo hide url infourl)) {
530 my $v = $self->{"$pfx.$k"} // next;
531 $es->{$k} = _array($v);
533 return unless valid_foo_name($name, 'extindex');
539 my ($self, $key, $url) = @_;
540 state $urlmatch_broken; # requires git 1.8.5
541 return if $urlmatch_broken;
542 my $file = $self->{'-f'} // default_file();
543 my $cmd = [qw/git config -z --includes --get-urlmatch/,
544 "--file=$file", $key, $url ];
545 my $fh = popen_rd($cmd);
552 $urlmatch_broken = 1 if (($? >> 8) != 1);
560 for my $mod (qw(Cpanel::JSON::XS JSON::MaybeXS JSON JSON::PP)) {
561 eval "require $mod" or next;
562 # ->ascii encodes non-ASCII to "\uXXXX"
563 $json = $mod->new->ascii(1) and last;
569 sub squote_maybe ($) {
571 if ($val =~ m{([^\w@\./,\%\+\-])}) {
572 $val =~ s/(['!])/'\\$1'/g; # '!' for csh