]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Config.pm
config: remove *_url_format support for cgit
[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         my $dir = $self->{"$pfx.dir"} // do { # aka "GIT_DIR"
332                 warn "$pfx.dir unset\n";
333                 return;
334         };
335         my $git = PublicInbox::Git->new($dir);
336         if (defined(my $cgits = $self->{"$pfx.cgiturl"})) {
337                 $git->{cgit_url} = $cgits = _array($cgits);
338                 $self->{"$pfx.cgiturl"} = $cgits;
339         }
340
341         $git;
342 }
343
344 sub get_all {
345         my ($self, $key) = @_;
346         my $v = $self->{$key} // return;
347         _array($v);
348 }
349
350 sub git_bool {
351         my ($val) = $_[-1]; # $_[0] may be $self, or $val
352         if ($val =~ /\A(?:false|no|off|[\-\+]?(?:0x)?0+)\z/i) {
353                 0;
354         } elsif ($val =~ /\A(?:true|yes|on|[\-\+]?(?:0x)?[0-9]+)\z/i) {
355                 1;
356         } else {
357                 undef;
358         }
359 }
360
361 # abs_path resolves symlinks, so we want to avoid it if rel2abs
362 # is sufficient and doesn't leave "/.." or "/../"
363 sub rel2abs_collapsed {
364         require File::Spec;
365         my $p = File::Spec->rel2abs($_[-1]);
366         return $p if substr($p, -3, 3) ne '/..' && index($p, '/../') < 0;
367         require Cwd;
368         Cwd::abs_path($p);
369 }
370
371 sub get_1 {
372         my ($self, $key) = @_;
373         my $v = $self->{$key};
374         return $v if !ref($v);
375         warn "W: $key has multiple values, only using `$v->[-1]'\n";
376         $v->[-1];
377 }
378
379 sub repo_objs {
380         my ($self, $ibxish) = @_;
381         my $ibx_code_repos = $ibxish->{coderepo} or return;
382         $ibxish->{-repo_objs} //= do {
383                 my $code_repos = $self->{-code_repos};
384                 my @repo_objs;
385                 for my $nick (@$ibx_code_repos) {
386                         my @parts = split(m!/!, $nick);
387                         for (@parts) {
388                                 @parts = () unless valid_foo_name($_);
389                         }
390                         unless (@parts) {
391                                 warn "invalid coderepo name: `$nick'\n";
392                                 next;
393                         }
394                         my $repo = $code_repos->{$nick} //=
395                                                 _fill_code_repo($self, $nick);
396                         push @repo_objs, $repo if $repo;
397                 }
398                 if (scalar @repo_objs) {
399                         \@repo_objs;
400                 } else {
401                         delete $ibxish->{coderepo};
402                         undef;
403                 }
404         }
405 }
406
407 sub _fill_ibx {
408         my ($self, $name) = @_;
409         my $pfx = "publicinbox.$name";
410         my $ibx = {};
411         for my $k (qw(watch)) {
412                 my $v = $self->{"$pfx.$k"};
413                 $ibx->{$k} = $v if defined $v;
414         }
415         for my $k (qw(filter inboxdir newsgroup replyto httpbackendmax feedmax
416                         indexlevel indexsequentialshard boost)) {
417                 my $v = get_1($self, "$pfx.$k") // next;
418                 $ibx->{$k} = $v;
419         }
420
421         # "mainrepo" is backwards compatibility:
422         my $dir = $ibx->{inboxdir} //= $self->{"$pfx.mainrepo"} // return;
423         if (index($dir, "\n") >= 0) {
424                 warn "E: `$dir' must not contain `\\n'\n";
425                 return;
426         }
427         for my $k (qw(obfuscate)) {
428                 my $v = $self->{"$pfx.$k"} // next;
429                 if (defined(my $bval = git_bool($v))) {
430                         $ibx->{$k} = $bval;
431                 } else {
432                         warn "Ignoring $pfx.$k=$v in config, not boolean\n";
433                 }
434         }
435         # TODO: more arrays, we should support multi-value for
436         # more things to encourage decentralization
437         for my $k (qw(address altid nntpmirror imapmirror
438                         coderepo hide listid url
439                         infourl watchheader nntpserver imapserver)) {
440                 my $v = $self->{"$pfx.$k"} // next;
441                 $ibx->{$k} = _array($v);
442         }
443
444         return unless valid_foo_name($name, 'publicinbox');
445         $ibx->{name} = $name;
446         $ibx->{-pi_cfg} = $self;
447         $ibx = PublicInbox::Inbox->new($ibx);
448         foreach (@{$ibx->{address}}) {
449                 my $lc_addr = lc($_);
450                 $self->{-by_addr}->{$lc_addr} = $ibx;
451                 $self->{-no_obfuscate}->{$lc_addr} = 1;
452         }
453         if (my $listids = $ibx->{listid}) {
454                 # RFC2919 section 6 stipulates "case insensitive equality"
455                 foreach my $list_id (@$listids) {
456                         $self->{-by_list_id}->{lc($list_id)} = $ibx;
457                 }
458         }
459         if (defined(my $ngname = $ibx->{newsgroup})) {
460                 if (ref($ngname)) {
461                         delete $ibx->{newsgroup};
462                         warn 'multiple newsgroups not supported: '.
463                                 join(', ', @$ngname). "\n";
464                 # Newsgroup name needs to be compatible with RFC 3977
465                 # wildmat-exact and RFC 3501 (IMAP) ATOM-CHAR.
466                 # Leave out a few chars likely to cause problems or conflicts:
467                 # '|', '<', '>', ';', '#', '$', '&',
468                 } elsif ($ngname =~ m![^A-Za-z0-9/_\.\-\~\@\+\=:]! ||
469                                 $ngname eq '') {
470                         delete $ibx->{newsgroup};
471                         warn "newsgroup name invalid: `$ngname'\n";
472                 } else {
473                         # PublicInbox::NNTPD does stricter ->nntp_usable
474                         # checks, keep this lean for startup speed
475                         $self->{-by_newsgroup}->{$ngname} = $ibx;
476                 }
477         }
478         unless (defined $ibx->{newsgroup}) { # for ->eidx_key
479                 my $abs = rel2abs_collapsed($dir);
480                 if ($abs ne $dir) {
481                         warn "W: `$dir' canonicalized to `$abs'\n";
482                         $ibx->{inboxdir} = $abs;
483                 }
484         }
485         $self->{-by_name}->{$name} = $ibx;
486         if ($ibx->{obfuscate}) {
487                 $ibx->{-no_obfuscate} = $self->{-no_obfuscate};
488                 $ibx->{-no_obfuscate_re} = $self->{-no_obfuscate_re};
489                 fill_all($self); # noop to populate -no_obfuscate
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, $name) = @_;
500         eval { require PublicInbox::ExtSearch } or return;
501         my $pfx = "extindex.$name";
502         my $d = $self->{"$pfx.topdir"} // return;
503         -d $d or return;
504         if (index($d, "\n") >= 0) {
505                 warn "E: `$d' must not contain `\\n'\n";
506                 return;
507         }
508         my $es = PublicInbox::ExtSearch->new($d);
509         for my $k (qw(indexlevel indexsequentialshard)) {
510                 my $v = get_1($self, "$pfx.$k") // next;
511                 $es->{$k} = $v;
512         }
513         for my $k (qw(coderepo hide url infourl)) {
514                 my $v = $self->{"$pfx.$k"} // next;
515                 $es->{$k} = _array($v);
516         }
517         return unless valid_foo_name($name, 'extindex');
518         $es->{name} = $name;
519         $es;
520 }
521
522 sub urlmatch {
523         my ($self, $key, $url) = @_;
524         state $urlmatch_broken; # requires git 1.8.5
525         return if $urlmatch_broken;
526         my $file = $self->{'-f'} // default_file();
527         my $cmd = [qw/git config -z --includes --get-urlmatch/,
528                 "--file=$file", $key, $url ];
529         my $fh = popen_rd($cmd);
530         local $/ = "\0";
531         my $val = <$fh>;
532         if (close($fh)) {
533                 chomp($val);
534                 $val;
535         } else {
536                 $urlmatch_broken = 1 if (($? >> 8) != 1);
537                 undef;
538         }
539 }
540
541 sub json {
542         state $json;
543         $json //= do {
544                 for my $mod (qw(Cpanel::JSON::XS JSON::MaybeXS JSON JSON::PP)) {
545                         eval "require $mod" or next;
546                         # ->ascii encodes non-ASCII to "\uXXXX"
547                         $json = $mod->new->ascii(1) and last;
548                 }
549                 $json;
550         };
551 }
552
553 sub squote_maybe ($) {
554         my ($val) = @_;
555         if ($val =~ m{([^\w@\./,\%\+\-])}) {
556                 $val =~ s/(['!])/'\\$1'/g; # '!' for csh
557                 return "'$val'";
558         }
559         $val;
560 }
561
562 1;