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