b480c9ad7bb6d19c818ac5ffa7ff1f8a49a14c1a
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Engine / FastCGI.pm
1 package Catalyst::Engine::FastCGI;
2
3 use Moose;
4 extends 'Catalyst::Engine::CGI';
5
6 # eval { Class::MOP::load_class("FCGI") };
7 eval "use FCGI";
8 die "Unable to load the FCGI module, you may need to install it:\n$@\n" if $@;
9
10 =head1 NAME
11
12 Catalyst::Engine::FastCGI - FastCGI Engine
13
14 =head1 DESCRIPTION
15
16 This is the FastCGI engine.
17
18 =head1 OVERLOADED METHODS
19
20 This class overloads some methods from C<Catalyst::Engine::CGI>.
21
22 =head2 $self->run($c, $listen, { option => value, ... })
23
24 Starts the FastCGI server.  If C<$listen> is set, then it specifies a
25 location to listen for FastCGI requests;
26
27 =over 4
28
29 =item /path
30
31 listen via Unix sockets on /path
32
33 =item :port
34
35 listen via TCP on port on all interfaces
36
37 =item hostname:port
38
39 listen via TCP on port bound to hostname
40
41 =back
42
43 Options may also be specified;
44
45 =over 4
46
47 =item leave_umask
48
49 Set to 1 to disable setting umask to 0 for socket open
50
51 =item nointr
52
53 Do not allow the listener to be interrupted by Ctrl+C
54
55 =item nproc
56
57 Specify a number of processes for FCGI::ProcManager
58
59 =item pidfile
60
61 Specify a filename for the pid file
62
63 =item manager
64
65 Specify a FCGI::ProcManager sub-class
66
67 =item detach
68
69 Detach from console
70
71 =item keep_stderr
72
73 Send STDERR to STDOUT instead of the webserver
74
75 =back
76
77 =cut
78
79 sub run {
80     my ( $self, $class, $listen, $options ) = @_;
81
82     my $sock = 0;
83     if ($listen) {
84         my $old_umask = umask;
85         unless ( $options->{leave_umask} ) {
86             umask(0);
87         }
88         $sock = FCGI::OpenSocket( $listen, 100 )
89           or die "failed to open FastCGI socket; $!";
90         unless ( $options->{leave_umask} ) {
91             umask($old_umask);
92         }
93     }
94     elsif ( $^O ne 'MSWin32' ) {
95         -S STDIN
96           or die "STDIN is not a socket; specify a listen location";
97     }
98
99     $options ||= {};
100
101     my %env;
102     my $error = \*STDERR; # send STDERR to the web server
103        $error = \*STDOUT  # send STDERR to stdout (a logfile)
104          if $options->{keep_stderr}; # (if asked to)
105
106     my $request =
107       FCGI::Request( \*STDIN, \*STDOUT, $error, \%env, $sock,
108         ( $options->{nointr} ? 0 : &FCGI::FAIL_ACCEPT_ON_INTR ),
109       );
110
111     my $proc_manager;
112
113     if ($listen) {
114         $options->{manager} ||= "FCGI::ProcManager";
115         $options->{nproc}   ||= 1;
116
117         $self->daemon_fork() if $options->{detach};
118
119         if ( $options->{manager} ) {
120             eval "use $options->{manager}; 1" or die $@;
121
122             $proc_manager = $options->{manager}->new(
123                 {
124                     n_processes => $options->{nproc},
125                     pid_fname   => $options->{pidfile},
126                 }
127             );
128
129             # detach *before* the ProcManager inits
130             $self->daemon_detach() if $options->{detach};
131
132             $proc_manager->pm_manage();
133
134             # Give each child its own RNG state.
135             srand;
136         }
137         elsif ( $options->{detach} ) {
138             $self->daemon_detach();
139         }
140     }
141
142     while ( $request->Accept >= 0 ) {
143         $proc_manager && $proc_manager->pm_pre_dispatch();
144
145         $self->_fix_env( \%env );
146
147         $class->handle_request( env => \%env );
148
149         $proc_manager && $proc_manager->pm_post_dispatch();
150     }
151 }
152
153 =head2 $self->write($c, $buffer)
154
155 =cut
156
157 sub write {
158     my ( $self, $c, $buffer ) = @_;
159
160     unless ( $self->_prepared_write ) {
161         $self->prepare_write($c);
162         $self->_prepared_write(1);
163     }
164
165     # XXX: We can't use Engine's write() method because syswrite
166     # appears to return bogus values instead of the number of bytes
167     # written: http://www.fastcgi.com/om_archive/mail-archive/0128.html
168
169     # Prepend the headers if they have not yet been sent
170     if ( $self->_has_header_buf ) {
171         $buffer = $self->_clear_header_buf . $buffer;
172     }
173
174     # FastCGI does not stream data properly if using 'print $handle',
175     # but a syswrite appears to work properly.
176     *STDOUT->syswrite($buffer);
177 }
178
179 =head2 $self->daemon_fork()
180
181 Performs the first part of daemon initialisation.  Specifically,
182 forking.  STDERR, etc are still connected to a terminal.
183
184 =cut
185
186 sub daemon_fork {
187     require POSIX;
188     fork && exit;
189 }
190
191 =head2 $self->daemon_detach( )
192
193 Performs the second part of daemon initialisation.  Specifically,
194 disassociates from the terminal.
195
196 However, this does B<not> change the current working directory to "/",
197 as normal daemons do.  It also does not close all open file
198 descriptors (except STDIN, STDOUT and STDERR, which are re-opened from
199 F</dev/null>).
200
201 =cut
202
203 sub daemon_detach {
204     my $self = shift;
205     print "FastCGI daemon started (pid $$)\n";
206     open STDIN,  "+</dev/null" or die $!;
207     open STDOUT, ">&STDIN"     or die $!;
208     open STDERR, ">&STDIN"     or die $!;
209     POSIX::setsid();
210 }
211
212 =head2 $self->_fix_env( $env )
213
214 Adjusts the environment variables when necessary.
215
216 =cut
217
218 sub _fix_env
219 {
220     my $self = shift;
221     my $env = shift;
222
223     # we are gonna add variables from current system environment %ENV to %env
224     # that contains at this moment just variables taken from FastCGI request
225     foreach my $k (keys(%ENV)) {
226       $env->{$k} = $ENV{$k} unless defined($env->{$k});
227     }
228
229     return unless ( $env->{SERVER_SOFTWARE} );
230
231     # If we're running under Lighttpd, swap PATH_INFO and SCRIPT_NAME
232     # http://lists.scsys.co.uk/pipermail/catalyst/2006-June/008361.html
233     # Thanks to Mark Blythe for this fix
234     if ( $env->{SERVER_SOFTWARE} =~ /lighttpd/ ) {
235         $env->{PATH_INFO} ||= delete $env->{SCRIPT_NAME};
236     }
237     # Fix the environment variables PATH_INFO and SCRIPT_NAME when running 
238     # under IIS
239     # FIXME - How does this handle %7F?
240     elsif ( $env->{SERVER_SOFTWARE} =~ /IIS\/[6-9]\.[0-9]/ ) {
241         my @script_name = split(m!/!, $env->{PATH_INFO});
242         my @path_translated = split(m!/|\\\\?!, $env->{PATH_TRANSLATED});
243         my @path_info;
244
245         while ($script_name[$#script_name] eq $path_translated[$#path_translated]) {
246             pop(@path_translated);
247             unshift(@path_info, pop(@script_name));
248         }
249
250         unshift(@path_info, '', '');
251
252         $env->{PATH_INFO} = join('/', @path_info);
253         $env->{SCRIPT_NAME} = join('/', @script_name);
254     }
255 }
256
257 1;
258 __END__
259
260 =head1 WEB SERVER CONFIGURATIONS
261
262 =head2 Standalone FastCGI Server
263
264 In server mode the application runs as a standalone server and accepts
265 connections from a web server.  The application can be on the same machine as
266 the web server, on a remote machine, or even on multiple remote machines.
267 Advantages of this method include running the Catalyst application as a
268 different user than the web server, and the ability to set up a scalable
269 server farm.
270
271 To start your application in server mode, install the FCGI::ProcManager
272 module and then use the included fastcgi.pl script.
273
274     $ script/myapp_fastcgi.pl -l /tmp/myapp.socket -n 5
275
276 Command line options for fastcgi.pl include:
277
278     -d -daemon     Daemonize the server.
279     -p -pidfile    Write a pidfile with the pid of the process manager.
280     -l -listen     Listen on a socket path, hostname:port, or :port.
281     -n -nproc      The number of processes started to handle requests.
282
283 See below for the specific web server configurations for using the external
284 server.
285
286 =head2 Apache 1.x, 2.x
287
288 Apache requires the mod_fastcgi module.  The same module supports both
289 Apache 1 and 2.
290
291 There are three ways to run your application under FastCGI on Apache: server,
292 static, and dynamic.
293
294 =head3 Standalone server mode
295
296     FastCgiExternalServer /tmp/myapp.fcgi -socket /tmp/myapp.socket
297     Alias /myapp/ /tmp/myapp/myapp.fcgi/
298
299     # Or, run at the root
300     Alias / /tmp/myapp.fcgi/
301
302     # Optionally, rewrite the path when accessed without a trailing slash
303     RewriteRule ^/myapp$ myapp/ [R]
304
305
306 The FastCgiExternalServer directive tells Apache that when serving
307 /tmp/myapp to use the FastCGI application listenting on the socket
308 /tmp/mapp.socket.  Note that /tmp/myapp.fcgi B<MUST NOT> exist --
309 it's a virtual file name.  With some versions of C<mod_fastcgi> or
310 C<mod_fcgid>, you can use any name you like, but some require that the
311 virtual filename end in C<.fcgi>.
312
313 It's likely that Apache is not configured to serve files in /tmp, so the
314 Alias directive maps the url path /myapp/ to the (virtual) file that runs the
315 FastCGI application. The trailing slashes are important as their use will
316 correctly set the PATH_INFO environment variable used by Catalyst to
317 determine the request path.  If you would like to be able to access your app
318 without a trailing slash (http://server/myapp), you can use the above
319 RewriteRule directive.
320
321 =head3 Static mode
322
323 The term 'static' is misleading, but in static mode Apache uses its own
324 FastCGI Process Manager to start the application processes.  This happens at
325 Apache startup time.  In this case you do not run your application's
326 fastcgi.pl script -- that is done by Apache. Apache then maps URIs to the
327 FastCGI script to run your application.
328
329     FastCgiServer /path/to/myapp/script/myapp_fastcgi.pl -processes 3
330     Alias /myapp/ /path/to/myapp/script/myapp_fastcgi.pl/
331
332 FastCgiServer tells Apache to start three processes of your application at
333 startup.  The Alias command maps a path to the FastCGI application. Again,
334 the trailing slashes are important.
335
336 =head3 Dynamic mode
337
338 In FastCGI dynamic mode, Apache will run your application on demand,
339 typically by requesting a file with a specific extension (e.g. .fcgi).  ISPs
340 often use this type of setup to provide FastCGI support to many customers.
341
342 In this mode it is often enough to place or link your *_fastcgi.pl script in
343 your cgi-bin directory with the extension of .fcgi.  In dynamic mode Apache
344 must be able to run your application as a CGI script so ExecCGI must be
345 enabled for the directory.
346
347     AddHandler fastcgi-script .fcgi
348
349 The above tells Apache to run any .fcgi file as a FastCGI application.
350
351 Here is a complete example:
352
353     <VirtualHost *:80>
354         ServerName www.myapp.com
355         DocumentRoot /path/to/MyApp
356
357         # Allow CGI script to run
358         <Directory /path/to/MyApp>
359             Options +ExecCGI
360         </Directory>
361
362         # Tell Apache this is a FastCGI application
363         <Files myapp_fastcgi.pl>
364             SetHandler fastcgi-script
365         </Files>
366     </VirtualHost>
367
368 Then a request for /script/myapp_fastcgi.pl will run the
369 application.
370
371 For more information on using FastCGI under Apache, visit
372 L<http://www.fastcgi.com/mod_fastcgi/docs/mod_fastcgi.html>
373
374 =head3 Authorization header with mod_fastcgi or mod_cgi
375
376 By default, mod_fastcgi/mod_cgi do not pass along the Authorization header,
377 so modules like C<Catalyst::Plugin::Authentication::Credential::HTTP> will
378 not work.  To enable pass-through of this header, add the following
379 mod_rewrite directives:
380
381     RewriteCond %{HTTP:Authorization} ^(.+)
382     RewriteRule ^(.*)$ $1 [E=HTTP_AUTHORIZATION:%1,PT]
383
384 =head2 Lighttpd
385
386 These configurations were tested with Lighttpd 1.4.7.
387
388 =head3 Standalone server mode
389
390     server.document-root = "/var/www/MyApp/root"
391
392     fastcgi.server = (
393         "" => (
394             "MyApp" => (
395                 "socket"      => "/tmp/myapp.socket",
396                 "check-local" => "disable"
397             )
398         )
399     )
400
401 =head3 Static mode
402
403     server.document-root = "/var/www/MyApp/root"
404
405     fastcgi.server = (
406         "" => (
407             "MyApp" => (
408                 "socket"       => "/tmp/myapp.socket",
409                 "check-local"  => "disable",
410                 "bin-path"     => "/var/www/MyApp/script/myapp_fastcgi.pl",
411                 "min-procs"    => 2,
412                 "max-procs"    => 5,
413                 "idle-timeout" => 20
414             )
415         )
416     )
417
418 Note that in newer versions of lighttpd, the min-procs and idle-timeout
419 values are disabled.  The above example would start 5 processes.
420
421 =head3 Non-root configuration
422
423 You can also run your application at any non-root location with either of the
424 above modes.  Note the required mod_rewrite rule.
425
426     url.rewrite = ( "myapp\$" => "myapp/" )
427     fastcgi.server = (
428         "/myapp" => (
429             "MyApp" => (
430                 # same as above
431             )
432         )
433     )
434
435 For more information on using FastCGI under Lighttpd, visit
436 L<http://www.lighttpd.net/documentation/fastcgi.html>
437
438 =head2 nginx
439
440 Catalyst runs under nginx via FastCGI in a similar fashion as the lighttpd
441 standalone server as described above.
442
443 nginx does not have its own internal FastCGI process manager, so you must run
444 the FastCGI service separately.
445
446 =head3 Configuration
447
448 To configure nginx, you must configure the FastCGI parameters and also the
449 socket your FastCGI daemon is listening on.  It can be either a TCP socket
450 or a Unix file socket.
451
452 The server configuration block should look roughly like:
453
454     server {
455         listen $port;
456
457         location / {
458             fastcgi_param  QUERY_STRING       $query_string;
459             fastcgi_param  REQUEST_METHOD     $request_method;
460             fastcgi_param  CONTENT_TYPE       $content_type;
461             fastcgi_param  CONTENT_LENGTH     $content_length;
462
463             fastcgi_param  PATH_INFO          $fastcgi_script_name;
464             fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
465             fastcgi_param  REQUEST_URI        $request_uri;
466             fastcgi_param  DOCUMENT_URI       $document_uri;
467             fastcgi_param  DOCUMENT_ROOT      $document_root;
468             fastcgi_param  SERVER_PROTOCOL    $server_protocol;
469
470             fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
471             fastcgi_param  SERVER_SOFTWARE    nginx/$nginx_version;
472
473             fastcgi_param  REMOTE_ADDR        $remote_addr;
474             fastcgi_param  REMOTE_PORT        $remote_port;
475             fastcgi_param  SERVER_ADDR        $server_addr;
476             fastcgi_param  SERVER_PORT        $server_port;
477             fastcgi_param  SERVER_NAME        $server_name;
478         
479             # Adjust the socket for your applications!
480             fastcgi_pass   unix:$docroot/myapp.socket;
481         }
482     }
483
484 It is the standard convention of nginx to include the fastcgi_params in a
485 separate file (usually something like C</etc/nginx/fastcgi_params>) and
486 simply include that file.
487
488 =head3  Non-root configuration
489
490 If you properly specify the PATH_INFO and SCRIPT_NAME parameters your 
491 application will be accessible at any path.  The SCRIPT_NAME variable is the
492 prefix of your application, and PATH_INFO would be everything in addition.
493
494 As an example, if your application is rooted at /myapp, you would configure:
495
496     fastcgi_param  PATH_INFO /myapp/;
497     fastcgi_param  SCRIPT_NAME $fastcgi_script_name;
498
499 C<$fastcgi_script_name> would be "/myapp/path/of/the/action".  Catalyst will
500 process this accordingly and setup the application base as expected.
501
502 This behavior is somewhat different than Apache and Lighttpd, but is still
503 functional.
504
505 For more information on nginx, visit:
506 L<http://nginx.net>
507
508 =head2 Microsoft IIS
509
510 It is possible to run Catalyst under IIS with FastCGI, but only on IIS 6.0
511 (Microsoft Windows 2003), IIS 7.0 (Microsoft Windows 2008 and Vista) and
512 hopefully its successors.
513
514 Even if it is declared that FastCGI is supported on IIS 5.1 (Windows XP) it
515 does not support some features (specifically: wildcard mappings) that prevents
516 running Catalyst application.
517
518 Let us assume that our server has the following layout:
519
520     d:\WWW\WebApp\                   path to our Catalyst application
521     d:\strawberry\perl\bin\perl.exe  path to perl interpreter (with Catalyst installed)
522     c:\windows                       Windows directory
523
524 =head3 Setup IIS 6.0 (Windows 2003)
525
526 =over 4
527
528 =item Install FastCGI extension for IIS 6.0
529
530 FastCGI is not a standard part of IIS 6 - you have to install it separately. For
531 more info and download go to L<http://www.iis.net/extensions/FastCGI>. Choose
532 approptiate version (32-bit/64-bit), installation is quite simple
533 (in fact no questions, no options).
534
535 =item Create a new website
536
537 Open "Control Panel" > "Administrative Tools" > "Internet Information Services Manager".
538 Click "Action" > "New" > "Web Site". After you finish the installation wizard
539 you need to go to the new website's properties.
540
541 =item Set website properties
542
543 On tab "Web site" set proper values for:
544 Site Description, IP Address, TCP Port, SSL Port etc.
545
546 On tab "Home Directory" set the following:
547
548     Local path: "d:\WWW\WebApp\root"
549     Local path permission flags: check only "Read" + "Log visits"
550     Execute permitions: "Scripts only"
551
552 Click "Configuration" button (still on Home Directory tab) then click "Insert"
553 the wildcard application mapping and in the next dialog set:
554
555     Executable: "c:\windows\system32\inetsrv\fcgiext.dll"
556     Uncheck: "Verify that file exists"
557
558 Close all dialogs with "OK".
559
560 =item Edit fcgiext.ini
561
562 Put the following lines into c:\windows\system32\inetsrv\fcgiext.ini (on 64-bit
563 system c:\windows\syswow64\inetsrv\fcgiext.ini):
564
565     [Types]
566     *:8=CatalystApp
567     ;replace 8 with the identification number of the newly created website
568     ;it is not so easy to get this number:
569     ; - you can use utility "c:\inetpub\adminscripts\adsutil.vbs"
570     ;   to list websites:   "cscript adsutil.vbs ENUM /P /W3SVC"
571     ;   to get site name:   "cscript adsutil.vbs GET /W3SVC/<number>/ServerComment"
572     ;   to get all details: "cscript adsutil.vbs GET /W3SVC/<number>"
573     ; - or look where are the logs located:
574     ;   c:\WINDOWS\SYSTEM32\Logfiles\W3SVC7\whatever.log
575     ;   means that the corresponding number is "7"
576     ;if you are running just one website using FastCGI you can use '*=CatalystApp'
577
578     [CatalystApp]
579     ExePath=d:\strawberry\perl\bin\perl.exe
580     Arguments="d:\WWW\WebApp\script\webapp_fastcgi.pl -e"
581
582     ;by setting this you can instruct IIS to serve Catalyst static files
583     ;directly not via FastCGI (in case of any problems try 1)
584     IgnoreExistingFiles=0
585
586     ;do not be fooled by Microsoft doc talking about "IgnoreExistingDirectories"
587     ;that does not work and use "IgnoreDirectories" instead
588     IgnoreDirectories=1
589
590 =back
591
592 =head3 Setup IIS 7.0 (Windows 2008 and Vista)
593
594 Microsoft IIS 7.0 has built-in support for FastCGI so you do not have to install
595 any addons.
596
597 =over 4
598
599 =item Necessary steps during IIS7 installation
600
601 During IIS7 installation after you have added role "Web Server (IIS)"
602 you need to check to install role feature "CGI" (do not be nervous that it is
603 not FastCGI). If you already have IIS7 installed you can add "CGI" role feature
604 through "Control panel" > "Programs and Features".
605
606 =item Create a new website
607
608 Open "Control Panel" > "Administrative Tools" > "Internet Information Services Manager"
609 > "Add Web Site".
610
611     site name: "CatalystSite"
612     content directory: "d:\WWW\WebApp\root"
613     binding: set proper IP address, port etc.
614
615 =item Configure FastCGI
616
617 You can configure FastCGI extension using commandline utility
618 "c:\windows\system32\inetsrv\appcmd.exe"
619
620 =over 4
621
622 =item Configuring section "fastCgi" (it is a global setting)
623
624   appcmd.exe set config -section:system.webServer/fastCgi /+"[fullPath='d:\strawberry\perl\bin\perl.exe',arguments='d:\www\WebApp\script\webapp_fastcgi.pl -e',maxInstances='4',idleTimeout='300',activityTimeout='30',requestTimeout='90',instanceMaxRequests='1000',protocol='NamedPipe',flushNamedPipe='False']" /commit:apphost
625
626 =item Configuring proper handler (it is a site related setting)
627
628   appcmd.exe set config "CatalystSite" -section:system.webServer/handlers /+"[name='CatalystFastCGI',path='*',verb='GET,HEAD,POST',modules='FastCgiModule',scriptProcessor='d:\strawberry\perl\bin\perl.exe|d:\www\WebApp\script\webapp_fastcgi.pl -e',resourceType='Unspecified',requireAccess='Script']" /commit:apphost
629
630 Note: before launching the commands above do not forget to change site
631 name and paths to values relevant for your server setup.
632
633 =back
634
635 =back
636
637 =head1 SEE ALSO
638
639 L<Catalyst>, L<FCGI>.
640
641 =head1 AUTHORS
642
643 Catalyst Contributors, see Catalyst.pm
644
645 =head1 THANKS
646
647 Bill Moseley, for documentation updates and testing.
648
649 =head1 COPYRIGHT
650
651 This library is free software. You can redistribute it and/or modify it under
652 the same terms as Perl itself.
653
654 =cut