A module to provide Apache functions.
add_version_component
chdir_file(str)
request
server_root
server_built
server_version
unescape_url(str)
Handler status return codes
HTTP response codes
Request method constants
For testing against the return value of Apache::Request#method_number.
M_CONNECT, M_COPY, M_DELETE, M_GET, M_INVALID, M_LOCK, M_MKCOL, M_MOVE, M_OPTIONS, M_PATCH, M_POST, M_PROPFIND, M_PROPPATCH, M_PUT, M_TRACE, M_UNLOCK, METHODS
Options bitmask constants
Constants for testing for enabled options via Apache::Request#allow_options.
OPT_ALL, OPT_EXECCGI, OPT_INCLUDES, OPT_INCNOEXEC, OPT_INDEXES, OPT_MULTI, OPT_NONE, OPT_SYM_LINKS, OPT_SYM_OWNER, OPT_UNSET
Satisfy constants
Constants for testing the return value of the Apache::Request#satisfies method.
SATISFY_ALL, SATISFY_ANY, SATISFY_NOSPEC
Remotehost constants
Constants which can be (optionally) passed to Apache::Request#remote_host to affect what type of lookup is performed.
REMOTE_DOUBLE_REV, REMOTE_HOST, REMOTE_NAME, REMOTE_NOLOOKUP
Blocking Policy constants
Constants which are used for setting the blocking policy via Apache::Request#setup_client_block.
REQUEST_NO_BODY, REQUEST_CHUNKED_ERROR, REQUEST_CHUNKED_DECHUNK, REQUEST_CHUNKED_PASS
A class to wrap request_rec
data type.
Object
Enumerable
<< obj
to_s
.[] =
[str]
add_cgi_vars
add_common_vars
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:
include Apache # Make sure that ExecCGI and Indexes are turned on for the Location # being served: unless req.allow_options & (OPT_EXECCGI|OPT_INDEXES) req.log_reason( "ExecCGI and/or Indexes are off in this directory", req.filename ) return FORBIDDEN end
allow_overrides
allowed
allowed= 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
?
.auth_name
auth_name= str
auth_type
auth_type= str
"Basic"
or "Digest"
.binmode
bytes_sent
cache_resp
cache_resp= val
Returns/sets the flag that controls whether the response will have
cache-control headers put into its response. If cache_resp
is set to
to true
, the response will have the following headers added:
Pragma: no-cache Cache-control: no-cache
If set to false
, the Pragma
and Cache-control
headers
will be removed completely from the response headers, regardless of their
content.
cancel
connection
construct_url(uri)
String
from the path specified by
uri using the request object's server name and port.content_encoding
content_encoding= str
Content-Encoding
header of the response.content_languages
Content-Languages
of the response. This is
typically set by the MIME-checking phase of the transaction.content_languages= str
content_length
Content-Length
header. Deprecated: Use
req.headers_in['Content-Length']
instead.content_type
content_type= str
Content-Type
header of the response.custom_response(status,uri)
Set the error document for the given status to the given
uri. The status is a Fixnum
status 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
AddDefaultCharset
directive.default_type
DefaultType
directive, or
"text/plain"
if not configured.dispatch_handler
dispatch_handler= str
each([rs]) {|line|...}
$/
by default).each_byte {|ch|...}
each_header {|hdr,val|...}
each_key {|hdr|...}
each_line([rs]) {|line|...}
each_value {|val|...}
eof
true
if the client input data stream is at end of file.eof?
err_headers_out
error_message
escape_html(str)
&
', '"
', '<
', or
'>
' characters escaped to their HTML entity equivalents.exception
Exception
object set by mod_ruby's internal
exception-handler, if any.filename
filename=
finfo
File::Stat
object 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
SystemExit
exception is
raised with its status code set to the status code returned by the call.getc
gets([rs])
$/
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_timeout
reset_timeout
soft_timeout(msg)
Apache timeout interface methods. These methods are only available under Apache 1.x.
#hard_timeout
initiates a "hard" timeout. If an IO operation takes
longer than the time specified by the Timeout
directive, the current
handler will be aborted and Apache will immediately enter the logging
phase.
#soft_timeout
does 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 return true
.
#reset_timeout
is used to reset the timer back to zero between
reads or writes.
#kill_timeout
cancels 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?
true
if the request is a head-only request (ie.,
req.request_method == 'HEAD'
.headers_in
headers_out
hostname
initial?
true
if 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
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
nil
if the
receiver is the main request.main?
true
if the receiver is the initial request object or an
internal redirect (ie., not a subrequest).method_number
Integer
. You can compare them to the
request method constants above. next
nil
if no such request exists.note_auth_failure
note_basic_auth_failure
note_digest_auth_failure
notes
output_buffer
String
currently associated with the request.path_info
path_info= str
pos
pos= n
prev
print(arg...)
to_s
method. Returns nil
.printf(fmt, arg...)
protocol
"HTTP/1.1"
).proxy?
true
if the request is for a proxy URI.proxy_pass?
true
if the request is for a pass-through-proxied URL.putc(ch)
puts(arg...)
read([len])
readchar
EOFError
on end of file.readline([rs])
EOFError
on end of file.readlines([rs])
Array
. Lines are separated by the optional separator string
rs.register_cleanup {...}
register_cleanup( plain, [child] )
#call
method (eg., a Proc
, a
Method
, etc.). The plain cleanup handler may also be given in
the form of a block.remote_host([type])
remote_logname
nil
if the name could not be
looked up. This method also depends on the server having the
IdentityCheck
configuration directive turned on, which it is not by
default.replace(str)
request_method
request_time
requires
Returns an associative Array
of the require
directives 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
require
directive (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 requires
method 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
lineno
to zero.satisfies
Integer
that 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])
IO::SEEK_CUR
IO::SEEK_END
IO::SEEK_SET
(the default)send_fd(io)
Send the contents of the specified IO
object 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
sent_http_header?
true
if the header has been sent already.server
server_name
String
suitable for inclusion
in self-referential URLs.server_port
Integer
suitable for
inclusion in self-referential URLs.setup_cgi_env
MOD_RUBY
and GATEWAY_INTERFACE
variables into the environment shared with subprocesses.get_client_block(bufsiz)
setup_client_block([policy])
should_client_block
should_client_block?
signature
ServerSignature
has been turned on.status
status=
status_line
status_line= str
200 OK
).subprocess_env
sync=
sync_header
sync_header=
sync_header
is true
, headers will be sent immediately as they are written, and
remaining content will be buffered until the end of the request.sync_output
sync_output=
sync_output
is true
, all output will be sent
immediately instead of buffering it until the end of the request.tell
the_request
String
, for logging
purposes.ungetc(ch)
unparsed_uri
uri
uri= str
user
user= str
write(str)
to_s
. Returns
the number of bytes written.If mod_ruby has been compiled with support for the Generic Apache Request library (libapreq), then the following methods will also be available.
cookies
cookies=
disable_uploads=
true
value,
Apache::Request#parse will raise an Apache::RequestError if a
file upload is attempted.disable_uploads?
uploads_disabled?
true
if uploads are disabled.param(name)
params(name)
paramtable
String
or an Array
.parse( [options] )
GET
or POST
, the query string
arguments and the client form data will be read, parsed and saved. In
addition, if the request method is POST
and the Content-type
is multipart/form-data
, any uploaded files will be written to
temporary files which can be accessed with the corresponding
parameters. The return value is OK
on success; on an error, an error
code is returned. The optional options hash sets options for the
parsed request:
:post_max
Apache::RequestError
is raised if the specified size is
exceeded.
:disable_uploads
true
value, an Apache::RequestError
will be
raised if a file upload is attempted.
:temp_dir
:upload_hook
Proc
or Method
to use as a callback that is
run whenever file upload data is read. See
Apache::Request#upload_hook.
:hook_data
:upload_hook
,
if any.
post_max
post_max=( bytes )
POST
data (in
bytes). Apache::Request#parse will raise an
Apache::RequestError if the size is exceeded.temp_dir
temp_dir=
link(2)
, the specified direction should be located on the
same file system as the final destination file.upload_hook
upload_hook=
Specifies a Proc
or Method
to 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_data
attribute 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_data
upload_hook_data=
uploads
POST
and the
request's 'Content-type
' was multipart/form-data
.A class for manipulating a request's HTTP cookies. This functionality is only available if mod_ruby is compiled with Generic Apache Request library (libapreq) support. A hash of the cookies associated with a request can be fetched by calling Apache::Request#cookies.
Object
strftime
-compatible date format used in the #expires
attribute for absolute expirations.
new( request, [options] )
Apache::Cookie
for the specified request (an
Apache::Request object). The optional options Hash may be used
to initialize the cookie's attributes. The following keys are supported:
:name
name
field to the given value.
:value
values
field.
:expires
expires
field to the calculated date String
or
Time
object. See Apache::Cookie#expires for a
listing of format options. The default is nil
.
:domain
domain
field to the given value. The default is
nil
.
:path
path
field to the given value. The default path is
derived from the requested uri.
:secure
secure
field to true
or false
.
bake
domain
domain=
Get/set the domain
attribute of the cookie. From the Netscape spec:
When searching the cookie list for valid cookies, a comparison of the (({domain})) attributes of the cookie is made with the Internet domain name of the host from which the URL will be fetched. If there is a tail match, then the cookie will go through path matching to see if it should be sent. "Tail matching" means that (({domain})) attribute is matched against the tail of the fully qualified domain name of the host. A (({domain})) attribute of "acme.com" would match host names "anvil.acme.com" as well as "shipping.crate.acme.com". Only hosts within the specified domain can set a cookie for a domain and domains must have at least two (2) or three (3) periods in them to prevent domains of the form: ".com", ".edu", and "va.us". Any domain that fails within one of the seven special top level domains listed below only require two periods. Any other domain requires at least three. The seven special top level domains are: "COM", "EDU", "NET", "ORG", "GOV", "MIL", and "INT". The default value of (({domain})) is the host name of the server which generated the cookie response.
expires
expires=
expires
field. The value can be either a Time
object or a
String
in any of the following formats:
+30s
+10m
+1h
-1d
now
+3M
+10y
Thursday, 25-Apr-1999 00:40:33 GMT
name
name=
path
path=
Get/set the cookie's path
attribute. From the Netscape spec:
The (({path})) attribute is used to specify the subset of URLs in a domain for which the cookie is valid. If a cookie has already passed (({domain})) matching, then the pathname component of the URL is compared with the path attribute, and if there is a match, the cookie is considered valid and is sent along with the URL request. The path "/foo" would match "/foobar" and "/foo/bar.html". The path "/" is the most general path. If the (({path})) is not specified, it as assumed to be the same path as the document being described by the header which contains the cookie.
secure=
secure
flag to the given value.secure?
true
if the cookie's secure
flag is set.to_s
String
.value
String
.values
Array
.value=
Set the value of the cookie. If the new value responds to #each
,
#each
will be called, and the result of calling #to_s
on each
iterated value will be added to the cookie's value. If the new value
doesn't respond to #each
, the result of calling #to_s
on the
value itself is added.
For example:
svarcookie = Apache::Cookie::new( req, :name => 'sessionvars' ) svarcookie.value = [ Time::now, req.headers_in['host'] ] svarcookie.bake
Apache::MultiVal
is a multi-valued datatype for Apache request
parameters. Instances of it are used to represent request parameters in a
parameter table in an Apache mod_ruby application. Apache::MultiVal makes each
parameter in the table capable of being treated like both a String and an Array
by delegating String and Array instance methods to either the first value or the
Array of values, respectively. The instance methods which String and Array share
in common are delegated to the String, except #each, #[], and #[]=, which are
sent to the Array. This allows the code to be kept simple: if you only ever
expect a parameter to have a single value, you can treat it as if it is a
String:
foo = request.paramtable['foo'].downcase
and treat parameters which can have multiple values (mostly) as an Array:
bars = request.paramtable['bar'].collect {|val| val.downcase}
For the methods that Array and String share in common, you can cast the parameter to the object you wish with the normal #to_a and #to_s methods:
foo = request.paramtable['foo'] if foo.to_a.length > 1 request.log_warn( "Request had more than one 'foo' parameter: %s", foo.to_a.inspect )
Of course, the Array's length could be obtained with foo.nitems, too, since Array#nitems isn't obscured by String's instance methods.
As indicated above, some of Array's methods are obscured by those of String, so you should take special note when using them to be sure you know what you'll be getting. For the version of Ruby that was most recent as of this writing (ruby 1.8.0 (2003-06-27)), these are:
"*", "+", "<<", "<=>", "==", "concat", "delete", "empty?", "eql?", "hash", "include?", "index", "insert", "inspect", "length", "replace", "reverse", "reverse!", "rindex", "size", "slice", "slice!", "to_s"
A class that provides an interface for accessing files uploaded by the client. This class is only available when mod_ruby is compiled with the Generic Apache Request Library (libapreq).
Object
filename
info
io
Returns a new IO object opened (readonly) to the temporary file associated
with the upload. Alias: fp
.
Example:
upload = req.uploads['the-file'] tempfile = upload.io destfile = File::open( "/some/where/thefile.txt", File::WRONLY ) {|safefile| tempfile.each {|line| safefile.print(line) } }
name
size
tempname
type
Returns the file's MIME content type. This is a shortcut for accessing the uploaded file's 'Content-Type' header:
upload = req.uploads['the-file'] upload.info['content-type'] == upload.type
A class to wrap table
data type.
Object
Enumerable
clear
self[name]
get(name)
self[name]= val
set(name, val)
setn(name, val)
merge(name, val)
mergen(name, val)
add(name, val)
addn(name, val)
unset(name)
each {|key,val|...}
each_key {|key|...}
each_value {|val|...}
A derivative of Apache::Table that returns Apache::MultiVal objects for values instead of Strings.
A class to wrap global and virtual server configuration and utility methods. Can be fetched via Apache::Request#server.
Object
access_confname
admin
defn_line_number
defn_name
document_root
DocumentRoot
directive.error_fname
gid
hostname
is_virtual
virtual?
true
if the server is a virtual host.limit_req_fields
limit_req_fieldsize
limit_req_line
log_alert(fmt,*args)
log_crit(fmt,*args)
log_debug(fmt,*args)
log_emerg(fmt,*args)
log_error(fmt,*args)
log_info(fmt,*args)
log_notice(fmt,*args)
log_warn(fmt,*args)
LogLevel
is the
specified level or above. The fmt and args are used the same
way as the arguments to printf
.loglevel
Integer
between 1 and 8; 1
being the least verbose (emerg) and 8 being the most verbose (debug).names
ServerAlias
directive.path
ServerPath
directive.port
send_buffer_size
srm_confname
keep_alive
keep_alive?
keep_alive_max
keep_alive_timeout
timeout
Timeout
,
KeepAliveTimeout
, MaxKeepAliveRequests
, and the
KeepAlive
directives.uid
wild_names
A class to wrap client socket connection records; may be fetched via Apache::Request#connection.
Object
aborted?
true
if a timeout set by
Apache::Request#soft_timeout occurs while reading or
writing to the client.auth_type
auth_type= str
String
.
These methods are only implemented when running under Apache 1.x.local_host
local_ip
local_port
remote_host
remote_ip
String
.remote_logname
remote_port
user
user= str
*1if implemented
*2if implemented
*3This may change in the future