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