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