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