]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Config.pm
config: use '-f' key to store config file pathname
[public-inbox.git] / lib / PublicInbox / Config.pm
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>
3 #
4 # Used throughout the project for reading configuration
5 #
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
9
10 package PublicInbox::Config;
11 use strict;
12 use v5.10.1;
13 use PublicInbox::Inbox;
14 use PublicInbox::Spawn qw(popen_rd);
15
16 sub _array ($) { ref($_[0]) eq 'ARRAY' ? $_[0] : [ $_[0] ] }
17
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
20 sub new {
21         my ($class, $file) = @_;
22         $file //= default_file();
23         my $self;
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", '=');
27         } else {
28                 $self = git_config_dump($file);
29                 $self->{'-f'} = $file;
30         }
31         bless $self, $class;
32         # caches
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'};
42
43         if (my $no = delete $self->{'publicinbox.noobfuscate'}) {
44                 $no = _array($no);
45                 my @domains;
46                 foreach my $n (@$no) {
47                         my @n = split(/\s+/, $n);
48                         foreach (@n) {
49                                 if (/\S+@\S+/) { # full address
50                                         $self->{-no_obfuscate}->{lc $_} = 1;
51                                 } else {
52                                         # allow "example.com" or "@example.com"
53                                         s/\A@//;
54                                         push @domains, quotemeta($_);
55                                 }
56                         }
57                 }
58                 my $nod = join('|', @domains);
59                 $self->{-no_obfuscate_re} = qr/(?:$nod)\z/i;
60         }
61         if (my $css = delete $self->{'publicinbox.css'}) {
62                 $self->{css} = _array($css);
63         }
64
65         $self;
66 }
67
68 sub noop {}
69 sub fill_all ($) { each_inbox($_[0], \&noop) }
70
71 sub _lookup_fill ($$$) {
72         my ($self, $cache, $key) = @_;
73         $self->{$cache}->{$key} // do {
74                 fill_all($self);
75                 $self->{$cache}->{$key};
76         }
77 }
78
79 sub lookup {
80         my ($self, $recipient) = @_;
81         _lookup_fill($self, '-by_addr', lc($recipient));
82 }
83
84 sub lookup_list_id {
85         my ($self, $list_id) = @_;
86         _lookup_fill($self, '-by_list_id', lc($list_id));
87 }
88
89 sub lookup_name ($$) {
90         my ($self, $name) = @_;
91         $self->{-by_name}->{$name} // _fill($self, "publicinbox.$name");
92 }
93
94 sub lookup_ei {
95         my ($self, $name) = @_;
96         $self->{-ei_by_name}->{$name} //= _fill_ei($self, "extindex.$name");
97 }
98
99 # special case for [extindex "all"]
100 sub ALL { lookup_ei($_[0], 'all') }
101
102 sub each_inbox {
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;
108                 $cb->($ibx, @arg);
109         }
110 }
111
112 sub lookup_newsgroup {
113         my ($self, $ng) = @_;
114         _lookup_fill($self, '-by_newsgroup', lc($ng));
115 }
116
117 sub limiter {
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);
124                 $limiter;
125         };
126 }
127
128 sub config_dir { $ENV{PI_DIR} // "$ENV{HOME}/.public-inbox" }
129
130 sub default_file {
131         $ENV{PI_CONFIG} // (config_dir() . '/config');
132 }
133
134 sub config_fh_parse ($$$) {
135         my ($fh, $rs, $fs) = @_;
136         my (%rv, %seen, @section_order, $line, $k, $v, $section, $cur, $i);
137         local $/ = $rs;
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);
144
145                 if (defined($cur = $rv{$k})) {
146                         if (ref($cur) eq "ARRAY") {
147                                 push @$cur, $v;
148                         } else {
149                                 $rv{$k} = [ $cur, $v ];
150                         }
151                 } else {
152                         $rv{$k} = $v;
153                 }
154         }
155         $rv{-section_order} = \@section_order;
156
157         \%rv;
158 }
159
160 sub git_config_dump {
161         my ($file) = @_;
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: $?";
167         $rv;
168 }
169
170 sub valid_inbox_name ($) {
171         my ($name) = @_;
172
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/) {
179                 return 0;
180         }
181
182         # Note: we allow URL-unfriendly characters; users may configure
183         # non-HTTP-accessible inboxes
184         1;
185 }
186
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";
194         }
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);
203                 if ($off != 0) {
204                         $rel = $path;
205                 } else {
206                         $rel = substr($path, length($base) + 1);
207                 }
208
209                 $rel =~ s!/\.git\z!! or
210                         $rel =~ s!/+\z!!;
211
212                 $self->{-cgit_remove_suffix} and
213                         $rel =~ s!/?\.git\z!!;
214         }
215         $self->{"coderepo.$rel.dir"} //= $path;
216         $self->{"coderepo.$rel.cgiturl"} //= _array($rel);
217 }
218
219 sub is_git_dir ($) {
220         my ($git_dir) = @_;
221         -d "$git_dir/objects" && -f "$git_dir/HEAD";
222 }
223
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";
229                 return
230         };
231         my $git_dir = $path;
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);
235                 return;
236         }
237         while (defined(my $dn = readdir $dh)) {
238                 next if $dn eq '.' || $dn eq '..';
239                 if (index($dn, '.') == 0 && !$self->{-cgit_scan_hidden_path}) {
240                         next;
241                 }
242                 my $dir = "$path/$dn";
243                 scan_path_coderepo($self, $base, $dir) if -d $dir;
244         }
245 }
246
247 sub scan_tree_coderepo ($$) {
248         my ($self, $path) = @_;
249         scan_path_coderepo($self, $path, $path);
250 }
251
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";
256                 return;
257         };
258         while (<$fh>) {
259                 chomp;
260                 scan_path_coderepo($self, $path, "$path/$_");
261         }
262 }
263
264 sub parse_cgitrc {
265         my ($self, $cgitrc, $nesting) = @_;
266         if ($nesting == 0) {
267                 # defaults:
268                 my %s = map { $_ => 1 } qw(/cgit.css /cgit.png
269                                                 /favicon.ico /robots.txt);
270                 $self->{-cgit_static} = \%s;
271         }
272
273         # same limit as cgit/configfile.c::parse_configfile
274         return if $nesting > 8;
275
276         open my $fh, '<', $cgitrc or do {
277                 warn "failed to open cgitrc=$cgitrc: $!\n";
278                 return;
279         };
280
281         # FIXME: this doesn't support macro expansion via $VARS, yet
282         my $repo;
283         while (<$fh>) {
284                 chomp;
285                 if (m!\Arepo\.url=(.+?)/*\z!) {
286                         my $nick = $1;
287                         cgit_repo_merge($self, $repo->{dir}, $repo) if $repo;
288                         $repo = { url => $nick };
289                 } elsif (m!\Arepo\.path=(.+)\z!) {
290                         if (defined $repo) {
291                                 $repo->{dir} = $1;
292                         } else {
293                                 warn "$_ without repo.url\n";
294                         }
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);
299                         $k =~ tr/-/_/;
300                         $self->{"-cgit_$k"} = $v;
301                 } elsif (m!\A(project-list|strict-export)=(.+)\z!) {
302                         my ($k, $v) = ($1, $2);
303                         $k =~ tr/-/_/;
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);
308                         } else {
309                                 scan_tree_coderepo($self, $1);
310                         }
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;
314                 }
315         }
316         cgit_repo_merge($self, $repo->{dir}, $repo) if $repo;
317 }
318
319 # parse a code 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";
324
325         # TODO: support gitweb and other repository viewers?
326         if (defined(my $cgitrc = delete $self->{-cgitrc_unparsed})) {
327                 parse_cgitrc($self, $cgitrc, 0);
328         }
329         my $dir = $self->{"$pfx.dir"}; # aka "GIT_DIR"
330         unless (defined $dir) {
331                 warn "$pfx.dir unset\n";
332                 return;
333         }
334
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")});
339         }
340
341         if (defined(my $cgits = $self->{"$pfx.cgiturl"})) {
342                 $git->{cgit_url} = $cgits = _array($cgits);
343                 $self->{"$pfx.cgiturl"} = $cgits;
344
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 {
349                                 "$_/$t/?id=%s"
350                         } @$cgits;
351                 }
352         }
353
354         $git;
355 }
356
357 sub git_bool {
358         my ($val) = $_[-1]; # $_[0] may be $self, or $val
359         if ($val =~ /\A(?:false|no|off|[\-\+]?(?:0x)?0+)\z/i) {
360                 0;
361         } elsif ($val =~ /\A(?:true|yes|on|[\-\+]?(?:0x)?[0-9]+)\z/i) {
362                 1;
363         } else {
364                 undef;
365         }
366 }
367
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 {
371         require File::Spec;
372         my $p = File::Spec->rel2abs($_[-1]);
373         return $p if substr($p, -3, 3) ne '/..' && index($p, '/../') < 0;
374         require Cwd;
375         Cwd::abs_path($p);
376 }
377
378 sub _fill {
379         my ($self, $pfx) = @_;
380         my $ibx = {};
381
382         for my $k (qw(watch nntpserver)) {
383                 my $v = $self->{"$pfx.$k"};
384                 $ibx->{$k} = $v if defined $v;
385         }
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') {
390                                 warn <<EOF;
391 W: $pfx.$k has multiple values, only using `$v->[-1]'
392 EOF
393                                 $ibx->{$k} = $v->[-1];
394                         } else {
395                                 $ibx->{$k} = $v;
396                         }
397                 }
398         }
399
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";
404                 return;
405         }
406         foreach my $k (qw(obfuscate)) {
407                 my $v = $self->{"$pfx.$k"};
408                 defined $v or next;
409                 if (defined(my $bval = git_bool($v))) {
410                         $ibx->{$k} = $bval;
411                 } else {
412                         warn "Ignoring $pfx.$k=$v in config, not boolean\n";
413                 }
414         }
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);
421                 }
422         }
423
424         my $name = substr($pfx, length('publicinbox.'));
425         if (!valid_inbox_name($name)) {
426                 warn "invalid inbox name: '$name'\n";
427                 return;
428         }
429
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;
437         }
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;
442                 }
443         }
444         if (defined(my $ngname = $ibx->{newsgroup})) {
445                 if (ref($ngname)) {
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/_\.\-\~\@\+\=:]! ||
454                                 $ngname eq '') {
455                         delete $ibx->{newsgroup};
456                         warn "newsgroup name invalid: `$ngname'\n";
457                 } else {
458                         # PublicInbox::NNTPD does stricter ->nntp_usable
459                         # checks, keep this lean for startup speed
460                         $self->{-by_newsgroup}->{$ngname} = $ibx;
461                 }
462         }
463         unless (defined $ibx->{newsgroup}) { # for ->eidx_key
464                 my $abs = rel2abs_collapsed($dir);
465                 if ($abs ne $dir) {
466                         warn "W: `$dir' canonicalized to `$abs'\n";
467                         $ibx->{inboxdir} = $abs;
468                 }
469         }
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
475         }
476
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);
482                         my $valid = 0;
483                         $valid += valid_inbox_name($_) foreach (@parts);
484                         $valid == scalar(@parts) or next;
485
486                         my $repo = $code_repos->{$nick} //=
487                                                 _fill_code_repo($self, $nick);
488                         push @$repo_objs, $repo if $repo;
489                 }
490         }
491         if (my $es = ALL($self)) {
492                 require PublicInbox::Isearch;
493                 $ibx->{isrch} = PublicInbox::Isearch->new($ibx, $es);
494         }
495         $self->{-by_eidx_key}->{$ibx->eidx_key} = $ibx;
496 }
497
498 sub _fill_ei ($$) {
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;
503 }
504
505 sub urlmatch {
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);
513         local $/ = "\0";
514         my $val = <$fh>;
515         if (close($fh)) {
516                 chomp($val);
517                 $val;
518         } else {
519                 $urlmatch_broken = 1 if (($? >> 8) != 1);
520                 undef;
521         }
522 }
523
524 sub json {
525         state $json;
526         $json //= do {
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;
531                 }
532                 $json;
533         };
534 }
535
536 1;