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