2 use ExtUtils::MakeMaker;
4 do 'FCGI.cfg' or die "no FCGI.cfg";
8 print "Generating FCGI.pm\n";
10 # $Id: FCGI.PL,v 1.34 2001/10/04 08:04:16 skimo Exp $
17 @ISA = qw(Exporter DynaLoader);
18 # Items to export into callers namespace by default. Note: do not export
19 # names by default without a very good reason. Use EXPORT_OK instead.
20 # Do not simply export all your public functions/methods/constants.
27 print OUT '$VERSION = '.MM->parse_version('version.pm').";\n\n";
29 print OUT "bootstrap FCGI;\n" unless ($pure);
31 print OUT <<'EOP' if ($pure);
35 use constant VERSION_1 => 1;
37 use constant BEGIN_REQUEST => 1;
38 use constant PARAMS => 4;
39 use constant FCGI_STDIN => 5;
40 use constant FCGI_STDOUT => 6;
41 use constant FCGI_STDERR => 7;
43 use constant RESPONDER => 1;
44 use constant AUTHORIZER => 2;
45 use constant FILTER => 3;
47 %FCGI::rolenames = (RESPONDER, "RESPONDER",
48 AUTHORIZER, "AUTHORIZER",
52 # This only works on Unix; anyone familiar with Windows is welcome
57 (!defined getpeername shift->{listen_sock}) && $! == ENOTCONN
58 unless exists $req->{isfastcgi};
59 return $req->{isfastcgi};
63 return shift->{'env'};
69 return undef unless read $stream, $buf, 1, 0;
70 my ($len) = unpack("C", $buf);
72 $buf = pack("C", $len & 0x7F);
73 return undef unless read $stream, $buf, 3, 1;
74 $len = unpack("N", $buf);
89 open $self->{listen_sock}, "<&=0";
98 unless ($req->IsFastCGI()) {
99 return -1 if $run_once;
105 $req->{socket} = gensym();
106 if ($req->{last} || !accept($req->{socket}, $req->{listen_sock})) {
107 $req->{error} = "accept";
110 my ($type, $id, $body) = $req->read_record();
111 if ($type != BEGIN_REQUEST) {
112 $req->{error} = "begin request";
115 my ($role, $flags) = unpack("nC", $body);
116 $req->{role} = $role;
117 $req->{flags} = $flags;
121 $req->{env}{FCGI_ROLE} = $FCGI::rolenames{$req->{role}};
122 my $param = FCGI::Stream->new($req, PARAMS);
124 while (defined($nlen = read_nv_len($param)) &&
125 defined($vlen = read_nv_len($param))) {
127 read $param, $name, $nlen;
128 read $param, $val, $vlen;
129 $req->{env}{$name} = $val;
132 $req->{accepted} = 1;
140 untie ${$req->{out}};
141 untie ${$req->{err}};
147 tie ${$req->{in}}, 'FCGI::Stream', $req, FCGI_STDIN;
148 tie ${$req->{out}}, 'FCGI::Stream', $req, FCGI_STDOUT;
149 tie ${$req->{err}}, 'FCGI::Stream', $req, FCGI_STDERR;
155 $req->Bind() if ($req->{accepted} && !$req->{bound});
160 $req->UndoBindings() if ($req->{accepted} && $req->{bound});
165 return unless $req->{accepted};
167 $req->UndoBindings();
168 close ${$req->{out}};
169 close ${$req->{err}};
171 $req->{accepted} = 0;
186 read($self->{socket}, $header, 8);
187 my ($version, $type, $id, $clen, $plen) = unpack("CCnnC", $header);
188 read($self->{socket}, $body, $clen+$plen);
189 $body = undef if $clen == 0;
194 my ($self, $rtype, $len) = @_;
195 while (length $self->{buf} < $len) {
196 my ($type, $id, $buf) = $self->read_record();
197 return undef unless defined $buf;
198 if ($type != $rtype) {
199 $self->{error} = "unexpected stream type";
202 $self->{buf} .= $buf;
204 my ($newbuf, $result) = (substr($self->{buf}, $len),
205 substr($self->{buf}, 0, $len));
206 $self->{buf} = $newbuf;
215 my ($self, $type, $content, $len) = @_;
216 return unless $len > 0;
217 $self->write_record($type, $content, $len);
221 my ($self, $type, $content, $len) = @_;
222 my $padlen = (8 - ($len % 8)) % 8;
223 my $templ = "CCnnCxa${len}x$padlen";
224 my $data = pack($templ,
225 VERSION_1, $type, $self->{id}, $len, $padlen, $content);
226 syswrite $self->{socket}, $data;
229 { package FCGI::Stream;
232 my ($class, $src, $type) = @_;
233 my $handle = do { \local *FH };
234 tie($$handle, $class, $src, $type);
239 my ($class, $src, $type) = @_;
240 bless { src => $src, type => $type }, $class;
244 my ($stream, undef, $len, $offset) = @_;
246 my $buf = $stream->{src}->read($stream->{type}, $len);
247 return undef unless defined $buf;
248 substr($$ref, $offset, 0, $buf);
253 my ($stream) = shift;
255 $stream->{src}->write($stream->{type}, $_, length($_));
261 $stream->{src}->write_record($stream->{type}, undef, 0);
267 print OUT while <DATA>;
271 # Preloaded methods go here.
273 # Autoload methods go after __END__, and are processed by the autosplit program.
275 *FAIL_ACCEPT_ON_INTR = sub() { 1 };
277 sub Request(;***$*$) {
278 my @defaults = (\*STDIN, \*STDOUT, \*STDERR, \%ENV, 0, 0);
279 $_[4] = fileno($_[4]) if defined($_[4]) && defined(fileno($_[4]));
280 splice @defaults,0,@_,@_;
285 warn "accept called as a method; you probably wanted to call Accept" if @_;
286 if (defined %FCGI::ENV) {
291 my $rc = Accept($global_request);
292 for (keys %FCGI::ENV) {
293 $ENV{$_} = $FCGI::ENV{$_} unless exists $ENV{$_};
297 $SIG{__WARN__} = $warn_handler if (tied (*STDIN));
298 $SIG{__DIE__} = $die_handler if (tied (*STDIN));
304 warn "finish called as a method; you probably wanted to call Finish" if @_;
305 %ENV = %FCGI::ENV if (defined %FCGI::ENV);
309 delete $SIG{__WARN__} if ($SIG{__WARN__} == $warn_handler);
310 delete $SIG{__DIE__} if ($SIG{__DIE__} == $die_handler);
313 Finish ($global_request);
317 warn "flush called as a method; you probably wanted to call Flush" if @_;
318 Flush($global_request);
322 warn "detach called as a method; you probably wanted to call Detach" if @_;
323 Detach($global_request);
327 warn "attach called as a method; you probably wanted to call Attach" if @_;
328 Attach($global_request);
332 sub set_exit_status {
335 sub start_filter_data() {
336 StartFilterData($global_request);
339 $global_request = Request();
340 $warn_handler = sub { print STDERR @_ };
341 $die_handler = sub { print STDERR @_ unless $^S };
343 package FCGI::Stream;
346 shift->PRINT(sprintf(shift, @_));
355 my $rs = $/ eq '' ? "\n\n" : $/;
356 my $l = substr $rs, -1;
357 my $len = length $rs;
359 $c = $stream->GETC();
362 $c = $stream->GETC();
367 last if $c eq $l and substr($s, -$len) eq $rs;
368 $c = $stream->GETC();
376 return open($_[0], $_[1]);
379 eval("$rc = open($_[0], $_[1], $_[2])");
391 FCGI - Fast CGI module
398 my $request = FCGI::Request();
400 while($request->Accept() >= 0) {
401 print("Content-type: text/html\r\n\r\n", ++$count);
412 Creates a request handle. It has the following optional parameters:
416 =item input perl file handle (default: \*STDIN)
418 =item output perl file handle (default: \*STDOUT)
420 =item error perl file handle (default: \*STDERR)
422 These filehandles will be setup to act as input/output/error
425 =item environment hash reference (default: \%ENV)
427 The hash will be populated with the environment.
429 =item socket (default: 0)
431 Socket to communicate with the server.
432 Can be the result of the OpenSocket function.
433 For the moment, it's the file descriptor of the socket
434 that should be passed. This may change in the future.
436 You should only use your own socket if your program
437 is not started by a process manager such as mod_fastcgi
438 (except for the FastCgiExternalServer case) or cgi-fcgi.
439 If you use the option, you have to let your FastCGI
440 server know which port (and possibly server) your program
442 See remote.pl for an example.
444 =item flags (default: 0)
450 =item FCGI::FAIL_ACCEPT_ON_INTR
452 If set, Accept will fail if interrupted.
453 It not set, it will just keep on waiting.
460 my $req = FCGI::Request;
464 my $in = new IO::Handle;
465 my $out = new IO::Handle;
466 my $err = new IO::Handle;
467 my $req = FCGI::Request($in, $out, $err, \%env);
469 =item FCGI::OpenSocket(path, backlog)
471 Creates a socket suitable to use as an argument to Request.
477 Pathname of socket or colon followed by local tcp port.
478 Note that some systems take file permissions into account
479 on Unix domain sockets, so you'll have to make sure that
480 the server can write to the created file, by changing
481 the umask before the call and/or changing permissions and/or
482 group of the file afterwards.
486 Maximum length of the queue of pending connections.
488 request arrives with the queue full the client may receive
489 an error with an indication of ECONNREFUSED.
493 =item FCGI::CloseSocket(socket)
495 Close a socket opened with OpenSocket.
499 Accepts a connection on $req, attaching the filehandles and
500 populating the environment hash.
501 Returns 0 on success.
502 If a connection has been accepted before, the old
503 one will be finished first.
505 Note that unlike with the old interface, no die and warn
506 handlers are installed by default. This means that if
507 you are not running an sfio enabled perl, any warn or
508 die message will not end up in the server's log by default.
509 It is advised you set up die and warn handlers yourself.
510 FCGI.pm contains an example of die and warn handlers.
514 Finishes accepted connection.
515 Also detaches filehandles.
519 Flushes accepted connection.
523 Temporarily detaches filehandles on an accepted connection.
527 Re-attaches filehandles on an accepted connection.
529 =item $req->LastCall()
531 Tells the library not to accept any more requests on this handle.
532 It should be safe to call this method from signal handlers.
534 Note that this method is still experimental and everything
535 about it, including its name, is subject to change.
537 =item $env = $req->GetEnvironment()
539 Returns the environment parameter passed to FCGI::Request.
541 =item ($in, $out, $err) = $req->GetHandles()
543 Returns the file handle parameters passed to FCGI::Request.
545 =item $isfcgi = $req->IsFastCGI()
547 Returns whether or not the program was run as a FastCGI.
553 Sven Verdoolaege <skimo@kotnet.org>