blib/lib/WWW/Lk4.pm untested

filter: Statementstmt 0.0% 0 / 344 Branchbran 0.0% 0 / 118 Conditioncond 0.0% 0 / 23 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 26 Podpod 0.0% 0 / 22 totaltotal 0.0% 0 / 533 CC 60 SCAR 42.0
CC
60
Cov
0%
read_config_file
210.0
resolve
90.0
compile_menu
90.0
CRAP 66.5
1 package WWW::Lk4;
2  
3 use strict;
4 use warnings;
5  
6 use DB_File;
7  
8 our $VERSION = '0.11';
9  
10 use constant KEYJOINER => "\x1c";
11  
12 # --- Public methods
13  
14 sub new {
15 my ($cls, %arg) = @_;
16 my @contexts = ( { 'name' => '$self', 'stash' => {} } );
17 my %scopes;
18 my %file2data;
19 my $self = bless {
20 'config_file' => '/etc/lk4/lk4.conf',
21 'data_dir' => '/var/local/lk4',
22 %arg,
23 'contexts' => \@contexts,
24 'scopes' => \%scopes,
25 'file2data' => \%file2data,
26 }, $cls;
27 $self->load_config;
28 return $self;
29 }
30  
31 sub resolve {
32 my ($self, $req, %env) = @_;
33 # Extract path info components and query string from the requested URI
34 # These are normalized to remove extra slashes, etc.
35 # For example, this:
36 # /proxy/emerson/?url=http://example.com/foo/bar
37 # Yields two path components:
38 # /proxy
39 # /emerson
40 # And the query string:
41 # ?url=http://example.com/foo/bar
42 my ($path_info, $query_string);
43 if ($req =~ /^([^?]*)(?:(\?.*))?/) {
44 ($path_info, $query_string) = ($1, $2);
45 $query_string = '' if !defined $query_string;
46 }
47 else {
48 ($path_info, $query_string) = ('/', '');
49 }
50 $path_info =~ s{/*$}{/};
51 $path_info =~ s{/\./}{//}g;
52 $path_info =~ tr{/}{/}s;
53 my @path = ('', $path_info =~ m{(/[^/]+)}g);
54  
55 # Look for a context under which to redirect
56 # For example, we might have this in a config file:
57 # under /proxy {
58 # forward ...
59 # }
60 undef $path_info;
61 my $scope;
62 my $scopes = $self->{'scopes'};
63 foreach (reverse 0..$#path) {
64 my $str = join '', @path[0..$_];
65 next if !defined ($scope = $scopes->{$str});
66 splice @path, 0, $_ + 1;
67 $path_info = join '', @path;
68 $path_info =~ s{(?<=.)/$}{};
69 last;
70 }
71 return err(404, "$req :: no forward") if !defined $path_info;
72 my $contexts = $self->{'contexts'};
73 push @$contexts, {
74 'name' => '$request',
75 'stash' => \%env,
76 };
77 my $forwards = $scope->{'forwards'};
78 my %result = ('ok' => 0);
79 foreach (@$forwards) {
80 my $result;
81 eval {
82 $result = $_->($scope, $path_info, $query_string);
83 if (defined $result) {
84 $result{'ok'} = 1;
85 if (ref($result) eq 'HASH') {
86 $result{'menu'} = $result;
87 }
88 else {
89 $result{'uri'} = $result;
90 }
91 }
92 };
93 if ($@) {
94 chomp $@;
95 $result{'message'} = "$req :: $@";
96 }
97 last if defined $result;
98 }
99 pop @$contexts;
100 return %result;
101 }
102  
103 sub let {
104 my ($self, %arg) = @_;
105 $self->{'contexts'}->[0]->{'stash'}{$_} = $arg{$_} for keys %arg;
106 return $self;
107 }
108  
109 sub read_config_file {
110 my ($self, $f) = @_;
111 open my $fh, '<', $f or die "Can't open config file $f: $!";
112 my $scopes = $self->{'scopes'};
113 my $contexts = $self->{'contexts'};
114 while (<$fh>) {
115 normalize($_);
116 next if /^#|^$/;
117 my $stash = $contexts->[-1]->{'stash'};
118 if (/^let (\S+) = (.*)$/) {
119 $stash->{$1} = $self->compile_general_expression($2);
120 }
121 elsif (/^under (\S+) {$/) {
122 my $context = $scopes->{$1} = {
123 'name' => $1,
124 'stash' => {},
125 'patterns' => {},
126 };
127 push @$contexts, $context;
128 }
129 elsif ($_ eq '}') {
130 pop @$contexts;
131 die "Underflow" if @$contexts == 0;
132 }
133 elsif (/^function (\S+) :file (\S+)/) {
134 my ($key, $code) = $self->compile_function_from_file($1, $2);
135 $stash->{$key} = $code;
136 }
137 elsif (/^function (\S+) {$/) {
138 my ($key, $code) = $self->compile_function_inline($1, $fh);
139 $stash->{$key} = $code;
140 }
141 elsif (/^function (\S+) :perl {$/) {
142 my ($key, $code) = $self->compile_perl_function_inline($1, $fh);
143 $stash->{$key} = $code;
144 }
145 elsif (/^list (\S+) {$/) {
146 my ($key, $code) = $self->compile_list($1, $fh);
147 $stash->{$key} = $code;
148 }
149 elsif (/^menu (\S+) {/) {
150 my ($key, $code) = $self->compile_menu($1, $fh);
151 $stash->{$key} = $code;
152 }
153 elsif (/^menu (\S+) "(.+)" :perl {/) {
154 my ($key, $code) = $self->compile_perl_menu($1, $2, $fh);
155 $stash->{$key} = $code;
156 }
157 elsif (/^forward(?: \+(\d\d\d))? (\S+) to (.+)$/) {
158 # forward /foo to http://example.com/bar
159 # forward +301 /foo to http://example.com/bar
160 my ($status, $from, $to) = ($1, $2, $3);
161 push @{ $contexts->[-1]->{'forwards'} ||= [] }, $self->compile_forward($from, $to, $status);
162 }
163 elsif (/^match (\S+) to (.*)/) {
164 $contexts->[-1]->{'patterns'}{$1} = qr/$2/;
165 }
166 else {
167 die "Syntax error: $_";
168 }
169 }
170 close $fh;
171 }
172  
173 sub compile_data_reader {
174 my ($self, $f, $arity) = @_;
175 return sub {
176 my ($c) = @_;
177 my @debug = ($f);
178 return $self->{'file2data'}->{$f} if exists $self->{'file2data'}->{$f};
179 my %data;
180 my $fdb = "$f.db";
181 if (-e $fdb && ( ! -e $f || -M $fdb < -M $f) ) {
182 # Use $f.db
183 tie %data, 'DB_File', $fdb, O_RDONLY, 0644, $DB_HASH
184 or die;
185 }
186 elsif (-e $f) {
187 open my $fh, '<', $f or die "Can't open data file $f: $!";
188 while (<$fh>) {
189 chomp;
190 my @key = split /\t/;
191 my $val = pop @key;
192 die "Bad arity: @key (should be $arity)" if $arity != @key;
193 $data{join(KEYJOINER, @key)} = $val;
194 }
195 close $fh;
196 }
197 return $self->{'file2data'}->{$f} = \%data;
198 }
199 }
200  
201 sub compile_menu {
202 my ($self, $spec, $fh) = @_;
203 my ($key, @params) = parse_spec($spec);
204 my %menu;
205 my @items;
206 my ($var, $list);
207 my ($uri, $label);
208 while (<$fh>) {
209 normalize($_);
210 if (/^}$/) {
211 last;
212 }
213 elsif (/^(title|template) (.+)$/) {
214 $menu{$1} = $2;
215 }
216 elsif (/^item (\S+) (.+)$/) {
217 my ($uri, $label) = ($1, $2);
218 push @items, {
219 'uri' => $self->compile_general_expression($uri),
220 'label' => $label,
221 };
222 }
223 elsif (/^for (\S+) in (\S+) {$/) {
224 ($var, $list) = ($1, $2);
225 while (<$fh>) {
226 normalize($_);
227 if (/^}$/) {
228 last;
229 }
230 elsif (/^item (\S+) (.+)$/) {
231 ($uri, $label) = ($1, $2);
232 }
233 }
234 die "Item not defined" if !defined $uri;
235 $uri = $self->compile_general_expression($uri);
236 $label = $self->compile_general_expression($label);
237 }
238 else {
239 die;
240 }
241 }
242 if (@items) {
243 return $key, sub {
244 my @debug = ($spec, $key, @params); # Just for debugging
245 my ($c) = @_;
246 return {
247 %menu,
248 'items' => [ map { evaluate($_, $c) } @items ],
249 };
250 };
251 }
252 else {
253 return $key, sub {
254 my @debug = ($spec, $key, @params, $var, $list, $uri, $label); # Just for debugging
255 my ($c) = @_;
256 my @list = @{ $c->{$list} || die "No such list: $list" };
257 return {
258 %menu,
259 'items' => [ map {
260 my %c = ( %$c, $var => $_ );
261 evaluate(+{'uri' => $uri, 'label' => $label}, \%c);
262 } @list ],
263 }
264 };
265 }
266 }
267  
268 sub compile_perl_menu {
269 my ($self, $spec, $title, $fh) = @_;
270 my ($key, @params) = parse_spec($spec);
271 my $src = "sub {\n";
272 while (<$fh>) {
273 die if !defined $_;
274 $src .= $_;
275 last if /^\s*}\s*$/;
276 }
277 my $inner_sub = eval $src;
278 return $key, sub {
279 my @debug = ($spec, $src); # Just for debugging
280 my $c = shift;
281 return $inner_sub->('title' => $title);
282 };
283 }
284  
285 sub compile_forward {
286 my ($self, $from, $to, $status) = @_;
287 my (@matchers, @keys);
288 my $spec = '';
289 my $contexts = $self->{'contexts'};
290 foreach ($from =~ m{([^/]+)}g) {
291 if (/^<\*>$/) {
292 push @keys, '*';
293 $spec .= '/(.*)';
294 }
295 elsif (/^([^<>]*)<(.+)>([^<>]*)$/) {
296 my ($pfx, $key, $sfx) = ($1, $2, $3);
297 push @keys, $key;
298 my $str = $contexts->[-1]->{'patterns'}{$key} ||= '[^/]+';
299 $spec .= '/' . $pfx . '(' . $str . ')' . $sfx;
300 }
301 else {
302 push @keys, undef;
303 $spec .= '/(' . $_ . ')';
304 }
305 }
306 my $value;
307 if ($to =~ s/^:menu //) {
308 $value = $self->compile_menu_expression($to);
309 }
310 elsif ($to =~ s/^:file //) {
311 $value = $self->compile_file_expression($to);
312 }
313 elsif ($to =~ s/^(:uri )?//) {
314 $value = $self->compile_general_expression($to);
315 }
316 $spec = qr/^$spec$/;
317 return sub {
318 my @debug = ($self, $contexts, $spec, $from, $to, $status); # Just for debugging
319 my ($scope, $path_info, $query_string) = @_;
320 my @m = ( $path_info =~ $spec );
321 return if !@m;
322 my @k = @keys;
323 my %context = map { %{ $_->{'stash'} } } (@$contexts, $scope);
324 while (@k && @m) {
325 my $k = shift @k;
326 my $m = shift @m;
327 if (defined $k) {
328 $context{$k} = $m;
329 }
330 }
331 return $value->(\%context);
332 }
333 }
334  
335 sub compile_menu_expression {
336 my ($self, $str) = @_;
337 if ($str =~ /^(\w+(?:\((.+)\))?)$/) {
338 my $key = $1;
339 return sub {
340 my @debug = ($str);
341 my ($c) = @_;
342 my @keys = ($key);
343 my ($val) = grep { defined $_ } map { $c->{$_} } @keys;
344 die if !defined $val;
345 return evaluate($val, $c);
346 # return 'menu' => ( ref($val) eq 'CODE' ? $val->($c) : $val );
347 };
348 }
349 else {
350 die;
351 }
352 }
353  
354 sub compile_function_from_file {
355 my ($self, $spec, $file) = @_;
356 $file = $self->find_data_file($file);
357 my ($key, @params) = parse_spec($spec);
358 my $reader = $self->compile_data_reader($file, scalar @params);
359 return $key, sub {
360 my @debug = ($spec); # Just for debugging
361 my ($c) = @_;
362 my $data = $reader->($c);
363 my $key = join(KEYJOINER, @$c{@params});
364 my $val = $data->{$key};
365 die "can't evaluate: $spec => undef" if !defined $val;
366 return $val;
367 };
368 }
369 sub find_data_file {
370 my ($self, $f) = @_;
371 return $f if $f =~ m{^/};
372 my $contexts = $self->{'contexts'};
373 my $ddir = $contexts->[0]->{'stash'}->{'data_dir'};
374 if (defined $ddir) {
375 $ddir = $ddir->($contexts->[0]->{'stash'}) if ref $ddir;
376 }
377 else {
378 $ddir = $self->{'data_dir'};
379 }
380 $ddir =~ s{/+$}{};
381 return $ddir . '/' . $f;
382 }
383  
384 # --- Utility functions
385 #
386 sub normalize {
387 for (@_) {
388 chomp;
389 s/\s+/ /g;
390 s/^ | $//g;
391 }
392 }
393  
394 sub parse_spec {
395 my ($spec) = @_;
396 $spec =~ m{(\w+)\(([^()]+)\)} or return ($spec);
397 my ($name, @params) = ($1, split /, */, $2);
398 my $key = sprintf('%s(%s)', $name, join(',', @params));
399 return ($key, @params);
400 }
401  
402 sub read_inline_data {
403 my ($fh, $arity) = @_;
404 my %data;
405 while (<$fh>) {
406 normalize($_);
407 last if /^}$/;
408 my ($keyspec, $val) = split / -> /;
409 my @key = split /, /, $keyspec;
410 die "Bad arity: $keyspec (should be $arity)" if $arity != @key;
411 $data{join(KEYJOINER, @key)} = $val;
412 }
413 return \%data;
414 }
415  
416 sub compile_general_expression {
417 my ($self, $str) = @_;
418 # <base>/<script(resource)>?docid=<resource>
419 my @subexpressions;
420 while ($str =~ m/([^<>]+)|<([^<>]+)>/g) {
421 if (defined $1) {
422 push @subexpressions, $1;
423 }
424 else {
425 my $key = $2;
426 push @subexpressions, sub {
427 my @debug = ($str); # Just for debugging
428 my ($c) = @_;
429 my @keys = ($key);
430 my ($val) = grep { defined $_ } map { $c->{$_} } @keys;
431 die "Can't evaluate: $str" if !defined $val;
432 return evaluate($val, $c);
433 # return ref($val) ? $val->($c) : $val;
434 }
435 }
436 }
437 return sub {
438 my @debug = ($str);
439 my ($c) = @_;
440 my $uri = '';
441 foreach my $expr (@subexpressions) {
442 $uri .= evaluate($expr, $c);
443 # $uri .= ref($expr) ? $expr->($c) : $expr;
444 }
445 return $uri;
446 };
447 }
448  
449 sub evaluate {
450 my ($x, $c) = @_;
451 my $r = ref $x;
452 return $x->($c) if $r eq 'CODE';
453 return { map { $_ => evaluate($x->{$_}, $c) } keys %$x } if $r eq 'HASH';
454 return $x;
455 }
456  
457 sub compile_perl_function_inline {
458 my ($self, $spec, $fh) = @_;
459 my ($key, @params) = parse_spec($spec);
460 my $src = "sub {\n";
461 while (<$fh>) {
462 die if !defined $_;
463 $src .= $_;
464 last if /^\s*}\s*$/;
465 }
466 my $inner_sub = eval $src;
467 return $key, sub {
468 my @debug = ($spec, $src); # Just for debugging
469 my $c = shift;
470 my @args = map { evaluate($_, $c) } @$c{@params};
471 # my @args = map { ref($_) ? $_->($c) : $_ } @$c{@params};
472 $inner_sub->(@args);
473 };
474 #return eval $src;
475 }
476  
477 sub compile_list {
478 my ($self, $name, $fh) = @_;
479 my @elems;
480 while (<$fh>) {
481 normalize($_);
482 last if /^}$/;
483 push @elems, $_;
484 }
485 return $name, \@elems;
486 }
487  
488 # --- Private methods
489 #
490 sub load_config {
491 my ($self) = @_;
492 my $root = { 'name' => '', 'stash' => {} };
493 $self->{'scopes'} = { '' => $root };
494 push @{ $self->{'contexts'} }, $root;
495 my $cfile = $self->{'config_file'};
496 my $cdir = $self->{'config_dir'};
497 if (!defined $cdir) {
498 $cdir = $cfile;
499 $cdir =~ s/\.conf/.d/;
500 }
501 foreach my $f (grep { -e } map { glob } $cfile, "$cdir/*.conf") {
502 $self->read_config_file($f);
503 }
504 %{ $self->{'file2data'} } = (); # XXX Untie?
505 return 1;
506 }
507  
508 sub compile_function_inline {
509 my ($self, $spec, $fh) = @_;
510 my ($key, @params) = parse_spec($spec);
511 my $data = read_inline_data($fh, scalar @params);
512 return $key, sub {
513 my @debug = ($spec); # Just for debugging
514 my ($c) = @_;
515 my $key = join(KEYJOINER, @$c{@params});
516 my $val = $data->{$key};
517 die "can't evaluate: $spec => undef" if !defined $val;
518 return $val;
519 };
520 }
521  
522 sub ok {
523 my ($status, $msg) = @_;
524 return (
525 'ok' => 1,
526 'status' => sprintf('%03d', $status),
527 'message' => $msg,
528 );
529 }
530  
531 sub err {
532 my ($status, $msg) = @_;
533 return (
534 'ok' => 0,
535 'status' => sprintf('%03d', $status),
536 'message' => $msg,
537 );
538 }
539  
540 1;
541  
542 =head1 NAME
543  
544 WWW::Lk4 - rule- and data-based transformation of URLs
545  
546 =head1 SYNOPSIS
547  
548 use WWW::Lk4;
549 $lk4 = WWW::Lk4->new(
550 'config_file' => $conf,
551 'data_dir' => $dir,
552 ...
553 );
554 $lk4->let('$foo' => 'bar');
555 $lk4->let('foo(bar)' => \&baz);
556 %result = $lk4->resolve('/absolute/uri/path');
557  
558 =head1 DESCRIPTION
559  
560 B<WWW::Lk4> resolves URIs into target URIs.
561  
562 It is suitable for use in a general link redirection service.
563  
564 =head1 METHODS
565  
566 =over 4
567  
568 =item B<new>
569  
570 $lk4 = WWW::Lk4->new(
571 'config_file' => $conf,
572 'data_dir' => $dir,
573 ...
574 );
575  
576 Which config files are read may be overridden by specifying C<config_file> or
577 C<config_dir> arguments (or both):
578  
579 $lk4 = WWW::Lk4->new(
580 'config_file' => '/etc/lk4/foo/main.conf',
581 'config_dir' => '/etc/lk4/foo/includes',
582 );
583  
584 If B<config_file> is used but not B<config_dir>, then B<config_dir> will be set
585 to the value of B<config_file> with C<.d> substituted for C<.conf>.
586  
587 The names of config files within I<config_dir> B<must> match the glob C<*.conf>
588 or they will be ignored.
589  
590 =item B<read_config_file>
591  
592 $lk4->read_config_file($f);
593  
594 =item B<let>
595  
596 $lk4->let('$foo' => 'bar');
597 $lk4->let('foo(bar)' => \&baz);
598  
599 Define a variable or function. This is not normally required, as you can
600 accomplish the same thing using a Perl function in a config file.
601  
602 =item B<resolve>
603  
604 %result = $lk4->resolve($uri);
605 if (!$result{ok}) {
606 print "Error: $result{message}\n";
607 }
608 elsif ($result{uri}) {
609 print "URI: $result{uri}\n";
610 }
611 elsif ($result{menu}) {
612 print "Menu: $result{menu}{title}\n";
613 }
614  
615 =back
616  
617 =head1 CONFIGURATION
618  
619 Config files contain this stuff...
620  
621 =over 4
622  
623 =item B<under>
624  
625 C<under> introduces a scope under which URIs beginning with a particular prefix may be
626 resolved. For example:
627  
628 under /doc {
629 forward /<docid> to http://public.example.org/read?docID=<docid>
630 forward /<docid>/secret to http://secret.example.org/read?docID=<docid>
631 }
632  
633 This would redirect C</doc/12345> to C<<
634 http://public.example.org/read?docID=12345 >> and C</doc/98765/secret> to C<<
635 http://secret.example.org/read?docID=98765 >>.
636  
637 An C<under> block may contain any directive, not just C<redirect>; those
638 directives will apply only to URIs that fall under the given prefix.
639  
640 =item B<function>
641  
642 A function takes zero or more inputs and produces an output. You can use this,
643 for example, to map library names to proxy prefixes
644  
645 function base(name) {
646 main -> http://example.net
647 smith -> http://smith.example.net
648 jones -> http://jones.example.net
649 }
650 forward /foo/<name>/<docid> to <base(name)>/foo/<docid>
651  
652 Functions may be defined in a data file:
653  
654 function new(docid) from doc-id-mapping
655 forward /doc/<docid> to http://new.example.org/doc/<new(docid)>
656  
657 Functions may be written in Perl:
658  
659 function qux(docid) :perl {
660 my ($docid) = @_;
661 my $uri = ...;
662 return $uri;
663 }
664  
665 =item B<menu>
666  
667 A menu is a list of URIs to present to the user. Example:
668  
669 under /doc {
670 menu pdf_or_text(docid) {
671 title Alternatives
672 item /pdf/<docid>.pdf "PDF"
673 item /txt/<docid>.txt "Text"
674 }
675 forward /<docid> to :menu pdf_or_text(docid)
676 }
677  
678 =back
679  
680 =head1 FILES
681  
682 Default config files are as follows:
683  
684 =over 4
685  
686 =item B</usr/local/lk4/conf/lk4.conf>
687  
688 =item B</usr/local/lk4/conf/lk4.d/*.conf>
689  
690 =back
691  
692 =head1 BUGS
693  
694 Functions must be called using arguments whose names match the formal parameter
695 names with which the function was declared. Ditto menus.
696  
697 =head1 AUTHOR
698  
699 Paul Hoffman E<lt>paul@flo.orgE<gt>.
700  
701 =head1 LICENCE AND COPYRIGHT
702  
703 Copyright (c) 2012 Fenway Libraries Online.
704  
705 This module is free software; you can redistribute it and/or modify it under
706 the terms of the GNU General Public License, version 2.
707  
708 This program is distributed in the hope that it will be useful,
709 but WITHOUT ANY WARRANTY; without even the implied warranty of
710 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
711  
712 =cut