2 <!DOCTYPE modulesynopsis SYSTEM "../style/modulesynopsis.dtd">
3 <?xml-stylesheet type="text/xsl" href="../style/manual.en.xsl"?>
4 <!-- $LastChangedRevision$ -->
7 Licensed to the Apache Software Foundation (ASF) under one or more
8 contributor license agreements. See the NOTICE file distributed with
9 this work for additional information regarding copyright ownership.
10 The ASF licenses this file to You under the Apache License, Version 2.0
11 (the "License"); you may not use this file except in compliance with
12 the License. You may obtain a copy of the License at
14 http://www.apache.org/licenses/LICENSE-2.0
16 Unless required by applicable law or agreed to in writing, software
17 distributed under the License is distributed on an "AS IS" BASIS,
18 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19 See the License for the specific language governing permissions and
20 limitations under the License.
23 <modulesynopsis metafile="mod_lua.xml.meta">
27 <description>Provides Lua hooks into various portions of the httpd
28 request processing</description>
29 <status>Experimental</status>
30 <sourcefile>mod_lua.c</sourcefile>
31 <identifier>lua_module</identifier>
32 <compatibility>2.3 and later</compatibility>
35 <p>This module allows the server to be extended with scripts written in the
36 Lua programming language. The extension points (hooks) available with
37 <module>mod_lua</module> include many of the hooks available to
38 natively compiled Apache HTTP Server modules, such as mapping requests to
39 files, generating dynamic responses, access control, authentication, and
42 <p>More information on the Lua programming language can be found at the
43 <a href="http://www.lua.org/">the Lua website</a>.</p>
45 <note><code>mod_lua</code> is still in experimental state.
46 Until it is declared stable, usage and behavior may change
47 at any time, even between stable releases of the 2.4.x series.
48 Be sure to check the CHANGES file before upgrading.</note>
50 <note type="warning"><title>Warning</title>
51 <p>This module holds a great deal of power over httpd, which is both a
52 strength and a potential security risk. It is <strong>not</strong> recommended
53 that you use this module on a server that is shared with users you do not
54 trust, as it can be abused to change the internal workings of httpd.</p>
59 <section id="basicconf"><title>Basic Configuration</title>
61 <p>The basic module loading directive is</p>
63 <highlight language="config">
64 LoadModule lua_module modules/mod_lua.so
68 <code>mod_lua</code> provides a handler named <code>lua-script</code>,
69 which can be used with an <code>AddHandler</code> directive:</p>
71 <highlight language="config">
72 AddHandler lua-script .lua
76 This will cause <code>mod_lua</code> to handle requests for files
77 ending in <code>.lua</code> by invoking that file's
78 <code>handle</code> function.
81 <p>For more flexibility, see <directive>LuaMapHandler</directive>.
86 <section id="writinghandlers"><title>Writing Handlers</title>
87 <p> In the Apache HTTP Server API, the handler is a specific kind of hook
88 responsible for generating the response. Examples of modules that include a
89 handler are <module>mod_proxy</module>, <module>mod_cgi</module>,
90 and <module>mod_status</module>.</p>
92 <p><code>mod_lua</code> always looks to invoke a Lua function for the handler, rather than
93 just evaluating a script body CGI style. A handler function looks
94 something like this:</p>
97 <highlight language="lua">
98 <strong>example.lua</strong><br/>
104 This is the default method name for Lua handlers, see the optional
105 function-name in the LuaMapHandler directive to choose a different
109 r.content_type = "text/plain"
110 r:puts("Hello Lua World!\n")
112 if r.method == 'GET' then
113 for k, v in pairs( r:parseargs() ) do
114 r:puts( string.format("%s: %s\n", k, v) )
116 elseif r.method == 'POST' then
117 for k, v in pairs( r:parsebody() ) do
118 r:puts( string.format("%s: %s\n", k, v) )
121 r:puts("Unsupported HTTP method " .. r.method)
127 This handler function just prints out the uri or form encoded
128 arguments to a plaintext page.
132 This means (and in fact encourages) that you can have multiple
133 handlers (or hooks, or filters) in the same script.
138 <section id="writingauthzproviders">
139 <title>Writing Authorization Providers</title>
141 <p><module>mod_authz_core</module> provides a high-level interface to
142 authorization that is much easier to use than using into the relevant
143 hooks directly. The first argument to the
144 <directive module="mod_authz_core">Require</directive> directive gives
145 the name of the responsible authorization provider. For any
146 <directive module="mod_authz_core">Require</directive> line,
147 <module>mod_authz_core</module> will call the authorization provider
148 of the given name, passing the rest of the line as parameters. The
149 provider will then check authorization and pass the result as return
152 <p>The authz provider is normally called before authentication. If it needs to
153 know the authenticated user name (or if the user will be authenticated at
154 all), the provider must return <code>apache2.AUTHZ_DENIED_NO_USER</code>.
155 This will cause authentication to proceed and the authz provider to be
156 called a second time.</p>
158 <p>The following authz provider function takes two arguments, one ip
159 address and one user name. It will allow access from the given ip address
160 without authentication, or if the authenticated user matches the second
163 <highlight language="lua">
164 <strong>authz_provider.lua</strong><br/>
168 function authz_check_foo(r, ip, user)
169 if r.useragent_ip == ip then
170 return apache2.AUTHZ_GRANTED
171 elseif r.user == nil then
172 return apache2.AUTHZ_DENIED_NO_USER
173 elseif r.user == user then
174 return apache2.AUTHZ_GRANTED
176 return apache2.AUTHZ_DENIED
181 <p>The following configuration registers this function as provider
182 <code>foo</code> and configures it for URL <code>/</code>:</p>
183 <highlight language="config">
184 LuaAuthzProvider foo authz_provider.lua authz_check_foo
186 Require foo 10.1.2.3 john_doe
192 <section id="writinghooks"><title>Writing Hooks</title>
194 <p>Hook functions are how modules (and Lua scripts) participate in the
195 processing of requests. Each type of hook exposed by the server exists for
196 a specific purpose, such as mapping requests to the filesystem,
197 performing access control, or setting mimetypes:</p>
199 <table border="1" style="zebra">
202 <th>mod_lua directive</th>
206 <td>Quick handler</td>
207 <td><directive module="mod_lua">LuaQuickHandler</directive></td>
208 <td>This is the first hook that will be called after a request has
209 been mapped to a host or virtual host</td>
212 <td>Translate name</td>
213 <td><directive module="mod_lua">LuaHookTranslateName</directive></td>
214 <td>This phase translates the requested URI into a filename on the
215 system. Modules such as <module>mod_alias</module> and
216 <module>mod_rewrite</module> operate in this phase.</td>
219 <td>Map to storage</td>
220 <td><directive module="mod_lua">LuaHookMapToStorage</directive></td>
221 <td>This phase maps files to their physical, cached or external/proxied storage.
222 It can be used by proxy or caching modules</td>
225 <td>Check Access</td>
226 <td><directive module="mod_lua">LuaHookAccessChecker</directive></td>
227 <td>This phase checks whether a client has access to a resource. This
228 phase is run before the user is authenticated, so beware.
232 <td>Check User ID</td>
233 <td><directive module="mod_lua">LuaHookCheckUserID</directive></td>
234 <td>This phase it used to check the negotiated user ID</td>
237 <td>Check Authorization</td>
238 <td><directive module="mod_lua">LuaHookAuthChecker</directive> or
239 <directive module="mod_lua">LuaAuthzProvider</directive></td>
240 <td>This phase authorizes a user based on the negotiated credentials, such as
241 user ID, client certificate etc.
246 <td><directive module="mod_lua">LuaHookTypeChecker</directive></td>
247 <td>This phase checks the requested file and assigns a content type and
252 <td><directive module="mod_lua">LuaHookFixups</directive></td>
253 <td>This is the final "fix anything" phase before the content handlers
254 are run. Any last-minute changes to the request should be made here.</td>
257 <td>Content handler</td>
258 <td>fx. <code>.lua</code> files or through <directive module="mod_lua">LuaMapHandler</directive></td>
259 <td>This is where the content is handled. Files are read, parsed, some are run,
260 and the result is sent to the client</td>
265 <td>Once a request has been handled, it enters several logging phases,
266 which logs the request in either the error or access log</td>
271 <p>Hook functions are passed the request object as their only argument
272 (except for LuaAuthzProvider, which also gets passed the arguments from
273 the Require directive).
274 They can return any value, depending on the hook, but most commonly
275 they'll return OK, DONE, or DECLINED, which you can write in lua as
276 <code>apache2.OK</code>, <code>apache2.DONE</code>, or
277 <code>apache2.DECLINED</code>, or else an HTTP status code.</p>
280 <highlight language="lua">
281 <strong>translate_name.lua</strong><br/>
282 -- example hook that rewrites the URI to a filesystem path.
286 function translate_name(r)
287 if r.uri == "/translate-name" then
288 r.filename = r.document_root .. "/find_me.txt"
291 -- we don't care about this URL, give another module a chance
292 return apache2.DECLINED
297 <highlight language="lua">
298 <strong>translate_name2.lua</strong><br/>
299 --[[ example hook that rewrites one URI to another URI. It returns a
300 apache2.DECLINED to give other URL mappers a chance to work on the
301 substitution, including the core translate_name hook which maps based
304 Note: Use the early/late flags in the directive to make it run before
310 function translate_name(r)
311 if r.uri == "/translate-name" then
312 r.uri = "/find_me.txt"
313 return apache2.DECLINED
315 return apache2.DECLINED
320 <section id="datastructures"><title>Data Structures</title>
325 <p>The request_rec is mapped in as a userdata. It has a metatable
326 which lets you do useful things with it. For the most part it
327 has the same fields as the request_rec struct, many of which are writeable as
328 well as readable. (The table fields' content can be changed, but the
329 fields themselves cannot be set to different tables.)</p>
331 <table border="1" style="zebra">
334 <th><strong>Name</strong></th>
335 <th><strong>Lua type</strong></th>
336 <th><strong>Writable</strong></th>
337 <th><strong>Description</strong></th>
340 <td><code>allowoverrides</code></td>
343 <td>The AllowOverride options applied to the current request.</td>
346 <td><code>ap_auth_type</code></td>
349 <td>If an authentication check was made, this is set to the type
350 of authentication (f.x. <code>basic</code>)</td>
353 <td><code>args</code></td>
356 <td>The query string arguments extracted from the request
357 (f.x. <code>foo=bar&name=johnsmith</code>)</td>
360 <td><code>assbackwards</code></td>
363 <td>Set to true if this is an HTTP/0.9 style request
364 (e.g. <code>GET /foo</code> (with no headers) )</td>
367 <td><code>auth_name</code></td>
370 <td>The realm name used for authorization (if applicable).</td>
373 <td><code>banner</code></td>
376 <td>The server banner, f.x. <code>Apache HTTP Server/2.4.3 openssl/0.9.8c</code></td>
379 <td><code>basic_auth_pw</code></td>
382 <td>The basic auth password sent with this request, if any</td>
385 <td><code>canonical_filename</code></td>
388 <td>The canonical filename of the request</td>
391 <td><code>content_encoding</code></td>
394 <td>The content encoding of the current request</td>
397 <td><code>content_type</code></td>
400 <td>The content type of the current request, as determined in the
401 type_check phase (f.x. <code>image/gif</code> or <code>text/html</code>)</td>
404 <td><code>context_prefix</code></td>
410 <td><code>context_document_root</code></td>
417 <td><code>document_root</code></td>
420 <td>The document root of the host</td>
423 <td><code>err_headers_out</code></td>
426 <td>MIME header environment for the response, printed even on errors and
427 persist across internal redirects</td>
430 <td><code>filename</code></td>
433 <td>The file name that the request maps to, f.x. /www/example.com/foo.txt. This can be
434 changed in the translate-name or map-to-storage phases of a request to allow the
435 default handler (or script handlers) to serve a different file than what was requested.</td>
438 <td><code>handler</code></td>
441 <td>The name of the <a href="../handler.html">handler</a> that should serve this request, f.x.
442 <code>lua-script</code> if it is to be served by mod_lua. This is typically set by the
443 <directive module="mod_mime">AddHandler</directive> or <directive module="core">SetHandler</directive>
444 directives, but could also be set via mod_lua to allow another handler to serve up a specific request
445 that would otherwise not be served by it.
450 <td><code>headers_in</code></td>
453 <td>MIME header environment from the request. This contains headers such as <code>Host,
454 User-Agent, Referer</code> and so on.</td>
457 <td><code>headers_out</code></td>
460 <td>MIME header environment for the response.</td>
463 <td><code>hostname</code></td>
466 <td>The host name, as set by the <code>Host:</code> header or by a full URI.</td>
469 <td><code>is_https</code></td>
472 <td>Whether or not this request is done via HTTPS</td>
475 <td><code>is_initial_req</code></td>
478 <td>Whether this request is the initial request or a sub-request</td>
481 <td><code>limit_req_body</code></td>
484 <td>The size limit of the request body for this request, or 0 if no limit.</td>
487 <td><code>log_id</code></td>
490 <td>The ID to identify request in access and error log.</td>
493 <td><code>method</code></td>
496 <td>The request method, f.x. <code>GET</code> or <code>POST</code>.</td>
499 <td><code>notes</code></td>
502 <td>A list of notes that can be passed on from one module to another.</td>
505 <td><code>options</code></td>
508 <td>The Options directive applied to the current request.</td>
511 <td><code>path_info</code></td>
514 <td>The PATH_INFO extracted from this request.</td>
517 <td><code>port</code></td>
520 <td>The server port used by the request.</td>
523 <td><code>protocol</code></td>
526 <td>The protocol used, f.x. <code>HTTP/1.1</code></td>
529 <td><code>proxyreq</code></td>
532 <td>Denotes whether this is a proxy request or not. This value is generally set in
533 the post_read_request/translate_name phase of a request.</td>
536 <td><code>range</code></td>
539 <td>The contents of the <code>Range:</code> header.</td>
542 <td><code>remaining</code></td>
545 <td>The number of bytes remaining to be read from the request body.</td>
548 <td><code>server_built</code></td>
551 <td>The time the server executable was built.</td>
554 <td><code>server_name</code></td>
557 <td>The server name for this request.</td>
560 <td><code>some_auth_required</code></td>
563 <td>Whether some authorization is/was required for this request.</td>
566 <td><code>subprocess_env</code></td>
569 <td>The environment variables set for this request.</td>
572 <td><code>started</code></td>
575 <td>The time the server was (re)started, in seconds since the epoch (Jan 1st, 1970)</td>
578 <td><code>status</code></td>
581 <td>The (current) HTTP return code for this request, f.x. <code>200</code> or <code>404</code>.</td>
584 <td><code>the_request</code></td>
587 <td>The request string as sent by the client, f.x. <code>GET /foo/bar HTTP/1.1</code>.</td>
590 <td><code>unparsed_uri</code></td>
593 <td>The unparsed URI of the request</td>
596 <td><code>uri</code></td>
599 <td>The URI after it has been parsed by httpd</td>
602 <td><code>user</code></td>
605 <td>If an authentication check has been made, this is set to the name of the authenticated user.</td>
608 <td><code>useragent_ip</code></td>
611 <td>The IP of the user agent making the request</td>
615 <p>The request_rec has (at least) the following methods:</p>
617 <highlight language="lua">
618 r:flush() -- flushes the output buffer
621 <highlight language="lua">
622 r:addoutputfilter(name|function) -- add an output filter
625 <highlight language="lua">
626 r:sendfile(filename) -- sends an entire file to the client, using sendfile if supported by the current platform
629 <highlight language="lua">
630 r:parseargs() -- returns a Lua table containing the request's query string arguments
633 <highlight language="lua">
634 r:parsebody([sizeLimit]) -- parse the request body as a POST and return a lua table.
635 -- An optional number may be passed to specify the maximum number
636 -- of bytes to parse. Default is 8192 bytes.
639 <highlight language="lua">
640 r:puts("hello", " world", "!") -- print to response body
643 <highlight language="lua">
644 r:write("a single string") -- print to response body
647 <highlight language="lua">
648 r:escape_html("<html>test</html>") -- Escapes HTML code and returns the escaped result
651 <highlight language="lua">
652 r:base64_encode(string) -- Encodes a string using the Base64 encoding standard
655 <highlight language="lua">
656 r:base64_decode(string) -- Decodes a Base64-encoded string
659 <highlight language="lua">
660 r:md5(string) -- Calculates and returns the MD5 digest of a string (binary safe)
663 <highlight language="lua">
664 r:sha1(string) -- Calculates and returns the SHA1 digest of a string (binary safe)
667 <highlight language="lua">
668 r:escape(string) -- URL-Escapes a string
671 <highlight language="lua">
672 r:unescape(string) -- Unescapes an URL-escaped string
675 <highlight language="lua">
676 r:banner() -- Returns the current server banner
679 <highlight language="lua">
680 r:port() -- Returns the current server port used for the request
683 <highlight language="lua">
684 r:mpm_query(number) -- Queries the server for MPM information using ap_mpm_query
687 <highlight language="lua">
688 r:expr(string) -- Evaluates an <a href="../expr.html">expr</a> string.
691 <highlight language="lua">
692 r:scoreboard_process(a) -- Queries the server for information about the process at position <code>a</code>
695 <highlight language="lua">
696 r:scoreboard_worker(a, b) -- Queries for information about the worker thread, <code>b</code>, in process <code>a</code>
699 <highlight language="lua">
700 r:started() -- Returns the time of the last server (re)start
703 <highlight language="lua">
704 r:clock() -- Returns the current time with microsecond precision
707 <highlight language="lua">
708 r:requestbody(filename) -- Reads and returns the request body of a request.
709 -- If 'filename' is specified, it instead saves the
710 -- contents to that file.
713 <highlight language="lua">
714 r:add_input_filter(filter_name) -- Adds 'filter_name' as an input filter
717 <highlight language="lua">
718 r:module_info(module_name) -- Queries the server for information about a module
721 <highlight language="lua">
722 r:loaded_modules() -- Returns a list of modules loaded by httpd
725 <highlight language="lua">
726 r:runtime_dir_relative(filename) -- Compute the name of a run-time file (e.g., shared memory "file")
727 -- relative to the appropriate run-time directory.
730 <highlight language="lua">
731 r:server_info() -- Returns a table containing server information, such as
732 -- the name of the httpd executable file, mpm used etc.
735 <highlight language="lua">
736 r:set_document_root(file_path) -- Sets the document root for the request to file_path
739 <highlight language="lua">
740 r:add_version_component(component_string) -- Adds a component to the server banner.
743 <highlight language="lua">
744 r:set_context_info(prefix, docroot) -- Sets the context prefix and context document root for a request
747 <highlight language="lua">
748 r:os_escape_path(file_path) -- Converts an OS path to a URL in an OS dependant way
751 <highlight language="lua">
752 r:escape_logitem(string) -- Escapes a string for logging
755 <highlight language="lua">
756 r:strcmp_match(string, pattern) -- Checks if 'string' matches 'pattern' using strcmp_match (GLOBs).
757 -- fx. whether 'www.example.com' matches '*.example.com'
760 <highlight language="lua">
761 r:set_keepalive() -- Sets the keepalive status for a request. Returns true if possible, false otherwise.
764 <highlight language="lua">
765 r:make_etag() -- Constructs and returns the etag for the current request.
768 <highlight language="lua">
769 r:send_interim_response(clear) -- Sends an interim (1xx) response to the client.
770 -- if 'clear' is true, available headers will be sent and cleared.
773 <highlight language="lua">
774 r:custom_response(status_code, string) -- Construct and set a custom response for a given status code.
775 -- This works much like the ErrorDocument directive.
778 <highlight language="lua">
779 r:exists_config_define(string) -- Checks whether a configuration definition exists or not.
782 <highlight language="lua">
783 r:state_query(string) -- Queries the server for state information
786 <highlight language="lua">
787 r:stat(filename) -- Runs stat() on a file, and returns a table with file information
790 <highlight language="lua">
791 r:regex(string, pattern) -- Runs a regular expression match on a string, returning captures if matched.
794 <highlight language="lua">
795 r:sleep(number_of_seconds) -- Puts the script to sleep for a given number of seconds.
798 <highlight language="lua">
799 r:dbacquire(dbType[, dbParams]) -- Acquires a connection to a database and returns a database class.
800 -- See '<a href="#databases">Database connectivity</a>' for details.
807 <section id="logging"><title>Logging Functions</title>
809 <highlight language="lua">
810 -- examples of logging messages<br />
811 r:trace1("This is a trace log message") -- trace1 through trace8 can be used <br />
812 r:debug("This is a debug log message")<br />
813 r:info("This is an info log message")<br />
814 r:notice("This is a notice log message")<br />
815 r:warn("This is a warn log message")<br />
816 r:err("This is an err log message")<br />
817 r:alert("This is an alert log message")<br />
818 r:crit("This is a crit log message")<br />
819 r:emerg("This is an emerg log message")<br />
824 <section id="apache2"><title>apache2 Package</title>
825 <p>A package named <code>apache2</code> is available with (at least) the following contents.</p>
828 <dd>internal constant OK. Handlers should return this if they've
829 handled the request.</dd>
830 <dt>apache2.DECLINED</dt>
831 <dd>internal constant DECLINED. Handlers should return this if
832 they are not going to handle the request.</dd>
833 <dt>apache2.DONE</dt>
834 <dd>internal constant DONE.</dd>
835 <dt>apache2.version</dt>
836 <dd>Apache HTTP server version string</dd>
837 <dt>apache2.HTTP_MOVED_TEMPORARILY</dt>
838 <dd>HTTP status code</dd>
839 <dt>apache2.PROXYREQ_NONE, apache2.PROXYREQ_PROXY, apache2.PROXYREQ_REVERSE, apache2.PROXYREQ_RESPONSE</dt>
840 <dd>internal constants used by <module>mod_proxy</module></dd>
841 <dt>apache2.AUTHZ_DENIED, apache2.AUTHZ_GRANTED, apache2.AUTHZ_NEUTRAL, apache2.AUTHZ_GENERAL_ERROR, apache2.AUTHZ_DENIED_NO_USER</dt>
842 <dd>internal constants used by <module>mod_authz_core</module></dd>
845 <p>(Other HTTP status codes are not yet implemented.)</p>
848 <section id="modifying_buckets">
849 <title>Modifying contents with Lua filters</title>
851 Filter functions implemented via <directive module="mod_lua">LuaInputFilter</directive>
852 or <directive module="mod_lua">LuaOutputFilter</directive> are designed as
853 three-stage non-blocking functions using coroutines to suspend and resume a
854 function as buckets are sent down the filter chain. The core structure of
857 <highlight language="lua">
859 -- Our first yield is to signal that we are ready to receive buckets.
860 -- Before this yield, we can set up our environment, check for conditions,
861 -- and, if we deem it necessary, decline filtering a request alltogether:
862 if something_bad then
863 return -- This would skip this filter.
865 -- Regardless of whether we have data to prepend, a yield MUST be called here.
866 -- Note that only output filters can prepend data. Input filters must use the
867 -- final stage to append data to the content.
868 coroutine.yield([optional header to be prepended to the content])
870 -- After we have yielded, buckets will be sent to us, one by one, and we can
871 -- do whatever we want with them and then pass on the result.
872 -- Buckets are stored in the global variable 'bucket', so we create a loop
873 -- that checks if 'bucket' is not nil:
874 while bucket ~= nil do
875 local output = mangle(bucket) -- Do some stuff to the content
876 coroutine.yield(output) -- Return our new content to the filter chain
879 -- Once the buckets are gone, 'bucket' is set to nil, which will exit the
880 -- loop and land us here. Anything extra we want to append to the content
881 -- can be done by doing a final yield here. Both input and output filters
882 -- can append data to the content in this phase.
883 coroutine.yield([optional footer to be appended to the content])
888 <section id="databases">
889 <title>Database connectivity</title>
891 Mod_lua implements a simple database feature for querying and running commands
892 on the most popular database engines (mySQL, PostgreSQL, FreeTDS, ODBC, SQLite, Oracle)
895 <p>The example below shows how to acquire a database handle and return information from a table:</p>
896 <highlight language="lua">
898 -- Acquire a database handle
899 local database, err = r:dbacquire("mysql", "server=localhost&user=root&database=mydb")
901 -- Select some information from it
902 local results, err = database:select(r, "SELECT `name`, `age` FROM `people` WHERE 1")
904 local rows = results(0) -- fetch all rows synchronously
905 for k, row in pairs(rows) do
906 r:puts( string.format("Name: %s, Age: %s<br/>", row[1], row[2]) )
909 r:puts("Database query error: " .. err)
913 r:puts("Could not connect to the database: " .. err)
918 To utilize <module>mod_dbd</module>, specify <code>mod_dbd</code>
919 as the database type, or leave the field blank:
921 <highlight language="lua">
922 local database = r:dbacquire("mod_dbd")
924 <section id="database_object">
925 <title>Database object and contained functions</title>
926 <p>The database object returned by <code>dbacquire</code> has the following methods:</p>
927 <p><strong>Normal select and query from a database:</strong></p>
928 <highlight language="lua">
929 -- Run a statement and return the number of rows affected:
930 local affected, errmsg = database:query(r, "DELETE FROM `tbl` WHERE 1")
932 -- Run a statement and return a result set that can be used synchronously or async:
933 local result, errmsg = database:select(r, "SELECT * FROM `people` WHERE 1")
935 <p><strong>Using prepared statements (recommended):</strong></p>
936 <highlight language="lua">
937 -- Create and run a prepared statement:
938 local statement, errmsg = database:prepare(r, "DELETE FROM `tbl` WHERE `age` > %u")
940 local result, errmsg = statement:query(20) -- run the statement with age >20
943 -- Fetch a prepared statement from a DBDPrepareSQL directive:
944 local statement, errmsg = database:prepared(r, "someTag")
946 local result, errmsg = statement:select("John Doe", 123) -- inject the values "John Doe" and 123 into the statement
950 <p><strong>Escaping values, closing databases etc:</strong></p>
951 <highlight language="lua">
952 -- Escape a value for use in a statement:
953 local escaped = database:escape(r, [["'|blabla]])
955 -- Close a database connection and free up handles:
958 -- Check whether a database connection is up and running:
959 local connected = database:active()
962 <section id="result_sets">
963 <title>Working with result sets</title>
964 <p>The result set returned by <code>db:select</code> or by the prepared statement functions
965 created through <code>db:prepare</code> can be used to
966 fetch rows synchronously or asynchronously, depending on the row number specified:<br/>
967 <code>result(0)</code> fetches all rows in a synchronous manner, returning a table of rows.<br/>
968 <code>result(-1)</code> fetches the next available row in the set, asynchronously.<br/>
969 <code>result(N)</code> fetches row number <code>N</code>, asynchronously:
971 <highlight language="lua">
972 -- fetch a result set using a regular query:
973 local result, err = db:select(r, "SELECT * FROM `tbl` WHERE 1")
975 local rows = result(0) -- Fetch ALL rows synchronously
976 local row = result(-1) -- Fetch the next available row, asynchronously
977 local row = result(1234) -- Fetch row number 1234, asynchronously
979 <p>One can construct a function that returns an iterative function to iterate over all rows
980 in a synchronous or asynchronous way, depending on the async argument:
982 <highlight language="lua">
983 function rows(resultset, async)
985 local function getnext()
987 local row = resultset(-1)
988 return row and a or nil, row
991 return pairs(resultset(0))
997 local statement, err = db:prepare(r, "SELECT * FROM `tbl` WHERE `age` > %u")
999 -- fetch rows asynchronously:
1000 local result, err = statement:select(20)
1002 for index, row in rows(result, true) do
1007 -- fetch rows synchronously:
1008 local result, err = statement:select(20)
1010 for index, row in rows(result, false) do
1017 <section id="closing_databases">
1018 <title>Closing a database connection</title>
1020 <p>Database handles should be closed using <code>database:close()</code> when they are no longer
1021 needed. If you do not close them manually, they will eventually be garbage collected and
1022 closed by mod_lua, but you may end up having too many unused connections to the database
1023 if you leave the closing up to mod_lua. Essentially, the following two measures are
1026 <highlight language="lua">
1027 -- Method 1: Manually close a handle
1028 local database = r:dbacquire("mod_dbd")
1029 database:close() -- All done
1031 -- Method 2: Letting the garbage collector close it
1032 local database = r:dbacquire("mod_dbd")
1033 database = nil -- throw away the reference
1034 collectgarbage() -- close the handle via GC
1037 <section id="database_caveat">
1038 <title>Precautions when working with databases</title>
1039 <p>Although the standard <code>query</code> and <code>run</code> functions are freely
1040 available, it is recommended that you use prepared statements whenever possible, to
1041 both optimize performance (if your db handle lives on for a long time) and to minimize
1042 the risk of SQL injection attacks. <code>run</code> and <code>query</code> should only
1043 be used when there are no variables inserted into a statement (a static statement).
1044 When using dynamic statements, use <code>db:prepare</code> or <code>db:prepared</code>.
1051 <name>LuaRoot</name>
1052 <description>Specify the base path for resolving relative paths for mod_lua directives</description>
1053 <syntax>LuaRoot /path/to/a/directory</syntax>
1054 <contextlist><context>server config</context><context>virtual host</context>
1055 <context>directory</context><context>.htaccess</context>
1057 <override>All</override>
1060 <p>Specify the base path which will be used to evaluate all
1061 relative paths within mod_lua. If not specified they
1062 will be resolved relative to the current working directory,
1063 which may not always work well for a server.</p>
1065 </directivesynopsis>
1068 <name>LuaScope</name>
1069 <description>One of once, request, conn, thread -- default is once</description>
1070 <syntax>LuaScope once|request|conn|thread|server [min] [max]</syntax>
1071 <default>LuaScope once</default>
1072 <contextlist><context>server config</context><context>virtual host</context>
1073 <context>directory</context><context>.htaccess</context>
1075 <override>All</override>
1078 <p>Specify the lifecycle scope of the Lua interpreter which will
1079 be used by handlers in this "Directory." The default is "once"</p>
1082 <dt>once:</dt> <dd>use the interpreter once and throw it away.</dd>
1084 <dt>request:</dt> <dd>use the interpreter to handle anything based on
1085 the same file within this request, which is also
1086 request scoped.</dd>
1088 <dt>conn:</dt> <dd>Same as request but attached to the connection_rec</dd>
1090 <dt>thread:</dt> <dd>Use the interpreter for the lifetime of the thread
1091 handling the request (only available with threaded MPMs).</dd>
1093 <dt>server:</dt> <dd>This one is different than others because the
1094 server scope is quite long lived, and multiple threads
1095 will have the same server_rec. To accommodate this,
1096 server scoped Lua states are stored in an apr
1097 resource list. The <code>min</code> and <code>max</code> arguments
1098 specify the minimum and maximum number of Lua states to keep in the
1102 Generally speaking, the <code>thread</code> and <code>server</code> scopes
1103 execute roughly 2-3 times faster than the rest, because they don't have to
1104 spawn new Lua states on every request (especially with the event MPM, as
1105 even keepalive requests will use a new thread for each request). If you are
1106 satisfied that your scripts will not have problems reusing a state, then
1107 the <code>thread</code> or <code>server</code> scopes should be used for
1108 maximum performance. While the <code>thread</code> scope will provide the
1109 fastest responses, the <code>server</code> scope will use less memory, as
1110 states are pooled, allowing f.x. 1000 threads to share only 100 Lua states,
1111 thus using only 10% of the memory required by the <code>thread</code> scope.
1114 </directivesynopsis>
1117 <name>LuaMapHandler</name>
1118 <description>Map a path to a lua handler</description>
1119 <syntax>LuaMapHandler uri-pattern /path/to/lua/script.lua [function-name]</syntax>
1120 <contextlist><context>server config</context><context>virtual host</context>
1121 <context>directory</context><context>.htaccess</context>
1123 <override>All</override>
1125 <p>This directive matches a uri pattern to invoke a specific
1126 handler function in a specific file. It uses PCRE regular
1127 expressions to match the uri, and supports interpolating
1128 match groups into both the file path and the function name.
1129 Be careful writing your regular expressions to avoid security
1131 <example><title>Examples:</title>
1132 <highlight language="config">
1133 LuaMapHandler /(\w+)/(\w+) /scripts/$1.lua handle_$2
1136 <p>This would match uri's such as /photos/show?id=9
1137 to the file /scripts/photos.lua and invoke the
1138 handler function handle_show on the lua vm after
1139 loading that file.</p>
1141 <highlight language="config">
1142 LuaMapHandler /bingo /scripts/wombat.lua
1144 <p>This would invoke the "handle" function, which
1145 is the default if no specific function name is
1148 </directivesynopsis>
1151 <name>LuaPackagePath</name>
1152 <description>Add a directory to lua's package.path</description>
1153 <syntax>LuaPackagePath /path/to/include/?.lua</syntax>
1154 <contextlist><context>server config</context><context>virtual host</context>
1155 <context>directory</context><context>.htaccess</context>
1157 <override>All</override>
1158 <usage><p>Add a path to lua's module search path. Follows the same
1159 conventions as lua. This just munges the package.path in the
1162 <example><title>Examples:</title>
1163 <highlight language="config">
1164 LuaPackagePath /scripts/lib/?.lua
1165 LuaPackagePath /scripts/lib/?/init.lua
1169 </directivesynopsis>
1172 <name>LuaPackageCPath</name>
1173 <description>Add a directory to lua's package.cpath</description>
1174 <syntax>LuaPackageCPath /path/to/include/?.soa</syntax>
1175 <contextlist><context>server config</context><context>virtual host</context>
1176 <context>directory</context><context>.htaccess</context>
1178 <override>All</override>
1181 <p>Add a path to lua's shared library search path. Follows the same
1182 conventions as lua. This just munges the package.cpath in the
1186 </directivesynopsis>
1189 <name>LuaCodeCache</name>
1190 <description>Configure the compiled code cache.</description>
1191 <syntax>LuaCodeCache stat|forever|never</syntax>
1192 <default>LuaCodeCache stat</default>
1194 <context>server config</context><context>virtual host</context>
1195 <context>directory</context><context>.htaccess</context>
1197 <override>All</override>
1200 Specify the behavior of the in-memory code cache. The default
1201 is stat, which stats the top level script (not any included
1202 ones) each time that file is needed, and reloads it if the
1203 modified time indicates it is newer than the one it has
1204 already loaded. The other values cause it to keep the file
1205 cached forever (don't stat and replace) or to never cache the
1208 <p>In general stat or forever is good for production, and stat or never
1209 for development.</p>
1211 <example><title>Examples:</title>
1212 <highlight language="config">
1214 LuaCodeCache forever
1220 </directivesynopsis>
1223 <name>LuaHookTranslateName</name>
1224 <description>Provide a hook for the translate name phase of request processing</description>
1225 <syntax>LuaHookTranslateName /path/to/lua/script.lua hook_function_name [early|late]</syntax>
1226 <contextlist><context>server config</context><context>virtual host</context>
1228 <override>All</override>
1229 <compatibility>The optional third argument is supported in 2.3.15 and later</compatibility>
1232 Add a hook (at APR_HOOK_MIDDLE) to the translate name phase of
1233 request processing. The hook function receives a single
1234 argument, the request_rec, and should return a status code,
1235 which is either an HTTP error code, or the constants defined
1236 in the apache2 module: apache2.OK, apache2.DECLINED, or
1239 <p>For those new to hooks, basically each hook will be invoked
1240 until one of them returns apache2.OK. If your hook doesn't
1241 want to do the translation it should just return
1242 apache2.DECLINED. If the request should stop processing, then
1243 return apache2.DONE.</p>
1247 <highlight language="config">
1249 LuaHookTranslateName /scripts/conf/hooks.lua silly_mapper
1252 <highlight language="lua">
1253 -- /scripts/conf/hooks.lua --
1255 function silly_mapper(r)
1256 if r.uri == "/" then
1257 r.filename = "/var/www/home.lua"
1260 return apache2.DECLINED
1265 <note><title>Context</title><p>This directive is not valid in <directive
1266 type="section" module="core">Directory</directive>, <directive
1267 type="section" module="core">Files</directive>, or htaccess
1270 <note><title>Ordering</title><p>The optional arguments "early" or "late"
1271 control when this script runs relative to other modules.</p></note>
1274 </directivesynopsis>
1277 <name>LuaHookFixups</name>
1278 <description>Provide a hook for the fixups phase of a request
1279 processing</description>
1280 <syntax>LuaHookFixups /path/to/lua/script.lua hook_function_name</syntax>
1281 <contextlist><context>server config</context><context>virtual host</context>
1282 <context>directory</context><context>.htaccess</context>
1284 <override>All</override>
1287 Just like LuaHookTranslateName, but executed at the fixups phase
1290 </directivesynopsis>
1293 <name>LuaHookMapToStorage</name>
1294 <description>Provide a hook for the map_to_storage phase of request processing</description>
1295 <syntax>LuaHookMapToStorage /path/to/lua/script.lua hook_function_name</syntax>
1296 <contextlist><context>server config</context><context>virtual host</context>
1297 <context>directory</context><context>.htaccess</context>
1299 <override>All</override>
1301 <p>Like <directive>LuaHookTranslateName</directive> but executed at the
1302 map-to-storage phase of a request. Modules like mod_cache run at this phase,
1303 which makes for an interesting example on what to do here:</p>
1304 <highlight language="config">
1305 LuaHookMapToStorage /path/to/lua/script.lua check_cache
1307 <highlight language="lua">
1311 function read_file(filename)
1312 local input = io.open(filename, "r")
1314 local data = input:read("*a")
1315 cached_files[filename] = data
1316 file = cached_files[filename]
1319 return cached_files[filename]
1322 function check_cache(r)
1323 if r.filename:match("%.png$") then -- Only match PNG files
1324 local file = cached_files[r.filename] -- Check cache entries
1326 file = read_file(r.filename) -- Read file into cache
1328 if file then -- If file exists, write it out
1331 r:info(("Sent %s to client from cache"):format(r.filename))
1332 return apache2.DONE -- skip default handler for PNG files
1335 return apache2.DECLINED -- If we had nothing to do, let others serve this.
1340 </directivesynopsis>
1343 <name>LuaHookCheckUserID</name>
1344 <description>Provide a hook for the check_user_id phase of request processing</description>
1345 <syntax>LuaHookCheckUserID /path/to/lua/script.lua hook_function_name [early|late]</syntax>
1346 <contextlist><context>server config</context><context>virtual host</context>
1347 <context>directory</context><context>.htaccess</context>
1349 <override>All</override>
1350 <compatibility>The optional third argument is supported in 2.3.15 and later</compatibility>
1352 <note><title>Ordering</title><p>The optional arguments "early" or "late"
1353 control when this script runs relative to other modules.</p></note>
1355 </directivesynopsis>
1358 <name>LuaHookTypeChecker</name>
1359 <description>Provide a hook for the type_checker phase of request processing</description>
1360 <syntax>LuaHookTypeChecker /path/to/lua/script.lua hook_function_name</syntax>
1361 <contextlist><context>server config</context><context>virtual host</context>
1362 <context>directory</context><context>.htaccess</context>
1364 <override>All</override>
1366 This directive provides a hook for the type_checker phase of the request processing.
1367 This phase is where requests are assigned a content type and a handler, and thus can
1368 be used to modify the type and handler based on input:
1370 <highlight language="config">
1371 LuaHookTypeChecker /path/to/lua/script.lua type_checker
1373 <highlight language="lua">
1374 function type_checker(r)
1375 if r.uri:match("%.to_gif$") then -- match foo.png.to_gif
1376 r.content_type = "image/gif" -- assign it the image/gif type
1377 r.handler = "gifWizard" -- tell the gifWizard module to handle this
1378 r.filename = r.uri:gsub("%.to_gif$", "") -- fix the filename requested
1382 return apache2.DECLINED
1386 </directivesynopsis>
1389 <name>LuaHookAuthChecker</name>
1390 <description>Provide a hook for the auth_checker phase of request processing</description>
1391 <syntax>LuaHookAuthChecker /path/to/lua/script.lua hook_function_name [early|late]</syntax>
1392 <contextlist><context>server config</context><context>virtual host</context>
1393 <context>directory</context><context>.htaccess</context>
1395 <override>All</override>
1396 <compatibility>The optional third argument is supported in 2.3.15 and later</compatibility>
1398 <p>Invoke a lua function in the auth_checker phase of processing
1399 a request. This can be used to implement arbitrary authentication
1400 and authorization checking. A very simple example:
1402 <highlight language="lua">
1405 -- fake authcheck hook
1406 -- If request has no auth info, set the response header and
1407 -- return a 401 to ask the browser for basic auth info.
1408 -- If request has auth info, don't actually look at it, just
1409 -- pretend we got userid 'foo' and validated it.
1410 -- Then check if the userid is 'foo' and accept the request.
1411 function authcheck_hook(r)
1413 -- look for auth info
1414 auth = r.headers_in['Authorization']
1420 if r.user == nil then
1421 r:debug("authcheck: user is nil, returning 401")
1422 r.err_headers_out['WWW-Authenticate'] = 'Basic realm="WallyWorld"'
1424 elseif r.user == "foo" then
1425 r:debug('user foo: OK')
1427 r:debug("authcheck: user='" .. r.user .. "'")
1428 r.err_headers_out['WWW-Authenticate'] = 'Basic realm="WallyWorld"'
1434 <note><title>Ordering</title><p>The optional arguments "early" or "late"
1435 control when this script runs relative to other modules.</p></note>
1437 </directivesynopsis>
1440 <name>LuaHookAccessChecker</name>
1441 <description>Provide a hook for the access_checker phase of request processing</description>
1442 <syntax>LuaHookAccessChecker /path/to/lua/script.lua hook_function_name [early|late]</syntax>
1443 <contextlist><context>server config</context><context>virtual host</context>
1444 <context>directory</context><context>.htaccess</context>
1446 <override>All</override>
1447 <compatibility>The optional third argument is supported in 2.3.15 and later</compatibility>
1449 <p>Add your hook to the access_checker phase. An access checker
1450 hook function usually returns OK, DECLINED, or HTTP_FORBIDDEN.</p>
1451 <note><title>Ordering</title><p>The optional arguments "early" or "late"
1452 control when this script runs relative to other modules.</p></note>
1454 </directivesynopsis>
1457 <name>LuaHookInsertFilter</name>
1458 <description>Provide a hook for the insert_filter phase of request processing</description>
1459 <syntax>LuaHookInsertFilter /path/to/lua/script.lua hook_function_name</syntax>
1460 <contextlist><context>server config</context><context>virtual host</context>
1461 <context>directory</context><context>.htaccess</context>
1463 <override>All</override>
1464 <usage><p>Not Yet Implemented</p></usage>
1465 </directivesynopsis>
1468 <name>LuaInherit</name>
1469 <description>Controls how parent configuration sections are merged into children</description>
1470 <syntax>LuaInherit none|parent-first|parent-last</syntax>
1471 <default>LuaInherit parent-first</default>
1472 <contextlist><context>server config</context><context>virtual host</context>
1473 <context>directory</context><context>.htaccess</context>
1475 <override>All</override>
1476 <compatibility>2.4.0 and later</compatibility>
1477 <usage><p>By default, if LuaHook* directives are used in overlapping
1478 Directory or Location configuration sections, the scripts defined in the
1479 more specific section are run <em>after</em> those defined in the more
1480 generic section (LuaInherit parent-first). You can reverse this order, or
1481 make the parent context not apply at all.</p>
1483 <p> In previous 2.3.x releases, the default was effectively to ignore LuaHook*
1484 directives from parent configuration sections.</p></usage>
1485 </directivesynopsis>
1488 <name>LuaQuickHandler</name>
1489 <description>Provide a hook for the quick handler of request processing</description>
1490 <syntax>LuaQuickHandler /path/to/script.lua hook_function_name</syntax>
1491 <contextlist><context>server config</context><context>virtual host</context>
1493 <override>All</override>
1496 This phase is run immediately after the request has been mapped to a virtal host,
1497 and can be used to either do some request processing before the other phases kick
1498 in, or to serve a request without the need to translate, map to storage et cetera.
1499 As this phase is run before anything else, directives such as <directive
1500 type="section" module="core">Location</directive> or <directive
1501 type="section" module="core">Directory</directive> are void in this phase, just as
1502 URIs have not been properly parsed yet.
1504 <note><title>Context</title><p>This directive is not valid in <directive
1505 type="section" module="core">Directory</directive>, <directive
1506 type="section" module="core">Files</directive>, or htaccess
1509 </directivesynopsis>
1512 <name>LuaAuthzProvider</name>
1513 <description>Plug an authorization provider function into <module>mod_authz_core</module>
1515 <syntax>LuaAuthzProvider provider_name /path/to/lua/script.lua function_name</syntax>
1516 <contextlist><context>server config</context> </contextlist>
1517 <compatibility>2.4.3 and later</compatibility>
1520 <p>After a lua function has been registered as authorization provider, it can be used
1521 with the <directive module="mod_authz_core">Require</directive> directive:</p>
1523 <highlight language="config">
1524 LuaRoot /usr/local/apache2/lua
1525 LuaAuthzProvider foo authz.lua authz_check_foo
1530 <highlight language="lua">
1532 function authz_check_foo(r, who)
1533 if r.user ~= who then return apache2.AUTHZ_DENIED
1534 return apache2.AUTHZ_GRANTED
1540 </directivesynopsis>
1544 <name>LuaInputFilter</name>
1545 <description>Provide a Lua function for content input filtering</description>
1546 <syntax>LuaInputFilter filter_name /path/to/lua/script.lua function_name</syntax>
1547 <contextlist><context>server config</context> </contextlist>
1548 <compatibility>2.5.0 and later</compatibility>
1551 <p>Provides a means of adding a Lua function as an input filter.
1552 As with output filters, input filters work as coroutines,
1553 first yielding before buffers are sent, then yielding whenever
1554 a bucket needs to be passed down the chain, and finally (optionally)
1555 yielding anything that needs to be appended to the input data. The
1556 global variable <code>bucket</code> holds the buckets as they are passed
1557 onto the Lua script:
1560 <highlight language="config">
1561 LuaInputFilter myInputFilter /www/filter.lua input_filter
1562 <FilesMatch "\.lua>
1563 SetInputFilter myInputFilter
1566 <highlight language="lua">
1568 Example input filter that converts all POST data to uppercase.
1570 function input_filter(r)
1571 print("luaInputFilter called") -- debug print
1572 coroutine.yield() -- Yield and wait for buckets
1573 while bucket do -- For each bucket, do...
1574 local output = string.upper(bucket) -- Convert all POST data to uppercase
1575 coroutine.yield(output) -- Send converted data down the chain
1577 -- No more buckets available.
1578 coroutine.yield("&filterSignature=1234") -- Append signature at the end
1582 The input filter supports denying/skipping a filter if it is deemed unwanted:
1584 <highlight language="lua">
1585 function input_filter(r)
1587 return -- Simply deny filtering, passing on the original content instead
1589 coroutine.yield() -- wait for buckets
1590 ... -- insert filter stuff here
1594 See "<a href="#modifying_buckets">Modifying contents with Lua
1595 filters</a>" for more information.
1598 </directivesynopsis>
1601 <name>LuaOutputFilter</name>
1602 <description>Provide a Lua function for content output filtering</description>
1603 <syntax>LuaOutputFilter filter_name /path/to/lua/script.lua function_name</syntax>
1604 <contextlist><context>server config</context> </contextlist>
1605 <compatibility>2.5.0 and later</compatibility>
1608 <p>Provides a means of adding a Lua function as an output filter.
1609 As with input filters, output filters work as coroutines,
1610 first yielding before buffers are sent, then yielding whenever
1611 a bucket needs to be passed down the chain, and finally (optionally)
1612 yielding anything that needs to be appended to the input data. The
1613 global variable <code>bucket</code> holds the buckets as they are passed
1614 onto the Lua script:
1617 <highlight language="config">
1618 LuaOutputFilter myOutputFilter /www/filter.lua output_filter
1619 <FilesMatch "\.lua>
1620 SetOutputFilter myOutputFilter
1623 <highlight language="lua">
1625 Example output filter that escapes all HTML entities in the output
1627 function output_filter(r)
1628 coroutine.yield("(Handled by myOutputFilter)<br/>\n") -- Prepend some data to the output,
1629 -- yield and wait for buckets.
1630 while bucket do -- For each bucket, do...
1631 local output = r:escape_html(bucket) -- Escape all output
1632 coroutine.yield(output) -- Send converted data down the chain
1634 -- No more buckets available.
1638 As with the input filter, the output filter supports denying/skipping a filter
1639 if it is deemed unwanted:
1641 <highlight language="lua">
1642 function output_filter(r)
1643 if not r.content_type:match("text/html") then
1644 return -- Simply deny filtering, passing on the original content instead
1646 coroutine.yield() -- wait for buckets
1647 ... -- insert filter stuff here
1651 See "<a href="#modifying_buckets">Modifying contents with Lua filters</a>" for more
1655 </directivesynopsis>