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