lua.xml revision e8d4816269fa7d1fdeec38efc75aa055721c0631
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE manualpage SYSTEM "/style/manualpage.dtd">
<?xml-stylesheet type="text/xsl" href="/style/manual.en.xsl"?>
<!-- $LastChangedRevision: 1353955 $ -->
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<manualpage metafile="lua.xml.meta">
<parentdocument href="./">Developer</parentdocument>
<title>Creating hooks and scripts with mod_lua</title>
<summary>
<p>This document expands on the <module>mod_lua</module> documentation and explores
additional ways of using mod_lua for writing hooks and scripts.</p>
</summary>
<seealso><a href="/mod/mod_lua.html">mod_lua</a></seealso>
<seealso><a href="modguide.html">Developing modules for Apache 2.4</a></seealso>
<seealso><a href="request.html">Request Processing in Apache 2.4</a></seealso>
<seealso><a href="hooks.html">Apache 2.x Hook Functions</a></seealso>
<section id="introduction"><title>Introduction</title>
<section id="what"><title>What is mod_lua</title>
<p>
Stuff about what <module>mod_lua</module> is goes here.
</p>
</section>
<section id="contents"><title>What we will be discussing in this document</title>
<p>
This document will discuss several cases where <module>mod_lua</module> can be used
to either ease up a phase of the request processing or create more transparency in
the logic behind a decision made in a phase.
</p>
</section>
<section id="prerequisites"><title>Prerequisites</title>
<p>
First and foremost, you are expected to have a basic knowledge of how the Lua
programming language works. In most cases, we will try to be as pedagogical
as possible and link to documents describing the functions used in the
examples, but there are also many cases where it is necessary to either
just assume that "it works" or do some digging yourself into what the hows
and whys of various function calls.
</p>
</section>
</section>
<section id="enabling"><title>Optimizing mod_lua for production servers</title>
<section><title>Setting a scope for Lua states</title>
<p>
Setting the right <directive module="mod_lua">LuaScope</directive> setting
for your Lua scripts can be essential to your server's
performance. By default, the scope is set to <code>once</code>, which means
that every call to a Lua script will spawn a new Lua state that handles that
script and is destroyed immediately after. This option keeps the memory
footprint of mod_lua low, but also affects the processing speed of a request.
If you have the memory to spare, you can set the scope to <code>thread</code>,
which will make mod_lua spawn a Lua state that lasts the entirity of a thread's
lifetime, speeding up request processing by 2-3 times. Since mod_lua will create
a state for each script, this may be an expensive move, memory-wise, so to
compromise between speed and memory usage, you can choose the <code>server</code>
option to create a pool of Lua states to be used. Each request for a Lua script or
a hook function will then acquire a state from the pool and release it back when it's
done using it, allowing you to still gain a significant performance increase, while
keeping your memory footprint low. Some examples of possible settings are:
</p>
<highlight language="config">
LuaScope once
LuaScope thread
LuaScope server 5 40
</highlight>
<p>
As a general rule of thumb: If your server has none to low usage, use <code>once</code>
or <code>request</code>, if your server has low to medium usage, use the <code>server</code>
pool, and if it has high usage, use the <code>thread</code> setting. As your server's
load increases, so will the number of states being actively used, and having your scope
set to <code>once/request/conn</code> will stop being beneficial to your memory footprint.
</p>
<p>
<strong>Note:</strong> The <code>min</code> and <code>max</code> settings for the
<code>server</code> scope denotes the minimum and maximum states to keep in a pool per
server <em>process</em>, so keep this below your <code>ThreadsPerChild</code> limit.
</p>
</section>
<section><title>Using code caching</title>
<p>
By default, <module>mod_lua</module> stats each Lua script to determine whether a reload
(and thus, a re-interpretation and re-compilation) of a script is required. This is managed
through the <directive module="mod_lua">LuaCodeCache</directive> directive. If you are running
your scripts on a production server, and you do not need to update them regularly, it may be
advantageous to set this directive to the <code>forever</code> value, which will cause mod_lua
to skip the stat process and always reuse the compiled byte-code from the first access to the
script, thus speeding up the processing. For Lua hooks, this can prove to increase peformance,
while for scripts handled by the <code>lua-script</code> handler, the increase in performance
may be negligible, as files httpd will stat the files regardless.
</p>
</section>
<section><title>Keeping the scope clean</title>
<p>
For maximum performance, it is generally recommended that any initialization of libraries,
constants and master tables be kept outside the handle's scope:
</p>
<highlight language="lua">
--[[ This is good practice ]]--
require "string"
require "someLibrary"
local masterTable = {}
local constant = "Foo bar baz"
function handle(r)
do_stuff()
end
</highlight>
<highlight language="lua">
--[[ This is bad practice ]]--
require "string"
function handle(r)
require "someLibrary"
local masterTable = {}
local constant = "Foo bar baz"
do_stuff()
end
</highlight>
</section>
</section>
<section id="basic_remap"><title>Example 1: A basic remapping module</title>
<p>
</p>
<highlight language="config">
LuaHookTranslateName /path/too/foo.lua remap
</highlight>
<!-- BEGIN EXAMPLE CODE -->
<highlight language="lua">
--[[
Simple remap example.
This example will rewrite /foo/test.bar to the physical file
/internal/test, somewhat like how mod_alias works.
]]--
function remap(r)
-- Test if the URI matches our criteria
local barFile = r.uri:match("/foo/([a-zA-Z0-9]+%.bar)")
if barFile then
r.filename = "/internal/" .. barFile
end
return apache2.OK
end
</highlight>
<!-- END EXAMPLE CODE -->
<!-- BEGIN EXAMPLE CODE -->
<highlight language="lua">
--[[
Advanced remap example.
This example will evaluate some conditions, and based on that,
remap a file to one of two destinations, using a rewrite map.
]]--
local map = {
photos = {
source = [[^/photos/(.+)\.png$]],
destination = [[/uploads/www/$1.png]],
proxy = false
},
externals = {
source = [[^/ext/(.*)$]],
destination = [[http://www.example.com/$1]],
proxy = true
}
}
function interpolateString(s,v)
return s:gsub("%$(%d+)", function(a) return v[tonumber(a)] end)
end
function remap(r)
-- browse through the rewrite map
for key, entry in pairs(map) do
-- Match source regex against URI
local match = apache2.regex(r, entry.source, r.uri) then
if match and match[0] then
r.filename = interpolateString(entry.destination, match)
-- Is this a proxied remap?
if entry.proxy then
r.handler = "proxy-server" -- tell mod_proxy to handle this
r.proxyreq = apache2.PROXYREQ_REVERSE -- We'll want to do a reverse proxy
r.filename = "proxy:" .. r.filename -- Add the proxy scheme to the destination
end
return apache2.OK
end
end
return apache2.DECLINED
end
</highlight>
<!-- END EXAMPLE CODE -->
<p>
bla bla
</p>
</section>
<section id="mass_vhost"><title>Example 2: Mass virtual hosting</title>
<p>
</p>
<highlight language="config">
LuaHookTranslateName /path/too/foo.lua mass_vhost
</highlight>
<!-- BEGIN EXAMPLE CODE -->
<highlight language="lua">
--[[
Simple mass vhost script
This example will check a map for a virtual host and rewrite filename and
document root accordingly.
]]--
local vhosts = {
{ domain = "example.com", home = "/www/example.com" },
{ domain = "example.org", home = "/nfs/ext1/example.org" }
}
function mass_vhost(r)
-- Match against our hostname
for key, entry in pairs(vhosts) do
-- match against either host or *.host:
if apache2.strcmp_match(r.hostname, entry.domain) or
apache2.strcmp_match(r.hostname, "*." .. entry.domain) then
-- If it matches, rewrite filename and set document root
local filename = r.filename:sub(r.document_root:len()+1)
r.filename = entry.home .. filename
apahce2.set_document_root(entry.home)
return apache2.OK
end
end
return apache2.DECLINED
end
</highlight>
<!-- END EXAMPLE CODE -->
<!-- BEGIN EXAMPLE CODE -->
<highlight language="lua">
--[[
Advanced mass virtual hosting
This example will query a database for vhost entries and save them for
60 seconds before checking for updates. For best performance, such scripts
should generally be run with LuaScope set to 'thread' or 'server'
]]--
local cached_vhosts = {}
local timeout = 60
-- Function for querying the database for saved vhost entries
function query_vhosts(host)
if not cached_vhosts[host] or (cached_vhosts[host] and cached_vhosts[host].updated &lt; os.time() - timeout) then
local db = apache2.dbopen(r,"mod_dbd")
local _host = db:escape(_host)
local res, err = db:query( ("SELECT `destination` FROM `vhosts` WHERE `hostname` = '%s' LIMIT 1"):format(_host) )
if res and #res == 1 then
cached_vhosts[host] = { updated = os.time(), destination = res[1][1] }
else
cached_vhosts[host] = nil
end
db:close()
end
if cached_vhosts[host] then
return cached_vhosts[host].destination
else
return nil
end
end
function mass_vhost(r)
-- Check whether the hostname is in our database
local destination = query_vhosts(r.hostname)
if destination then
-- If found, rewrite and change document root
local filename = r.filename:sub(r.document_root:len()+1)
r.filename = destination .. filename
apahce2.set_document_root(destination)
return apache2.OK
end
return apache2.DECLINED
end
</highlight>
<!-- END EXAMPLE CODE -->
<p>
bla bla
</p>
</section>
<section id="basic_auth"><title>Example 3: A basic authorization hook</title>
<highlight language="config">
LuaHookAuthChecker /path/too/foo.lua check_auth
</highlight>
<!-- BEGIN EXAMPLE CODE -->
<highlight language="lua">
--[[
A simple authentication hook that checks a table containing usernames and
passwords of two accounts.
]]--
local accounts = {
bob = 'somePassword',
jane = 'Iloveponies'
}
-- Function for parsing the Authorization header into a username and a password
function parse_auth(str)
local user,pass = nil, nil
if str and str:len() > 0 then
str = apache2.base64_decode(auth):sub(7));
user, pass = auth:match("([^:]+)%:([^:]+)")
end
return user, pass
end
-- The authentication hook
function check_auth(r)
local user, pass = parse_auth(r.headers_in['Authorization'])
local authenticated = false
if user and pass then
if accounts[user] and accounts[user] == pass then
authenticated = true
r.user = user
end
end
r.headers_out["WWW-Authenticate"] = 'Basic realm="Super secret zone"'
if not authenticated then
return 401
else
return apache2.OK
end
end
</highlight>
<!-- END EXAMPLE CODE -->
<!-- BEGIN EXAMPLE CODE -->
<highlight language="lua">
--[[
An advanced authentication checker with a database backend,
caching account entries for 1 minute
]]--
local timeout = 60 -- Set account info to be refreshed every minute
local accounts = {}
-- Function for parsing the Authorization header into a username and a password
function parse_auth(str)
local user,pass = nil, nil
if str and str:len() > 0 then
str = apache2.base64_decode(auth):sub(7));
user, pass = auth:match("([^:]+)%:([^:]+)")
end
return user, pass
end
-- Function for querying the database for the account's password (stored as a salted SHA-1 hash)
function fetch_password(user)
if not accounts[user] or (accounts[user] and accounts[user].updated &lt; os.time() - timeout) then
local db = apache2.dbopen(r, "mod_dbd")
local usr = db:escape(user)
local res, err = db:query( ("SELECT `password` FROM `accounts` WHERE `user` = '%s' LIMIT 1"):format(usr) )
if res and #res == 1 then
accounts[user] = { updated = os.time(), password = res[1][1] }
else
accounts[user] = nil
end
db:close()
end
if accounts[user] then
return accounts[user].password
else
return nil
end
end
-- The authentication hook
function check_auth(r)
local user, pass = parse_auth(r.headers_in['Authorization'])
local authenticated = false
if user and pass then
pass = apache2.sha1("addSomeSalt" .. pass)
local stored_pass = fetch_password(user)
if stored_pass and pass == stored_pass then
authenticated = true
r.user = user
end
end
r.headers_out["WWW-Authenticate"] = 'Basic realm="Super secret zone"'
if not authenticated then
return 401
else
return apache2.OK
end
end
</highlight>
<!-- END EXAMPLE CODE -->
</section>
<section id="authz"><title>Example 4: Authorization using LuaAuthzProvider</title>
<highlight language="config">
LuaAuthzProvider rights /path/to/lua/script.lua rights_handler
&lt;Directory /www/private&gt;
Require rights member
&lt;/Directory&gt;
&lt;Directory /www/admin&gt;
Require rights admin
&lt;/Directory&gt;
</highlight>
<highlight language="lua">
--[[
This script has two user groups; members and admins, and whichever
is refered to by the "Require rights" directive is checked to see
if the authenticated user belongs to this group.
]]--
local members = { "rbowen", "humbedooh", "igalic", "covener" }
local admins = { "humbedooh" }
function rights_handler(r, what)
if r.user == nil then
return apache2.AUTHZ_AUTHZ_DENIED_NO_USER
end
if what == "member" then
for k, v in pairs(members) do
if r.user == v then
return apache2.AUTHZ_GRANTED
end
end
elseif what == "admin" then
for k, v in pairs(admins) do
if r.user == v then
return apache2.AUTHZ_GRANTED
end
end
end
return apache2.AUTHZ_DENIED
end
</highlight>
</section>
<section id="map_handler"><title>Example 5: Overlays using LuaMapHandler</title>
<highlight language="config">
LuaMapHandler ^/portal/([a-z]+)/ /path/to/lua/script.lua handle_$1
</highlight>
</section>
<section id="mod_status_lua"><title>Example 6: Basic Lua scripts</title>
</section>
<section id="String_manipulation">
<title>HTTPd bindings: String manipulation</title>
<p>
<a href="#apache2.base64_encode">apache2.base64_encode</a>
<br/>
<a href="#apache2.base64_decode">apache2.base64_decode</a>
<br/>
<a href="#apache2.escape">apache2.escape</a>
<br/>
<a href="#apache2.unescape">apache2.unescape</a>
<br/>
<a href="#apache2.escapehtml">apache2.escapehtml</a>
<br/>
<a href="#apache2.md5">apache2.md5</a>
<br/>
<a href="#apache2.sha1">apache2.sha1</a>
<br/>
<a href="#apache2.os_escape_path">apache2.os_escape_path</a>
<br/>
<a href="#apache2.escape_logitem">apache2.escape_logitem</a>
<br/>
</p>
<section id="apache2.base64_decode">
<title>apache2.base64_decode(
request_rec<em> r</em>,  string<em> string</em>
)
</title>
<p>
Decodes a base64-encoded string
</p>
<p>
<em>Arguments:</em>
</p>
<table border="1">
<tr>
<th>Argument</th>
<th>Description</th>
</tr>
<tr>
<td>r</td>
<td>The mod_lua request handle</td>
</tr>
<tr>
<td>string</td>
<td>The string to decode</td>
</tr>
</table>
<p>
<em>Return value(s):</em>
<br/>
The base64-decoded string.
</p>
<p>
<em>Example:</em>
</p>
<highlight language="lua">
local str = "This is a test"
local encoded = apache2.base64_encode(str)
local decoded = apache2.base64_decode(encoded)
</highlight>
<p> </p>
</section>
<section id="apache2.base64_encode">
<title>apache2.base64_encode(
request_rec<em> r</em>,  string<em> string</em>
)
</title>
<p>
Encodes a string using the base64 encoding scheme.
</p>
<p>
<em>Arguments:</em>
</p>
<table border="1">
<tr>
<th>Argument</th>
<th>Description</th>
</tr>
<tr>
<td>r</td>
<td>The mod_lua request handle</td>
</tr>
<tr>
<td>string</td>
<td>The string to encode</td>
</tr>
</table>
<p>
<em>Example:</em>
</p>
<highlight language="lua">
local str = "This is a test"
local encoded = apache2.base64_encode(str)
local decoded = apache2.base64_decode(encoded)
</highlight>
<p> </p>
</section>
<section id="apache2.escape">
<title>apache2.escape(
request_rec<em> r</em>,  string<em> string</em>
)
</title>
<p>
url-escapes a string
</p>
<p>
<em>Arguments:</em>
</p>
<table border="1">
<tr>
<th>Argument</th>
<th>Description</th>
</tr>
<tr>
<td>r</td>
<td>The mod_lua request handle</td>
</tr>
<tr>
<td>string</td>
<td>The string to escape</td>
</tr>
</table>
<p>
<em>Return value(s):</em>
<br/>
The URL-escaped string.
</p>
<p>
<em>Example:</em>
</p>
<highlight language="lua">
local str = "This is a test"
local escaped = apache2.escape(str)
print(escaped) -- prints "This+is+a+test"
</highlight>
<p> </p>
</section>
<section id="apache2.escape_logitem">
<title>apache2.escape_logitem(
request_rec<em> r</em>,  string<em> path</em>
)
</title>
<p>
Escape a string for logging
</p>
<p>
<em>Arguments:</em>
</p>
<table border="1">
<tr>
<th>Argument</th>
<th>Description</th>
</tr>
<tr>
<td>r</td>
<td>The mod_lua request handle</td>
</tr>
<tr>
<td>path</td>
<td>The string to escape</td>
</tr>
</table>
<p>
<em>Return value(s):</em>
<br/>
The converted string
</p>
<p> </p>
</section>
<section id="apache2.escapehtml">
<title>apache2.escapehtml(
request_rec<em> r</em>,  string<em> html</em>,  boolean<em> toasc</em>
)
</title>
<p>
Escapes HTML entities.
</p>
<p>
<em>Arguments:</em>
</p>
<table border="1">
<tr>
<th>Argument</th>
<th>Description</th>
</tr>
<tr>
<td>r</td>
<td>The mod_lua request handle</td>
</tr>
<tr>
<td>html</td>
<td>The HTML code to escape</td>
</tr>
<tr>
<td>toasc</td>
<td>Whether to escape all non-ASCI characters as &amp;#nnn;</td>
</tr>
</table>
<p>
<em>Return value(s):</em>
<br/>
The escaped HTML code.
</p>
<p>
<em>Example:</em>
</p>
<highlight language="lua">
local html = "&lt;b&gt;Testing!&lt;/b&gt;"
local escaped = apache2.escapehtml(html)
r:puts(escaped) -- prints "&amp;lt;b&amp;gt;Testing!&amp;lt;/b&amp;gt;"
</highlight>
<p> </p>
</section>
<section id="apache2.md5">
<title>apache2.md5(
request_rec<em> r</em>,  string<em> string</em>
)
</title>
<p>
Computes an MD5 digest sum based on a string (binary safe)
</p>
<p>
<em>Arguments:</em>
</p>
<table border="1">
<tr>
<th>Argument</th>
<th>Description</th>
</tr>
<tr>
<td>r</td>
<td>The mod_lua request handle</td>
</tr>
<tr>
<td>string</td>
<td>The (binary) string to digest</td>
</tr>
</table>
<p>
<em>Return value(s):</em>
<br/>
The MD5 digest sum of the data provided
</p>
<p>
<em>Example:</em>
</p>
<highlight language="lua">
local text = "The quick brown fox jumps over the lazy dog"
local md5 = apache2.md51(text)
r:puts(md5) -- prints out "9e107d9d372bb6826bd81d3542a419d6"
</highlight>
<p> </p>
</section>
<section id="apache2.os_escape_path">
<title>apache2.os_escape_path(
request_rec<em> r</em>,  string<em> path</em>,  boolean<em> partial</em>
)
</title>
<p>
convert an OS path to a URL in an OS dependant way.
</p>
<p>
<em>Arguments:</em>
</p>
<table border="1">
<tr>
<th>Argument</th>
<th>Description</th>
</tr>
<tr>
<td>r</td>
<td>The mod_lua request handle</td>
</tr>
<tr>
<td>path</td>
<td>The path to convert</td>
</tr>
<tr>
<td>partial</td>
<td>partial if set, assume that the path will be appended to something with a '/' in it (and thus does not prefix "./")</td>
</tr>
</table>
<p>
<em>Return value(s):</em>
<br/>
The converted URL
</p>
<p>
<em>Example:</em>
</p>
<highlight language="lua">
local path = ap_os_escape_path("C:/foo/bar.txt")
</highlight>
<p> </p>
</section>
<section id="apache2.sha1">
<title>apache2.sha1(
request_rec<em> r</em>,  string<em> string</em>
)
</title>
<p>
Computes an SHA-1 digest sum based on a string (binary safe)
</p>
<p>
<em>Arguments:</em>
</p>
<table border="1">
<tr>
<th>Argument</th>
<th>Description</th>
</tr>
<tr>
<td>r</td>
<td>The mod_lua request handle</td>
</tr>
<tr>
<td>string</td>
<td>The (binary) string to digest</td>
</tr>
</table>
<p>
<em>Return value(s):</em>
<br/>
The SHA-1 digest sum of the data provided
</p>
<p>
<em>Example:</em>
</p>
<highlight language="lua">
local text = "The quick brown fox jumps over the lazy dog"
local sha1 = apache2.sha1(text)
r:puts(sha1) -- prints out "2fd4e1c67a2d28fced849ee1bb76e7391b93eb12"
</highlight>
<p> </p>
</section>
<section id="apache2.unescape">
<title>apache2.unescape(
request_rec<em> r</em>,  string<em> string</em>
)
</title>
<p>
unescapes an URL-escaped string
</p>
<p>
<em>Arguments:</em>
</p>
<table border="1">
<tr>
<th>Argument</th>
<th>Description</th>
</tr>
<tr>
<td>r</td>
<td>The mod_lua request handle</td>
</tr>
<tr>
<td>string</td>
<td>The string to unescape</td>
</tr>
</table>
<p>
<em>Return value(s):</em>
<br/>
The URL-unescaped string
</p>
<p>
<em>Example:</em>
</p>
<highlight language="lua">
local str = "This+is+a+test"
local unescaped = apache2.unescape(str)
print(unescaped) -- prints "This is a test"
</highlight>
<p> </p>
</section>
</section>
<section id="Request_handling">
<title>HTTPd bindings: Request handling</title>
<p>
<a href="#apache2.requestbody">apache2.requestbody</a>
<br/>
<a href="#apache2.add_input_filter">apache2.add_input_filter</a>
<br/>
<a href="#apache2.get_basic_auth_pw">apache2.get_basic_auth_pw</a>
<br/>
<a href="#apache2.set_document_root">apache2.set_document_root</a>
<br/>
<a href="#apache2.set_context_prefix">apache2.set_context_prefix</a>
<br/>
<a href="#apache2.get_server_name_for_url">apache2.get_server_name_for_url</a>
<br/>
<a href="#apache2.set_keepalive">apache2.set_keepalive</a>
<br/>
<a href="#apache2.make_etag">apache2.make_etag</a>
<br/>
<a href="#apache2.send_interim_response">apache2.send_interim_response</a>
<br/>
</p>
<section id="apache2.add_input_filter">
<title>apache2.add_input_filter(
request_rec<em> r</em>,  string<em> filter</em>
)
</title>
<p>
Adds an input filter to the request
</p>
<p>
<em>Arguments:</em>
</p>
<table border="1">
<tr>
<th>Argument</th>
<th>Description</th>
</tr>
<tr>
<td>r</td>
<td>The mod_lua request handle</td>
</tr>
<tr>
<td>filter</td>
<td>The name of the filter handler to add</td>
</tr>
</table>
<p>
<em>Example:</em>
</p>
<highlight language="lua">
apache2.add_input_filter(r, "SPAM_FILTER") -- Check input for spam..?
</highlight>
<p> </p>
</section>
<section id="apache2.get_basic_auth_pw">
<title>apache2.get_basic_auth_pw(
request_rec<em> r</em>
)
</title>
<p>
Returns the password from a basic authorization request or nil if none was supplied
</p>
<p>
<em>Arguments:</em>
</p>
<table border="1">
<tr>
<th>Argument</th>
<th>Description</th>
</tr>
<tr>
<td>r</td>
<td>The mod_lua request handle</td>
</tr>
</table>
<p>
<em>Return value(s):</em>
<br/>
The password from a basic authorization request or nil if none was supplied
</p>
<p> </p>
</section>
<section id="apache2.get_server_name_for_url">
<title>apache2.get_server_name_for_url(
request_rec<em> r</em>
)
</title>
<p>
Get the current server name from the request for the purposes of using in a URL.
If the server name is an IPv6 literal address, it will be returned in URL format (e.g., "[fe80::1]").
</p>
<p>
<em>Arguments:</em>
</p>
<table border="1">
<tr>
<th>Argument</th>
<th>Description</th>
</tr>
<tr>
<td>r</td>
<td>The mod_lua request handle</td>
</tr>
</table>
<p> </p>
</section>
<section id="apache2.make_etag">
<title>apache2.make_etag(
request_rec<em> r</em>,  boolean<em> force_weak</em>
)
</title>
<p>
Constructs an entity tag from the resource information. If it's a real file, build in some of the file characteristics.
</p>
<p>
<em>Arguments:</em>
</p>
<table border="1">
<tr>
<th>Argument</th>
<th>Description</th>
</tr>
<tr>
<td>r</td>
<td>The mod_lua request handle</td>
</tr>
<tr>
<td>force_weak</td>
<td>force_weak Force the entity tag to be weak - it could be modified again in as short an interval.</td>
</tr>
</table>
<p>
<em>Return value(s):</em>
<br/>
The entity tag
</p>
<p> </p>
</section>
<section id="apache2.requestbody">
<title>apache2.requestbody(
request_rec<em> r</em>,  number<em> size</em>,  string<em> filename</em>
)
</title>
<p>
Reads the request body. If a filename is specified, the request body will be written to that file and the number of bytes written returned, otherwise, the full request body will be returned as a string.
</p>
<p>
<em>Arguments:</em>
</p>
<table border="1">
<tr>
<th>Argument</th>
<th>Description</th>
</tr>
<tr>
<td>r</td>
<td>The mod_lua request handle</td>
</tr>
<tr>
<td>size</td>
<td>The maximum size allowed, or 0/nil for unlimited size</td>
</tr>
<tr>
<td>filename</td>
<td>The file to save the output to, or nil to return it as a string</td>
</tr>
</table>
<p>
<em>Return value(s):</em>
<br/>
The number of bytes written if a filename was specified, otherwise it returns the entire request body as a string.
</p>
<p>
<em>Example:</em>
</p>
<highlight language="lua">
if tonumber(r.headers_in['Content-Length'] or 0) &lt; 10000 then
local smallfile = apache2.requestbody(r, 10000) -- fetch a small file into memory
r:puts("I saved the uploaded file in memory")
else
local read = apache2.requestbody(r, 0, "/path/to/tmp")
r:puts("I saved the uploaded file in a temp directory. Total bytes written was: ", read)
end
</highlight>
<p> </p>
</section>
<section id="apache2.send_interim_response">
<title>apache2.send_interim_response(
request_rec<em> r</em>,  boolean<em> send_headers</em>
)
</title>
<p>
Sends an interim (HTTP 1xx) response immediately.
</p>
<p>
<em>Arguments:</em>
</p>
<table border="1">
<tr>
<th>Argument</th>
<th>Description</th>
</tr>
<tr>
<td>r</td>
<td>The mod_lua request handle</td>
</tr>
<tr>
<td>send_headers</td>
<td>send_headers Whether to send&amp;clear headers in r-&gt;headers_out</td>
</tr>
</table>
<p>
<em>Example:</em>
</p>
<highlight language="lua">
apache2.send_interim_response(r, false)
</highlight>
<p> </p>
</section>
<section id="apache2.set_context_prefix">
<title>apache2.set_context_prefix(
request_rec<em> r</em>,  string<em> prefix</em>,  string<em> document</em>
)
</title>
<p>
Set context_prefix and context_document_root for a request.
</p>
<p>
<em>Arguments:</em>
</p>
<table border="1">
<tr>
<th>Argument</th>
<th>Description</th>
</tr>
<tr>
<td>r</td>
<td>The mod_lua request handle</td>
</tr>
<tr>
<td>prefix</td>
<td>The URI prefix, without trailing slash</td>
</tr>
<tr>
<td>document</td>
<td>The corresponding directory on disk, without trailing slash</td>
</tr>
</table>
<p> </p>
</section>
<section id="apache2.set_document_root">
<title>apache2.set_document_root(
request_rec<em> r</em>,  string<em> root</em>
)
</title>
<p>
Sets the document root of the request.
</p>
<p>
<em>Arguments:</em>
</p>
<table border="1">
<tr>
<th>Argument</th>
<th>Description</th>
</tr>
<tr>
<td>r</td>
<td>The mod_lua request handle</td>
</tr>
<tr>
<td>root</td>
<td>root</td>
</tr>
</table>
<p>
<em>Example:</em>
</p>
<highlight language="lua">
-- Suppose our real document root is /var/bar, then...
if r.hostname == "www.foo.com" then
apache2.set_document_root(r, "/www/foo") -- change document root on the fly
end
</highlight>
<p> </p>
</section>
<section id="apache2.set_keepalive">
<title>apache2.set_keepalive(
request_rec<em> r</em>
)
</title>
<p>
Sets the keepalive status for this request
</p>
<p>
<em>Arguments:</em>
</p>
<table border="1">
<tr>
<th>Argument</th>
<th>Description</th>
</tr>
<tr>
<td>r</td>
<td>The mod_lua request handle</td>
</tr>
</table>
<p>
<em>Return value(s):</em>
<br/>
True if keepalive can be set, false otherwise
</p>
<p> </p>
</section>
</section>
<section id="Parser_functions">
<title>HTTPd bindings: Parser functions</title>
<p>
<a href="#apache2.expr">apache2.expr</a>
<br/>
<a href="#apache2.regex">apache2.regex</a>
<br/>
<a href="#apache2.strcmp_match">apache2.strcmp_match</a>
<br/>
</p>
<section id="apache2.expr">
<title>apache2.expr(
request_rec<em> r</em>,  string<em> expression</em>
)
</title>
<p>
Evaluates an ap_expr (think &lt;If ...&gt;) expression and returns true if the expression is true, false otherwise. A second value containing an error string is returned if the expression is invalid.
</p>
<p>
<em>Arguments:</em>
</p>
<table border="1">
<tr>
<th>Argument</th>
<th>Description</th>
</tr>
<tr>
<td>r</td>
<td>The mod_lua request handle</td>
</tr>
<tr>
<td>expression</td>
<td>expression</td>
</tr>
</table>
<p>
<em>Return value(s):</em>
<br/>
True if the expression evaluates as true, false if the expression doesn't evaluate as true or if an error occurred. If an error occurred during parsing, a second value will be returned, containng the error string.
</p>
<p>
<em>Example:</em>
</p>
<highlight language="lua">
if apache2.expr("%{REQUEST_URI} =~ /force-gzip") then
r:addoutputfilter("DEFLATE")
end
</highlight>
<p> </p>
</section>
<section id="apache2.regex">
<title>apache2.regex(
request_rec<em> r</em>,  string<em> expression</em>,  string<em> source</em>
)
</title>
<p>
Evaluates a regular expression and, if it matches the source string, captures the variables and returns the matches as a table. On error, it returns nil.
</p>
<p>
<em>Arguments:</em>
</p>
<table border="1">
<tr>
<th>Argument</th>
<th>Description</th>
</tr>
<tr>
<td>r</td>
<td>The mod_lua request handle</td>
</tr>
<tr>
<td>expression</td>
<td>expression to match for</td>
</tr>
<tr>
<td>source</td>
<td>the source string to capture from</td>
</tr>
</table>
<p>
<em>Return value(s):</em>
<br/>
True if the expression evaluates as true, false if the expression doesn't evaluate as true or if an error occurred. If an error occurred during parsing, a second value will be returned, containng the error string.
</p>
<p>
<em>Example:</em>
</p>
<highlight language="lua">
local matches = apache2.regex(r, [[(\S+) kitty]], "Hello kitty")
if matches and matches[1] then
r:puts("You said ", matches[1], " to kitty")
end
</highlight>
<p> </p>
</section>
<section id="apache2.strcmp_match">
<title>apache2.strcmp_match(
string<em> str</em>,  string<em> expexted</em>,  boolean<em> ignoreCase</em>
)
</title>
<p>
Determines if a string matches a pattern containing the wildcards '?' or '*'
</p>
<p>
<em>Arguments:</em>
</p>
<table border="1">
<tr>
<th>Argument</th>
<th>Description</th>
</tr>
<tr>
<td>str</td>
<td>The string to check</td>
</tr>
<tr>
<td>expexted</td>
<td>The pattern to match against</td>
</tr>
<tr>
<td>ignoreCase</td>
<td>Whether to ignore case when matching</td>
</tr>
</table>
<p>
<em>Return value(s):</em>
<br/>
True if the two strings match, false otherwise.
</p>
<p>
<em>Example:</em>
</p>
<highlight language="lua">
if apache2.strcmp_match("foo.bar", "foo.*") then
r:puts("It matches!")
end
</highlight>
<p> </p>
</section>
</section>
<section id="Server_settings">
<title>HTTPd bindings: Server settings</title>
<p>
<a href="#apache2.add_version_component">apache2.add_version_component</a>
<br/>
<a href="#apache2.mpm_query">apache2.mpm_query</a>
<br/>
<a href="#apache2.terminate">apache2.terminate</a>
<br/>
<a href="#apache2.scoreboard_process">apache2.scoreboard_process</a>
<br/>
<a href="#apache2.scoreboard_worker">apache2.scoreboard_worker</a>
<br/>
<a href="#apache2.module_info">apache2.module_info</a>
<br/>
<a href="#apache2.loaded_modules">apache2.loaded_modules</a>
<br/>
<a href="#apache2.runtime_dir_relative">apache2.runtime_dir_relative</a>
<br/>
<a href="#apache2.server_info">apache2.server_info</a>
<br/>
<a href="#apache2.state_query">apache2.state_query</a>
<br/>
<a href="#apache2.custom_response">apache2.custom_response</a>
<br/>
<a href="#apache2.exists_config_define">apache2.exists_config_define</a>
<br/>
</p>
<section id="apache2.add_version_component">
<title>apache2.add_version_component(
request_rec<em> r</em>,  string<em> component</em>
)
</title>
<p>
Adds a component to the server description and banner strings
</p>
<p>
<em>Arguments:</em>
</p>
<table border="1">
<tr>
<th>Argument</th>
<th>Description</th>
</tr>
<tr>
<td>r</td>
<td>The mod_lua request handle</td>
</tr>
<tr>
<td>component</td>
<td>The component to add</td>
</tr>
</table>
<p>
<em>Example:</em>
</p>
<highlight language="lua">
if not apache2.banner():match("FooModule") then -- Make sure we haven't added it already
apache2.add_version_component(r, "FooModule/1.0")
end
</highlight>
<p> </p>
</section>
<section id="apache2.custom_response">
<title>apache2.custom_response(
request_rec<em> r</em>,  number<em> status</em>,  string<em> string</em>
)
</title>
<p>
Install a custom response handler for a given status
</p>
<p>
<em>Arguments:</em>
</p>
<table border="1">
<tr>
<th>Argument</th>
<th>Description</th>
</tr>
<tr>
<td>r</td>
<td>The mod_lua request handle</td>
</tr>
<tr>
<td>status</td>
<td>The status for which the custom response should be used</td>
</tr>
<tr>
<td>string</td>
<td>The custom response. This can be a static string, a file or a URL</td>
</tr>
</table>
<p>
<em>Example:</em>
</p>
<highlight language="lua">
apache2.custom_response(r, 404, "Not found!!")
</highlight>
<p> </p>
</section>
<section id="apache2.exists_config_define">
<title>apache2.exists_config_define(
string<em> name</em>
)
</title>
<p>
Checks for a definition from the server command line
</p>
<p>
<em>Arguments:</em>
</p>
<table border="1">
<tr>
<th>Argument</th>
<th>Description</th>
</tr>
<tr>
<td>name</td>
<td>The define to check for</td>
</tr>
</table>
<p>
<em>Example:</em>
</p>
<highlight language="lua">
if apache2.exists_config_define("FOO") then
r:puts("This server was started with -DFOO")
end
</highlight>
<p> </p>
</section>
<section id="apache2.loaded_modules">
<title>apache2.loaded_modules(
)
</title>
<p>
Returns a table containing the name (c filename) of all loaded modules
</p>
<p>
<em>Arguments:</em>
</p>
<p>None</p>
<p>
<em>Return value(s):</em>
<br/>
A table containing the name (c filename) of all loaded modules
</p>
<p> </p>
</section>
<section id="apache2.module_info">
<title>apache2.module_info(
string<em> c</em>,  string<em> file</em>
)
</title>
<p>
Returns information about a specific module (if loaded)
</p>
<p>
<em>Arguments:</em>
</p>
<table border="1">
<tr>
<th>Argument</th>
<th>Description</th>
</tr>
<tr>
<td>c</td>
<td>c</td>
</tr>
<tr>
<td>file</td>
<td>file</td>
</tr>
</table>
<p>
<em>Return value(s):</em>
<br/>
The various commands available to this module as a table, or nil if the module wasn't found.
</p>
<p> </p>
</section>
<section id="apache2.mpm_query">
<title>apache2.mpm_query(
number<em> i</em>
)
</title>
<p>
Queries the MPM for a specific value
</p>
<p>
<em>Arguments:</em>
</p>
<table border="1">
<tr>
<th>Argument</th>
<th>Description</th>
</tr>
<tr>
<td>i</td>
<td>i</td>
</tr>
</table>
<p>
<em>Return value(s):</em>
<br/>
The queried value
</p>
<p> </p>
</section>
<section id="apache2.runtime_dir_relative">
<title>apache2.runtime_dir_relative(
request_rec<em> r</em>,  string<em> file</em>
)
</title>
<p>
Returns the path of a file relative to the default runtime directory
</p>
<p>
<em>Arguments:</em>
</p>
<table border="1">
<tr>
<th>Argument</th>
<th>Description</th>
</tr>
<tr>
<td>r</td>
<td>The mod_lua request handle</td>
</tr>
<tr>
<td>file</td>
<td>file</td>
</tr>
</table>
<p>
<em>Return value(s):</em>
<br/>
The path of a file relative to the default runtime directory
</p>
<p> </p>
</section>
<section id="apache2.scoreboard_process">
<title>apache2.scoreboard_process(
request_rec<em> r</em>,  number<em> child</em>
)
</title>
<p>
Returns the scoreboard for a server daemon as a table
</p>
<p>
<em>Arguments:</em>
</p>
<table border="1">
<tr>
<th>Argument</th>
<th>Description</th>
</tr>
<tr>
<td>r</td>
<td>The mod_lua request handle</td>
</tr>
<tr>
<td>child</td>
<td>The server child to query</td>
</tr>
</table>
<p>
<em>Return value(s):</em>
<br/>
The scoreboard for a server daemon as a table
</p>
<p> </p>
</section>
<section id="apache2.scoreboard_worker">
<title>apache2.scoreboard_worker(
request_rec<em> r</em>,  number<em> child</em>,  number<em> thread</em>
)
</title>
<p>
Returns the scoreboard for a single thread as a table
</p>
<p>
<em>Arguments:</em>
</p>
<table border="1">
<tr>
<th>Argument</th>
<th>Description</th>
</tr>
<tr>
<td>r</td>
<td>The mod_lua request handle</td>
</tr>
<tr>
<td>child</td>
<td>The server child to query</td>
</tr>
<tr>
<td>thread</td>
<td>The thread to query</td>
</tr>
</table>
<p>
<em>Return value(s):</em>
<br/>
The scoreboard for a single thread as a table
</p>
<p> </p>
</section>
<section id="apache2.server_info">
<title>apache2.server_info(
)
</title>
<p>
Returns a table with information about the server program
</p>
<p>
<em>Arguments:</em>
</p>
<p>None</p>
<p>
<em>Return value(s):</em>
<br/>
A table with information about the server program
</p>
<p> </p>
</section>
<section id="apache2.state_query">
<title>apache2.state_query(
number<em> field</em>
)
</title>
<p>
Query the server for some state information
</p>
<p>
<em>Arguments:</em>
</p>
<table border="1">
<tr>
<th>Argument</th>
<th>Description</th>
</tr>
<tr>
<td>field</td>
<td>Which information is requested</td>
</tr>
</table>
<p>
<em>Example:</em>
</p>
<highlight language="lua">
local gen = apache2.state_query(2)
r:puts("This is generation no. " .. gen .. " of the top-level parent")
</highlight>
<p> </p>
</section>
<section id="apache2.terminate">
<title>apache2.terminate(
)
</title>
<p>
Kills off a server process. This has no other use than to show how dangerous mod_lua can be ;)
</p>
<p>
<em>Arguments:</em>
</p>
<p>None</p>
<p> </p>
</section>
</section>
<section id="Database_connectivity">
<title>HTTPd bindings: Database connectivity</title>
<p>
<a href="#apache2.dbopen">apache2.dbopen</a>
<br/>
<a href="#db:query">db:query</a>
<br/>
<a href="#db:do">db:do</a>
<br/>
<a href="#db:close">db:close</a>
<br/>
</p>
<section id="apache2.dbopen">
<title>apache2.dbopen(
request_rec<em> r</em>,  string<em> dbtype</em>,  string<em> conn_string</em>
)
</title>
<p>
Opens up a new database connection. See the DB functions for mod_pLua for more info on this.
</p>
<p>
<em>Arguments:</em>
</p>
<table border="1">
<tr>
<th>Argument</th>
<th>Description</th>
</tr>
<tr>
<td>r</td>
<td>The mod_lua request handle</td>
</tr>
<tr>
<td>dbtype</td>
<td>dbtype</td>
</tr>
<tr>
<td>conn_string</td>
<td>connection string</td>
</tr>
</table>
<p>
<em>Return value(s):</em>
<br/>
The database connection as a table with functions, or nil if the connection failed. If a connection failed, a second argument (string) with the error code is returned.
</p>
<p>
<em>Example:</em>
</p>
<highlight language="lua">
local db, error = apache2.dbopen(r, "mod_dbd")
if error then
r:puts("DB error: ", error)
else
-- DB stuff here
end
</highlight>
<p> </p>
</section>
<section id="db:close">
<title>db:close(
request_rec<em> r</em>
)
</title>
<p>
Closes a database connection
</p>
<p>
<em>Arguments:</em>
</p>
<table border="1">
<tr>
<th>Argument</th>
<th>Description</th>
</tr>
<tr>
<td>r</td>
<td>The mod_lua request handle</td>
</tr>
</table>
<p>
<em>Example:</em>
</p>
<highlight language="lua">
local db = apache2.dbopen(r, "mod_dbd") -- open a db connection
db:close() -- close it down
</highlight>
<p> </p>
</section>
<section id="db:do">
<title>db:do(
request_rec<em> r</em>,  string<em> query</em>
)
</title>
<p>
Executes a statement that doesn't return a result set
</p>
<p>
<em>Arguments:</em>
</p>
<table border="1">
<tr>
<th>Argument</th>
<th>Description</th>
</tr>
<tr>
<td>r</td>
<td>The mod_lua request handle</td>
</tr>
<tr>
<td>query</td>
<td>The SQL statement to execute</td>
</tr>
</table>
<p>
<em>Return value(s):</em>
<br/>
If the statement is valid, a table of results are returned. If an error occurred, the first return value is false and the second return value is a string containing an error message.
</p>
<p>
<em>Example:</em>
</p>
<highlight language="lua">
local db = apache2.dbopen(r, "mod_dbd")
local affected = db:do("DELETE FROM `table` WHERE 1")
if affected then
r:puts("Affected ", affected, " rows")
end
</highlight>
<p> </p>
</section>
<section id="db:query">
<title>db:query(
request_rec<em> r</em>,  string<em> query</em>
)
</title>
<p>
Queries the database for information using the specified statement.
</p>
<p>
<em>Arguments:</em>
</p>
<table border="1">
<tr>
<th>Argument</th>
<th>Description</th>
</tr>
<tr>
<td>r</td>
<td>The mod_lua request handle</td>
</tr>
<tr>
<td>query</td>
<td>The SQL statement to execute</td>
</tr>
</table>
<p>
<em>Return value(s):</em>
<br/>
If the statement is valid, a table of results are returned. If an error occurred, the first return value is false and the second return value is a string containing an error message.
</p>
<p>
<em>Example:</em>
</p>
<highlight language="lua">
local db = apache2.dbopen(r, "mod_dbd")
local result, error = db:query("SELECT * FROM `table` WHERE 1")
if result then
for key, value in pairs(result)
r:puts( ("row %s: %s\n"):format(key, table.concat(value, ", ")) )
end
end
</highlight>
<p> </p>
</section>
</section>
<section id="Miscellaneous">
<title>HTTPd bindings: Miscellaneous</title>
<p>
<a href="#apache2.clock">apache2.clock</a>
<br/>
<a href="#apache2.sleep">apache2.sleep</a>
<br/>
</p>
<section id="apache2.clock">
<title>apache2.clock(
)
</title>
<p>
Returns the current time in microseconds.
</p>
<p>
<em>Arguments:</em>
</p>
<p>None</p>
<p>
<em>Return value(s):</em>
<br/>
The current time in microseconds.
</p>
<p> </p>
</section>
<section id="apache2.sleep">
<title>apache2.sleep(
number<em> seconds</em>
)
</title>
<p>
Sleeps for a while. Floating point values can be used to sleep for less than a second.
</p>
<p>
<em>Arguments:</em>
</p>
<table border="1">
<tr>
<th>Argument</th>
<th>Description</th>
</tr>
<tr>
<td>seconds</td>
<td>The number of seconds to sleep.</td>
</tr>
</table>
<p>
<em>Example:</em>
</p>
<highlight language="lua">
r:puts("this is ")
apache2.flush(r)
apache2.sleep(0.25) -- sleep for a quarter second.
r:puts("delayed")
</highlight>
<p> </p>
</section>
</section>
</manualpage>