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
49 $self->{-cgitrc_unparsed} = $self->{'publicinbox.cgitrc'};
51 if (my $no = delete $self->{'publicinbox.noobfuscate'}) {
54 foreach my $n (@$no) {
55 my @n = split(/\s+/, $n);
57 if (/\S+@\S+/) { # full address
58 $self->{-no_obfuscate}->{lc $_} = 1;
60 # allow "example.com" or "@example.com"
62 push @domains, quotemeta($_);
66 my $nod = join('|', @domains);
67 $self->{-no_obfuscate_re} = qr/(?:$nod)\z/i;
69 if (my $css = delete $self->{'publicinbox.css'}) {
70 $self->{css} = _array($css);
72 $DEDUPE->{$file} = $self if $set_dedupe;
77 sub fill_all ($) { each_inbox($_[0], \&noop) }
79 sub _lookup_fill ($$$) {
80 my ($self, $cache, $key) = @_;
81 $self->{$cache}->{$key} // do {
83 $self->{$cache}->{$key};
88 my ($self, $recipient) = @_;
89 _lookup_fill($self, '-by_addr', lc($recipient));
93 my ($self, $list_id) = @_;
94 _lookup_fill($self, '-by_list_id', lc($list_id));
97 sub lookup_name ($$) {
98 my ($self, $name) = @_;
99 $self->{-by_name}->{$name} // _fill_ibx($self, $name);
103 my ($self, $name) = @_;
104 $self->{-ei_by_name}->{$name} //= _fill_ei($self, $name);
107 sub lookup_eidx_key {
108 my ($self, $eidx_key) = @_;
109 _lookup_fill($self, '-by_eidx_key', $eidx_key);
112 # special case for [extindex "all"]
113 sub ALL { lookup_ei($_[0], 'all') }
116 my ($self, $cb, @arg) = @_;
117 # may auto-vivify if config file is non-existent:
118 foreach my $section (@{$self->{-section_order}}) {
119 next if $section !~ m!\Apublicinbox\.([^/]+)\z!;
120 my $ibx = lookup_name($self, $1) or next;
125 sub lookup_newsgroup {
126 my ($self, $ng) = @_;
127 _lookup_fill($self, '-by_newsgroup', lc($ng));
131 my ($self, $name) = @_;
132 $self->{-limiters}->{$name} //= do {
133 require PublicInbox::Qspawn;
134 my $max = $self->{"publicinboxlimiter.$name.max"} || 1;
135 my $limiter = PublicInbox::Qspawn::Limiter->new($max);
136 $limiter->setup_rlimit($name, $self);
141 sub config_dir { $ENV{PI_DIR} // "$ENV{HOME}/.public-inbox" }
144 $ENV{PI_CONFIG} // (config_dir() . '/config');
147 sub config_fh_parse ($$$) {
148 my ($fh, $rs, $fs) = @_;
149 my (%rv, %seen, @section_order, $line, $k, $v, $section, $cur, $i);
151 while (defined($line = <$fh>)) { # perf critical with giant configs
152 $i = index($line, $fs);
153 $k = substr($line, 0, $i);
154 $v = substr($line, $i + 1, -1); # chop off $fs
155 $section = substr($k, 0, rindex($k, '.'));
156 $seen{$section} //= push(@section_order, $section);
158 if (defined($cur = $rv{$k})) {
159 if (ref($cur) eq "ARRAY") {
162 $rv{$k} = [ $cur, $v ];
168 $rv{-section_order} = \@section_order;
173 sub git_config_dump {
174 my ($class, $file, $errfh) = @_;
175 return bless {}, $class unless -e $file;
176 my $cmd = [ qw(git config -z -l --includes), "--file=$file" ];
177 my $fh = popen_rd($cmd, undef, { 2 => $errfh // 2 });
178 my $rv = config_fh_parse($fh, "\0", "\n");
179 close $fh or die "@$cmd failed: \$?=$?\n";
183 sub valid_foo_name ($;$) {
184 my ($name, $pfx) = @_;
186 # Similar rules found in git.git/remote.c::valid_remote_nick
187 # and git.git/refs.c::check_refname_component
188 # We don't reject /\.lock\z/, however, since we don't lock refs
189 if ($name eq '' || $name =~ /\@\{/ ||
190 $name =~ /\.\./ || $name =~ m![/:\?\[\]\^~\s\f[:cntrl:]\*]! ||
191 $name =~ /\A\./ || $name =~ /\.\z/) {
192 warn "invalid $pfx name: `$name'\n" if $pfx;
196 # Note: we allow URL-unfriendly characters; users may configure
197 # non-HTTP-accessible inboxes
201 # XXX needs testing for cgit compatibility
202 # cf. cgit/scan-tree.c::add_repo
203 sub cgit_repo_merge ($$$) {
204 my ($self, $base, $repo) = @_;
205 my $path = $repo->{dir};
206 if (defined(my $se = $self->{-cgit_strict_export})) {
207 return unless -e "$path/$se";
209 return if -e "$path/noweb";
210 # this comes from the cgit config, and AFAIK cgit only allows
211 # repos to have one URL, but that's just the PATH_INFO component,
212 # not the Host: portion
213 # $repo = { url => 'foo.git', dir => '/path/to/foo.git' }
214 my $rel = $repo->{url};
215 unless (defined $rel) {
216 my $off = index($path, $base, 0);
220 $rel = substr($path, length($base) + 1);
223 $rel =~ s!/\.git\z!! or
226 $self->{-cgit_remove_suffix} and
227 $rel =~ s!/?\.git\z!!;
229 $self->{"coderepo.$rel.dir"} //= $path;
230 $self->{"coderepo.$rel.cgiturl"} //= _array($rel);
235 -d "$git_dir/objects" && -f "$git_dir/HEAD";
238 # XXX needs testing for cgit compatibility
239 sub scan_path_coderepo {
240 my ($self, $base, $path) = @_;
241 opendir(my $dh, $path) or do {
242 warn "error opening directory: $path\n";
246 if (is_git_dir($git_dir) || is_git_dir($git_dir .= '/.git')) {
247 my $repo = { dir => $git_dir };
248 cgit_repo_merge($self, $base, $repo);
251 while (defined(my $dn = readdir $dh)) {
252 next if $dn eq '.' || $dn eq '..';
253 if (index($dn, '.') == 0 && !$self->{-cgit_scan_hidden_path}) {
256 my $dir = "$path/$dn";
257 scan_path_coderepo($self, $base, $dir) if -d $dir;
261 sub scan_tree_coderepo ($$) {
262 my ($self, $path) = @_;
263 scan_path_coderepo($self, $path, $path);
266 sub scan_projects_coderepo ($$$) {
267 my ($self, $list, $path) = @_;
268 open my $fh, '<', $list or do {
269 warn "failed to open cgit projectlist=$list: $!\n";
274 scan_path_coderepo($self, $path, "$path/$_");
279 my ($self, $cgitrc, $nesting) = @_;
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;
330 cgit_repo_merge($self, $repo->{dir}, $repo) if $repo;
333 # parse a code repo, only git is supported at the moment
335 my ($self, $nick) = @_;
336 my $pfx = "coderepo.$nick";
337 my $dir = $self->{"$pfx.dir"} // do { # aka "GIT_DIR"
338 warn "$pfx.dir unset\n";
341 my $git = PublicInbox::Git->new($dir);
342 if (defined(my $cgits = $self->{"$pfx.cgiturl"})) {
343 $git->{cgit_url} = $cgits = _array($cgits);
344 $self->{"$pfx.cgiturl"} = $cgits;
351 my ($self, $key) = @_;
352 my $v = $self->{$key} // return;
357 my ($val) = $_[-1]; # $_[0] may be $self, or $val
358 if ($val =~ /\A(?:false|no|off|[\-\+]?(?:0x)?0+)\z/i) {
360 } elsif ($val =~ /\A(?:true|yes|on|[\-\+]?(?:0x)?[0-9]+)\z/i) {
367 # abs_path resolves symlinks, so we want to avoid it if rel2abs
368 # is sufficient and doesn't leave "/.." or "/../"
369 sub rel2abs_collapsed {
371 my $p = File::Spec->rel2abs($_[-1]);
372 return $p if substr($p, -3, 3) ne '/..' && index($p, '/../') < 0;
378 my ($self, $key) = @_;
379 my $v = $self->{$key};
380 return $v if !ref($v);
381 warn "W: $key has multiple values, only using `$v->[-1]'\n";
386 my ($self, $ibxish) = @_;
387 my $ibx_code_repos = $ibxish->{coderepo} // return;
388 $ibxish->{-repo_objs} // do {
389 my $code_repos = $self->{-code_repos};
391 for my $nick (@$ibx_code_repos) {
392 my @parts = split(m!/!, $nick);
394 @parts = () unless valid_foo_name($_);
397 warn "invalid coderepo name: `$nick'\n";
400 my $repo = $code_repos->{$nick} //=
401 fill_code_repo($self, $nick);
402 push @repo_objs, $repo if $repo;
404 if (scalar @repo_objs) {
405 $ibxish ->{-repo_objs} = \@repo_objs;
407 delete $ibxish->{coderepo};
413 my ($self, $name) = @_;
414 my $pfx = "publicinbox.$name";
416 for my $k (qw(watch)) {
417 my $v = $self->{"$pfx.$k"};
418 $ibx->{$k} = $v if defined $v;
420 for my $k (qw(filter inboxdir newsgroup replyto httpbackendmax feedmax
421 indexlevel indexsequentialshard boost)) {
422 my $v = get_1($self, "$pfx.$k") // next;
426 # "mainrepo" is backwards compatibility:
427 my $dir = $ibx->{inboxdir} //= $self->{"$pfx.mainrepo"} // return;
428 if (index($dir, "\n") >= 0) {
429 warn "E: `$dir' must not contain `\\n'\n";
432 for my $k (qw(obfuscate)) {
433 my $v = $self->{"$pfx.$k"} // next;
434 if (defined(my $bval = git_bool($v))) {
437 warn "Ignoring $pfx.$k=$v in config, not boolean\n";
440 # TODO: more arrays, we should support multi-value for
441 # more things to encourage decentralization
442 for my $k (qw(address altid nntpmirror imapmirror
443 coderepo hide listid url
445 nntpserver imapserver pop3server)) {
446 my $v = $self->{"$pfx.$k"} // next;
447 $ibx->{$k} = _array($v);
450 return unless valid_foo_name($name, 'publicinbox');
451 $ibx->{name} = $name;
452 $ibx->{-pi_cfg} = $self;
453 $ibx = PublicInbox::Inbox->new($ibx);
454 foreach (@{$ibx->{address}}) {
455 my $lc_addr = lc($_);
456 $self->{-by_addr}->{$lc_addr} = $ibx;
457 $self->{-no_obfuscate}->{$lc_addr} = 1;
459 if (my $listids = $ibx->{listid}) {
460 # RFC2919 section 6 stipulates "case insensitive equality"
461 foreach my $list_id (@$listids) {
462 $self->{-by_list_id}->{lc($list_id)} = $ibx;
465 if (defined(my $ngname = $ibx->{newsgroup})) {
467 delete $ibx->{newsgroup};
468 warn 'multiple newsgroups not supported: '.
469 join(', ', @$ngname). "\n";
470 # Newsgroup name needs to be compatible with RFC 3977
471 # wildmat-exact and RFC 3501 (IMAP) ATOM-CHAR.
472 # Leave out a few chars likely to cause problems or conflicts:
473 # '|', '<', '>', ';', '#', '$', '&',
474 } elsif ($ngname =~ m![^A-Za-z0-9/_\.\-\~\@\+\=:]! ||
476 delete $ibx->{newsgroup};
477 warn "newsgroup name invalid: `$ngname'\n";
479 # PublicInbox::NNTPD does stricter ->nntp_usable
480 # checks, keep this lean for startup speed
481 $self->{-by_newsgroup}->{$ngname} = $ibx;
484 unless (defined $ibx->{newsgroup}) { # for ->eidx_key
485 my $abs = rel2abs_collapsed($dir);
487 warn "W: `$dir' canonicalized to `$abs'\n";
488 $ibx->{inboxdir} = $abs;
491 $self->{-by_name}->{$name} = $ibx;
492 if ($ibx->{obfuscate}) {
493 $ibx->{-no_obfuscate} = $self->{-no_obfuscate};
494 $ibx->{-no_obfuscate_re} = $self->{-no_obfuscate_re};
495 fill_all($self); # noop to populate -no_obfuscate
497 if (my $es = ALL($self)) {
498 require PublicInbox::Isearch;
499 $ibx->{isrch} = PublicInbox::Isearch->new($ibx, $es);
501 $self->{-by_eidx_key}->{$ibx->eidx_key} = $ibx;
505 my ($self, $name) = @_;
506 eval { require PublicInbox::ExtSearch } or return;
507 my $pfx = "extindex.$name";
508 my $d = $self->{"$pfx.topdir"} // return;
510 if (index($d, "\n") >= 0) {
511 warn "E: `$d' must not contain `\\n'\n";
514 my $es = PublicInbox::ExtSearch->new($d);
515 for my $k (qw(indexlevel indexsequentialshard)) {
516 my $v = get_1($self, "$pfx.$k") // next;
519 for my $k (qw(coderepo hide url infourl)) {
520 my $v = $self->{"$pfx.$k"} // next;
521 $es->{$k} = _array($v);
523 return unless valid_foo_name($name, 'extindex');
529 my ($self, $key, $url) = @_;
530 state $urlmatch_broken; # requires git 1.8.5
531 return if $urlmatch_broken;
532 my $file = $self->{'-f'} // default_file();
533 my $cmd = [qw/git config -z --includes --get-urlmatch/,
534 "--file=$file", $key, $url ];
535 my $fh = popen_rd($cmd);
542 $urlmatch_broken = 1 if (($? >> 8) != 1);
550 for my $mod (qw(Cpanel::JSON::XS JSON::MaybeXS JSON JSON::PP)) {
551 eval "require $mod" or next;
552 # ->ascii encodes non-ASCII to "\uXXXX"
553 $json = $mod->new->ascii(1) and last;
559 sub squote_maybe ($) {
561 if ($val =~ m{([^\w@\./,\%\+\-])}) {
562 $val =~ s/(['!])/'\\$1'/g; # '!' for csh