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