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