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;
229 $self->{"coderepo.$rel.cgiturl"} //= _array($rel);
234 -d "$git_dir/objects" && -f "$git_dir/HEAD";
237 # XXX needs testing for cgit compatibility
238 sub scan_path_coderepo {
239 my ($self, $base, $path) = @_;
240 opendir(my $dh, $path) or do {
241 warn "error opening directory: $path\n";
245 if (is_git_dir($git_dir) || is_git_dir($git_dir .= '/.git')) {
246 my $repo = { dir => $git_dir };
247 cgit_repo_merge($self, $base, $repo);
250 while (defined(my $dn = readdir $dh)) {
251 next if $dn eq '.' || $dn eq '..';
252 if (index($dn, '.') == 0 && !$self->{-cgit_scan_hidden_path}) {
255 my $dir = "$path/$dn";
256 scan_path_coderepo($self, $base, $dir) if -d $dir;
260 sub scan_tree_coderepo ($$) {
261 my ($self, $path) = @_;
262 scan_path_coderepo($self, $path, $path);
265 sub scan_projects_coderepo ($$$) {
266 my ($self, $list, $path) = @_;
267 open my $fh, '<', $list or do {
268 warn "failed to open cgit projectlist=$list: $!\n";
273 scan_path_coderepo($self, $path, "$path/$_");
278 my ($self, $cgitrc, $nesting) = @_;
279 $cgitrc //= $self->{'publicinbox.cgitrc'};
282 my %s = map { $_ => 1 } qw(/cgit.css /cgit.png
283 /favicon.ico /robots.txt);
284 $self->{-cgit_static} = \%s;
287 # same limit as cgit/configfile.c::parse_configfile
288 return if $nesting > 8;
290 open my $fh, '<', $cgitrc or do {
291 warn "failed to open cgitrc=$cgitrc: $!\n";
295 # FIXME: this doesn't support macro expansion via $VARS, yet
299 if (m!\Arepo\.url=(.+?)/*\z!) {
301 cgit_repo_merge($self, $repo->{dir}, $repo) if $repo;
302 $repo = { url => $nick };
303 } elsif (m!\Arepo\.path=(.+)\z!) {
307 warn "$_ without repo.url\n";
309 } elsif (m!\Ainclude=(.+)\z!) {
310 parse_cgitrc($self, $1, $nesting + 1);
311 } elsif (m!\A(scan-hidden-path|remove-suffix)=([0-9]+)\z!) {
312 my ($k, $v) = ($1, $2);
314 $self->{"-cgit_$k"} = $v;
315 } elsif (m!\A(project-list|strict-export)=(.+)\z!) {
316 my ($k, $v) = ($1, $2);
318 $self->{"-cgit_$k"} = $v;
319 } elsif (m!\Ascan-path=(.+)\z!) {
320 if (defined(my $list = $self->{-cgit_project_list})) {
321 scan_projects_coderepo($self, $list, $1);
323 scan_tree_coderepo($self, $1);
325 } elsif (m!\A(?:css|favicon|logo|repo\.logo)=(/.+)\z!) {
326 # absolute paths for static files via PublicInbox::Cgit
327 $self->{-cgit_static}->{$1} = 1;
328 } elsif (s!\Asnapshots=\s*!!) {
329 $self->{'coderepo.snapshots'} = $_;
332 cgit_repo_merge($self, $repo->{dir}, $repo) if $repo;
335 # parse a code repo, only git is supported at the moment
337 my ($self, $nick) = @_;
338 my $pfx = "coderepo.$nick";
339 my $dir = $self->{"$pfx.dir"} // do { # aka "GIT_DIR"
340 warn "$pfx.dir unset\n";
343 my $git = PublicInbox::Git->new($dir);
344 if (defined(my $cgits = $self->{"$pfx.cgiturl"})) {
345 $git->{cgit_url} = $cgits = _array($cgits);
346 $self->{"$pfx.cgiturl"} = $cgits;
348 $git->{nick} = $nick;
353 my ($self, $key) = @_;
354 my $v = $self->{$key} // return;
359 my ($val) = $_[-1]; # $_[0] may be $self, or $val
360 if ($val =~ /\A(?:false|no|off|[\-\+]?(?:0x)?0+)\z/i) {
362 } elsif ($val =~ /\A(?:true|yes|on|[\-\+]?(?:0x)?[0-9]+)\z/i) {
369 # abs_path resolves symlinks, so we want to avoid it if rel2abs
370 # is sufficient and doesn't leave "/.." or "/../"
371 sub rel2abs_collapsed {
373 my $p = File::Spec->rel2abs($_[-1]);
374 return $p if substr($p, -3, 3) ne '/..' && index($p, '/../') < 0;
380 my ($self, $key) = @_;
381 my $v = $self->{$key};
382 return $v if !ref($v);
383 warn "W: $key has multiple values, only using `$v->[-1]'\n";
388 my ($self, $ibxish) = @_;
389 my $ibx_code_repos = $ibxish->{coderepo} // return;
390 $ibxish->{-repo_objs} // do {
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) {
407 require Scalar::Util;
409 push @{$_->{-ibxs}}, $ibxish;
410 Scalar::Util::weaken($_->{-ibxs}->[-1]);
412 $ibxish->{-repo_objs} = \@repo_objs;
414 delete $ibxish->{coderepo};
420 my ($self, $name) = @_;
421 my $pfx = "publicinbox.$name";
423 for my $k (qw(watch)) {
424 my $v = $self->{"$pfx.$k"};
425 $ibx->{$k} = $v if defined $v;
427 for my $k (qw(filter inboxdir newsgroup replyto httpbackendmax feedmax
428 indexlevel indexsequentialshard boost)) {
429 my $v = get_1($self, "$pfx.$k") // next;
433 # "mainrepo" is backwards compatibility:
434 my $dir = $ibx->{inboxdir} //= $self->{"$pfx.mainrepo"} // return;
435 if (index($dir, "\n") >= 0) {
436 warn "E: `$dir' must not contain `\\n'\n";
439 for my $k (qw(obfuscate)) {
440 my $v = $self->{"$pfx.$k"} // next;
441 if (defined(my $bval = git_bool($v))) {
444 warn "Ignoring $pfx.$k=$v in config, not boolean\n";
447 # TODO: more arrays, we should support multi-value for
448 # more things to encourage decentralization
449 for my $k (qw(address altid nntpmirror imapmirror
450 coderepo hide listid url
452 nntpserver imapserver pop3server)) {
453 my $v = $self->{"$pfx.$k"} // next;
454 $ibx->{$k} = _array($v);
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;
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;
472 if (defined(my $ngname = $ibx->{newsgroup})) {
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/_\.\-\~\@\+\=:]! ||
483 delete $ibx->{newsgroup};
484 warn "newsgroup name invalid: `$ngname'\n";
486 # PublicInbox::NNTPD does stricter ->nntp_usable
487 # checks, keep this lean for startup speed
488 $self->{-by_newsgroup}->{$ngname} = $ibx;
491 unless (defined $ibx->{newsgroup}) { # for ->eidx_key
492 my $abs = rel2abs_collapsed($dir);
494 warn "W: `$dir' canonicalized to `$abs'\n";
495 $ibx->{inboxdir} = $abs;
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
504 if (my $es = ALL($self)) {
505 require PublicInbox::Isearch;
506 $ibx->{isrch} = PublicInbox::Isearch->new($ibx, $es);
508 $self->{-by_eidx_key}->{$ibx->eidx_key} = $ibx;
512 my ($self, $name) = @_;
513 eval { require PublicInbox::ExtSearch } or return;
514 my $pfx = "extindex.$name";
515 my $d = $self->{"$pfx.topdir"} // return;
517 if (index($d, "\n") >= 0) {
518 warn "E: `$d' must not contain `\\n'\n";
521 my $es = PublicInbox::ExtSearch->new($d);
522 for my $k (qw(indexlevel indexsequentialshard)) {
523 my $v = get_1($self, "$pfx.$k") // next;
526 for my $k (qw(coderepo hide url infourl)) {
527 my $v = $self->{"$pfx.$k"} // next;
528 $es->{$k} = _array($v);
530 return unless valid_foo_name($name, 'extindex');
536 my ($self, $key, $url, $try_git) = @_;
537 state $urlmatch_broken; # requires git 1.8.5
538 return if $urlmatch_broken;
539 my $file = $self->{'-f'} // default_file();
540 my $cmd = [qw/git config -z --includes --get-urlmatch/,
541 "--file=$file", $key, $url ];
542 my $fh = popen_rd($cmd);
547 if (($? >> 8) != 1) {
548 $urlmatch_broken = 1;
549 } elsif ($try_git) { # n.b. this takes cwd into account
550 $cmd = [qw(git config -z --get-urlmatch), $key, $url];
551 $fh = popen_rd($cmd);
553 close($fh) or undef($val);
556 $? = 0; # don't influence lei exit status
557 chomp $val if defined $val;
564 for my $mod (qw(Cpanel::JSON::XS JSON::MaybeXS JSON JSON::PP)) {
565 eval "require $mod" or next;
566 # ->ascii encodes non-ASCII to "\uXXXX"
567 $json = $mod->new->ascii(1) and last;
573 sub squote_maybe ($) {
575 if ($val =~ m{([^\w@\./,\%\+\-])}) {
576 $val =~ s/(['!])/'\\$1'/g; # '!' for csh