aboutsummaryrefslogtreecommitdiffstats
path: root/net
diff options
context:
space:
mode:
Diffstat (limited to 'net')
-rw-r--r--net/dns.lua2
-rw-r--r--net/http.lua88
-rw-r--r--net/http/parser.lua40
-rw-r--r--net/http/server.lua45
-rw-r--r--net/server.lua19
-rw-r--r--net/server_event.lua2
-rw-r--r--net/server_select.lua156
7 files changed, 195 insertions, 157 deletions
diff --git a/net/dns.lua b/net/dns.lua
index a134eceb..c9c51fe8 100644
--- a/net/dns.lua
+++ b/net/dns.lua
@@ -223,7 +223,7 @@ end
function dns.random(...) -- - - - - - - - - - - - - - - - - - - dns.random
- math.randomseed(math.floor(10000*socket.gettime()));
+ math.randomseed(math.floor(10000*socket.gettime()) % 0x100000000);
dns.random = math.random;
return dns.random(...);
end
diff --git a/net/http.lua b/net/http.lua
index 273eee09..3b783a41 100644
--- a/net/http.lua
+++ b/net/http.lua
@@ -9,14 +9,17 @@
local socket = require "socket"
local b64 = require "util.encodings".base64.encode;
local url = require "socket.url"
-local httpstream_new = require "util.httpstream".new;
+local httpstream_new = require "net.http.parser".new;
+local util_http = require "util.http";
+
+local ssl_available = pcall(require, "ssl");
local server = require "net.server"
local t_insert, t_concat = table.insert, table.concat;
-local pairs, ipairs = pairs, ipairs;
-local tonumber, tostring, xpcall, select, debug_traceback, char, format =
- tonumber, tostring, xpcall, select, debug.traceback, string.char, string.format;
+local pairs = pairs;
+local tonumber, tostring, xpcall, select, traceback =
+ tonumber, tostring, xpcall, select, debug.traceback;
local log = require "util.logger".init("http");
@@ -63,64 +66,29 @@ end
function listener.ondisconnect(conn, err)
local request = requests[conn];
if request and request.conn then
- request:reader(nil);
+ request:reader(nil, err);
end
requests[conn] = nil;
end
-function urlencode(s) return s and (s:gsub("[^a-zA-Z0-9.~_-]", function (c) return format("%%%02x", c:byte()); end)); end
-function urldecode(s) return s and (s:gsub("%%(%x%x)", function (c) return char(tonumber(c,16)); end)); end
-
-local function _formencodepart(s)
- return s and (s:gsub("%W", function (c)
- if c ~= " " then
- return format("%%%02x", c:byte());
- else
- return "+";
- end
- end));
-end
-
-function formencode(form)
- local result = {};
- if form[1] then -- Array of ordered { name, value }
- for _, field in ipairs(form) do
- t_insert(result, _formencodepart(field.name).."=".._formencodepart(field.value));
- end
- else -- Unordered map of name -> value
- for name, value in pairs(form) do
- t_insert(result, _formencodepart(name).."=".._formencodepart(value));
- end
- end
- return t_concat(result, "&");
-end
-
-function formdecode(s)
- if not s:match("=") then return urldecode(s); end
- local r = {};
- for k, v in s:gmatch("([^=&]*)=([^&]*)") do
- k, v = k:gsub("%+", "%%20"), v:gsub("%+", "%%20");
- k, v = urldecode(k), urldecode(v);
- t_insert(r, { name = k, value = v });
- r[k] = v;
- end
- return r;
-end
-
-local function request_reader(request, data, startpos)
+local function request_reader(request, data, err)
if not request.parser then
- if not data then return; end
- local function success_cb(r)
+ local function error_cb(reason)
if request.callback then
- for k,v in pairs(r) do request[k] = v; end
- request.callback(r.body, r.code, request, r);
+ request.callback(reason or "connection-closed", 0, request);
request.callback = nil;
end
destroy_request(request);
end
- local function error_cb(r)
+
+ if not data then
+ error_cb(err);
+ return;
+ end
+
+ local function success_cb(r)
if request.callback then
- request.callback(r or "connection-closed", 0, request);
+ request.callback(r.body, r.code, r, request);
request.callback = nil;
end
destroy_request(request);
@@ -133,7 +101,7 @@ local function request_reader(request, data, startpos)
request.parser:feed(data);
end
-local function handleerr(err) log("error", "Traceback[http]: %s: %s", tostring(err), debug_traceback()); end
+local function handleerr(err) log("error", "Traceback[http]: %s", traceback(tostring(err), 2)); end
function request(u, ex, callback)
local req = url.parse(u);
@@ -177,6 +145,9 @@ function request(u, ex, callback)
req.method, req.headers, req.body = method, headers, body;
local using_https = req.scheme == "https";
+ if using_https and not ssl_available then
+ error("SSL not available, unable to contact https URL");
+ end
local port = tonumber(req.port) or (using_https and 443 or 80);
-- Connect the socket, and wrap it with net.server
@@ -188,7 +159,12 @@ function request(u, ex, callback)
return nil, err;
end
- req.handler, req.conn = server.wrapclient(conn, req.host, port, listener, "*a", using_https and { mode = "client", protocol = "sslv23" });
+ local sslctx = false;
+ if using_https then
+ sslctx = ex and ex.sslctx or { mode = "client", protocol = "sslv23", options = { "no_sslv2" } };
+ end
+
+ req.handler, req.conn = server.wrapclient(conn, req.host, port, listener, "*a", sslctx);
req.write = function (...) return req.handler:write(...); end
req.callback = function (content, code, request, response) log("debug", "Calling callback, status %s", code or "---"); return select(2, xpcall(function () return callback(content, code, request, response) end, handleerr)); end
@@ -206,6 +182,10 @@ function destroy_request(request)
end
end
-_M.urlencode = urlencode;
+local urlencode, urldecode = util_http.urlencode, util_http.urldecode;
+local formencode, formdecode = util_http.formencode, util_http.formdecode;
+
+_M.urlencode, _M.urldecode = urlencode, urldecode;
+_M.formencode, _M.formdecode = formencode, formdecode;
return _M;
diff --git a/net/http/parser.lua b/net/http/parser.lua
index 2545b5ac..f9e6cea0 100644
--- a/net/http/parser.lua
+++ b/net/http/parser.lua
@@ -1,8 +1,7 @@
-
local tonumber = tonumber;
local assert = assert;
local url_parse = require "socket.url".parse;
-local urldecode = require "net.http".urldecode;
+local urldecode = require "util.http".urldecode;
local function preprocess_path(path)
path = urldecode((path:gsub("//+", "/")));
@@ -29,7 +28,7 @@ function httpstream.new(success_cb, error_cb, parser_type, options_cb)
local client = true;
if not parser_type or parser_type == "server" then client = false; else assert(parser_type == "client", "Invalid parser type"); end
local buf = "";
- local chunked;
+ local chunked, chunk_size, chunk_start;
local state = nil;
local packet;
local len;
@@ -65,12 +64,12 @@ function httpstream.new(success_cb, error_cb, parser_type, options_cb)
first_line = line;
if client then
httpversion, status_code, reason_phrase = line:match("^HTTP/(1%.[01]) (%d%d%d) (.*)$");
+ status_code = tonumber(status_code);
if not status_code then error = true; return error_cb("invalid-status-line"); end
have_body = not
( (options_cb and options_cb().method == "HEAD")
or (status_code == 204 or status_code == 304 or status_code == 301)
or (status_code >= 100 and status_code < 200) );
- chunked = have_body and headers["transfer-encoding"] == "chunked";
else
method, path, httpversion = line:match("^(%w+) (%S+) HTTP/(1%.[01])$");
if not method then error = true; return error_cb("invalid-status-line"); end
@@ -78,6 +77,7 @@ function httpstream.new(success_cb, error_cb, parser_type, options_cb)
end
end
if not first_line then error = true; return error_cb("invalid-status-line"); end
+ chunked = have_body and headers["transfer-encoding"] == "chunked";
len = tonumber(headers["content-length"]); -- TODO check for invalid len
if client then
-- FIXME handle '100 Continue' response (by skipping it)
@@ -120,22 +120,30 @@ function httpstream.new(success_cb, error_cb, parser_type, options_cb)
if state then -- read body
if client then
if chunked then
- local index = buf:find("\r\n", nil, true);
- if not index then return; end -- not enough data
- local chunk_size = buf:match("^%x+");
- if not chunk_size then error = true; return error_cb("invalid-chunk-size"); end
- chunk_size = tonumber(chunk_size, 16);
- index = index + 2;
- if chunk_size == 0 then
- state = nil; success_cb(packet);
- elseif #buf - index + 1 >= chunk_size then -- we have a chunk
- packet.body = packet.body..buf:sub(index, index + chunk_size - 1);
- buf = buf:sub(index + chunk_size);
+ if not buf:find("\r\n", nil, true) then
+ return;
+ end -- not enough data
+ if not chunk_size then
+ chunk_size, chunk_start = buf:match("^(%x+)[^\r\n]*\r\n()");
+ chunk_size = chunk_size and tonumber(chunk_size, 16);
+ if not chunk_size then error = true; return error_cb("invalid-chunk-size"); end
+ end
+ if chunk_size == 0 and buf:find("\r\n\r\n", chunk_start-2, true) then
+ state, chunk_size = nil, nil;
+ buf = buf:gsub("^.-\r\n\r\n", ""); -- This ensure extensions and trailers are stripped
+ success_cb(packet);
+ elseif #buf - chunk_start + 2 >= chunk_size then -- we have a chunk
+ packet.body = packet.body..buf:sub(chunk_start, chunk_start + (chunk_size-1));
+ buf = buf:sub(chunk_start + chunk_size + 2);
+ chunk_size, chunk_start = nil, nil;
+ else -- Partial chunk remaining
+ break;
end
- error("trailers"); -- FIXME MUST read trailers
elseif len and #buf >= len then
packet.body, buf = buf:sub(1, len), buf:sub(len + 1);
state = nil; success_cb(packet);
+ else
+ break;
end
elseif #buf >= len then
packet.body, buf = buf:sub(1, len), buf:sub(len + 1);
diff --git a/net/http/server.lua b/net/http/server.lua
index 7cf25009..dec7da19 100644
--- a/net/http/server.lua
+++ b/net/http/server.lua
@@ -9,7 +9,7 @@ local pairs = pairs;
local s_upper = string.upper;
local setmetatable = setmetatable;
local xpcall = xpcall;
-local debug = debug;
+local traceback = debug.traceback;
local tostring = tostring;
local codes = require "net.http.codes";
@@ -27,8 +27,11 @@ local function is_wildcard_match(wildcard_event, event)
return wildcard_event:sub(1, -2) == event:sub(1, #wildcard_event-1);
end
+local recent_wildcard_events, max_cached_wildcard_events = {}, 10000;
+
local event_map = events._event_map;
setmetatable(events._handlers, {
+ -- Called when firing an event that doesn't exist (but may match a wildcard handler)
__index = function (handlers, curr_event)
if is_wildcard_event(curr_event) then return; end -- Wildcard events cannot be fired
-- Find all handlers that could match this event, sort them
@@ -58,6 +61,12 @@ setmetatable(events._handlers, {
handlers_array = false;
end
rawset(handlers, curr_event, handlers_array);
+ if not event_map[curr_event] then -- Only wildcard handlers match, if any
+ table.insert(recent_wildcard_events, curr_event);
+ if #recent_wildcard_events > max_cached_wildcard_events then
+ rawset(handlers, table.remove(recent_wildcard_events, 1), nil);
+ end
+ end
return handlers_array;
end;
__newindex = function (handlers, curr_event, handlers_array)
@@ -79,7 +88,7 @@ local _1, _2, _3;
local function _handle_request() return handle_request(_1, _2, _3); end
local last_err;
-local function _traceback_handler(err) last_err = err; log("error", "Traceback[http]: %s: %s", tostring(err), debug.traceback()); end
+local function _traceback_handler(err) last_err = err; log("error", "Traceback[httpserver]: %s", traceback(tostring(err), 2)); end
events.add_handler("http-error", function (error)
return "Error processing request: "..codes[error.code]..". Check your error log for more information.";
end, -1);
@@ -89,29 +98,30 @@ function listener.onconnect(conn)
local pending = {};
local waiting = false;
local function process_next()
- --if waiting then log("debug", "can't process_next, waiting"); return; end
- if sessions[conn] and #pending > 0 then
+ if waiting then log("debug", "can't process_next, waiting"); return; end
+ waiting = true;
+ while sessions[conn] and #pending > 0 do
local request = t_remove(pending);
--log("debug", "process_next: %s", request.path);
- waiting = true;
--handle_request(conn, request, process_next);
_1, _2, _3 = conn, request, process_next;
if not xpcall(_handle_request, _traceback_handler) then
conn:write("HTTP/1.0 500 Internal Server Error\r\n\r\n"..events.fire_event("http-error", { code = 500, private_message = last_err }));
conn:close();
end
- else
- --log("debug", "ready for more");
- waiting = false;
end
+ --log("debug", "ready for more");
+ waiting = false;
end
local function success_cb(request)
--log("debug", "success_cb: %s", request.path);
+ if waiting then
+ log("error", "http connection handler is not reentrant: %s", request.path);
+ assert(false, "http connection handler is not reentrant");
+ end
request.secure = secure;
t_insert(pending, request);
- if not waiting then
- process_next();
- end
+ process_next();
end
local function error_cb(err)
log("debug", "error_cb: %s", err or "<nil>");
@@ -158,7 +168,7 @@ function handle_request(conn, request, finish_cb)
local conn_header = request.headers.connection;
conn_header = conn_header and ","..conn_header:gsub("[ \t]", ""):lower().."," or ""
local httpversion = request.httpversion
- local persistent = conn_header:find(",keep-alive,", 1, true)
+ local persistent = conn_header:find(",Keep-Alive,", 1, true)
or (httpversion == "1.1" and not conn_header:find(",close,", 1, true));
local response_conn_header;
@@ -218,7 +228,13 @@ function handle_request(conn, request, finish_cb)
body = result;
elseif result_type == "table" then
for k, v in pairs(result) do
- response[k] = v;
+ if k ~= "headers" then
+ response[k] = v;
+ else
+ for header_name, header_value in pairs(v) do
+ response.headers[header_name] = header_value;
+ end
+ end
end
end
response:send(body);
@@ -277,6 +293,9 @@ end
function _M.set_default_host(host)
default_host = host;
end
+function _M.fire_event(event, ...)
+ return events.fire_event(event, ...);
+end
_M.listener = listener;
_M.codes = codes;
diff --git a/net/server.lua b/net/server.lua
index 3cdbe551..375e7081 100644
--- a/net/server.lua
+++ b/net/server.lua
@@ -6,7 +6,7 @@
-- COPYING file in the source package for more information.
--
-local use_luaevent = prosody and require "core.configmanager".get("*", "core", "use_libevent");
+local use_luaevent = prosody and require "core.configmanager".get("*", "use_libevent");
if use_luaevent then
use_luaevent = pcall(require, "luaevent.core");
@@ -42,11 +42,16 @@ end
if prosody then
local config_get = require "core.configmanager".get;
+ local defaults = {};
+ for k,v in pairs(server.cfg or server.getsettings()) do
+ defaults[k] = v;
+ end
local function load_config()
- local settings = config_get("*", "core", "network_settings") or {};
+ local settings = config_get("*", "network_settings") or {};
if use_luaevent then
local event_settings = {
ACCEPT_DELAY = settings.event_accept_retry_interval;
+ ACCEPT_QUEUE = settings.tcp_backlog;
CLEAR_DELAY = settings.event_clear_interval;
CONNECT_TIMEOUT = settings.connect_timeout;
DEBUG = settings.debug;
@@ -59,11 +64,15 @@ if prosody then
WRITE_TIMEOUT = settings.send_timeout;
};
- for k, v in pairs(event_settings) do
- server.cfg[k] = v;
+ for k,default in pairs(defaults) do
+ server.cfg[k] = event_settings[k] or default;
end
else
- server.changesettings(settings);
+ local select_settings = {};
+ for k,default in pairs(defaults) do
+ select_settings[k] = settings[k] or default;
+ end
+ server.changesettings(select_settings);
end
end
load_config();
diff --git a/net/server_event.lua b/net/server_event.lua
index 08926939..5eae95a9 100644
--- a/net/server_event.lua
+++ b/net/server_event.lua
@@ -23,6 +23,7 @@ local cfg = {
HANDSHAKE_TIMEOUT = 60, -- timeout in seconds per handshake attempt
MAX_READ_LENGTH = 1024 * 1024 * 1024 * 1024, -- max bytes allowed to read from sockets
MAX_SEND_LENGTH = 1024 * 1024 * 1024 * 1024, -- max bytes size of write buffer (for writing on sockets)
+ ACCEPT_QUEUE = 128, -- might influence the length of the pending sockets queue
ACCEPT_DELAY = 10, -- seconds to wait until the next attempt of a full server to accept
READ_TIMEOUT = 60 * 60 * 6, -- timeout in seconds for read data from socket
WRITE_TIMEOUT = 180, -- timeout in seconds for write data on socket
@@ -460,7 +461,6 @@ end
local handleclient;
do
local string_sub = string.sub -- caching table lookups
- local string_len = string.len
local addevent = base.addevent
local socket_gettime = socket.gettime
function handleclient( client, ip, port, server, pattern, listener, sslctx ) -- creates an client interface
diff --git a/net/server_select.lua b/net/server_select.lua
index 0852d444..7eb330a8 100644
--- a/net/server_select.lua
+++ b/net/server_select.lua
@@ -10,11 +10,6 @@
local use = function( what )
return _G[ what ]
end
-local clean = function( tbl )
- for i, k in pairs( tbl ) do
- tbl[ i ] = nil
- end
-end
local log, table_concat = require ("util.logger").init("socket"), table.concat;
local out_put = function (...) return log("debug", table_concat{...}); end
@@ -47,7 +42,6 @@ local os_difftime = os.difftime
local math_min = math.min
local math_huge = math.huge
local table_concat = table.concat
-local string_len = string.len
local string_sub = string.sub
local coroutine_wrap = coroutine.wrap
local coroutine_yield = coroutine.yield
@@ -107,6 +101,7 @@ local _readtraffic
local _selecttimeout
local _sleeptime
+local _tcpbacklog
local _starttime
local _currenttime
@@ -118,11 +113,10 @@ local _checkinterval
local _sendtimeout
local _readtimeout
-local _cleanqueue
-
local _timer
-local _maxclientsperserver
+local _maxselectlen
+local _maxfd
local _maxsslhandshake
@@ -146,6 +140,7 @@ _readtraffic = 0
_selecttimeout = 1 -- timeout of socket.select
_sleeptime = 0 -- time to wait at the end of every loop
+_tcpbacklog = 128 -- some kind of hint to the OS
_maxsendlen = 51000 * 1024 -- max len of send buffer
_maxreadlen = 25000 * 1024 -- max len of read buffer
@@ -154,17 +149,21 @@ _checkinterval = 1200000 -- interval in secs to check idle clients
_sendtimeout = 60000 -- allowed send idle time in secs
_readtimeout = 6 * 60 * 60 -- allowed read idle time in secs
-_cleanqueue = false -- clean bufferqueue after using
-
-_maxclientsperserver = 1000
+local is_windows = package.config:sub(1,1) == "\\" -- check the directory separator, to detemine whether this is Windows
+_maxfd = luasocket._SETSIZE or (is_windows and math.huge) or 1024 -- max fd number, limit to 1024 by default to prevent glibc buffer overflow, but not on Windows
+_maxselectlen = luasocket._SETSIZE or 1024 -- But this still applies on Windows
_maxsslhandshake = 30 -- max handshake round-trips
----------------------------------// PRIVATE //--
-wrapserver = function( listeners, socket, ip, serverport, pattern, sslctx, maxconnections ) -- this function wraps a server
+wrapserver = function( listeners, socket, ip, serverport, pattern, sslctx ) -- this function wraps a server -- FIXME Make sure FD < _maxfd
- maxconnections = maxconnections or _maxclientsperserver
+ if socket:getfd() >= _maxfd then
+ out_error("server.lua: Disallowed FD number: "..socket:getfd())
+ socket:close()
+ return nil, "fd-too-large"
+ end
local connections = 0
@@ -201,20 +200,23 @@ wrapserver = function( listeners, socket, ip, serverport, pattern, sslctx, maxco
--mem_free( )
out_put "server.lua: closed server handler and removed sockets from list"
end
- handler.pause = function()
+ handler.pause = function( hard )
if not handler.paused then
- socket:close( )
- _sendlistlen = removesocket( _sendlist, socket, _sendlistlen )
_readlistlen = removesocket( _readlist, socket, _readlistlen )
- _socketlist[ socket ] = nil
- socket = nil;
+ if hard then
+ _socketlist[ socket ] = nil
+ socket:close( )
+ socket = nil;
+ end
handler.paused = true;
end
end
- handler.resume = function()
+ handler.resume = function( )
if handler.paused then
- socket = socket_bind( ip, serverport );
- socket:settimeout( 0 )
+ if not socket then
+ socket = socket_bind( ip, serverport, _tcpbacklog );
+ socket:settimeout( 0 )
+ end
_readlistlen = addsocket(_readlist, socket, _readlistlen)
_socketlist[ socket ] = handler
handler.paused = false;
@@ -230,7 +232,7 @@ wrapserver = function( listeners, socket, ip, serverport, pattern, sslctx, maxco
return socket
end
handler.readbuffer = function( )
- if connections > maxconnections then
+ if _readlistlen >= _maxselectlen or _sendlistlen >= _maxselectlen then
handler.pause( )
out_put( "server.lua: refused new client connection: server full" )
return false
@@ -244,7 +246,7 @@ wrapserver = function( listeners, socket, ip, serverport, pattern, sslctx, maxco
end
connections = connections + 1
out_put( "server.lua: accepted new client connection from ", tostring(ip), ":", tostring(clientport), " to ", tostring(serverport))
- if dispatch then
+ if dispatch and not sslctx then -- SSL connections will notify onconnect when handshake completes
return dispatch( handler );
end
return;
@@ -258,6 +260,12 @@ end
wrapconnection = function( server, listeners, socket, ip, serverport, clientport, pattern, sslctx ) -- this function wraps a client to a handler object
+ if socket:getfd() >= _maxfd then
+ out_error("server.lua: Disallowed FD number: "..socket:getfd()) -- PROTIP: Switch to libevent
+ socket:close( ) -- Should we send some kind of error here?
+ server.pause( )
+ return nil, nil, "fd-too-large"
+ end
socket:settimeout( 0 )
--// local import of socket methods //--
@@ -335,9 +343,6 @@ wrapconnection = function( server, listeners, socket, ip, serverport, clientport
handler.force_close = function ( self, err )
if bufferqueuelen ~= 0 then
out_put("server.lua: discarding unwritten data for ", tostring(ip), ":", tostring(clientport))
- for i = bufferqueuelen, 1, -1 do
- bufferqueue[i] = nil;
- end
bufferqueuelen = 0;
end
return self:close(err);
@@ -391,7 +396,7 @@ wrapconnection = function( server, listeners, socket, ip, serverport, clientport
return clientport
end
local write = function( self, data )
- bufferlen = bufferlen + string_len( data )
+ bufferlen = bufferlen + #data
if bufferlen > maxsendlen then
_closelist[ handler ] = "send buffer exceeded" -- cannot close the client at the moment, have to wait to the end of the cycle
handler.write = idfalse -- dont write anymore
@@ -473,7 +478,7 @@ wrapconnection = function( server, listeners, socket, ip, serverport, clientport
local buffer, err, part = receive( socket, pattern ) -- receive buffer with "pattern"
if not err or (err == "wantread" or err == "timeout") then -- received something
local buffer = buffer or part or ""
- local len = string_len( buffer )
+ local len = #buffer
if len > maxreadlen then
handler:close( "receive buffer exceeded" )
return false
@@ -499,7 +504,9 @@ wrapconnection = function( server, listeners, socket, ip, serverport, clientport
count = ( succ or byte or 0 ) * STAT_UNIT
sendtraffic = sendtraffic + count
_sendtraffic = _sendtraffic + count
- _ = _cleanqueue and clean( bufferqueue )
+ for i = bufferqueuelen,1,-1 do
+ bufferqueue[ i ] = nil
+ end
--out_put( "server.lua: sended '", buffer, "', bytes: ", tostring(succ), ", error: ", tostring(err), ", part: ", tostring(byte), ", to: ", tostring(ip), ":", tostring(clientport) )
else
succ, err, count = false, "unexpected close", 0;
@@ -568,7 +575,7 @@ wrapconnection = function( server, listeners, socket, ip, serverport, clientport
end
out_put( "server.lua: ssl handshake error: ", tostring(err or "handshake too long") )
_ = handler and handler:force_close("ssl handshake failed")
- return false, err -- handshake failed
+ return false, err -- handshake failed
end
)
end
@@ -612,7 +619,7 @@ wrapconnection = function( server, listeners, socket, ip, serverport, clientport
handler.readbuffer = handshake
handler.sendbuffer = handshake
- return handshake( socket ) -- do handshake
+ return handshake( socket ) -- do handshake
end
end
@@ -628,10 +635,10 @@ wrapconnection = function( server, listeners, socket, ip, serverport, clientport
if sslctx and luasec then
out_put "server.lua: auto-starting ssl negotiation..."
handler.autostart_ssl = true;
- local ok, err = handler:starttls(sslctx);
- if ok == false then
- return nil, nil, err
- end
+ local ok, err = handler:starttls(sslctx);
+ if ok == false then
+ return nil, nil, err
+ end
end
return handler, socket
@@ -716,12 +723,12 @@ addserver = function( addr, port, listeners, pattern, sslctx ) -- this function
return nil, err
end
addr = addr or "*"
- local server, err = socket_bind( addr, port )
+ local server, err = socket_bind( addr, port, _tcpbacklog )
if err then
out_error( "server.lua, [", addr, "]:", port, ": ", err )
return nil, err
end
- local handler, err = wrapserver( listeners, server, addr, port, pattern, sslctx, _maxclientsperserver ) -- wrap new server socket
+ local handler, err = wrapserver( listeners, server, addr, port, pattern, sslctx ) -- wrap new server socket
if not handler then
server:close( )
return nil, err
@@ -765,7 +772,19 @@ closeall = function( )
end
getsettings = function( )
- return _selecttimeout, _sleeptime, _maxsendlen, _maxreadlen, _checkinterval, _sendtimeout, _readtimeout, _cleanqueue, _maxclientsperserver, _maxsslhandshake
+ return {
+ select_timeout = _selecttimeout;
+ select_sleep_time = _sleeptime;
+ tcp_backlog = _tcpbacklog;
+ max_send_buffer_size = _maxsendlen;
+ max_receive_buffer_size = _maxreadlen;
+ select_idle_check_interval = _checkinterval;
+ send_timeout = _sendtimeout;
+ read_timeout = _readtimeout;
+ max_connections = _maxselectlen;
+ max_ssl_handshake_roundtrips = _maxsslhandshake;
+ highest_allowed_fd = _maxfd;
+ }
end
changesettings = function( new )
@@ -777,11 +796,12 @@ changesettings = function( new )
_maxsendlen = tonumber( new.max_send_buffer_size ) or _maxsendlen
_maxreadlen = tonumber( new.max_receive_buffer_size ) or _maxreadlen
_checkinterval = tonumber( new.select_idle_check_interval ) or _checkinterval
+ _tcpbacklog = tonumber( new.tcp_backlog ) or _tcpbacklog
_sendtimeout = tonumber( new.send_timeout ) or _sendtimeout
_readtimeout = tonumber( new.read_timeout ) or _readtimeout
- _cleanqueue = new.select_clean_queue
- _maxclientsperserver = new.max_connections or _maxclientsperserver
+ _maxselectlen = new.max_connections or _maxselectlen
_maxsslhandshake = new.max_ssl_handshake_roundtrips or _maxsslhandshake
+ _maxfd = new.highest_allowed_fd or _maxfd
return true
end
@@ -831,9 +851,31 @@ loop = function(once) -- this is the main loop of the program
for handler, err in pairs( _closelist ) do
handler.disconnect( )( handler, err )
handler:force_close() -- forced disconnect
+ _closelist[ handler ] = nil;
end
- clean( _closelist )
_currenttime = luasocket_gettime( )
+
+ -- Check for socket timeouts
+ local difftime = os_difftime( _currenttime - _starttime )
+ if difftime > _checkinterval then
+ _starttime = _currenttime
+ for handler, timestamp in pairs( _writetimes ) do
+ if os_difftime( _currenttime - timestamp ) > _sendtimeout then
+ --_writetimes[ handler ] = nil
+ handler.disconnect( )( handler, "send timeout" )
+ handler:force_close() -- forced disconnect
+ end
+ end
+ for handler, timestamp in pairs( _readtimes ) do
+ if os_difftime( _currenttime - timestamp ) > _readtimeout then
+ --_readtimes[ handler ] = nil
+ handler.disconnect( )( handler, "read timeout" )
+ handler:close( ) -- forced disconnect?
+ end
+ end
+ end
+
+ -- Fire timers
if _currenttime - _timer >= math_min(next_timer_time, 1) then
next_timer_time = math_huge;
for i = 1, _timerlistlen do
@@ -844,8 +886,9 @@ loop = function(once) -- this is the main loop of the program
else
next_timer_time = next_timer_time - (_currenttime - _timer);
end
- socket_sleep( _sleeptime ) -- wait some time
- --collectgarbage( )
+
+ -- wait some time (0 by default)
+ socket_sleep( _sleeptime )
until quitting;
if once and quitting == "once" then quitting = nil; return; end
return "quitting"
@@ -862,7 +905,8 @@ end
--// EXPERIMENTAL //--
local wrapclient = function( socket, ip, serverport, listeners, pattern, sslctx )
- local handler = wrapconnection( nil, listeners, socket, ip, serverport, "clientport", pattern, sslctx )
+ local handler, socket, err = wrapconnection( nil, listeners, socket, ip, serverport, "clientport", pattern, sslctx )
+ if not handler then return nil, err end
_socketlist[ socket ] = handler
if not sslctx then
_sendlistlen = addsocket(_sendlist, socket, _sendlistlen)
@@ -908,28 +952,6 @@ use "setmetatable" ( _writetimes, { __mode = "k" } )
_timer = luasocket_gettime( )
_starttime = luasocket_gettime( )
-addtimer( function( )
- local difftime = os_difftime( _currenttime - _starttime )
- if difftime > _checkinterval then
- _starttime = _currenttime
- for handler, timestamp in pairs( _writetimes ) do
- if os_difftime( _currenttime - timestamp ) > _sendtimeout then
- --_writetimes[ handler ] = nil
- handler.disconnect( )( handler, "send timeout" )
- handler:force_close() -- forced disconnect
- end
- end
- for handler, timestamp in pairs( _readtimes ) do
- if os_difftime( _currenttime - timestamp ) > _readtimeout then
- --_readtimes[ handler ] = nil
- handler.disconnect( )( handler, "read timeout" )
- handler:close( ) -- forced disconnect?
- end
- end
- end
- end
-)
-
local function setlogger(new_logger)
local old_logger = log;
if new_logger then