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