da95c6c38e793d341023f4739bdcdf504ae02968
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Engine / CGI.pm
1 package Catalyst::Engine::CGI;
2
3 use Moose;
4 extends 'Catalyst::Engine';
5
6 has _header_buf => (is => 'rw', clearer => '_clear_header_buf', predicate => '_has_header_buf');
7
8 =head1 NAME
9
10 Catalyst::Engine::CGI - The CGI Engine
11
12 =head1 SYNOPSIS
13
14 A script using the Catalyst::Engine::CGI module might look like:
15
16     #!/usr/bin/perl -w
17
18     use strict;
19     use lib '/path/to/MyApp/lib';
20     use MyApp;
21
22     MyApp->run;
23
24 The application module (C<MyApp>) would use C<Catalyst>, which loads the
25 appropriate engine module.
26
27 =head1 DESCRIPTION
28
29 This is the Catalyst engine specialized for the CGI environment.
30
31 =head1 OVERLOADED METHODS
32
33 This class overloads some methods from C<Catalyst::Engine>.
34
35 =head2 $self->finalize_headers($c)
36
37 =cut
38
39 sub finalize_headers {
40     my ( $self, $c ) = @_;
41
42     $c->response->header( Status => $c->response->status );
43
44     $self->_header_buf($c->response->headers->as_string("\015\012") . "\015\012");
45 }
46
47 =head2 $self->prepare_connection($c)
48
49 =cut
50
51 sub prepare_connection {
52     my ( $self, $c ) = @_;
53     local (*ENV) = $self->env || \%ENV;
54
55     my $request = $c->request;
56     $request->address( $ENV{REMOTE_ADDR} );
57
58   PROXY_CHECK:
59     {
60         unless ( ref($c)->config->{using_frontend_proxy} ) {
61             last PROXY_CHECK if $ENV{REMOTE_ADDR} ne '127.0.0.1';
62             last PROXY_CHECK if ref($c)->config->{ignore_frontend_proxy};
63         }
64         last PROXY_CHECK unless $ENV{HTTP_X_FORWARDED_FOR};
65
66         # If we are running as a backend server, the user will always appear
67         # as 127.0.0.1. Select the most recent upstream IP (last in the list)
68         my ($ip) = $ENV{HTTP_X_FORWARDED_FOR} =~ /([^,\s]+)$/;
69         $request->address($ip);
70         if ( defined $ENV{HTTP_X_FORWARDED_PORT} ) {
71             $ENV{SERVER_PORT} = $ENV{HTTP_X_FORWARDED_PORT};
72         }
73     }
74
75     $request->hostname( $ENV{REMOTE_HOST} ) if exists $ENV{REMOTE_HOST};
76     $request->protocol( $ENV{SERVER_PROTOCOL} );
77     $request->user( $ENV{REMOTE_USER} );  # XXX: Deprecated. See Catalyst::Request for removal information
78     $request->remote_user( $ENV{REMOTE_USER} );
79     $request->method( $ENV{REQUEST_METHOD} );
80
81     if ( $ENV{HTTPS} && uc( $ENV{HTTPS} ) eq 'ON' ) {
82         $request->secure(1);
83     }
84
85     if ( $ENV{SERVER_PORT} == 443 ) {
86         $request->secure(1);
87     }
88     binmode(STDOUT); # Ensure we are sending bytes.
89 }
90
91 =head2 $self->prepare_headers($c)
92
93 =cut
94
95 sub prepare_headers {
96     my ( $self, $c ) = @_;
97     local (*ENV) = $self->env || \%ENV;
98     my $headers = $c->request->headers;
99     # Read headers from %ENV
100     foreach my $header ( keys %ENV ) {
101         next unless $header =~ /^(?:HTTP|CONTENT|COOKIE)/i;
102         ( my $field = $header ) =~ s/^HTTPS?_//;
103         $headers->header( $field => $ENV{$header} );
104     }
105 }
106
107 =head2 $self->prepare_path($c)
108
109 =cut
110
111 # Please don't touch this method without adding tests in
112 # t/aggregate/unit_core_engine_cgi-prepare_path.t
113 sub prepare_path {
114     my ( $self, $c ) = @_;
115     local (*ENV) = $self->env || \%ENV;
116
117     my $scheme = $c->request->secure ? 'https' : 'http';
118     my $host      = $ENV{HTTP_HOST}   || $ENV{SERVER_NAME};
119     my $port      = $ENV{SERVER_PORT} || 80;
120     my $script_name = $ENV{SCRIPT_NAME};
121     $script_name =~ s/([^$URI::uric])/$URI::Escape::escapes{$1}/go if $script_name;
122
123     my $base_path;
124     if ( exists $ENV{REDIRECT_URL} ) {
125         $base_path = $ENV{REDIRECT_URL};
126         $base_path =~ s/\Q$ENV{PATH_INFO}\E$//;
127     }
128     else {
129         $base_path = $script_name || '/';
130     }
131
132     # If we are running as a backend proxy, get the true hostname
133   PROXY_CHECK:
134     {
135         unless ( ref($c)->config->{using_frontend_proxy} ) {
136             last PROXY_CHECK if $host !~ /localhost|127.0.0.1/;
137             last PROXY_CHECK if ref($c)->config->{ignore_frontend_proxy};
138         }
139         last PROXY_CHECK unless $ENV{HTTP_X_FORWARDED_HOST};
140
141         $host = $ENV{HTTP_X_FORWARDED_HOST};
142
143         # backend could be on any port, so
144         # assume frontend is on the default port
145         $port = $c->request->secure ? 443 : 80;
146         if ( $ENV{HTTP_X_FORWARDED_PORT} ) {
147             $port = $ENV{HTTP_X_FORWARDED_PORT};
148         }
149     }
150
151     my $path_info   = $ENV{PATH_INFO};
152     if ($c->config->{use_request_uri_for_path}) {
153         # RFC 3875: "Unlike a URI path, the PATH_INFO is not URL-encoded,
154         # and cannot contain path-segment parameters." This means PATH_INFO
155         # is always decoded, and the script can't distinguish / vs %2F.
156         # See https://issues.apache.org/bugzilla/show_bug.cgi?id=35256
157         # Here we try to resurrect the original encoded URI from REQUEST_URI.
158         if (my $req_uri = $ENV{REQUEST_URI}) {
159             if (defined $script_name) {
160                 $req_uri =~ s/^\Q$script_name\E//;
161             }
162             $req_uri =~ s/\?.*$//;
163             $path_info = $req_uri if $req_uri;
164         }
165     }
166
167     # set the request URI
168     my $path = $base_path . ( $path_info || '' );
169     $path =~ s{^/+}{};
170
171     # Using URI directly is way too slow, so we construct the URLs manually
172     my $uri_class = "URI::$scheme";
173
174     # HTTP_HOST will include the port even if it's 80/443
175     $host =~ s/:(?:80|443)$//;
176
177     if ( $port !~ /^(?:80|443)$/ && $host !~ /:/ ) {
178         $host .= ":$port";
179     }
180
181     # Escape the path
182     $path =~ s/([^$URI::uric])/$URI::Escape::escapes{$1}/go;
183     $path =~ s/\?/%3F/g; # STUPID STUPID SPECIAL CASE
184
185     my $query = $ENV{QUERY_STRING} ? '?' . $ENV{QUERY_STRING} : '';
186     my $uri   = $scheme . '://' . $host . '/' . $path . $query;
187
188     $c->request->uri( bless(\$uri, $uri_class)->canonical );
189
190     # set the base URI
191     # base must end in a slash
192     $base_path .= '/' unless $base_path =~ m{/$};
193
194     my $base_uri = $scheme . '://' . $host . $base_path;
195
196     $c->request->base( bless \$base_uri, $uri_class );
197 }
198
199 =head2 $self->prepare_query_parameters($c)
200
201 =cut
202
203 around prepare_query_parameters => sub {
204     my $orig = shift;
205     my ( $self, $c ) = @_;
206     local (*ENV) = $self->env || \%ENV;
207
208     if ( $ENV{QUERY_STRING} ) {
209         $self->$orig( $c, $ENV{QUERY_STRING} );
210     }
211 };
212
213 =head2 $self->prepare_request($c, (env => \%env))
214
215 =cut
216
217 sub prepare_request {
218     my ( $self, $c, %args ) = @_;
219
220     if ( $args{env} ) {
221         $self->env( $args{env} );
222     }
223 }
224
225 =head2 $self->prepare_write($c)
226
227 Enable autoflush on the output handle for CGI-based engines.
228
229 =cut
230
231 around prepare_write => sub {
232     *STDOUT->autoflush(1);
233     return shift->(@_);
234 };
235
236 =head2 $self->write($c, $buffer)
237
238 Writes the buffer to the client.
239
240 =cut
241
242 around write => sub {
243     my $orig = shift;
244     my ( $self, $c, $buffer ) = @_;
245
246     # Prepend the headers if they have not yet been sent
247     if ( $self->_has_header_buf ) {
248         $buffer = $self->_clear_header_buf . $buffer;
249     }
250
251     return $self->$orig( $c, $buffer );
252 };
253
254 =head2 $self->read_chunk($c, $buffer, $length)
255
256 =cut
257
258 sub read_chunk { shift; shift; *STDIN->sysread(@_); }
259
260 =head2 $self->run
261
262 =cut
263
264 sub run { shift; shift->handle_request( env => \%ENV ) }
265
266 =head1 SEE ALSO
267
268 L<Catalyst>, L<Catalyst::Engine>
269
270 =head1 AUTHORS
271
272 Catalyst Contributors, see Catalyst.pm
273
274 =head1 COPYRIGHT
275
276 This library is free software. You can redistribute it and/or modify it under
277 the same terms as Perl itself.
278
279 =cut
280 no Moose;
281
282 1;