1 # Copyright (C) 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
16 our $DEDUPE; # set to {} to dedupe or clear cache
18 sub _array ($) { ref($_[0]) eq 'ARRAY' ? $_[0] : [ $_[0] ] }
20 # returns key-value pairs of config directives in a hash
21 # if keys may be multi-value, the value is an array ref containing all values
23 my ($class, $file, $errfh) = @_;
24 $file //= default_file();
27 if (ref($file) eq 'SCALAR') { # used by some tests
28 open my $fh, '<', $file or die; # PerlIO::scalar
29 $self = config_fh_parse($fh, "\n", '=');
32 if (-f $file && $DEDUPE) {
33 $file = rel2abs_collapsed($file);
34 $self = $DEDUPE->{$file} and return $self;
37 $self = git_config_dump($class, $file, $errfh);
38 $self->{'-f'} = $file;
41 $self->{-by_addr} = {};
42 $self->{-by_list_id} = {};
43 $self->{-by_name} = {};
44 $self->{-by_newsgroup} = {};
45 $self->{-by_eidx_key} = {};
46 $self->{-no_obfuscate} = {};
47 $self->{-limiters} = {};
48 $self->{-code_repos} = {}; # nick => PublicInbox::Git object
50 if (my $no = delete $self->{'publicinbox.noobfuscate'}) {
53 foreach my $n (@$no) {
54 my @n = split(/\s+/, $n);
56 if (/\S+@\S+/) { # full address
57 $self->{-no_obfuscate}->{lc $_} = 1;
59 # allow "example.com" or "@example.com"
61 push @domains, quotemeta($_);
65 my $nod = join('|', @domains);
66 $self->{-no_obfuscate_re} = qr/(?:$nod)\z/i;
68 if (my $css = delete $self->{'publicinbox.css'}) {
69 $self->{css} = _array($css);
71 $DEDUPE->{$file} = $self if $set_dedupe;
76 sub fill_all ($) { each_inbox($_[0], \&noop) }
78 sub _lookup_fill ($$$) {
79 my ($self, $cache, $key) = @_;
80 $self->{$cache}->{$key} // do {
82 $self->{$cache}->{$key};
87 my ($self, $recipient) = @_;
88 _lookup_fill($self, '-by_addr', lc($recipient));
92 my ($self, $list_id) = @_;
93 _lookup_fill($self, '-by_list_id', lc($list_id));
96 sub lookup_name ($$) {
97 my ($self, $name) = @_;
98 $self->{-by_name}->{$name} // _fill_ibx($self, $name);
102 my ($self, $name) = @_;
103 $self->{-ei_by_name}->{$name} //= _fill_ei($self, $name);
106 sub lookup_eidx_key {
107 my ($self, $eidx_key) = @_;
108 _lookup_fill($self, '-by_eidx_key', $eidx_key);
111 # special case for [extindex "all"]
112 sub ALL { lookup_ei($_[0], 'all') }
115 my ($self, $cb, @arg) = @_;
116 # may auto-vivify if config file is non-existent:
117 foreach my $section (@{$self->{-section_order}}) {
118 next if $section !~ m!\Apublicinbox\.([^/]+)\z!;
119 my $ibx = lookup_name($self, $1) or next;
124 sub lookup_newsgroup {
125 my ($self, $ng) = @_;
126 _lookup_fill($self, '-by_newsgroup', lc($ng));
130 my ($self, $name) = @_;
131 $self->{-limiters}->{$name} //= do {
132 require PublicInbox::Qspawn;
133 my $max = $self->{"publicinboxlimiter.$name.max"} || 1;
134 my $limiter = PublicInbox::Qspawn::Limiter->new($max);
135 $limiter->setup_rlimit($name, $self);
140 sub config_dir { $ENV{PI_DIR} // "$ENV{HOME}/.public-inbox" }
143 $ENV{PI_CONFIG} // (config_dir() . '/config');
146 sub config_fh_parse ($$$) {
147 my ($fh, $rs, $fs) = @_;
148 my (%rv, %seen, @section_order, $line, $k, $v, $section, $cur, $i);
150 while (defined($line = <$fh>)) { # perf critical with giant configs
151 $i = index($line, $fs);
152 $k = substr($line, 0, $i);
153 $v = substr($line, $i + 1, -1); # chop off $fs
154 $section = substr($k, 0, rindex($k, '.'));
155 $seen{$section} //= push(@section_order, $section);
157 if (defined($cur = $rv{$k})) {
158 if (ref($cur) eq "ARRAY") {
161 $rv{$k} = [ $cur, $v ];
167 $rv{-section_order} = \@section_order;
172 sub git_config_dump {
173 my ($class, $file, $errfh) = @_;
174 return bless {}, $class unless -e $file;
175 my $cmd = [ qw(git config -z -l --includes), "--file=$file" ];
176 my $fh = popen_rd($cmd, undef, { 2 => $errfh // 2 });
177 my $rv = config_fh_parse($fh, "\0", "\n");
178 close $fh or die "@$cmd failed: \$?=$?\n";
182 sub valid_foo_name ($;$) {
183 my ($name, $pfx) = @_;
185 # Similar rules found in git.git/remote.c::valid_remote_nick
186 # and git.git/refs.c::check_refname_component
187 # We don't reject /\.lock\z/, however, since we don't lock refs
188 if ($name eq '' || $name =~ /\@\{/ ||
189 $name =~ /\.\./ || $name =~ m![/:\?\[\]\^~\s\f[:cntrl:]\*]! ||
190 $name =~ /\A\./ || $name =~ /\.\z/) {
191 warn "invalid $pfx name: `$name'\n" if $pfx;
195 # Note: we allow URL-unfriendly characters; users may configure
196 # non-HTTP-accessible inboxes
200 # XXX needs testing for cgit compatibility
201 # cf. cgit/scan-tree.c::add_repo
202 sub cgit_repo_merge ($$$) {
203 my ($self, $base, $repo) = @_;
204 my $path = $repo->{dir};
205 if (defined(my $se = $self->{-cgit_strict_export})) {
206 return unless -e "$path/$se";
208 return if -e "$path/noweb";
209 # this comes from the cgit config, and AFAIK cgit only allows
210 # repos to have one URL, but that's just the PATH_INFO component,
211 # not the Host: portion
212 # $repo = { url => 'foo.git', dir => '/path/to/foo.git' }
213 my $rel = $repo->{url};
214 unless (defined $rel) {
215 my $off = index($path, $base, 0);
219 $rel = substr($path, length($base) + 1);
222 $rel =~ s!/\.git\z!! or
225 $self->{-cgit_remove_suffix} and
226 $rel =~ s!/?\.git\z!!;
228 $self->{"coderepo.$rel.dir"} //= $path;
233 -d "$git_dir/objects" && -f "$git_dir/HEAD";
236 # XXX needs testing for cgit compatibility
237 sub scan_path_coderepo {
238 my ($self, $base, $path) = @_;
239 opendir(my $dh, $path) or do {
240 warn "error opening directory: $path\n";
244 if (is_git_dir($git_dir) || is_git_dir($git_dir .= '/.git')) {
245 my $repo = { dir => $git_dir };
246 cgit_repo_merge($self, $base, $repo);
249 while (defined(my $dn = readdir $dh)) {
250 next if $dn eq '.' || $dn eq '..';
251 if (index($dn, '.') == 0 && !$self->{-cgit_scan_hidden_path}) {
254 my $dir = "$path/$dn";
255 scan_path_coderepo($self, $base, $dir) if -d $dir;
259 sub scan_tree_coderepo ($$) {
260 my ($self, $path) = @_;
261 scan_path_coderepo($self, $path, $path);
264 sub scan_projects_coderepo ($$$) {
265 my ($self, $list, $path) = @_;
266 open my $fh, '<', $list or do {
267 warn "failed to open cgit projectlist=$list: $!\n";
272 scan_path_coderepo($self, $path, "$path/$_");
277 my ($self, $cgitrc, $nesting) = @_;
278 $cgitrc //= $self->{'publicinbox.cgitrc'} // return;
281 my %s = map { $_ => 1 } qw(/cgit.css /cgit.png
282 /favicon.ico /robots.txt);
283 $self->{-cgit_static} = \%s;
286 # same limit as cgit/configfile.c::parse_configfile
287 return if $nesting > 8;
289 open my $fh, '<', $cgitrc or do {
290 warn "failed to open cgitrc=$cgitrc: $!\n";
294 # FIXME: this doesn't support macro expansion via $VARS, yet
298 if (m!\Arepo\.url=(.+?)/*\z!) {
300 cgit_repo_merge($self, $repo->{dir}, $repo) if $repo;
301 $repo = { url => $nick };
302 } elsif (m!\Arepo\.path=(.+)\z!) {
306 warn "$_ without repo.url\n";
308 } elsif (m!\Ainclude=(.+)\z!) {
309 parse_cgitrc($self, $1, $nesting + 1);
310 } elsif (m!\A(scan-hidden-path|remove-suffix)=([0-9]+)\z!) {
311 my ($k, $v) = ($1, $2);
313 $self->{"-cgit_$k"} = $v;
314 } elsif (m!\A(project-list|strict-export)=(.+)\z!) {
315 my ($k, $v) = ($1, $2);
317 $self->{"-cgit_$k"} = $v;
318 } elsif (m!\Ascan-path=(.+)\z!) {
319 if (defined(my $list = $self->{-cgit_project_list})) {
320 scan_projects_coderepo($self, $list, $1);
322 scan_tree_coderepo($self, $1);
324 } elsif (m!\A(?:css|favicon|logo|repo\.logo)=(/.+)\z!) {
325 # absolute paths for static files via PublicInbox::Cgit
326 $self->{-cgit_static}->{$1} = 1;
327 } elsif (s!\Asnapshots=\s*!!) {
328 $self->{'coderepo.snapshots'} = $_;
331 cgit_repo_merge($self, $repo->{dir}, $repo) if $repo;
334 # parse a code repo, only git is supported at the moment
336 my ($self, $nick) = @_;
337 my $pfx = "coderepo.$nick";
338 my $dir = $self->{"$pfx.dir"} // do { # aka "GIT_DIR"
339 warn "$pfx.dir unset\n";
342 my $git = PublicInbox::Git->new($dir);
343 if (defined(my $cgits = $self->{"$pfx.cgiturl"})) {
344 $git->{cgit_url} = $cgits = _array($cgits);
345 $self->{"$pfx.cgiturl"} = $cgits;
347 $git->{nick} = $nick;
352 my ($self, $key) = @_;
353 my $v = $self->{$key} // return;
358 my ($val) = $_[-1]; # $_[0] may be $self, or $val
359 if ($val =~ /\A(?:false|no|off|[\-\+]?(?:0x)?0+)\z/i) {
361 } elsif ($val =~ /\A(?:true|yes|on|[\-\+]?(?:0x)?[0-9]+)\z/i) {
368 # abs_path resolves symlinks, so we want to avoid it if rel2abs
369 # is sufficient and doesn't leave "/.." or "/../"
370 sub rel2abs_collapsed {
372 my $p = File::Spec->rel2abs($_[-1]);
373 return $p if substr($p, -3, 3) ne '/..' && index($p, '/../') < 0;
379 my ($self, $key) = @_;
380 my $v = $self->{$key};
381 return $v if !ref($v);
382 warn "W: $key has multiple values, only using `$v->[-1]'\n";
387 my ($self, $ibxish) = @_;
388 my $ibx_code_repos = $ibxish->{coderepo} // return;
389 $ibxish->{-repo_objs} // do {
390 parse_cgitrc($self, undef, 0);
391 my $code_repos = $self->{-code_repos};
393 for my $nick (@$ibx_code_repos) {
394 my @parts = split(m!/!, $nick);
396 @parts = () unless valid_foo_name($_);
399 warn "invalid coderepo name: `$nick'\n";
402 my $repo = $code_repos->{$nick} //=
403 fill_code_repo($self, $nick);
404 push @repo_objs, $repo if $repo;
406 if (scalar @repo_objs) {
408 push @{$_->{ibx_names}}, $ibxish->{name};
410 $ibxish->{-repo_objs} = \@repo_objs;
412 delete $ibxish->{coderepo};
418 my ($self, $name) = @_;
419 my $pfx = "publicinbox.$name";
421 for my $k (qw(watch)) {
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 boost)) {
427 my $v = get_1($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 imapmirror
448 coderepo hide listid url
450 nntpserver imapserver pop3server)) {
451 my $v = $self->{"$pfx.$k"} // next;
452 $ibx->{$k} = _array($v);
455 return unless valid_foo_name($name, 'publicinbox');
456 $ibx->{name} = $name;
457 $ibx->{-pi_cfg} = $self;
458 $ibx = PublicInbox::Inbox->new($ibx);
459 foreach (@{$ibx->{address}}) {
460 my $lc_addr = lc($_);
461 $self->{-by_addr}->{$lc_addr} = $ibx;
462 $self->{-no_obfuscate}->{$lc_addr} = 1;
464 if (my $listids = $ibx->{listid}) {
465 # RFC2919 section 6 stipulates "case insensitive equality"
466 foreach my $list_id (@$listids) {
467 $self->{-by_list_id}->{lc($list_id)} = $ibx;
470 if (defined(my $ngname = $ibx->{newsgroup})) {
472 delete $ibx->{newsgroup};
473 warn 'multiple newsgroups not supported: '.
474 join(', ', @$ngname). "\n";
475 # Newsgroup name needs to be compatible with RFC 3977
476 # wildmat-exact and RFC 3501 (IMAP) ATOM-CHAR.
477 # Leave out a few chars likely to cause problems or conflicts:
478 # '|', '<', '>', ';', '#', '$', '&',
479 } elsif ($ngname =~ m![^A-Za-z0-9/_\.\-\~\@\+\=:]! ||
481 delete $ibx->{newsgroup};
482 warn "newsgroup name invalid: `$ngname'\n";
484 # PublicInbox::NNTPD does stricter ->nntp_usable
485 # checks, keep this lean for startup speed
486 $self->{-by_newsgroup}->{$ngname} = $ibx;
489 unless (defined $ibx->{newsgroup}) { # for ->eidx_key
490 my $abs = rel2abs_collapsed($dir);
492 warn "W: `$dir' canonicalized to `$abs'\n";
493 $ibx->{inboxdir} = $abs;
496 $self->{-by_name}->{$name} = $ibx;
497 if ($ibx->{obfuscate}) {
498 $ibx->{-no_obfuscate} = $self->{-no_obfuscate};
499 $ibx->{-no_obfuscate_re} = $self->{-no_obfuscate_re};
500 fill_all($self); # noop to populate -no_obfuscate
502 if (my $es = ALL($self)) {
503 require PublicInbox::Isearch;
504 $ibx->{isrch} = PublicInbox::Isearch->new($ibx, $es);
506 $self->{-by_eidx_key}->{$ibx->eidx_key} = $ibx;
510 my ($self, $name) = @_;
511 eval { require PublicInbox::ExtSearch } or return;
512 my $pfx = "extindex.$name";
513 my $d = $self->{"$pfx.topdir"} // return;
515 if (index($d, "\n") >= 0) {
516 warn "E: `$d' must not contain `\\n'\n";
519 my $es = PublicInbox::ExtSearch->new($d);
520 for my $k (qw(indexlevel indexsequentialshard)) {
521 my $v = get_1($self, "$pfx.$k") // next;
524 for my $k (qw(coderepo hide url infourl)) {
525 my $v = $self->{"$pfx.$k"} // next;
526 $es->{$k} = _array($v);
528 return unless valid_foo_name($name, 'extindex');
534 my ($self, $key, $url, $try_git) = @_;
535 state $urlmatch_broken; # requires git 1.8.5
536 return if $urlmatch_broken;
537 my $file = $self->{'-f'} // default_file();
538 my $cmd = [qw/git config -z --includes --get-urlmatch/,
539 "--file=$file", $key, $url ];
540 my $fh = popen_rd($cmd);
545 if (($? >> 8) != 1) {
546 $urlmatch_broken = 1;
547 } elsif ($try_git) { # n.b. this takes cwd into account
548 $cmd = [qw(git config -z --get-urlmatch), $key, $url];
549 $fh = popen_rd($cmd);
551 close($fh) or undef($val);
554 $? = 0; # don't influence lei exit status
555 chomp $val if defined $val;
562 for my $mod (qw(Cpanel::JSON::XS JSON::MaybeXS JSON JSON::PP)) {
563 eval "require $mod" or next;
564 # ->ascii encodes non-ASCII to "\uXXXX"
565 $json = $mod->new->ascii(1) and last;
571 sub squote_maybe ($) {
573 if ($val =~ m{([^\w@\./,\%\+\-])}) {
574 $val =~ s/(['!])/'\\$1'/g; # '!' for csh