]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Config.pm
config: config_fh_parse: micro-optimize
[public-inbox.git] / lib / PublicInbox / Config.pm
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>
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         }
30         bless $self, $class;
31         # caches
32         $self->{-by_addr} = {};
33         $self->{-by_list_id} = {};
34         $self->{-by_name} = {};
35         $self->{-by_newsgroup} = {};
36         $self->{-by_eidx_key} = {};
37         $self->{-no_obfuscate} = {};
38         $self->{-limiters} = {};
39         $self->{-code_repos} = {}; # nick => PublicInbox::Git object
40         $self->{-cgitrc_unparsed} = $self->{'publicinbox.cgitrc'};
41
42         if (my $no = delete $self->{'publicinbox.noobfuscate'}) {
43                 $no = _array($no);
44                 my @domains;
45                 foreach my $n (@$no) {
46                         my @n = split(/\s+/, $n);
47                         foreach (@n) {
48                                 if (/\S+@\S+/) { # full address
49                                         $self->{-no_obfuscate}->{lc $_} = 1;
50                                 } else {
51                                         # allow "example.com" or "@example.com"
52                                         s/\A@//;
53                                         push @domains, quotemeta($_);
54                                 }
55                         }
56                 }
57                 my $nod = join('|', @domains);
58                 $self->{-no_obfuscate_re} = qr/(?:$nod)\z/i;
59         }
60         if (my $css = delete $self->{'publicinbox.css'}) {
61                 $self->{css} = _array($css);
62         }
63
64         $self;
65 }
66
67 sub noop {}
68 sub fill_all ($) { each_inbox($_[0], \&noop) }
69
70 sub _lookup_fill ($$$) {
71         my ($self, $cache, $key) = @_;
72         $self->{$cache}->{$key} // do {
73                 fill_all($self);
74                 $self->{$cache}->{$key};
75         }
76 }
77
78 sub lookup {
79         my ($self, $recipient) = @_;
80         _lookup_fill($self, '-by_addr', lc($recipient));
81 }
82
83 sub lookup_list_id {
84         my ($self, $list_id) = @_;
85         _lookup_fill($self, '-by_list_id', lc($list_id));
86 }
87
88 sub lookup_name ($$) {
89         my ($self, $name) = @_;
90         $self->{-by_name}->{$name} // _fill($self, "publicinbox.$name");
91 }
92
93 sub lookup_ei {
94         my ($self, $name) = @_;
95         $self->{-ei_by_name}->{$name} //= _fill_ei($self, "extindex.$name");
96 }
97
98 # special case for [extindex "all"]
99 sub ALL { lookup_ei($_[0], 'all') }
100
101 sub each_inbox {
102         my ($self, $cb, @arg) = @_;
103         # may auto-vivify if config file is non-existent:
104         foreach my $section (@{$self->{-section_order}}) {
105                 next if $section !~ m!\Apublicinbox\.([^/]+)\z!;
106                 my $ibx = lookup_name($self, $1) or next;
107                 $cb->($ibx, @arg);
108         }
109 }
110
111 sub lookup_newsgroup {
112         my ($self, $ng) = @_;
113         _lookup_fill($self, '-by_newsgroup', lc($ng));
114 }
115
116 sub limiter {
117         my ($self, $name) = @_;
118         $self->{-limiters}->{$name} //= do {
119                 require PublicInbox::Qspawn;
120                 my $max = $self->{"publicinboxlimiter.$name.max"} || 1;
121                 my $limiter = PublicInbox::Qspawn::Limiter->new($max);
122                 $limiter->setup_rlimit($name, $self);
123                 $limiter;
124         };
125 }
126
127 sub config_dir { $ENV{PI_DIR} // "$ENV{HOME}/.public-inbox" }
128
129 sub default_file {
130         $ENV{PI_CONFIG} // (config_dir() . '/config');
131 }
132
133 sub config_fh_parse ($$$) {
134         my ($fh, $rs, $fs) = @_;
135         my (%rv, %section_seen, @section_order, $line, $k, $v, $section, $cur);
136         local $/ = $rs;
137         while (defined($line = <$fh>)) { # performance critical with giant configs
138                 chomp $line;
139                 ($k, $v) = split($fs, $line, 2);
140                 $section = substr($k, 0, rindex($k, '.'));
141                 $section_seen{$section} //= push(@section_order, $section);
142
143                 if (defined($cur = $rv{$k})) {
144                         if (ref($cur) eq "ARRAY") {
145                                 push @$cur, $v;
146                         } else {
147                                 $rv{$k} = [ $cur, $v ];
148                         }
149                 } else {
150                         $rv{$k} = $v;
151                 }
152         }
153         $rv{-section_order} = \@section_order;
154
155         \%rv;
156 }
157
158 sub git_config_dump {
159         my ($file) = @_;
160         return {} unless -e $file;
161         my $cmd = [ qw(git config -z -l --includes), "--file=$file" ];
162         my $fh = popen_rd($cmd);
163         my $rv = config_fh_parse($fh, "\0", qr/\n/);
164         close $fh or die "failed to close (@$cmd) pipe: $?";
165         $rv;
166 }
167
168 sub valid_inbox_name ($) {
169         my ($name) = @_;
170
171         # Similar rules found in git.git/remote.c::valid_remote_nick
172         # and git.git/refs.c::check_refname_component
173         # We don't reject /\.lock\z/, however, since we don't lock refs
174         if ($name eq '' || $name =~ /\@\{/ ||
175             $name =~ /\.\./ || $name =~ m![/:\?\[\]\^~\s\f[:cntrl:]\*]! ||
176             $name =~ /\A\./ || $name =~ /\.\z/) {
177                 return 0;
178         }
179
180         # Note: we allow URL-unfriendly characters; users may configure
181         # non-HTTP-accessible inboxes
182         1;
183 }
184
185 # XXX needs testing for cgit compatibility
186 # cf. cgit/scan-tree.c::add_repo
187 sub cgit_repo_merge ($$$) {
188         my ($self, $base, $repo) = @_;
189         my $path = $repo->{dir};
190         if (defined(my $se = $self->{-cgit_strict_export})) {
191                 return unless -e "$path/$se";
192         }
193         return if -e "$path/noweb";
194         # this comes from the cgit config, and AFAIK cgit only allows
195         # repos to have one URL, but that's just the PATH_INFO component,
196         # not the Host: portion
197         # $repo = { url => 'foo.git', dir => '/path/to/foo.git' }
198         my $rel = $repo->{url};
199         unless (defined $rel) {
200                 my $off = index($path, $base, 0);
201                 if ($off != 0) {
202                         $rel = $path;
203                 } else {
204                         $rel = substr($path, length($base) + 1);
205                 }
206
207                 $rel =~ s!/\.git\z!! or
208                         $rel =~ s!/+\z!!;
209
210                 $self->{-cgit_remove_suffix} and
211                         $rel =~ s!/?\.git\z!!;
212         }
213         $self->{"coderepo.$rel.dir"} //= $path;
214         $self->{"coderepo.$rel.cgiturl"} //= _array($rel);
215 }
216
217 sub is_git_dir ($) {
218         my ($git_dir) = @_;
219         -d "$git_dir/objects" && -f "$git_dir/HEAD";
220 }
221
222 # XXX needs testing for cgit compatibility
223 sub scan_path_coderepo {
224         my ($self, $base, $path) = @_;
225         opendir(my $dh, $path) or do {
226                 warn "error opening directory: $path\n";
227                 return
228         };
229         my $git_dir = $path;
230         if (is_git_dir($git_dir) || is_git_dir($git_dir .= '/.git')) {
231                 my $repo = { dir => $git_dir };
232                 cgit_repo_merge($self, $base, $repo);
233                 return;
234         }
235         while (defined(my $dn = readdir $dh)) {
236                 next if $dn eq '.' || $dn eq '..';
237                 if (index($dn, '.') == 0 && !$self->{-cgit_scan_hidden_path}) {
238                         next;
239                 }
240                 my $dir = "$path/$dn";
241                 scan_path_coderepo($self, $base, $dir) if -d $dir;
242         }
243 }
244
245 sub scan_tree_coderepo ($$) {
246         my ($self, $path) = @_;
247         scan_path_coderepo($self, $path, $path);
248 }
249
250 sub scan_projects_coderepo ($$$) {
251         my ($self, $list, $path) = @_;
252         open my $fh, '<', $list or do {
253                 warn "failed to open cgit projectlist=$list: $!\n";
254                 return;
255         };
256         while (<$fh>) {
257                 chomp;
258                 scan_path_coderepo($self, $path, "$path/$_");
259         }
260 }
261
262 sub parse_cgitrc {
263         my ($self, $cgitrc, $nesting) = @_;
264         if ($nesting == 0) {
265                 # defaults:
266                 my %s = map { $_ => 1 } qw(/cgit.css /cgit.png
267                                                 /favicon.ico /robots.txt);
268                 $self->{-cgit_static} = \%s;
269         }
270
271         # same limit as cgit/configfile.c::parse_configfile
272         return if $nesting > 8;
273
274         open my $fh, '<', $cgitrc or do {
275                 warn "failed to open cgitrc=$cgitrc: $!\n";
276                 return;
277         };
278
279         # FIXME: this doesn't support macro expansion via $VARS, yet
280         my $repo;
281         while (<$fh>) {
282                 chomp;
283                 if (m!\Arepo\.url=(.+?)/*\z!) {
284                         my $nick = $1;
285                         cgit_repo_merge($self, $repo->{dir}, $repo) if $repo;
286                         $repo = { url => $nick };
287                 } elsif (m!\Arepo\.path=(.+)\z!) {
288                         if (defined $repo) {
289                                 $repo->{dir} = $1;
290                         } else {
291                                 warn "$_ without repo.url\n";
292                         }
293                 } elsif (m!\Ainclude=(.+)\z!) {
294                         parse_cgitrc($self, $1, $nesting + 1);
295                 } elsif (m!\A(scan-hidden-path|remove-suffix)=([0-9]+)\z!) {
296                         my ($k, $v) = ($1, $2);
297                         $k =~ tr/-/_/;
298                         $self->{"-cgit_$k"} = $v;
299                 } elsif (m!\A(project-list|strict-export)=(.+)\z!) {
300                         my ($k, $v) = ($1, $2);
301                         $k =~ tr/-/_/;
302                         $self->{"-cgit_$k"} = $v;
303                 } elsif (m!\Ascan-path=(.+)\z!) {
304                         if (defined(my $list = $self->{-cgit_project_list})) {
305                                 scan_projects_coderepo($self, $list, $1);
306                         } else {
307                                 scan_tree_coderepo($self, $1);
308                         }
309                 } elsif (m!\A(?:css|favicon|logo|repo\.logo)=(/.+)\z!) {
310                         # absolute paths for static files via PublicInbox::Cgit
311                         $self->{-cgit_static}->{$1} = 1;
312                 }
313         }
314         cgit_repo_merge($self, $repo->{dir}, $repo) if $repo;
315 }
316
317 # parse a code repo
318 # Only git is supported at the moment, but SVN and Hg are possibilities
319 sub _fill_code_repo {
320         my ($self, $nick) = @_;
321         my $pfx = "coderepo.$nick";
322
323         # TODO: support gitweb and other repository viewers?
324         if (defined(my $cgitrc = delete $self->{-cgitrc_unparsed})) {
325                 parse_cgitrc($self, $cgitrc, 0);
326         }
327         my $dir = $self->{"$pfx.dir"}; # aka "GIT_DIR"
328         unless (defined $dir) {
329                 warn "$pfx.dir unset\n";
330                 return;
331         }
332
333         my $git = PublicInbox::Git->new($dir);
334         foreach my $t (qw(blob commit tree tag)) {
335                 $git->{$t.'_url_format'} =
336                                 _array($self->{lc("$pfx.${t}UrlFormat")});
337         }
338
339         if (defined(my $cgits = $self->{"$pfx.cgiturl"})) {
340                 $git->{cgit_url} = $cgits = _array($cgits);
341                 $self->{"$pfx.cgiturl"} = $cgits;
342
343                 # cgit supports "/blob/?id=%s", but it's only a plain-text
344                 # display and requires an unabbreviated id=
345                 foreach my $t (qw(blob commit tag)) {
346                         $git->{$t.'_url_format'} //= map {
347                                 "$_/$t/?id=%s"
348                         } @$cgits;
349                 }
350         }
351
352         $git;
353 }
354
355 sub git_bool {
356         my ($val) = $_[-1]; # $_[0] may be $self, or $val
357         if ($val =~ /\A(?:false|no|off|[\-\+]?(?:0x)?0+)\z/i) {
358                 0;
359         } elsif ($val =~ /\A(?:true|yes|on|[\-\+]?(?:0x)?[0-9]+)\z/i) {
360                 1;
361         } else {
362                 undef;
363         }
364 }
365
366 # abs_path resolves symlinks, so we want to avoid it if rel2abs
367 # is sufficient and doesn't leave "/.." or "/../"
368 sub rel2abs_collapsed {
369         require File::Spec;
370         my $p = File::Spec->rel2abs($_[-1]);
371         return $p if substr($p, -3, 3) ne '/..' && index($p, '/../') < 0;
372         require Cwd;
373         Cwd::abs_path($p);
374 }
375
376 sub _fill {
377         my ($self, $pfx) = @_;
378         my $ibx = {};
379
380         for my $k (qw(watch nntpserver)) {
381                 my $v = $self->{"$pfx.$k"};
382                 $ibx->{$k} = $v if defined $v;
383         }
384         for my $k (qw(filter inboxdir newsgroup replyto httpbackendmax feedmax
385                         indexlevel indexsequentialshard)) {
386                 if (defined(my $v = $self->{"$pfx.$k"})) {
387                         if (ref($v) eq 'ARRAY') {
388                                 warn <<EOF;
389 W: $pfx.$k has multiple values, only using `$v->[-1]'
390 EOF
391                                 $ibx->{$k} = $v->[-1];
392                         } else {
393                                 $ibx->{$k} = $v;
394                         }
395                 }
396         }
397
398         # "mainrepo" is backwards compatibility:
399         my $dir = $ibx->{inboxdir} //= $self->{"$pfx.mainrepo"} // return;
400         if (index($dir, "\n") >= 0) {
401                 warn "E: `$dir' must not contain `\\n'\n";
402                 return;
403         }
404         foreach my $k (qw(obfuscate)) {
405                 my $v = $self->{"$pfx.$k"};
406                 defined $v or next;
407                 if (defined(my $bval = git_bool($v))) {
408                         $ibx->{$k} = $bval;
409                 } else {
410                         warn "Ignoring $pfx.$k=$v in config, not boolean\n";
411                 }
412         }
413         # TODO: more arrays, we should support multi-value for
414         # more things to encourage decentralization
415         foreach my $k (qw(address altid nntpmirror coderepo hide listid url
416                         infourl watchheader)) {
417                 if (defined(my $v = $self->{"$pfx.$k"})) {
418                         $ibx->{$k} = _array($v);
419                 }
420         }
421
422         my $name = substr($pfx, length('publicinbox.'));
423         if (!valid_inbox_name($name)) {
424                 warn "invalid inbox name: '$name'\n";
425                 return;
426         }
427
428         $ibx->{name} = $name;
429         $ibx->{-pi_cfg} = $self;
430         $ibx = PublicInbox::Inbox->new($ibx);
431         foreach (@{$ibx->{address}}) {
432                 my $lc_addr = lc($_);
433                 $self->{-by_addr}->{$lc_addr} = $ibx;
434                 $self->{-no_obfuscate}->{$lc_addr} = 1;
435         }
436         if (my $listids = $ibx->{listid}) {
437                 # RFC2919 section 6 stipulates "case insensitive equality"
438                 foreach my $list_id (@$listids) {
439                         $self->{-by_list_id}->{lc($list_id)} = $ibx;
440                 }
441         }
442         if (defined(my $ngname = $ibx->{newsgroup})) {
443                 if (ref($ngname)) {
444                         delete $ibx->{newsgroup};
445                         warn 'multiple newsgroups not supported: '.
446                                 join(', ', @$ngname). "\n";
447                 # Newsgroup name needs to be compatible with RFC 3977
448                 # wildmat-exact and RFC 3501 (IMAP) ATOM-CHAR.
449                 # Leave out a few chars likely to cause problems or conflicts:
450                 # '|', '<', '>', ';', '#', '$', '&',
451                 } elsif ($ngname =~ m![^A-Za-z0-9/_\.\-\~\@\+\=:]! ||
452                                 $ngname eq '') {
453                         delete $ibx->{newsgroup};
454                         warn "newsgroup name invalid: `$ngname'\n";
455                 } else {
456                         # PublicInbox::NNTPD does stricter ->nntp_usable
457                         # checks, keep this lean for startup speed
458                         $self->{-by_newsgroup}->{$ngname} = $ibx;
459                 }
460         }
461         unless (defined $ibx->{newsgroup}) { # for ->eidx_key
462                 my $abs = rel2abs_collapsed($dir);
463                 if ($abs ne $dir) {
464                         warn "W: `$dir' canonicalized to `$abs'\n";
465                         $ibx->{inboxdir} = $abs;
466                 }
467         }
468         $self->{-by_name}->{$name} = $ibx;
469         if ($ibx->{obfuscate}) {
470                 $ibx->{-no_obfuscate} = $self->{-no_obfuscate};
471                 $ibx->{-no_obfuscate_re} = $self->{-no_obfuscate_re};
472                 fill_all($self); # noop to populate -no_obfuscate
473         }
474
475         if (my $ibx_code_repos = $ibx->{coderepo}) {
476                 my $code_repos = $self->{-code_repos};
477                 my $repo_objs = $ibx->{-repo_objs} = [];
478                 foreach my $nick (@$ibx_code_repos) {
479                         my @parts = split(m!/!, $nick);
480                         my $valid = 0;
481                         $valid += valid_inbox_name($_) foreach (@parts);
482                         $valid == scalar(@parts) or next;
483
484                         my $repo = $code_repos->{$nick} //=
485                                                 _fill_code_repo($self, $nick);
486                         push @$repo_objs, $repo if $repo;
487                 }
488         }
489         if (my $es = ALL($self)) {
490                 require PublicInbox::Isearch;
491                 $ibx->{isrch} = PublicInbox::Isearch->new($ibx, $es);
492         }
493         $self->{-by_eidx_key}->{$ibx->eidx_key} = $ibx;
494 }
495
496 sub _fill_ei ($$) {
497         my ($self, $pfx) = @_;
498         require PublicInbox::ExtSearch;
499         my $d = $self->{"$pfx.topdir"};
500         defined($d) && -d $d ? PublicInbox::ExtSearch->new($d) : undef;
501 }
502
503 sub urlmatch {
504         my ($self, $key, $url) = @_;
505         state $urlmatch_broken; # requires git 1.8.5
506         return if $urlmatch_broken;
507         my $file = default_file();
508         my $cmd = [qw/git config -z --includes --get-urlmatch/,
509                 "--file=$file", $key, $url ];
510         my $fh = popen_rd($cmd);
511         local $/ = "\0";
512         my $val = <$fh>;
513         if (close($fh)) {
514                 chomp($val);
515                 $val;
516         } else {
517                 $urlmatch_broken = 1 if (($? >> 8) != 1);
518                 undef;
519         }
520 }
521
522 sub json {
523         state $json;
524         $json //= do {
525                 for my $mod (qw(Cpanel::JSON::XS JSON::MaybeXS JSON JSON::PP)) {
526                         eval "require $mod" or next;
527                         # ->ascii encodes non-ASCII to "\uXXXX"
528                         $json = $mod->new->ascii(1) and last;
529                 }
530                 $json;
531         };
532 }
533
534 1;