9ec8961b87f21d81b24e2ecf32b0f4fb1bedaeaf
[project/luci.git] / libs / httpd / luasrc / httpd / server.lua
1 --[[
2
3 HTTP server implementation for LuCI - helper class
4 (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
5 (c) 2008 Steven Barth <steven@midlink.org>
6
7 Licensed under the Apache License, Version 2.0 (the "License");
8 you may not use this file except in compliance with the License.
9 You may obtain a copy of the License at
10
11         http://www.apache.org/licenses/LICENSE-2.0
12
13 $Id$
14
15 ]]--
16
17 module("luci.httpd.server", package.seeall)
18 require("socket")
19 require("socket.http")
20 require("luci.util")
21
22 READ_BUFSIZE = 1024
23 VERSION = 0.2
24
25
26 VHost = luci.util.class()
27
28 function VHost.__init__(self, handler)
29         self.handler = handler
30         self.dhandler = {}
31 end
32
33 function VHost.process(self, request, sourcein, sinkerr, ...)
34         local handler = self.handler
35
36         local uri = request.env.REQUEST_URI:match("^([^?]*)")
37
38         -- SCRIPT_NAME
39         request.env.SCRIPT_NAME = ""
40
41         -- Call URI part
42         request.env.PATH_INFO = uri
43
44         for k, dhandler in pairs(self.dhandler) do
45                 if k == uri or k.."/" == uri:sub(1, #k+1) then
46                         handler = dhandler
47                         request.env.SCRIPT_NAME = k
48                         request.env.PATH_INFO   = uri:sub(#k+1)
49                         break;
50                 end
51         end
52
53         if handler then
54                 return handler:process(request, sourcein, sinkerr, ...)
55         end
56 end
57
58
59 function VHost.set_default_handler(self, handler)
60         self.handler = handler
61 end
62
63
64 function VHost.set_handler(self, match, handler)
65         self.dhandler[match] = handler
66 end
67
68
69
70 Server = luci.util.class()
71
72 function Server.__init__(self, host)
73         self.host = host
74         self.vhosts = {}
75 end
76
77 function Server.set_default_vhost(self, vhost)
78         self.host = vhost
79 end
80
81 -- Sets a vhost
82 function Server.set_vhost(self, name, vhost)
83         self.vhosts[name] = vhost
84 end
85
86 function Server.create_daemon_handlers(self)
87         return function(...) return self:process(...) end,
88                 function(...) return self:error_overload(...) end
89 end
90
91
92 function Server.error(self, socket, code, msg)
93         hcode = tostring(code)
94         
95         socket:send( "HTTP/1.0 " .. hcode .. " " ..
96          luci.http.protocol.statusmsg[code] .. "\r\n" )
97         socket:send( "Connection: close\r\n" )
98         socket:send( "Content-Type: text/plain\r\n\r\n" )
99
100         if msg then
101                 socket:send( "HTTP-Error " .. code .. ": " .. msg .. "\r\n" )
102         end
103 end
104
105 function Server.error_overload(self, socket)
106         self:error(socket, 503, "Too many simultaneous connections")
107 end
108
109
110 function Server.process( self, client )
111
112         -- Setup sockets and sources
113         local thread = {
114                 receive = function(self, ...) return luci.httpd.corecv(client, ...) end,
115                 send = function(self, ...) return luci.httpd.cosend(client, ...) end
116         }
117         
118         client:settimeout( 0 )
119         
120         local sourcein  = ltn12.source.empty()
121         local sourcehdr = luci.http.protocol.header_source( thread )
122         local sinkerr   = ltn12.sink.file( io.stderr )
123         
124         local close = false
125         
126         local reading = { client }
127
128         local message, err
129         
130         repeat
131                 -- parse headers
132                 message, err = luci.http.protocol.parse_message_header( sourcehdr )
133
134                 if not message then
135                         self:error( client, 400, err )
136                         break
137                 end     
138                 
139                 -- keep-alive
140                 if message.http_version == 1.1 then
141                         close = (message.env.HTTP_CONNECTION == "close")
142                 else
143                         close = not message.env.HTTP_CONNECTION or message.env.HTTP_CONNECTION == "close"
144                 end
145         
146                 if message.request_method == "get" or message.request_method == "head" then
147                         -- Be happy
148                         
149                 elseif message.request_method == "post" then
150                         -- If we have a HTTP/1.1 client and an Expect: 100-continue header then
151                         -- respond with HTTP 100 Continue message
152                         if message.http_version == 1.1 and message.headers['Expect'] and
153                                 message.headers['Expect'] == '100-continue'
154                         then
155                                 client:send("HTTP/1.1 100 Continue\r\n\r\n")
156                         end
157                         
158                         if message.headers['Transfer-Encoding'] and
159                          message.headers['Transfer-Encoding'] ~= "identity" then
160                                 sourcein = socket.source("http-chunked", thread)
161                         elseif message.env.CONTENT_LENGTH then
162                                 sourcein = socket.source("by-length", thread,
163                                  tonumber(message.env.CONTENT_LENGTH))
164                         else
165                                 self:error( client, 411, luci.http.protocol.statusmsg[411] )
166                                 break;
167                         end
168                         
169                 else
170                         self:error( client, 405, luci.http.protocol.statusmsg[405] )
171                         break;
172                         
173                 end
174
175
176                 local host = self.vhosts[message.env.HTTP_HOST] or self.host
177                 if not host then
178                         self:error( client, 500, "Unable to find matching host" )
179                         break;
180                 end
181                 
182                 local response, sourceout = host:process(
183                         message, sourcein, sinkerr,
184                         client, io.stderr 
185                 )
186                 if not response then
187                         self:error( client, 500, "Error processing handler" )
188                 end
189                 
190                 -- Post process response
191                 local sinkmode = close and "close-when-done" or "keep-open"
192                 
193                 if sourceout then
194                         if not response.headers["Content-Length"] then
195                                 if message.http_version == 1.1 then
196                                         response.headers["Transfer-Encoding"] = "chunked"
197                                         sinkmode = "http-chunked"
198                                 else
199                                         close = true
200                                         sinkmode = "close-when-done"
201                                 end
202                         end
203                 end
204                 
205                 if close then
206                         response.headers["Connection"] = "close"
207                 end
208                 
209                 
210                 local sinkout = socket.sink(sinkmode, thread)
211                 
212                 local header =
213                         message.env.SERVER_PROTOCOL .. " " ..
214                         tostring(response.status) .. " " ..
215                         luci.http.protocol.statusmsg[response.status] .. "\r\n"
216
217                 header = header .. "Server: LuCI HTTPd/" .. tostring(VERSION) .. "\r\n"
218
219                 
220                 for k,v in pairs(response.headers) do
221                         header = header .. k .. ": " .. v .. "\r\n"
222                 end
223                 
224                 client:send(header .. "\r\n")
225                 
226                 if sourceout then
227                         local eof = false
228                         repeat
229                                 coroutine.yield()
230                                 eof = not ltn12.pump.step(sourceout, sinkout)
231                         until eof
232                 end
233         until close
234         
235         client:close()
236 end