]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Config.pm
5620bd0e6b6ce7a0f53f5959023c64ae6841b31f
[public-inbox.git] / lib / PublicInbox / Config.pm
1 # Copyright (C) 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 our $LD_PRELOAD = $ENV{LD_PRELOAD}; # only valid at startup
16 our $DEDUPE; # set to {} to dedupe or clear cache
17
18 sub _array ($) { ref($_[0]) eq 'ARRAY' ? $_[0] : [ $_[0] ] }
19
20 # returns key-value pairs of config directives in a hash
21 # if keys may be multi-value, the value is an array ref containing all values
22 sub new {
23         my ($class, $file, $errfh) = @_;
24         $file //= default_file();
25         my $self;
26         my $set_dedupe;
27         if (ref($file) eq 'SCALAR') { # used by some tests
28                 open my $fh, '<', $file or die;  # PerlIO::scalar
29                 $self = config_fh_parse($fh, "\n", '=');
30                 bless $self, $class;
31         } else {
32                 if (-f $file && $DEDUPE) {
33                         $file = rel2abs_collapsed($file);
34                         $self = $DEDUPE->{$file} and return $self;
35                         $set_dedupe = 1;
36                 }
37                 $self = git_config_dump($class, $file, $errfh);
38                 $self->{'-f'} = $file;
39         }
40         # caches
41         $self->{-by_addr} = {};
42         $self->{-by_list_id} = {};
43         $self->{-by_name} = {};
44         $self->{-by_newsgroup} = {};
45         $self->{-by_eidx_key} = {};
46         $self->{-no_obfuscate} = {};
47         $self->{-limiters} = {};
48         $self->{-code_repos} = {}; # nick => PublicInbox::Git object
49
50         if (my $no = delete $self->{'publicinbox.noobfuscate'}) {
51                 $no = _array($no);
52                 my @domains;
53                 foreach my $n (@$no) {
54                         my @n = split(/\s+/, $n);
55                         foreach (@n) {
56                                 if (/\S+@\S+/) { # full address
57                                         $self->{-no_obfuscate}->{lc $_} = 1;
58                                 } else {
59                                         # allow "example.com" or "@example.com"
60                                         s/\A@//;
61                                         push @domains, quotemeta($_);
62                                 }
63                         }
64                 }
65                 my $nod = join('|', @domains);
66                 $self->{-no_obfuscate_re} = qr/(?:$nod)\z/i;
67         }
68         if (my $css = delete $self->{'publicinbox.css'}) {
69                 $self->{css} = _array($css);
70         }
71         $DEDUPE->{$file} = $self if $set_dedupe;
72         $self;
73 }
74
75 sub noop {}
76 sub fill_all ($) { each_inbox($_[0], \&noop) }
77
78 sub _lookup_fill ($$$) {
79         my ($self, $cache, $key) = @_;
80         $self->{$cache}->{$key} // do {
81                 fill_all($self);
82                 $self->{$cache}->{$key};
83         }
84 }
85
86 sub lookup {
87         my ($self, $recipient) = @_;
88         _lookup_fill($self, '-by_addr', lc($recipient));
89 }
90
91 sub lookup_list_id {
92         my ($self, $list_id) = @_;
93         _lookup_fill($self, '-by_list_id', lc($list_id));
94 }
95
96 sub lookup_name ($$) {
97         my ($self, $name) = @_;
98         $self->{-by_name}->{$name} // _fill_ibx($self, $name);
99 }
100
101 sub lookup_ei {
102         my ($self, $name) = @_;
103         $self->{-ei_by_name}->{$name} //= _fill_ei($self, $name);
104 }
105
106 sub lookup_eidx_key {
107         my ($self, $eidx_key) = @_;
108         _lookup_fill($self, '-by_eidx_key', $eidx_key);
109 }
110
111 # special case for [extindex "all"]
112 sub ALL { lookup_ei($_[0], 'all') }
113
114 sub each_inbox {
115         my ($self, $cb, @arg) = @_;
116         # may auto-vivify if config file is non-existent:
117         foreach my $section (@{$self->{-section_order}}) {
118                 next if $section !~ m!\Apublicinbox\.([^/]+)\z!;
119                 my $ibx = lookup_name($self, $1) or next;
120                 $cb->($ibx, @arg);
121         }
122 }
123
124 sub lookup_newsgroup {
125         my ($self, $ng) = @_;
126         _lookup_fill($self, '-by_newsgroup', lc($ng));
127 }
128
129 sub limiter {
130         my ($self, $name) = @_;
131         $self->{-limiters}->{$name} //= do {
132                 require PublicInbox::Qspawn;
133                 my $max = $self->{"publicinboxlimiter.$name.max"} || 1;
134                 my $limiter = PublicInbox::Qspawn::Limiter->new($max);
135                 $limiter->setup_rlimit($name, $self);
136                 $limiter;
137         };
138 }
139
140 sub config_dir { $ENV{PI_DIR} // "$ENV{HOME}/.public-inbox" }
141
142 sub default_file {
143         $ENV{PI_CONFIG} // (config_dir() . '/config');
144 }
145
146 sub config_fh_parse ($$$) {
147         my ($fh, $rs, $fs) = @_;
148         my (%rv, %seen, @section_order, $line, $k, $v, $section, $cur, $i);
149         local $/ = $rs;
150         while (defined($line = <$fh>)) { # perf critical with giant configs
151                 $i = index($line, $fs);
152                 $k = substr($line, 0, $i);
153                 $v = substr($line, $i + 1, -1); # chop off $fs
154                 $section = substr($k, 0, rindex($k, '.'));
155                 $seen{$section} //= push(@section_order, $section);
156
157                 if (defined($cur = $rv{$k})) {
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 ($class, $file, $errfh) = @_;
174         return bless {}, $class unless -e $file;
175         my $cmd = [ qw(git config -z -l --includes), "--file=$file" ];
176         my $fh = popen_rd($cmd, undef, { 2 => $errfh // 2 });
177         my $rv = config_fh_parse($fh, "\0", "\n");
178         close $fh or die "@$cmd failed: \$?=$?\n";
179         bless $rv, $class;
180 }
181
182 sub valid_foo_name ($;$) {
183         my ($name, $pfx) = @_;
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                 warn "invalid $pfx name: `$name'\n" if $pfx;
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         $cgitrc //= $self->{'publicinbox.cgitrc'};
280         if ($nesting == 0) {
281                 # defaults:
282                 my %s = map { $_ => 1 } qw(/cgit.css /cgit.png
283                                                 /favicon.ico /robots.txt);
284                 $self->{-cgit_static} = \%s;
285         }
286
287         # same limit as cgit/configfile.c::parse_configfile
288         return if $nesting > 8;
289
290         open my $fh, '<', $cgitrc or do {
291                 warn "failed to open cgitrc=$cgitrc: $!\n";
292                 return;
293         };
294
295         # FIXME: this doesn't support macro expansion via $VARS, yet
296         my $repo;
297         while (<$fh>) {
298                 chomp;
299                 if (m!\Arepo\.url=(.+?)/*\z!) {
300                         my $nick = $1;
301                         cgit_repo_merge($self, $repo->{dir}, $repo) if $repo;
302                         $repo = { url => $nick };
303                 } elsif (m!\Arepo\.path=(.+)\z!) {
304                         if (defined $repo) {
305                                 $repo->{dir} = $1;
306                         } else {
307                                 warn "$_ without repo.url\n";
308                         }
309                 } elsif (m!\Ainclude=(.+)\z!) {
310                         parse_cgitrc($self, $1, $nesting + 1);
311                 } elsif (m!\A(scan-hidden-path|remove-suffix)=([0-9]+)\z!) {
312                         my ($k, $v) = ($1, $2);
313                         $k =~ tr/-/_/;
314                         $self->{"-cgit_$k"} = $v;
315                 } elsif (m!\A(project-list|strict-export)=(.+)\z!) {
316                         my ($k, $v) = ($1, $2);
317                         $k =~ tr/-/_/;
318                         $self->{"-cgit_$k"} = $v;
319                 } elsif (m!\Ascan-path=(.+)\z!) {
320                         if (defined(my $list = $self->{-cgit_project_list})) {
321                                 scan_projects_coderepo($self, $list, $1);
322                         } else {
323                                 scan_tree_coderepo($self, $1);
324                         }
325                 } elsif (m!\A(?:css|favicon|logo|repo\.logo)=(/.+)\z!) {
326                         # absolute paths for static files via PublicInbox::Cgit
327                         $self->{-cgit_static}->{$1} = 1;
328                 } elsif (s!\Asnapshots=\s*!!) {
329                         $self->{'coderepo.snapshots'} = $_;
330                 }
331         }
332         cgit_repo_merge($self, $repo->{dir}, $repo) if $repo;
333 }
334
335 # parse a code repo, only git is supported at the moment
336 sub fill_code_repo {
337         my ($self, $nick) = @_;
338         my $pfx = "coderepo.$nick";
339         my $dir = $self->{"$pfx.dir"} // do { # aka "GIT_DIR"
340                 warn "$pfx.dir unset\n";
341                 return;
342         };
343         my $git = PublicInbox::Git->new($dir);
344         if (defined(my $cgits = $self->{"$pfx.cgiturl"})) {
345                 $git->{cgit_url} = $cgits = _array($cgits);
346                 $self->{"$pfx.cgiturl"} = $cgits;
347         }
348         $git->{nick} = $nick;
349         $git;
350 }
351
352 sub get_all {
353         my ($self, $key) = @_;
354         my $v = $self->{$key} // return;
355         _array($v);
356 }
357
358 sub git_bool {
359         my ($val) = $_[-1]; # $_[0] may be $self, or $val
360         if ($val =~ /\A(?:false|no|off|[\-\+]?(?:0x)?0+)\z/i) {
361                 0;
362         } elsif ($val =~ /\A(?:true|yes|on|[\-\+]?(?:0x)?[0-9]+)\z/i) {
363                 1;
364         } else {
365                 undef;
366         }
367 }
368
369 # abs_path resolves symlinks, so we want to avoid it if rel2abs
370 # is sufficient and doesn't leave "/.." or "/../"
371 sub rel2abs_collapsed {
372         require File::Spec;
373         my $p = File::Spec->rel2abs($_[-1]);
374         return $p if substr($p, -3, 3) ne '/..' && index($p, '/../') < 0;
375         require Cwd;
376         Cwd::abs_path($p);
377 }
378
379 sub get_1 {
380         my ($self, $key) = @_;
381         my $v = $self->{$key};
382         return $v if !ref($v);
383         warn "W: $key has multiple values, only using `$v->[-1]'\n";
384         $v->[-1];
385 }
386
387 sub repo_objs {
388         my ($self, $ibxish) = @_;
389         my $ibx_code_repos = $ibxish->{coderepo} // return;
390         $ibxish->{-repo_objs} // do {
391                 my $code_repos = $self->{-code_repos};
392                 my @repo_objs;
393                 for my $nick (@$ibx_code_repos) {
394                         my @parts = split(m!/!, $nick);
395                         for (@parts) {
396                                 @parts = () unless valid_foo_name($_);
397                         }
398                         unless (@parts) {
399                                 warn "invalid coderepo name: `$nick'\n";
400                                 next;
401                         }
402                         my $repo = $code_repos->{$nick} //=
403                                                 fill_code_repo($self, $nick);
404                         push @repo_objs, $repo if $repo;
405                 }
406                 if (scalar @repo_objs) {
407                         require Scalar::Util;
408                         for (@repo_objs) {
409                                 push @{$_->{-ibxs}}, $ibxish;
410                                 Scalar::Util::weaken($_->{-ibxs}->[-1]);
411                         }
412                         $ibxish->{-repo_objs} = \@repo_objs;
413                 } else {
414                         delete $ibxish->{coderepo};
415                 }
416         }
417 }
418
419 sub _fill_ibx {
420         my ($self, $name) = @_;
421         my $pfx = "publicinbox.$name";
422         my $ibx = {};
423         for my $k (qw(watch)) {
424                 my $v = $self->{"$pfx.$k"};
425                 $ibx->{$k} = $v if defined $v;
426         }
427         for my $k (qw(filter inboxdir newsgroup replyto httpbackendmax feedmax
428                         indexlevel indexsequentialshard boost)) {
429                 my $v = get_1($self, "$pfx.$k") // next;
430                 $ibx->{$k} = $v;
431         }
432
433         # "mainrepo" is backwards compatibility:
434         my $dir = $ibx->{inboxdir} //= $self->{"$pfx.mainrepo"} // return;
435         if (index($dir, "\n") >= 0) {
436                 warn "E: `$dir' must not contain `\\n'\n";
437                 return;
438         }
439         for my $k (qw(obfuscate)) {
440                 my $v = $self->{"$pfx.$k"} // next;
441                 if (defined(my $bval = git_bool($v))) {
442                         $ibx->{$k} = $bval;
443                 } else {
444                         warn "Ignoring $pfx.$k=$v in config, not boolean\n";
445                 }
446         }
447         # TODO: more arrays, we should support multi-value for
448         # more things to encourage decentralization
449         for my $k (qw(address altid nntpmirror imapmirror
450                         coderepo hide listid url
451                         infourl watchheader
452                         nntpserver imapserver pop3server)) {
453                 my $v = $self->{"$pfx.$k"} // next;
454                 $ibx->{$k} = _array($v);
455         }
456
457         return unless valid_foo_name($name, 'publicinbox');
458         $ibx->{name} = $name;
459         $ibx->{-pi_cfg} = $self;
460         $ibx = PublicInbox::Inbox->new($ibx);
461         foreach (@{$ibx->{address}}) {
462                 my $lc_addr = lc($_);
463                 $self->{-by_addr}->{$lc_addr} = $ibx;
464                 $self->{-no_obfuscate}->{$lc_addr} = 1;
465         }
466         if (my $listids = $ibx->{listid}) {
467                 # RFC2919 section 6 stipulates "case insensitive equality"
468                 foreach my $list_id (@$listids) {
469                         $self->{-by_list_id}->{lc($list_id)} = $ibx;
470                 }
471         }
472         if (defined(my $ngname = $ibx->{newsgroup})) {
473                 if (ref($ngname)) {
474                         delete $ibx->{newsgroup};
475                         warn 'multiple newsgroups not supported: '.
476                                 join(', ', @$ngname). "\n";
477                 # Newsgroup name needs to be compatible with RFC 3977
478                 # wildmat-exact and RFC 3501 (IMAP) ATOM-CHAR.
479                 # Leave out a few chars likely to cause problems or conflicts:
480                 # '|', '<', '>', ';', '#', '$', '&',
481                 } elsif ($ngname =~ m![^A-Za-z0-9/_\.\-\~\@\+\=:]! ||
482                                 $ngname eq '') {
483                         delete $ibx->{newsgroup};
484                         warn "newsgroup name invalid: `$ngname'\n";
485                 } else {
486                         # PublicInbox::NNTPD does stricter ->nntp_usable
487                         # checks, keep this lean for startup speed
488                         $self->{-by_newsgroup}->{$ngname} = $ibx;
489                 }
490         }
491         unless (defined $ibx->{newsgroup}) { # for ->eidx_key
492                 my $abs = rel2abs_collapsed($dir);
493                 if ($abs ne $dir) {
494                         warn "W: `$dir' canonicalized to `$abs'\n";
495                         $ibx->{inboxdir} = $abs;
496                 }
497         }
498         $self->{-by_name}->{$name} = $ibx;
499         if ($ibx->{obfuscate}) {
500                 $ibx->{-no_obfuscate} = $self->{-no_obfuscate};
501                 $ibx->{-no_obfuscate_re} = $self->{-no_obfuscate_re};
502                 fill_all($self); # noop to populate -no_obfuscate
503         }
504         if (my $es = ALL($self)) {
505                 require PublicInbox::Isearch;
506                 $ibx->{isrch} = PublicInbox::Isearch->new($ibx, $es);
507         }
508         $self->{-by_eidx_key}->{$ibx->eidx_key} = $ibx;
509 }
510
511 sub _fill_ei ($$) {
512         my ($self, $name) = @_;
513         eval { require PublicInbox::ExtSearch } or return;
514         my $pfx = "extindex.$name";
515         my $d = $self->{"$pfx.topdir"} // return;
516         -d $d or return;
517         if (index($d, "\n") >= 0) {
518                 warn "E: `$d' must not contain `\\n'\n";
519                 return;
520         }
521         my $es = PublicInbox::ExtSearch->new($d);
522         for my $k (qw(indexlevel indexsequentialshard)) {
523                 my $v = get_1($self, "$pfx.$k") // next;
524                 $es->{$k} = $v;
525         }
526         for my $k (qw(coderepo hide url infourl)) {
527                 my $v = $self->{"$pfx.$k"} // next;
528                 $es->{$k} = _array($v);
529         }
530         return unless valid_foo_name($name, 'extindex');
531         $es->{name} = $name;
532         $es;
533 }
534
535 sub urlmatch {
536         my ($self, $key, $url, $try_git) = @_;
537         state $urlmatch_broken; # requires git 1.8.5
538         return if $urlmatch_broken;
539         my $file = $self->{'-f'} // default_file();
540         my $cmd = [qw/git config -z --includes --get-urlmatch/,
541                 "--file=$file", $key, $url ];
542         my $fh = popen_rd($cmd);
543         local $/ = "\0";
544         my $val = <$fh>;
545         if (!close($fh)) {
546                 undef $val;
547                 if (($? >> 8) != 1) {
548                         $urlmatch_broken = 1;
549                 } elsif ($try_git) { # n.b. this takes cwd into account
550                         $cmd = [qw(git config -z --get-urlmatch), $key, $url];
551                         $fh = popen_rd($cmd);
552                         $val = <$fh>;
553                         close($fh) or undef($val);
554                 }
555         }
556         $? = 0; # don't influence lei exit status
557         chomp $val if defined $val;
558         $val;
559 }
560
561 sub json {
562         state $json;
563         $json //= do {
564                 for my $mod (qw(Cpanel::JSON::XS JSON::MaybeXS JSON JSON::PP)) {
565                         eval "require $mod" or next;
566                         # ->ascii encodes non-ASCII to "\uXXXX"
567                         $json = $mod->new->ascii(1) and last;
568                 }
569                 $json;
570         };
571 }
572
573 sub squote_maybe ($) {
574         my ($val) = @_;
575         if ($val =~ m{([^\w@\./,\%\+\-])}) {
576                 $val =~ s/(['!])/'\\$1'/g; # '!' for csh
577                 return "'$val'";
578         }
579         $val;
580 }
581
582 1;