Merge with albert and waqas
authorMatthew Wild <mwild1@gmail.com>
Sat, 8 Aug 2009 21:09:59 +0000 (22:09 +0100)
committerMatthew Wild <mwild1@gmail.com>
Sat, 8 Aug 2009 21:09:59 +0000 (22:09 +0100)
14 files changed:
core/modulemanager.lua
core/usermanager.lua
net/xmppclient_listener.lua
net/xmppserver_listener.lua
plugins/mod_console.lua
plugins/mod_muc.lua
plugins/mod_saslauth.lua
plugins/mod_xmlrpc.lua
prosody
tools/ejabberdsql2prosody.lua [new file with mode: 0644]
util/broadcast.lua [new file with mode: 0644]
util/helpers.lua [new file with mode: 0644]
util/pubsub.lua [deleted file]
util/sasl.lua

index 0c9ef581a96368e36416ebf794c6ee641b7befa1..c2e6e68e4760f236f49d11583436f8707106d1dd 100644 (file)
@@ -418,6 +418,10 @@ function api:require(lib)
        return f();
 end
 
+function api:get_option(name, default_value)
+       return config.get(self.host, self.name, name) or config.get(self.host, "core", name) or default_value;
+end
+
 --------------------------------------------------------------------
 
 local actions = {};
index bd7772cae8469b1dc567798ac0365b2b976b46cc..6c36fa29d13b8f7bfc4bf9baa6ed4df27cb673a7 100644 (file)
@@ -1,7 +1,7 @@
 -- Prosody IM
 -- Copyright (C) 2008-2009 Matthew Wild
 -- Copyright (C) 2008-2009 Waqas Hussain
--- 
+--
 -- This project is MIT/X11 licensed. Please see the
 -- COPYING file in the source package for more information.
 --
@@ -23,6 +23,7 @@ module "usermanager"
 function validate_credentials(host, username, password, method)
        log("debug", "User '%s' is being validated", username);
        local credentials = datamanager.load(username, host, "accounts") or {};
+
        if method == nil then method = "PLAIN"; end
        if method == "PLAIN" and credentials.password then -- PLAIN, do directly
                if password == credentials.password then
@@ -30,7 +31,7 @@ function validate_credentials(host, username, password, method)
                else
                        return nil, "Auth failed. Invalid username or password.";
                end
-       end
+  end
        -- must do md5
        -- make credentials md5
        local pwd = credentials.password;
@@ -49,6 +50,10 @@ function validate_credentials(host, username, password, method)
        end
 end
 
+function get_password(username, host)
+  return (datamanager.load(username, host, "accounts") or {}).password
+end
+
 function user_exists(username, host)
        return datamanager.load(username, host, "accounts") ~= nil; -- FIXME also check for empty credentials
 end
@@ -58,13 +63,11 @@ function create_user(username, password, host)
 end
 
 function get_supported_methods(host)
-       local methods = {["PLAIN"] = true}; -- TODO this should be taken from the config
-       methods["DIGEST-MD5"] = true;
-       return methods;
+       return {["PLAIN"] = true, ["DIGEST-MD5"] = true}; -- TODO this should be taken from the config
 end
 
 function is_admin(jid)
-       local admins = config.get("*", "core", "admins") or {};
+       local admins = config.get("*", "core", "admins");
        if type(admins) == "table" then
                jid = jid_bare(jid);
                for _,admin in ipairs(admins) do
index ce7788c76d97d70286d6a1d7ecad61d99719f576..dcc561f373dd844af220b04382a3d472b7dc06b6 100644 (file)
@@ -61,6 +61,7 @@ local function session_reset_stream(session)
                function session.data(conn, data)
                        local ok, err = parser:parse(data);
                        if ok then return; end
+                       log("debug", "Received invalid XML (%s) %d bytes: %s", tostring(err), #data, data:sub(1, 300):gsub("[\r\n]+", " "));
                        session:close("xml-not-well-formed");
                end
                
@@ -100,7 +101,7 @@ local function session_close(session, reason)
                end
                session.send("</stream:stream>");
                session.conn.close();
-               xmppclient.disconnect(session.conn, (reason and reason.condition) or reason or "session closed");
+               xmppclient.disconnect(session.conn, (reason and (reason.text or reason.condition)) or reason or "session closed");
        end
 end
 
index 81d26526db0a523f3aa721c8a9b5bb33136eea12..1f27d841721cd4b6a1f5b5fabb18c1cb14405d20 100644 (file)
@@ -61,6 +61,7 @@ local function session_reset_stream(session)
                function session.data(conn, data)
                        local ok, err = parser:parse(data);
                        if ok then return; end
+                       log("debug", "Received invalid XML (%s) %d bytes: %s", tostring(err), #data, data:sub(1, 300):gsub("[\r\n]+", " "));
                        session:close("xml-not-well-formed");
                end
                
index a3ed94999abe906ce3085d096edf8e9497822f1b..367c46b80608d1138d5fea6027a61178e570b125 100644 (file)
@@ -70,6 +70,9 @@ function console_listener.listener(conn, data)
                        if data:match("^>") then
                                data = data:gsub("^>", "");
                                useglobalenv = true;
+                       elseif data == "\004" then
+                               commands["bye"](session, data);
+                               return;
                        else
                                local command = data:lower();
                                command = data:match("^%w+") or data:match("%p");
@@ -205,7 +208,8 @@ end
 -- Anything in def_env will be accessible within the session as a global variable
 
 def_env.server = {};
-function def_env.server:reload()
+
+function def_env.server:insane_reload()
        prosody.unlock_globals();
        dofile "prosody"
        prosody = _G.prosody;
@@ -230,6 +234,11 @@ function def_env.server:uptime()
                minutes, (minutes ~= 1 and "s") or "", os.date("%c", prosody.start_time));
 end
 
+function def_env.server:shutdown(reason)
+       prosody.shutdown(reason);
+       return true, "Shutdown initiated";
+end
+
 def_env.module = {};
 
 local function get_hosts_set(hosts, module)
@@ -333,6 +342,11 @@ function def_env.config:get(host, section, key)
        return true, tostring(config_get(host, section, key));
 end
 
+function def_env.config:reload()
+       local ok, err = prosody.reload_config();
+       return ok, (ok and "Config reloaded (you may need to reload modules to take effect)") or tostring(err);
+end
+
 def_env.hosts = {};
 function def_env.hosts:list()
        for host, host_session in pairs(hosts) do
@@ -359,10 +373,19 @@ end
 
 function def_env.c2s:show(match_jid)
        local print, count = self.session.print, 0;
-       show_c2s(function (jid)
+       show_c2s(function (jid, session)
                if (not match_jid) or jid:match(match_jid) then
                        count = count + 1;
-                       print(jid);
+                       local status, priority = "unavailable", tostring(session.priority or "-");
+                       if session.presence then
+                               status = session.presence:child_with_name("show");
+                               if status then
+                                       status = status:get_text() or "[invalid!]";
+                               else
+                                       status = "available";
+                               end
+                       end
+                       print(jid.." - "..status.."("..priority..")");
                end             
        end);
        return true, "Total: "..count.." clients";
index e99ef83c0adab6f39a69d05b9e7036027750b5d3..b38468ea3151dabe3058800fc93bd057b7f84667 100644 (file)
@@ -76,6 +76,8 @@ component = register_component(muc_host, function(origin, stanza)
        handle_to_domain(origin, stanza);
 end);
 
+prosody.hosts[module:get_host()].muc = { rooms = rooms };
+
 module.unload = function()
        deregister_component(muc_host);
 end
@@ -84,4 +86,5 @@ module.save = function()
 end
 module.restore = function(data)
        rooms = data.rooms or {};
+       prosody.hosts[module:get_host()].muc = { rooms = rooms };
 end
index 8d1e05298bd817de2b42dae9ff3a233dcf886c45..8d3b4ae40133be814cc6dbb7b2d408df7f161d46 100644 (file)
@@ -1,7 +1,7 @@
 -- Prosody IM
 -- Copyright (C) 2008-2009 Matthew Wild
 -- Copyright (C) 2008-2009 Waqas Hussain
--- 
+--
 -- This project is MIT/X11 licensed. Please see the
 -- COPYING file in the source package for more information.
 --
@@ -15,6 +15,9 @@ local base64 = require "util.encodings".base64;
 
 local datamanager_load = require "util.datamanager".load;
 local usermanager_validate_credentials = require "core.usermanager".validate_credentials;
+local usermanager_get_supported_methods = require "core.usermanager".get_supported_methods;
+local usermanager_user_exists = require "core.usermanager".user_exists;
+local usermanager_get_password = require "core.usermanager".get_password;
 local t_concat, t_insert = table.concat, table.insert;
 local tostring = tostring;
 local jid_split = require "util.jid".split
@@ -57,25 +60,35 @@ local function handle_status(session, status)
                        session.sasl_handler = nil;
                        session:reset_stream();
                        return;
-               end 
+               end
                sm_make_authenticated(session, session.sasl_handler.username);
                session.sasl_handler = nil;
                session:reset_stream();
        end
 end
 
-local function password_callback(node, hostname, realm, mechanism, decoder)
-       local password = (datamanager_load(node, hostname, "accounts") or {}).password; -- FIXME handle hashed passwords
-       local func = function(x) return x; end;
-       if password then
-               if mechanism == "PLAIN" then
-                       return func, password;
-               elseif mechanism == "DIGEST-MD5" then
-                       if decoder then node, realm, password = decoder(node), decoder(realm), decoder(password); end
+local function credentials_callback(mechanism, ...)
+       if mechanism == "PLAIN" then
+               local username, hostname, password = ...;
+               local response = usermanager_validate_credentials(hostname, username, password, mechanism);
+               if response == nil then
+                       return false;
+               else
+                       return response;
+               end
+       elseif mechanism == "DIGEST-MD5" then
+               function func(x) return x; end
+               local node, domain, realm, decoder = ...;
+               local password = usermanager_get_password(node, domain);
+               if password then
+                       if decoder then
+                               node, realm, password = decoder(node), decoder(realm), decoder(password);
+                       end
                        return func, md5(node..":"..realm..":"..password);
+               else
+                       return func, nil;
                end
        end
-       return func, nil;
 end
 
 local function sasl_handler(session, stanza)
@@ -88,7 +101,7 @@ local function sasl_handler(session, stanza)
                elseif stanza.attr.mechanism == "ANONYMOUS" then
                        return session.send(build_reply("failure", "mechanism-too-weak"));
                end
-               session.sasl_handler = new_sasl(stanza.attr.mechanism, session.host, password_callback);
+               session.sasl_handler = new_sasl(stanza.attr.mechanism, session.host, credentials_callback);
                if not session.sasl_handler then
                        return session.send(build_reply("failure", "invalid-mechanism"));
                end
@@ -107,7 +120,7 @@ local function sasl_handler(session, stanza)
        end
        local status, ret, err_msg = session.sasl_handler:feed(text);
        handle_status(session, status);
-       local s = build_reply(status, ret, err_msg); 
+       local s = build_reply(status, ret, err_msg);
        log("debug", "sasl reply: %s", tostring(s));
        session.send(s);
 end
@@ -119,8 +132,8 @@ module:add_handler("c2s_unauthed", "response", xmlns_sasl, sasl_handler);
 local mechanisms_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-sasl' };
 local bind_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-bind' };
 local xmpp_session_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-session' };
-module:add_event_hook("stream-features", 
-               function (session, features)                                                                                            
+module:add_event_hook("stream-features",
+               function (session, features)
                        if not session.username then
                                if secure_auth_only and not session.secure then
                                        return;
@@ -130,8 +143,10 @@ module:add_event_hook("stream-features",
                                        if config.get(session.host or "*", "core", "anonymous_login") then
                                                features:tag("mechanism"):text("ANONYMOUS"):up();
                                        else
-                                               features:tag("mechanism"):text("DIGEST-MD5"):up();
-                                               features:tag("mechanism"):text("PLAIN"):up();
+                                               mechanisms = usermanager_get_supported_methods(session.host or "*");
+                                               for k, v in pairs(mechanisms) do
+                                                       features:tag("mechanism"):text(k):up();
+                                               end
                                        end
                                features:up();
                        else
@@ -139,8 +154,8 @@ module:add_event_hook("stream-features",
                                features:tag("session", xmpp_session_attr):up();
                        end
                end);
-                                       
-module:add_iq_handler("c2s", "urn:ietf:params:xml:ns:xmpp-bind", 
+
+module:add_iq_handler("c2s", "urn:ietf:params:xml:ns:xmpp-bind",
                function (session, stanza)
                        log("debug", "Client requesting a resource bind");
                        local resource;
@@ -162,8 +177,8 @@ module:add_iq_handler("c2s", "urn:ietf:params:xml:ns:xmpp-bind",
                                        :tag("jid"):text(session.full_jid));
                        end
                end);
-               
-module:add_iq_handler("c2s", "urn:ietf:params:xml:ns:xmpp-session", 
+
+module:add_iq_handler("c2s", "urn:ietf:params:xml:ns:xmpp-session",
                function (session, stanza)
                        log("debug", "Client requesting a session");
                        session.send(st.reply(stanza));
index 46edcaeeb59d729079d07f223b17c14bc5905bd9..7165386ae3fec8516ac53fccfe80feb220675d60 100644 (file)
@@ -16,6 +16,7 @@ local unpack = unpack;
 local tostring = tostring;
 local is_admin = require "core.usermanager".is_admin;
 local jid_split = require "util.jid".split;
+local jid_bare = require "util.jid".bare;
 local b64_decode = require "util.encodings".base64.decode;
 local get_method = require "core.objectmanager".get_object;
 local validate_credentials = require "core.usermanager".validate_credentials;
@@ -65,10 +66,15 @@ local function parse_xml(xml)
        return stanza.tags[1];
 end
 
-local function handle_xmlrpc_request(method, args)
+local function handle_xmlrpc_request(jid, method, args)
+       local is_secure_call = (method:sub(1,7) == "secure/");
+       if not is_admin(jid) and not is_secure_call then
+               return create_error_response(401, "not authorized");
+       end
        method = get_method(method);
        if not method then return create_error_response(404, "method not found"); end
        args = args or {};
+       if is_secure_call then table.insert(args, 1, jid); end
        local success, result = pcall(method, unpack(args));
        if success then
                success, result = pcall(create_response, result or "nil");
@@ -77,22 +83,20 @@ local function handle_xmlrpc_request(method, args)
                end
                return create_error_response(500, "Error in creating response: "..result);
        end
-       return create_error_response(0, result or "nil");
+       return create_error_response(0, tostring(result):gsub("^[^:]+:%d+: ", ""));
 end
 
 local function handle_xmpp_request(origin, stanza)
        local query = stanza.tags[1];
        if query.name == "query" then
                if #query.tags == 1 then
-                       if is_admin(stanza.attr.from) then
-                               local success, method, args = pcall(translate_request, query.tags[1]);
-                               if success then
-                                       local result = handle_xmlrpc_request(method, args);
-                                       origin.send(st.reply(stanza):tag('query', {xmlns='jabber:iq:rpc'}):add_child(result));
-                               else
-                                       origin.send(st.error_reply(stanza, "modify", "bad-request", method));
-                               end
-                       else origin.send(st.error_reply(stanza, "auth", "forbidden", "No content in XML-RPC request")); end
+                       local success, method, args = pcall(translate_request, query.tags[1]);
+                       if success then
+                               local result = handle_xmlrpc_request(jid_bare(stanza.attr.from), method, args);
+                               origin.send(st.reply(stanza):tag('query', {xmlns='jabber:iq:rpc'}):add_child(result));
+                       else
+                               origin.send(st.error_reply(stanza, "modify", "bad-request", method));
+                       end
                else origin.send(st.error_reply(stanza, "modify", "bad-request", "No content in XML-RPC request")); end
        else origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); end
 end
@@ -106,7 +110,7 @@ local function handle_http_request(method, body, request)
        -- authenticate user
        local username, password = b64_decode(request['authorization'] or ''):gmatch('([^:]*):(.*)')(); -- TODO digest auth
        local node, host = jid_split(username);
-       if not validate_credentials(host, node, password) and is_admin(username) then
+       if not validate_credentials(host, node, password) then
                return unauthorized_response;
        end
        -- parse request
@@ -117,7 +121,7 @@ local function handle_http_request(method, body, request)
        -- execute request
        local success, method, args = pcall(translate_request, stanza);
        if success then
-               return { headers = default_headers; body = tostring(handle_xmlrpc_request(method, args)) };
+               return { headers = default_headers; body = tostring(handle_xmlrpc_request(node.."@"..host, method, args)) };
        end
        return "<html><body>Error parsing XML-RPC request: "..tostring(method).."</body></html>";
 end
diff --git a/prosody b/prosody
index 4984ed15f906fa766d4c3781f7852da1f45b68f1..0618a1f3d3b52aa15750ba134edf08c4178b1fee 100755 (executable)
--- a/prosody
+++ b/prosody
@@ -36,7 +36,7 @@ pcall(require, "luarocks.require")
 
 config = require "core.configmanager"
 
-do
+function read_config()
        -- TODO: Check for other formats when we add support for them
        -- Use lfs? Make a new conf/ dir?
        local ok, level, err = config.load((CFG_CONFIGDIR or ".").."/prosody.cfg.lua");
@@ -62,236 +62,269 @@ do
        end
 end
 
---- Initialize logging
-require "core.loggingmanager"
-
---- Check runtime dependencies
-require "util.dependencies"
-
---- Load socket framework
-local server = require "net.server"
-
-bare_sessions = {};
-full_sessions = {};
-hosts = {};
-
--- Global 'prosody' object
-prosody = {};
-local prosody = prosody;
-
-prosody.bare_sessions = bare_sessions;
-prosody.full_sessions = full_sessions;
-prosody.hosts = hosts;
-
-prosody.paths = { source = CFG_SOURCEDIR, config = CFG_CONFIGDIR, 
-                  plugins = CFG_PLUGINDIR, data = CFG_DATADIR };
-
-prosody.arg = arg;
-
-prosody.events = require "util.events".new();
+function load_libraries()
+       --- Initialize logging
+       require "core.loggingmanager"
+       
+       --- Check runtime dependencies
+       require "util.dependencies"
+       
+       --- Load socket framework
+       server = require "net.server"
+end    
+
+function init_global_state()
+       bare_sessions = {};
+       full_sessions = {};
+       hosts = {};
+
+       -- Global 'prosody' object
+       prosody = {};
+       local prosody = prosody;
+       
+       prosody.bare_sessions = bare_sessions;
+       prosody.full_sessions = full_sessions;
+       prosody.hosts = hosts;
+       
+       prosody.paths = { source = CFG_SOURCEDIR, config = CFG_CONFIGDIR, 
+                         plugins = CFG_PLUGINDIR, data = CFG_DATADIR };
+       
+       prosody.arg = _G.arg;
 
--- Try to determine version
-local version_file = io.open((CFG_SOURCEDIR or ".").."/prosody.version");
-if version_file then
-       prosody.version = version_file:read("*a"):gsub("%s*$", "");
-       version_file:close();
-       if #prosody.version == 12 and prosody.version:match("^[a-f0-9]+$") then
-               prosody.version = "hg:"..prosody.version;
+       prosody.events = require "util.events".new();
+       
+       
+       -- Function to reload the config file
+       function prosody.reload_config()
+               log("info", "Reloading configuration file");
+               prosody.events.fire_event("reloading-config");
+               local ok, level, err = config.load((rawget(_G, "CFG_CONFIGDIR") or ".").."/prosody.cfg.lua");
+               if not ok then
+                       if level == "parser" then
+                               log("error", "There was an error parsing the configuration file: %s", tostring(err));
+                       elseif level == "file" then
+                               log("error", "Couldn't read the config file when trying to reload: %s", tostring(err));
+                       end
+               end
+               return ok, (err and tostring(level)..": "..tostring(err)) or nil;
        end
-else
-       prosody.version = "unknown";
-end
 
-log("info", "Hello and welcome to Prosody version %s", prosody.version);
-
---- Load and initialise core modules
-require "util.import"
-require "core.xmlhandlers"
-require "core.rostermanager"
-require "core.eventmanager"
-require "core.hostmanager"
-require "core.modulemanager"
-require "core.usermanager"
-require "core.sessionmanager"
-require "core.stanza_router"
-
-require "util.array"
-require "util.iterators"
-require "util.timer"
-
--- Commented to protect us from 
--- the second kind of people
---[[ 
-pcall(require, "remdebug.engine");
-if remdebug then remdebug.engine.start() end
-]]
-
-local cl = require "net.connlisteners";
-
-require "util.stanza"
-require "util.jid"
-
-------------------------------------------------------------------------
-
-
-------------- Begin code without a home ---------------------
-
-local data_path = config.get("*", "core", "data_path") or CFG_DATADIR or "data";
-require "util.datamanager".set_data_path(data_path);
-require "util.datamanager".add_callback(function(username, host, datastore, data)
-       if config.get(host, "core", "anonymous_login") then
-               return false;
+       -- Function to reopen logfiles
+       function prosody.reopen_logfiles()
+               log("info", "Re-opening log files");
+               eventmanager.fire_event("reopen-log-files"); -- Handled by appropriate log sinks
+               prosody.events.fire_event("reopen-log-files");
        end
-       return username, host, datastore, data;
-end);
 
------------ End of out-of-place code --------------
+       -- Function to initiate prosody shutdown
+       function prosody.shutdown(reason)
+               log("info", "Shutting down: %s", reason or "unknown reason");
+               prosody.shutdown_reason = reason;
+               prosody.events.fire_event("server-stopping", {reason = reason});
+               server.setquitting(true);
+       end
+end
 
--- Function to reload the config file
-function prosody.reload_config()
-       log("info", "Reloading configuration file");
-       prosody.events.fire_event("reloading-config");
-       local ok, level, err = config.load((rawget(_G, "CFG_CONFIGDIR") or ".").."/prosody.cfg.lua");
-       if not ok then
-               if level == "parser" then
-                       log("error", "There was an error parsing the configuration file: %s", tostring(err));
-               elseif level == "file" then
-                       log("error", "Couldn't read the config file when trying to reload: %s", tostring(err));
+function read_version()
+       -- Try to determine version
+       local version_file = io.open((CFG_SOURCEDIR or ".").."/prosody.version");
+       if version_file then
+               prosody.version = version_file:read("*a"):gsub("%s*$", "");
+               version_file:close();
+               if #prosody.version == 12 and prosody.version:match("^[a-f0-9]+$") then
+                       prosody.version = "hg:"..prosody.version;
                end
+       else
+               prosody.version = "unknown";
        end
 end
 
--- Function to reopen logfiles
-function prosody.reopen_logfiles()
-       log("info", "Re-opening log files");
-       eventmanager.fire_event("reopen-log-files"); -- Handled by appropriate log sinks
-       prosody.events.fire_event("reopen-log-files");
+function load_secondary_libraries()
+       --- Load and initialise core modules
+       require "util.import"
+       require "core.xmlhandlers"
+       require "core.rostermanager"
+       require "core.eventmanager"
+       require "core.hostmanager"
+       require "core.modulemanager"
+       require "core.usermanager"
+       require "core.sessionmanager"
+       require "core.stanza_router"
+
+       require "util.array"
+       require "util.iterators"
+       require "util.timer"
+       require "util.helpers"
+       
+       -- Commented to protect us from 
+       -- the second kind of people
+       --[[ 
+       pcall(require, "remdebug.engine");
+       if remdebug then remdebug.engine.start() end
+       ]]
+
+       require "net.connlisteners";
+       
+       require "util.stanza"
+       require "util.jid"
 end
 
--- Function to initiate prosody shutdown
-function prosody.shutdown(reason)
-       log("info", "Shutting down: %s", reason or "unknown reason");
-       prosody.events.fire_event("server-stopping", {reason = reason});
-       server.setquitting(true);
+function init_data_store()
+       local data_path = config.get("*", "core", "data_path") or CFG_DATADIR or "data";
+       require "util.datamanager".set_data_path(data_path);
+       require "util.datamanager".add_callback(function(username, host, datastore, data)
+               if config.get(host, "core", "anonymous_login") then
+                       return false;
+               end
+               return username, host, datastore, data;
+       end);
 end
 
--- Signal to modules that we are ready to start
-eventmanager.fire_event("server-starting");
-prosody.events.fire_event("server-starting");
+function prepare_to_start()
+       -- Signal to modules that we are ready to start
+       eventmanager.fire_event("server-starting");
+       prosody.events.fire_event("server-starting");
 
--- Load SSL settings from config, and create a ctx table
-local global_ssl_ctx = ssl and config.get("*", "core", "ssl");
-if global_ssl_ctx then
-       local default_ssl_ctx = { mode = "server", protocol = "sslv23", capath = "/etc/ssl/certs", verify = "none"; };
-       setmetatable(global_ssl_ctx, { __index = default_ssl_ctx });
-end
+       -- Load SSL settings from config, and create a ctx table
+       local global_ssl_ctx = ssl and config.get("*", "core", "ssl");
+       if global_ssl_ctx then
+               local default_ssl_ctx = { mode = "server", protocol = "sslv23", capath = "/etc/ssl/certs", verify = "none"; };
+               setmetatable(global_ssl_ctx, { __index = default_ssl_ctx });
+       end
 
--- start listening on sockets
-function net_activate_ports(option, listener, default, conntype)
-       if not cl.get(listener) then return; end
-       local ports = config.get("*", "core", option.."_ports") or default;
-       if type(ports) == "number" then ports = {ports} end;
-       
-       if type(ports) ~= "table" then
-               log("error", "core."..option.." is not a table");
-       else
-               for _, port in ipairs(ports) do
-                       if type(port) ~= "number" then
-                               log("error", "Non-numeric "..option.."_ports: "..tostring(port));
-                       else
-                               cl.start(listener, { 
-                                       ssl = conntype ~= "tcp" and global_ssl_ctx,
-                                       port = port,
-                                       interface = config.get("*", "core", option.."_interface") 
-                                               or cl.get(listener).default_interface 
-                                               or config.get("*", "core", "interface"),
-                                       type = conntype
-                               });
+       local cl = require "net.connlisteners";
+       -- start listening on sockets
+       function net_activate_ports(option, listener, default, conntype)
+               if not cl.get(listener) then return; end
+               local ports = config.get("*", "core", option.."_ports") or default;
+               if type(ports) == "number" then ports = {ports} end;
+               
+               if type(ports) ~= "table" then
+                       log("error", "core."..option.." is not a table");
+               else
+                       for _, port in ipairs(ports) do
+                               if type(port) ~= "number" then
+                                       log("error", "Non-numeric "..option.."_ports: "..tostring(port));
+                               else
+                                       cl.start(listener, { 
+                                               ssl = conntype ~= "tcp" and global_ssl_ctx,
+                                               port = port,
+                                               interface = config.get("*", "core", option.."_interface") 
+                                                       or cl.get(listener).default_interface 
+                                                       or config.get("*", "core", "interface"),
+                                               type = conntype
+                                       });
+                               end
                        end
                end
        end
-end
-
-net_activate_ports("c2s", "xmppclient", {5222}, (global_ssl_ctx and "tls") or "tcp");
-net_activate_ports("s2s", "xmppserver", {5269}, "tcp");
-net_activate_ports("component", "xmppcomponent", {}, "tcp");
-net_activate_ports("legacy_ssl", "xmppclient", {}, "ssl");
-net_activate_ports("console", "console", {5582}, "tcp");
-
--- Catch global accesses --
-local locked_globals_mt = { __index = function (t, k) error("Attempt to read a non-existent global '"..k.."'", 2); end, __newindex = function (t, k, v) error("Attempt to set a global: "..tostring(k).." = "..tostring(v), 2); end }
 
-function prosody.unlock_globals()
-       setmetatable(_G, nil);
-end
+       net_activate_ports("c2s", "xmppclient", {5222}, (global_ssl_ctx and "tls") or "tcp");
+       net_activate_ports("s2s", "xmppserver", {5269}, "tcp");
+       net_activate_ports("component", "xmppcomponent", {}, "tcp");
+       net_activate_ports("legacy_ssl", "xmppclient", {}, "ssl");
+       net_activate_ports("console", "console", {5582}, "tcp");
+
+       prosody.start_time = os.time();
+end    
+
+function init_global_protection()
+       -- Catch global accesses --
+       local locked_globals_mt = { __index = function (t, k) error("Attempt to read a non-existent global '"..k.."'", 2); end, __newindex = function (t, k, v) error("Attempt to set a global: "..tostring(k).." = "..tostring(v), 2); end }
+               
+       function prosody.unlock_globals()
+               setmetatable(_G, nil);
+       end
+       
+       function prosody.lock_globals()
+               setmetatable(_G, locked_globals_mt);
+       end
 
-function prosody.lock_globals()
-       setmetatable(_G, locked_globals_mt);
+       -- And lock now...
+       prosody.lock_globals();
 end
 
--- And lock now...
-prosody.lock_globals();
-
-prosody.start_time = os.time();
-
-eventmanager.fire_event("server-started");
-prosody.events.fire_event("server-started");
-
--- Error handler for errors that make it this far
-local function catch_uncaught_error(err)
-       if err:match("%d*: interrupted!$") then
-               return "quitting";
+function loop()
+       -- Error handler for errors that make it this far
+       local function catch_uncaught_error(err)
+               if err:match("%d*: interrupted!$") then
+                       return "quitting";
+               end
+               
+               log("error", "Top-level error, please report:\n%s", tostring(err));
+               local traceback = debug.traceback("", 2);
+               if traceback then
+                       log("error", "%s", traceback);
+               end
+               
+               prosody.events.fire_event("very-bad-error", {error = err, traceback = traceback});
        end
        
-       log("error", "Top-level error, please report:\n%s", tostring(err));
-       local traceback = debug.traceback("", 2);
-       if traceback then
-               log("error", "%s", traceback);
+       while select(2, xpcall(server.loop, catch_uncaught_error)) ~= "quitting" do
+               socket.sleep(0.2);
        end
-       
-       prosody.events.fire_event("very-bad-error", {error = err, traceback = traceback});
-end
-
-while select(2, xpcall(server.loop, catch_uncaught_error)) ~= "quitting" do
-       socket.sleep(0.2);
 end
 
-log("info", "Shutdown status: Cleaning up");
-prosody.events.fire_event("server-cleanup");
-
--- Ok, we're quitting I know, but we
--- need to do some tidying before we go :)
-server.setquitting(false);
-
-log("info", "Shutdown status: Closing all active sessions");
-for hostname, host in pairs(hosts) do
-       log("debug", "Shutdown status: Closing client connections for %s", hostname)
-       if host.sessions then
-               for username, user in pairs(host.sessions) do
-                       for resource, session in pairs(user.sessions) do
-                               log("debug", "Closing connection for %s@%s/%s", username, hostname, resource);
-                               session:close("system-shutdown");
+function cleanup()
+       log("info", "Shutdown status: Cleaning up");
+       prosody.events.fire_event("server-cleanup");
+       
+       -- Ok, we're quitting I know, but we
+       -- need to do some tidying before we go :)
+       server.setquitting(false);
+       
+       log("info", "Shutdown status: Closing all active sessions");
+       for hostname, host in pairs(hosts) do
+               log("debug", "Shutdown status: Closing client connections for %s", hostname)
+               if host.sessions then
+                       local reason = { condition = "system-shutdown", text = "Server is shutting down" };
+                       if prosody.shutdown_reason then
+                               reason.text = reason.text..": "..prosody.shutdown_reason;
+                       end
+                       for username, user in pairs(host.sessions) do
+                               for resource, session in pairs(user.sessions) do
+                                       log("debug", "Closing connection for %s@%s/%s", username, hostname, resource);
+                                       session:close(reason);
+                               end
                        end
                end
-       end
        
-       log("debug", "Shutdown status: Closing outgoing s2s connections from %s", hostname);
-       if host.s2sout then
-               for remotehost, session in pairs(host.s2sout) do
-                       if session.close then
-                               session:close("system-shutdown");
-                       else
-                               log("warn", "Unable to close outgoing s2s session to %s, no session:close()?!", remotehost);
+               log("debug", "Shutdown status: Closing outgoing s2s connections from %s", hostname);
+               if host.s2sout then
+                       for remotehost, session in pairs(host.s2sout) do
+                               if session.close then
+                                       session:close("system-shutdown");
+                               else
+                                       log("warn", "Unable to close outgoing s2s session to %s, no session:close()?!", remotehost);
+                               end
                        end
                end
        end
+
+       log("info", "Shutdown status: Closing all server connections");
+       server.closeall();
+       
+       server.setquitting(true);
 end
 
-log("info", "Shutdown status: Closing all server connections");
-server.closeall();
+read_config();
+load_libraries();
+init_global_state();
+read_version();
+log("info", "Hello and welcome to Prosody version %s", prosody.version);
+load_secondary_libraries();
+init_data_store();
+prepare_to_start();
+init_global_protection();
+
+eventmanager.fire_event("server-started");
+prosody.events.fire_event("server-started");
 
-server.setquitting(true);
+loop();
 
+log("info", "Shutting down...");
+cleanup();
 eventmanager.fire_event("server-stopped");
 prosody.events.fire_event("server-stopped");
-log("info", "Shutdown status: Complete!");
+log("info", "Shutdown complete");
+
diff --git a/tools/ejabberdsql2prosody.lua b/tools/ejabberdsql2prosody.lua
new file mode 100644 (file)
index 0000000..4aace08
--- /dev/null
@@ -0,0 +1,325 @@
+#!/usr/bin/env lua
+-- Prosody IM
+-- Copyright (C) 2008-2009 Matthew Wild
+-- Copyright (C) 2008-2009 Waqas Hussain
+-- 
+-- This project is MIT/X11 licensed. Please see the
+-- COPYING file in the source package for more information.
+--
+
+package.path = package.path ..";../?.lua";
+local serialize = require "util.serialization".serialize;
+local st = require "util.stanza";
+package.loaded["util.logger"] = {init = function() return function() end; end}
+local dm = require "util.datamanager"
+dm.set_data_path("data");
+
+function parseFile(filename)
+------
+
+local file = nil;
+local last = nil;
+local function read(expected)
+       local ch;
+       if last then
+               ch = last; last = nil;
+       else ch = file:read(1); end
+       if expected and ch ~= expected then error("expected: "..expected.."; got: "..(ch or "nil")); end
+       return ch;
+end
+local function pushback(ch)
+       if last then error(); end
+       last = ch;
+end
+local function peek()
+       if not last then last = read(); end
+       return last;
+end
+
+local escapes = {
+       ["\\0"] = "\0";
+       ["\\'"] = "'";
+       ["\\\""] = "\"";
+       ["\\b"] = "\b";
+       ["\\n"] = "\n";
+       ["\\r"] = "\r";
+       ["\\t"] = "\t";
+       ["\\Z"] = "\26";
+       ["\\\\"] = "\\";
+       ["\\%"] = "%";
+       ["\\_"] = "_";
+}
+local function unescape(s)
+       return escapes[s] or error("Unknown escape sequence: "..s);
+end
+local function readString()
+       read("'");
+       local s = "";
+       while true do
+               local ch = peek();
+               if ch == "\\" then
+                       s = s..unescape(read()..read());
+               elseif ch == "'" then
+                       break;
+               else
+                       s = s..read();
+               end
+       end
+       read("'");
+       return s;
+end
+local function readNonString()
+       local s = "";
+       while true do
+               if peek() == "," or peek() == ")" then
+                       break;
+               else
+                       s = s..read();
+               end
+       end
+       return tonumber(s);
+end
+local function readItem()
+       if peek() == "'" then
+               return readString();
+       else
+               return readNonString();
+       end
+end
+local function readTuple()
+       local items = {}
+       read("(");
+       while peek() ~= ")" do
+               table.insert(items, readItem());
+               if peek() == ")" then break; end
+               read(",");
+       end
+       read(")");
+       return items;
+end
+local function readTuples()
+       if peek() ~= "(" then read("("); end
+       local tuples = {};
+       while true do
+               table.insert(tuples, readTuple());
+               if peek() == "," then read() end
+               if peek() == ";" then break; end
+       end
+       return tuples;
+end
+local function readTableName()
+       local tname = "";
+       while peek() ~= "`" do tname = tname..read(); end
+       return tname;
+end
+local function readInsert()
+       if peek() == nil then return nil; end
+       for ch in ("INSERT INTO `"):gmatch(".") do -- find line starting with this
+               if peek() == ch then
+                       read(); -- found
+               else -- match failed, skip line
+                       while peek() and read() ~= "\n" do end
+                       return nil;
+               end
+       end
+       local tname = readTableName();
+       for ch in ("` VALUES "):gmatch(".") do read(ch); end -- expect this
+       local tuples = readTuples();
+       read(";"); read("\n");
+       return tname, tuples;
+end
+
+local function readFile(filename)
+       file = io.open(filename);
+       if not file then error("File not found: "..filename); os.exit(0); end
+       local t = {};
+       while true do
+               local tname, tuples = readInsert();
+               if tname then
+                       if t[name] then
+                               local t_name = t[name];
+                               for i=1,#tuples do
+                                       table.insert(t_name, tuples[i]);
+                               end
+                       else
+                               t[tname] = tuples;
+                       end
+               elseif peek() == nil then
+                       break;
+               end
+       end
+       return t;
+end
+
+return readFile(filename);
+
+------
+end
+
+-- XML parser
+local parse_xml = (function()
+       local entity_map = setmetatable({
+               ["amp"] = "&";
+               ["gt"] = ">";
+               ["lt"] = "<";
+               ["apos"] = "'";
+               ["quot"] = "\"";
+       }, {__index = function(_, s)
+                       if s:sub(1,1) == "#" then
+                               if s:sub(2,2) == "x" then
+                                       return string.char(tonumber(s:sub(3), 16));
+                               else
+                                       return string.char(tonumber(s:sub(2)));
+                               end
+                       end
+               end
+       });
+       local function xml_unescape(str)
+               return (str:gsub("&(.-);", entity_map));
+       end
+       local function parse_tag(s)
+               local name,sattr=(s):gmatch("([^%s]+)(.*)")();
+               local attr = {};
+               for a,b in (sattr):gmatch("([^=%s]+)=['\"]([^'\"]*)['\"]") do attr[a] = xml_unescape(b); end
+               return name, attr;
+       end
+       return function(xml)
+               local stanza = st.stanza("root");
+               local regexp = "<([^>]*)>([^<]*)";
+               for elem, text in xml:gmatch(regexp) do
+                       if elem:sub(1,1) == "!" or elem:sub(1,1) == "?" then -- neglect comments and processing-instructions
+                       elseif elem:sub(1,1) == "/" then -- end tag
+                               elem = elem:sub(2);
+                               stanza:up(); -- TODO check for start-end tag name match
+                       elseif elem:sub(-1,-1) == "/" then -- empty tag
+                               elem = elem:sub(1,-2);
+                               local name,attr = parse_tag(elem);
+                               stanza:tag(name, attr):up();
+                       else -- start tag
+                               local name,attr = parse_tag(elem);
+                               stanza:tag(name, attr);
+                       end
+                       if #text ~= 0 then -- text
+                               stanza:text(xml_unescape(text));
+                       end
+               end
+               return stanza.tags[1];
+       end
+end)();
+-- end of XML parser
+
+local arg, host = ...;
+local help = "/? -? ? /h -h /help -help --help";
+if not(arg and host) or help:find(arg, 1, true) then
+       print([[ejabberd SQL DB dump importer for Prosody
+
+  Usage: ejabberdsql2prosody.lua filename.txt hostname
+
+The file can be generated using mysqldump:
+  mysqldump db_name > filename.txt]]);
+       os.exit(1);
+end
+local map = {
+       ["last"] = {"username", "seconds", "state"};
+       ["privacy_default_list"] = {"username", "name"};
+       ["privacy_list"] = {"username", "name", "id"};
+       ["privacy_list_data"] = {"id", "t", "value", "action", "ord", "match_all", "match_iq", "match_message", "match_presence_in", "match_presence_out"};
+       ["private_storage"] = {"username", "namespace", "data"};
+       ["rostergroups"] = {"username", "jid", "grp"};
+       ["rosterusers"] = {"username", "jid", "nick", "subscription", "ask", "askmessage", "server", "subscribe", "type"};
+       ["spool"] = {"username", "xml", "seq"};
+       ["users"] = {"username", "password"};
+       ["vcard"] = {"username", "vcard"};
+       --["vcard_search"] = {};
+}
+local NULL = {};
+local t = parseFile(arg);
+for name, data in pairs(t) do
+       local m = map[name];
+       if m then
+               if #data > 0 and #data[1] ~= #m then
+                       print("[warning] expected "..#m.." columns for table `"..name.."`, found "..#data[1]);
+               end
+               for i=1,#data do
+                       local row = data[i];
+                       for j=1,#m do
+                               row[m[j]] = row[j];
+                               row[j] = nil;
+                       end
+               end
+       end
+end
+--print(serialize(t));
+
+for i, row in ipairs(t["users"] or NULL) do
+       local node, password = row.username, row.password;
+       local ret, err = dm.store(node, host, "accounts", {password = password});
+       print("["..(err or "success").."] accounts: "..node.."@"..host.." = "..password);
+end
+
+function roster(node, host, jid, item)
+       local roster = dm.load(node, host, "roster") or {};
+       roster[jid] = item;
+       local ret, err = dm.store(node, host, "roster", roster);
+       print("["..(err or "success").."] roster: " ..node.."@"..host.." - "..jid);
+end
+function roster_pending(node, host, jid)
+       local roster = dm.load(node, host, "roster") or {};
+       roster.pending = roster.pending or {};
+       roster.pending[jid] = true;
+       local ret, err = dm.store(node, host, "roster", roster);
+       print("["..(err or "success").."] roster-pending: " ..node.."@"..host.." - "..jid);
+end
+function roster_group(node, host, jid, group)
+       local roster = dm.load(node, host, "roster") or {};
+       local item = roster[jid];
+       if not item then print("Warning: No roster item "..jid.." for user "..node..", can't put in group "..group); return; end
+       item.groups[group] = true;
+       local ret, err = dm.store(node, host, "roster", roster);
+       print("["..(err or "success").."] roster-group: " ..node.."@"..host.." - "..jid.." - "..group);
+end
+function private_storage(node, host, xmlns, stanza)
+       local private = dm.load(node, host, "private") or {};
+       private[stanza.name..":"..xmlns] = st.preserialize(stanza);
+       local ret, err = dm.store(node, host, "private", private);
+       print("["..(err or "success").."] private: " ..node.."@"..host.." - "..xmlns);
+end
+for i, row in ipairs(t["rosterusers"] or NULL) do
+       local node, contact = row.username, row.jid;
+       local name = row.nick;
+       if name == "" then name = nil; end
+       local subscription = row.subscription;
+       if subscription == "N" then
+               subscription = "none"
+       elseif subscription == "B" then
+               subscription = "both"
+       elseif subscription == "F" then
+               subscription = "from"
+       elseif subscription == "T" then
+               subscription = "to"
+       else error("Unknown subscription type: "..subscription) end;
+       local ask = row.ask;
+       if ask == "N" then
+               ask = nil;
+       elseif ask == "O" then
+               ask = "subscribe";
+       elseif ask == "I" then
+               roster_pending(node, host, contact);
+               ask = nil;
+       elseif ask == "B" then
+               roster_pending(node, host, contact);
+               ask = "subscribe";
+       else error("Unknown ask type: "..ask); end
+       local item = {name = name, ask = ask, subscription = subscription, groups = {}};
+       roster(node, host, contact, item);
+end
+for i, row in ipairs(t["rostergroups"] or NULL) do
+       roster_group(row.username, host, row.jid, row.grp);
+end
+for i, row in ipairs(t["vcard"] or NULL) do
+       local ret, err = dm.store(row.username, host, "vcard", st.preserialize(parse_xml(row.vcard)));
+       print("["..(err or "success").."] vCard: "..row.username.."@"..host);
+end
+for i, row in ipairs(t["private_storage"] or NULL) do
+       private_storage(row.username, host, row.namespace, st.preserialize(parse_xml(row.data)));
+end
diff --git a/util/broadcast.lua b/util/broadcast.lua
new file mode 100644 (file)
index 0000000..8f6af2f
--- /dev/null
@@ -0,0 +1,68 @@
+-- Prosody IM
+-- Copyright (C) 2008-2009 Matthew Wild
+-- Copyright (C) 2008-2009 Waqas Hussain
+-- 
+-- This project is MIT/X11 licensed. Please see the
+-- COPYING file in the source package for more information.
+--
+
+
+local ipairs, pairs, setmetatable, type = 
+        ipairs, pairs, setmetatable, type;
+
+module "pubsub"
+
+local pubsub_node_mt = { __index = _M };
+
+function new_node(name)
+       return setmetatable({ name = name, subscribers = {} }, pubsub_node_mt);
+end
+
+function set_subscribers(node, subscribers_list, list_type)
+       local subscribers = node.subscribers;
+       
+       if list_type == "array" then
+               for _, jid in ipairs(subscribers_list) do
+                       if not subscribers[jid] then
+                               node:add_subscriber(jid);
+                       end
+               end
+       elseif (not list_type) or list_type == "set" then
+               for jid in pairs(subscribers_list) do
+                       if type(jid) == "string" then
+                               node:add_subscriber(jid);
+                       end
+               end
+       end
+end
+
+function get_subscribers(node)
+       return node.subscribers;
+end
+
+function publish(node, item, dispatcher, data)
+       local subscribers = node.subscribers;
+       for i = 1,#subscribers do
+               item.attr.to = subscribers[i];
+               dispatcher(data, item);
+       end
+end
+
+function add_subscriber(node, jid)
+       local subscribers = node.subscribers;
+       if not subscribers[jid] then
+               local space = #subscribers;
+               subscribers[space] = jid;
+               subscribers[jid] = space;
+       end
+end
+
+function remove_subscriber(node, jid)
+       local subscribers = node.subscribers;
+       if subscribers[jid] then
+               subscribers[subscribers[jid]] = nil;
+               subscribers[jid] = nil;
+       end
+end
+
+return _M;
diff --git a/util/helpers.lua b/util/helpers.lua
new file mode 100644 (file)
index 0000000..80f72b3
--- /dev/null
@@ -0,0 +1,26 @@
+
+module("helpers", package.seeall);
+
+-- Helper functions for debugging
+
+local log = require "util.logger".init("util.debug");
+
+function log_events(events, name, logger)
+       local f = events.fire_event;
+       if not f then
+               error("Object does not appear to be a util.events object");
+       end
+       logger = logger or log;
+       name = name or tostring(events);
+       function events.fire_event(event, ...)
+               logger("debug", "%s firing event: %s", name, event);
+       end
+       events[events.fire_event] = f;
+       return events;
+end
+
+function revert_log_events(events)
+       events.fire_event, events[events.fire_event] = events[events.fire_event], nil; -- :)
+end
+
+return _M;
diff --git a/util/pubsub.lua b/util/pubsub.lua
deleted file mode 100644 (file)
index 8f6af2f..0000000
+++ /dev/null
@@ -1,68 +0,0 @@
--- Prosody IM
--- Copyright (C) 2008-2009 Matthew Wild
--- Copyright (C) 2008-2009 Waqas Hussain
--- 
--- This project is MIT/X11 licensed. Please see the
--- COPYING file in the source package for more information.
---
-
-
-local ipairs, pairs, setmetatable, type = 
-        ipairs, pairs, setmetatable, type;
-
-module "pubsub"
-
-local pubsub_node_mt = { __index = _M };
-
-function new_node(name)
-       return setmetatable({ name = name, subscribers = {} }, pubsub_node_mt);
-end
-
-function set_subscribers(node, subscribers_list, list_type)
-       local subscribers = node.subscribers;
-       
-       if list_type == "array" then
-               for _, jid in ipairs(subscribers_list) do
-                       if not subscribers[jid] then
-                               node:add_subscriber(jid);
-                       end
-               end
-       elseif (not list_type) or list_type == "set" then
-               for jid in pairs(subscribers_list) do
-                       if type(jid) == "string" then
-                               node:add_subscriber(jid);
-                       end
-               end
-       end
-end
-
-function get_subscribers(node)
-       return node.subscribers;
-end
-
-function publish(node, item, dispatcher, data)
-       local subscribers = node.subscribers;
-       for i = 1,#subscribers do
-               item.attr.to = subscribers[i];
-               dispatcher(data, item);
-       end
-end
-
-function add_subscriber(node, jid)
-       local subscribers = node.subscribers;
-       if not subscribers[jid] then
-               local space = #subscribers;
-               subscribers[space] = jid;
-               subscribers[jid] = space;
-       end
-end
-
-function remove_subscriber(node, jid)
-       local subscribers = node.subscribers;
-       if subscribers[jid] then
-               subscribers[subscribers[jid]] = nil;
-               subscribers[jid] = nil;
-       end
-end
-
-return _M;
index 0082b9ccf9f074181bfc01600b7283d43889f11e..48412ea7189802575dbcbb43012e732ad849e2d0 100644 (file)
@@ -1,14 +1,14 @@
 -- sasl.lua v0.4
 -- Copyright (C) 2008-2009 Tobias Markmann
--- 
+--
 --    All rights reserved.
---    
+--
 --    Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
---    
+--
 --        * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 --        * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 --        * Neither the name of Tobias Markmann nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
---    
+--
 --    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
 
@@ -30,47 +30,45 @@ local print = print
 
 module "sasl"
 
-local function new_plain(realm, password_handler)
-       local object = { mechanism = "PLAIN", realm = realm, password_handler = password_handler}
+-- Credentials handler:
+--   Arguments: ("PLAIN", user, host, password)
+--   Returns: true (success) | false (fail) | nil (user unknown)
+local function new_plain(realm, credentials_handler)
+       local object = { mechanism = "PLAIN", realm = realm, credentials_handler = credentials_handler}
        function object.feed(self, message)
-       
                if message == "" or message == nil then return "failure", "malformed-request" end
                local response = message
                local authorization = s_match(response, "([^&%z]+)")
                local authentication = s_match(response, "%z([^&%z]+)%z")
                local password = s_match(response, "%z[^&%z]+%z([^&%z]+)")
-               
-               if authentication == nil or password == nil then return "failure", "malformed-request" end
-               
-               local password_encoding, correct_password = self.password_handler(authentication, self.realm, self.realm, "PLAIN")
-               
-               if correct_password == nil then return "failure", "not-authorized"
-               elseif correct_password == false then return "failure", "account-disabled" end
-               
-               local claimed_password = ""
-               if password_encoding == nil then claimed_password = password
-               else claimed_password = password_encoding(password) end
-               
-               self.username = authentication
-               if claimed_password == correct_password then
-                       return "success"
-               else
-                       return "failure", "not-authorized"
-               end
-       end
-       return object
-end
 
+    if authentication == nil or password == nil then return "failure", "malformed-request" end
+    self.username = authentication
+    local auth_success = self.credentials_handler("PLAIN", self.username, self.realm, password)
+
+    if auth_success then
+      return "success"
+    elseif auth_success == nil then
+      return "failure", "account-disabled"
+    else
+      return "failure", "not-authorized"
+    end
+  end
+  return object
+end
 
+-- credentials_handler:
+--   Arguments: (mechanism, node, domain, realm, decoder)
+--   Returns: Password encoding, (plaintext) password
 -- implementing RFC 2831
-local function new_digest_md5(realm, password_handler)
+local function new_digest_md5(realm, credentials_handler)
        --TODO complete support for authzid
 
        local function serialize(message)
                local data = ""
-               
+
                if type(message) ~= "table" then error("serialize needs an argument of type table.") end
-               
+
                -- testing all possible values
                if message["nonce"] then data = data..[[nonce="]]..message.nonce..[[",]] end
                if message["qop"] then data = data..[[qop="]]..message.qop..[[",]] end
@@ -81,7 +79,7 @@ local function new_digest_md5(realm, password_handler)
                data = data:gsub(",$", "")
                return data
        end
-       
+
        local function utf8tolatin1ifpossible(passwd)
                local i = 1;
                while i <= #passwd do
@@ -137,16 +135,16 @@ local function new_digest_md5(realm, password_handler)
                return message;
        end
 
-       local object = { mechanism = "DIGEST-MD5", realm = realm, password_handler = password_handler};
-       
+       local object = { mechanism = "DIGEST-MD5", realm = realm, credentials_handler = credentials_handler};
+
        object.nonce = generate_uuid();
        object.step = 0;
        object.nonce_count = {};
-                                                                                               
+
        function object.feed(self, message)
                self.step = self.step + 1;
                if (self.step == 1) then
-                       local challenge = serialize({   nonce = object.nonce, 
+                       local challenge = serialize({   nonce = object.nonce,
                                                                                        qop = "auth",
                                                                                        charset = "utf-8",
                                                                                        algorithm = "md5-sess",
@@ -158,13 +156,13 @@ local function new_digest_md5(realm, password_handler)
                        if response["nc"] then
                                if self.nonce_count[response["nc"]] then return "failure", "not-authorized" end
                        end
-                       
+
                        -- check for username, it's REQUIRED by RFC 2831
                        if not response["username"] then
                                return "failure", "malformed-request";
                        end
                        self["username"] = response["username"];
-                       
+
                        -- check for nonce, ...
                        if not response["nonce"] then
                                return "failure", "malformed-request";
@@ -172,23 +170,23 @@ local function new_digest_md5(realm, password_handler)
                                -- check if it's the right nonce
                                if response["nonce"] ~= tostring(self.nonce) then return "failure", "malformed-request" end
                        end
-                       
+
                        if not response["cnonce"] then return "failure", "malformed-request", "Missing entry for cnonce in SASL message." end
                        if not response["qop"] then response["qop"] = "auth" end
-                       
+
                        if response["realm"] == nil or response["realm"] == "" then
                                response["realm"] = "";
                        elseif response["realm"] ~= self.realm then
                                return "failure", "not-authorized", "Incorrect realm value";
                        end
-                       
+
                        local decoder;
                        if response["charset"] == nil then
                                decoder = utf8tolatin1ifpossible;
                        elseif response["charset"] ~= "utf-8" then
                                return "failure", "incorrect-encoding", "The client's response uses "..response["charset"].." for encoding with isn't supported by sasl.lua. Supported encodings are latin or utf-8.";
                        end
-                       
+
                        local domain = "";
                        local protocol = "";
                        if response["digest-uri"] then
@@ -197,10 +195,10 @@ local function new_digest_md5(realm, password_handler)
                        else
                                return "failure", "malformed-request", "Missing entry for digest-uri in SASL message."
                        end
-                       
+
                        --TODO maybe realm support
                        self.username = response["username"];
-                       local password_encoding, Y = self.password_handler(response["username"], to_unicode(domain), response["realm"], "DIGEST-MD5", decoder);
+                       local password_encoding, Y = self.credentials_handler("DIGEST-MD5", response["username"], to_unicode(domain), response["realm"], decoder);
                        if Y == nil then return "failure", "not-authorized"
                        elseif Y == false then return "failure", "account-disabled" end
                        local A1 = "";
@@ -216,27 +214,27 @@ local function new_digest_md5(realm, password_handler)
                                A1 = Y..":"..response["nonce"]..":"..response["cnonce"];
                        end
                        local A2 = "AUTHENTICATE:"..protocol.."/"..domain;
-                       
+
                        local HA1 = md5(A1, true);
                        local HA2 = md5(A2, true);
-                       
+
                        local KD = HA1..":"..response["nonce"]..":"..response["nc"]..":"..response["cnonce"]..":"..response["qop"]..":"..HA2;
                        local response_value = md5(KD, true);
-                       
+
                        if response_value == response["response"] then
                                -- calculate rspauth
                                A2 = ":"..protocol.."/"..domain;
-                               
+
                                HA1 = md5(A1, true);
                                HA2 = md5(A2, true);
-                               
+
                                KD = HA1..":"..response["nonce"]..":"..response["nc"]..":"..response["cnonce"]..":"..response["qop"]..":"..HA2
                                local rspauth = md5(KD, true);
                                self.authenticated = true;
                                return "challenge", serialize({rspauth = rspauth});
                        else
                                return "failure", "not-authorized", "The response provided by the client doesn't match the one we calculated."
-                       end                                                     
+                       end
                elseif self.step == 3 then
                        if self.authenticated ~= nil then return "success"
                        else return "failure", "malformed-request" end
@@ -245,8 +243,10 @@ local function new_digest_md5(realm, password_handler)
        return object;
 end
 
-local function new_anonymous(realm, password_handler)
-       local object = { mechanism = "ANONYMOUS", realm = realm, password_handler = password_handler}
+-- Credentials handler: Can be nil. If specified, should take the mechanism as
+-- the only argument, and return true for OK, or false for not-OK (TODO)
+local function new_anonymous(realm, credentials_handler)
+       local object = { mechanism = "ANONYMOUS", realm = realm, credentials_handler = credentials_handler}
                function object.feed(self, message)
                        return "success"
                end
@@ -255,11 +255,11 @@ local function new_anonymous(realm, password_handler)
 end
 
 
-function new(mechanism, realm, password_handler)
+function new(mechanism, realm, credentials_handler)
        local object
-       if mechanism == "PLAIN" then object = new_plain(realm, password_handler)
-       elseif mechanism == "DIGEST-MD5" then object = new_digest_md5(realm, password_handler)
-       elseif mechanism == "ANONYMOUS" then object = new_anonymous(realm, password_handler)
+       if mechanism == "PLAIN" then object = new_plain(realm, credentials_handler)
+       elseif mechanism == "DIGEST-MD5" then object = new_digest_md5(realm, credentials_handler)
+       elseif mechanism == "ANONYMOUS" then object = new_anonymous(realm, credentials_handler)
        else
                log("debug", "Unsupported SASL mechanism: "..tostring(mechanism));
                return nil