Apache::Request
A class to wrap request_rec data type.
Superclass
Object
Included Modules
Enumerable
Methods
<< obj-
String Output---Writes obj to the client output buffer. obj
will be converted to a string using
to_s. [] =- Sets the value of the specified response header. Deprecated: Use #headers_out? instead.
[str]- Returns the value of the specified request header. Deprecated: Use #headers_in? instead.
add_cgi_vars- Add the variables required by the CGI/1.1 protocol to the subprocess_env? table.
add_common_vars- Add other Apache CGI variables to the subprocess_env? table.
allow_options-
Returns the bitmap with specifies which options are enabled for the directory to which the request has been mapped. You can use the Apache module's options bitmask constants? to test for desired values.
For example:
# req is an instance of Apache::Request. def check_access(req) # Make sure that ExecCGI and Indexes are turned on for the Location # being served: if req.allow_options & Apache::OPT_EXECCGI == 0 || req.allow_options & Apache::OPT_INDEXES == 0 req.log_reason( "ExecCGI and/or Indexes are off in this directory", req.filename ) return Apache::FORBIDDEN end return Apache::OK end allow_overrides- Returns an Integer (?).
allowedallowed= int-
Returns/sets the bitvector (an
Integer) of the request methods that the handler can accommodate. You can set bits in this field using one or more request method constants?.Example:
include Apache Apache::request.allowed |= (1 << M_GET) Apache::request.allowed |= (1 << M_POST)
args-
Returns the quest string for CGI GET requests, and corresponds to the
portion of the URI following the
?. auth_nameauth_name= str- Returns/sets the authentication realm for the receiving request.
auth_typeauth_type= str-
Returns/sets the authentication type for the receiving request. Usually
one of
"Basic"or"Digest". binmode- Puts the client input data stream into binary mode. This is useful only in MS-DOS/Windows environments. Once a stream is in binary mode, it cannot be reset to nonbinary mode.
bytes_sent- Returns the number of bytes sent by the server to the client, excluding the HTTP headers. It is only useful after send_http_header? has been called.
cache_respcache_resp= val-
Returns/sets the flag that controls whether the response will have cache-control headers put into its response. If
cache_respis set to totrue, the response will have the following headers added:Pragma: no-cache Cache-control: no-cache
If set to
false, thePragmaandCache-controlheaders will be removed completely from the response headers, regardless of their content. cancel- Clears the output buffer.
connection- Returns the Apache::Connection object associated with the request.
construct_url(uri)-
Returns a fully-qualified URI
Stringfrom the path specified by uri using the request object's server name and port. content_encoding- Returns the MIME encoding type of the response, as set by the MIME-checking phase of the transaction.
content_encoding= str-
Set the MIME
Content-Encodingheader of the response. content_languages-
Returns the value of the
Content-Languagesof the response. This is typically set by the MIME-checking phase of the transaction. content_languages= str- Specifies Content-Languages of the response header.
content_length-
Returns the length of the incoming content as specified by the
Content-Lengthheader. Deprecated: Usereq.headers_in['Content-Length']instead. content_type- Returns the MIME content type of the response, as set by the MIME-checking phase of the transaction.
content_type= str-
Set the
Content-Typeheader of the response. custom_response(status,uri)-
Set the error document for the given status to the given uri. The status is a
Fixnumstatus code like those in the Apache module's HTTP response codes?.Example:
include Apache unless req.notes['username'] req.custom_response( HTTP_UNAUTHORIZED, "/noauth.html" ) return HTTP_UNAUTHORIZED end
default_charset-
Returns the name of the default character set, as defined by the
AddDefaultCharsetdirective. default_type-
Returns the value of the
DefaultTypedirective, or"text/plain"if not configured. dispatch_handlerdispatch_handler= str- Allows one to get/set the Ruby code which returns the dispatch handler for requests. This makes it possible to write your own dispatch handler.
each([rs]) {|line|...}-
Executes the block for every line, where lines are separated by the
separator string rs (
$/by default). each_byte {|ch|...}- Calls the given block once for each byte (0..255) in the input from the client, passing the byte as an argument.
each_header {|hdr,val|...}- Iterates over the headers in the request, calling the specified block with each header name and value. Deprecated: Use #headers_in? instead.
each_key {|hdr|...}- Iterates over the names of each header in the request, calling the specified block once with each one. Deprecated: Use #headers_in? instead.
each_line([rs]) {|line|...}- Synonym for Apache::Request#each?.
each_value {|val|...}- Iterates over the values of each header in the request, calling the specified block once with each one. Deprecated: Use #headers_in? instead.
eof-
Returns
trueif the client input data stream is at end of file. eof?- Synonym for Apache::Request#eof?.
err_headers_out- Returns the Apache::Table object for the headers which will be sent even when an error occurs, and which persist across internal redirects.
error_message- Returns the error message set by mod_ruby's internal exception-handler, if any.
escape_html(str)-
Returns the specified string with any '
&', '"', '<', or '>' characters escaped to their HTML entity equivalents. exception-
Returns the
Exceptionobject set by mod_ruby's internal exception-handler, if any. filenamefilename=- Returns/sets the translated physical pathname of the document as determined during the URI translation phase.
finfo-
Returns the
File::Statobject associated with the translated filename of the request, if any. If no physical file is associated with the transaction, the File::Stat object will be the same as that returned from testing a non-existant file. get_basic_auth_pw-
Returns the plaintext password entered by the user as a String. If there
was any error fetching the password, a
SystemExitexception is raised with its status code set to the status code returned by the call. getc- Returns the next 8-bit byte (0..255) from the data from the client. Returns nil if called at end of file.
gets([rs])-
Reads the next "line" from the I/O stream; lines are separated by the
separator string rs, which is
$/by default. A separator of nil reads the entire contents, and a zero-length separator reads the input a paragraph at a time (two successive newlines in the input separate paragraphs). The line read in will be returned and also assigned to $_. Returns nil if called at end of file. hard_timeout(msg)kill_timeoutreset_timeoutsoft_timeout(msg)-
Apache timeout interface methods. These methods are only available under Apache 1.x.
#hard_timeoutinitiates a "hard" timeout. If an IO operation takes longer than the time specified by theTimeoutdirective, the current handler will be aborted and Apache will immediately enter the logging phase.#soft_timeoutdoes not abort the current handler, but returns control to it when the timer expires after no-oping all input and output methods. After this occurs, Apache::Connection#aborted?? will returntrue.#reset_timeoutis used to reset the timer back to zero between reads or writes.#kill_timeoutcancels the timeout currently in effect when the IO operations it governs are finished.Example:
input = '' req.hard_timeout( "#{caller(0)[0]}: Reading request." ) req.each_line {|line| input << line req.reset_timeout } req.kill_timeout req.sync = true req.soft_timeout( "#{caller(0)[0]: Sending response headers." ) req.send_http_header req.kill_timeout req.soft_timeout( "#{caller(0)[0]: Sending response data." ) until output_data.empty? bytes = req.write( output_data ) if bytes.nonzero? req.reset_timeout output_data.slice!(0,bytes) end end req.kill_timeout header_only?-
Returns
trueif the request is a head-only request (ie.,req.request_method == 'HEAD'. headers_in- Returns the Apache::Table object for the request header.
headers_out- Returns the Apache::Table object for the response header.
hostname- Returns the hostname, as set by full URI or Host:.
initial?-
Returns
trueif the request is the initial request (ie., not an internal redirect or a subrequest). internal_redirect(uri)-
Redirect the current request internally to the specified (absolute) uri.
Example:
if req.headers_in['user-agent'] !~ /mozilla/i req.internal_redirect( "/unsupported-browser.html" ) end
last- Return the final Apache::Request object for the current chain or internal redirects or subrequests.
log_reason(msg,file)-
Output a file-processing log message that looks like:
access to #{file} failed for #{req.get_remote_host}, reason: #{msg} lookup_file(file)lookup_uri(uri)-
Will perform a sub-request to lookup a given uri or file, respectively. The data will not be strongly verified (won't go through most of the request cycle), but it will return a new request object that you can use to play with and perform operations on.
For example:
subr = r.lookup_uri('/non/existent/file.html?asdf=asdf&asdf=asdf') subr.status # ((* => 200 *)) subr.filename # ((* => '/usr/local/www/data/non' *)) subr = r.lookup_file('/etc/foo/bar/baz/non/existent/file.html?asdf=asdf&asdf=asdf') subr.status # ((* => 200 *)) subr.filename # ((* => '/etc/foo/bar/baz/non/existent/file.html' *))The moral of the story is that you have to be careful and perform your own data verification with a lookup. If you use
lookup_file(), then Apache assumes that the filename specified is authoritative. main-
Returns the main Apache::Request object, or
nilif the receiver is the main request. main?-
Returns
trueif the receiver is the initial request object or an internal redirect (ie., not a subrequest). method_number-
Returns the request method as a
Integer. You can compare them to the request method constants? above. next-
Returns the Apache::Request object for the next (newer) subrequest
or internal redirect, if any. Returns
nilif no such request exists. note_auth_failure- Set up the current request's response to indicate a failure to authenticate (ie., will send an "Authentication Required" message to the browser). It will call either note_basic_auth_failure? or note_digest_auth_failure?, depending on which kind of authentication is configured for the current directory.
note_basic_auth_failure- Set up the current request's response to indicate a failure to authenticate via HTTP Basic Authentication.
note_digest_auth_failure- Set up the current request's response to indicate a failure to authenticate via HTTP Digest Authentication.
notes- Returns the Apache::Table object which can be used to pass "notes" from one handler module to another.
output_buffer-
Returns the output buffer
Stringcurrently associated with the request. path_infopath_info= str- Returns/sets the additional path information that remains after the URI has been translated into a file path.
pos- Returns the current offset (in bytes) of the client input data stream.
pos= n- Seeks to the given position n (in bytes) in the client input data stream.
prev- Returns the Apache::Request object for the previous (older) subrequest or internal redirect.
print(arg...)-
Writes the given arg object(s) to the output buffer. If the output
record separator ($\) is not nil, it will be appended to the output. If no
arguments are given, prints $_. Objects that aren't strings will be
converted by calling their
to_smethod. Returnsnil. printf(fmt, arg...)- Formats and writes to the output buffer, converting parameters under control of the fmt string.
protocol-
Returns the name and version number of the protocol requested by the
browser (eg.,
"HTTP/1.1"). proxy?-
Returns
trueif the request is for a proxy URI. proxy_pass?-
Returns
trueif the request is for a pass-through-proxied URL. putc(ch)- Writes the given character ch (taken from a String or a Fixnum) to the output buffer.
puts(arg...)- Writes the given arg objects to the output buffer as with Apache::Request#print? . Writes a record separator (typically a newline) after any that do not already end with a newline sequence. If called with an array argument, writes each element on a new line. If called without arguments, outputs a single record separator.
read([len])- Read len bytes from the client.
readchar-
Reads a character as with Apache::Request#getc? , but raises an
EOFErroron end of file. readline([rs])-
Reads a line as with Apache::Request#gets? , but raises an
EOFErroron end of file. readlines([rs])-
Reads all of the lines from the client, and returns them in an
Array. Lines are separated by the optional separator string rs. register_cleanup {...}register_cleanup( plain, [child] )-
Register a cleanup handler for the request (plain) and/or any child
processes forked by the current child (child). Either handler may be
any object which responds to the
#callmethod (eg., aProc, aMethod, etc.). The plain cleanup handler may also be given in the form of a block. remote_host([type])- Returns the remote client's DNS hostname, or its IP address if the hostname cannot be looked up. The optional argument specifies what type of lookup should be performed. The remotehost constants can be used for the type argument.
remote_logname-
Returns the login name of the remote user if the host is running the
identd service (RFC 1413), or
nilif the name could not be looked up. This method also depends on the server having theIdentityCheckconfiguration directive turned on, which it is not by default. replace(str)- Replaces the output buffer with str.
request_method- Returns the request method as a string (eg., "GET", "HEAD", "POST").
request_time- Returns the time when the request started.
requires-
Returns an associative
Arrayof therequiredirectives that apply to the current request. Each entry is of the form:[ method_mask, requirement ]
where method_mask is a bitmap of the HTTP request methods that the requirement applies to, and requirement is the contents of the
requiredirective (ie., everything after the space).For example, given a config section like this:
<Limit GET POST> require valid-user </Limit> <Limit PUT DELETE> require group Admin </Limit>
the
requiresmethod would return something like:[ [ 5, "valid-user" ], [ 10, "group Admin" ] ]
The bitmask can be tested by left-shifting the mask by the method number, eg.,
get_mask = 1 << Apache::M_GET post_mask = 1 << Apache::M_POST
rewind-
Positions the client data stream to the beginning of input, resetting
linenoto zero. satisfies-
Returns an
Integerthat can be compared with one of the Apache module's satisfy constants? to test the type of access control that applies to the request. seek(offset, [whence])-
Seeks to a given offset offset in the stream according to the value
of whence:
IO::SEEK_CUR- Seeks to offset plus current position.
IO::SEEK_END- Seeks to anInteger plus end of stream (you probably want a negative value for offset).
IO::SEEK_SET(the default)- Seeks to the absolute location given by offset.
send_fd(io)-
Send the contents of the specified
IOobject to the client. Eg.,BannerFile = "/www/htdocs/banner.html" begin File::open( BannerFile, File::O_RDONLY ) {|ofh| req.send_fd(ofh) } rescue IOError => err req.log_reason( err.message, BannerFile ) return Apache::NOT_FOUND end send_http_header- Sends the HTTP response header. If you call this method more than once, only the first call will actually send it.
sent_http_header?-
Returns
trueif the header has been sent already. server- Returns the Apache::Server object associated with the request.
server_name-
Returns the server's public name as a
Stringsuitable for inclusion in self-referential URLs. server_port-
Returns the port the request was sent to as an
Integersuitable for inclusion in self-referential URLs. setup_cgi_env-
Clear the current environment and add CGI and common variables to the
subprocess_env? table. Then export the subprocess_env? table,
the variables defined in the server and directory configurations for the
current request, and the
MOD_RUBYandGATEWAY_INTERFACEvariables into the environment shared with subprocesses. get_client_block(bufsiz)setup_client_block([policy])should_client_blockshould_client_block?- Interface to Apache's internal request-reading functions. The policy argument accepts one of the blocking policy constants?.
signature-
Returns the server's signature footer line if the server's
ServerSignaturehas been turned on. statusstatus=- Returns/sets the numeric status code of the transaction.
status_linestatus_line= str-
Returns/sets the full text of the status line returned from Apache to the
remote browser (eg.,
200 OK). subprocess_env- Returns the Apache::Table object containing environment variables which should be passed to subprocesses.
sync=- Set the synchronization of both headers and response body IO.
sync_headersync_header=-
Returns/sets the status of header IO synchronization. If
sync_headeristrue, headers will be sent immediately as they are written, and remaining content will be buffered until the end of the request. sync_outputsync_output=-
Returns/sets the status of the synchronization of IO for the response
body. If
sync_outputistrue, all output will be sent immediately instead of buffering it until the end of the request. tell- Synonym for Apache::Request#pos?.
the_request-
Returns the first line of the request as a
String, for logging purposes. ungetc(ch)- Pushes back one character onto the date stream from the client, such that a subsequent buffered read will return it. Only one character may be pushed back before a subsequent read operation (that is, you will be able to read only the last of several characters that have been pushed back).
unparsed_uri- Returns the uri without any parsing performed.
uriuri= str- Returns/sets the path portion of the URI.
useruser= str- Portably set the authenticated username for the current request. For Apache 1.x, calling either of these methods just calls the equivalent method of the connection object, but since Apache 2.x moved the username into the main request object, this way of setting the username will work for either version.
write(str)-
Writes the given string str to the output buffer. If the argument is
not a string, it will be converted to a string using
to_s. Returns the number of bytes written.
Libapreq Support
If mod_ruby has been compiled with support for the Generic Apache Request library (libapreq), then the following methods will also be available.
cookiescookies=- Get/set the HTTP cookies (RFC 2109) associated with the request as a hash of Apache::Cookie objects keyed by cookie name. Note that setting the cookies hash does not automatically add them to the response. You must call Apache::Cookie#bake? on each one to add it to the response. *1
disable_uploads=-
Turns uploads on/off; If set to a
truevalue, Apache::Request#parse will raise an Apache::RequestError? if a file upload is attempted. disable_uploads?uploads_disabled?-
Returns
trueif uploads are disabled. param(name)- Returns a single parameter by String.
params(name)- Returns multiple parameters by Array.
paramtable-
Returns an Apache::ParamTable object which contains the request's
parsed parameters. Each parameter will be contained in an
Apache::MultiVal object, which allows it to be treated either like a
Stringor anArray. parse( [options] )-
If the request method is
GETorPOST, the query string arguments and the client form data will be read, parsed and saved. In addition, if the request method isPOSTand theContent-typeismultipart/form-data, any uploaded files will be written to temporary files which can be accessed with the corresponding parameters. The return value isOKon success; on an error, an error code is returned. The optional options hash sets options for the parsed request::post_max-
Specifies the limit for the size of POST data (in bytes). An
Apache::RequestErroris raised if the specified size is exceeded. :disable_uploads-
If set to a
truevalue, anApache::RequestErrorwill be raised if a file upload is attempted. :temp_dir- Specifies the directory where upload files are spooled. See Apache::Request#temp_dir?.
:upload_hook-
Specifies a
ProcorMethodto use as a callback that is run whenever file upload data is read. See Apache::Request#upload_hook?. :hook_data-
Set the third argument passed to every call to the
:upload_hook, if any.
post_maxpost_max=( bytes )-
Get/set the limit for the size of
POSTdata (in bytes). Apache::Request#parse will raise an Apache::RequestError? if the size is exceeded. temp_dirtemp_dir=-
Get/set the directory where upload files are spooled. On a system that
supports
link(2), the specified direction should be located on the same file system as the final destination file. upload_hookupload_hook=-
Specifies a
ProcorMethodto use as a callback that is run whenever file upload data is read. This can be used to write data to database instead of file, or to provide an upload progress meter during file uploads. Apache doesn't write the original data to the upload filehandle, so you have to write it yourself if needed. The buffer argument contains a copy of the input buffer read for this chunk of the upload, the upload argument is the Apache::Upload object associated with the file being uploaded, and arg is whatever was set as the upload hook user argument via Apache::Request#upload_hook_data? or the:hook_dataattribute of the configuration hash passed to Apache::Request#parse?.Example:
hook = Proc::new {|buffer,upload,arg| request.server.log_debug( "Read %d bytes from upload '%s'", buffer.length, upload.filename ) upload.io.write(buffer) } request.parse( :upload_hook => hook ) upload_hook_dataupload_hook_data=- Get/set the object that is passed as the third argument every time the Apache::Request#upload_hook? is called.
uploads-
Returns a hash of any uploaded files as Apache::Upload objects. The
hash will only be filled if the request method was
POSTand the request's 'Content-type' wasmultipart/form-data.
*1This may change in the future
Keyword(s):
References:[Apache::Cookie] [ClassReferenceManual] [Apache::Request] [Apache::Connection] [Apache]