]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Config.pm
extsearch: wire up remaining Inbox-like methods for WWW
[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->{-no_obfuscate} = {};
37         $self->{-limiters} = {};
38         $self->{-code_repos} = {}; # nick => PublicInbox::Git object
39         $self->{-cgitrc_unparsed} = $self->{'publicinbox.cgitrc'};
40
41         if (my $no = delete $self->{'publicinbox.noobfuscate'}) {
42                 $no = _array($no);
43                 my @domains;
44                 foreach my $n (@$no) {
45                         my @n = split(/\s+/, $n);
46                         foreach (@n) {
47                                 if (/\S+@\S+/) { # full address
48                                         $self->{-no_obfuscate}->{lc $_} = 1;
49                                 } else {
50                                         # allow "example.com" or "@example.com"
51                                         s/\A@//;
52                                         push @domains, quotemeta($_);
53                                 }
54                         }
55                 }
56                 my $nod = join('|', @domains);
57                 $self->{-no_obfuscate_re} = qr/(?:$nod)\z/i;
58         }
59         if (my $css = delete $self->{'publicinbox.css'}) {
60                 $self->{css} = _array($css);
61         }
62
63         $self;
64 }
65
66 sub noop {}
67 sub fill_all ($) { each_inbox($_[0], \&noop) }
68
69 sub _lookup_fill ($$$) {
70         my ($self, $cache, $key) = @_;
71         $self->{$cache}->{$key} // do {
72                 fill_all($self);
73                 $self->{$cache}->{$key};
74         }
75 }
76
77 sub lookup {
78         my ($self, $recipient) = @_;
79         _lookup_fill($self, '-by_addr', lc($recipient));
80 }
81
82 sub lookup_list_id {
83         my ($self, $list_id) = @_;
84         _lookup_fill($self, '-by_list_id', lc($list_id));
85 }
86
87 sub lookup_name ($$) {
88         my ($self, $name) = @_;
89         $self->{-by_name}->{$name} // _fill($self, "publicinbox.$name");
90 }
91
92 sub lookup_ei {
93         my ($self, $name) = @_;
94         $self->{-ei_by_name}->{$name} //= _fill_ei($self, "eindex.$name");
95 }
96
97 sub each_inbox {
98         my ($self, $cb, @arg) = @_;
99         # may auto-vivify if config file is non-existent:
100         foreach my $section (@{$self->{-section_order}}) {
101                 next if $section !~ m!\Apublicinbox\.([^/]+)\z!;
102                 my $ibx = lookup_name($self, $1) or next;
103                 $cb->($ibx, @arg);
104         }
105 }
106
107 sub lookup_newsgroup {
108         my ($self, $ng) = @_;
109         _lookup_fill($self, '-by_newsgroup', lc($ng));
110 }
111
112 sub limiter {
113         my ($self, $name) = @_;
114         $self->{-limiters}->{$name} //= do {
115                 require PublicInbox::Qspawn;
116                 my $max = $self->{"publicinboxlimiter.$name.max"} || 1;
117                 my $limiter = PublicInbox::Qspawn::Limiter->new($max);
118                 $limiter->setup_rlimit($name, $self);
119                 $limiter;
120         };
121 }
122
123 sub config_dir { $ENV{PI_DIR} // "$ENV{HOME}/.public-inbox" }
124
125 sub default_file {
126         $ENV{PI_CONFIG} // (config_dir() . '/config');
127 }
128
129 sub config_fh_parse ($$$) {
130         my ($fh, $rs, $fs) = @_;
131         my %rv;
132         my (%section_seen, @section_order);
133         local $/ = $rs;
134         while (defined(my $line = <$fh>)) {
135                 chomp $line;
136                 my ($k, $v) = split($fs, $line, 2);
137                 my ($section) = ($k =~ /\A(\S+)\.[^\.]+\z/);
138                 unless (defined $section_seen{$section}) {
139                         $section_seen{$section} = 1;
140                         push @section_order, $section;
141                 }
142
143                 my $cur = $rv{$k};
144                 if (defined $cur) {
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 $cmd = join(' ', @cmd);
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_inbox_name ($) {
171         my ($name) = @_;
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                 return 0;
180         }
181
182         # Note: we allow URL-unfriendly characters; users may configure
183         # non-HTTP-accessible inboxes
184         1;
185 }
186
187 # XXX needs testing for cgit compatibility
188 # cf. cgit/scan-tree.c::add_repo
189 sub cgit_repo_merge ($$$) {
190         my ($self, $base, $repo) = @_;
191         my $path = $repo->{dir};
192         if (defined(my $se = $self->{-cgit_strict_export})) {
193                 return unless -e "$path/$se";
194         }
195         return if -e "$path/noweb";
196         # this comes from the cgit config, and AFAIK cgit only allows
197         # repos to have one URL, but that's just the PATH_INFO component,
198         # not the Host: portion
199         # $repo = { url => 'foo.git', dir => '/path/to/foo.git' }
200         my $rel = $repo->{url};
201         unless (defined $rel) {
202                 my $off = index($path, $base, 0);
203                 if ($off != 0) {
204                         $rel = $path;
205                 } else {
206                         $rel = substr($path, length($base) + 1);
207                 }
208
209                 $rel =~ s!/\.git\z!! or
210                         $rel =~ s!/+\z!!;
211
212                 $self->{-cgit_remove_suffix} and
213                         $rel =~ s!/?\.git\z!!;
214         }
215         $self->{"coderepo.$rel.dir"} //= $path;
216         $self->{"coderepo.$rel.cgiturl"} //= _array($rel);
217 }
218
219 sub is_git_dir ($) {
220         my ($git_dir) = @_;
221         -d "$git_dir/objects" && -f "$git_dir/HEAD";
222 }
223
224 # XXX needs testing for cgit compatibility
225 sub scan_path_coderepo {
226         my ($self, $base, $path) = @_;
227         opendir(my $dh, $path) or do {
228                 warn "error opening directory: $path\n";
229                 return
230         };
231         my $git_dir = $path;
232         if (is_git_dir($git_dir) || is_git_dir($git_dir .= '/.git')) {
233                 my $repo = { dir => $git_dir };
234                 cgit_repo_merge($self, $base, $repo);
235                 return;
236         }
237         while (defined(my $dn = readdir $dh)) {
238                 next if $dn eq '.' || $dn eq '..';
239                 if (index($dn, '.') == 0 && !$self->{-cgit_scan_hidden_path}) {
240                         next;
241                 }
242                 my $dir = "$path/$dn";
243                 scan_path_coderepo($self, $base, $dir) if -d $dir;
244         }
245 }
246
247 sub scan_tree_coderepo ($$) {
248         my ($self, $path) = @_;
249         scan_path_coderepo($self, $path, $path);
250 }
251
252 sub scan_projects_coderepo ($$$) {
253         my ($self, $list, $path) = @_;
254         open my $fh, '<', $list or do {
255                 warn "failed to open cgit projectlist=$list: $!\n";
256                 return;
257         };
258         while (<$fh>) {
259                 chomp;
260                 scan_path_coderepo($self, $path, "$path/$_");
261         }
262 }
263
264 sub parse_cgitrc {
265         my ($self, $cgitrc, $nesting) = @_;
266         if ($nesting == 0) {
267                 # defaults:
268                 my %s = map { $_ => 1 } qw(/cgit.css /cgit.png
269                                                 /favicon.ico /robots.txt);
270                 $self->{-cgit_static} = \%s;
271         }
272
273         # same limit as cgit/configfile.c::parse_configfile
274         return if $nesting > 8;
275
276         open my $fh, '<', $cgitrc or do {
277                 warn "failed to open cgitrc=$cgitrc: $!\n";
278                 return;
279         };
280
281         # FIXME: this doesn't support macro expansion via $VARS, yet
282         my $repo;
283         while (<$fh>) {
284                 chomp;
285                 if (m!\Arepo\.url=(.+?)/*\z!) {
286                         my $nick = $1;
287                         cgit_repo_merge($self, $repo->{dir}, $repo) if $repo;
288                         $repo = { url => $nick };
289                 } elsif (m!\Arepo\.path=(.+)\z!) {
290                         if (defined $repo) {
291                                 $repo->{dir} = $1;
292                         } else {
293                                 warn "$_ without repo.url\n";
294                         }
295                 } elsif (m!\Ainclude=(.+)\z!) {
296                         parse_cgitrc($self, $1, $nesting + 1);
297                 } elsif (m!\A(scan-hidden-path|remove-suffix)=([0-9]+)\z!) {
298                         my ($k, $v) = ($1, $2);
299                         $k =~ tr/-/_/;
300                         $self->{"-cgit_$k"} = $v;
301                 } elsif (m!\A(project-list|strict-export)=(.+)\z!) {
302                         my ($k, $v) = ($1, $2);
303                         $k =~ tr/-/_/;
304                         $self->{"-cgit_$k"} = $v;
305                 } elsif (m!\Ascan-path=(.+)\z!) {
306                         if (defined(my $list = $self->{-cgit_project_list})) {
307                                 scan_projects_coderepo($self, $list, $1);
308                         } else {
309                                 scan_tree_coderepo($self, $1);
310                         }
311                 } elsif (m!\A(?:css|favicon|logo|repo\.logo)=(/.+)\z!) {
312                         # absolute paths for static files via PublicInbox::Cgit
313                         $self->{-cgit_static}->{$1} = 1;
314                 }
315         }
316         cgit_repo_merge($self, $repo->{dir}, $repo) if $repo;
317 }
318
319 # parse a code repo
320 # Only git is supported at the moment, but SVN and Hg are possibilities
321 sub _fill_code_repo {
322         my ($self, $nick) = @_;
323         my $pfx = "coderepo.$nick";
324
325         # TODO: support gitweb and other repository viewers?
326         if (defined(my $cgitrc = delete $self->{-cgitrc_unparsed})) {
327                 parse_cgitrc($self, $cgitrc, 0);
328         }
329         my $dir = $self->{"$pfx.dir"}; # aka "GIT_DIR"
330         unless (defined $dir) {
331                 warn "$pfx.dir unset\n";
332                 return;
333         }
334
335         my $git = PublicInbox::Git->new($dir);
336         foreach my $t (qw(blob commit tree tag)) {
337                 $git->{$t.'_url_format'} =
338                                 _array($self->{lc("$pfx.${t}UrlFormat")});
339         }
340
341         if (defined(my $cgits = $self->{"$pfx.cgiturl"})) {
342                 $git->{cgit_url} = $cgits = _array($cgits);
343                 $self->{"$pfx.cgiturl"} = $cgits;
344
345                 # cgit supports "/blob/?id=%s", but it's only a plain-text
346                 # display and requires an unabbreviated id=
347                 foreach my $t (qw(blob commit tag)) {
348                         $git->{$t.'_url_format'} //= map {
349                                 "$_/$t/?id=%s"
350                         } @$cgits;
351                 }
352         }
353
354         $git;
355 }
356
357 sub git_bool {
358         my ($val) = $_[-1]; # $_[0] may be $self, or $val
359         if ($val =~ /\A(?:false|no|off|[\-\+]?(?:0x)?0+)\z/i) {
360                 0;
361         } elsif ($val =~ /\A(?:true|yes|on|[\-\+]?(?:0x)?[0-9]+)\z/i) {
362                 1;
363         } else {
364                 undef;
365         }
366 }
367
368 sub _fill {
369         my ($self, $pfx) = @_;
370         my $ibx = {};
371
372         for my $k (qw(watch nntpserver)) {
373                 my $v = $self->{"$pfx.$k"};
374                 $ibx->{$k} = $v if defined $v;
375         }
376         for my $k (qw(filter inboxdir newsgroup replyto httpbackendmax feedmax
377                         indexlevel indexsequentialshard)) {
378                 if (defined(my $v = $self->{"$pfx.$k"})) {
379                         if (ref($v) eq 'ARRAY') {
380                                 warn <<EOF;
381 W: $pfx.$k has multiple values, only using `$v->[-1]'
382 EOF
383                                 $ibx->{$k} = $v->[-1];
384                         } else {
385                                 $ibx->{$k} = $v;
386                         }
387                 }
388         }
389
390         # backwards compatibility:
391         $ibx->{inboxdir} //= $self->{"$pfx.mainrepo"};
392         if (($ibx->{inboxdir} // '') =~ /\n/s) {
393                 warn "E: `$ibx->{inboxdir}' must not contain `\\n'\n";
394                 return;
395         }
396         foreach my $k (qw(obfuscate)) {
397                 my $v = $self->{"$pfx.$k"};
398                 defined $v or next;
399                 if (defined(my $bval = git_bool($v))) {
400                         $ibx->{$k} = $bval;
401                 } else {
402                         warn "Ignoring $pfx.$k=$v in config, not boolean\n";
403                 }
404         }
405         # TODO: more arrays, we should support multi-value for
406         # more things to encourage decentralization
407         foreach my $k (qw(address altid nntpmirror coderepo hide listid url
408                         infourl watchheader)) {
409                 if (defined(my $v = $self->{"$pfx.$k"})) {
410                         $ibx->{$k} = _array($v);
411                 }
412         }
413
414         return unless defined($ibx->{inboxdir});
415         my $name = $pfx;
416         $name =~ s/\Apublicinbox\.//;
417
418         if (!valid_inbox_name($name)) {
419                 warn "invalid inbox name: '$name'\n";
420                 return;
421         }
422
423         $ibx->{name} = $name;
424         $ibx->{-pi_config} = $self;
425         $ibx = PublicInbox::Inbox->new($ibx);
426         foreach (@{$ibx->{address}}) {
427                 my $lc_addr = lc($_);
428                 $self->{-by_addr}->{$lc_addr} = $ibx;
429                 $self->{-no_obfuscate}->{$lc_addr} = 1;
430         }
431         if (my $listids = $ibx->{listid}) {
432                 # RFC2919 section 6 stipulates "case insensitive equality"
433                 foreach my $list_id (@$listids) {
434                         $self->{-by_list_id}->{lc($list_id)} = $ibx;
435                 }
436         }
437         if (my $ng = $ibx->{newsgroup}) {
438                 $self->{-by_newsgroup}->{$ng} = $ibx;
439         }
440         $self->{-by_name}->{$name} = $ibx;
441         if ($ibx->{obfuscate}) {
442                 $ibx->{-no_obfuscate} = $self->{-no_obfuscate};
443                 $ibx->{-no_obfuscate_re} = $self->{-no_obfuscate_re};
444                 fill_all($self); # noop to populate -no_obfuscate
445         }
446
447         if (my $ibx_code_repos = $ibx->{coderepo}) {
448                 my $code_repos = $self->{-code_repos};
449                 my $repo_objs = $ibx->{-repo_objs} = [];
450                 foreach my $nick (@$ibx_code_repos) {
451                         my @parts = split(m!/!, $nick);
452                         my $valid = 0;
453                         $valid += valid_inbox_name($_) foreach (@parts);
454                         $valid == scalar(@parts) or next;
455
456                         my $repo = $code_repos->{$nick} //=
457                                                 _fill_code_repo($self, $nick);
458                         push @$repo_objs, $repo if $repo;
459                 }
460         }
461
462         $ibx
463 }
464
465 sub _fill_ei ($$) {
466         my ($self, $pfx) = @_;
467         require PublicInbox::ExtSearch;
468         my $d = $self->{"$pfx.topdir"};
469         defined($d) && -d $d ? PublicInbox::ExtSearch->new($d) : undef;
470 }
471
472 sub urlmatch {
473         my ($self, $key, $url) = @_;
474         state $urlmatch_broken; # requires git 1.8.5
475         return if $urlmatch_broken;
476         my $file = default_file();
477         my $cmd = [qw/git config -z --includes --get-urlmatch/,
478                 "--file=$file", $key, $url ];
479         my $fh = popen_rd($cmd);
480         local $/ = "\0";
481         my $val = <$fh>;
482         if (close($fh)) {
483                 chomp($val);
484                 $val;
485         } else {
486                 $urlmatch_broken = 1 if (($? >> 8) != 1);
487                 undef;
488         }
489 }
490
491 1;