]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Config.pm
113975dd9e2816b7e32366df030423eabecad3d9
[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_ibx($self, $name);
92 }
93
94 sub lookup_ei {
95         my ($self, $name) = @_;
96         $self->{-ei_by_name}->{$name} //= _fill_ei($self, $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_foo_name ($;$) {
171         my ($name, $pfx) = @_;
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                 warn "invalid $pfx name: `$name'\n" if $pfx;
180                 return 0;
181         }
182
183         # Note: we allow URL-unfriendly characters; users may configure
184         # non-HTTP-accessible inboxes
185         1;
186 }
187
188 # XXX needs testing for cgit compatibility
189 # cf. cgit/scan-tree.c::add_repo
190 sub cgit_repo_merge ($$$) {
191         my ($self, $base, $repo) = @_;
192         my $path = $repo->{dir};
193         if (defined(my $se = $self->{-cgit_strict_export})) {
194                 return unless -e "$path/$se";
195         }
196         return if -e "$path/noweb";
197         # this comes from the cgit config, and AFAIK cgit only allows
198         # repos to have one URL, but that's just the PATH_INFO component,
199         # not the Host: portion
200         # $repo = { url => 'foo.git', dir => '/path/to/foo.git' }
201         my $rel = $repo->{url};
202         unless (defined $rel) {
203                 my $off = index($path, $base, 0);
204                 if ($off != 0) {
205                         $rel = $path;
206                 } else {
207                         $rel = substr($path, length($base) + 1);
208                 }
209
210                 $rel =~ s!/\.git\z!! or
211                         $rel =~ s!/+\z!!;
212
213                 $self->{-cgit_remove_suffix} and
214                         $rel =~ s!/?\.git\z!!;
215         }
216         $self->{"coderepo.$rel.dir"} //= $path;
217         $self->{"coderepo.$rel.cgiturl"} //= _array($rel);
218 }
219
220 sub is_git_dir ($) {
221         my ($git_dir) = @_;
222         -d "$git_dir/objects" && -f "$git_dir/HEAD";
223 }
224
225 # XXX needs testing for cgit compatibility
226 sub scan_path_coderepo {
227         my ($self, $base, $path) = @_;
228         opendir(my $dh, $path) or do {
229                 warn "error opening directory: $path\n";
230                 return
231         };
232         my $git_dir = $path;
233         if (is_git_dir($git_dir) || is_git_dir($git_dir .= '/.git')) {
234                 my $repo = { dir => $git_dir };
235                 cgit_repo_merge($self, $base, $repo);
236                 return;
237         }
238         while (defined(my $dn = readdir $dh)) {
239                 next if $dn eq '.' || $dn eq '..';
240                 if (index($dn, '.') == 0 && !$self->{-cgit_scan_hidden_path}) {
241                         next;
242                 }
243                 my $dir = "$path/$dn";
244                 scan_path_coderepo($self, $base, $dir) if -d $dir;
245         }
246 }
247
248 sub scan_tree_coderepo ($$) {
249         my ($self, $path) = @_;
250         scan_path_coderepo($self, $path, $path);
251 }
252
253 sub scan_projects_coderepo ($$$) {
254         my ($self, $list, $path) = @_;
255         open my $fh, '<', $list or do {
256                 warn "failed to open cgit projectlist=$list: $!\n";
257                 return;
258         };
259         while (<$fh>) {
260                 chomp;
261                 scan_path_coderepo($self, $path, "$path/$_");
262         }
263 }
264
265 sub parse_cgitrc {
266         my ($self, $cgitrc, $nesting) = @_;
267         if ($nesting == 0) {
268                 # defaults:
269                 my %s = map { $_ => 1 } qw(/cgit.css /cgit.png
270                                                 /favicon.ico /robots.txt);
271                 $self->{-cgit_static} = \%s;
272         }
273
274         # same limit as cgit/configfile.c::parse_configfile
275         return if $nesting > 8;
276
277         open my $fh, '<', $cgitrc or do {
278                 warn "failed to open cgitrc=$cgitrc: $!\n";
279                 return;
280         };
281
282         # FIXME: this doesn't support macro expansion via $VARS, yet
283         my $repo;
284         while (<$fh>) {
285                 chomp;
286                 if (m!\Arepo\.url=(.+?)/*\z!) {
287                         my $nick = $1;
288                         cgit_repo_merge($self, $repo->{dir}, $repo) if $repo;
289                         $repo = { url => $nick };
290                 } elsif (m!\Arepo\.path=(.+)\z!) {
291                         if (defined $repo) {
292                                 $repo->{dir} = $1;
293                         } else {
294                                 warn "$_ without repo.url\n";
295                         }
296                 } elsif (m!\Ainclude=(.+)\z!) {
297                         parse_cgitrc($self, $1, $nesting + 1);
298                 } elsif (m!\A(scan-hidden-path|remove-suffix)=([0-9]+)\z!) {
299                         my ($k, $v) = ($1, $2);
300                         $k =~ tr/-/_/;
301                         $self->{"-cgit_$k"} = $v;
302                 } elsif (m!\A(project-list|strict-export)=(.+)\z!) {
303                         my ($k, $v) = ($1, $2);
304                         $k =~ tr/-/_/;
305                         $self->{"-cgit_$k"} = $v;
306                 } elsif (m!\Ascan-path=(.+)\z!) {
307                         if (defined(my $list = $self->{-cgit_project_list})) {
308                                 scan_projects_coderepo($self, $list, $1);
309                         } else {
310                                 scan_tree_coderepo($self, $1);
311                         }
312                 } elsif (m!\A(?:css|favicon|logo|repo\.logo)=(/.+)\z!) {
313                         # absolute paths for static files via PublicInbox::Cgit
314                         $self->{-cgit_static}->{$1} = 1;
315                 }
316         }
317         cgit_repo_merge($self, $repo->{dir}, $repo) if $repo;
318 }
319
320 # parse a code repo
321 # Only git is supported at the moment, but SVN and Hg are possibilities
322 sub _fill_code_repo {
323         my ($self, $nick) = @_;
324         my $pfx = "coderepo.$nick";
325
326         # TODO: support gitweb and other repository viewers?
327         if (defined(my $cgitrc = delete $self->{-cgitrc_unparsed})) {
328                 parse_cgitrc($self, $cgitrc, 0);
329         }
330         my $dir = $self->{"$pfx.dir"}; # aka "GIT_DIR"
331         unless (defined $dir) {
332                 warn "$pfx.dir unset\n";
333                 return;
334         }
335
336         my $git = PublicInbox::Git->new($dir);
337         foreach my $t (qw(blob commit tree tag)) {
338                 $git->{$t.'_url_format'} =
339                                 _array($self->{lc("$pfx.${t}UrlFormat")});
340         }
341
342         if (defined(my $cgits = $self->{"$pfx.cgiturl"})) {
343                 $git->{cgit_url} = $cgits = _array($cgits);
344                 $self->{"$pfx.cgiturl"} = $cgits;
345
346                 # cgit supports "/blob/?id=%s", but it's only a plain-text
347                 # display and requires an unabbreviated id=
348                 foreach my $t (qw(blob commit tag)) {
349                         $git->{$t.'_url_format'} //= map {
350                                 "$_/$t/?id=%s"
351                         } @$cgits;
352                 }
353         }
354
355         $git;
356 }
357
358 sub git_bool {
359         my ($val) = $_[-1]; # $_[0] may be $self, or $val
360         if ($val =~ /\A(?:false|no|off|[\-\+]?(?:0x)?0+)\z/i) {
361                 0;
362         } elsif ($val =~ /\A(?:true|yes|on|[\-\+]?(?:0x)?[0-9]+)\z/i) {
363                 1;
364         } else {
365                 undef;
366         }
367 }
368
369 # abs_path resolves symlinks, so we want to avoid it if rel2abs
370 # is sufficient and doesn't leave "/.." or "/../"
371 sub rel2abs_collapsed {
372         require File::Spec;
373         my $p = File::Spec->rel2abs($_[-1]);
374         return $p if substr($p, -3, 3) ne '/..' && index($p, '/../') < 0;
375         require Cwd;
376         Cwd::abs_path($p);
377 }
378
379 sub _one_val {
380         my ($self, $pfx, $k) = @_;
381         my $v = $self->{"$pfx.$k"} // return;
382         return $v if !ref($v);
383         warn "W: $pfx.$k has multiple values, only using `$v->[-1]'\n";
384         $v->[-1];
385 }
386
387 sub _fill_ibx {
388         my ($self, $name) = @_;
389         my $pfx = "publicinbox.$name";
390         my $ibx = {};
391         for my $k (qw(watch nntpserver)) {
392                 my $v = $self->{"$pfx.$k"};
393                 $ibx->{$k} = $v if defined $v;
394         }
395         for my $k (qw(filter inboxdir newsgroup replyto httpbackendmax feedmax
396                         indexlevel indexsequentialshard)) {
397                 my $v = _one_val($self, $pfx, $k) // next;
398                 $ibx->{$k} = $v;
399         }
400
401         # "mainrepo" is backwards compatibility:
402         my $dir = $ibx->{inboxdir} //= $self->{"$pfx.mainrepo"} // return;
403         if (index($dir, "\n") >= 0) {
404                 warn "E: `$dir' must not contain `\\n'\n";
405                 return;
406         }
407         for my $k (qw(obfuscate)) {
408                 my $v = $self->{"$pfx.$k"} // 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         for my $k (qw(address altid nntpmirror coderepo hide listid url
418                         infourl watchheader)) {
419                 my $v = $self->{"$pfx.$k"} // next;
420                 $ibx->{$k} = _array($v);
421         }
422
423         return unless valid_foo_name($name, 'publicinbox');
424         $ibx->{name} = $name;
425         $ibx->{-pi_cfg} = $self;
426         $ibx = PublicInbox::Inbox->new($ibx);
427         foreach (@{$ibx->{address}}) {
428                 my $lc_addr = lc($_);
429                 $self->{-by_addr}->{$lc_addr} = $ibx;
430                 $self->{-no_obfuscate}->{$lc_addr} = 1;
431         }
432         if (my $listids = $ibx->{listid}) {
433                 # RFC2919 section 6 stipulates "case insensitive equality"
434                 foreach my $list_id (@$listids) {
435                         $self->{-by_list_id}->{lc($list_id)} = $ibx;
436                 }
437         }
438         if (defined(my $ngname = $ibx->{newsgroup})) {
439                 if (ref($ngname)) {
440                         delete $ibx->{newsgroup};
441                         warn 'multiple newsgroups not supported: '.
442                                 join(', ', @$ngname). "\n";
443                 # Newsgroup name needs to be compatible with RFC 3977
444                 # wildmat-exact and RFC 3501 (IMAP) ATOM-CHAR.
445                 # Leave out a few chars likely to cause problems or conflicts:
446                 # '|', '<', '>', ';', '#', '$', '&',
447                 } elsif ($ngname =~ m![^A-Za-z0-9/_\.\-\~\@\+\=:]! ||
448                                 $ngname eq '') {
449                         delete $ibx->{newsgroup};
450                         warn "newsgroup name invalid: `$ngname'\n";
451                 } else {
452                         # PublicInbox::NNTPD does stricter ->nntp_usable
453                         # checks, keep this lean for startup speed
454                         $self->{-by_newsgroup}->{$ngname} = $ibx;
455                 }
456         }
457         unless (defined $ibx->{newsgroup}) { # for ->eidx_key
458                 my $abs = rel2abs_collapsed($dir);
459                 if ($abs ne $dir) {
460                         warn "W: `$dir' canonicalized to `$abs'\n";
461                         $ibx->{inboxdir} = $abs;
462                 }
463         }
464         $self->{-by_name}->{$name} = $ibx;
465         if ($ibx->{obfuscate}) {
466                 $ibx->{-no_obfuscate} = $self->{-no_obfuscate};
467                 $ibx->{-no_obfuscate_re} = $self->{-no_obfuscate_re};
468                 fill_all($self); # noop to populate -no_obfuscate
469         }
470         if (my $ibx_code_repos = $ibx->{coderepo}) {
471                 my $code_repos = $self->{-code_repos};
472                 my $repo_objs = $ibx->{-repo_objs} = [];
473                 foreach my $nick (@$ibx_code_repos) {
474                         my @parts = split(m!/!, $nick);
475                         my $valid = 0;
476                         $valid += valid_foo_name($_) foreach (@parts);
477                         $valid == scalar(@parts) or next;
478
479                         my $repo = $code_repos->{$nick} //=
480                                                 _fill_code_repo($self, $nick);
481                         push @$repo_objs, $repo if $repo;
482                 }
483         }
484         if (my $es = ALL($self)) {
485                 require PublicInbox::Isearch;
486                 $ibx->{isrch} = PublicInbox::Isearch->new($ibx, $es);
487         }
488         $self->{-by_eidx_key}->{$ibx->eidx_key} = $ibx;
489 }
490
491 sub _fill_ei ($$) {
492         my ($self, $name) = @_;
493         eval { require PublicInbox::ExtSearch } or return;
494         my $pfx = "extindex.$name";
495         my $d = $self->{"$pfx.topdir"} // return;
496         -d $d or return;
497         my $es = PublicInbox::ExtSearch->new($d);
498         for my $k (qw(indexlevel indexsequentialshard)) {
499                 my $v = _one_val($self, $pfx, $k) // next;
500                 $es->{$k} = $v;
501         }
502         for my $k (qw(altid coderepo hide url infourl)) {
503                 my $v = $self->{"$pfx.$k"} // next;
504                 $es->{$k} = _array($v);
505         }
506         return unless valid_foo_name($name, 'extindex');
507         $es->{name} = $name;
508         $es;
509 }
510
511 sub urlmatch {
512         my ($self, $key, $url) = @_;
513         state $urlmatch_broken; # requires git 1.8.5
514         return if $urlmatch_broken;
515         my $file = $self->{'-f'} // default_file();
516         my $cmd = [qw/git config -z --includes --get-urlmatch/,
517                 "--file=$file", $key, $url ];
518         my $fh = popen_rd($cmd);
519         local $/ = "\0";
520         my $val = <$fh>;
521         if (close($fh)) {
522                 chomp($val);
523                 $val;
524         } else {
525                 $urlmatch_broken = 1 if (($? >> 8) != 1);
526                 undef;
527         }
528 }
529
530 sub json {
531         state $json;
532         $json //= do {
533                 for my $mod (qw(Cpanel::JSON::XS JSON::MaybeXS JSON JSON::PP)) {
534                         eval "require $mod" or next;
535                         # ->ascii encodes non-ASCII to "\uXXXX"
536                         $json = $mod->new->ascii(1) and last;
537                 }
538                 $json;
539         };
540 }
541
542 1;