]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Config.pm
No ext_urls
[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 }
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         $cgitrc //= $self->{'publicinbox.cgitrc'} // return;
279         if ($nesting == 0) {
280                 # defaults:
281                 my %s = map { $_ => 1 } qw(/cgit.css /cgit.png
282                                                 /favicon.ico /robots.txt);
283                 $self->{-cgit_static} = \%s;
284         }
285
286         # same limit as cgit/configfile.c::parse_configfile
287         return if $nesting > 8;
288
289         open my $fh, '<', $cgitrc or do {
290                 warn "failed to open cgitrc=$cgitrc: $!\n";
291                 return;
292         };
293
294         # FIXME: this doesn't support macro expansion via $VARS, yet
295         my $repo;
296         while (<$fh>) {
297                 chomp;
298                 if (m!\Arepo\.url=(.+?)/*\z!) {
299                         my $nick = $1;
300                         cgit_repo_merge($self, $repo->{dir}, $repo) if $repo;
301                         $repo = { url => $nick };
302                 } elsif (m!\Arepo\.path=(.+)\z!) {
303                         if (defined $repo) {
304                                 $repo->{dir} = $1;
305                         } else {
306                                 warn "$_ without repo.url\n";
307                         }
308                 } elsif (m!\Ainclude=(.+)\z!) {
309                         parse_cgitrc($self, $1, $nesting + 1);
310                 } elsif (m!\A(scan-hidden-path|remove-suffix)=([0-9]+)\z!) {
311                         my ($k, $v) = ($1, $2);
312                         $k =~ tr/-/_/;
313                         $self->{"-cgit_$k"} = $v;
314                 } elsif (m!\A(project-list|strict-export)=(.+)\z!) {
315                         my ($k, $v) = ($1, $2);
316                         $k =~ tr/-/_/;
317                         $self->{"-cgit_$k"} = $v;
318                 } elsif (m!\Ascan-path=(.+)\z!) {
319                         if (defined(my $list = $self->{-cgit_project_list})) {
320                                 scan_projects_coderepo($self, $list, $1);
321                         } else {
322                                 scan_tree_coderepo($self, $1);
323                         }
324                 } elsif (m!\A(?:css|favicon|logo|repo\.logo)=(/.+)\z!) {
325                         # absolute paths for static files via PublicInbox::Cgit
326                         $self->{-cgit_static}->{$1} = 1;
327                 } elsif (s!\Asnapshots=\s*!!) {
328                         $self->{'coderepo.snapshots'} = $_;
329                 }
330         }
331         cgit_repo_merge($self, $repo->{dir}, $repo) if $repo;
332 }
333
334 # parse a code repo, only git is supported at the moment
335 sub fill_code_repo {
336         my ($self, $nick) = @_;
337         my $pfx = "coderepo.$nick";
338         my $dir = $self->{"$pfx.dir"} // do { # aka "GIT_DIR"
339                 warn "$pfx.dir unset\n";
340                 return;
341         };
342         my $git = PublicInbox::Git->new($dir);
343         if (defined(my $cgits = $self->{"$pfx.cgiturl"})) {
344                 $git->{cgit_url} = $cgits = _array($cgits);
345                 $self->{"$pfx.cgiturl"} = $cgits;
346         }
347         $git->{nick} = $nick;
348         $git;
349 }
350
351 sub get_all {
352         my ($self, $key) = @_;
353         my $v = $self->{$key} // return;
354         _array($v);
355 }
356
357 sub git_bool {
358         my ($val) = $_[-1]; # $_[0] may be $self, or $val
359         if ($val =~ /\A(?:false|no|off|[\-\+]?(?:0x)?0+)\z/i) {
360                 0;
361         } elsif ($val =~ /\A(?:true|yes|on|[\-\+]?(?:0x)?[0-9]+)\z/i) {
362                 1;
363         } else {
364                 undef;
365         }
366 }
367
368 # abs_path resolves symlinks, so we want to avoid it if rel2abs
369 # is sufficient and doesn't leave "/.." or "/../"
370 sub rel2abs_collapsed {
371         require File::Spec;
372         my $p = File::Spec->rel2abs($_[-1]);
373         return $p if substr($p, -3, 3) ne '/..' && index($p, '/../') < 0;
374         require Cwd;
375         Cwd::abs_path($p);
376 }
377
378 sub get_1 {
379         my ($self, $key) = @_;
380         my $v = $self->{$key};
381         return $v if !ref($v);
382         warn "W: $key has multiple values, only using `$v->[-1]'\n";
383         $v->[-1];
384 }
385
386 sub repo_objs {
387         my ($self, $ibxish) = @_;
388         my $ibx_code_repos = $ibxish->{coderepo} // return;
389         $ibxish->{-repo_objs} // do {
390                 parse_cgitrc($self, undef, 0);
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                         for (@repo_objs) {
408                                 push @{$_->{ibx_names}}, $ibxish->{name};
409                         }
410                         $ibxish->{-repo_objs} = \@repo_objs;
411                 } else {
412                         delete $ibxish->{coderepo};
413                 }
414         }
415 }
416
417 sub _fill_ibx {
418         my ($self, $name) = @_;
419         my $pfx = "publicinbox.$name";
420         my $ibx = {};
421         for my $k (qw(watch)) {
422                 my $v = $self->{"$pfx.$k"};
423                 $ibx->{$k} = $v if defined $v;
424         }
425         for my $k (qw(filter inboxdir newsgroup replyto httpbackendmax feedmax
426                         indexlevel indexsequentialshard boost)) {
427                 my $v = get_1($self, "$pfx.$k") // next;
428                 $ibx->{$k} = $v;
429         }
430
431         # "mainrepo" is backwards compatibility:
432         my $dir = $ibx->{inboxdir} //= $self->{"$pfx.mainrepo"} // return;
433         if (index($dir, "\n") >= 0) {
434                 warn "E: `$dir' must not contain `\\n'\n";
435                 return;
436         }
437         for my $k (qw(obfuscate)) {
438                 my $v = $self->{"$pfx.$k"} // next;
439                 if (defined(my $bval = git_bool($v))) {
440                         $ibx->{$k} = $bval;
441                 } else {
442                         warn "Ignoring $pfx.$k=$v in config, not boolean\n";
443                 }
444         }
445         # TODO: more arrays, we should support multi-value for
446         # more things to encourage decentralization
447         for my $k (qw(address altid nntpmirror imapmirror
448                         coderepo hide listid url
449                         infourl watchheader
450                         nntpserver imapserver pop3server)) {
451                 my $v = $self->{"$pfx.$k"} // next;
452                 $ibx->{$k} = _array($v);
453         }
454
455         return unless valid_foo_name($name, 'publicinbox');
456         $ibx->{name} = $name;
457         $ibx->{-pi_cfg} = $self;
458         $ibx = PublicInbox::Inbox->new($ibx);
459         foreach (@{$ibx->{address}}) {
460                 my $lc_addr = lc($_);
461                 $self->{-by_addr}->{$lc_addr} = $ibx;
462                 $self->{-no_obfuscate}->{$lc_addr} = 1;
463         }
464         if (my $listids = $ibx->{listid}) {
465                 # RFC2919 section 6 stipulates "case insensitive equality"
466                 foreach my $list_id (@$listids) {
467                         $self->{-by_list_id}->{lc($list_id)} = $ibx;
468                 }
469         }
470         if (defined(my $ngname = $ibx->{newsgroup})) {
471                 if (ref($ngname)) {
472                         delete $ibx->{newsgroup};
473                         warn 'multiple newsgroups not supported: '.
474                                 join(', ', @$ngname). "\n";
475                 # Newsgroup name needs to be compatible with RFC 3977
476                 # wildmat-exact and RFC 3501 (IMAP) ATOM-CHAR.
477                 # Leave out a few chars likely to cause problems or conflicts:
478                 # '|', '<', '>', ';', '#', '$', '&',
479                 } elsif ($ngname =~ m![^A-Za-z0-9/_\.\-\~\@\+\=:]! ||
480                                 $ngname eq '') {
481                         delete $ibx->{newsgroup};
482                         warn "newsgroup name invalid: `$ngname'\n";
483                 } else {
484                         # PublicInbox::NNTPD does stricter ->nntp_usable
485                         # checks, keep this lean for startup speed
486                         $self->{-by_newsgroup}->{$ngname} = $ibx;
487                 }
488         }
489         unless (defined $ibx->{newsgroup}) { # for ->eidx_key
490                 my $abs = rel2abs_collapsed($dir);
491                 if ($abs ne $dir) {
492                         warn "W: `$dir' canonicalized to `$abs'\n";
493                         $ibx->{inboxdir} = $abs;
494                 }
495         }
496         $self->{-by_name}->{$name} = $ibx;
497         if ($ibx->{obfuscate}) {
498                 $ibx->{-no_obfuscate} = $self->{-no_obfuscate};
499                 $ibx->{-no_obfuscate_re} = $self->{-no_obfuscate_re};
500                 fill_all($self); # noop to populate -no_obfuscate
501         }
502         if (my $es = ALL($self)) {
503                 require PublicInbox::Isearch;
504                 $ibx->{isrch} = PublicInbox::Isearch->new($ibx, $es);
505         }
506         $self->{-by_eidx_key}->{$ibx->eidx_key} = $ibx;
507 }
508
509 sub _fill_ei ($$) {
510         my ($self, $name) = @_;
511         eval { require PublicInbox::ExtSearch } or return;
512         my $pfx = "extindex.$name";
513         my $d = $self->{"$pfx.topdir"} // return;
514         -d $d or return;
515         if (index($d, "\n") >= 0) {
516                 warn "E: `$d' must not contain `\\n'\n";
517                 return;
518         }
519         my $es = PublicInbox::ExtSearch->new($d);
520         for my $k (qw(indexlevel indexsequentialshard)) {
521                 my $v = get_1($self, "$pfx.$k") // next;
522                 $es->{$k} = $v;
523         }
524         for my $k (qw(coderepo hide url infourl)) {
525                 my $v = $self->{"$pfx.$k"} // next;
526                 $es->{$k} = _array($v);
527         }
528         return unless valid_foo_name($name, 'extindex');
529         $es->{name} = $name;
530         $es;
531 }
532
533 sub urlmatch {
534         my ($self, $key, $url, $try_git) = @_;
535         state $urlmatch_broken; # requires git 1.8.5
536         return if $urlmatch_broken;
537         my $file = $self->{'-f'} // default_file();
538         my $cmd = [qw/git config -z --includes --get-urlmatch/,
539                 "--file=$file", $key, $url ];
540         my $fh = popen_rd($cmd);
541         local $/ = "\0";
542         my $val = <$fh>;
543         if (!close($fh)) {
544                 undef $val;
545                 if (($? >> 8) != 1) {
546                         $urlmatch_broken = 1;
547                 } elsif ($try_git) { # n.b. this takes cwd into account
548                         $cmd = [qw(git config -z --get-urlmatch), $key, $url];
549                         $fh = popen_rd($cmd);
550                         $val = <$fh>;
551                         close($fh) or undef($val);
552                 }
553         }
554         $? = 0; # don't influence lei exit status
555         chomp $val if defined $val;
556         $val;
557 }
558
559 sub json {
560         state $json;
561         $json //= do {
562                 for my $mod (qw(Cpanel::JSON::XS JSON::MaybeXS JSON JSON::PP)) {
563                         eval "require $mod" or next;
564                         # ->ascii encodes non-ASCII to "\uXXXX"
565                         $json = $mod->new->ascii(1) and last;
566                 }
567                 $json;
568         };
569 }
570
571 sub squote_maybe ($) {
572         my ($val) = @_;
573         if ($val =~ m{([^\w@\./,\%\+\-])}) {
574                 $val =~ s/(['!])/'\\$1'/g; # '!' for csh
575                 return "'$val'";
576         }
577         $val;
578 }
579
580 1;