]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Config.pm
config: allow "0" as a valid mainrepo path
[public-inbox.git] / lib / PublicInbox / Config.pm
1 # Copyright (C) 2014-2019 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 warnings;
13 require 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() unless defined($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 _fill_all ($) { each_inbox($_[0], sub {}) }
67
68 sub _lookup_fill ($$$) {
69         my ($self, $cache, $key) = @_;
70         $self->{$cache}->{$key} // do {
71                 _fill_all($self);
72                 $self->{$cache}->{$key};
73         }
74 }
75
76 sub lookup {
77         my ($self, $recipient) = @_;
78         _lookup_fill($self, '-by_addr', lc($recipient));
79 }
80
81 sub lookup_list_id {
82         my ($self, $list_id) = @_;
83         _lookup_fill($self, '-by_list_id', lc($list_id));
84 }
85
86 sub lookup_name ($$) {
87         my ($self, $name) = @_;
88         $self->{-by_name}->{$name} // _fill($self, "publicinbox.$name");
89 }
90
91 sub each_inbox {
92         my ($self, $cb) = @_;
93         # may auto-vivify if config file is non-existent:
94         foreach my $section (@{$self->{-section_order}}) {
95                 next if $section !~ m!\Apublicinbox\.([^/]+)\z!;
96                 defined($self->{"publicinbox.$1.mainrepo"}) or next;
97                 my $ibx = lookup_name($self, $1) or next;
98                 $cb->($ibx);
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         my $f = $ENV{PI_CONFIG};
122         return $f if defined $f;
123         config_dir() . '/config';
124 }
125
126 sub config_fh_parse ($$$) {
127         my ($fh, $rs, $fs) = @_;
128         my %rv;
129         my (%section_seen, @section_order);
130         local $/ = $rs;
131         while (defined(my $line = <$fh>)) {
132                 chomp $line;
133                 my ($k, $v) = split($fs, $line, 2);
134                 my ($section) = ($k =~ /\A(\S+)\.[^\.]+\z/);
135                 unless (defined $section_seen{$section}) {
136                         $section_seen{$section} = 1;
137                         push @section_order, $section;
138                 }
139
140                 my $cur = $rv{$k};
141                 if (defined $cur) {
142                         if (ref($cur) eq "ARRAY") {
143                                 push @$cur, $v;
144                         } else {
145                                 $rv{$k} = [ $cur, $v ];
146                         }
147                 } else {
148                         $rv{$k} = $v;
149                 }
150         }
151         $rv{-section_order} = \@section_order;
152
153         \%rv;
154 }
155
156 sub git_config_dump {
157         my ($file) = @_;
158         return {} unless -e $file;
159         my @cmd = (qw/git config -z -l/, "--file=$file");
160         my $cmd = join(' ', @cmd);
161         my $fh = popen_rd(\@cmd) or die "popen_rd failed for $file: $!\n";
162         my $rv = config_fh_parse($fh, "\0", "\n");
163         close $fh or die "failed to close ($cmd) pipe: $?";
164         $rv;
165 }
166
167 sub valid_inbox_name ($) {
168         my ($name) = @_;
169
170         # Similar rules found in git.git/remote.c::valid_remote_nick
171         # and git.git/refs.c::check_refname_component
172         # We don't reject /\.lock\z/, however, since we don't lock refs
173         if ($name eq '' || $name =~ /\@\{/ ||
174             $name =~ /\.\./ || $name =~ m![/:\?\[\]\^~\s\f[:cntrl:]\*]! ||
175             $name =~ /\A\./ || $name =~ /\.\z/) {
176                 return 0;
177         }
178
179         # Note: we allow URL-unfriendly characters; users may configure
180         # non-HTTP-accessible inboxes
181         1;
182 }
183
184 # XXX needs testing for cgit compatibility
185 # cf. cgit/scan-tree.c::add_repo
186 sub cgit_repo_merge ($$$) {
187         my ($self, $base, $repo) = @_;
188         my $path = $repo->{dir};
189         if (defined(my $se = $self->{-cgit_strict_export})) {
190                 return unless -e "$path/$se";
191         }
192         return if -e "$path/noweb";
193         # $repo = { url => 'foo.git', dir => '/path/to/foo.git' }
194         my $rel = $repo->{url};
195         unless (defined $rel) {
196                 my $off = index($path, $base, 0);
197                 if ($off != 0) {
198                         $rel = $path;
199                 } else {
200                         $rel = substr($path, length($base) + 1);
201                 }
202
203                 $rel =~ s!/\.git\z!! or
204                         $rel =~ s!/+\z!!;
205
206                 $self->{-cgit_remove_suffix} and
207                         $rel =~ s!/?\.git\z!!;
208         }
209         $self->{"coderepo.$rel.dir"} //= $path;
210         $self->{"coderepo.$rel.cgiturl"} //= $rel;
211 }
212
213 sub is_git_dir ($) {
214         my ($git_dir) = @_;
215         -d "$git_dir/objects" && -f "$git_dir/HEAD";
216 }
217
218 # XXX needs testing for cgit compatibility
219 sub scan_path_coderepo {
220         my ($self, $base, $path) = @_;
221         opendir(my $dh, $path) or do {
222                 warn "error opening directory: $path\n";
223                 return
224         };
225         my $git_dir = $path;
226         if (is_git_dir($git_dir) || is_git_dir($git_dir .= '/.git')) {
227                 my $repo = { dir => $git_dir };
228                 cgit_repo_merge($self, $base, $repo);
229                 return;
230         }
231         while (defined(my $dn = readdir $dh)) {
232                 next if $dn eq '.' || $dn eq '..';
233                 if (index($dn, '.') == 0 && !$self->{-cgit_scan_hidden_path}) {
234                         next;
235                 }
236                 my $dir = "$path/$dn";
237                 scan_path_coderepo($self, $base, $dir) if -d $dir;
238         }
239 }
240
241 sub scan_tree_coderepo ($$) {
242         my ($self, $path) = @_;
243         scan_path_coderepo($self, $path, $path);
244 }
245
246 sub scan_projects_coderepo ($$$) {
247         my ($self, $list, $path) = @_;
248         open my $fh, '<', $list or do {
249                 warn "failed to open cgit projectlist=$list: $!\n";
250                 return;
251         };
252         foreach (<$fh>) {
253                 chomp;
254                 scan_path_coderepo($self, $path, "$path/$_");
255         }
256 }
257
258 sub parse_cgitrc {
259         my ($self, $cgitrc, $nesting) = @_;
260         if ($nesting == 0) {
261                 # defaults:
262                 my %s = map { $_ => 1 } qw(/cgit.css /cgit.png
263                                                 /favicon.ico /robots.txt);
264                 $self->{-cgit_static} = \%s;
265         }
266
267         # same limit as cgit/configfile.c::parse_configfile
268         return if $nesting > 8;
269
270         open my $fh, '<', $cgitrc or do {
271                 warn "failed to open cgitrc=$cgitrc: $!\n";
272                 return;
273         };
274
275         # FIXME: this doesn't support macro expansion via $VARS, yet
276         my $repo;
277         foreach (<$fh>) {
278                 chomp;
279                 if (m!\Arepo\.url=(.+?)/*\z!) {
280                         my $nick = $1;
281                         cgit_repo_merge($self, $repo->{dir}, $repo) if $repo;
282                         $repo = { url => $nick };
283                 } elsif (m!\Arepo\.path=(.+)\z!) {
284                         if (defined $repo) {
285                                 $repo->{dir} = $1;
286                         } else {
287                                 warn "$_ without repo.url\n";
288                         }
289                 } elsif (m!\Ainclude=(.+)\z!) {
290                         parse_cgitrc($self, $1, $nesting + 1);
291                 } elsif (m!\A(scan-hidden-path|remove-suffix)=([0-9]+)\z!) {
292                         my ($k, $v) = ($1, $2);
293                         $k =~ tr/-/_/;
294                         $self->{"-cgit_$k"} = $v;
295                 } elsif (m!\A(project-list|strict-export)=(.+)\z!) {
296                         my ($k, $v) = ($1, $2);
297                         $k =~ tr/-/_/;
298                         $self->{"-cgit_$k"} = $v;
299                 } elsif (m!\Ascan-path=(.+)\z!) {
300                         if (defined(my $list = $self->{-cgit_project_list})) {
301                                 scan_projects_coderepo($self, $list, $1);
302                         } else {
303                                 scan_tree_coderepo($self, $1);
304                         }
305                 } elsif (m!\A(?:css|favicon|logo|repo\.logo)=(/.+)\z!) {
306                         # absolute paths for static files via PublicInbox::Cgit
307                         $self->{-cgit_static}->{$1} = 1;
308                 }
309         }
310         cgit_repo_merge($self, $repo->{dir}, $repo) if $repo;
311 }
312
313 # parse a code repo
314 # Only git is supported at the moment, but SVN and Hg are possibilities
315 sub _fill_code_repo {
316         my ($self, $nick) = @_;
317         my $pfx = "coderepo.$nick";
318
319         # TODO: support gitweb and other repository viewers?
320         if (defined(my $cgitrc = delete $self->{-cgitrc_unparsed})) {
321                 parse_cgitrc($self, $cgitrc, 0);
322         }
323         my $dir = $self->{"$pfx.dir"}; # aka "GIT_DIR"
324         unless (defined $dir) {
325                 warn "$pfx.dir unset\n";
326                 return;
327         }
328
329         my $git = PublicInbox::Git->new($dir);
330         foreach my $t (qw(blob commit tree tag)) {
331                 $git->{$t.'_url_format'} =
332                                 _array($self->{lc("$pfx.${t}UrlFormat")});
333         }
334
335         if (my $cgits = $self->{lc("$pfx.cgitUrl")}) {
336                 $git->{cgit_url} = $cgits = _array($cgits);
337
338                 # cgit supports "/blob/?id=%s", but it's only a plain-text
339                 # display and requires an unabbreviated id=
340                 foreach my $t (qw(blob commit tag)) {
341                         $git->{$t.'_url_format'} //= map {
342                                 "$_/$t/?id=%s"
343                         } @$cgits;
344                 }
345         }
346
347         $git;
348 }
349
350 sub _git_config_bool ($) {
351         my ($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 sub _fill {
362         my ($self, $pfx) = @_;
363         my $ibx = {};
364
365         foreach my $k (qw(mainrepo filter url newsgroup
366                         infourl watch watchheader httpbackendmax
367                         replyto feedmax nntpserver indexlevel)) {
368                 my $v = $self->{"$pfx.$k"};
369                 $ibx->{$k} = $v if defined $v;
370         }
371         foreach my $k (qw(obfuscate)) {
372                 my $v = $self->{"$pfx.$k"};
373                 defined $v or next;
374                 if (defined(my $bval = _git_config_bool($v))) {
375                         $ibx->{$k} = $bval;
376                 } else {
377                         warn "Ignoring $pfx.$k=$v in config, not boolean\n";
378                 }
379         }
380         # TODO: more arrays, we should support multi-value for
381         # more things to encourage decentralization
382         foreach my $k (qw(address altid nntpmirror coderepo hide listid)) {
383                 if (defined(my $v = $self->{"$pfx.$k"})) {
384                         $ibx->{$k} = _array($v);
385                 }
386         }
387
388         return unless $ibx->{mainrepo};
389         my $name = $pfx;
390         $name =~ s/\Apublicinbox\.//;
391
392         if (!valid_inbox_name($name)) {
393                 warn "invalid inbox name: '$name'\n";
394                 return;
395         }
396
397         $ibx->{name} = $name;
398         $ibx->{-pi_config} = $self;
399         $ibx = PublicInbox::Inbox->new($ibx);
400         foreach (@{$ibx->{address}}) {
401                 my $lc_addr = lc($_);
402                 $self->{-by_addr}->{$lc_addr} = $ibx;
403                 $self->{-no_obfuscate}->{$lc_addr} = 1;
404         }
405         if (my $listids = $ibx->{listid}) {
406                 foreach my $list_id (@$listids) {
407                         $self->{-by_list_id}->{$list_id} = $ibx;
408                 }
409         }
410         if (my $ng = $ibx->{newsgroup}) {
411                 $self->{-by_newsgroup}->{$ng} = $ibx;
412         }
413         $self->{-by_name}->{$name} = $ibx;
414         if ($ibx->{obfuscate}) {
415                 $ibx->{-no_obfuscate} = $self->{-no_obfuscate};
416                 $ibx->{-no_obfuscate_re} = $self->{-no_obfuscate_re};
417                 _fill_all($self); # noop to populate -no_obfuscate
418         }
419
420         if (my $ibx_code_repos = $ibx->{coderepo}) {
421                 my $code_repos = $self->{-code_repos};
422                 my $repo_objs = $ibx->{-repo_objs} = [];
423                 foreach my $nick (@$ibx_code_repos) {
424                         my @parts = split(m!/!, $nick);
425                         my $valid = 0;
426                         $valid += valid_inbox_name($_) foreach (@parts);
427                         $valid == scalar(@parts) or next;
428
429                         my $repo = $code_repos->{$nick} //=
430                                                 _fill_code_repo($self, $nick);
431                         push @$repo_objs, $repo if $repo;
432                 }
433         }
434
435         $ibx
436 }
437
438 1;