]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Config.pm
www_coderepo: an alternative to cgit
[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         $self->{-cgitrc_unparsed} = $self->{'publicinbox.cgitrc'};
50
51         if (my $no = delete $self->{'publicinbox.noobfuscate'}) {
52                 $no = _array($no);
53                 my @domains;
54                 foreach my $n (@$no) {
55                         my @n = split(/\s+/, $n);
56                         foreach (@n) {
57                                 if (/\S+@\S+/) { # full address
58                                         $self->{-no_obfuscate}->{lc $_} = 1;
59                                 } else {
60                                         # allow "example.com" or "@example.com"
61                                         s/\A@//;
62                                         push @domains, quotemeta($_);
63                                 }
64                         }
65                 }
66                 my $nod = join('|', @domains);
67                 $self->{-no_obfuscate_re} = qr/(?:$nod)\z/i;
68         }
69         if (my $css = delete $self->{'publicinbox.css'}) {
70                 $self->{css} = _array($css);
71         }
72         $DEDUPE->{$file} = $self if $set_dedupe;
73         $self;
74 }
75
76 sub noop {}
77 sub fill_all ($) { each_inbox($_[0], \&noop) }
78
79 sub _lookup_fill ($$$) {
80         my ($self, $cache, $key) = @_;
81         $self->{$cache}->{$key} // do {
82                 fill_all($self);
83                 $self->{$cache}->{$key};
84         }
85 }
86
87 sub lookup {
88         my ($self, $recipient) = @_;
89         _lookup_fill($self, '-by_addr', lc($recipient));
90 }
91
92 sub lookup_list_id {
93         my ($self, $list_id) = @_;
94         _lookup_fill($self, '-by_list_id', lc($list_id));
95 }
96
97 sub lookup_name ($$) {
98         my ($self, $name) = @_;
99         $self->{-by_name}->{$name} // _fill_ibx($self, $name);
100 }
101
102 sub lookup_ei {
103         my ($self, $name) = @_;
104         $self->{-ei_by_name}->{$name} //= _fill_ei($self, $name);
105 }
106
107 sub lookup_eidx_key {
108         my ($self, $eidx_key) = @_;
109         _lookup_fill($self, '-by_eidx_key', $eidx_key);
110 }
111
112 # special case for [extindex "all"]
113 sub ALL { lookup_ei($_[0], 'all') }
114
115 sub each_inbox {
116         my ($self, $cb, @arg) = @_;
117         # may auto-vivify if config file is non-existent:
118         foreach my $section (@{$self->{-section_order}}) {
119                 next if $section !~ m!\Apublicinbox\.([^/]+)\z!;
120                 my $ibx = lookup_name($self, $1) or next;
121                 $cb->($ibx, @arg);
122         }
123 }
124
125 sub lookup_newsgroup {
126         my ($self, $ng) = @_;
127         _lookup_fill($self, '-by_newsgroup', lc($ng));
128 }
129
130 sub limiter {
131         my ($self, $name) = @_;
132         $self->{-limiters}->{$name} //= do {
133                 require PublicInbox::Qspawn;
134                 my $max = $self->{"publicinboxlimiter.$name.max"} || 1;
135                 my $limiter = PublicInbox::Qspawn::Limiter->new($max);
136                 $limiter->setup_rlimit($name, $self);
137                 $limiter;
138         };
139 }
140
141 sub config_dir { $ENV{PI_DIR} // "$ENV{HOME}/.public-inbox" }
142
143 sub default_file {
144         $ENV{PI_CONFIG} // (config_dir() . '/config');
145 }
146
147 sub config_fh_parse ($$$) {
148         my ($fh, $rs, $fs) = @_;
149         my (%rv, %seen, @section_order, $line, $k, $v, $section, $cur, $i);
150         local $/ = $rs;
151         while (defined($line = <$fh>)) { # perf critical with giant configs
152                 $i = index($line, $fs);
153                 $k = substr($line, 0, $i);
154                 $v = substr($line, $i + 1, -1); # chop off $fs
155                 $section = substr($k, 0, rindex($k, '.'));
156                 $seen{$section} //= push(@section_order, $section);
157
158                 if (defined($cur = $rv{$k})) {
159                         if (ref($cur) eq "ARRAY") {
160                                 push @$cur, $v;
161                         } else {
162                                 $rv{$k} = [ $cur, $v ];
163                         }
164                 } else {
165                         $rv{$k} = $v;
166                 }
167         }
168         $rv{-section_order} = \@section_order;
169
170         \%rv;
171 }
172
173 sub git_config_dump {
174         my ($class, $file, $errfh) = @_;
175         return bless {}, $class unless -e $file;
176         my $cmd = [ qw(git config -z -l --includes), "--file=$file" ];
177         my $fh = popen_rd($cmd, undef, { 2 => $errfh // 2 });
178         my $rv = config_fh_parse($fh, "\0", "\n");
179         close $fh or die "@$cmd failed: \$?=$?\n";
180         bless $rv, $class;
181 }
182
183 sub valid_foo_name ($;$) {
184         my ($name, $pfx) = @_;
185
186         # Similar rules found in git.git/remote.c::valid_remote_nick
187         # and git.git/refs.c::check_refname_component
188         # We don't reject /\.lock\z/, however, since we don't lock refs
189         if ($name eq '' || $name =~ /\@\{/ ||
190             $name =~ /\.\./ || $name =~ m![/:\?\[\]\^~\s\f[:cntrl:]\*]! ||
191             $name =~ /\A\./ || $name =~ /\.\z/) {
192                 warn "invalid $pfx name: `$name'\n" if $pfx;
193                 return 0;
194         }
195
196         # Note: we allow URL-unfriendly characters; users may configure
197         # non-HTTP-accessible inboxes
198         1;
199 }
200
201 # XXX needs testing for cgit compatibility
202 # cf. cgit/scan-tree.c::add_repo
203 sub cgit_repo_merge ($$$) {
204         my ($self, $base, $repo) = @_;
205         my $path = $repo->{dir};
206         if (defined(my $se = $self->{-cgit_strict_export})) {
207                 return unless -e "$path/$se";
208         }
209         return if -e "$path/noweb";
210         # this comes from the cgit config, and AFAIK cgit only allows
211         # repos to have one URL, but that's just the PATH_INFO component,
212         # not the Host: portion
213         # $repo = { url => 'foo.git', dir => '/path/to/foo.git' }
214         my $rel = $repo->{url};
215         unless (defined $rel) {
216                 my $off = index($path, $base, 0);
217                 if ($off != 0) {
218                         $rel = $path;
219                 } else {
220                         $rel = substr($path, length($base) + 1);
221                 }
222
223                 $rel =~ s!/\.git\z!! or
224                         $rel =~ s!/+\z!!;
225
226                 $self->{-cgit_remove_suffix} and
227                         $rel =~ s!/?\.git\z!!;
228         }
229         $self->{"coderepo.$rel.dir"} //= $path;
230         $self->{"coderepo.$rel.cgiturl"} //= _array($rel);
231 }
232
233 sub is_git_dir ($) {
234         my ($git_dir) = @_;
235         -d "$git_dir/objects" && -f "$git_dir/HEAD";
236 }
237
238 # XXX needs testing for cgit compatibility
239 sub scan_path_coderepo {
240         my ($self, $base, $path) = @_;
241         opendir(my $dh, $path) or do {
242                 warn "error opening directory: $path\n";
243                 return
244         };
245         my $git_dir = $path;
246         if (is_git_dir($git_dir) || is_git_dir($git_dir .= '/.git')) {
247                 my $repo = { dir => $git_dir };
248                 cgit_repo_merge($self, $base, $repo);
249                 return;
250         }
251         while (defined(my $dn = readdir $dh)) {
252                 next if $dn eq '.' || $dn eq '..';
253                 if (index($dn, '.') == 0 && !$self->{-cgit_scan_hidden_path}) {
254                         next;
255                 }
256                 my $dir = "$path/$dn";
257                 scan_path_coderepo($self, $base, $dir) if -d $dir;
258         }
259 }
260
261 sub scan_tree_coderepo ($$) {
262         my ($self, $path) = @_;
263         scan_path_coderepo($self, $path, $path);
264 }
265
266 sub scan_projects_coderepo ($$$) {
267         my ($self, $list, $path) = @_;
268         open my $fh, '<', $list or do {
269                 warn "failed to open cgit projectlist=$list: $!\n";
270                 return;
271         };
272         while (<$fh>) {
273                 chomp;
274                 scan_path_coderepo($self, $path, "$path/$_");
275         }
276 }
277
278 sub parse_cgitrc {
279         my ($self, $cgitrc, $nesting) = @_;
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                 }
329         }
330         cgit_repo_merge($self, $repo->{dir}, $repo) if $repo;
331 }
332
333 # parse a code repo, only git is supported at the moment
334 sub fill_code_repo {
335         my ($self, $nick) = @_;
336         my $pfx = "coderepo.$nick";
337         my $dir = $self->{"$pfx.dir"} // do { # aka "GIT_DIR"
338                 warn "$pfx.dir unset\n";
339                 return;
340         };
341         my $git = PublicInbox::Git->new($dir);
342         if (defined(my $cgits = $self->{"$pfx.cgiturl"})) {
343                 $git->{cgit_url} = $cgits = _array($cgits);
344                 $self->{"$pfx.cgiturl"} = $cgits;
345         }
346         $git->{nick} = $nick;
347         $git;
348 }
349
350 sub get_all {
351         my ($self, $key) = @_;
352         my $v = $self->{$key} // return;
353         _array($v);
354 }
355
356 sub git_bool {
357         my ($val) = $_[-1]; # $_[0] may be $self, or $val
358         if ($val =~ /\A(?:false|no|off|[\-\+]?(?:0x)?0+)\z/i) {
359                 0;
360         } elsif ($val =~ /\A(?:true|yes|on|[\-\+]?(?:0x)?[0-9]+)\z/i) {
361                 1;
362         } else {
363                 undef;
364         }
365 }
366
367 # abs_path resolves symlinks, so we want to avoid it if rel2abs
368 # is sufficient and doesn't leave "/.." or "/../"
369 sub rel2abs_collapsed {
370         require File::Spec;
371         my $p = File::Spec->rel2abs($_[-1]);
372         return $p if substr($p, -3, 3) ne '/..' && index($p, '/../') < 0;
373         require Cwd;
374         Cwd::abs_path($p);
375 }
376
377 sub get_1 {
378         my ($self, $key) = @_;
379         my $v = $self->{$key};
380         return $v if !ref($v);
381         warn "W: $key has multiple values, only using `$v->[-1]'\n";
382         $v->[-1];
383 }
384
385 sub repo_objs {
386         my ($self, $ibxish) = @_;
387         my $ibx_code_repos = $ibxish->{coderepo} // return;
388         $ibxish->{-repo_objs} // do {
389                 my $code_repos = $self->{-code_repos};
390                 my @repo_objs;
391                 for my $nick (@$ibx_code_repos) {
392                         my @parts = split(m!/!, $nick);
393                         for (@parts) {
394                                 @parts = () unless valid_foo_name($_);
395                         }
396                         unless (@parts) {
397                                 warn "invalid coderepo name: `$nick'\n";
398                                 next;
399                         }
400                         my $repo = $code_repos->{$nick} //=
401                                                 fill_code_repo($self, $nick);
402                         push @repo_objs, $repo if $repo;
403                 }
404                 if (scalar @repo_objs) {
405                         $ibxish->{-repo_objs} = \@repo_objs;
406                 } else {
407                         delete $ibxish->{coderepo};
408                 }
409         }
410 }
411
412 sub _fill_ibx {
413         my ($self, $name) = @_;
414         my $pfx = "publicinbox.$name";
415         my $ibx = {};
416         for my $k (qw(watch)) {
417                 my $v = $self->{"$pfx.$k"};
418                 $ibx->{$k} = $v if defined $v;
419         }
420         for my $k (qw(filter inboxdir newsgroup replyto httpbackendmax feedmax
421                         indexlevel indexsequentialshard boost)) {
422                 my $v = get_1($self, "$pfx.$k") // next;
423                 $ibx->{$k} = $v;
424         }
425
426         # "mainrepo" is backwards compatibility:
427         my $dir = $ibx->{inboxdir} //= $self->{"$pfx.mainrepo"} // return;
428         if (index($dir, "\n") >= 0) {
429                 warn "E: `$dir' must not contain `\\n'\n";
430                 return;
431         }
432         for my $k (qw(obfuscate)) {
433                 my $v = $self->{"$pfx.$k"} // next;
434                 if (defined(my $bval = git_bool($v))) {
435                         $ibx->{$k} = $bval;
436                 } else {
437                         warn "Ignoring $pfx.$k=$v in config, not boolean\n";
438                 }
439         }
440         # TODO: more arrays, we should support multi-value for
441         # more things to encourage decentralization
442         for my $k (qw(address altid nntpmirror imapmirror
443                         coderepo hide listid url
444                         infourl watchheader
445                         nntpserver imapserver pop3server)) {
446                 my $v = $self->{"$pfx.$k"} // next;
447                 $ibx->{$k} = _array($v);
448         }
449
450         return unless valid_foo_name($name, 'publicinbox');
451         $ibx->{name} = $name;
452         $ibx->{-pi_cfg} = $self;
453         $ibx = PublicInbox::Inbox->new($ibx);
454         foreach (@{$ibx->{address}}) {
455                 my $lc_addr = lc($_);
456                 $self->{-by_addr}->{$lc_addr} = $ibx;
457                 $self->{-no_obfuscate}->{$lc_addr} = 1;
458         }
459         if (my $listids = $ibx->{listid}) {
460                 # RFC2919 section 6 stipulates "case insensitive equality"
461                 foreach my $list_id (@$listids) {
462                         $self->{-by_list_id}->{lc($list_id)} = $ibx;
463                 }
464         }
465         if (defined(my $ngname = $ibx->{newsgroup})) {
466                 if (ref($ngname)) {
467                         delete $ibx->{newsgroup};
468                         warn 'multiple newsgroups not supported: '.
469                                 join(', ', @$ngname). "\n";
470                 # Newsgroup name needs to be compatible with RFC 3977
471                 # wildmat-exact and RFC 3501 (IMAP) ATOM-CHAR.
472                 # Leave out a few chars likely to cause problems or conflicts:
473                 # '|', '<', '>', ';', '#', '$', '&',
474                 } elsif ($ngname =~ m![^A-Za-z0-9/_\.\-\~\@\+\=:]! ||
475                                 $ngname eq '') {
476                         delete $ibx->{newsgroup};
477                         warn "newsgroup name invalid: `$ngname'\n";
478                 } else {
479                         # PublicInbox::NNTPD does stricter ->nntp_usable
480                         # checks, keep this lean for startup speed
481                         $self->{-by_newsgroup}->{$ngname} = $ibx;
482                 }
483         }
484         unless (defined $ibx->{newsgroup}) { # for ->eidx_key
485                 my $abs = rel2abs_collapsed($dir);
486                 if ($abs ne $dir) {
487                         warn "W: `$dir' canonicalized to `$abs'\n";
488                         $ibx->{inboxdir} = $abs;
489                 }
490         }
491         $self->{-by_name}->{$name} = $ibx;
492         if ($ibx->{obfuscate}) {
493                 $ibx->{-no_obfuscate} = $self->{-no_obfuscate};
494                 $ibx->{-no_obfuscate_re} = $self->{-no_obfuscate_re};
495                 fill_all($self); # noop to populate -no_obfuscate
496         }
497         if (my $es = ALL($self)) {
498                 require PublicInbox::Isearch;
499                 $ibx->{isrch} = PublicInbox::Isearch->new($ibx, $es);
500         }
501         $self->{-by_eidx_key}->{$ibx->eidx_key} = $ibx;
502 }
503
504 sub _fill_ei ($$) {
505         my ($self, $name) = @_;
506         eval { require PublicInbox::ExtSearch } or return;
507         my $pfx = "extindex.$name";
508         my $d = $self->{"$pfx.topdir"} // return;
509         -d $d or return;
510         if (index($d, "\n") >= 0) {
511                 warn "E: `$d' must not contain `\\n'\n";
512                 return;
513         }
514         my $es = PublicInbox::ExtSearch->new($d);
515         for my $k (qw(indexlevel indexsequentialshard)) {
516                 my $v = get_1($self, "$pfx.$k") // next;
517                 $es->{$k} = $v;
518         }
519         for my $k (qw(coderepo hide url infourl)) {
520                 my $v = $self->{"$pfx.$k"} // next;
521                 $es->{$k} = _array($v);
522         }
523         return unless valid_foo_name($name, 'extindex');
524         $es->{name} = $name;
525         $es;
526 }
527
528 sub urlmatch {
529         my ($self, $key, $url) = @_;
530         state $urlmatch_broken; # requires git 1.8.5
531         return if $urlmatch_broken;
532         my $file = $self->{'-f'} // default_file();
533         my $cmd = [qw/git config -z --includes --get-urlmatch/,
534                 "--file=$file", $key, $url ];
535         my $fh = popen_rd($cmd);
536         local $/ = "\0";
537         my $val = <$fh>;
538         if (close($fh)) {
539                 chomp($val);
540                 $val;
541         } else {
542                 $urlmatch_broken = 1 if (($? >> 8) != 1);
543                 undef;
544         }
545 }
546
547 sub json {
548         state $json;
549         $json //= do {
550                 for my $mod (qw(Cpanel::JSON::XS JSON::MaybeXS JSON JSON::PP)) {
551                         eval "require $mod" or next;
552                         # ->ascii encodes non-ASCII to "\uXXXX"
553                         $json = $mod->new->ascii(1) and last;
554                 }
555                 $json;
556         };
557 }
558
559 sub squote_maybe ($) {
560         my ($val) = @_;
561         if ($val =~ m{([^\w@\./,\%\+\-])}) {
562                 $val =~ s/(['!])/'\\$1'/g; # '!' for csh
563                 return "'$val'";
564         }
565         $val;
566 }
567
568 1;