1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
|
--[[
HTTP server implementation for LuCI - core
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
(c) 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
module("luci.httpd", package.seeall)
require("socket")
THREAD_IDLEWAIT = 0.01
THREAD_TIMEOUT = 90
THREAD_LIMIT = nil
local reading = {}
local clhandler = {}
local erhandler = {}
local threadc = 0
local threads = {}
local threadm = {}
local threadi = {}
local _meta = {__mode = "k"}
setmetatable(threadm, _meta)
setmetatable(threadi, _meta)
function Socket(ip, port)
local sock, err = socket.bind( ip, port )
if sock then
sock:settimeout( 0, "t" )
end
return sock, err
end
function corecv(socket, ...)
threadi[socket] = true
while true do
local chunk, err, part = socket:receive(...)
if err ~= "timeout" then
threadi[socket] = false
return chunk, err, part
end
coroutine.yield()
end
end
function cosend(socket, chunk, i, ...)
threadi[socket] = true
i = i or 1
while true do
local stat, err, sent = socket:send(chunk, i, ...)
if err ~= "timeout" then
threadi[socket] = false
return stat, err, sent
else
i = sent and (sent + 1) or i
end
coroutine.yield()
end
end
function register(socket, s_clhandler, s_errhandler)
table.insert(reading, socket)
clhandler[socket] = s_clhandler
erhandler[socket] = s_errhandler
end
function run()
while true do
step()
end
end
function step()
local idle = true
if not THREAD_LIMIT or threadc < THREAD_LIMIT then
local now = os.time()
for i, server in ipairs(reading) do
local client = server:accept()
if client then
threadm[client] = now
threadc = threadc + 1
threads[client] = coroutine.create(clhandler[server])
end
end
end
for client, thread in pairs(threads) do
coroutine.resume(thread, client)
local now = os.time()
if coroutine.status(thread) == "dead" then
threadc = threadc - 1
threads[client] = nil
elseif threadm[client] and threadm[client] + THREAD_TIMEOUT < now then
threads[client] = nil
threadc = threadc - 1
client:close()
elseif not threadi[client] then
threadm[client] = now
idle = false
end
end
if idle then
collectgarbage()
socket.sleep(THREAD_IDLEWAIT)
end
end
|