]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Config.pm
917939ca6f5f8de6a8809d5326ad36290dba8408
[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 warnings;
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() 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 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         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 --includes/, "--file=$file");
160         my $cmd = join(' ', @cmd);
161         my $fh = popen_rd(\@cmd);
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         # this comes from the cgit config, and AFAIK cgit only allows
194         # repos to have one URL, but that's just the PATH_INFO component,
195         # not the Host: portion
196         # $repo = { url => 'foo.git', dir => '/path/to/foo.git' }
197         my $rel = $repo->{url};
198         unless (defined $rel) {
199                 my $off = index($path, $base, 0);
200                 if ($off != 0) {
201                         $rel = $path;
202                 } else {
203                         $rel = substr($path, length($base) + 1);
204                 }
205
206                 $rel =~ s!/\.git\z!! or
207                         $rel =~ s!/+\z!!;
208
209                 $self->{-cgit_remove_suffix} and
210                         $rel =~ s!/?\.git\z!!;
211         }
212         $self->{"coderepo.$rel.dir"} //= $path;
213         $self->{"coderepo.$rel.cgiturl"} //= _array($rel);
214 }
215
216 sub is_git_dir ($) {
217         my ($git_dir) = @_;
218         -d "$git_dir/objects" && -f "$git_dir/HEAD";
219 }
220
221 # XXX needs testing for cgit compatibility
222 sub scan_path_coderepo {
223         my ($self, $base, $path) = @_;
224         opendir(my $dh, $path) or do {
225                 warn "error opening directory: $path\n";
226                 return
227         };
228         my $git_dir = $path;
229         if (is_git_dir($git_dir) || is_git_dir($git_dir .= '/.git')) {
230                 my $repo = { dir => $git_dir };
231                 cgit_repo_merge($self, $base, $repo);
232                 return;
233         }
234         while (defined(my $dn = readdir $dh)) {
235                 next if $dn eq '.' || $dn eq '..';
236                 if (index($dn, '.') == 0 && !$self->{-cgit_scan_hidden_path}) {
237                         next;
238                 }
239                 my $dir = "$path/$dn";
240                 scan_path_coderepo($self, $base, $dir) if -d $dir;
241         }
242 }
243
244 sub scan_tree_coderepo ($$) {
245         my ($self, $path) = @_;
246         scan_path_coderepo($self, $path, $path);
247 }
248
249 sub scan_projects_coderepo ($$$) {
250         my ($self, $list, $path) = @_;
251         open my $fh, '<', $list or do {
252                 warn "failed to open cgit projectlist=$list: $!\n";
253                 return;
254         };
255         while (<$fh>) {
256                 chomp;
257                 scan_path_coderepo($self, $path, "$path/$_");
258         }
259 }
260
261 sub parse_cgitrc {
262         my ($self, $cgitrc, $nesting) = @_;
263         if ($nesting == 0) {
264                 # defaults:
265                 my %s = map { $_ => 1 } qw(/cgit.css /cgit.png
266                                                 /favicon.ico /robots.txt);
267                 $self->{-cgit_static} = \%s;
268         }
269
270         # same limit as cgit/configfile.c::parse_configfile
271         return if $nesting > 8;
272
273         open my $fh, '<', $cgitrc or do {
274                 warn "failed to open cgitrc=$cgitrc: $!\n";
275                 return;
276         };
277
278         # FIXME: this doesn't support macro expansion via $VARS, yet
279         my $repo;
280         while (<$fh>) {
281                 chomp;
282                 if (m!\Arepo\.url=(.+?)/*\z!) {
283                         my $nick = $1;
284                         cgit_repo_merge($self, $repo->{dir}, $repo) if $repo;
285                         $repo = { url => $nick };
286                 } elsif (m!\Arepo\.path=(.+)\z!) {
287                         if (defined $repo) {
288                                 $repo->{dir} = $1;
289                         } else {
290                                 warn "$_ without repo.url\n";
291                         }
292                 } elsif (m!\Ainclude=(.+)\z!) {
293                         parse_cgitrc($self, $1, $nesting + 1);
294                 } elsif (m!\A(scan-hidden-path|remove-suffix)=([0-9]+)\z!) {
295                         my ($k, $v) = ($1, $2);
296                         $k =~ tr/-/_/;
297                         $self->{"-cgit_$k"} = $v;
298                 } elsif (m!\A(project-list|strict-export)=(.+)\z!) {
299                         my ($k, $v) = ($1, $2);
300                         $k =~ tr/-/_/;
301                         $self->{"-cgit_$k"} = $v;
302                 } elsif (m!\Ascan-path=(.+)\z!) {
303                         if (defined(my $list = $self->{-cgit_project_list})) {
304                                 scan_projects_coderepo($self, $list, $1);
305                         } else {
306                                 scan_tree_coderepo($self, $1);
307                         }
308                 } elsif (m!\A(?:css|favicon|logo|repo\.logo)=(/.+)\z!) {
309                         # absolute paths for static files via PublicInbox::Cgit
310                         $self->{-cgit_static}->{$1} = 1;
311                 }
312         }
313         cgit_repo_merge($self, $repo->{dir}, $repo) if $repo;
314 }
315
316 # parse a code repo
317 # Only git is supported at the moment, but SVN and Hg are possibilities
318 sub _fill_code_repo {
319         my ($self, $nick) = @_;
320         my $pfx = "coderepo.$nick";
321
322         # TODO: support gitweb and other repository viewers?
323         if (defined(my $cgitrc = delete $self->{-cgitrc_unparsed})) {
324                 parse_cgitrc($self, $cgitrc, 0);
325         }
326         my $dir = $self->{"$pfx.dir"}; # aka "GIT_DIR"
327         unless (defined $dir) {
328                 warn "$pfx.dir unset\n";
329                 return;
330         }
331
332         my $git = PublicInbox::Git->new($dir);
333         foreach my $t (qw(blob commit tree tag)) {
334                 $git->{$t.'_url_format'} =
335                                 _array($self->{lc("$pfx.${t}UrlFormat")});
336         }
337
338         if (defined(my $cgits = $self->{"$pfx.cgiturl"})) {
339                 $git->{cgit_url} = $cgits = _array($cgits);
340                 $self->{"$pfx.cgiturl"} = $cgits;
341
342                 # cgit supports "/blob/?id=%s", but it's only a plain-text
343                 # display and requires an unabbreviated id=
344                 foreach my $t (qw(blob commit tag)) {
345                         $git->{$t.'_url_format'} //= map {
346                                 "$_/$t/?id=%s"
347                         } @$cgits;
348                 }
349         }
350
351         $git;
352 }
353
354 sub _git_config_bool ($) {
355         my ($val) = @_;
356         if ($val =~ /\A(?:false|no|off|[\-\+]?(?:0x)?0+)\z/i) {
357                 0;
358         } elsif ($val =~ /\A(?:true|yes|on|[\-\+]?(?:0x)?[0-9]+)\z/i) {
359                 1;
360         } else {
361                 undef;
362         }
363 }
364
365 sub _fill {
366         my ($self, $pfx) = @_;
367         my $ibx = {};
368
369         foreach my $k (qw(inboxdir filter newsgroup
370                         watch watchheader httpbackendmax
371                         replyto feedmax nntpserver indexlevel)) {
372                 my $v = $self->{"$pfx.$k"};
373                 $ibx->{$k} = $v if defined $v;
374         }
375
376         # backwards compatibility:
377         $ibx->{inboxdir} //= $self->{"$pfx.mainrepo"};
378
379         foreach my $k (qw(obfuscate)) {
380                 my $v = $self->{"$pfx.$k"};
381                 defined $v or next;
382                 if (defined(my $bval = _git_config_bool($v))) {
383                         $ibx->{$k} = $bval;
384                 } else {
385                         warn "Ignoring $pfx.$k=$v in config, not boolean\n";
386                 }
387         }
388         # TODO: more arrays, we should support multi-value for
389         # more things to encourage decentralization
390         foreach my $k (qw(address altid nntpmirror coderepo hide listid url
391                         infourl)) {
392                 if (defined(my $v = $self->{"$pfx.$k"})) {
393                         $ibx->{$k} = _array($v);
394                 }
395         }
396
397         return unless defined($ibx->{inboxdir});
398         my $name = $pfx;
399         $name =~ s/\Apublicinbox\.//;
400
401         if (!valid_inbox_name($name)) {
402                 warn "invalid inbox name: '$name'\n";
403                 return;
404         }
405
406         $ibx->{name} = $name;
407         $ibx->{-pi_config} = $self;
408         $ibx = PublicInbox::Inbox->new($ibx);
409         foreach (@{$ibx->{address}}) {
410                 my $lc_addr = lc($_);
411                 $self->{-by_addr}->{$lc_addr} = $ibx;
412                 $self->{-no_obfuscate}->{$lc_addr} = 1;
413         }
414         if (my $listids = $ibx->{listid}) {
415                 foreach my $list_id (@$listids) {
416                         $self->{-by_list_id}->{$list_id} = $ibx;
417                 }
418         }
419         if (my $ng = $ibx->{newsgroup}) {
420                 $self->{-by_newsgroup}->{$ng} = $ibx;
421         }
422         $self->{-by_name}->{$name} = $ibx;
423         if ($ibx->{obfuscate}) {
424                 $ibx->{-no_obfuscate} = $self->{-no_obfuscate};
425                 $ibx->{-no_obfuscate_re} = $self->{-no_obfuscate_re};
426                 fill_all($self); # noop to populate -no_obfuscate
427         }
428
429         if (my $ibx_code_repos = $ibx->{coderepo}) {
430                 my $code_repos = $self->{-code_repos};
431                 my $repo_objs = $ibx->{-repo_objs} = [];
432                 foreach my $nick (@$ibx_code_repos) {
433                         my @parts = split(m!/!, $nick);
434                         my $valid = 0;
435                         $valid += valid_inbox_name($_) foreach (@parts);
436                         $valid == scalar(@parts) or next;
437
438                         my $repo = $code_repos->{$nick} //=
439                                                 _fill_code_repo($self, $nick);
440                         push @$repo_objs, $repo if $repo;
441                 }
442         }
443
444         $ibx
445 }
446
447 1;