File: Registry.pm

package info (click to toggle)
libapache-mod-perl 1.16-2
  • links: PTS
  • area: main
  • in suites: slink
  • size: 1,580 kB
  • ctags: 1,064
  • sloc: ansic: 4,489; perl: 4,415; sh: 305; makefile: 137
file content (323 lines) | stat: -rw-r--r-- 8,945 bytes parent folder | download
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
package Apache::Registry;
use Apache ();
#use strict; #eval'd scripts will inherit hints
use Apache::Constants qw(:common &OPT_EXECCGI &REDIRECT);

$Apache::Registry::VERSION = '2.00';

$Apache::Registry::Debug ||= 0;
# 1 => log recompile in errorlog
# 2 => Apache::Debug::dump in case of $@
# 4 => trace pedantically
Apache->module('Apache::Debug') if $Apache::Registry::Debug;

my $Is_Win32 = $^O eq "MSWin32";

unless (defined $Apache::Registry::NameWithVirtualHost) {
    $Apache::Registry::NameWithVirtualHost = 1;
}
unless (defined $Apache::Registry::MarkLine) {
    $Apache::Registry::MarkLine = 1;
}

sub handler {
    my $r = shift;
    if(ref $r) {
	$r->request($r);
    }
    else {
	#warn "Registry args are: ($r, @_)\n";
	$r = Apache->request;
    }
    my $filename = $r->filename;
    #local $0 = $filename; #this core dumps!?
    *0 = \$filename;
    my $oldwarn = $^W;
    $r->log_error("Apache::Registry::handler for $filename in process $$")
	if $Debug && $Debug & 4;

    if (-r $filename && -s _) {
	if (!($r->allow_options & OPT_EXECCGI)) {
	    $r->log_reason("Options ExecCGI is off in this directory",
			   $filename);
	    return FORBIDDEN;
 	}
	if (-d _) {
	    return DECLINED; 
	}
	unless (-x _ or $Is_Win32) {
	    $r->log_reason("file permissions deny server execution",
			   $filename);
	    return FORBIDDEN;
	}

	my $mtime = -M _;

	my $uri = $r->uri;
	$uri = "/__INDEX__" if $uri eq "/";
	# turn into a package name
	$r->log_error(sprintf "Apache::Registry::handler examining %s",
		      $uri) if $Debug && $Debug & 4;
	my $script_name = $r->path_info ?
	    substr($uri, 0, length($uri)-length($r->path_info)) :
		$uri;

	if($Apache::Registry::NameWithVirtualHost) {
	    my $name = $r->get_server_name;
	    $script_name = join "", $name, $script_name if $name;
	}

	# Escape everything into valid perl identifiers
	$script_name =~ s/([^A-Za-z0-9\/])/sprintf("_%2x",unpack("C",$1))/eg;

	# second pass cares for slashes and words starting with a digit
	$script_name =~ s{
			  (/+)       # directory
			  (\d?)      # package's first character
			 }[
			   "::" . ($2 ? sprintf("_%2x",unpack("C",$2)) : "")
			  ]egx;

	my $package = "Apache::ROOT$script_name";
	$Apache::Registry::curstash = $script_name;
	$r->log_error("Apache::Registry::handler package $package")
	   if $Debug && $Debug & 4;

	$r->chdir_file;

	if (
	    exists $Apache::Registry->{$package}{'mtime'}
	    &&
	    $Apache::Registry->{$package}{'mtime'} <= $mtime
	   ){
	    # we have compiled this subroutine already, nothing left to do
 	} else {
	    $r->log_error("Apache::Registry::handler reading $filename")
		if $Debug && $Debug & 4;
	    my $sub = $r->slurp_filename;
	    $sub = parse_cmdline($$sub);

	    # compile this subroutine into the uniq package name
            $r->log_error("Apache::Registry::handler eval-ing") if $Debug && $Debug & 4;
 	    undef &{"$package\::handler"} unless $Debug && $Debug & 4; #avoid warnings
	    if($package->can('undef_functions')) {
		$package->undef_functions;
	    }
	    $r->clear_rgy_endav($script_name);

	    my $line = $Apache::Registry::MarkLine ?
		"\n#line 1 $filename\n" : "";
 
	    my $eval = join(
			    '',
			    'package ',
			    $package,
 			    ';use Apache qw(exit);',
 			    'sub handler {',
			    $line,
			    $sub,
			    "\n}", # last line comment without newline?
			   );
	    compile($eval);
	    $r->stash_rgy_endav($script_name);
	    if ($@) {
		$r->log_error($@);
		$@{$uri} = $@;
		return SERVER_ERROR unless $Debug && $Debug & 2;
		return Apache::Debug::dump($r, SERVER_ERROR);
	    }
            $r->log_error(qq{Compiled package \"$package\" for process $$})
	       if $Debug && $Debug & 1;
	    $Apache::Registry->{$package}{'mtime'} = $mtime;
	}

	my $cv = \&{"$package\::handler"};
	eval { &{$cv}($r, @_) } if $r->seqno;
	$r->chdir_file("$Apache::Server::CWD/");
	$^W = $oldwarn;

	my $errsv = "";
	if($@) {
	    $errsv = $@;
	    $@ = ''; #XXX fix me, if we don't do this Apache::exit() breaks
	    $@{$uri} = $errsv;
	}

	if($errsv) {
	    $r->log_error($errsv);
	    return SERVER_ERROR unless $Debug && $Debug & 2;
	    return Apache::Debug::dump($r, SERVER_ERROR);
	}

#	#XXX
#	if(my $loc = $r->header_out("Location")) {
#	    if($r->status == 200 and substr($loc, 0, 1) ne "/") {
#		return REDIRECT;
#	    }
#	}
	return $r->status;
    } else {
	return NOT_FOUND unless $Debug && $Debug & 2;
	return Apache::Debug::dump($r, NOT_FOUND);
    }
}

sub compile {
    my $eval = shift;
    Apache->untaint($eval);
    eval $eval;
}

#XXX not good enough yet
my(%switches) = (
   'T' => sub {
       Apache::warn("Apache::Registry: T switch ignored, ".
		    "enable with 'PerlTaintCheck On'\n")
	   unless $Apache::__T; "";
   },
   'w' => sub { 'BEGIN {$^W = 1;}' },
);

sub parse_cmdline {
    my $sub = shift;
    my($line) = $sub =~ /^(.*)$/m;
    my(@cmdline) = split /\s+/, $line;
    return $sub unless @cmdline;
    return $sub unless shift(@cmdline) =~ /^\#!/;
    my($s, @s, $prepend);
    $prepend = "";
    for $s (@cmdline) {
	next unless $s =~ s/^-//;
	last if substr($s,0,1) eq "-";
	for (split //, $s) {
	    next unless $switches{$_};
	    #print STDERR "parsed `$_' switch\n";
	    $prepend .= &{$switches{$_}};
	}
    }
    $sub =~ s/^/$prepend/ if $prepend;
    return $sub;
}

#trick so we show up under CPAN/modules/by-module/CGI/
package CGI::mod_perl;

sub DESTROY {}

1;

__END__

=head1 NAME

Apache::Registry - Run unaltered CGI scrips under mod_perl

=head1 SYNOPSIS

 #in httpd.conf

 Alias /perl/ /perl/apache/scripts/ #optional
 PerlModule Apache::Registry

 <Location /perl>
 SetHandler perl-script
 PerlHandler Apache::Registry
 Options ExecCGI 
 ...
 </Directory>

=head1 DESCRIPTION

URIs in the form of C<http://www.host.com/perl/file.pl> will be
compiled as the body of a perl subroutine and executed.  Each server
process or 'child' will compile the subroutine once and store it in
memory. It will recompile it whenever the file is updated on disk.
Think of it as an object oriented server with each script implementing
a class loaded at runtime.

The file looks much like a "normal" script, but it is compiled or 'evaled'
into a subroutine.

Here's an example:

 my $r = Apache->request;
 $r->content_type("text/html");
 $r->send_http_header;
 $r->print("Hi There!");

This module emulates the CGI environment,
allowing programmers to write scripts that run under CGI or
mod_perl without change.  Existing CGI scripts may require some
changes, simply because a CGI script has a very short lifetime of one
HTTP request, allowing you to get away with "quick and dirty"
scripting.  Using mod_perl and Apache::Registry requires you to be
more careful, but it also gives new meaning to the word "quick"!

Be sure to read all mod_perl related documentation for more details,
including instructions for setting up an environment that looks exactly
like CGI:

 print "Content-type: text/html\n\n";
 print "Hi There!";

Note that each httpd process or "child" must compile each script once,
so the first request to one server may seem slow, but each request
there after will be faster.  If your scripts are large and/or make use
of many Perl modules, this difference should be noticeable to the human
eye.

=head1 SECURITY

Apache::Registry::handler will preform the same checks as mod_cgi
before running the script.

=head1 ENVIRONMENT

The Apache function `exit' overrides the Perl core built-in function.

The environment variable B<GATEWAY_INTERFACE> is set to C<CGI-Perl/1.1>.

=head1 COMMANDLINE SWITCHES IN FIRST LINE

Normally when a Perl script is run from the command line or under CGI,
arguments on the `#!' line are passed to the perl interpreter for processing.

Apache::Registry currently only honors the B<-w> switch and will turn
on warnings using the C<$^W> global variable.  Another common switch
used with CGI scripts is B<-T> to turn on taint checking.  This can
only be enabled when the server starts with the configuration
directive:

 PerlTaintCheck On

However, if taint checking is not enabled, but the B<-T> switch is seen,
Apache::Registry will write a warning to the error_log.

=head1 DEBUGGING

You may set the debug level with the $Apache::Registry::Debug bitmask

 1 => log recompile in errorlog
 2 => Apache::Debug::dump in case of $@
 4 => trace pedantically

=head1 CAVEATS

Apache::Registry makes things look just the CGI environment, however, you
must understand that this *is not CGI*.  Each httpd child will compile
your script into memory and keep it there, whereas CGI will run it once,
cleaning out the entire process space.  Many times you have heard
"always use C<-w>, always use C<-w> and 'use strict'".
This is more important here than anywhere else!

Your scripts cannot contain the __END__ or __DATA__ token to terminate
compilation.

=head1 SEE ALSO

perl(1), mod_perl(3), Apache(3), Apache::Debug(3)

=head1 AUTHORS

Andreas J. Koenig and Doug MacEachern