aboutsummaryrefslogtreecommitdiff
path: root/Inject/Handler.pm
blob: 5a40fd8710387fd7668bb12ce0d0da88ad73804b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package Apache::Inject::Handler;

use strict;
use warnings FATAL => 'all';

use Apache2::RequestRec ();
use Apache2::RequestUtil ();
use Apache2::Const qw/OK DECLINED/;

my $doc = qr{
	\A
	(?<head> \s*
	         (<!doctype[^>]*>)? \s*
	         (<html[^>]*>)? \s*
	         ( <head[^>]*>.*?</head> \s*
	         | ( <title[^>]*>.*?</title> \s*
	           | <base[^>]*> \s*
	           | <meta[^>]*> \s*
	           | <link[^>]*> \s*
	           | <style[^>]*>.*?</style> \s* # n.b.
	           | <script[^>]*>.*?</script> \s* # n.b.
	           )+
	         )?
	         (<body[^>]*>)?
	)?
	(?<body> .*? )
	(?<rest> </html> \s* )?
	\z
}xmsi;

sub inject {
	my ($r, $var) = @_;

	# Retrieve value implicitly set by Inject directive
	return if not (my $val = $r->dir_config($var));

	# Validate path
	if ($val =~ m{^/}) {
		warn "$var should not begin with slash, "
		   . "as it is already always relative to document root";
	}
	if ($val =~ m{^../|/../|/..$}) {
		warn "$var cannot extend past document root";
		return;
	}

	# note: document root has been confirmed not to be empty
	my $root = $r->document_root;

	# Read contents of specified file
	open my $fh, '<', "$root/$val" or do {
		warn "$var $root/$val does not exist";
		return;
	};
	print for <$fh>;
	close $fh;
}

sub handler {
	my $r = shift;

	return DECLINED if not $r->content_type eq 'text/html';

	my $content = ${$r->slurp_filename};
	return DECLINED if not $content =~ /$doc/;

	# Or is DocumentRoot guaranteed not to be empty?
	if (not $r->document_root) {
		warn 'Declining request due to empty document root';
		return DECLINED;
	}

	print $+{head} if $+{head};
	inject($r, "InjectHead");
	print $+{body} if $+{body};
	inject($r, "InjectFoot");
	print $+{rest} if $+{rest};

	return OK;
}

1;