ActiveState!

ActivePerl Documentation
Table of Contents

(Usage Statistics)
(about this ver)


* Getting Started
    * Welcome To ActivePerl
    * Release Notes
    * Readme
    * ActivePerl Change Log
* Install Notes
    * Linux
    * Solaris
    * Windows
* ActivePerl Components
    * Overview
    * PPM
    * Windows Specifics
       * OLE Browser
       * PerlScript
       * Perl for ISAPI
       * PerlEZ
* ActivePerl FAQ
    * Introduction
    * Availability & Install
    * Using PPM
    * Docs & Support
    * Windows Specifics
       * Perl for ISAPI
       * Windows 9X/NT/2000
       * Quirks
       * Web Server Config
       * Web programming
       * Programming
       * Modules & Samples
       * Embedding & Extending
       * Using OLE with Perl
* Windows Scripting
    * Active Server Pages
    * Windows Script Host
    * Windows Script Components

Core Perl Documentation


* perl
* perlfaq
* perltoc
* perlbook

* perlsyn
* perldata
* perlop
* perlreftut
* perldsc
* perllol

* perllexwarn
* perldebug

* perlrun
* perlfunc
* perlopentut
* perlvar
* perlsub
* perlmod
* perlpod

* perlstyle
* perlmodlib
* perlmodinstall
* perltrap
* perlport
* perlsec

* perlref
* perlre
* perlform
* perllocale
* perlunicode

* perlboot
* perltoot
* perltootc
* perlobj
* perlbot
* perltie

* perlipc
* perlnumber
* perlfork
* perlthrtut

* perldiag
* perlfaq1
* perlfaq2
* perlfaq3
* perlfaq4
* perlfaq5
* perlfaq6
* perlfaq7
* perlfaq8
* perlfaq9

* perlcompile

* perlembed
* perlxstut
* perlxs
* perlguts
* perlcall
* perlfilter
* perldbmfilter
* perlapi
* perlintern
* perlapio
* perltodo
* perlhack

* perlhist
* perldelta
* perl5005delta
* perl5004delta

* perlamiga
* perlcygwin
* perldos
* perlhpux
* perlmachten
* perlos2
* perlos390
* perlvms
* perlwin32

Pragmas


* attributes
* attrs
* autouse
* base
* blib
* bytes
* charnames
* constant
* diagnostics
* fields
* filetest
* integer
* less
* lib
* locale
* lwpcook
* open
* ops
* overload
* perllocal
* re
* sigtrap
* strict
* subs
* utf8
* vars
* warnings

Libraries


* ActivePerl
    * DocTools
        * TOC
            * RDF
* AnyDBM_File
* Archive
    * Tar
* AutoLoader
* AutoSplit
* B
    * Asmdata
    * Assembler
    * Bblock
    * Bytecode
    * C
    * CC
    * Debug
    * Deparse
    * Disassembler
    * Lint
    * Showlex
    * Stackobj
    * Terse
    * Xref
* Benchmark
* Bundle
    * LWP
* ByteLoader
* Carp
    * Heavy
* CGI
    * Apache
    * Carp
    * Cookie
    * Fast
    * Pretty
    * Push
    * Switch
* Class
    * Struct
* Compress
    * Zlib
* Config
* CPAN
    * FirstTime
    * Nox
* Cwd
* Data
    * Dumper
* DB
* Devel
    * DProf
    * Peek
    * SelfStubber
* Digest
    * HMAC
    * HMAC_MD5
    * HMAC_SHA1
    * MD2
    * MD5
    * SHA1
* DirHandle
* Dumpvalue
* DynaLoader
* English
* Env
* Errno
* Exporter
    * Heavy
* ExtUtils
    * Command
    * Embed
    * Install
    * Installed
    * Liblist
    * MakeMaker
    * Manifest
    * Miniperl
    * Mkbootstrap
    * Mksymlists
    * MM_Cygwin
    * MM_OS2
    * MM_Unix
    * MM_VMS
    * MM_Win32
    * Packlist
    * testlib
* Fatal
* Fcntl
* File
    * Basename
    * CheckTree
    * Compare
    * Copy
    * CounterFile
    * DosGlob
    * Find
    * Glob
    * Listing
    * Path
    * Spec
        * Functions
        * Mac
        * OS2
        * Unix
        * VMS
        * Win32
    * stat
* FileCache
* FileHandle
* FindBin
* Font
    * AFM
* Getopt
    * Long
    * Std
* HTML
    * AsSubs
    * Element
    * Entities
    * Filter
    * Form
    * FormatPS
    * Formatter
    * FormatText
    * HeadParser
    * LinkExtor
    * Parse
    * Parser
    * TokeParser
    * TreeBuilder
* HTTP
    * Cookies
    * Daemon
    * Date
    * Headers
        * Util
    * Message
    * Negotiate
    * Request
        * Common
    * Response
    * Status
* I18N
    * Collate
* IO
    * Dir
    * File
    * Handle
    * Pipe
    * Poll
    * Seekable
    * Select
    * Socket
        * INET
        * UNIX
* IPC
    * Msg
    * Open2
    * Open3
    * Semaphore
    * SysV
* LWP
    * Debug
    * MediaTypes
    * MemberMixin
    * Protocol
    * RobotUA
    * Simple
    * UserAgent
* Math
    * BigFloat
    * BigInt
    * Complex
    * Trig
* MD5
* MIME
    * Base64
    * QuotedPrint
* NDBM_File
* Net
    * Cmd
    * Config
    * Domain
    * DummyInetd
    * FTP
    * hostent
    * libnetFAQ
    * netent
    * Netrc
    * NNTP
    * PH
    * Ping
    * POP3
    * protoent
    * servent
    * SMTP
    * SNPP
    * Time
* O
* ODBM_File
* Opcode
* Pod
    * Checker
    * Find
    * Html
    * InputObjects
    * Man
    * Parser
    * ParseUtils
    * Plainer
    * Select
    * Text
        * Color
        * Termcap
    * Usage
* POSIX
* PPM
    * SOAPClient
    * SOAPServer
* Safe
* SDBM_File
* Search
    * Dict
* SelectSaver
* SelfLoader
* SHA
* Shell
* SOAP
    * Defs
    * Envelope
    * EnvelopeMaker
    * GenericHashSerializer
    * GenericInputStream
    * GenericScalarSerializer
    * Lite
    * OutputStream
    * Packager
    * Parser
    * Transport
        * HTTP
            * Apache
            * CGI
            * Client
            * Server
        * LOCAL
        * MAILTO
        * POP3
        * TCP
    * TypeMapper
* Socket
* Symbol
* Sys
    * Hostname
    * Syslog
* Term
    * ANSIColor
    * Cap
    * Complete
    * ReadLine
* Test
    * Harness
* Text
    * Abbrev
    * ParseWords
    * Soundex
    * Tabs
    * Wrap
* Thread
    * Queue
    * Semaphore
    * Signal
    * Specific
* Tie
    * Array
    * Handle
    * Hash
    * RefHash
    * Scalar
    * SubstrHash
* Time
    * gmtime
    * Local
    * localtime
    * tm
* UDDI
    * Lite
* UNIVERSAL
* URI
    * data
    * Escape
    * file
    * Heuristic
    * ldap
    * URL
    * WithBase
* User
    * grent
    * pwent
* Win32
    * AuthenticateUser
    * ChangeNotify
    * Clipboard
    * Console
    * Event
    * EventLog
    * File
    * FileSecurity
    * Internet
    * IPC
    * Mutex
    * NetAdmin
    * NetResource
    * ODBC
    * OLE
        * Const
        * Enum
        * NEWS
        * NLS
        * TPJ
        * Variant
    * PerfLib
    * Pipe
    * Process
    * Registry
    * Semaphore
    * Service
    * Sound
    * TieRegistry
* Win32API
    * File
    * Net
    * Registry
* WWW
    * RobotRules
        * AnyDBM_File
* XML
    * Element
    * Parser
        * Expat
    * PPD
    * PPMConfig
    * ValidatingElement
* XSLoader

 HTTP::Daemon - a simple http server class


NAME

HTTP::Daemon - a simple http server class


SUPPORTED PLATFORMS

  • Linux
  • Solaris
  • Windows

SYNOPSIS

  use HTTP::Daemon;
  use HTTP::Status;
  my $d = new HTTP::Daemon;
  print "Please contact me at: <URL:", $d->url, ">\n";
  while (my $c = $d->accept) {
      while (my $r = $c->get_request) {
          if ($r->method eq 'GET' and $r->url->path eq "/xyzzy") {
              # remember, this is *not* recommened practice :-)
              $c->send_file_response("/etc/passwd");
          } else {
              $c->send_error(RC_FORBIDDEN)
          }
      }
      $c->close;
      undef($c);
  }


DESCRIPTION

Instances of the HTTP::Daemon class are HTTP/1.1 servers that listen on a socket for incoming requests. The HTTP::Daemon is a sub-class of IO::Socket::INET, so you can perform socket operations directly on it too.

The accept() method will return when a connection from a client is available. The returned value will be a reference to a object of the HTTP::Daemon::ClientConn class which is another IO::Socket::INET subclass. Calling the get_request() method on this object will read data from the client and return an HTTP::Request object reference.

This HTTP daemon does not fork(2) for you. Your application, i.e. the user of the HTTP::Daemon is reponsible for forking if that is desirable. Also note that the user is responsible for generating responses that conform to the HTTP/1.1 protocol. The HTTP::Daemon::ClientConn class provides some methods that make this easier.


METHODS

The following is a list of methods that are new (or enhanced) relative to the IO::Socket::INET base class.

$d = new HTTP::Daemon
The constructor takes the same parameters as the IO::Socket::INET constructor. It can also be called without specifying any parameters. The daemon will then set up a listen queue of 5 connections and allocate some random port number. A server that wants to bind to some specific address on the standard HTTP port will be constructed like this:
  $d = new HTTP::Daemon
        LocalAddr => 'www.someplace.com',
        LocalPort => 80;

$c = $d->accept([$pkg])
This method is the same as IO::Socket::accept but returns an HTTP::Daemon::ClientConn reference by default. It returns undef if you specify a timeout and no connection is made within that time.

$d->url
Returns a URL string that can be used to access the server root.

$d->product_tokens
Returns the name that this server will use to identify itself. This is the string that is sent with the Server response header. The main reason to have this method is that subclasses can override it if they want to use another product name.

The HTTP::Daemon::ClientConn is also a IO::Socket::INET subclass. Instances of this class are returned by the accept() method of HTTP::Daemon. The following additional methods are provided:

$c->get_request([$headers_only])
Read data from the client and turn it into an HTTP::Request object which is then returned. It returns undef if reading of the request fails. If it fails, then the HTTP::Daemon::ClientConn object ($c) should be discarded, and you should not call this method again. The $c->reason method might give you some information about why $c->get_request returned undef.

The $c->get_request method supports HTTP/1.1 request content bodies, including chunked transfer encoding with footer and self delimiting multipart/* content types.

The $c->get_request method will normally not return until the whole request has been received from the client. This might not be what you want if the request is an upload of a multi-mega-byte file (and with chunked transfer encoding HTTP can even support infinite request messages - uploading live audio for instance). If you pass a TRUE value as the $headers_only argument, then $c->get_request will return immediately after parsing the request headers and you are responsible for reading the rest of the request content. If you are going to call $c->get_request again on the same connection you better read the correct number of bytes.

$c->read_buffer([$new_value])
Bytes read by $c->get_request, but not used are placed in the read buffer. The next time $c->get_request is called it will consume the bytes in this buffer before reading more data from the network connection itself. The read buffer is invalid after $c->get_request has returned an undefined value.

If you handle the reading of the request content yourself you need to empty this buffer before you read more and you need to place unconsumed bytes here. You also need this buffer if you implement services like 101 Switching Protocols.

This method always return the old buffer content and can optionally replace the buffer content if you pass it an argument.

$c->reason
When $c->get_request returns undef you can obtain a short string describing why it happened by calling $c->reason.

$c->proto_ge($proto)
Return TRUE if the client announced a protocol with version number greater or equal to the given argument. The $proto argument can be a string like ``HTTP/1.1'' or just ``1.1''.

$c->antique_client
Return TRUE if the client speaks the HTTP/0.9 protocol. No status code and no headers should be returned to such a client. This should be the same as !$c->proto_ge(``HTTP/1.0'').

$c->force_last_request
Make sure that $c->get_request will not try to read more requests off this connection. If you generate a response that is not self delimiting, then you should signal this fact by calling this method.

This attribute is turned on automatically if the client announces protocol HTTP/1.0 or worse and does not include a ``Connection: Keep-Alive'' header. It is also turned on automatically when HTTP/1.1 or better clients send the ``Connection: close'' request header.

$c->send_status_line( [$code, [$mess, [$proto]]] )
Send the status line back to the client. If $code is omitted 200 is assumed. If $mess is omitted, then a message corresponding to $code is inserted. If $proto is missing the content of the $HTTP::Daemon::PROTO variable is used.

$c->send_crlf
Send the CRLF sequence to the client.

$c->send_basic_header( [$code, [$mess, [$proto]]] )
Send the status line and the ``Date:'' and ``Server:'' headers back to the client. This header is assumed to be continued and does not end with an empty CRLF line.

$c->send_response( [$res] )
Write a HTTP::Response object to the client as a response. We try hard to make sure that the response is self delimiting so that the connection can stay persistent for further request/response exchanges.

The content attribute of the HTTP::Response object can be a normal string or a subroutine reference. If it is a subroutine, then whatever this callback routine returns is written back to the client as the response content. The routine will be called until it return an undefined or empty value. If the client is HTTP/1.1 aware then we will use chunked transfer encoding for the response.

$c->send_redirect( $loc, [$code, [$entity_body]] )
Send a redirect response back to the client. The location ($loc) can be an absolute or relative URL. The $code must be one the redirect status codes, and defaults to ``301 Moved Permanently''

$c->send_error( [$code, [$error_message]] )
Send an error response back to the client. If the $code is missing a ``Bad Request'' error is reported. The $error_message is a string that is incorporated in the body of the HTML entity body.

$c->send_file_response($filename)
Send back a response with the specified $filename as content. If the file is a directory we try to generate an HTML index of it.

$c->send_file($fd);
Copy the file to the client. The file can be a string (which will be interpreted as a filename) or a reference to an IO::Handle or glob.

$c->daemon
Return a reference to the corresponding HTTP::Daemon object.


SEE ALSO

RFC 2068

the IO::Socket manpage, the Apache manpage


COPYRIGHT

Copyright 1996-1998, Gisle Aas

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

 HTTP::Daemon - a simple http server class