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