1 # Copyright (C) 2014-2020 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);
32 $self->{-by_addr} = {};
33 $self->{-by_list_id} = {};
34 $self->{-by_name} = {};
35 $self->{-by_newsgroup} = {};
36 $self->{-no_obfuscate} = {};
37 $self->{-limiters} = {};
38 $self->{-code_repos} = {}; # nick => PublicInbox::Git object
39 $self->{-cgitrc_unparsed} = $self->{'publicinbox.cgitrc'};
41 if (my $no = delete $self->{'publicinbox.noobfuscate'}) {
44 foreach my $n (@$no) {
45 my @n = split(/\s+/, $n);
47 if (/\S+@\S+/) { # full address
48 $self->{-no_obfuscate}->{lc $_} = 1;
50 # allow "example.com" or "@example.com"
52 push @domains, quotemeta($_);
56 my $nod = join('|', @domains);
57 $self->{-no_obfuscate_re} = qr/(?:$nod)\z/i;
59 if (my $css = delete $self->{'publicinbox.css'}) {
60 $self->{css} = _array($css);
67 sub fill_all ($) { each_inbox($_[0], \&noop) }
69 sub _lookup_fill ($$$) {
70 my ($self, $cache, $key) = @_;
71 $self->{$cache}->{$key} // do {
73 $self->{$cache}->{$key};
78 my ($self, $recipient) = @_;
79 _lookup_fill($self, '-by_addr', lc($recipient));
83 my ($self, $list_id) = @_;
84 _lookup_fill($self, '-by_list_id', lc($list_id));
87 sub lookup_name ($$) {
88 my ($self, $name) = @_;
89 $self->{-by_name}->{$name} // _fill($self, "publicinbox.$name");
93 my ($self, $name) = @_;
94 $self->{-ei_by_name}->{$name} //= _fill_ei($self, "extindex.$name");
98 my ($self, $cb, @arg) = @_;
99 # may auto-vivify if config file is non-existent:
100 foreach my $section (@{$self->{-section_order}}) {
101 next if $section !~ m!\Apublicinbox\.([^/]+)\z!;
102 my $ibx = lookup_name($self, $1) or next;
107 sub lookup_newsgroup {
108 my ($self, $ng) = @_;
109 _lookup_fill($self, '-by_newsgroup', lc($ng));
113 my ($self, $name) = @_;
114 $self->{-limiters}->{$name} //= do {
115 require PublicInbox::Qspawn;
116 my $max = $self->{"publicinboxlimiter.$name.max"} || 1;
117 my $limiter = PublicInbox::Qspawn::Limiter->new($max);
118 $limiter->setup_rlimit($name, $self);
123 sub config_dir { $ENV{PI_DIR} // "$ENV{HOME}/.public-inbox" }
126 $ENV{PI_CONFIG} // (config_dir() . '/config');
129 sub config_fh_parse ($$$) {
130 my ($fh, $rs, $fs) = @_;
132 my (%section_seen, @section_order);
134 while (defined(my $line = <$fh>)) {
136 my ($k, $v) = split($fs, $line, 2);
137 my ($section) = ($k =~ /\A(\S+)\.[^\.]+\z/);
138 unless (defined $section_seen{$section}) {
139 $section_seen{$section} = 1;
140 push @section_order, $section;
145 if (ref($cur) eq "ARRAY") {
148 $rv{$k} = [ $cur, $v ];
154 $rv{-section_order} = \@section_order;
159 sub git_config_dump {
161 return {} unless -e $file;
162 my @cmd = (qw/git config -z -l --includes/, "--file=$file");
163 my $cmd = join(' ', @cmd);
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) {
369 my ($self, $pfx) = @_;
372 for my $k (qw(watch nntpserver)) {
373 my $v = $self->{"$pfx.$k"};
374 $ibx->{$k} = $v if defined $v;
376 for my $k (qw(filter inboxdir newsgroup replyto httpbackendmax feedmax
377 indexlevel indexsequentialshard)) {
378 if (defined(my $v = $self->{"$pfx.$k"})) {
379 if (ref($v) eq 'ARRAY') {
381 W: $pfx.$k has multiple values, only using `$v->[-1]'
383 $ibx->{$k} = $v->[-1];
390 # backwards compatibility:
391 $ibx->{inboxdir} //= $self->{"$pfx.mainrepo"};
392 if (($ibx->{inboxdir} // '') =~ /\n/s) {
393 warn "E: `$ibx->{inboxdir}' must not contain `\\n'\n";
396 foreach my $k (qw(obfuscate)) {
397 my $v = $self->{"$pfx.$k"};
399 if (defined(my $bval = git_bool($v))) {
402 warn "Ignoring $pfx.$k=$v in config, not boolean\n";
405 # TODO: more arrays, we should support multi-value for
406 # more things to encourage decentralization
407 foreach my $k (qw(address altid nntpmirror coderepo hide listid url
408 infourl watchheader)) {
409 if (defined(my $v = $self->{"$pfx.$k"})) {
410 $ibx->{$k} = _array($v);
414 return unless defined($ibx->{inboxdir});
416 $name =~ s/\Apublicinbox\.//;
418 if (!valid_inbox_name($name)) {
419 warn "invalid inbox name: '$name'\n";
423 $ibx->{name} = $name;
424 $ibx->{-pi_config} = $self;
425 $ibx = PublicInbox::Inbox->new($ibx);
426 foreach (@{$ibx->{address}}) {
427 my $lc_addr = lc($_);
428 $self->{-by_addr}->{$lc_addr} = $ibx;
429 $self->{-no_obfuscate}->{$lc_addr} = 1;
431 if (my $listids = $ibx->{listid}) {
432 # RFC2919 section 6 stipulates "case insensitive equality"
433 foreach my $list_id (@$listids) {
434 $self->{-by_list_id}->{lc($list_id)} = $ibx;
437 if (my $ng = $ibx->{newsgroup}) {
438 $self->{-by_newsgroup}->{$ng} = $ibx;
440 $self->{-by_name}->{$name} = $ibx;
441 if ($ibx->{obfuscate}) {
442 $ibx->{-no_obfuscate} = $self->{-no_obfuscate};
443 $ibx->{-no_obfuscate_re} = $self->{-no_obfuscate_re};
444 fill_all($self); # noop to populate -no_obfuscate
447 if (my $ibx_code_repos = $ibx->{coderepo}) {
448 my $code_repos = $self->{-code_repos};
449 my $repo_objs = $ibx->{-repo_objs} = [];
450 foreach my $nick (@$ibx_code_repos) {
451 my @parts = split(m!/!, $nick);
453 $valid += valid_inbox_name($_) foreach (@parts);
454 $valid == scalar(@parts) or next;
456 my $repo = $code_repos->{$nick} //=
457 _fill_code_repo($self, $nick);
458 push @$repo_objs, $repo if $repo;
466 my ($self, $pfx) = @_;
467 require PublicInbox::ExtSearch;
468 my $d = $self->{"$pfx.topdir"};
469 defined($d) && -d $d ? PublicInbox::ExtSearch->new($d) : undef;
473 my ($self, $key, $url) = @_;
474 state $urlmatch_broken; # requires git 1.8.5
475 return if $urlmatch_broken;
476 my $file = default_file();
477 my $cmd = [qw/git config -z --includes --get-urlmatch/,
478 "--file=$file", $key, $url ];
479 my $fh = popen_rd($cmd);
486 $urlmatch_broken = 1 if (($? >> 8) != 1);
494 for my $mod (qw(Cpanel::JSON::XS JSON::MaybeXS JSON JSON::PP)) {
495 eval "require $mod" or next;
496 # ->ascii encodes non-ASCII to "\uXXXX"
497 $json = $mod->new->ascii(1) and last;