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;
326 # parse a code repo, only git is supported at the moment
328 my ($self, $nick) = @_;
329 my $pfx = "coderepo.$nick";
330 my $dir = $self->{"$pfx.dir"} // do { # aka "GIT_DIR"
331 warn "$pfx.dir unset\n";
334 my $git = PublicInbox::Git->new($dir);
335 if (defined(my $cgits = $self->{"$pfx.cgiturl"})) {
336 $git->{cgit_url} = $cgits = _array($cgits);
337 $self->{"$pfx.cgiturl"} = $cgits;
344 my ($self, $key) = @_;
345 my $v = $self->{$key} // return;
350 my ($val) = $_[-1]; # $_[0] may be $self, or $val
351 if ($val =~ /\A(?:false|no|off|[\-\+]?(?:0x)?0+)\z/i) {
353 } elsif ($val =~ /\A(?:true|yes|on|[\-\+]?(?:0x)?[0-9]+)\z/i) {
360 # abs_path resolves symlinks, so we want to avoid it if rel2abs
361 # is sufficient and doesn't leave "/.." or "/../"
362 sub rel2abs_collapsed {
364 my $p = File::Spec->rel2abs($_[-1]);
365 return $p if substr($p, -3, 3) ne '/..' && index($p, '/../') < 0;
371 my ($self, $key) = @_;
372 my $v = $self->{$key};
373 return $v if !ref($v);
374 warn "W: $key has multiple values, only using `$v->[-1]'\n";
379 my ($self, $ibxish) = @_;
380 my $ibx_code_repos = $ibxish->{coderepo} // return;
381 $ibxish->{-repo_objs} // do {
382 my $code_repos = $self->{-code_repos};
384 for my $nick (@$ibx_code_repos) {
385 my @parts = split(m!/!, $nick);
387 @parts = () unless valid_foo_name($_);
390 warn "invalid coderepo name: `$nick'\n";
393 my $repo = $code_repos->{$nick} //=
394 fill_code_repo($self, $nick);
395 push @repo_objs, $repo if $repo;
397 if (scalar @repo_objs) {
398 $ibxish ->{-repo_objs} = \@repo_objs;
400 delete $ibxish->{coderepo};
406 my ($self, $name) = @_;
407 my $pfx = "publicinbox.$name";
409 for my $k (qw(watch)) {
410 my $v = $self->{"$pfx.$k"};
411 $ibx->{$k} = $v if defined $v;
413 for my $k (qw(filter inboxdir newsgroup replyto httpbackendmax feedmax
414 indexlevel indexsequentialshard boost)) {
415 my $v = get_1($self, "$pfx.$k") // next;
419 # "mainrepo" is backwards compatibility:
420 my $dir = $ibx->{inboxdir} //= $self->{"$pfx.mainrepo"} // return;
421 if (index($dir, "\n") >= 0) {
422 warn "E: `$dir' must not contain `\\n'\n";
425 for my $k (qw(obfuscate)) {
426 my $v = $self->{"$pfx.$k"} // next;
427 if (defined(my $bval = git_bool($v))) {
430 warn "Ignoring $pfx.$k=$v in config, not boolean\n";
433 # TODO: more arrays, we should support multi-value for
434 # more things to encourage decentralization
435 for my $k (qw(address altid nntpmirror imapmirror
436 coderepo hide listid url
437 infourl watchheader nntpserver imapserver)) {
438 my $v = $self->{"$pfx.$k"} // next;
439 $ibx->{$k} = _array($v);
442 return unless valid_foo_name($name, 'publicinbox');
443 $ibx->{name} = $name;
444 $ibx->{-pi_cfg} = $self;
445 $ibx = PublicInbox::Inbox->new($ibx);
446 foreach (@{$ibx->{address}}) {
447 my $lc_addr = lc($_);
448 $self->{-by_addr}->{$lc_addr} = $ibx;
449 $self->{-no_obfuscate}->{$lc_addr} = 1;
451 if (my $listids = $ibx->{listid}) {
452 # RFC2919 section 6 stipulates "case insensitive equality"
453 foreach my $list_id (@$listids) {
454 $self->{-by_list_id}->{lc($list_id)} = $ibx;
457 if (defined(my $ngname = $ibx->{newsgroup})) {
459 delete $ibx->{newsgroup};
460 warn 'multiple newsgroups not supported: '.
461 join(', ', @$ngname). "\n";
462 # Newsgroup name needs to be compatible with RFC 3977
463 # wildmat-exact and RFC 3501 (IMAP) ATOM-CHAR.
464 # Leave out a few chars likely to cause problems or conflicts:
465 # '|', '<', '>', ';', '#', '$', '&',
466 } elsif ($ngname =~ m![^A-Za-z0-9/_\.\-\~\@\+\=:]! ||
468 delete $ibx->{newsgroup};
469 warn "newsgroup name invalid: `$ngname'\n";
471 # PublicInbox::NNTPD does stricter ->nntp_usable
472 # checks, keep this lean for startup speed
473 $self->{-by_newsgroup}->{$ngname} = $ibx;
476 unless (defined $ibx->{newsgroup}) { # for ->eidx_key
477 my $abs = rel2abs_collapsed($dir);
479 warn "W: `$dir' canonicalized to `$abs'\n";
480 $ibx->{inboxdir} = $abs;
483 $self->{-by_name}->{$name} = $ibx;
484 if ($ibx->{obfuscate}) {
485 $ibx->{-no_obfuscate} = $self->{-no_obfuscate};
486 $ibx->{-no_obfuscate_re} = $self->{-no_obfuscate_re};
487 fill_all($self); # noop to populate -no_obfuscate
489 if (my $es = ALL($self)) {
490 require PublicInbox::Isearch;
491 $ibx->{isrch} = PublicInbox::Isearch->new($ibx, $es);
493 $self->{-by_eidx_key}->{$ibx->eidx_key} = $ibx;
497 my ($self, $name) = @_;
498 eval { require PublicInbox::ExtSearch } or return;
499 my $pfx = "extindex.$name";
500 my $d = $self->{"$pfx.topdir"} // return;
502 if (index($d, "\n") >= 0) {
503 warn "E: `$d' must not contain `\\n'\n";
506 my $es = PublicInbox::ExtSearch->new($d);
507 for my $k (qw(indexlevel indexsequentialshard)) {
508 my $v = get_1($self, "$pfx.$k") // next;
511 for my $k (qw(coderepo hide url infourl)) {
512 my $v = $self->{"$pfx.$k"} // next;
513 $es->{$k} = _array($v);
515 return unless valid_foo_name($name, 'extindex');
521 my ($self, $key, $url) = @_;
522 state $urlmatch_broken; # requires git 1.8.5
523 return if $urlmatch_broken;
524 my $file = $self->{'-f'} // default_file();
525 my $cmd = [qw/git config -z --includes --get-urlmatch/,
526 "--file=$file", $key, $url ];
527 my $fh = popen_rd($cmd);
534 $urlmatch_broken = 1 if (($? >> 8) != 1);
542 for my $mod (qw(Cpanel::JSON::XS JSON::MaybeXS JSON JSON::PP)) {
543 eval "require $mod" or next;
544 # ->ascii encodes non-ASCII to "\uXXXX"
545 $json = $mod->new->ascii(1) and last;
551 sub squote_maybe ($) {
553 if ($val =~ m{([^\w@\./,\%\+\-])}) {
554 $val =~ s/(['!])/'\\$1'/g; # '!' for csh