local fire_event = prosody and prosody.events.fire_event or function () end;
+local envload = require"util.envload".envload;
local lfs = require "lfs";
local path_sep = package.config:sub(1,1);
-- Built-in Lua parser
do
- local loadstring, pcall, setmetatable = _G.loadstring, _G.pcall, _G.setmetatable;
- local setfenv, rawget, tostring = _G.setfenv, _G.rawget, _G.tostring;
+ local pcall, setmetatable = _G.pcall, _G.setmetatable;
+ local rawget, tostring = _G.rawget, _G.tostring;
parsers.lua = {};
function parsers.lua.load(data, config_file, config)
local env;
return dofile(resolve_relative_path(config_file:gsub("[^"..path_sep.."]+$", ""), file));
end
- local chunk, err = loadstring(data, "@"..config_file);
+ local chunk, err = envload(data, "@"..config_file, env);
if not chunk then
return nil, err;
end
- setfenv(chunk, env);
-
local ok, err = pcall(chunk);
if not ok then
local pluginloader = require "util.pluginloader";
local timer = require "util.timer";
+local multitable_new = require "util.multitable".new;
+
local t_insert, t_remove, t_concat = table.insert, table.remove, table.concat;
-local error, setmetatable, setfenv, type = error, setmetatable, setfenv, type;
+local error, setmetatable, type = error, setmetatable, type;
local ipairs, pairs, select, unpack = ipairs, pairs, select, unpack;
local tonumber, tostring = tonumber, tostring;
api.hook_stanza = api.hook_tag; -- COMPAT w/pre-0.9
function api:require(lib)
- local f, n = pluginloader.load_code(self.name, lib..".lib.lua");
+ local f, n = pluginloader.load_code(self.name, lib..".lib.lua", self.environment);
if not f then
- f, n = pluginloader.load_code(lib, lib..".lib.lua");
+ f, n = pluginloader.load_code(lib, lib..".lib.lua", self.environment);
end
if not f then error("Failed to load plugin library '"..lib.."', error: "..n); end -- FIXME better error message
- setfenv(f, self.environment);
return f();
end
return io.open(path, mode);
end
-return api;
\ No newline at end of file
+return api;
local prosody = prosody;
local pcall, xpcall = pcall, xpcall;
-local setmetatable, rawget, setfenv = setmetatable, rawget, setfenv;
+local setmetatable, rawget = setmetatable, rawget;
local pairs, type, tostring = pairs, type, tostring;
local debug_traceback = debug.traceback;
end
- local mod, err = pluginloader.load_code(module_name);
- if not mod then
- log("error", "Unable to load module '%s': %s", module_name or "nil", err or "nil");
- return nil, err;
- end
local _log = logger.init(host..":"..module_name);
- local api_instance = setmetatable({ name = module_name, host = host, path = err,
+ local api_instance = setmetatable({ name = module_name, host = host,
_log = _log, log = function (self, ...) return _log(...); end, event_handlers = new_multitable() }
, { __index = api });
local pluginenv = setmetatable({ module = api_instance }, { __index = _G });
api_instance.environment = pluginenv;
- setfenv(mod, pluginenv);
-
+ local mod, err = pluginloader.load_code(module_name, nil, pluginenv);
+ if not mod then
+ log("error", "Unable to load module '%s': %s", module_name or "nil", err or "nil");
+ return nil, err;
+ end
+
+ api_instance.path = err;
+
modulemap[host][module_name] = pluginenv;
local ok, err = pcall(mod);
if ok then
local setmetatable = setmetatable;
local format = string.format;
-local loadfile, setfenv, pcall = loadfile, setfenv, pcall;
+local pcall = pcall;
local pairs, ipairs = pairs, ipairs;
local tostring = tostring;
function load_roster(username, host)
local jid = username.."@"..host;
- log("debug", "load_roster: asked for: %s", jid);
+ log("debug", "load_roster: asked for: "..jid);
local user = bare_sessions[jid];
local roster;
if user then
roster = user.roster;
if roster then return roster; end
- log("debug", "load_roster: loading for new user: %s@%s", username, host);
+ log("debug", "load_roster: loading for new user: "..username.."@"..host);
else -- Attempt to load roster for non-loaded user
- log("debug", "load_roster: loading for offline user: %s@%s", username, host);
+ log("debug", "load_roster: loading for offline user: "..username.."@"..host);
end
local data, err = datamanager.load(username, host, "roster");
roster = data or {};
if not roster[false] then roster[false] = { broken = err or nil }; end
if roster[jid] then
roster[jid] = nil;
- log("warn", "roster for %s has a self-contact", jid);
+ log("warn", "roster for "..jid.." has a self-contact");
end
if not err then
hosts[host].events.fire_event("roster-load", username, host, roster);
end
function save_roster(username, host, roster)
- log("debug", "save_roster: saving roster for %s@%s", username, host);
+ log("debug", "save_roster: saving roster for "..username.."@"..host);
if not roster then
roster = hosts[host] and hosts[host].sessions[username] and hosts[host].sessions[username].roster;
--if not roster then
roster[jid] = item;
end
item.ask = "subscribe";
- log("debug", "set_contact_pending_out: saving roster; set %s@%s.roster[%q].ask=subscribe", username, host, jid);
+ log("debug", "set_contact_pending_out: saving roster; set "..username.."@"..host..".roster["..jid.."].ask=subscribe");
return save_roster(username, host, roster);
end
function unsubscribe(username, host, jid)
local prosody = _G.prosody;
local hosts = prosody.hosts;
-local console_listener = { default_port = 5582; default_mode = "*a"; interface = "127.0.0.1" };
+local console_listener = { default_port = 5582; default_mode = "*l"; interface = "127.0.0.1" };
local iterators = require "util.iterators";
local keys, values = iterators.keys, iterators.values;
local jid_bare, jid_split = jid.bare, jid.split;
local set, array = require "util.set", require "util.array";
local cert_verify_identity = require "util.x509".verify_identity;
+local envload = require "util.envload".envload;
+local envloadfile = require "util.envload".envloadfile;
local commands = module:shared("commands")
local def_env = module:shared("env");
local default_env_mt = { __index = def_env };
-local core_post_stanza = prosody.core_post_stanza;
local function redirect_output(_G, session)
local env = setmetatable({ print = session.print }, { __index = function (t, k) return rawget(_G, k); end });
env.dofile = function(name)
- local f, err = loadfile(name);
+ local f, err = envloadfile(name, env);
if not f then return f, err; end
- return setfenv(f, env)();
+ return f();
end;
return env;
end
function console_listener.onincoming(conn, data)
local session = sessions[conn];
- local partial = session.partial_data;
- if partial then
- data = partial..data;
- end
-
- for line in data:gmatch("[^\n]*[\n\004]") do
- -- Handle data (loop allows us to break to add \0 after response)
- repeat
- local useglobalenv;
-
- if line:match("^>") then
- line = line:gsub("^>", "");
- useglobalenv = true;
- elseif line == "\004" then
- commands["bye"](session, line);
- break;
- else
- local command = line:match("^%w+") or line:match("%p");
- if commands[command] then
- commands[command](session, line);
- break;
- end
+ -- Handle data
+ (function(session, data)
+ local useglobalenv;
+
+ 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");
+ if commands[command] then
+ commands[command](session, data);
+ return;
end
+ end
- session.env._ = line;
-
- local chunkname = "=console";
- local chunk, err = loadstring("return "..line, chunkname);
+ session.env._ = data;
+
+ local chunkname = "=console";
+ local env = (useglobalenv and redirect_output(_G, session)) or session.env or nil
+ local chunk, err = envload("return "..data, chunkname, env);
+ if not chunk then
+ chunk, err = envload(data, chunkname, env);
if not chunk then
- chunk, err = loadstring(line, chunkname);
- if not chunk then
- err = err:gsub("^%[string .-%]:%d+: ", "");
- err = err:gsub("^:%d+: ", "");
- err = err:gsub("'<eof>'", "the end of the line");
- session.print("Sorry, I couldn't understand that... "..err);
- break;
- end
- end
-
- setfenv(chunk, (useglobalenv and redirect_output(_G, session)) or session.env or nil);
-
- local ranok, taskok, message = pcall(chunk);
-
- if not (ranok or message or useglobalenv) and commands[line:lower()] then
- commands[line:lower()](session, line);
- break;
- end
-
- if not ranok then
- session.print("Fatal error while running command, it did not complete");
- session.print("Error: "..taskok);
- break;
+ err = err:gsub("^%[string .-%]:%d+: ", "");
+ err = err:gsub("^:%d+: ", "");
+ err = err:gsub("'<eof>'", "the end of the line");
+ session.print("Sorry, I couldn't understand that... "..err);
+ return;
end
-
- if not message then
- session.print("Result: "..tostring(taskok));
- break;
- elseif (not taskok) and message then
- session.print("Command completed with a problem");
- session.print("Message: "..tostring(message));
- break;
- end
-
- session.print("OK: "..tostring(message));
- until true
+ end
- session.send(string.char(0));
- end
- session.partial_data = data:match("[^\n]+$");
+ local ranok, taskok, message = pcall(chunk);
+
+ if not (ranok or message or useglobalenv) and commands[data:lower()] then
+ commands[data:lower()](session, data);
+ return;
+ end
+
+ if not ranok then
+ session.print("Fatal error while running command, it did not complete");
+ session.print("Error: "..taskok);
+ return;
+ end
+
+ if not message then
+ session.print("Result: "..tostring(taskok));
+ return;
+ elseif (not taskok) and message then
+ session.print("Command completed with a problem");
+ session.print("Message: "..tostring(message));
+ return;
+ end
+
+ session.print("OK: "..tostring(message));
+ end)(session, data);
+
+ session.send(string.char(0));
end
function console_listener.ondisconnect(conn, err)
print [[s2s - Commands to manage sessions between this server and others]]
print [[module - Commands to load/reload/unload modules/plugins]]
print [[host - Commands to activate, deactivate and list virtual hosts]]
- print [[user - Commands to create and delete users, and change their passwords]]
print [[server - Uptime, version, shutting down, etc.]]
print [[config - Reloading the configuration, etc.]]
print [[console - Help regarding the console itself]]
elseif section == "s2s" then
print [[s2s:show(domain) - Show all s2s connections for the given domain (or all if no domain given)]]
print [[s2s:close(from, to) - Close a connection from one domain to another]]
- print [[s2s:closeall(host) - Close all the incoming/outgoing s2s sessions to specified host]]
elseif section == "module" then
print [[module:load(module, host) - Load the specified module on the specified host (or all hosts if none given)]]
print [[module:reload(module, host) - The same, but unloads and loads the module (saving state if the module supports it)]]
print [[host:activate(hostname) - Activates the specified host]]
print [[host:deactivate(hostname) - Disconnects all clients on this host and deactivates]]
print [[host:list() - List the currently-activated hosts]]
- elseif section == "user" then
- print [[user:create(jid, password) - Create the specified user account]]
- print [[user:password(jid, password) - Set the password for the specified user account]]
- print [[user:delete(jid, password) - Permanently remove the specified user account]]
elseif section == "server" then
print [[server:version() - Show the server's version number]]
print [[server:uptime() - Show how long the server has been running]]
end
function def_env.s2s:showcert(domain)
+ local ser = require "util.serialization".serialize;
local print = self.session.print;
local domain_sessions = set.new(array.collect(keys(incoming_s2s)))
/function(session) return session.from_host == domain and session or nil; end;
end
local domain_certs = array.collect(values(cert_set));
-- Phew. We now have a array of unique certificates presented by domain.
+ local print = self.session.print;
local n_certs = #domain_certs;
if n_certs == 0 then
return true, "Closed "..count.." s2s session"..((count == 1 and "") or "s");
end
-function def_env.s2s:closeall(host)
- local count = 0;
-
- if not host or type(host) ~= "string" then return false, "wrong syntax: please use s2s:closeall('hostname.tld')"; end
- if hosts[host] then
- for session in pairs(incoming_s2s) do
- if session.to_host == host then
- (session.close or s2smanager.destroy_session)(session);
- count = count + 1;
- end
- end
- for _, session in pairs(hosts[host].s2sout) do
- (session.close or s2smanager.destroy_session)(session);
- count = count + 1;
- end
- else
- for session in pairs(incoming_s2s) do
- if session.from_host == host then
- (session.close or s2smanager.destroy_session)(session);
- count = count + 1;
- end
- end
- for _, h in pairs(hosts) do
- if h.s2sout[host] then
- (h.s2sout[host].close or s2smanager.destroy_session)(h.s2sout[host]);
- count = count + 1;
- end
- end
- end
-
- if count == 0 then return false, "No sessions to close.";
- else return true, "Closed "..count.." s2s session"..((count == 1 and "") or "s"); end
-end
-
def_env.host = {}; def_env.hosts = def_env.host;
function def_env.host:activate(hostname, config)
return setmetatable({ room = room_obj }, console_room_mt);
end
-local um = require"core.usermanager";
-
-def_env.user = {};
-function def_env.user:create(jid, password)
- local username, host = jid_split(jid);
- local ok, err = um.create_user(username, password, host);
- if ok then
- return true, "User created";
- else
- return nil, "Could not create user: "..err;
- end
-end
-
-function def_env.user:delete(jid)
- local username, host = jid_split(jid);
- local ok, err = um.delete_user(username, host);
- if ok then
- return true, "User deleted";
- else
- return nil, "Could not delete user: "..err;
- end
-end
-
-function def_env.user:passwd(jid, password)
- local username, host = jid_split(jid);
- local ok, err = um.set_password(username, password, host);
- if ok then
- return true, "User created";
- else
- return nil, "Could not change password for user: "..err;
- end
-end
-
-def_env.xmpp = {};
-
-local st = require "util.stanza";
-function def_env.xmpp:ping(localhost, remotehost)
- if hosts[localhost] then
- core_post_stanza(hosts[localhost],
- st.iq{ from=localhost, to=remotehost, type="get", id="ping" }
- :tag("ping", {xmlns="urn:xmpp:ping"}));
- return true, "Sent ping";
- else
- return nil, "No such host";
- end
-end
-
-------------
function printbanner(session)
if type(option) == "string" then
session.print(option)
elseif type(option) == "function" then
- setfenv(option, redirect_output(_G, session));
- pcall(option, session);
+ module:log("warn", "Using functions as value for the console_banner option is no longer supported");
end
end
end
-- This driver stores data as simple key-values
local ser = require "util.serialization".serialize;
+local envload = require "util.envload".envload;
local deser = function(data)
module:log("debug", "deser: %s", tostring(data));
if not data then return nil; end
- local f = loadstring("return "..data);
+ local f = envload("return "..data, nil, {});
if not f then return nil; end
- setfenv(f, {});
local s, d = pcall(f);
if not s then return nil; end
return d;
local coroutine = coroutine;
local lfs = require "lfs";
local loadfile = loadfile;
-local setfenv = setfenv;
local pcall = pcall;
local mtools = require "migrator.mtools";
local next = next;
end
table.remove(arg, handled_opts);
+if CFG_SOURCEDIR then
+ package.path = CFG_SOURCEDIR.."/?.lua;"..package.path;
+ package.cpath = CFG_SOURCEDIR.."/?.so;"..package.cpath;
+else
+ package.path = "../../?.lua;"..package.path
+ package.cpath = "../../?.so;"..package.cpath
+end
+
+local envloadfile = require "util.envload".envloadfile;
+
-- Load config file
local function loadfilein(file, env)
if loadin then
return loadin(env, io.open(file):read("*a"));
else
- local chunk, err = loadfile(file);
- if chunk then
- setfenv(chunk, env);
- end
- return chunk, err;
+ return envloadfile(file, env);
end
end
config_chunk();
-if CFG_SOURCEDIR then
- package.path = CFG_SOURCEDIR.."/?.lua;"..package.path;
- package.cpath = CFG_SOURCEDIR.."/?.so;"..package.cpath;
-elseif not package.loaded["util.json"] then
- package.path = "../../?.lua;"..package.path
- package.cpath = "../../?.so;"..package.cpath
-end
-
local have_err;
if #arg > 0 and #arg ~= 2 then
have_err = true;
local setmetatable, type = setmetatable, type;
local pairs, ipairs = pairs, ipairs;
local char = string.char;
-local loadfile, setfenv, pcall = loadfile, setfenv, pcall;
+local pcall = pcall;
local log = require "util.logger".init("datamanager");
local io_open = io.open;
local os_remove = os.remove;
local next = next;
local t_insert = table.insert;
local append = require "util.serialization".append;
+local envloadfile = require"util.envload".envloadfile;
local path_separator = assert ( package.config:match ( "^([^\n]+)" ) , "package.config not in standard form" ) -- Extract directory seperator from package.config (an undocumented string that comes with lua)
local lfs = require "lfs";
local prosody = prosody;
end
function load(username, host, datastore)
- local data, ret = loadfile(getpath(username, host, datastore));
+ local data, ret = envloadfile(getpath(username, host, datastore), {});
if not data then
local mode = lfs.attributes(getpath(username, host, datastore), "mode");
if not mode then
- log("debug", "Assuming empty %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "nil");
+ log("debug", "Assuming empty "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
return nil;
else -- file exists, but can't be read
-- TODO more detailed error checking and logging?
- log("error", "Failed to load %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "nil");
+ log("error", "Failed to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
return nil, "Error reading storage";
end
end
- setfenv(data, {});
+
local success, ret = pcall(data);
if not success then
- log("error", "Unable to load %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "nil");
+ log("error", "Unable to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
return nil, "Error reading storage";
end
return ret;
-- save the datastore
local f, msg = io_open(getpath(username, host, datastore, nil, true), "w+");
if not f then
- log("error", "Unable to write to %s storage ('%s') for user: %s@%s", datastore, msg, username or "nil", host or "nil");
+ log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..(username or "nil").."@"..(host or "nil"));
return nil, "Error saving to storage";
end
f:write("return ");
-- save the datastore
local f, msg = io_open(getpath(username, host, datastore, "list", true), "a+");
if not f then
- log("error", "Unable to write to %s storage ('%s') for user: %s@%s", datastore, msg, username or "nil", host or "nil");
+ log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..(username or "nil").."@"..(host or "nil"));
return;
end
f:write("item(");
-- save the datastore
local f, msg = io_open(getpath(username, host, datastore, "list", true), "w+");
if not f then
- log("error", "Unable to write to %s storage ('%s') for user: %s@%s", datastore, msg, username or "nil", host or "nil");
+ log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..(username or "nil").."@"..(host or "nil"));
return;
end
for _, d in ipairs(data) do
end
function list_load(username, host, datastore)
- local data, ret = loadfile(getpath(username, host, datastore, "list"));
+ local items = {};
+ local data, ret = envloadfile(getpath(username, host, datastore, "list"), {item = function(i) t_insert(items, i); end});
if not data then
local mode = lfs.attributes(getpath(username, host, datastore, "list"), "mode");
if not mode then
- log("debug", "Assuming empty %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "nil");
+ log("debug", "Assuming empty "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
return nil;
else -- file exists, but can't be read
-- TODO more detailed error checking and logging?
- log("error", "Failed to load %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "nil");
+ log("error", "Failed to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
return nil, "Error reading storage";
end
end
- local items = {};
- setfenv(data, {item = function(i) t_insert(items, i); end});
+
local success, ret = pcall(data);
if not success then
- log("error", "Unable to load %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "nil");
+ log("error", "Unable to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
return nil, "Error reading storage";
end
return items;
local io_open, os_time = io.open, os.time;
local loadstring, pairs = loadstring, pairs;
+local envload = require "util.envload".envload;
module "pluginloader"
return load_file(names);
end
-function load_code(plugin, resource)
+function load_code(plugin, resource, env)
local content, err = load_resource(plugin, resource);
if not content then return content, err; end
local path = err;
- local f, err = loadstring(content, "@"..path);
+ local f, err = envload(content, "@"..path, env);
if not f then return f, err; end
return f, path;
end
local next = next;
local loadstring = loadstring;
-local setfenv = setfenv;
local pcall = pcall;
local debug_traceback = debug.traceback;
local log = require "util.logger".init("serialization");
+local envload = require"util.envload".envload;
+
module "serialization"
local indent = function(i)
function deserialize(str)
if type(str) ~= "string" then return nil; end
str = "return "..str;
- local f, err = loadstring(str, "@data");
+ local f, err = envload(str, "@data", {});
if not f then return nil, err; end
- setfenv(f, {});
local success, ret = pcall(f);
if not success then return nil, ret; end
return ret;