Switched to new connection framework, courtesy of the luadch project
authormatthew <devnull@localhost>
Sun, 24 Aug 2008 01:51:02 +0000 (01:51 +0000)
committermatthew <devnull@localhost>
Sun, 24 Aug 2008 01:51:02 +0000 (01:51 +0000)
Now supports SSL on 5223
Beginning support for presence (aka. the proper routing of stanzas)

core/stanza_dispatch.lua
core/xmlhandlers.lua [new file with mode: 0644]
main.lua
server.lua [new file with mode: 0644]
util/stanza.lua

index b7428ecdc3296c6635da47bc262f4a379992e993..e392b5ba9044688f8250022cdded9bd0f06d3dac 100644 (file)
@@ -12,14 +12,17 @@ function init_stanza_dispatcher(session)
        local session_log = session.log;
        local log = function (type, msg) session_log(type, "stanza_dispatcher", msg); end
        local send = session.send;
-
-
+       local send_to;
+       do
+               local _send_to = session.send_to;
+               send_to = function (...) _send_to(session, ...); end
+       end
 
        iq_handlers["jabber:iq:auth"] = 
                function (stanza)
-                       local username = stanza[1]:child_with_name("username");
-                       local password = stanza[1]:child_with_name("password");
-                       local resource = stanza[1]:child_with_name("resource");
+                       local username = stanza.tags[1]:child_with_name("username");
+                       local password = stanza.tags[1]:child_with_name("password");
+                       local resource = stanza.tags[1]:child_with_name("resource");
                        if not (username and password and resource) then
                                local reply = st.reply(stanza);
                                send(reply:query("jabber:iq:auth")
@@ -78,24 +81,52 @@ function init_stanza_dispatcher(session)
 
        return  function (stanza)
                        log("info", "--> "..tostring(stanza));
-                       if stanza.name == "iq" then
-                               if not stanza[1] then log("warn", "<iq> without child is invalid"); return; end
-                               if not stanza.attr.id then log("warn", "<iq> without id attribute is invalid"); end
-                               local xmlns = stanza[1].attr.xmlns;
-                               if not xmlns then log("warn", "Child of <iq> has no xmlns - invalid"); return; end
-                               if (((not stanza.attr.to) or stanza.attr.to == session.host or stanza.attr.to:match("@[^/]+$")) and (stanza.attr.type == "get" or stanza.attr.type == "set")) then -- Stanza sent to us
-                                       if iq_handlers[xmlns] then
-                                               if iq_handlers[xmlns](stanza) then return; end;
+                       if (not stanza.attr.to) or (hosts[stanza.attr.to] and hosts[stanza.attr.to].type == "local") then
+                               if stanza.name == "iq" then
+                                       if not stanza.tags[1] then log("warn", "<iq> without child is invalid"); return; end
+                                       if not stanza.attr.id then log("warn", "<iq> without id attribute is invalid"); end
+                                       local xmlns = (stanza.tags[1].attr and stanza.tags[1].attr.xmlns) or nil;
+                                       if not xmlns then log("warn", "Child of <iq> has no xmlns - invalid"); return; end
+                                       if (((not stanza.attr.to) or stanza.attr.to == session.host or stanza.attr.to:match("@[^/]+$")) and (stanza.attr.type == "get" or stanza.attr.type == "set")) then -- Stanza sent to us
+                                               if iq_handlers[xmlns] then
+                                                       if iq_handlers[xmlns](stanza) then return; end;
+                                               end
+                                               log("warn", "Unhandled namespace: "..xmlns);
+                                               send(format("<iq type='error' id='%s'><error type='cancel'><service-unavailable/></error></iq>", stanza.attr.id));
+                                               return;
+                                       end
+                               elseif stanza.name == "presence" then
+                                       if session.roster then
+                                               -- Broadcast presence and probes
+                                               local broadcast = st.presence({ from = session.username.."@"..session.host.."/"..session.resource });
+                                               local probe = st.presence { from = broadcast.attr.from, type = "probe" };
+
+                                               for child in stanza:children() do
+                                                       broadcast:tag(child.name, child.attr);
+                                               end
+                                               for contact in pairs(session.roster) do
+                                                       broadcast.attr.to = contact;
+                                                       send_to(contact, broadcast);
+                                                       --local host = jid.host(contact);
+                                                       --if hosts[host] and hosts[host].type == "local" then
+                                                               --local node, host = jid.split(contact);
+                                                               --if host[host].sessions[node]
+                                                               --local pres = st.presence { from = con
+                                                       --else
+                                                       --      probe.attr.to = contact;
+                                                       --      send_to(contact, probe);
+                                                       --end
+                                               end
+                                               
+                                               -- Probe for our contacts' presence
                                        end
-                                       log("warn", "Unhandled namespace: "..xmlns);
-                                       send(format("<iq type='error' id='%s'><error type='cancel'><service-unavailable/></error></iq>", stanza.attr.id));
                                end
-                       
-                       end
-                                                       -- Need to route stanza
-                       if stanza.attr.to and ((not hosts[stanza.attr.to]) or hosts[stanza.attr.to].type ~= "local") then
+                       else
+                       --end                           
+                       --if stanza.attr.to and ((not hosts[stanza.attr.to]) or hosts[stanza.attr.to].type ~= "local") then
+                               -- Need to route stanza
                                stanza.attr.from = session.username.."@"..session.host;
-                               session.send_to(stanza.attr.to, stanza);
+                               session:send_to(stanza.attr.to, stanza);
                        end
                end
 
diff --git a/core/xmlhandlers.lua b/core/xmlhandlers.lua
new file mode 100644 (file)
index 0000000..4d536ce
--- /dev/null
@@ -0,0 +1,92 @@
+
+require "util.stanza"
+
+local st = stanza;
+local tostring = tostring;
+local format = string.format;
+local m_random = math.random;
+local t_insert = table.insert;
+local t_remove = table.remove;
+local t_concat = table.concat;
+local t_concatall = function (t, sep) local tt = {}; for _, s in ipairs(t) do t_insert(tt, tostring(s)); end return t_concat(tt, sep); end
+
+local error = error;
+
+module "xmlhandlers"
+
+function init_xmlhandlers(session)
+               local ns_stack = { "" };
+               local curr_ns = "";
+               local curr_tag;
+               local chardata = {};
+               local xml_handlers = {};
+               local log = session.log;
+               local print = function (...) log("info", "xmlhandlers", t_concatall({...}, "\t")); end
+               
+               local send = session.send;
+               
+               local stanza
+               function xml_handlers:StartElement(name, attr)
+                       if stanza and #chardata > 0 then
+                               stanza:text(t_concat(chardata));
+                               print("Char data:", t_concat(chardata));
+                               chardata = {};
+                       end
+                       curr_ns,name = name:match("^(.+):(%w+)$");
+                       print("Tag received:", name, tostring(curr_ns));
+                       if not stanza then
+                               if session.notopen then
+                                       if name == "stream" then
+                                               session.host = attr.to or error("Client failed to specify destination hostname");
+                                               session.version = attr.version or 0;
+                                               session.streamid = m_random(1000000, 99999999);
+                                               print(session, session.host, "Client opened stream");
+                                               send("<?xml version='1.0'?>");
+                                               send(format("<stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' id='%s' from='%s' >", session.streamid, session.host));
+                                               --send("<stream:features>");
+                                               --send("<mechanism>PLAIN</mechanism>");
+                                               --send [[<register xmlns="http://jabber.org/features/iq-register"/> ]]
+                                               --send("</stream:features>");
+                                               log("info", "core", "Stream opened successfully");
+                                               session.notopen = nil;
+                                               return;
+                                       end
+                                       error("Client failed to open stream successfully");
+                               end
+                               if name ~= "iq" and name ~= "presence" and name ~= "message" then
+                                       error("Client sent invalid top-level stanza");
+                               end
+                               stanza = st.stanza(name, { to = attr.to, type = attr.type, id = attr.id, xmlns = curr_ns });
+                               curr_tag = stanza;
+                       else
+                               attr.xmlns = curr_ns;
+                               stanza:tag(name, attr);
+                       end
+               end
+               function xml_handlers:CharacterData(data)
+                       if stanza then
+                               t_insert(chardata, data);
+                       end
+               end
+               function xml_handlers:EndElement(name)
+                       curr_ns,name = name:match("^(.+):(%w+)$");
+                       --print("<"..name.."/>", tostring(stanza), tostring(#stanza.last_add < 1), tostring(stanza.last_add[#stanza.last_add].name));
+                       if (not stanza) or #stanza.last_add < 0 or (#stanza.last_add > 0 and name ~= stanza.last_add[#stanza.last_add].name) then error("XML parse error in client stream"); end
+                       if stanza and #chardata > 0 then
+                               stanza:text(t_concat(chardata));
+                               print("Char data:", t_concat(chardata));
+                               chardata = {};
+                       end
+                       -- Complete stanza
+                       print(name, tostring(#stanza.last_add));
+                       if #stanza.last_add == 0 then
+                               session.stanza_dispatch(stanza);
+                               stanza = nil;
+                       else
+                               stanza:up();
+                       end
+               end
+       return xml_handlers;
+end
+
+return init_xmlhandlers;
index cb6e03fd591d3da714db353d3928c4ee8e74a043..41d812bccad37bd8acdbb74924ec6b2bbb9a1db9 100644 (file)
--- a/main.lua
+++ b/main.lua
@@ -1,6 +1,6 @@
 require "luarocks.require"
 
-require "copas"
+server = require "server"
 require "socket"
 require "ssl"
 require "lxp"
@@ -10,8 +10,10 @@ function log(type, area, message)
 end
 
 require "core.stanza_dispatch"
+init_xmlhandlers = require "core.xmlhandlers"
 require "core.rostermanager"
 require "core.offlinemessage"
+require "core.usermanager"
 require "util.stanza"
 require "util.jid"
 
@@ -24,7 +26,7 @@ local format = string.format;
 local st = stanza;
 ------------------------------
 
-users = {};
+sessions = {};
 hosts =        { 
                        ["localhost"] =         {
                                                        type = "local";
@@ -40,236 +42,118 @@ hosts =   {
 
 local hosts, users = hosts, users;
 
-local ssl_ctx, msg = ssl.newcontext { mode = "server", protocol = "sslv23", key = "/home/matthew/ssl_cert/server.key",
+--local ssl_ctx, msg = ssl.newcontext { mode = "server", protocol = "sslv23", key = "/home/matthew/ssl_cert/server.key",
+--    certificate = "/home/matthew/ssl_cert/server.crt", capath = "/etc/ssl/certs", verify = "none", }
+--        
+--if not ssl_ctx then error("Failed to initialise SSL/TLS support: "..tostring(msg)); end
+
+
+local ssl_ctx = { mode = "server", protocol = "sslv23", key = "/home/matthew/ssl_cert/server.key",
     certificate = "/home/matthew/ssl_cert/server.crt", capath = "/etc/ssl/certs", verify = "none", }
-        
-if not ssl_ctx then error("Failed to initialise SSL/TLS support: "..tostring(msg)); end
 
 
 function connect_host(host)
        hosts[host] = { type = "remote", sendbuffer = {} };
 end
 
-function handler(conn)
-       local copas_receive, copas_send = copas.receive, copas.send;
-       local reqdata, sktmsg;
-       local session = { sendbuffer = { external = {} }, conn = conn, notopen = true, priority = 0 }
-
-
-       -- Logging functions --
-
-       local mainlog, log = log;
-       do
-               local conn_name = tostring(conn):match("%w+$");
-               log = function (type, area, message) mainlog(type, conn_name, message); end
-       end
-       local print = function (...) log("info", "core", t_concatall({...}, "\t")); end
-       session.log = log;
-
-       --      --      --
-
-       -- Send buffers --
-
-       local sendbuffer = session.sendbuffer;
-       local send = function (data) return t_insert(sendbuffer, tostring(data)); end;
-       local send_to =         function (to, stanza)
-                                       local node, host, resource = jid.split(to);
-                                       print("Routing stanza to "..to..":", node, host, resource);
-                                       if not hosts[host] then
-                                               print("   ...but host offline, establishing connection");
-                                               connect_host(host);
-                                               t_insert(hosts[host].sendbuffer, stanza); -- This will be sent when s2s connection succeeds                                     
-                                       elseif hosts[host].connected then
-                                               print("   ...putting in our external send buffer");
-                                               t_insert(sendbuffer.external, { node = node, host = host, resource = resource, data = stanza});
-                                               print("   ...there are now "..tostring(#sendbuffer.external).." stanzas in the external send buffer");
+local function send_to(session, to, stanza)
+       local node, host, resource = jid.split(to);
+       if not hosts[host] then
+               -- s2s
+       elseif hosts[host].type == "local" then
+               print("   ...is to a local user")
+               local destuser = hosts[host].sessions[node];
+               if destuser and destuser.sessions then
+                       if not destuser.sessions[resource] then
+                               local best_session;
+                               for resource, session in pairs(destuser.sessions) do
+                                       if not best_session then best_session = session;
+                                       elseif session.priority >= best_session.priority and session.priority >= 0 then
+                                               best_session = session;
                                        end
                                end
-       session.send, session.send_to = send, send_to;
-
-       --      --      --
-       print("Client connected");
-       conn = ssl.wrap(copas.wrap(conn), ssl_ctx);
-       
-       do
-               local succ, msg
-               conn:settimeout(15)
-               while not succ do
-                       succ, msg = conn:dohandshake()
-                       if not succ then
-                               print("SSL: "..tostring(msg));
-                               if msg == 'wantread' then
-                                       socket.select({conn}, nil)
-                               elseif msg == 'wantwrite' then
-                                       socket.select(nil, {conn})
+                               if not best_session then
+                                       offlinemessage.new(node, host, stanza);
                                else
-                                       -- other error
+                                       print("resource '"..resource.."' was not online, have chosen to send to '"..best_session.username.."@"..best_session.host.."/"..best_session.resource.."'");
+                                       resource = best_session.resource;
                                end
                        end
+                       if destuser.sessions[resource] == session then
+                               log("warn", "core", "Attempt to send stanza to self, dropping...");
+                       else
+                               print("...sending...", tostring(stanza));
+                               --destuser.sessions[resource].conn.write(tostring(data));
+                               print("   to conn ", destuser.sessions[resource].conn);
+                               destuser.sessions[resource].conn.write(tostring(stanza));
+                               print("...sent")
+                       end
+               elseif stanza.name == "message" then
+                       print("   ...will be stored offline");
+                       offlinemessage.new(node, host, stanza);
+               elseif stanza.name == "iq" then
+                       print("   ...is an iq");
+                       session.send(st.reply(stanza)
+                               :tag("error", { type = "cancel" })
+                                       :tag("service-unavailable", { xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas" }));
                end
+               print("   ...done routing");
        end
-       print("SSL handshake complete");
-       -- XML parser initialisation --
+end
 
-       local parser;
-       local stanza;
+function handler(conn, data, err)
+       local session = sessions[conn];
        
-       local stanza_dispatch = init_stanza_dispatcher(session);
+       if not session then
+               sessions[conn] = { conn = conn, notopen = true, priority = 0 };
+               session = sessions[conn];
 
-       local xml_handlers = {};
-       
-       do
-               local ns_stack = { "" };
-               local curr_ns = "";
-               local curr_tag;
-               function xml_handlers:StartElement(name, attr)
-                       curr_ns,name = name:match("^(.+):(%w+)$");
-                       print("Tag received:", name, tostring(curr_ns));
-                       if not stanza then
-                               if session.notopen then
-                                       if name == "stream" then
-                                               session.host = attr.to or error("Client failed to specify destination hostname");
-                                               session.version = attr.version or 0;
-                                               session.streamid = m_random(1000000, 99999999);
-                                               print(session, session.host, "Client opened stream");
-                                               send("<?xml version='1.0'?>");
-                                               send(format("<stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' id='%s' from='%s' >", session.streamid, session.host));
-                                               --send("<stream:features>");
-                                               --send("<mechanism>PLAIN</mechanism>");
-                                               --send [[<register xmlns="http://jabber.org/features/iq-register"/> ]]
-                                               --send("</stream:features>");
-                                               log("info", "core", "Stream opened successfully");
-                                               session.notopen = nil;
-                                               return;
-                                       end
-                                       error("Client failed to open stream successfully");
-                               end
-                               if name ~= "iq" and name ~= "presence" and name ~= "message" then
-                                       error("Client sent invalid top-level stanza");
-                               end
-                               stanza = st.stanza(name, { to = attr.to, type = attr.type, id = attr.id, xmlns = curr_ns });
-                               curr_tag = stanza;
-                       else
-                               attr.xmlns = curr_ns;
-                               stanza:tag(name, attr);
-                       end
-               end
-               function xml_handlers:CharacterData(data)
-                       if data:match("%S") then
-                               stanza:text(data);
-                       end
-               end
-               function xml_handlers:EndElement(name)
-                       curr_ns,name = name:match("^(.+):(%w+)$");
-                       --print("<"..name.."/>", tostring(stanza), tostring(#stanza.last_add < 1), tostring(stanza.last_add[#stanza.last_add].name));
-                       if (not stanza) or #stanza.last_add < 0 or (#stanza.last_add > 0 and name ~= stanza.last_add[#stanza.last_add].name) then error("XML parse error in client stream"); end
-                       -- Complete stanza
-                       print(name, tostring(#stanza.last_add));
-                       if #stanza.last_add == 0 then
-                               stanza_dispatch(stanza);
-                               stanza = nil;
-                       else
-                               stanza:up();
-                       end
-               end
---[[           function xml_handlers:StartNamespaceDecl(namespace)
-                       table.insert(ns_stack, namespace);
-                       curr_ns = namespace;
-                       log("debug", "parser", "Entering namespace "..tostring(curr_ns));
-               end
-               function xml_handlers:EndNamespaceDecl(namespace)
-                       table.remove(ns_stack);
-                       log("debug", "parser", "Leaving namespace "..tostring(curr_ns));
-                       curr_ns = ns_stack[#ns_stack];
-                       log("debug", "parser", "Entering namespace "..tostring(curr_ns));
+               -- Logging functions --
+
+               local mainlog, log = log;
+               do
+                       local conn_name = tostring(conn):match("%w+$");
+                       log = function (type, area, message) mainlog(type, conn_name, message); end
                end
-]]
-       end
-       parser = lxp.new(xml_handlers, ":");
+               local print = function (...) log("info", "core", t_concatall({...}, "\t")); end
+               session.log = log;
 
-       --      --      --
+               --      --      --
 
-       -- Main loop --
-       print "Receiving..."
-       reqdata = copas_receive(conn, 1);
-       print "Received"
-       while reqdata do
-               parser:parse(reqdata);
-               if #sendbuffer.external > 0 then
-                       -- Stanzas queued to go to other places, from us
-                       -- ie. other local users, or remote hosts that weren't connected before
-                       print(#sendbuffer.external.." stanzas queued for other recipients, sending now...");
-                       for n, packet in pairs(sendbuffer.external) do
-                               if not hosts[packet.host] then
-                                       connect_host(packet.host);
-                                       t_insert(hosts[packet.host].sendbuffer, packet.data);
-                               elseif hosts[packet.host].type == "local" then
-                                       print("   ...is to a local user")
-                                       local destuser = hosts[packet.host].sessions[packet.node];
-                                       if destuser and destuser.sessions then
-                                               if not destuser.sessions[packet.resource] then
-                                                       local best_resource;
-                                                       for resource, session in pairs(destuser.sessions) do
-                                                               if not best_session then best_session = session;
-                                                               elseif session.priority >= best_session.priority and session.priority >= 0 then
-                                                                       best_session = session;
-                                                               end
-                                                       end
-                                                       if not best_session then
-                                                               offlinemessage.new(packet.node, packet.host, packet.data);
-                                                       else
-                                                               print("resource '"..packet.resource.."' was not online, have chosen to send to '"..best_session.username.."@"..best_session.host.."/"..best_session.resource.."'");
-                                                               packet.resource = best_session.resource;
-                                                       end
-                                               end
-                                               if destuser.sessions[packet.resource] == session then
-                                                       log("warn", "core", "Attempt to send stanza to self, dropping...");
-                                               else
-                                                       print("...sending...");
-                                                       copas_send(destuser.sessions[packet.resource].conn, tostring(packet.data));
-                                                       print("...sent")
-                                               end
-                                       elseif packet.data.name == "message" then
-                                               print("   ...will be stored offline");
-                                               offlinemessage.new(packet.node, packet.host, packet.data);
-                                       elseif packet.data.name == "iq" then
-                                               print("   ...is an iq");
-                                               send(st.reply(packet.data)
-                                                       :tag("error", { type = "cancel" })
-                                                               :tag("service-unavailable", { xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas" }));
-                                       end
-                                       print("   ...removing from send buffer");
-                                       sendbuffer.external[n] = nil;
-                               end
-                       end
-               end
+               -- Send buffers --
+
+               local send = function (data) print("Sending...", tostring(data)); conn.write(tostring(data)); end;
+               session.send, session.send_to = send, send_to;
+
+                       print("Client connected");
                
-               if #sendbuffer > 0 then 
-                       for n, data in ipairs(sendbuffer) do
-                               print "Sending..."
-                               copas_send(conn, data);
-                               print "Sent"
-                               sendbuffer[n] = nil;
+                       session.stanza_dispatch = init_stanza_dispatcher(session);
+                       session.xml_handlers = init_xmlhandlers(session);
+                       session.parser = lxp.new(session.xml_handlers, ":");
+                       
+                       function session.disconnect(err)
+                               print("Disconnected: "..err);
                        end
                end
-               print "Receiving..."
-               repeat
-                       reqdata, sktmsg = copas_receive(conn, 1);
-                       if sktmsg == 'wantread' then
-                               print("Received... wantread");
-                               --socket.select({conn}, nil)
-                               --print("Socket ready now...");
-                       elseif sktmsg then
-                               print("Received socket message:", sktmsg);
-                       end
-               until reqdata or sktmsg == "closed";
-               print("Received", tostring(reqdata));
+       if data then
+               session.parser:parse(data);
        end
-       log("info", "core", "Client disconnected, connection closed");
+       
+       --log("info", "core", "Client disconnected, connection closed");
+end
+
+function disconnect(conn, err)
+       sessions[conn].disconnect(err);
 end
 
-server = socket.bind("*", 5223)
-assert(server, "Failed to bind to socket")
-copas.addserver(server, handler)
+print("ssl_ctx:", type(ssl_ctx));
+
+setmetatable(_G, { __index = function (t, k) print("WARNING: ATTEMPT TO READ A NIL GLOBAL!!!", k); error("Attempt to read a non-existent global. Naughty boy.", 2); end, __newindex = function (t, k, v) print("ATTEMPT TO SET A GLOBAL!!!!", tostring(k).." = "..tostring(v)); error("Attempt to set a global. Naughty boy.", 2); end }) --]][][[]][];
+
+
+local protected_handler = function (...) local success, ret = pcall(handler, ...); if not success then print("ERROR on "..tostring((select(1, ...)))..": "..ret); end end;
+
+print( server.add( { listener = protected_handler, disconnect = disconnect }, 5222, "*", 1, nil ) )    -- server.add will send a status message
+print( server.add( { listener = protected_handler, disconnect = disconnect }, 5223, "*", 1, ssl_ctx ) )    -- server.add will send a status message
 
-copas.loop();
+server.loop();
diff --git a/server.lua b/server.lua
new file mode 100644 (file)
index 0000000..0f73131
--- /dev/null
@@ -0,0 +1,611 @@
+--[[\r
+\r
+        server.lua by blastbeat\r
+\r
+        - this script contains the server loop of the program\r
+        - other scripts can reg a server here\r
+\r
+]]--\r
+\r
+----------------------------------// DECLARATION //--\r
+\r
+--// constants //--\r
+\r
+local STAT_UNIT = 1 / ( 1024 * 1024 )    -- mb\r
+\r
+--// lua functions //--\r
+\r
+local function use( what ) return _G[ what ] end\r
+\r
+local type = use "type"\r
+local pairs = use "pairs"\r
+local ipairs = use "ipairs"\r
+local tostring = use "tostring"\r
+local collectgarbage = use "collectgarbage"\r
+\r
+--// lua libs //--\r
+\r
+local table = use "table"\r
+local coroutine = use "coroutine"\r
+\r
+--// lua lib methods //--\r
+\r
+local table_concat = table.concat\r
+local table_remove = table.remove\r
+local string_sub = use'string'.sub\r
+local coroutine_wrap = coroutine.wrap\r
+local coroutine_yield = coroutine.yield\r
+local print = print;\r
+local out_put = function () end --print;\r
+local out_error = print;\r
+\r
+--// extern libs //--\r
+\r
+local luasec = require "ssl"\r
+local luasocket = require "socket"\r
+\r
+--// extern lib methods //--\r
+\r
+local ssl_wrap = ( luasec and luasec.wrap )\r
+local socket_bind = luasocket.bind\r
+local socket_select = luasocket.select\r
+local ssl_newcontext = ( luasec and luasec.newcontext )\r
+\r
+--// functions //--\r
+\r
+local loop\r
+local stats\r
+local addtimer\r
+local closeall\r
+local addserver\r
+local firetimer\r
+local closesocket\r
+local removesocket\r
+local wrapserver\r
+local wraptcpclient\r
+local wrapsslclient\r
+\r
+--// tables //--\r
+\r
+local listener\r
+local readlist\r
+local writelist\r
+local socketlist\r
+local timelistener\r
+\r
+--// simple data types //--\r
+\r
+local _\r
+local readlen = 0    -- length of readlist\r
+local writelen = 0    -- lenght of writelist\r
+\r
+local sendstat= 0\r
+local receivestat = 0\r
+\r
+----------------------------------// DEFINITION //--\r
+\r
+listener = { }    -- key = port, value = table\r
+readlist = { }    -- array with sockets to read from\r
+writelist = { }    -- arrary with sockets to write to\r
+socketlist = { }    -- key = socket, value = wrapped socket\r
+timelistener = { }\r
+\r
+stats = function( )\r
+    return receivestat, sendstat\r
+end\r
+\r
+wrapserver = function( listener, socket, ip, serverport, mode, sslctx )    -- this function wraps a server\r
+\r
+    local dispatch, disconnect = listener.listener, listener.disconnect    -- dangerous\r
+\r
+    local wrapclient, err\r
+\r
+    if sslctx then\r
+        if not ssl_newcontext then\r
+            return nil, "luasec not found"\r
+--        elseif not cfg_get "use_ssl" then\r
+--            return nil, "ssl is deactivated"\r
+        end\r
+        if type( sslctx ) ~= "table" then\r
+            out_error "server.lua: wrong server sslctx"\r
+            return nil, "wrong server sslctx"\r
+        end\r
+        sslctx, err = ssl_newcontext( sslctx )\r
+        if not sslctx then\r
+            err = err or "wrong sslctx parameters"\r
+            out_error( "server.lua: ", err )\r
+            return nil, err\r
+        end\r
+        wrapclient = wrapsslclient\r
+    else\r
+        wrapclient = wraptcpclient\r
+    end\r
+\r
+    local accept = socket.accept\r
+    local close = socket.close\r
+\r
+    --// public methods of the object //--    \r
+\r
+    local handler = { }\r
+\r
+    handler.shutdown = function( ) end\r
+\r
+    --[[handler.listener = function( data, err )\r
+        return ondata( handler, data, err )\r
+    end]]\r
+    handler.ssl = function( )\r
+        return sslctx and true or false\r
+    end\r
+    handler.close = function( closed )\r
+        _ = not closed and close( socket )\r
+        writelen = removesocket( writelist, socket, writelen )\r
+        readlen = removesocket( readlist, socket, readlen )\r
+        socketlist[ socket ] = nil\r
+        handler = nil\r
+    end\r
+    handler.ip = function( )\r
+        return ip\r
+    end\r
+    handler.serverport = function( )\r
+        return serverport\r
+    end\r
+    handler.socket = function( )\r
+        return socket\r
+    end\r
+    handler.receivedata = function( )\r
+        local client, err = accept( socket )    -- try to accept\r
+        if client then\r
+            local ip, clientport = client:getpeername( )\r
+            client:settimeout( 0 )\r
+            local handler, client, err = wrapclient( listener, client, ip, serverport, clientport, mode, sslctx )    -- wrap new client socket\r
+            if err then    -- error while wrapping ssl socket\r
+                return false\r
+            end\r
+            out_put( "server.lua: accepted new client connection from ", ip, ":", clientport )\r
+            return dispatch( handler )\r
+        elseif err then    -- maybe timeout or something else\r
+            out_put( "server.lua: error with new client connection: ", err )\r
+            return false\r
+        end\r
+    end\r
+    return handler\r
+end\r
+\r
+wrapsslclient = function( listener, socket, ip, serverport, clientport, mode, sslctx )    -- this function wraps a ssl cleint\r
+\r
+    local dispatch, disconnect = listener.listener, listener.disconnect\r
+\r
+    --// transform socket to ssl object //--\r
+\r
+    local err\r
+    socket, err = ssl_wrap( socket, sslctx )    -- wrap socket\r
+    if err then\r
+        out_put( "server.lua: ssl error: ", err )\r
+        return nil, nil, err    -- fatal error\r
+    end\r
+    socket:settimeout( 0 )\r
+\r
+    --// private closures of the object //--\r
+\r
+    local writequeue = { }    -- buffer for messages to send\r
+\r
+    local eol   -- end of buffer\r
+\r
+    local sstat, rstat = 0, 0\r
+\r
+    --// local import of socket methods //--\r
+\r
+    local send = socket.send\r
+    local receive = socket.receive\r
+    local close = socket.close\r
+    --local shutdown = socket.shutdown\r
+\r
+    --// public methods of the object //--\r
+\r
+    local handler = { }\r
+\r
+    handler.getstats = function( )\r
+        return rstat, sstat\r
+    end\r
+\r
+    handler.listener = function( data, err )\r
+        return listener( handler, data, err )\r
+    end\r
+    handler.ssl = function( )\r
+        return true\r
+    end\r
+    handler.send = function( _, data, i, j )\r
+            return send( socket, data, i, j )\r
+    end\r
+    handler.receive = function( pattern, prefix )\r
+            return receive( socket, pattern, prefix )\r
+    end\r
+    handler.shutdown = function( pattern )\r
+        --return shutdown( socket, pattern )\r
+    end\r
+    handler.close = function( closed )\r
+        close( socket )\r
+        writelen = ( eol and removesocket( writelist, socket, writelen ) ) or writelen\r
+        readlen = removesocket( readlist, socket, readlen )\r
+        socketlist[ socket ] = nil\r
+        out_put "server.lua: closed handler and removed socket from list"\r
+    end\r
+    handler.ip = function( )\r
+        return ip\r
+    end\r
+    handler.serverport = function( )\r
+        return serverport\r
+    end\r
+    handler.clientport = function( ) \r
+        return clientport\r
+    end\r
+\r
+    handler.write = function( data )\r
+        if not eol then\r
+            writelen = writelen + 1\r
+            writelist[ writelen ] = socket\r
+            eol = 0\r
+        end\r
+        eol = eol + 1\r
+        writequeue[ eol ] = data\r
+    end\r
+    handler.writequeue = function( )\r
+        return writequeue\r
+    end\r
+    handler.socket = function( )\r
+        return socket\r
+    end\r
+    handler.mode = function( )\r
+        return mode\r
+    end\r
+    handler._receivedata = function( )\r
+        local data, err, part = receive( socket, mode )    -- receive data in "mode"\r
+        if not err or ( err == "timeout" or err == "wantread" ) then    -- received something\r
+            local data = data or part or ""\r
+            local count = #data * STAT_UNIT\r
+            rstat = rstat + count\r
+            receivestat = receivestat + count\r
+            out_put( "server.lua: read data '", data, "', error: ", err )\r
+            return dispatch( handler, data, err )\r
+        else    -- connections was closed or fatal error\r
+            out_put( "server.lua: client ", ip, ":", clientport, " error: ", err )\r
+            handler.close( )\r
+            disconnect( handler, err )\r
+            writequeue = nil\r
+            handler = nil\r
+            return false\r
+        end\r
+    end\r
+    handler._dispatchdata = function( )    -- this function writes data to handlers\r
+        local buffer = table_concat( writequeue, "", 1, eol )\r
+        local succ, err, byte = send( socket, buffer )\r
+        local count = ( succ or 0 ) * STAT_UNIT\r
+        sstat = sstat + count\r
+        sendstat = sendstat + count\r
+        out_put( "server.lua: sended '", buffer, "', bytes: ", succ, ", error: ", err, ", part: ", byte, ", to: ", ip, ":", clientport )\r
+        if succ then    -- sending succesful\r
+            --writequeue = { }\r
+            eol = nil\r
+            writelen = removesocket( writelist, socket, writelen )    -- delete socket from writelist\r
+            return true\r
+        elseif byte and ( err == "timeout" or err == "wantwrite" ) then    -- want write\r
+            buffer = string_sub( buffer, byte + 1, -1 )    -- new buffer\r
+            writequeue[ 1 ] = buffer    -- insert new buffer in queue\r
+            eol = 1\r
+            return true\r
+        else    -- connection was closed during sending or fatal error\r
+            out_put( "server.lua: client ", ip, ":", clientport, " error: ", err )\r
+            handler.close( )\r
+            disconnect( handler, err )\r
+            writequeue = nil\r
+            handler = nil\r
+            return false\r
+        end\r
+    end\r
+\r
+    -- // COMPAT // --\r
+\r
+    handler.getIp = handler.ip\r
+    handler.getPort = handler.clientport\r
+\r
+    --// handshake //--\r
+\r
+    local wrote\r
+\r
+    handler.handshake = coroutine_wrap( function( client )\r
+            local err\r
+            for i = 1, 10 do    -- 10 handshake attemps\r
+                _, err = client:dohandshake( )\r
+                if not err then\r
+                    out_put( "server.lua: ssl handshake done" )\r
+                    writelen = ( wrote and removesocket( writelist, socket, writelen ) ) or writelen\r
+                    handler.receivedata = handler._receivedata    -- when handshake is done, replace the handshake function with regular functions\r
+                    handler.dispatchdata = handler._dispatchdata\r
+                    return dispatch( handler )\r
+                else\r
+                    out_put( "server.lua: error during ssl handshake: ", err )\r
+                    if err == "wantwrite" then\r
+                        if wrote == nil then\r
+                            writelen = writelen + 1\r
+                            writelist[ writelen ] = client\r
+                            wrote = true\r
+                        end\r
+                    end\r
+                    coroutine_yield( handler, nil, err )    -- handshake not finished\r
+                end\r
+            end\r
+            _ = err ~= "closed" and close( socket )\r
+            handler.close( )\r
+            disconnect( handler, err )\r
+            writequeue = nil\r
+            handler = nil\r
+            return false    -- handshake failed\r
+        end\r
+    )\r
+    handler.receivedata = handler.handshake\r
+    handler.dispatchdata = handler.handshake\r
+\r
+    handler.handshake( socket )    -- do handshake\r
+\r
+    socketlist[ socket ] = handler\r
+    readlen = readlen + 1\r
+    readlist[ readlen ] = socket\r
+\r
+    return handler, socket\r
+end\r
+\r
+wraptcpclient = function( listener, socket, ip, serverport, clientport, mode )    -- this function wraps a socket\r
+\r
+    local dispatch, disconnect = listener.listener, listener.disconnect\r
+\r
+    --// private closures of the object //--\r
+\r
+    local writequeue = { }    -- list for messages to send\r
+\r
+    local eol\r
+\r
+    local rstat, sstat = 0, 0\r
+\r
+    --// local import of socket methods //--\r
+\r
+    local send = socket.send\r
+    local receive = socket.receive\r
+    local close = socket.close\r
+    local shutdown = socket.shutdown\r
+\r
+    --// public methods of the object //--\r
+\r
+    local handler = { }\r
+\r
+    handler.getstats = function( )\r
+        return rstat, sstat\r
+    end\r
+\r
+    handler.listener = function( data, err )\r
+        return listener( handler, data, err )\r
+    end\r
+    handler.ssl = function( )\r
+        return false\r
+    end\r
+    handler.send = function( _, data, i, j )\r
+            return send( socket, data, i, j )\r
+    end\r
+    handler.receive = function( pattern, prefix )\r
+            return receive( socket, pattern, prefix )\r
+    end\r
+    handler.shutdown = function( pattern )\r
+        return shutdown( socket, pattern )\r
+    end\r
+    handler.close = function( closed )\r
+        _ = not closed and shutdown( socket )\r
+        _ = not closed and close( socket )\r
+        writelen = ( eol and removesocket( writelist, socket, writelen ) ) or writelen\r
+        readlen = removesocket( readlist, socket, readlen )\r
+        socketlist[ socket ] = nil\r
+        out_put "server.lua: closed handler and removed socket from list"\r
+    end\r
+    handler.ip = function( )\r
+        return ip\r
+    end\r
+    handler.serverport = function( )\r
+        return serverport\r
+    end\r
+    handler.clientport = function( ) \r
+        return clientport\r
+    end\r
+    handler.write = function( data )\r
+        if not eol then\r
+            writelen = writelen + 1\r
+            writelist[ writelen ] = socket\r
+            eol = 0\r
+        end\r
+        eol = eol + 1\r
+        writequeue[ eol ] = data\r
+    end\r
+    handler.writequeue = function( )\r
+        return writequeue\r
+    end\r
+    handler.socket = function( )\r
+        return socket\r
+    end\r
+    handler.mode = function( )\r
+        return mode\r
+    end\r
+    handler.receivedata = function( )\r
+        local data, err, part = receive( socket, mode )    -- receive data in "mode"\r
+        if not err or ( err == "timeout" or err == "wantread" ) then    -- received something\r
+            local data = data or part or ""\r
+            local count = #data * STAT_UNIT\r
+            rstat = rstat + count\r
+            receivestat = receivestat + count\r
+            out_put( "server.lua: read data '", data, "', error: ", err )\r
+            return dispatch( handler, data, err )\r
+        else    -- connections was closed or fatal error\r
+            out_put( "server.lua: client ", ip, ":", clientport, " error: ", err )\r
+            handler.close( )\r
+            disconnect( handler, err )\r
+            writequeue = nil\r
+            handler = nil\r
+            return false\r
+        end\r
+    end\r
+    handler.dispatchdata = function( )    -- this function writes data to handlers\r
+        local buffer = table_concat( writequeue, "", 1, eol )\r
+        local succ, err, byte = send( socket, buffer )\r
+        local count = ( succ or 0 ) * STAT_UNIT\r
+        sstat = sstat + count\r
+        sendstat = sendstat + count\r
+        out_put( "server.lua: sended '", buffer, "', bytes: ", succ, ", error: ", err, ", part: ", byte, ", to: ", ip, ":", clientport )\r
+        if succ then    -- sending succesful\r
+            --writequeue = { }\r
+            eol = nil\r
+            writelen = removesocket( writelist, socket, writelen )    -- delete socket from writelist\r
+            return true\r
+        elseif byte and ( err == "timeout" or err == "wantwrite" ) then    -- want write\r
+            buffer = string_sub( buffer, byte + 1, -1 )    -- new buffer\r
+            writequeue[ 1 ] = buffer    -- insert new buffer in queue\r
+            eol = 1\r
+            return true\r
+        else    -- connection was closed during sending or fatal error\r
+            out_put( "server.lua: client ", ip, ":", clientport, " error: ", err )\r
+            handler.close( )\r
+            disconnect( handler, err )\r
+            writequeue = nil\r
+            handler = nil\r
+            return false\r
+        end\r
+    end\r
+\r
+    -- // COMPAT // --\r
+\r
+    handler.getIp = handler.ip\r
+    handler.getPort = handler.clientport\r
+\r
+    socketlist[ socket ] = handler\r
+    readlen = readlen + 1\r
+    readlist[ readlen ] = socket\r
+\r
+    return handler, socket\r
+end\r
+\r
+addtimer = function( listener )\r
+    timelistener[ #timelistener + 1 ] = listener\r
+end\r
+\r
+firetimer = function( listener )\r
+    for i, listener in ipairs( timelistener ) do\r
+        listener( )\r
+    end\r
+end\r
+\r
+addserver = function( listeners, port, addr, mode, sslctx )    -- this function provides a way for other scripts to reg a server\r
+    local err\r
+    if type( listeners ) ~= "table" then\r
+        err = "invalid listener table"\r
+    else\r
+        for name, func in pairs( listeners ) do\r
+            if type( func ) ~= "function" then\r
+                err = "invalid listener function"\r
+                break\r
+            end\r
+        end\r
+    end\r
+    if not type( port ) == "number" or not ( port >= 0 and port <= 65535 ) then\r
+        err = "invalid port"\r
+    elseif listener[ port ] then\r
+        err=  "listeners on port '" .. port .. "' already exist"\r
+    elseif sslctx and not luasec then\r
+        err = "luasec not found"\r
+    end\r
+    if err then\r
+        out_error( "server.lua: ", err )\r
+        return nil, err\r
+    end\r
+    addr = addr or "*"\r
+    local server, err = socket_bind( addr, port )\r
+    if err then\r
+        out_error( "server.lua: ", err )\r
+        return nil, err\r
+    end\r
+    local handler, err = wrapserver( listeners, server, addr, port, mode, sslctx )    -- wrap new server socket\r
+    if not handler then\r
+        server:close( )\r
+        return nil, err\r
+    end\r
+    server:settimeout( 0 )\r
+    readlen = readlen + 1\r
+    readlist[ readlen ] = server\r
+    listener[ port ] = listeners\r
+    socketlist[ server ] = handler\r
+    out_put( "server.lua: new server listener on ", addr, ":", port )\r
+    return true\r
+end\r
+\r
+removesocket = function( tbl, socket, len )    -- this function removes sockets from a list\r
+    for i, target in ipairs( tbl ) do\r
+        if target == socket then\r
+            len = len - 1\r
+            table_remove( tbl, i )\r
+            return len\r
+        end\r
+    end\r
+    return len\r
+end\r
+\r
+closeall = function( )\r
+    for _, handler in pairs( socketlist ) do\r
+        handler.shutdown( )\r
+        handler.close( )\r
+        socketlist[ _ ] = nil\r
+    end\r
+    writelist, readlist, socketlist = { }, { }, { }\r
+end\r
+\r
+closesocket = function( socket )\r
+    writelen = removesocket( writelist, socket, writelen )\r
+    readlen = removesocket( readlist, socket, readlen )\r
+    socketlist[ socket ] = nil\r
+    socket:close( )\r
+end\r
+\r
+loop = function( )    -- this is the main loop of the program\r
+    --signal_set( "hub", "run" )\r
+    repeat\r
+        local read, write, err = socket_select( readlist, writelist, 1 )    -- 1 sec timeout, nice for timers\r
+        for i, socket in ipairs( write ) do    -- send data waiting in writequeues\r
+            local handler = socketlist[ socket ]\r
+            if handler then\r
+                handler.dispatchdata( )\r
+            else\r
+                closesocket( socket )\r
+                out_put "server.lua: found no handler and closed socket (writelist)"    -- this should not happen\r
+            end\r
+        end\r
+        for i, socket in ipairs( read ) do    -- receive data\r
+            local handler = socketlist[ socket ]\r
+            if handler then\r
+                handler.receivedata( )\r
+            else\r
+                closesocket( socket )\r
+                out_put "server.lua: found no handler and closed socket (readlist)"    -- this can happen\r
+            end\r
+        end\r
+        firetimer( )\r
+        --collectgarbage "collect"\r
+    until false --signal_get "hub" ~= "run"\r
+    return --signal_get "hub"\r
+end\r
+\r
+----------------------------------// BEGIN //--\r
+\r
+----------------------------------// PUBLIC INTERFACE //--\r
+\r
+return {\r
+\r
+    add = addserver,\r
+    loop = loop,\r
+    stats = stats,\r
+    closeall = closeall,\r
+    addtimer = addtimer,\r
+\r
+}\r
index 88d0609f9d26839f88f6a3faf3e39502d38ce17e..f41ba6999f10e1b03baca567f72efd23db909e33 100644 (file)
@@ -1,10 +1,11 @@
-local t_insert  =   table.insert;
-local t_remove  =   table.remove;
-local format    =  string.format;
-local tostring  =       tostring;
-local setmetatable= setmetatable;
-local pairs     =          pairs;
-local ipairs    =         ipairs;
+local t_insert      =  table.insert;
+local t_remove      =  table.remove;
+local format        = string.format;
+local tostring      =      tostring;
+local setmetatable  =  setmetatable;
+local pairs         =         pairs;
+local ipairs        =        ipairs;
+local type          =          type;
 
 module "stanza"
 
@@ -12,7 +13,7 @@ stanza_mt = {};
 stanza_mt.__index = stanza_mt;
 
 function stanza(name, attr)
-       local stanza = { name = name, attr = attr or {}, last_add = {}};
+       local stanza = { name = name, attr = attr or {}, tags = {}, last_add = {}};
        return setmetatable(stanza, stanza_mt);
 end
 
@@ -46,6 +47,9 @@ function stanza_mt:up()
 end
 
 function stanza_mt:add_child(child)
+       if type(child) == "table" then
+               t_insert(self.tags, child);
+       end
        t_insert(self, child);
 end
 
@@ -55,6 +59,16 @@ function stanza_mt:child_with_name(name)
        end
 end
 
+function stanza_mt:children()
+       local i = 0;
+       return function (a)
+                       i = i + 1
+                       local v = a[i]
+                       if v then return v; end
+               end, self, i;
+                                           
+end
+
 function stanza_mt.__tostring(t)
        local children_text = "";
        for n, child in ipairs(t) do
@@ -63,14 +77,14 @@ function stanza_mt.__tostring(t)
 
        local attr_string = "";
        if t.attr then
-               for k, v in pairs(t.attr) do attr_string = attr_string .. format(" %s='%s'", k, tostring(v)); end
+               for k, v in pairs(t.attr) do if type(k) == "string" then attr_string = attr_string .. format(" %s='%s'", k, tostring(v)); end end
        end
 
        return format("<%s%s>%s</%s>", t.name, attr_string, children_text, t.name);
 end
 
 function stanza_mt.__add(s1, s2)
-       return s:add_child(s2);
+       return s1:add_child(s2);
 end