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);
16 sub _array ($) { ref($_[0]) eq 'ARRAY' ? $_[0] : [ $_[0] ] }
18 # returns key-value pairs of config directives in a hash
19 # if keys may be multi-value, the value is an array ref containing all values
21 my ($class, $file) = @_;
22 $file //= default_file();
24 if (ref($file) eq 'SCALAR') { # used by some tests
25 open my $fh, '<', $file or die; # PerlIO::scalar
26 $self = config_fh_parse($fh, "\n", '=');
28 $self = git_config_dump($file);
29 $self->{'-f'} = $file;
33 $self->{-by_addr} = {};
34 $self->{-by_list_id} = {};
35 $self->{-by_name} = {};
36 $self->{-by_newsgroup} = {};
37 $self->{-by_eidx_key} = {};
38 $self->{-no_obfuscate} = {};
39 $self->{-limiters} = {};
40 $self->{-code_repos} = {}; # nick => PublicInbox::Git object
41 $self->{-cgitrc_unparsed} = $self->{'publicinbox.cgitrc'};
43 if (my $no = delete $self->{'publicinbox.noobfuscate'}) {
46 foreach my $n (@$no) {
47 my @n = split(/\s+/, $n);
49 if (/\S+@\S+/) { # full address
50 $self->{-no_obfuscate}->{lc $_} = 1;
52 # allow "example.com" or "@example.com"
54 push @domains, quotemeta($_);
58 my $nod = join('|', @domains);
59 $self->{-no_obfuscate_re} = qr/(?:$nod)\z/i;
61 if (my $css = delete $self->{'publicinbox.css'}) {
62 $self->{css} = _array($css);
69 sub fill_all ($) { each_inbox($_[0], \&noop) }
71 sub _lookup_fill ($$$) {
72 my ($self, $cache, $key) = @_;
73 $self->{$cache}->{$key} // do {
75 $self->{$cache}->{$key};
80 my ($self, $recipient) = @_;
81 _lookup_fill($self, '-by_addr', lc($recipient));
85 my ($self, $list_id) = @_;
86 _lookup_fill($self, '-by_list_id', lc($list_id));
89 sub lookup_name ($$) {
90 my ($self, $name) = @_;
91 $self->{-by_name}->{$name} // _fill($self, "publicinbox.$name");
95 my ($self, $name) = @_;
96 $self->{-ei_by_name}->{$name} //= _fill_ei($self, "extindex.$name");
99 # special case for [extindex "all"]
100 sub ALL { lookup_ei($_[0], 'all') }
103 my ($self, $cb, @arg) = @_;
104 # may auto-vivify if config file is non-existent:
105 foreach my $section (@{$self->{-section_order}}) {
106 next if $section !~ m!\Apublicinbox\.([^/]+)\z!;
107 my $ibx = lookup_name($self, $1) or next;
112 sub lookup_newsgroup {
113 my ($self, $ng) = @_;
114 _lookup_fill($self, '-by_newsgroup', lc($ng));
118 my ($self, $name) = @_;
119 $self->{-limiters}->{$name} //= do {
120 require PublicInbox::Qspawn;
121 my $max = $self->{"publicinboxlimiter.$name.max"} || 1;
122 my $limiter = PublicInbox::Qspawn::Limiter->new($max);
123 $limiter->setup_rlimit($name, $self);
128 sub config_dir { $ENV{PI_DIR} // "$ENV{HOME}/.public-inbox" }
131 $ENV{PI_CONFIG} // (config_dir() . '/config');
134 sub config_fh_parse ($$$) {
135 my ($fh, $rs, $fs) = @_;
136 my (%rv, %seen, @section_order, $line, $k, $v, $section, $cur, $i);
138 while (defined($line = <$fh>)) { # perf critical with giant configs
139 $i = index($line, $fs);
140 $k = substr($line, 0, $i);
141 $v = substr($line, $i + 1, -1); # chop off $fs
142 $section = substr($k, 0, rindex($k, '.'));
143 $seen{$section} //= push(@section_order, $section);
145 if (defined($cur = $rv{$k})) {
146 if (ref($cur) eq "ARRAY") {
149 $rv{$k} = [ $cur, $v ];
155 $rv{-section_order} = \@section_order;
160 sub git_config_dump {
162 return {} unless -e $file;
163 my $cmd = [ qw(git config -z -l --includes), "--file=$file" ];
164 my $fh = popen_rd($cmd);
165 my $rv = config_fh_parse($fh, "\0", "\n");
166 close $fh or die "failed to close (@$cmd) pipe: $?";
170 sub valid_inbox_name ($) {
173 # Similar rules found in git.git/remote.c::valid_remote_nick
174 # and git.git/refs.c::check_refname_component
175 # We don't reject /\.lock\z/, however, since we don't lock refs
176 if ($name eq '' || $name =~ /\@\{/ ||
177 $name =~ /\.\./ || $name =~ m![/:\?\[\]\^~\s\f[:cntrl:]\*]! ||
178 $name =~ /\A\./ || $name =~ /\.\z/) {
182 # Note: we allow URL-unfriendly characters; users may configure
183 # non-HTTP-accessible inboxes
187 # XXX needs testing for cgit compatibility
188 # cf. cgit/scan-tree.c::add_repo
189 sub cgit_repo_merge ($$$) {
190 my ($self, $base, $repo) = @_;
191 my $path = $repo->{dir};
192 if (defined(my $se = $self->{-cgit_strict_export})) {
193 return unless -e "$path/$se";
195 return if -e "$path/noweb";
196 # this comes from the cgit config, and AFAIK cgit only allows
197 # repos to have one URL, but that's just the PATH_INFO component,
198 # not the Host: portion
199 # $repo = { url => 'foo.git', dir => '/path/to/foo.git' }
200 my $rel = $repo->{url};
201 unless (defined $rel) {
202 my $off = index($path, $base, 0);
206 $rel = substr($path, length($base) + 1);
209 $rel =~ s!/\.git\z!! or
212 $self->{-cgit_remove_suffix} and
213 $rel =~ s!/?\.git\z!!;
215 $self->{"coderepo.$rel.dir"} //= $path;
216 $self->{"coderepo.$rel.cgiturl"} //= _array($rel);
221 -d "$git_dir/objects" && -f "$git_dir/HEAD";
224 # XXX needs testing for cgit compatibility
225 sub scan_path_coderepo {
226 my ($self, $base, $path) = @_;
227 opendir(my $dh, $path) or do {
228 warn "error opening directory: $path\n";
232 if (is_git_dir($git_dir) || is_git_dir($git_dir .= '/.git')) {
233 my $repo = { dir => $git_dir };
234 cgit_repo_merge($self, $base, $repo);
237 while (defined(my $dn = readdir $dh)) {
238 next if $dn eq '.' || $dn eq '..';
239 if (index($dn, '.') == 0 && !$self->{-cgit_scan_hidden_path}) {
242 my $dir = "$path/$dn";
243 scan_path_coderepo($self, $base, $dir) if -d $dir;
247 sub scan_tree_coderepo ($$) {
248 my ($self, $path) = @_;
249 scan_path_coderepo($self, $path, $path);
252 sub scan_projects_coderepo ($$$) {
253 my ($self, $list, $path) = @_;
254 open my $fh, '<', $list or do {
255 warn "failed to open cgit projectlist=$list: $!\n";
260 scan_path_coderepo($self, $path, "$path/$_");
265 my ($self, $cgitrc, $nesting) = @_;
268 my %s = map { $_ => 1 } qw(/cgit.css /cgit.png
269 /favicon.ico /robots.txt);
270 $self->{-cgit_static} = \%s;
273 # same limit as cgit/configfile.c::parse_configfile
274 return if $nesting > 8;
276 open my $fh, '<', $cgitrc or do {
277 warn "failed to open cgitrc=$cgitrc: $!\n";
281 # FIXME: this doesn't support macro expansion via $VARS, yet
285 if (m!\Arepo\.url=(.+?)/*\z!) {
287 cgit_repo_merge($self, $repo->{dir}, $repo) if $repo;
288 $repo = { url => $nick };
289 } elsif (m!\Arepo\.path=(.+)\z!) {
293 warn "$_ without repo.url\n";
295 } elsif (m!\Ainclude=(.+)\z!) {
296 parse_cgitrc($self, $1, $nesting + 1);
297 } elsif (m!\A(scan-hidden-path|remove-suffix)=([0-9]+)\z!) {
298 my ($k, $v) = ($1, $2);
300 $self->{"-cgit_$k"} = $v;
301 } elsif (m!\A(project-list|strict-export)=(.+)\z!) {
302 my ($k, $v) = ($1, $2);
304 $self->{"-cgit_$k"} = $v;
305 } elsif (m!\Ascan-path=(.+)\z!) {
306 if (defined(my $list = $self->{-cgit_project_list})) {
307 scan_projects_coderepo($self, $list, $1);
309 scan_tree_coderepo($self, $1);
311 } elsif (m!\A(?:css|favicon|logo|repo\.logo)=(/.+)\z!) {
312 # absolute paths for static files via PublicInbox::Cgit
313 $self->{-cgit_static}->{$1} = 1;
316 cgit_repo_merge($self, $repo->{dir}, $repo) if $repo;
320 # Only git is supported at the moment, but SVN and Hg are possibilities
321 sub _fill_code_repo {
322 my ($self, $nick) = @_;
323 my $pfx = "coderepo.$nick";
325 # TODO: support gitweb and other repository viewers?
326 if (defined(my $cgitrc = delete $self->{-cgitrc_unparsed})) {
327 parse_cgitrc($self, $cgitrc, 0);
329 my $dir = $self->{"$pfx.dir"}; # aka "GIT_DIR"
330 unless (defined $dir) {
331 warn "$pfx.dir unset\n";
335 my $git = PublicInbox::Git->new($dir);
336 foreach my $t (qw(blob commit tree tag)) {
337 $git->{$t.'_url_format'} =
338 _array($self->{lc("$pfx.${t}UrlFormat")});
341 if (defined(my $cgits = $self->{"$pfx.cgiturl"})) {
342 $git->{cgit_url} = $cgits = _array($cgits);
343 $self->{"$pfx.cgiturl"} = $cgits;
345 # cgit supports "/blob/?id=%s", but it's only a plain-text
346 # display and requires an unabbreviated id=
347 foreach my $t (qw(blob commit tag)) {
348 $git->{$t.'_url_format'} //= map {
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, $pfx) = @_;
382 for my $k (qw(watch nntpserver)) {
383 my $v = $self->{"$pfx.$k"};
384 $ibx->{$k} = $v if defined $v;
386 for my $k (qw(filter inboxdir newsgroup replyto httpbackendmax feedmax
387 indexlevel indexsequentialshard)) {
388 if (defined(my $v = $self->{"$pfx.$k"})) {
389 if (ref($v) eq 'ARRAY') {
391 W: $pfx.$k has multiple values, only using `$v->[-1]'
393 $ibx->{$k} = $v->[-1];
400 # "mainrepo" is backwards compatibility:
401 my $dir = $ibx->{inboxdir} //= $self->{"$pfx.mainrepo"} // return;
402 if (index($dir, "\n") >= 0) {
403 warn "E: `$dir' must not contain `\\n'\n";
406 foreach my $k (qw(obfuscate)) {
407 my $v = $self->{"$pfx.$k"};
409 if (defined(my $bval = git_bool($v))) {
412 warn "Ignoring $pfx.$k=$v in config, not boolean\n";
415 # TODO: more arrays, we should support multi-value for
416 # more things to encourage decentralization
417 foreach my $k (qw(address altid nntpmirror coderepo hide listid url
418 infourl watchheader)) {
419 if (defined(my $v = $self->{"$pfx.$k"})) {
420 $ibx->{$k} = _array($v);
424 my $name = substr($pfx, length('publicinbox.'));
425 if (!valid_inbox_name($name)) {
426 warn "invalid inbox name: '$name'\n";
430 $ibx->{name} = $name;
431 $ibx->{-pi_cfg} = $self;
432 $ibx = PublicInbox::Inbox->new($ibx);
433 foreach (@{$ibx->{address}}) {
434 my $lc_addr = lc($_);
435 $self->{-by_addr}->{$lc_addr} = $ibx;
436 $self->{-no_obfuscate}->{$lc_addr} = 1;
438 if (my $listids = $ibx->{listid}) {
439 # RFC2919 section 6 stipulates "case insensitive equality"
440 foreach my $list_id (@$listids) {
441 $self->{-by_list_id}->{lc($list_id)} = $ibx;
444 if (defined(my $ngname = $ibx->{newsgroup})) {
446 delete $ibx->{newsgroup};
447 warn 'multiple newsgroups not supported: '.
448 join(', ', @$ngname). "\n";
449 # Newsgroup name needs to be compatible with RFC 3977
450 # wildmat-exact and RFC 3501 (IMAP) ATOM-CHAR.
451 # Leave out a few chars likely to cause problems or conflicts:
452 # '|', '<', '>', ';', '#', '$', '&',
453 } elsif ($ngname =~ m![^A-Za-z0-9/_\.\-\~\@\+\=:]! ||
455 delete $ibx->{newsgroup};
456 warn "newsgroup name invalid: `$ngname'\n";
458 # PublicInbox::NNTPD does stricter ->nntp_usable
459 # checks, keep this lean for startup speed
460 $self->{-by_newsgroup}->{$ngname} = $ibx;
463 unless (defined $ibx->{newsgroup}) { # for ->eidx_key
464 my $abs = rel2abs_collapsed($dir);
466 warn "W: `$dir' canonicalized to `$abs'\n";
467 $ibx->{inboxdir} = $abs;
470 $self->{-by_name}->{$name} = $ibx;
471 if ($ibx->{obfuscate}) {
472 $ibx->{-no_obfuscate} = $self->{-no_obfuscate};
473 $ibx->{-no_obfuscate_re} = $self->{-no_obfuscate_re};
474 fill_all($self); # noop to populate -no_obfuscate
477 if (my $ibx_code_repos = $ibx->{coderepo}) {
478 my $code_repos = $self->{-code_repos};
479 my $repo_objs = $ibx->{-repo_objs} = [];
480 foreach my $nick (@$ibx_code_repos) {
481 my @parts = split(m!/!, $nick);
483 $valid += valid_inbox_name($_) foreach (@parts);
484 $valid == scalar(@parts) or next;
486 my $repo = $code_repos->{$nick} //=
487 _fill_code_repo($self, $nick);
488 push @$repo_objs, $repo if $repo;
491 if (my $es = ALL($self)) {
492 require PublicInbox::Isearch;
493 $ibx->{isrch} = PublicInbox::Isearch->new($ibx, $es);
495 $self->{-by_eidx_key}->{$ibx->eidx_key} = $ibx;
499 my ($self, $pfx) = @_;
500 eval { require PublicInbox::ExtSearch } or return;
501 my $d = $self->{"$pfx.topdir"};
502 defined($d) && -d $d ? PublicInbox::ExtSearch->new($d) : undef;
506 my ($self, $key, $url) = @_;
507 state $urlmatch_broken; # requires git 1.8.5
508 return if $urlmatch_broken;
509 my $file = $self->{'-f'} // default_file();
510 my $cmd = [qw/git config -z --includes --get-urlmatch/,
511 "--file=$file", $key, $url ];
512 my $fh = popen_rd($cmd);
519 $urlmatch_broken = 1 if (($? >> 8) != 1);
527 for my $mod (qw(Cpanel::JSON::XS JSON::MaybeXS JSON JSON::PP)) {
528 eval "require $mod" or next;
529 # ->ascii encodes non-ASCII to "\uXXXX"
530 $json = $mod->new->ascii(1) and last;