]> granicus.if.org Git - apache/blob - docs/manual/mod/mod_lua.html.en
mention some trickyness with mod_lua + mod_filter.
[apache] / docs / manual / mod / mod_lua.html.en
1 <?xml version="1.0" encoding="ISO-8859-1"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3 <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"><head><!--
4         XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
5               This file is generated from xml source: DO NOT EDIT
6         XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7       -->
8 <title>mod_lua - Apache HTTP Server</title>
9 <link href="../style/css/manual.css" rel="stylesheet" media="all" type="text/css" title="Main stylesheet" />
10 <link href="../style/css/manual-loose-100pc.css" rel="alternate stylesheet" media="all" type="text/css" title="No Sidebar - Default font size" />
11 <link href="../style/css/manual-print.css" rel="stylesheet" media="print" type="text/css" /><link rel="stylesheet" type="text/css" href="../style/css/prettify.css" />
12 <script src="../style/scripts/prettify.js" type="text/javascript">
13 </script>
14
15 <link href="../images/favicon.ico" rel="shortcut icon" /></head>
16 <body>
17 <div id="page-header">
18 <p class="menu"><a href="../mod/">Modules</a> | <a href="../mod/quickreference.html">Directives</a> | <a href="http://wiki.apache.org/httpd/FAQ">FAQ</a> | <a href="../glossary.html">Glossary</a> | <a href="../sitemap.html">Sitemap</a></p>
19 <p class="apache">Apache HTTP Server Version 2.5</p>
20 <img alt="" src="../images/feather.gif" /></div>
21 <div class="up"><a href="./"><img title="&lt;-" alt="&lt;-" src="../images/left.gif" /></a></div>
22 <div id="path">
23 <a href="http://www.apache.org/">Apache</a> &gt; <a href="http://httpd.apache.org/">HTTP Server</a> &gt; <a href="http://httpd.apache.org/docs/">Documentation</a> &gt; <a href="../">Version 2.5</a> &gt; <a href="./">Modules</a></div>
24 <div id="page-content">
25 <div id="preamble"><h1>Apache Module mod_lua</h1>
26 <div class="toplang">
27 <p><span>Available Languages: </span><a href="../en/mod/mod_lua.html" title="English">&nbsp;en&nbsp;</a> |
28 <a href="../fr/mod/mod_lua.html" hreflang="fr" rel="alternate" title="Français">&nbsp;fr&nbsp;</a></p>
29 </div>
30 <table class="module"><tr><th><a href="module-dict.html#Description">Description:</a></th><td>Provides Lua hooks into various portions of the httpd
31 request processing</td></tr>
32 <tr><th><a href="module-dict.html#Status">Status:</a></th><td>Experimental</td></tr>
33 <tr><th><a href="module-dict.html#ModuleIdentifier">Module Identifier:</a></th><td>lua_module</td></tr>
34 <tr><th><a href="module-dict.html#SourceFile">Source File:</a></th><td>mod_lua.c</td></tr>
35 <tr><th><a href="module-dict.html#Compatibility">Compatibility:</a></th><td>2.3 and later</td></tr></table>
36 <h3>Summary</h3>
37
38 <p>This module allows the server to be extended with scripts written in the
39 Lua programming language.  The extension points (hooks) available with
40 <code class="module"><a href="../mod/mod_lua.html">mod_lua</a></code> include many of the hooks available to
41 natively compiled Apache HTTP Server modules, such as mapping requests to
42 files, generating dynamic responses, access control, authentication, and
43 authorization</p>
44
45 <p>More information on the Lua programming language can be found at the
46 <a href="http://www.lua.org/">the Lua website</a>.</p>
47
48 <div class="note"><code>mod_lua</code> is still in experimental state.
49 Until it is declared stable, usage and behavior may change
50 at any time, even between stable releases of the 2.4.x series.
51 Be sure to check the CHANGES file before upgrading.</div>
52
53 <div class="warning"><h3>Warning</h3>
54 <p>This module holds a great deal of power over httpd, which is both a 
55 strength and a potential security risk. It is <strong>not</strong> recommended 
56 that you use this module on a server that is shared with users you do not 
57 trust, as it can be abused to change the internal workings of httpd.</p>
58 </div>
59
60 </div>
61 <div id="quickview"><h3 class="directives">Directives</h3>
62 <ul id="toc">
63 <li><img alt="" src="../images/down.gif" /> <a href="#luaauthzprovider">LuaAuthzProvider</a></li>
64 <li><img alt="" src="../images/down.gif" /> <a href="#luacodecache">LuaCodeCache</a></li>
65 <li><img alt="" src="../images/down.gif" /> <a href="#luahookaccesschecker">LuaHookAccessChecker</a></li>
66 <li><img alt="" src="../images/down.gif" /> <a href="#luahookauthchecker">LuaHookAuthChecker</a></li>
67 <li><img alt="" src="../images/down.gif" /> <a href="#luahookcheckuserid">LuaHookCheckUserID</a></li>
68 <li><img alt="" src="../images/down.gif" /> <a href="#luahookfixups">LuaHookFixups</a></li>
69 <li><img alt="" src="../images/down.gif" /> <a href="#luahookinsertfilter">LuaHookInsertFilter</a></li>
70 <li><img alt="" src="../images/down.gif" /> <a href="#luahooklog">LuaHookLog</a></li>
71 <li><img alt="" src="../images/down.gif" /> <a href="#luahookmaptostorage">LuaHookMapToStorage</a></li>
72 <li><img alt="" src="../images/down.gif" /> <a href="#luahooktranslatename">LuaHookTranslateName</a></li>
73 <li><img alt="" src="../images/down.gif" /> <a href="#luahooktypechecker">LuaHookTypeChecker</a></li>
74 <li><img alt="" src="../images/down.gif" /> <a href="#luainherit">LuaInherit</a></li>
75 <li><img alt="" src="../images/down.gif" /> <a href="#luainputfilter">LuaInputFilter</a></li>
76 <li><img alt="" src="../images/down.gif" /> <a href="#luamaphandler">LuaMapHandler</a></li>
77 <li><img alt="" src="../images/down.gif" /> <a href="#luaoutputfilter">LuaOutputFilter</a></li>
78 <li><img alt="" src="../images/down.gif" /> <a href="#luapackagecpath">LuaPackageCPath</a></li>
79 <li><img alt="" src="../images/down.gif" /> <a href="#luapackagepath">LuaPackagePath</a></li>
80 <li><img alt="" src="../images/down.gif" /> <a href="#luaquickhandler">LuaQuickHandler</a></li>
81 <li><img alt="" src="../images/down.gif" /> <a href="#luaroot">LuaRoot</a></li>
82 <li><img alt="" src="../images/down.gif" /> <a href="#luascope">LuaScope</a></li>
83 </ul>
84 <h3>Topics</h3>
85 <ul id="topics">
86 <li><img alt="" src="../images/down.gif" /> <a href="#basicconf">Basic Configuration</a></li>
87 <li><img alt="" src="../images/down.gif" /> <a href="#writinghandlers">Writing Handlers</a></li>
88 <li><img alt="" src="../images/down.gif" /> <a href="#writingauthzproviders">Writing Authorization Providers</a></li>
89 <li><img alt="" src="../images/down.gif" /> <a href="#writinghooks">Writing Hooks</a></li>
90 <li><img alt="" src="../images/down.gif" /> <a href="#datastructures">Data Structures</a></li>
91 <li><img alt="" src="../images/down.gif" /> <a href="#functions">Built in functions</a></li>
92 <li><img alt="" src="../images/down.gif" /> <a href="#logging">Logging Functions</a></li>
93 <li><img alt="" src="../images/down.gif" /> <a href="#apache2">apache2 Package</a></li>
94 <li><img alt="" src="../images/down.gif" /> <a href="#modifying_buckets">Modifying contents with Lua filters</a></li>
95 <li><img alt="" src="../images/down.gif" /> <a href="#databases">Database connectivity</a></li>
96 </ul><ul class="seealso"><li><a href="#comments_section">Comments</a></li></ul></div>
97 <div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
98 <div class="section">
99 <h2><a name="basicconf" id="basicconf">Basic Configuration</a></h2>
100
101 <p>The basic module loading directive is</p>
102
103 <pre class="prettyprint lang-config">
104     LoadModule lua_module modules/mod_lua.so
105 </pre>
106
107
108 <p>
109 <code>mod_lua</code> provides a handler named <code>lua-script</code>,
110 which can be used with an <code>AddHandler</code> directive:</p>
111
112 <pre class="prettyprint lang-config">
113 AddHandler lua-script .lua
114 </pre>
115
116
117 <p>
118 This will cause <code>mod_lua</code> to handle requests for files
119 ending in <code>.lua</code> by invoking that file's
120 <code>handle</code> function.
121 </p>
122
123 <p>For more flexibility, see <code class="directive">LuaMapHandler</code>.
124 </p>
125
126 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
127 <div class="section">
128 <h2><a name="writinghandlers" id="writinghandlers">Writing Handlers</a></h2>
129 <p> In the Apache HTTP Server API, the handler is a specific kind of hook
130 responsible for generating the response.  Examples of modules that include a
131 handler are <code class="module"><a href="../mod/mod_proxy.html">mod_proxy</a></code>, <code class="module"><a href="../mod/mod_cgi.html">mod_cgi</a></code>,
132 and <code class="module"><a href="../mod/mod_status.html">mod_status</a></code>.</p>
133
134 <p><code>mod_lua</code> always looks to invoke a Lua function for the handler, rather than
135 just evaluating a script body CGI style. A handler function looks
136 something like this:</p>
137
138
139 <pre class="prettyprint lang-lua">
140 <strong>example.lua</strong><br />
141 -- example handler
142
143 require "string"
144
145 --[[
146      This is the default method name for Lua handlers, see the optional
147      function-name in the LuaMapHandler directive to choose a different
148      entry point.
149 --]]
150 function handle(r)
151     r.content_type = "text/plain"
152
153     if r.method == 'GET' then
154         r:puts("Hello Lua World!\n")
155         for k, v in pairs( r:parseargs() ) do
156             r:puts( string.format("%s: %s\n", k, v) )
157         end
158     elseif r.method == 'POST' then
159         r:puts("Hello Lua World!\n")
160         for k, v in pairs( r:parsebody() ) do
161             r:puts( string.format("%s: %s\n", k, v) )
162         end
163     elseif r.method == 'PUT' then
164 -- use our own Error contents
165         r:puts("Unsupported HTTP method " .. r.method)
166         r.status = 405
167         return apache2.ok
168     else
169 -- use the ErrorDocument
170         return 501
171     end
172     return apache2.OK
173 end
174 </pre>
175
176
177 <p>
178 This handler function just prints out the uri or form encoded
179 arguments to a plaintext page.
180 </p>
181
182 <p>
183 This means (and in fact encourages) that you can have multiple
184 handlers (or hooks, or filters) in the same script.
185 </p>
186
187 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
188 <div class="section">
189 <h2><a name="writingauthzproviders" id="writingauthzproviders">Writing Authorization Providers</a></h2>
190
191
192 <p><code class="module"><a href="../mod/mod_authz_core.html">mod_authz_core</a></code> provides a high-level interface to
193 authorization that is much easier to use than using into the relevant
194 hooks directly. The first argument to the
195 <code class="directive"><a href="../mod/mod_authz_core.html#require">Require</a></code> directive gives
196 the name of the responsible authorization provider. For any
197 <code class="directive"><a href="../mod/mod_authz_core.html#require">Require</a></code> line,
198 <code class="module"><a href="../mod/mod_authz_core.html">mod_authz_core</a></code> will call the authorization provider
199 of the given name, passing the rest of the line as parameters. The
200 provider will then check authorization and pass the result as return
201 value.</p>
202
203 <p>The authz provider is normally called before authentication. If it needs to
204 know the authenticated user name (or if the user will be authenticated at
205 all), the provider must return <code>apache2.AUTHZ_DENIED_NO_USER</code>.
206 This will cause authentication to proceed and the authz provider to be
207 called a second time.</p>
208
209 <p>The following authz provider function takes two arguments, one ip
210 address and one user name. It will allow access from the given ip address
211 without authentication, or if the authenticated user matches the second
212 argument:</p>
213
214 <pre class="prettyprint lang-lua">
215 <strong>authz_provider.lua</strong><br />
216
217 require 'apache2'
218
219 function authz_check_foo(r, ip, user)
220     if r.useragent_ip == ip then
221         return apache2.AUTHZ_GRANTED
222     elseif r.user == nil then
223         return apache2.AUTHZ_DENIED_NO_USER
224     elseif r.user == user then
225         return apache2.AUTHZ_GRANTED
226     else
227         return apache2.AUTHZ_DENIED
228     end
229 end
230 </pre>
231
232
233 <p>The following configuration registers this function as provider
234 <code>foo</code> and configures it for URL <code>/</code>:</p>
235 <pre class="prettyprint lang-config">
236 LuaAuthzProvider foo authz_provider.lua authz_check_foo
237 &lt;Location /&gt;
238   Require foo 10.1.2.3 john_doe
239 &lt;/Location&gt;
240 </pre>
241
242
243 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
244 <div class="section">
245 <h2><a name="writinghooks" id="writinghooks">Writing Hooks</a></h2>
246
247 <p>Hook functions are how modules (and Lua scripts) participate in the
248 processing of requests. Each type of hook exposed by the server exists for
249 a specific purpose, such as mapping requests to the file system,
250 performing access control, or setting mime types:</p>
251
252 <table class="bordered"><tr class="header">
253         <th>Hook phase</th>
254         <th>mod_lua directive</th>
255         <th>Description</th>
256     </tr>
257 <tr>
258         <td>Quick handler</td>
259         <td><code class="directive"><a href="#luaquickhandler">LuaQuickHandler</a></code></td>
260         <td>This is the first hook that will be called after a request has 
261             been mapped to a host or virtual host</td>
262     </tr>
263 <tr class="odd">
264         <td>Translate name</td>
265         <td><code class="directive"><a href="#luahooktranslatename">LuaHookTranslateName</a></code></td>
266         <td>This phase translates the requested URI into a filename on the 
267             system. Modules such as <code class="module"><a href="../mod/mod_alias.html">mod_alias</a></code> and
268             <code class="module"><a href="../mod/mod_rewrite.html">mod_rewrite</a></code> operate in this phase.</td>
269     </tr>
270 <tr>
271         <td>Map to storage</td>
272         <td><code class="directive"><a href="#luahookmaptostorage">LuaHookMapToStorage</a></code></td>
273         <td>This phase maps files to their physical, cached or external/proxied storage. 
274             It can be used by proxy or caching modules</td>
275     </tr>
276 <tr class="odd">
277         <td>Check Access</td>
278         <td><code class="directive"><a href="#luahookaccesschecker">LuaHookAccessChecker</a></code></td>
279         <td>This phase checks whether a client has access to a resource. This 
280             phase is run before the user is authenticated, so beware.
281         </td>
282     </tr>
283 <tr>
284         <td>Check User ID</td>
285         <td><code class="directive"><a href="#luahookcheckuserid">LuaHookCheckUserID</a></code></td>
286         <td>This phase it used to check the negotiated user ID</td>
287     </tr>
288 <tr class="odd">
289         <td>Check Authorization</td>
290         <td><code class="directive"><a href="#luahookauthchecker">LuaHookAuthChecker</a></code> or 
291             <code class="directive"><a href="#luaauthzprovider">LuaAuthzProvider</a></code></td>
292         <td>This phase authorizes a user based on the negotiated credentials, such as 
293             user ID, client certificate etc.
294         </td>
295     </tr>
296 <tr>
297         <td>Check Type</td>
298         <td><code class="directive"><a href="#luahooktypechecker">LuaHookTypeChecker</a></code></td>
299         <td>This phase checks the requested file and assigns a content type and 
300             a handler to it</td>
301     </tr>
302 <tr class="odd">
303         <td>Fixups</td>
304         <td><code class="directive"><a href="#luahookfixups">LuaHookFixups</a></code></td>
305         <td>This is the final "fix anything" phase before the content handlers 
306             are run. Any last-minute changes to the request should be made here.</td>
307     </tr>
308 <tr>
309         <td>Content handler</td>
310         <td>fx. <code>.lua</code> files or through <code class="directive"><a href="#luamaphandler">LuaMapHandler</a></code></td>
311         <td>This is where the content is handled. Files are read, parsed, some are run, 
312             and the result is sent to the client</td>
313     </tr>
314 <tr class="odd">
315         <td>Logging</td>
316         <td><code class="directive"><a href="#luahooklog">LuaHookLog</a></code></td>
317         <td>Once a request has been handled, it enters several logging phases, 
318             which logs the request in either the error or access log. Mod_lua
319             is able to hook into the start of this and control logging output.</td>
320     </tr>
321 </table>
322
323 <p>Hook functions are passed the request object as their only argument 
324 (except for LuaAuthzProvider, which also gets passed the arguments from 
325 the Require directive).
326 They can return any value, depending on the hook, but most commonly
327 they'll return OK, DONE, or DECLINED, which you can write in Lua as
328 <code>apache2.OK</code>, <code>apache2.DONE</code>, or
329 <code>apache2.DECLINED</code>, or else an HTTP status code.</p>
330
331
332 <pre class="prettyprint lang-lua">
333 <strong>translate_name.lua</strong><br />
334 -- example hook that rewrites the URI to a filesystem path.
335
336 require 'apache2'
337
338 function translate_name(r)
339     if r.uri == "/translate-name" then
340         r.filename = r.document_root .. "/find_me.txt"
341         return apache2.OK
342     end
343     -- we don't care about this URL, give another module a chance
344     return apache2.DECLINED
345 end
346 </pre>
347
348
349
350 <pre class="prettyprint lang-lua">
351 <strong>translate_name2.lua</strong><br />
352 --[[ example hook that rewrites one URI to another URI. It returns a
353      apache2.DECLINED to give other URL mappers a chance to work on the
354      substitution, including the core translate_name hook which maps based
355      on the DocumentRoot.
356
357      Note: Use the early/late flags in the directive to make it run before
358            or after mod_alias.
359 --]]
360
361 require 'apache2'
362
363 function translate_name(r)
364     if r.uri == "/translate-name" then
365         r.uri = "/find_me.txt"
366         return apache2.DECLINED
367     end
368     return apache2.DECLINED
369 end
370 </pre>
371
372 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
373 <div class="section">
374 <h2><a name="datastructures" id="datastructures">Data Structures</a></h2>
375
376 <dl>
377 <dt>request_rec</dt>
378         <dd>
379         <p>The request_rec is mapped in as a userdata. It has a metatable
380         which lets you do useful things with it. For the most part it
381         has the same fields as the request_rec struct, many of which are writable as
382         well as readable.  (The table fields' content can be changed, but the
383         fields themselves cannot be set to different tables.)</p>
384
385         <table class="bordered"><tr class="header">
386           <th><strong>Name</strong></th>
387           <th><strong>Lua type</strong></th>
388           <th><strong>Writable</strong></th>
389           <th><strong>Description</strong></th>
390         </tr>
391 <tr>
392           <td><code>allowoverrides</code></td>
393           <td>string</td>
394           <td>no</td>
395           <td>The AllowOverride options applied to the current request.</td>
396         </tr>
397 <tr class="odd">
398           <td><code>ap_auth_type</code></td>
399           <td>string</td>
400           <td>no</td>
401           <td>If an authentication check was made, this is set to the type 
402           of authentication (f.x. <code>basic</code>)</td>
403         </tr>
404 <tr>
405           <td><code>args</code></td>
406           <td>string</td>
407           <td>yes</td>
408           <td>The query string arguments extracted from the request 
409             (f.x. <code>foo=bar&amp;name=johnsmith</code>)</td>
410         </tr>
411 <tr class="odd">
412           <td><code>assbackwards</code></td>
413           <td>boolean</td>
414           <td>no</td>
415           <td>Set to true if this is an HTTP/0.9 style request 
416             (e.g. <code>GET /foo</code> (with no headers) )</td>
417         </tr>
418 <tr>
419           <td><code>auth_name</code></td>
420           <td>string</td>
421           <td>no</td>
422           <td>The realm name used for authorization (if applicable).</td>
423         </tr>
424 <tr class="odd">
425           <td><code>banner</code></td>
426           <td>string</td>
427           <td>no</td>
428           <td>The server banner, f.x. <code>Apache HTTP Server/2.4.3 openssl/0.9.8c</code></td>
429         </tr>
430 <tr>
431           <td><code>basic_auth_pw</code></td>
432           <td>string</td>
433           <td>no</td>
434           <td>The basic auth password sent with this request, if any</td>
435         </tr>
436 <tr class="odd">
437           <td><code>canonical_filename</code></td>
438           <td>string</td>
439           <td>no</td>
440           <td>The canonical filename of the request</td>
441         </tr>
442 <tr>
443           <td><code>content_encoding</code></td>
444           <td>string</td>
445           <td>no</td>
446           <td>The content encoding of the current request</td>
447         </tr>
448 <tr class="odd">
449           <td><code>content_type</code></td>
450           <td>string</td>
451           <td>yes</td>
452           <td>The content type of the current request, as determined in the 
453             type_check phase (f.x. <code>image/gif</code> or <code>text/html</code>)</td>
454         </tr>
455 <tr>
456           <td><code>context_prefix</code></td>
457           <td>string</td>
458           <td>no</td>
459           <td />
460         </tr>
461 <tr class="odd">
462           <td><code>context_document_root</code></td>
463           <td>string</td>
464           <td>no</td>
465           <td />
466         </tr>
467 <tr>
468           <td><code>document_root</code></td>
469           <td>string</td>
470           <td>no</td>
471           <td>The document root of the host</td>
472         </tr>
473 <tr class="odd">
474           <td><code>err_headers_out</code></td>
475           <td>table</td>
476           <td>no</td>
477           <td>MIME header environment for the response, printed even on errors and
478             persist across internal redirects</td>
479         </tr>
480 <tr>
481           <td><code>filename</code></td>
482           <td>string</td>
483           <td>yes</td>
484           <td>The file name that the request maps to, f.x. /www/example.com/foo.txt. This can be 
485             changed in the translate-name or map-to-storage phases of a request to allow the 
486             default handler (or script handlers) to serve a different file than what was requested.</td>
487         </tr>
488 <tr class="odd">
489           <td><code>handler</code></td>
490           <td>string</td>
491           <td>yes</td>
492           <td>The name of the <a href="../handler.html">handler</a> that should serve this request, f.x. 
493             <code>lua-script</code> if it is to be served by mod_lua. This is typically set by the 
494             <code class="directive"><a href="../mod/mod_mime.html#addhandler">AddHandler</a></code> or <code class="directive"><a href="../mod/core.html#sethandler">SetHandler</a></code> 
495             directives, but could also be set via mod_lua to allow another handler to serve up a specific request 
496             that would otherwise not be served by it.
497             </td>
498         </tr>
499 <tr>
500           <td><code>headers_in</code></td>
501           <td>table</td>
502           <td>yes</td>
503           <td>MIME header environment from the request. This contains headers such as <code>Host, 
504             User-Agent, Referer</code> and so on.</td>
505         </tr>
506 <tr class="odd">
507           <td><code>headers_out</code></td>
508           <td>table</td>
509           <td>yes</td>
510           <td>MIME header environment for the response.</td>
511         </tr>
512 <tr>
513           <td><code>hostname</code></td>
514           <td>string</td>
515           <td>no</td>
516           <td>The host name, as set by the <code>Host:</code> header or by a full URI.</td>
517         </tr>
518 <tr class="odd">
519           <td><code>is_https</code></td>
520           <td>boolean</td>
521           <td>no</td>
522           <td>Whether or not this request is done via HTTPS</td>
523         </tr>
524 <tr>
525           <td><code>is_initial_req</code></td>
526           <td>boolean</td>
527           <td>no</td>
528           <td>Whether this request is the initial request or a sub-request</td>
529         </tr>
530 <tr class="odd">
531           <td><code>limit_req_body</code></td>
532           <td>number</td>
533           <td>no</td>
534           <td>The size limit of the request body for this request, or 0 if no limit.</td>
535         </tr>
536 <tr>
537           <td><code>log_id</code></td>
538           <td>string</td>
539           <td>no</td>
540           <td>The ID to identify request in access and error log.</td>
541         </tr>
542 <tr class="odd">
543           <td><code>method</code></td>
544           <td>string</td>
545           <td>no</td>
546           <td>The request method, f.x. <code>GET</code> or <code>POST</code>.</td>
547         </tr>
548 <tr>
549           <td><code>notes</code></td>
550           <td>table</td>
551           <td>yes</td>
552           <td>A list of notes that can be passed on from one module to another.</td>
553         </tr>
554 <tr class="odd">
555           <td><code>options</code></td>
556           <td>string</td>
557           <td>no</td>
558           <td>The Options directive applied to the current request.</td>
559         </tr>
560 <tr>
561           <td><code>path_info</code></td>
562           <td>string</td>
563           <td>no</td>
564           <td>The PATH_INFO extracted from this request.</td>
565         </tr>
566 <tr class="odd">
567           <td><code>port</code></td>
568           <td>number</td>
569           <td>no</td>
570           <td>The server port used by the request.</td>
571         </tr>
572 <tr>
573           <td><code>protocol</code></td>
574           <td>string</td>
575           <td>no</td>
576           <td>The protocol used, f.x. <code>HTTP/1.1</code></td>
577         </tr>
578 <tr class="odd">
579           <td><code>proxyreq</code></td>
580           <td>string</td>
581           <td>yes</td>
582           <td>Denotes whether this is a proxy request or not. This value is generally set in 
583             the post_read_request/translate_name phase of a request.</td>
584         </tr>
585 <tr>
586           <td><code>range</code></td>
587           <td>string</td>
588           <td>no</td>
589           <td>The contents of the <code>Range:</code> header.</td>
590         </tr>
591 <tr class="odd">
592           <td><code>remaining</code></td>
593           <td>number</td>
594           <td>no</td>
595           <td>The number of bytes remaining to be read from the request body.</td>
596         </tr>
597 <tr>
598           <td><code>server_built</code></td>
599           <td>string</td>
600           <td>no</td>
601           <td>The time the server executable was built.</td>
602         </tr>
603 <tr class="odd">
604           <td><code>server_name</code></td>
605           <td>string</td>
606           <td>no</td>
607           <td>The server name for this request.</td>
608         </tr>
609 <tr>
610           <td><code>some_auth_required</code></td>
611           <td>boolean</td>
612           <td>no</td>
613           <td>Whether some authorization is/was required for this request.</td>
614         </tr>
615 <tr class="odd">
616           <td><code>subprocess_env</code></td>
617           <td>table</td>
618           <td>yes</td>
619           <td>The environment variables set for this request.</td>
620         </tr>
621 <tr>
622           <td><code>started</code></td>
623           <td>number</td>
624           <td>no</td>
625           <td>The time the server was (re)started, in seconds since the epoch (Jan 1st, 1970)</td>
626         </tr>
627 <tr class="odd">
628           <td><code>status</code></td>
629           <td>number</td>
630           <td>yes</td>
631           <td>The (current) HTTP return code for this request, f.x. <code>200</code> or <code>404</code>.</td>
632         </tr>
633 <tr>
634           <td><code>the_request</code></td>
635           <td>string</td>
636           <td>no</td>
637           <td>The request string as sent by the client, f.x. <code>GET /foo/bar HTTP/1.1</code>.</td>
638         </tr>
639 <tr class="odd">
640           <td><code>unparsed_uri</code></td>
641           <td>string</td>
642           <td>no</td>
643           <td>The unparsed URI of the request</td>
644         </tr>
645 <tr>
646           <td><code>uri</code></td>
647           <td>string</td>
648           <td>yes</td>
649           <td>The URI after it has been parsed by httpd</td>
650         </tr>
651 <tr class="odd">
652           <td><code>user</code></td>
653           <td>string</td>
654           <td>yes</td>
655           <td>If an authentication check has been made, this is set to the name of the authenticated user.</td>
656         </tr>
657 <tr>
658           <td><code>useragent_ip</code></td>
659           <td>string</td>
660           <td>no</td>
661           <td>The IP of the user agent making the request</td>
662         </tr>
663 </table>
664            </dd>
665     </dl>
666 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
667 <div class="section">
668 <h2><a name="functions" id="functions">Built in functions</a></h2>
669
670 <p>The request_rec object has (at least) the following methods:</p>
671
672 <pre class="prettyprint lang-lua">
673 r:flush()   -- flushes the output buffer.
674             -- Returns true if the flush was successful, false otherwise.
675
676 while we_have_stuff_to_send do
677     r:puts("Bla bla bla\n") -- print something to client
678     r:flush() -- flush the buffer (send to client)
679     r.usleep(500000) -- fake processing time for 0.5 sec. and repeat
680 end
681 </pre>
682
683
684 <pre class="prettyprint lang-lua">
685 r:addoutputfilter(name|function) -- add an output filter:
686
687 r:addoutputfilter("fooFilter") -- add the fooFilter to the output stream
688 </pre>
689
690
691 <pre class="prettyprint lang-lua">
692 r:sendfile(filename) -- sends an entire file to the client, using sendfile if supported by the current platform:
693
694 if use_sendfile_thing then
695     r:sendfile("/var/www/large_file.img")
696 end
697 </pre>
698
699
700 <pre class="prettyprint lang-lua">
701 r:parseargs() -- returns two tables; one standard key/value table for regular GET data, 
702               -- and one for multi-value data (fx. foo=1&amp;foo=2&amp;foo=3):
703
704 local GET, GETMULTI = r:parseargs()
705 r:puts("Your name is: " .. GET['name'] or "Unknown")
706 </pre>
707
708
709 <pre class="prettyprint lang-lua">
710 r:parsebody([sizeLimit]) -- parse the request body as a POST and return two lua tables,
711                          -- just like r:parseargs().
712                          -- An optional number may be passed to specify the maximum number 
713                          -- of bytes to parse. Default is 8192 bytes:
714                  
715 local POST, POSTMULTI = r:parsebody(1024*1024)
716 r:puts("Your name is: " .. POST['name'] or "Unknown")
717 </pre>
718
719
720 <pre class="prettyprint lang-lua">
721 r:puts("hello", " world", "!") -- print to response body, self explanatory
722 </pre>
723
724
725 <pre class="prettyprint lang-lua">
726 r:write("a single string") -- print to response body, self explanatory
727 </pre>
728
729
730 <pre class="prettyprint lang-lua">
731 r:escape_html("&lt;html&gt;test&lt;/html&gt;") -- Escapes HTML code and returns the escaped result
732 </pre>
733
734
735 <pre class="prettyprint lang-lua">
736 r:base64_encode(string) -- Encodes a string using the Base64 encoding standard:
737
738 local encoded = r:base64_encode("This is a test") -- returns VGhpcyBpcyBhIHRlc3Q=
739 </pre>
740
741
742 <pre class="prettyprint lang-lua">
743 r:base64_decode(string) -- Decodes a Base64-encoded string:
744
745 local decoded = r:base64_decode("VGhpcyBpcyBhIHRlc3Q=") -- returns 'This is a test'
746 </pre>
747
748
749 <pre class="prettyprint lang-lua">
750 r:md5(string) -- Calculates and returns the MD5 digest of a string (binary safe):
751
752 local hash = r:md5("This is a test") -- returns ce114e4501d2f4e2dcea3e17b546f339
753 </pre>
754
755
756 <pre class="prettyprint lang-lua">
757 r:sha1(string) -- Calculates and returns the SHA1 digest of a string (binary safe):
758
759 local hash = r:sha1("This is a test") -- returns a54d88e06612d820bc3be72877c74f257b561b19
760 </pre>
761
762
763 <pre class="prettyprint lang-lua">
764 r:escape(string) -- URL-Escapes a string:
765
766 local url = "http://foo.bar/1 2 3 &amp; 4 + 5"
767 local escaped = r:escape(url) -- returns 'http%3a%2f%2ffoo.bar%2f1+2+3+%26+4+%2b+5'
768 </pre>
769
770
771 <pre class="prettyprint lang-lua">
772 r:unescape(string) -- Unescapes an URL-escaped string:
773
774 local url = "http%3a%2f%2ffoo.bar%2f1+2+3+%26+4+%2b+5"
775 local unescaped = r:unescape(url) -- returns 'http://foo.bar/1 2 3 &amp; 4 + 5'
776 </pre>
777
778
779 <pre class="prettyprint lang-lua">
780 r:construct_url(string) -- Constructs an URL from an URI
781
782 local url = r:construct_url(r.uri) 
783 </pre>
784
785
786 <pre class="prettyprint lang-lua">
787 r.mpm_query(number) -- Queries the server for MPM information using ap_mpm_query:
788
789 local mpm = r.mpm_query(14)
790 if mpm == 1 then
791     r:puts("This server uses the Event MPM")
792 end
793 </pre>
794
795
796 <pre class="prettyprint lang-lua">
797 r:expr(string) -- Evaluates an <a href="../expr.html">expr</a> string.
798
799 if r:expr("%{HTTP_HOST} =~ /^www/") then
800     r:puts("This host name starts with www")
801 end
802 </pre>
803
804
805 <pre class="prettyprint lang-lua">
806 r:scoreboard_process(a) -- Queries the server for information about the process at position <code>a</code>:
807
808 local process = r:scoreboard_process(1)
809 r:puts("Server 1 has PID " .. process.pid)
810 </pre>
811
812
813 <pre class="prettyprint lang-lua">
814 r:scoreboard_worker(a, b) -- Queries for information about the worker thread, <code>b</code>, in process <code>a</code>:
815
816 local thread = r:scoreboard_worker(1, 1)
817 r:puts("Server 1's thread 1 has thread ID " .. thread.tid .. " and is in " .. thread.status .. " status")
818 </pre>
819
820
821
822 <pre class="prettyprint lang-lua">
823 r:clock() -- Returns the current time with microsecond precision
824 </pre>
825
826
827 <pre class="prettyprint lang-lua">
828 r:requestbody(filename) -- Reads and returns the request body of a request.
829                 -- If 'filename' is specified, it instead saves the
830                 -- contents to that file:
831                 
832 local input = r:requestbody()
833 r:puts("You sent the following request body to me:\n")
834 r:puts(input)
835 </pre>
836
837
838 <pre class="prettyprint lang-lua">
839 r:add_input_filter(filter_name) -- Adds 'filter_name' as an input filter
840 </pre>
841
842
843 <pre class="prettyprint lang-lua">
844 r.module_info(module_name) -- Queries the server for information about a module
845
846 local mod = r.module_info("mod_lua.c")
847 if mod then
848     for k, v in pairs(mod.commands) do
849        r:puts( ("%s: %s\n"):format(k,v)) -- print out all directives accepted by this module
850     end
851 end
852 </pre>
853
854
855 <pre class="prettyprint lang-lua">
856 r:loaded_modules() -- Returns a list of modules loaded by httpd:
857
858 for k, module in pairs(r:loaded_modules()) do
859     r:puts("I have loaded module " .. module .. "\n")
860 end
861 </pre>
862
863
864 <pre class="prettyprint lang-lua">
865 r:runtime_dir_relative(filename) -- Compute the name of a run-time file (e.g., shared memory "file") 
866                          -- relative to the appropriate run-time directory. 
867 </pre>
868
869
870 <pre class="prettyprint lang-lua">
871 r:server_info() -- Returns a table containing server information, such as 
872                 -- the name of the httpd executable file, mpm used etc.
873 </pre>
874
875
876 <pre class="prettyprint lang-lua">
877 r:set_document_root(file_path) -- Sets the document root for the request to file_path
878 </pre>
879
880
881
882
883 <pre class="prettyprint lang-lua">
884 r:set_context_info(prefix, docroot) -- Sets the context prefix and context document root for a request
885 </pre>
886
887
888 <pre class="prettyprint lang-lua">
889 r:os_escape_path(file_path) -- Converts an OS path to a URL in an OS dependent way
890 </pre>
891
892
893 <pre class="prettyprint lang-lua">
894 r:escape_logitem(string) -- Escapes a string for logging
895 </pre>
896
897
898 <pre class="prettyprint lang-lua">
899 r.strcmp_match(string, pattern) -- Checks if 'string' matches 'pattern' using strcmp_match (globs).
900                         -- fx. whether 'www.example.com' matches '*.example.com':
901                         
902 local match = r.strcmp_match("foobar.com", "foo*.com")
903 if match then 
904     r:puts("foobar.com matches foo*.com")
905 end
906 </pre>
907
908
909 <pre class="prettyprint lang-lua">
910 r:set_keepalive() -- Sets the keepalive status for a request. Returns true if possible, false otherwise.
911 </pre>
912
913
914 <pre class="prettyprint lang-lua">
915 r:make_etag() -- Constructs and returns the etag for the current request.
916 </pre>
917
918
919 <pre class="prettyprint lang-lua">
920 r:send_interim_response(clear) -- Sends an interim (1xx) response to the client.
921                        -- if 'clear' is true, available headers will be sent and cleared.
922 </pre>
923
924
925 <pre class="prettyprint lang-lua">
926 r:custom_response(status_code, string) -- Construct and set a custom response for a given status code.
927                                -- This works much like the ErrorDocument directive:
928                                
929 r:custom_response(404, "Baleted!")
930 </pre>
931
932
933 <pre class="prettyprint lang-lua">
934 r.exists_config_define(string) -- Checks whether a configuration definition exists or not:
935
936 if r.exists_config_define("FOO") then
937     r:puts("httpd was probably run with -DFOO, or it was defined in the configuration")
938 end
939 </pre>
940
941
942 <pre class="prettyprint lang-lua">
943 r:state_query(string) -- Queries the server for state information
944 </pre>
945
946
947 <pre class="prettyprint lang-lua">
948 r:stat(filename [,wanted]) -- Runs stat() on a file, and returns a table with file information:
949
950 local info = r:stat("/var/www/foo.txt")
951 if info then
952     r:puts("This file exists and was last modified at: " .. info.modified)
953 end
954 </pre>
955
956
957 <pre class="prettyprint lang-lua">
958 r:regex(string, pattern [,flags]) -- Runs a regular expression match on a string, returning captures if matched:
959
960 local matches = r:regex("foo bar baz", [[foo (\w+) (\S*)]])
961 if matches then
962     r:puts("The regex matched, and the last word captured ($2) was: " .. matches[2])
963 end
964
965 -- Example ignoring case sensitivity:
966 local matches = r:regex("FOO bar BAz", [[(foo) bar]], 1)
967
968 -- Flags can be a bitwise combination of:
969 -- 0x01: Ignore case
970 -- 0x02: Multiline search
971 </pre>
972
973
974 <pre class="prettyprint lang-lua">
975 r.usleep(number_of_microseconds) -- Puts the script to sleep for a given number of microseconds.
976 </pre>
977
978
979 <pre class="prettyprint lang-lua">
980 r:dbacquire(dbType[, dbParams]) -- Acquires a connection to a database and returns a database class.
981                         -- See '<a href="#databases">Database connectivity</a>' for details.
982 </pre>
983
984
985 <pre class="prettyprint lang-lua">
986 r:ivm_set("key", value) -- Set an Inter-VM variable to hold a specific value.
987                         -- These values persist even though the VM is gone or not being used,
988                         -- and so should only be used if MaxConnectionsPerChild is &gt; 0
989                         -- Values can be numbers, strings and booleans, and are stored on a 
990                         -- per process basis (so they won't do much good with a prefork mpm)
991                         
992 r:ivm_get("key")        -- Fetches a variable set by ivm_set. Returns the contents of the variable
993                         -- if it exists or nil if no such variable exists.
994                         
995 -- An example getter/setter that saves a global variable outside the VM:
996 function handle(r)
997     -- First VM to call this will get no value, and will have to create it
998     local foo = r:ivm_get("cached_data")
999     if not foo then
1000         foo = do_some_calcs() -- fake some return value
1001         r:ivm_set("cached_data", foo) -- set it globally
1002     end
1003     r:puts("Cached data is: ", foo)
1004 end
1005 </pre>
1006
1007
1008 <pre class="prettyprint lang-lua">
1009 r:htpassword(string [,algorithm [,cost]]) -- Creates a password hash from a string.
1010                                           -- algorithm: 0 = APMD5 (default), 1 = SHA, 2 = BCRYPT, 3 = CRYPT.
1011                                           -- cost: only valid with BCRYPT algorithm (default = 5).
1012 </pre>
1013
1014
1015 <pre class="prettyprint lang-lua">
1016 r:mkdir(dir [,mode]) -- Creates a directory and sets mode to optional mode paramter.
1017 </pre>
1018
1019
1020 <pre class="prettyprint lang-lua">
1021 r:mkrdir(dir [,mode]) -- Creates directories recursive and sets mode to optional mode paramter.
1022 </pre>
1023
1024
1025 <pre class="prettyprint lang-lua">
1026 r:rmdir(dir) -- Removes a directory.
1027 </pre>
1028
1029
1030 <pre class="prettyprint lang-lua">
1031 r:touch(file [,mtime]) -- Sets the file modification time to current time or to optional mtime msec value.
1032 </pre>
1033
1034
1035 <pre class="prettyprint lang-lua">
1036 r:get_direntries(dir) -- Returns a table with all directory entries.
1037
1038 function handle(r)
1039   local dir = r.context_document_root
1040   for _, f in ipairs(r:get_direntries(dir)) do
1041     local info = r:stat(dir .. "/" .. f)
1042     if info then
1043       local mtime = os.date(fmt, info.mtime / 1000000)
1044       local ftype = (info.filetype == 2) and "[dir] " or "[file]"
1045       r:puts( ("%s %s %10i %s\n"):format(ftype, mtime, info.size, f) )
1046     end
1047   end
1048 end
1049 </pre>
1050
1051
1052 <pre class="prettyprint lang-lua">
1053 r.date_parse_rfc(string) -- Parses a date/time string and returns seconds since epoche.
1054 </pre>
1055
1056
1057 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
1058 <div class="section">
1059 <h2><a name="logging" id="logging">Logging Functions</a></h2>
1060
1061 <pre class="prettyprint lang-lua">
1062         -- examples of logging messages<br />
1063         r:trace1("This is a trace log message") -- trace1 through trace8 can be used <br />
1064         r:debug("This is a debug log message")<br />
1065         r:info("This is an info log message")<br />
1066         r:notice("This is a notice log message")<br />
1067         r:warn("This is a warn log message")<br />
1068         r:err("This is an err log message")<br />
1069         r:alert("This is an alert log message")<br />
1070         r:crit("This is a crit log message")<br />
1071         r:emerg("This is an emerg log message")<br />
1072 </pre>
1073
1074
1075 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
1076 <div class="section">
1077 <h2><a name="apache2" id="apache2">apache2 Package</a></h2>
1078 <p>A package named <code>apache2</code> is available with (at least) the following contents.</p>
1079 <dl>
1080   <dt>apache2.OK</dt>
1081   <dd>internal constant OK.  Handlers should return this if they've
1082   handled the request.</dd>
1083   <dt>apache2.DECLINED</dt>
1084   <dd>internal constant DECLINED.  Handlers should return this if
1085   they are not going to handle the request.</dd>
1086   <dt>apache2.DONE</dt>
1087   <dd>internal constant DONE.</dd>
1088   <dt>apache2.version</dt>
1089   <dd>Apache HTTP server version string</dd>
1090   <dt>apache2.HTTP_MOVED_TEMPORARILY</dt>
1091   <dd>HTTP status code</dd>
1092   <dt>apache2.PROXYREQ_NONE, apache2.PROXYREQ_PROXY, apache2.PROXYREQ_REVERSE, apache2.PROXYREQ_RESPONSE</dt>
1093   <dd>internal constants used by <code class="module"><a href="../mod/mod_proxy.html">mod_proxy</a></code></dd>
1094   <dt>apache2.AUTHZ_DENIED, apache2.AUTHZ_GRANTED, apache2.AUTHZ_NEUTRAL, apache2.AUTHZ_GENERAL_ERROR, apache2.AUTHZ_DENIED_NO_USER</dt>
1095   <dd>internal constants used by <code class="module"><a href="../mod/mod_authz_core.html">mod_authz_core</a></code></dd>
1096
1097 </dl>
1098 <p>(Other HTTP status codes are not yet implemented.)</p>
1099 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
1100 <div class="section">
1101 <h2><a name="modifying_buckets" id="modifying_buckets">Modifying contents with Lua filters</a></h2>
1102     
1103     <p>
1104     Filter functions implemented via <code class="directive"><a href="#luainputfilter">LuaInputFilter</a></code> 
1105     or <code class="directive"><a href="#luaoutputfilter">LuaOutputFilter</a></code> are designed as 
1106     three-stage non-blocking functions using coroutines to suspend and resume a 
1107     function as buckets are sent down the filter chain. The core structure of 
1108     such a function is:
1109     </p>
1110     <pre class="prettyprint lang-lua">
1111 function filter(r)
1112     -- Our first yield is to signal that we are ready to receive buckets.
1113     -- Before this yield, we can set up our environment, check for conditions,
1114     -- and, if we deem it necessary, decline filtering a request alltogether:
1115     if something_bad then
1116         return -- This would skip this filter.
1117     end
1118     -- Regardless of whether we have data to prepend, a yield MUST be called here.
1119     -- Note that only output filters can prepend data. Input filters must use the 
1120     -- final stage to append data to the content.
1121     coroutine.yield([optional header to be prepended to the content])
1122     
1123     -- After we have yielded, buckets will be sent to us, one by one, and we can 
1124     -- do whatever we want with them and then pass on the result.
1125     -- Buckets are stored in the global variable 'bucket', so we create a loop
1126     -- that checks if 'bucket' is not nil:
1127     while bucket ~= nil do
1128         local output = mangle(bucket) -- Do some stuff to the content
1129         coroutine.yield(output) -- Return our new content to the filter chain
1130     end
1131
1132     -- Once the buckets are gone, 'bucket' is set to nil, which will exit the 
1133     -- loop and land us here. Anything extra we want to append to the content
1134     -- can be done by doing a final yield here. Both input and output filters 
1135     -- can append data to the content in this phase.
1136     coroutine.yield([optional footer to be appended to the content])
1137 end
1138     </pre>
1139
1140 </div><div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
1141 <div class="section">
1142 <h2><a name="databases" id="databases">Database connectivity</a></h2>
1143     
1144     <p>
1145     Mod_lua implements a simple database feature for querying and running commands
1146     on the most popular database engines (mySQL, PostgreSQL, FreeTDS, ODBC, SQLite, Oracle)
1147     as well as mod_dbd.
1148     </p>
1149     <p>The example below shows how to acquire a database handle and return information from a table:</p>
1150     <pre class="prettyprint lang-lua">
1151 function handle(r)
1152     -- Acquire a database handle
1153     local database, err = r:dbacquire("mysql", "server=localhost,user=root,dbname=mydb")
1154     if not err then
1155         -- Select some information from it
1156         local results, err = database:select(r, "SELECT `name`, `age` FROM `people` WHERE 1")
1157         if not err then
1158             local rows = results(0) -- fetch all rows synchronously
1159             for k, row in pairs(rows) do
1160                 r:puts( string.format("Name: %s, Age: %s&lt;br/&gt;", row[1], row[2]) )
1161             end
1162         else
1163             r:puts("Database query error: " .. err)
1164         end
1165         database:close()
1166     else
1167         r:puts("Could not connect to the database: " .. err)
1168     end
1169 end
1170     </pre>
1171
1172     <p>
1173     To utilize <code class="module"><a href="../mod/mod_dbd.html">mod_dbd</a></code>, specify <code>mod_dbd</code>
1174     as the database type, or leave the field blank:
1175     </p>
1176     <pre class="prettyprint lang-lua">
1177     local database = r:dbacquire("mod_dbd")
1178     </pre>
1179
1180     <h3><a name="database_object" id="database_object">Database object and contained functions</a></h3>
1181         
1182         <p>The database object returned by <code>dbacquire</code> has the following methods:</p>
1183         <p><strong>Normal select and query from a database:</strong></p>
1184     <pre class="prettyprint lang-lua">
1185 -- Run a statement and return the number of rows affected:
1186 local affected, errmsg = database:query(r, "DELETE FROM `tbl` WHERE 1")
1187
1188 -- Run a statement and return a result set that can be used synchronously or async:
1189 local result, errmsg = database:select(r, "SELECT * FROM `people` WHERE 1")
1190     </pre>
1191
1192         <p><strong>Using prepared statements (recommended):</strong></p>
1193     <pre class="prettyprint lang-lua">
1194 -- Create and run a prepared statement:
1195 local statement, errmsg = database:prepare(r, "DELETE FROM `tbl` WHERE `age` &gt; %u")
1196 if not errmsg then
1197     local result, errmsg = statement:query(20) -- run the statement with age &gt; 20
1198 end
1199
1200 -- Fetch a prepared statement from a DBDPrepareSQL directive:
1201 local statement, errmsg = database:prepared(r, "someTag")
1202 if not errmsg then
1203     local result, errmsg = statement:select("John Doe", 123) -- inject the values "John Doe" and 123 into the statement
1204 end
1205
1206 </pre>
1207
1208         <p><strong>Escaping values, closing databases etc:</strong></p>
1209     <pre class="prettyprint lang-lua">
1210 -- Escape a value for use in a statement:
1211 local escaped = database:escape(r, [["'|blabla]])
1212
1213 -- Close a database connection and free up handles:
1214 database:close()
1215
1216 -- Check whether a database connection is up and running:
1217 local connected = database:active()
1218     </pre>
1219
1220     
1221     <h3><a name="result_sets" id="result_sets">Working with result sets</a></h3>
1222     
1223     <p>The result set returned by <code>db:select</code> or by the prepared statement functions 
1224     created through <code>db:prepare</code> can be used to
1225     fetch rows synchronously or asynchronously, depending on the row number specified:<br />
1226     <code>result(0)</code> fetches all rows in a synchronous manner, returning a table of rows.<br />
1227     <code>result(-1)</code> fetches the next available row in the set, asynchronously.<br />
1228     <code>result(N)</code> fetches row number <code>N</code>, asynchronously:
1229     </p>
1230     <pre class="prettyprint lang-lua">
1231 -- fetch a result set using a regular query:
1232 local result, err = db:select(r, "SELECT * FROM `tbl` WHERE 1")
1233
1234 local rows = result(0) -- Fetch ALL rows synchronously
1235 local row = result(-1) -- Fetch the next available row, asynchronously
1236 local row = result(1234) -- Fetch row number 1234, asynchronously
1237     </pre>
1238
1239     <p>One can construct a function that returns an iterative function to iterate over all rows 
1240     in a synchronous or asynchronous way, depending on the async argument:
1241     </p>
1242     <pre class="prettyprint lang-lua">
1243 function rows(resultset, async)
1244     local a = 0
1245     local function getnext()
1246         a = a + 1
1247         local row = resultset(-1)
1248         return row and a or nil, row
1249     end
1250     if not async then
1251         return pairs(resultset(0))
1252     else
1253         return getnext, self
1254     end
1255 end
1256
1257 local statement, err = db:prepare(r, "SELECT * FROM `tbl` WHERE `age` &gt; %u")
1258 if not err then
1259      -- fetch rows asynchronously:
1260     local result, err = statement:select(20)
1261     if not err then
1262         for index, row in rows(result, true) do
1263             ....
1264         end
1265     end
1266
1267      -- fetch rows synchronously:
1268     local result, err = statement:select(20)
1269     if not err then
1270         for index, row in rows(result, false) do
1271             ....
1272         end
1273     end
1274 end
1275     </pre>
1276
1277     
1278     <h3><a name="closing_databases" id="closing_databases">Closing a database connection</a></h3>
1279         
1280
1281     <p>Database handles should be closed using <code>database:close()</code> when they are no longer
1282     needed. If you do not close them manually, they will eventually be garbage collected and 
1283     closed by mod_lua, but you may end up having too many unused connections to the database 
1284     if you leave the closing up to mod_lua. Essentially, the following two measures are
1285     the same:
1286     </p>
1287     <pre class="prettyprint lang-lua">
1288 -- Method 1: Manually close a handle
1289 local database = r:dbacquire("mod_dbd")
1290 database:close() -- All done
1291
1292 -- Method 2: Letting the garbage collector close it
1293 local database = r:dbacquire("mod_dbd")
1294 database = nil -- throw away the reference
1295 collectgarbage() -- close the handle via GC
1296 </pre>
1297
1298     
1299     <h3><a name="database_caveat" id="database_caveat">Precautions when working with databases</a></h3>
1300     
1301     <p>Although the standard <code>query</code> and <code>run</code> functions are freely 
1302     available, it is recommended that you use prepared statements whenever possible, to 
1303     both optimize performance (if your db handle lives on for a long time) and to minimize 
1304     the risk of SQL injection attacks. <code>run</code> and <code>query</code> should only
1305     be used when there are no variables inserted into a statement (a static statement). 
1306     When using dynamic statements, use <code>db:prepare</code> or <code>db:prepared</code>.
1307     </p>
1308     
1309
1310 </div>
1311 <div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
1312 <div class="directive-section"><h2><a name="LuaAuthzProvider" id="LuaAuthzProvider">LuaAuthzProvider</a> <a name="luaauthzprovider" id="luaauthzprovider">Directive</a></h2>
1313 <table class="directive">
1314 <tr><th><a href="directive-dict.html#Description">Description:</a></th><td>Plug an authorization provider function into <code class="module"><a href="../mod/mod_authz_core.html">mod_authz_core</a></code>
1315 </td></tr>
1316 <tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code>LuaAuthzProvider provider_name /path/to/lua/script.lua function_name</code></td></tr>
1317 <tr><th><a href="directive-dict.html#Context">Context:</a></th><td>server config</td></tr>
1318 <tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Experimental</td></tr>
1319 <tr><th><a href="directive-dict.html#Module">Module:</a></th><td>mod_lua</td></tr>
1320 <tr><th><a href="directive-dict.html#Compatibility">Compatibility:</a></th><td>2.4.3 and later</td></tr>
1321 </table>
1322 <p>After a lua function has been registered as authorization provider, it can be used
1323 with the <code class="directive"><a href="../mod/mod_authz_core.html#require">Require</a></code> directive:</p>
1324
1325 <pre class="prettyprint lang-config">
1326 LuaRoot /usr/local/apache2/lua
1327 LuaAuthzProvider foo authz.lua authz_check_foo
1328 &lt;Location /&gt;
1329   Require foo johndoe
1330 &lt;/Location&gt;
1331 </pre>
1332
1333 <pre class="prettyprint lang-lua">
1334 require "apache2"
1335 function authz_check_foo(r, who)
1336     if r.user ~= who then return apache2.AUTHZ_DENIED
1337     return apache2.AUTHZ_GRANTED
1338 end
1339 </pre>
1340
1341
1342
1343
1344 </div>
1345 <div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
1346 <div class="directive-section"><h2><a name="LuaCodeCache" id="LuaCodeCache">LuaCodeCache</a> <a name="luacodecache" id="luacodecache">Directive</a></h2>
1347 <table class="directive">
1348 <tr><th><a href="directive-dict.html#Description">Description:</a></th><td>Configure the compiled code cache.</td></tr>
1349 <tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code>LuaCodeCache stat|forever|never</code></td></tr>
1350 <tr><th><a href="directive-dict.html#Default">Default:</a></th><td><code>LuaCodeCache stat</code></td></tr>
1351 <tr><th><a href="directive-dict.html#Context">Context:</a></th><td>server config, virtual host, directory, .htaccess</td></tr>
1352 <tr><th><a href="directive-dict.html#Override">Override:</a></th><td>All</td></tr>
1353 <tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Experimental</td></tr>
1354 <tr><th><a href="directive-dict.html#Module">Module:</a></th><td>mod_lua</td></tr>
1355 </table><p>
1356     Specify the behavior of the in-memory code cache. The default
1357     is stat, which stats the top level script (not any included
1358     ones) each time that file is needed, and reloads it if the
1359     modified time indicates it is newer than the one it has
1360     already loaded. The other values cause it to keep the file
1361     cached forever (don't stat and replace) or to never cache the
1362     file.</p>
1363
1364     <p>In general stat or forever is good for production, and stat or never
1365     for development.</p>
1366
1367     <div class="example"><h3>Examples:</h3><pre class="prettyprint lang-config">
1368 LuaCodeCache stat
1369 LuaCodeCache forever
1370 LuaCodeCache never
1371     </pre>
1372 </div>
1373
1374
1375 </div>
1376 <div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
1377 <div class="directive-section"><h2><a name="LuaHookAccessChecker" id="LuaHookAccessChecker">LuaHookAccessChecker</a> <a name="luahookaccesschecker" id="luahookaccesschecker">Directive</a></h2>
1378 <table class="directive">
1379 <tr><th><a href="directive-dict.html#Description">Description:</a></th><td>Provide a hook for the access_checker phase of request processing</td></tr>
1380 <tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code>LuaHookAccessChecker  /path/to/lua/script.lua  hook_function_name [early|late]</code></td></tr>
1381 <tr><th><a href="directive-dict.html#Context">Context:</a></th><td>server config, virtual host, directory, .htaccess</td></tr>
1382 <tr><th><a href="directive-dict.html#Override">Override:</a></th><td>All</td></tr>
1383 <tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Experimental</td></tr>
1384 <tr><th><a href="directive-dict.html#Module">Module:</a></th><td>mod_lua</td></tr>
1385 <tr><th><a href="directive-dict.html#Compatibility">Compatibility:</a></th><td>The optional third argument is supported in 2.3.15 and later</td></tr>
1386 </table>
1387 <p>Add your hook to the access_checker phase.  An access checker
1388 hook function usually returns OK, DECLINED, or HTTP_FORBIDDEN.</p>
1389    <div class="note"><h3>Ordering</h3><p>The optional arguments "early" or "late" 
1390    control when this script runs relative to other modules.</p></div>
1391
1392 </div>
1393 <div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
1394 <div class="directive-section"><h2><a name="LuaHookAuthChecker" id="LuaHookAuthChecker">LuaHookAuthChecker</a> <a name="luahookauthchecker" id="luahookauthchecker">Directive</a></h2>
1395 <table class="directive">
1396 <tr><th><a href="directive-dict.html#Description">Description:</a></th><td>Provide a hook for the auth_checker phase of request processing</td></tr>
1397 <tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code>LuaHookAuthChecker  /path/to/lua/script.lua hook_function_name [early|late]</code></td></tr>
1398 <tr><th><a href="directive-dict.html#Context">Context:</a></th><td>server config, virtual host, directory, .htaccess</td></tr>
1399 <tr><th><a href="directive-dict.html#Override">Override:</a></th><td>All</td></tr>
1400 <tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Experimental</td></tr>
1401 <tr><th><a href="directive-dict.html#Module">Module:</a></th><td>mod_lua</td></tr>
1402 <tr><th><a href="directive-dict.html#Compatibility">Compatibility:</a></th><td>The optional third argument is supported in 2.3.15 and later</td></tr>
1403 </table>
1404 <p>Invoke a lua function in the auth_checker phase of processing
1405 a request.  This can be used to implement arbitrary authentication
1406 and authorization checking.  A very simple example:
1407 </p>
1408 <pre class="prettyprint lang-lua">
1409 require 'apache2'
1410
1411 -- fake authcheck hook
1412 -- If request has no auth info, set the response header and
1413 -- return a 401 to ask the browser for basic auth info.
1414 -- If request has auth info, don't actually look at it, just
1415 -- pretend we got userid 'foo' and validated it.
1416 -- Then check if the userid is 'foo' and accept the request.
1417 function authcheck_hook(r)
1418
1419    -- look for auth info
1420    auth = r.headers_in['Authorization']
1421    if auth ~= nil then
1422      -- fake the user
1423      r.user = 'foo'
1424    end
1425
1426    if r.user == nil then
1427       r:debug("authcheck: user is nil, returning 401")
1428       r.err_headers_out['WWW-Authenticate'] = 'Basic realm="WallyWorld"'
1429       return 401
1430    elseif r.user == "foo" then
1431       r:debug('user foo: OK')
1432    else
1433       r:debug("authcheck: user='" .. r.user .. "'")
1434       r.err_headers_out['WWW-Authenticate'] = 'Basic realm="WallyWorld"'
1435       return 401
1436    end
1437    return apache2.OK
1438 end
1439 </pre>
1440
1441    <div class="note"><h3>Ordering</h3><p>The optional arguments "early" or "late" 
1442    control when this script runs relative to other modules.</p></div>
1443
1444 </div>
1445 <div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
1446 <div class="directive-section"><h2><a name="LuaHookCheckUserID" id="LuaHookCheckUserID">LuaHookCheckUserID</a> <a name="luahookcheckuserid" id="luahookcheckuserid">Directive</a></h2>
1447 <table class="directive">
1448 <tr><th><a href="directive-dict.html#Description">Description:</a></th><td>Provide a hook for the check_user_id phase of request processing</td></tr>
1449 <tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code>LuaHookCheckUserID  /path/to/lua/script.lua hook_function_name [early|late]</code></td></tr>
1450 <tr><th><a href="directive-dict.html#Context">Context:</a></th><td>server config, virtual host, directory, .htaccess</td></tr>
1451 <tr><th><a href="directive-dict.html#Override">Override:</a></th><td>All</td></tr>
1452 <tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Experimental</td></tr>
1453 <tr><th><a href="directive-dict.html#Module">Module:</a></th><td>mod_lua</td></tr>
1454 <tr><th><a href="directive-dict.html#Compatibility">Compatibility:</a></th><td>The optional third argument is supported in 2.3.15 and later</td></tr>
1455 </table><p>...</p>
1456    <div class="note"><h3>Ordering</h3><p>The optional arguments "early" or "late" 
1457    control when this script runs relative to other modules.</p></div>
1458
1459 </div>
1460 <div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
1461 <div class="directive-section"><h2><a name="LuaHookFixups" id="LuaHookFixups">LuaHookFixups</a> <a name="luahookfixups" id="luahookfixups">Directive</a></h2>
1462 <table class="directive">
1463 <tr><th><a href="directive-dict.html#Description">Description:</a></th><td>Provide a hook for the fixups phase of a request
1464 processing</td></tr>
1465 <tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code>LuaHookFixups  /path/to/lua/script.lua hook_function_name</code></td></tr>
1466 <tr><th><a href="directive-dict.html#Context">Context:</a></th><td>server config, virtual host, directory, .htaccess</td></tr>
1467 <tr><th><a href="directive-dict.html#Override">Override:</a></th><td>All</td></tr>
1468 <tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Experimental</td></tr>
1469 <tr><th><a href="directive-dict.html#Module">Module:</a></th><td>mod_lua</td></tr>
1470 </table>
1471 <p>
1472     Just like LuaHookTranslateName, but executed at the fixups phase
1473 </p>
1474
1475 </div>
1476 <div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
1477 <div class="directive-section"><h2><a name="LuaHookInsertFilter" id="LuaHookInsertFilter">LuaHookInsertFilter</a> <a name="luahookinsertfilter" id="luahookinsertfilter">Directive</a></h2>
1478 <table class="directive">
1479 <tr><th><a href="directive-dict.html#Description">Description:</a></th><td>Provide a hook for the insert_filter phase of request processing</td></tr>
1480 <tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code>LuaHookInsertFilter  /path/to/lua/script.lua hook_function_name</code></td></tr>
1481 <tr><th><a href="directive-dict.html#Context">Context:</a></th><td>server config, virtual host, directory, .htaccess</td></tr>
1482 <tr><th><a href="directive-dict.html#Override">Override:</a></th><td>All</td></tr>
1483 <tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Experimental</td></tr>
1484 <tr><th><a href="directive-dict.html#Module">Module:</a></th><td>mod_lua</td></tr>
1485 </table><p>Not Yet Implemented</p>
1486 </div>
1487 <div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
1488 <div class="directive-section"><h2><a name="LuaHookLog" id="LuaHookLog">LuaHookLog</a> <a name="luahooklog" id="luahooklog">Directive</a></h2>
1489 <table class="directive">
1490 <tr><th><a href="directive-dict.html#Description">Description:</a></th><td>Provide a hook for the access log phase of a request
1491 processing</td></tr>
1492 <tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code>LuaHookLog  /path/to/lua/script.lua log_function_name</code></td></tr>
1493 <tr><th><a href="directive-dict.html#Context">Context:</a></th><td>server config, virtual host, directory, .htaccess</td></tr>
1494 <tr><th><a href="directive-dict.html#Override">Override:</a></th><td>All</td></tr>
1495 <tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Experimental</td></tr>
1496 <tr><th><a href="directive-dict.html#Module">Module:</a></th><td>mod_lua</td></tr>
1497 </table>
1498 <p>
1499     This simple logging hook allows you to run a function when httpd enters the 
1500     logging phase of a request. With it, you can append data to your own logs, 
1501     manipulate data before the regular log is written, or prevent a log entry 
1502     from being created. To prevent the usual logging from happening, simply return
1503     <code>apache2.DONE</code> in your logging handler, otherwise return 
1504     <code>apache2.OK</code> to tell httpd to log as normal.
1505 </p>
1506 <p>Example:</p>
1507 <pre class="prettyprint lang-config">
1508 LuaHookLog /path/to/script.lua logger
1509 </pre>
1510
1511 <pre class="prettyprint lang-lua">
1512 -- /path/to/script.lua --
1513 function logger(r)
1514     -- flip a coin:
1515     -- If 1, then we write to our own Lua log and tell httpd not to log
1516     -- in the main log.
1517     -- If 2, then we just sanitize the output a bit and tell httpd to 
1518     -- log the sanitized bits.
1519
1520     if math.random(1,2) == 1 then
1521         -- Log stuff ourselves and don't log in the regular log
1522         local f = io.open("/foo/secret.log", "a")
1523         if f then
1524             f:write("Something secret happened at " .. r.uri .. "\n")
1525             f:close()
1526         end
1527         return apache2.DONE -- Tell httpd not to use the regular logging functions
1528     else
1529         r.uri = r.uri:gsub("somesecretstuff", "") -- sanitize the URI
1530         return apache2.OK -- tell httpd to log it.
1531     end
1532 end
1533 </pre>
1534
1535
1536 </div>
1537 <div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
1538 <div class="directive-section"><h2><a name="LuaHookMapToStorage" id="LuaHookMapToStorage">LuaHookMapToStorage</a> <a name="luahookmaptostorage" id="luahookmaptostorage">Directive</a></h2>
1539 <table class="directive">
1540 <tr><th><a href="directive-dict.html#Description">Description:</a></th><td>Provide a hook for the map_to_storage phase of request processing</td></tr>
1541 <tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code>LuaHookMapToStorage  /path/to/lua/script.lua hook_function_name</code></td></tr>
1542 <tr><th><a href="directive-dict.html#Context">Context:</a></th><td>server config, virtual host, directory, .htaccess</td></tr>
1543 <tr><th><a href="directive-dict.html#Override">Override:</a></th><td>All</td></tr>
1544 <tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Experimental</td></tr>
1545 <tr><th><a href="directive-dict.html#Module">Module:</a></th><td>mod_lua</td></tr>
1546 </table>
1547     <p>Like <code class="directive">LuaHookTranslateName</code> but executed at the 
1548     map-to-storage phase of a request. Modules like mod_cache run at this phase,
1549     which makes for an interesting example on what to do here:</p>
1550     <pre class="prettyprint lang-config">
1551     LuaHookMapToStorage /path/to/lua/script.lua check_cache
1552     </pre>
1553
1554     <pre class="prettyprint lang-lua">
1555 require"apache2"
1556 cached_files = {}
1557
1558 function read_file(filename) 
1559     local input = io.open(filename, "r")
1560     if input then
1561         local data = input:read("*a")
1562         cached_files[filename] = data
1563         file = cached_files[filename]
1564         input:close()
1565     end
1566     return cached_files[filename]
1567 end
1568
1569 function check_cache(r)
1570     if r.filename:match("%.png$") then -- Only match PNG files
1571         local file = cached_files[r.filename] -- Check cache entries
1572         if not file then
1573             file = read_file(r.filename)  -- Read file into cache
1574         end
1575         if file then -- If file exists, write it out
1576             r.status = 200
1577             r:write(file)
1578             r:info(("Sent %s to client from cache"):format(r.filename))
1579             return apache2.DONE -- skip default handler for PNG files
1580         end
1581     end
1582     return apache2.DECLINED -- If we had nothing to do, let others serve this.
1583 end
1584     </pre>
1585
1586
1587     
1588 </div>
1589 <div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
1590 <div class="directive-section"><h2><a name="LuaHookTranslateName" id="LuaHookTranslateName">LuaHookTranslateName</a> <a name="luahooktranslatename" id="luahooktranslatename">Directive</a></h2>
1591 <table class="directive">
1592 <tr><th><a href="directive-dict.html#Description">Description:</a></th><td>Provide a hook for the translate name phase of request processing</td></tr>
1593 <tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code>LuaHookTranslateName  /path/to/lua/script.lua  hook_function_name [early|late]</code></td></tr>
1594 <tr><th><a href="directive-dict.html#Context">Context:</a></th><td>server config, virtual host</td></tr>
1595 <tr><th><a href="directive-dict.html#Override">Override:</a></th><td>All</td></tr>
1596 <tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Experimental</td></tr>
1597 <tr><th><a href="directive-dict.html#Module">Module:</a></th><td>mod_lua</td></tr>
1598 <tr><th><a href="directive-dict.html#Compatibility">Compatibility:</a></th><td>The optional third argument is supported in 2.3.15 and later</td></tr>
1599 </table><p>
1600     Add a hook (at APR_HOOK_MIDDLE) to the translate name phase of
1601     request processing. The hook function receives a single
1602     argument, the request_rec, and should return a status code,
1603     which is either an HTTP error code, or the constants defined
1604     in the apache2 module: apache2.OK, apache2.DECLINED, or
1605     apache2.DONE. </p>
1606
1607     <p>For those new to hooks, basically each hook will be invoked
1608     until one of them returns apache2.OK. If your hook doesn't
1609     want to do the translation it should just return
1610     apache2.DECLINED. If the request should stop processing, then
1611     return apache2.DONE.</p>
1612
1613     <p>Example:</p>
1614
1615 <pre class="prettyprint lang-config">
1616 # httpd.conf
1617 LuaHookTranslateName /scripts/conf/hooks.lua silly_mapper
1618 </pre>
1619
1620
1621 <pre class="prettyprint lang-lua">
1622 -- /scripts/conf/hooks.lua --
1623 require "apache2"
1624 function silly_mapper(r)
1625     if r.uri == "/" then
1626         r.filename = "/var/www/home.lua"
1627         return apache2.OK
1628     else
1629         return apache2.DECLINED
1630     end
1631 end
1632 </pre>
1633
1634
1635    <div class="note"><h3>Context</h3><p>This directive is not valid in <code class="directive"><a href="../mod/core.html#directory">&lt;Directory&gt;</a></code>, <code class="directive"><a href="../mod/core.html#files">&lt;Files&gt;</a></code>, or htaccess
1636    context.</p></div>
1637
1638    <div class="note"><h3>Ordering</h3><p>The optional arguments "early" or "late" 
1639    control when this script runs relative to other modules.</p></div>
1640
1641
1642 </div>
1643 <div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
1644 <div class="directive-section"><h2><a name="LuaHookTypeChecker" id="LuaHookTypeChecker">LuaHookTypeChecker</a> <a name="luahooktypechecker" id="luahooktypechecker">Directive</a></h2>
1645 <table class="directive">
1646 <tr><th><a href="directive-dict.html#Description">Description:</a></th><td>Provide a hook for the type_checker phase of request processing</td></tr>
1647 <tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code>LuaHookTypeChecker  /path/to/lua/script.lua hook_function_name</code></td></tr>
1648 <tr><th><a href="directive-dict.html#Context">Context:</a></th><td>server config, virtual host, directory, .htaccess</td></tr>
1649 <tr><th><a href="directive-dict.html#Override">Override:</a></th><td>All</td></tr>
1650 <tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Experimental</td></tr>
1651 <tr><th><a href="directive-dict.html#Module">Module:</a></th><td>mod_lua</td></tr>
1652 </table><p>
1653     This directive provides a hook for the type_checker phase of the request processing. 
1654     This phase is where requests are assigned a content type and a handler, and thus can 
1655     be used to modify the type and handler based on input:
1656     </p>
1657     <pre class="prettyprint lang-config">
1658     LuaHookTypeChecker /path/to/lua/script.lua type_checker
1659     </pre>
1660
1661     <pre class="prettyprint lang-lua">
1662     function type_checker(r)
1663         if r.uri:match("%.to_gif$") then -- match foo.png.to_gif
1664             r.content_type = "image/gif" -- assign it the image/gif type
1665             r.handler = "gifWizard"      -- tell the gifWizard module to handle this
1666             r.filename = r.uri:gsub("%.to_gif$", "") -- fix the filename requested
1667             return apache2.OK
1668         end
1669
1670         return apache2.DECLINED
1671     end
1672     </pre>
1673
1674
1675 </div>
1676 <div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
1677 <div class="directive-section"><h2><a name="LuaInherit" id="LuaInherit">LuaInherit</a> <a name="luainherit" id="luainherit">Directive</a></h2>
1678 <table class="directive">
1679 <tr><th><a href="directive-dict.html#Description">Description:</a></th><td>Controls how parent configuration sections are merged into children</td></tr>
1680 <tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code>LuaInherit none|parent-first|parent-last</code></td></tr>
1681 <tr><th><a href="directive-dict.html#Default">Default:</a></th><td><code>LuaInherit parent-first</code></td></tr>
1682 <tr><th><a href="directive-dict.html#Context">Context:</a></th><td>server config, virtual host, directory, .htaccess</td></tr>
1683 <tr><th><a href="directive-dict.html#Override">Override:</a></th><td>All</td></tr>
1684 <tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Experimental</td></tr>
1685 <tr><th><a href="directive-dict.html#Module">Module:</a></th><td>mod_lua</td></tr>
1686 <tr><th><a href="directive-dict.html#Compatibility">Compatibility:</a></th><td>2.4.0 and later</td></tr>
1687 </table><p>By default, if LuaHook* directives are used in overlapping
1688     Directory or Location configuration sections, the scripts defined in the
1689     more specific section are run <em>after</em> those defined in the more
1690     generic section (LuaInherit parent-first).  You can reverse this order, or
1691     make the parent context not apply at all.</p>
1692     
1693     <p> In previous 2.3.x releases, the default was effectively to ignore LuaHook*
1694     directives from parent configuration sections.</p>
1695 </div>
1696 <div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
1697 <div class="directive-section"><h2><a name="LuaInputFilter" id="LuaInputFilter">LuaInputFilter</a> <a name="luainputfilter" id="luainputfilter">Directive</a></h2>
1698 <table class="directive">
1699 <tr><th><a href="directive-dict.html#Description">Description:</a></th><td>Provide a Lua function for content input filtering</td></tr>
1700 <tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code>LuaInputFilter filter_name /path/to/lua/script.lua function_name</code></td></tr>
1701 <tr><th><a href="directive-dict.html#Context">Context:</a></th><td>server config</td></tr>
1702 <tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Experimental</td></tr>
1703 <tr><th><a href="directive-dict.html#Module">Module:</a></th><td>mod_lua</td></tr>
1704 <tr><th><a href="directive-dict.html#Compatibility">Compatibility:</a></th><td>2.5.0 and later</td></tr>
1705 </table>
1706 <p>Provides a means of adding a Lua function as an input filter. 
1707 As with output filters, input filters work as coroutines, 
1708 first yielding before buffers are sent, then yielding whenever 
1709 a bucket needs to be passed down the chain, and finally (optionally) 
1710 yielding anything that needs to be appended to the input data. The 
1711 global variable <code>bucket</code> holds the buckets as they are passed 
1712 onto the Lua script:
1713 </p>
1714
1715 <pre class="prettyprint lang-config">
1716 LuaInputFilter myInputFilter /www/filter.lua input_filter
1717 &lt;FilesMatch "\.lua&gt;
1718   SetInputFilter myInputFilter
1719 &lt;/FilesMatch&gt;
1720 </pre>
1721
1722 <pre class="prettyprint lang-lua">
1723 --[[
1724     Example input filter that converts all POST data to uppercase.
1725 ]]--
1726 function input_filter(r)
1727     print("luaInputFilter called") -- debug print
1728     coroutine.yield() -- Yield and wait for buckets
1729     while bucket do -- For each bucket, do...
1730         local output = string.upper(bucket) -- Convert all POST data to uppercase
1731         coroutine.yield(output) -- Send converted data down the chain
1732     end
1733     -- No more buckets available.
1734     coroutine.yield("&amp;filterSignature=1234") -- Append signature at the end
1735 end
1736 </pre>
1737
1738 <p>
1739 The input filter supports denying/skipping a filter if it is deemed unwanted:
1740 </p>
1741 <pre class="prettyprint lang-lua">
1742 function input_filter(r)
1743     if not good then
1744         return -- Simply deny filtering, passing on the original content instead
1745     end
1746     coroutine.yield() -- wait for buckets
1747     ... -- insert filter stuff here
1748 end
1749 </pre>
1750
1751 <p>
1752 See "<a href="#modifying_buckets">Modifying contents with Lua 
1753 filters</a>" for more information.
1754 </p>
1755
1756 </div>
1757 <div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
1758 <div class="directive-section"><h2><a name="LuaMapHandler" id="LuaMapHandler">LuaMapHandler</a> <a name="luamaphandler" id="luamaphandler">Directive</a></h2>
1759 <table class="directive">
1760 <tr><th><a href="directive-dict.html#Description">Description:</a></th><td>Map a path to a lua handler</td></tr>
1761 <tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code>LuaMapHandler uri-pattern /path/to/lua/script.lua [function-name]</code></td></tr>
1762 <tr><th><a href="directive-dict.html#Context">Context:</a></th><td>server config, virtual host, directory, .htaccess</td></tr>
1763 <tr><th><a href="directive-dict.html#Override">Override:</a></th><td>All</td></tr>
1764 <tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Experimental</td></tr>
1765 <tr><th><a href="directive-dict.html#Module">Module:</a></th><td>mod_lua</td></tr>
1766 </table>
1767     <p>This directive matches a uri pattern to invoke a specific
1768     handler function in a specific file. It uses PCRE regular
1769     expressions to match the uri, and supports interpolating
1770     match groups into both the file path and the function name. 
1771     Be careful writing your regular expressions to avoid security
1772     issues.</p>
1773    <div class="example"><h3>Examples:</h3><pre class="prettyprint lang-config">
1774     LuaMapHandler /(\w+)/(\w+) /scripts/$1.lua handle_$2
1775     </pre>
1776 </div>
1777         <p>This would match uri's such as /photos/show?id=9
1778         to the file /scripts/photos.lua and invoke the
1779         handler function handle_show on the lua vm after
1780         loading that file.</p>
1781
1782 <pre class="prettyprint lang-config">
1783     LuaMapHandler /bingo /scripts/wombat.lua
1784 </pre>
1785
1786         <p>This would invoke the "handle" function, which
1787         is the default if no specific function name is
1788         provided.</p>
1789
1790 </div>
1791 <div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
1792 <div class="directive-section"><h2><a name="LuaOutputFilter" id="LuaOutputFilter">LuaOutputFilter</a> <a name="luaoutputfilter" id="luaoutputfilter">Directive</a></h2>
1793 <table class="directive">
1794 <tr><th><a href="directive-dict.html#Description">Description:</a></th><td>Provide a Lua function for content output filtering</td></tr>
1795 <tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code>LuaOutputFilter filter_name /path/to/lua/script.lua function_name</code></td></tr>
1796 <tr><th><a href="directive-dict.html#Context">Context:</a></th><td>server config</td></tr>
1797 <tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Experimental</td></tr>
1798 <tr><th><a href="directive-dict.html#Module">Module:</a></th><td>mod_lua</td></tr>
1799 <tr><th><a href="directive-dict.html#Compatibility">Compatibility:</a></th><td>2.5.0 and later</td></tr>
1800 </table>
1801 <p>Provides a means of adding a Lua function as an output filter. 
1802 As with input filters, output filters work as coroutines, 
1803 first yielding before buffers are sent, then yielding whenever 
1804 a bucket needs to be passed down the chain, and finally (optionally) 
1805 yielding anything that needs to be appended to the input data. The 
1806 global variable <code>bucket</code> holds the buckets as they are passed 
1807 onto the Lua script:
1808 </p>
1809
1810 <pre class="prettyprint lang-config">
1811 LuaOutputFilter myOutputFilter /www/filter.lua output_filter
1812 &lt;FilesMatch "\.lua&gt;
1813   SetOutputFilter myOutputFilter
1814 &lt;/FilesMatch&gt;
1815 </pre>
1816
1817 <pre class="prettyprint lang-lua">
1818 --[[
1819     Example output filter that escapes all HTML entities in the output
1820 ]]--
1821 function output_filter(r)
1822     coroutine.yield("(Handled by myOutputFilter)&lt;br/&gt;\n") -- Prepend some data to the output,
1823                                                           -- yield and wait for buckets.
1824     while bucket do -- For each bucket, do...
1825         local output = r:escape_html(bucket) -- Escape all output
1826         coroutine.yield(output) -- Send converted data down the chain
1827     end
1828     -- No more buckets available.
1829 end
1830 </pre>
1831
1832 <p>
1833 As with the input filter, the output filter supports denying/skipping a filter 
1834 if it is deemed unwanted:
1835 </p>
1836 <pre class="prettyprint lang-lua">
1837 function output_filter(r)
1838     if not r.content_type:match("text/html") then
1839         return -- Simply deny filtering, passing on the original content instead
1840     end
1841     coroutine.yield() -- wait for buckets
1842     ... -- insert filter stuff here
1843 end
1844 </pre>
1845
1846 <div class="note"><h3>Lua filters with <code class="module"><a href="../mod/mod_filter.html">mod_filter</a></code></h3>
1847 <p> When a Lua filter is used as the underlying provider via the 
1848 <code class="directive"><a href="../mod/mod_filter.html#filterprovider">FilterProvider</a></code> directive, filtering 
1849 will only work when the <var>filter-name</var> is identical to the <var>provider-name</var>.
1850 </p> </div>
1851
1852 <p>
1853 See "<a href="#modifying_buckets">Modifying contents with Lua filters</a>" for more 
1854 information.
1855 </p>
1856
1857
1858 </div>
1859 <div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
1860 <div class="directive-section"><h2><a name="LuaPackageCPath" id="LuaPackageCPath">LuaPackageCPath</a> <a name="luapackagecpath" id="luapackagecpath">Directive</a></h2>
1861 <table class="directive">
1862 <tr><th><a href="directive-dict.html#Description">Description:</a></th><td>Add a directory to lua's package.cpath</td></tr>
1863 <tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code>LuaPackageCPath /path/to/include/?.soa</code></td></tr>
1864 <tr><th><a href="directive-dict.html#Context">Context:</a></th><td>server config, virtual host, directory, .htaccess</td></tr>
1865 <tr><th><a href="directive-dict.html#Override">Override:</a></th><td>All</td></tr>
1866 <tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Experimental</td></tr>
1867 <tr><th><a href="directive-dict.html#Module">Module:</a></th><td>mod_lua</td></tr>
1868 </table>
1869     <p>Add a path to lua's shared library search path. Follows the same
1870     conventions as lua. This just munges the package.cpath in the
1871     lua vms.</p>
1872
1873
1874 </div>
1875 <div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
1876 <div class="directive-section"><h2><a name="LuaPackagePath" id="LuaPackagePath">LuaPackagePath</a> <a name="luapackagepath" id="luapackagepath">Directive</a></h2>
1877 <table class="directive">
1878 <tr><th><a href="directive-dict.html#Description">Description:</a></th><td>Add a directory to lua's package.path</td></tr>
1879 <tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code>LuaPackagePath /path/to/include/?.lua</code></td></tr>
1880 <tr><th><a href="directive-dict.html#Context">Context:</a></th><td>server config, virtual host, directory, .htaccess</td></tr>
1881 <tr><th><a href="directive-dict.html#Override">Override:</a></th><td>All</td></tr>
1882 <tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Experimental</td></tr>
1883 <tr><th><a href="directive-dict.html#Module">Module:</a></th><td>mod_lua</td></tr>
1884 </table><p>Add a path to lua's module search path. Follows the same
1885     conventions as lua. This just munges the package.path in the
1886     lua vms.</p>
1887
1888     <div class="example"><h3>Examples:</h3><pre class="prettyprint lang-config">
1889 LuaPackagePath /scripts/lib/?.lua
1890 LuaPackagePath /scripts/lib/?/init.lua
1891     </pre>
1892 </div>
1893
1894 </div>
1895 <div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
1896 <div class="directive-section"><h2><a name="LuaQuickHandler" id="LuaQuickHandler">LuaQuickHandler</a> <a name="luaquickhandler" id="luaquickhandler">Directive</a></h2>
1897 <table class="directive">
1898 <tr><th><a href="directive-dict.html#Description">Description:</a></th><td>Provide a hook for the quick handler of request processing</td></tr>
1899 <tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code>LuaQuickHandler /path/to/script.lua hook_function_name</code></td></tr>
1900 <tr><th><a href="directive-dict.html#Context">Context:</a></th><td>server config, virtual host</td></tr>
1901 <tr><th><a href="directive-dict.html#Override">Override:</a></th><td>All</td></tr>
1902 <tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Experimental</td></tr>
1903 <tr><th><a href="directive-dict.html#Module">Module:</a></th><td>mod_lua</td></tr>
1904 </table>
1905     <p>
1906     This phase is run immediately after the request has been mapped to a virtal host, 
1907     and can be used to either do some request processing before the other phases kick 
1908     in, or to serve a request without the need to translate, map to storage et cetera. 
1909     As this phase is run before anything else, directives such as <code class="directive"><a href="../mod/core.html#location">&lt;Location&gt;</a></code> or <code class="directive"><a href="../mod/core.html#directory">&lt;Directory&gt;</a></code> are void in this phase, just as 
1910     URIs have not been properly parsed yet.
1911     </p>
1912    <div class="note"><h3>Context</h3><p>This directive is not valid in <code class="directive"><a href="../mod/core.html#directory">&lt;Directory&gt;</a></code>, <code class="directive"><a href="../mod/core.html#files">&lt;Files&gt;</a></code>, or htaccess
1913    context.</p></div>
1914
1915 </div>
1916 <div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
1917 <div class="directive-section"><h2><a name="LuaRoot" id="LuaRoot">LuaRoot</a> <a name="luaroot" id="luaroot">Directive</a></h2>
1918 <table class="directive">
1919 <tr><th><a href="directive-dict.html#Description">Description:</a></th><td>Specify the base path for resolving relative paths for mod_lua directives</td></tr>
1920 <tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code>LuaRoot /path/to/a/directory</code></td></tr>
1921 <tr><th><a href="directive-dict.html#Context">Context:</a></th><td>server config, virtual host, directory, .htaccess</td></tr>
1922 <tr><th><a href="directive-dict.html#Override">Override:</a></th><td>All</td></tr>
1923 <tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Experimental</td></tr>
1924 <tr><th><a href="directive-dict.html#Module">Module:</a></th><td>mod_lua</td></tr>
1925 </table>
1926     <p>Specify the base path which will be used to evaluate all
1927     relative paths within mod_lua. If not specified they
1928     will be resolved relative to the current working directory,
1929     which may not always work well for a server.</p>
1930
1931 </div>
1932 <div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
1933 <div class="directive-section"><h2><a name="LuaScope" id="LuaScope">LuaScope</a> <a name="luascope" id="luascope">Directive</a></h2>
1934 <table class="directive">
1935 <tr><th><a href="directive-dict.html#Description">Description:</a></th><td>One of once, request, conn, thread -- default is once</td></tr>
1936 <tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code>LuaScope once|request|conn|thread|server [min] [max]</code></td></tr>
1937 <tr><th><a href="directive-dict.html#Default">Default:</a></th><td><code>LuaScope once</code></td></tr>
1938 <tr><th><a href="directive-dict.html#Context">Context:</a></th><td>server config, virtual host, directory, .htaccess</td></tr>
1939 <tr><th><a href="directive-dict.html#Override">Override:</a></th><td>All</td></tr>
1940 <tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Experimental</td></tr>
1941 <tr><th><a href="directive-dict.html#Module">Module:</a></th><td>mod_lua</td></tr>
1942 </table>
1943     <p>Specify the life cycle scope of the Lua interpreter which will
1944     be used by handlers in this "Directory." The default is "once"</p>
1945
1946    <dl>
1947     <dt>once:</dt> <dd>use the interpreter once and throw it away.</dd>
1948
1949     <dt>request:</dt> <dd>use the interpreter to handle anything based on
1950              the same file within this request, which is also
1951              request scoped.</dd>
1952
1953     <dt>conn:</dt> <dd>Same as request but attached to the connection_rec</dd>
1954
1955     <dt>thread:</dt> <dd>Use the interpreter for the lifetime of the thread 
1956             handling the request (only available with threaded MPMs).</dd>
1957
1958     <dt>server:</dt>  <dd>This one is different than others because the
1959             server scope is quite long lived, and multiple threads
1960             will have the same server_rec. To accommodate this,
1961             server scoped Lua states are stored in an apr
1962             resource list. The <code>min</code> and <code>max</code> arguments 
1963             specify the minimum and maximum number of Lua states to keep in the 
1964             pool.</dd>
1965    </dl>
1966     <p>
1967     Generally speaking, the <code>thread</code> and <code>server</code> scopes 
1968     execute roughly 2-3 times faster than the rest, because they don't have to 
1969     spawn new Lua states on every request (especially with the event MPM, as 
1970     even keepalive requests will use a new thread for each request). If you are 
1971     satisfied that your scripts will not have problems reusing a state, then 
1972     the <code>thread</code> or <code>server</code> scopes should be used for 
1973     maximum performance. While the <code>thread</code> scope will provide the 
1974     fastest responses, the <code>server</code> scope will use less memory, as 
1975     states are pooled, allowing f.x. 1000 threads to share only 100 Lua states, 
1976     thus using only 10% of the memory required by the <code>thread</code> scope.
1977     </p>
1978
1979 </div>
1980 </div>
1981 <div class="bottomlang">
1982 <p><span>Available Languages: </span><a href="../en/mod/mod_lua.html" title="English">&nbsp;en&nbsp;</a> |
1983 <a href="../fr/mod/mod_lua.html" hreflang="fr" rel="alternate" title="Français">&nbsp;fr&nbsp;</a></p>
1984 </div><div class="top"><a href="#page-header"><img src="../images/up.gif" alt="top" /></a></div><div class="section"><h2><a id="comments_section" name="comments_section">Comments</a></h2><div class="warning"><strong>Notice:</strong><br />This is not a Q&amp;A section. Comments placed here should be pointed towards suggestions on improving the documentation or server, and may be removed again by our moderators if they are either implemented or considered invalid/off-topic. Questions on how to manage the Apache HTTP Server should be directed at either our IRC channel, #httpd, on Freenode, or sent to our <a href="http://httpd.apache.org/lists.html">mailing lists</a>.</div>
1985 <script type="text/javascript"><!--//--><![CDATA[//><!--
1986 var comments_shortname = 'httpd';
1987 var comments_identifier = 'http://httpd.apache.org/docs/trunk/mod/mod_lua.html';
1988 (function(w, d) {
1989     if (w.location.hostname.toLowerCase() == "httpd.apache.org") {
1990         d.write('<div id="comments_thread"><\/div>');
1991         var s = d.createElement('script');
1992         s.type = 'text/javascript';
1993         s.async = true;
1994         s.src = 'https://comments.apache.org/show_comments.lua?site=' + comments_shortname + '&page=' + comments_identifier;
1995         (d.getElementsByTagName('head')[0] || d.getElementsByTagName('body')[0]).appendChild(s);
1996     }
1997     else {
1998         d.write('<div id="comments_thread">Comments are disabled for this page at the moment.<\/div>');
1999     }
2000 })(window, document);
2001 //--><!]]></script></div><div id="footer">
2002 <p class="apache">Copyright 2013 The Apache Software Foundation.<br />Licensed under the <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache License, Version 2.0</a>.</p>
2003 <p class="menu"><a href="../mod/">Modules</a> | <a href="../mod/quickreference.html">Directives</a> | <a href="http://wiki.apache.org/httpd/FAQ">FAQ</a> | <a href="../glossary.html">Glossary</a> | <a href="../sitemap.html">Sitemap</a></p></div><script type="text/javascript"><!--//--><![CDATA[//><!--
2004 if (typeof(prettyPrint) !== 'undefined') {
2005     prettyPrint();
2006 }
2007 //--><!]]></script>
2008 </body></html>