* libs/http: prepare support for RFC2616 / 14.24 - 14.28
[project/luci.git] / libs / httpd / luasrc / httpd / handler / file.lua
1 --[[
2
3 HTTP server implementation for LuCI - luci handler
4 (c) 2008 Steven Barth <steven@midlink.org>
5
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
9
10         http://www.apache.org/licenses/LICENSE-2.0
11
12 $Id$
13
14 ]]--
15
16 module("luci.httpd.handler.file", package.seeall)
17
18 require("luci.httpd.module")
19 require("luci.http.protocol.date")
20 require("luci.http.protocol.mime")
21 require("luci.http.protocol.conditionals")
22 require("luci.fs")
23 require("ltn12")
24
25 Simple = luci.util.class(luci.httpd.module.Handler)
26 Response = luci.httpd.module.Response
27
28 function Simple.__init__(self, docroot, dirlist)
29         luci.httpd.module.Handler.__init__(self)
30         self.docroot = docroot
31         self.dirlist = dirlist and true or false
32         self.mime    = luci.http.protocol.mime
33         self.date    = luci.http.protocol.date
34 end
35
36 function Simple.getfile(self, uri)
37         local file = self.docroot .. uri:gsub("%.%./", "")
38         local stat = luci.fs.stat(file)
39
40         return file, stat
41 end
42
43 function Simple.handle_get(self, request, sourcein, sinkerr)
44         local file, stat = self:getfile(request.env.PATH_INFO)
45
46         if stat then
47                 if stat.type == "regular" then
48
49                         -- Generate Entity Tag
50                         local etag = luci.http.protocol.conditionals.mk_etag( stat )
51
52                         -- Send Response
53                         return Response(
54                                 200, {
55                                         ["Date"]           = self.date.to_http( os.time() );
56                                         ["Last-Modified"]  = self.date.to_http( stat.mtime );
57                                         ["Content-Type"]   = self.mime.to_mime( file );
58                                         ["Content-Length"] = stat.size;
59                                         ["ETag"]           = etag;
60                                 }
61                         ), ltn12.source.file(io.open(file))
62                 else
63                         return self:failure(403, "Unable to transmit " .. stat.type .. " " .. file)
64                 end
65         else
66                 return self:failure(404, "No such file: " .. file)
67         end
68 end
69
70 function Simple.handle_head(self, ...)
71         local response, sourceout = self:handle_get(...)
72         return response
73 end