3 HTTP server implementation for LuCI - core
4 (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
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
10 http://www.apache.org/licenses/LICENSE-2.0
16 module("luci.httpd", package.seeall)
20 function Socket(ip, port)
21 local sock, err = socket.bind( ip, port )
24 sock:settimeout( 0, "t" )
31 Daemon = luci.util.class()
33 function Daemon.__init__(self, threadlimit, timeout)
38 self.threadlimit = threadlimit
39 self.timeout = timeout or 0.1
42 function Daemon.dprint(self, msg)
44 io.stderr:write("[daemon] " .. msg .. "\n")
48 function Daemon.register(self, sock, clhandler, errhandler)
49 table.insert( self.reading, sock )
50 self.handler[sock] = { clhandler = clhandler, errhandler = errhandler }
53 function Daemon.run(self)
59 function Daemon.step(self)
60 local input, output, err = socket.select( self.reading, nil, 0 )
62 if err == "timeout" and #self.running == 0 then
63 socket.sleep(self.timeout)
66 -- accept new connections
67 for i, connection in ipairs(input) do
69 local sock = connection:accept()
72 if not self.threadlimit or #self.running < self.threadlimit then
74 self:dprint("Accepted incoming connection from " .. sock:getpeername())
76 table.insert( self.running, {
77 coroutine.create( self.handler[connection].clhandler ),
81 self:dprint("Created " .. tostring(self.running[#self.running][1]))
85 self:dprint("Rejected incoming connection from " .. sock:getpeername())
87 if self.handler[connection].errhandler then
88 self.handler[connection].errhandler( sock )
95 -- create client handler
96 for i, client in ipairs( self.running ) do
99 if coroutine.status( client[1] ) == "dead" then
100 self:dprint("Completed " .. tostring(client[1]))
101 table.remove( self.running, i )
103 self:dprint("Resuming " .. tostring(client[1]))
105 local stat, err = coroutine.resume( client[1], client[2] )
107 self:dprint(tostring(client[1]) .. " returned")
110 self:dprint("Error in " .. tostring(client[1]) .. " " .. err)