prosodyctl: Support for plugin_paths config option
[prosody.git] / prosodyctl
1 #!/usr/bin/env lua
2 -- Prosody IM
3 -- Copyright (C) 2008-2010 Matthew Wild
4 -- Copyright (C) 2008-2010 Waqas Hussain
5 -- 
6 -- This project is MIT/X11 licensed. Please see the
7 -- COPYING file in the source package for more information.
8 --
9
10 -- prosodyctl - command-line controller for Prosody XMPP server
11
12 -- Will be modified by configure script if run --
13
14 CFG_SOURCEDIR=os.getenv("PROSODY_SRCDIR");
15 CFG_CONFIGDIR=os.getenv("PROSODY_CFGDIR");
16 CFG_PLUGINDIR=os.getenv("PROSODY_PLUGINDIR");
17 CFG_DATADIR=os.getenv("PROSODY_DATADIR");
18
19 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20
21 local function is_relative(path)
22         local path_sep = package.config:sub(1,1);
23         return ((path_sep == "/" and path:sub(1,1) ~= "/")
24         or (path_sep == "\\" and (path:sub(1,1) ~= "/" and path:sub(2,3) ~= ":\\")))
25 end
26
27 -- Tell Lua where to find our libraries
28 if CFG_SOURCEDIR then
29         local function filter_relative_paths(path)
30                 if is_relative(path) then return ""; end
31         end
32         local function sanitise_paths(paths)
33                 return (paths:gsub("[^;]+;?", filter_relative_paths):gsub(";;+", ";"));
34         end
35         package.path = sanitise_paths(CFG_SOURCEDIR.."/?.lua;"..package.path);
36         package.cpath = sanitise_paths(CFG_SOURCEDIR.."/?.so;"..package.cpath);
37 end
38
39 -- Substitute ~ with path to home directory in data path
40 if CFG_DATADIR then
41         if os.getenv("HOME") then
42                 CFG_DATADIR = CFG_DATADIR:gsub("^~", os.getenv("HOME"));
43         end
44 end
45
46 -- Global 'prosody' object
47 local prosody = {
48         hosts = {};
49         events = require "util.events".new();
50         platform = "posix";
51         lock_globals = function () end;
52         unlock_globals = function () end;
53 };
54 _G.prosody = prosody;
55
56 local dependencies = require "util.dependencies";
57 if not dependencies.check_dependencies() then
58         os.exit(1);
59 end
60
61 config = require "core.configmanager"
62
63 do
64         local filenames = {};
65         
66         local filename;
67         if arg[1] == "--config" and arg[2] then
68                 table.insert(filenames, arg[2]);
69                 table.remove(arg, 1); table.remove(arg, 1);
70                 if CFG_CONFIGDIR then
71                         table.insert(filenames, CFG_CONFIGDIR.."/"..arg[2]);
72                 end
73         else
74                 for _, format in ipairs(config.parsers()) do
75                         table.insert(filenames, (CFG_CONFIGDIR or ".").."/prosody.cfg."..format);
76                 end
77         end
78         for _,_filename in ipairs(filenames) do
79                 filename = _filename;
80                 local file = io.open(filename);
81                 if file then
82                         file:close();
83                         CFG_CONFIGDIR = filename:match("^(.*)[\\/][^\\/]*$");
84                         break;
85                 end
86         end
87         local ok, level, err = config.load(filename);
88         if not ok then
89                 print("\n");
90                 print("**************************");
91                 if level == "parser" then
92                         print("A problem occured while reading the config file "..(CFG_CONFIGDIR or ".").."/prosody.cfg.lua");
93                         local err_line, err_message = tostring(err):match("%[string .-%]:(%d*): (.*)");
94                         print("Error"..(err_line and (" on line "..err_line) or "")..": "..(err_message or tostring(err)));
95                         print("");
96                 elseif level == "file" then
97                         print("Prosody was unable to find the configuration file.");
98                         print("We looked for: "..(CFG_CONFIGDIR or ".").."/prosody.cfg.lua");
99                         print("A sample config file is included in the Prosody download called prosody.cfg.lua.dist");
100                         print("Copy or rename it to prosody.cfg.lua and edit as necessary.");
101                 end
102                 print("More help on configuring Prosody can be found at http://prosody.im/doc/configure");
103                 print("Good luck!");
104                 print("**************************");
105                 print("");
106                 os.exit(1);
107         end
108 end
109 local original_logging_config = config.get("*", "core", "log");
110 config.set("*", "core", "log", { { levels = { min="info" }, to = "console" } });
111
112 local data_path = config.get("*", "core", "data_path") or CFG_DATADIR or "data";
113 local custom_plugin_paths = config.get("*", "core", "plugin_paths");
114 if custom_plugin_paths then
115         CFG_PLUGINDIR = table.concat(custom_plugin_paths, package.config:sub(3,3)); -- path1;path2;path3
116 end
117 prosody.paths = { source = CFG_SOURCEDIR, config = CFG_CONFIGDIR, 
118                   plugins = CFG_PLUGINDIR, data = data_path };
119
120 require "core.loggingmanager"
121
122 dependencies.log_warnings();
123
124 -- Switch away from root and into the prosody user --
125 local switched_user, current_uid;
126
127 local want_pposix_version = "0.3.5";
128 local ok, pposix = pcall(require, "util.pposix");
129
130 if ok and pposix then
131         if pposix._VERSION ~= want_pposix_version then print(string.format("Unknown version (%s) of binary pposix module, expected %s", tostring(pposix._VERSION), want_pposix_version)); return; end
132         current_uid = pposix.getuid();
133         if current_uid == 0 then
134                 -- We haz root!
135                 local desired_user = config.get("*", "core", "prosody_user") or "prosody";
136                 local desired_group = config.get("*", "core", "prosody_group") or desired_user;
137                 local ok, err = pposix.setgid(desired_group);
138                 if ok then
139                         ok, err = pposix.initgroups(desired_user);
140                 end
141                 if ok then
142                         ok, err = pposix.setuid(desired_user);
143                         if ok then
144                                 -- Yay!
145                                 switched_user = true;
146                         end
147                 end
148                 if not switched_user then
149                         -- Boo!
150                         print("Warning: Couldn't switch to Prosody user/group '"..tostring(desired_user).."'/'"..tostring(desired_group).."': "..tostring(err));
151                 end
152         end
153         
154         -- Set our umask to protect data files
155         pposix.umask(config.get("*", "core", "umask") or "027");
156 else
157         print("Error: Unable to load pposix module. Check that Prosody is installed correctly.")
158         print("For more help send the below error to us through http://prosody.im/discuss");
159         print(tostring(pposix))
160 end
161
162 local function test_writeable(filename)
163         local f, err = io.open(filename, "a");
164         if not f then
165                 return false, err;
166         end
167         f:close();
168         return true;
169 end
170
171 local unwriteable_files = {};
172 if type(original_logging_config) == "string" and original_logging_config:sub(1,1) ~= "*" then
173         local ok, err = test_writeable(original_logging_config);
174         if not ok then
175                 table.insert(unwriteable_files, err);
176         end
177 elseif type(original_logging_config) == "table" then
178         for _, rule in ipairs(original_logging_config) do
179                 if rule.filename then
180                         local ok, err = test_writeable(rule.filename);
181                         if not ok then
182                                 table.insert(unwriteable_files, err);
183                         end
184                 end
185         end
186 end
187
188 if #unwriteable_files > 0 then
189         print("One of more of the Prosody log files are not");
190         print("writeable, please correct the errors and try");
191         print("starting prosodyctl again.");
192         print("");
193         for _, err in ipairs(unwriteable_files) do
194                 print(err);
195         end
196         print("");
197         os.exit(1);
198 end
199
200
201 local error_messages = setmetatable({ 
202                 ["invalid-username"] = "The given username is invalid in a Jabber ID";
203                 ["invalid-hostname"] = "The given hostname is invalid";
204                 ["no-password"] = "No password was supplied";
205                 ["no-such-user"] = "The given user does not exist on the server";
206                 ["unable-to-save-data"] = "Unable to store, perhaps you don't have permission?";
207                 ["no-pidfile"] = "There is no 'pidfile' option in the configuration file, see http://prosody.im/doc/prosodyctl#pidfile for help";
208                 ["no-posix"] = "The mod_posix module is not enabled in the Prosody config file, see http://prosody.im/doc/prosodyctl for more info";
209                 ["no-such-method"] = "This module has no commands";
210                 ["not-running"] = "Prosody is not running";
211                 }, { __index = function (t,k) return "Error: "..(tostring(k):gsub("%-", " "):gsub("^.", string.upper)); end });
212
213 hosts = prosody.hosts;
214
215 local function make_host(hostname)
216         return {
217                 type = "local",
218                 events = prosody.events,
219                 users = require "core.usermanager".new_null_provider(hostname)
220         };
221 end
222
223 for hostname, config in pairs(config.getconfig()) do
224         hosts[hostname] = make_host(hostname);
225 end
226         
227 require "core.modulemanager"
228
229 require "util.prosodyctl"
230 require "socket"
231 -----------------------
232
233 local show_message, show_warning = prosodyctl.show_message, prosodyctl.show_warning;
234 local show_usage = prosodyctl.show_usage;
235 local getchar, getpass = prosodyctl.getchar, prosodyctl.getpass;
236 local show_yesno = prosodyctl.show_yesno;
237 local read_password = prosodyctl.read_password;
238
239 local prosodyctl_timeout = (config.get("*", "core", "prosodyctl_timeout") or 5) * 2;
240 -----------------------
241 local commands = {};
242 local command = arg[1];
243
244 function commands.adduser(arg)
245         if not arg[1] or arg[1] == "--help" then
246                 show_usage([[adduser JID]], [[Create the specified user account in Prosody]]);
247                 return 1;
248         end
249         local user, host = arg[1]:match("([^@]+)@(.+)");
250         if not user and host then
251                 show_message [[Failed to understand JID, please supply the JID you want to create]]
252                 show_usage [[adduser user@host]]
253                 return 1;
254         end
255         
256         if not host then
257                 show_message [[Please specify a JID, including a host. e.g. alice@example.com]];
258                 return 1;
259         end
260         
261         if not hosts[host] then
262                 show_warning("The host '%s' is not listed in the configuration file (or is not enabled).", host)
263                 show_warning("The user will not be able to log in until this is changed.");
264                 hosts[host] = make_host(host);
265         end
266         
267         if prosodyctl.user_exists{ user = user, host = host } then
268                 show_message [[That user already exists]];
269                 return 1;
270         end
271         
272         local password = read_password();
273         if not password then return 1; end
274         
275         local ok, msg = prosodyctl.adduser { user = user, host = host, password = password };
276         
277         if ok then return 0; end
278         
279         show_message(msg)
280         return 1;
281 end
282
283 function commands.passwd(arg)
284         if not arg[1] or arg[1] == "--help" then
285                 show_usage([[passwd JID]], [[Set the password for the specified user account in Prosody]]);
286                 return 1;
287         end
288         local user, host = arg[1]:match("([^@]+)@(.+)");
289         if not user and host then
290                 show_message [[Failed to understand JID, please supply the JID you want to set the password for]]
291                 show_usage [[passwd user@host]]
292                 return 1;
293         end
294         
295         if not host then
296                 show_message [[Please specify a JID, including a host. e.g. alice@example.com]];
297                 return 1;
298         end
299         
300         if not hosts[host] then
301                 show_warning("The host '%s' is not listed in the configuration file (or is not enabled).", host)
302                 show_warning("The user will not be able to log in until this is changed.");
303                 hosts[host] = make_host(host);
304         end
305         
306         if not prosodyctl.user_exists { user = user, host = host } then
307                 show_message [[That user does not exist, use prosodyctl adduser to create a new user]]
308                 return 1;
309         end
310         
311         local password = read_password();
312         if not password then return 1; end
313         
314         local ok, msg = prosodyctl.passwd { user = user, host = host, password = password };
315         
316         if ok then return 0; end
317         
318         show_message(error_messages[msg])
319         return 1;
320 end
321
322 function commands.deluser(arg)
323         if not arg[1] or arg[1] == "--help" then
324                 show_usage([[deluser JID]], [[Permanently remove the specified user account from Prosody]]);
325                 return 1;
326         end
327         local user, host = arg[1]:match("([^@]+)@(.+)");
328         if not user and host then
329                 show_message [[Failed to understand JID, please supply the JID you want to set the password for]]
330                 show_usage [[passwd user@host]]
331                 return 1;
332         end
333         
334         if not host then
335                 show_message [[Please specify a JID, including a host. e.g. alice@example.com]];
336                 return 1;
337         end
338         
339         if not hosts[host] then
340                 show_warning("The host '%s' is not listed in the configuration file (or is not enabled).", host)
341                 show_warning("The user will not be able to log in until this is changed.");
342                 hosts[host] = make_host(host);
343         end
344
345         if not prosodyctl.user_exists { user = user, host = host } then
346                 show_message [[That user does not exist on this server]]
347                 return 1;
348         end
349         
350         local ok, msg = prosodyctl.passwd { user = user, host = host };
351         
352         if ok then return 0; end
353         
354         show_message(error_messages[msg])
355         return 1;
356 end
357
358 function commands.start(arg)
359         if arg[1] == "--help" then
360                 show_usage([[start]], [[Start Prosody]]);
361                 return 1;
362         end
363         local ok, ret = prosodyctl.isrunning();
364         if not ok then
365                 show_message(error_messages[ret]);
366                 return 1;
367         end
368         
369         if ret then
370                 local ok, ret = prosodyctl.getpid();
371                 if not ok then
372                         show_message("Couldn't get running Prosody's PID");
373                         show_message(error_messages[ret]);
374                         return 1;
375                 end
376                 show_message("Prosody is already running with PID %s", ret or "(unknown)");
377                 return 1;
378         end
379         
380         local ok, ret = prosodyctl.start();
381         if ok then
382                 if config.get("*", "core", "daemonize") ~= false then
383                         local i=1;
384                         while true do
385                                 local ok, running = prosodyctl.isrunning();
386                                 if ok and running then
387                                         break;
388                                 elseif i == 5 then
389                                         show_message("Still waiting...");
390                                 elseif i >= prosodyctl_timeout then
391                                         show_message("Prosody is still not running. Please give it some time or check your log files for errors.");
392                                         return 2;
393                                 end
394                                 socket.sleep(0.5);
395                                 i = i + 1;
396                         end
397                         show_message("Started");
398                 end
399                 return 0;
400         end
401
402         show_message("Failed to start Prosody");
403         show_message(error_messages[ret])       
404         return 1;       
405 end
406
407 function commands.status(arg)
408         if arg[1] == "--help" then
409                 show_usage([[status]], [[Reports the running status of Prosody]]);
410                 return 1;
411         end
412
413         local ok, ret = prosodyctl.isrunning();
414         if not ok then
415                 show_message(error_messages[ret]);
416                 return 1;
417         end
418         
419         if ret then
420                 local ok, ret = prosodyctl.getpid();
421                 if not ok then
422                         show_message("Couldn't get running Prosody's PID");
423                         show_message(error_messages[ret]);
424                         return 1;
425                 end
426                 show_message("Prosody is running with PID %s", ret or "(unknown)");
427                 return 0;
428         else
429                 show_message("Prosody is not running");
430                 if not switched_user and current_uid ~= 0 then
431                         print("\nNote:")
432                         print(" You will also see this if prosodyctl is not running under");
433                         print(" the same user account as Prosody. Try running as root (e.g. ");
434                         print(" with 'sudo' in front) to gain access to Prosody's real status.");
435                 end
436                 return 2
437         end
438         return 1;
439 end
440
441 function commands.stop(arg)
442         if arg[1] == "--help" then
443                 show_usage([[stop]], [[Stop a running Prosody server]]);
444                 return 1;
445         end
446
447         if not prosodyctl.isrunning() then
448                 show_message("Prosody is not running");
449                 return 1;
450         end
451         
452         local ok, ret = prosodyctl.stop();
453         if ok then
454                 local i=1;
455                 while true do
456                         local ok, running = prosodyctl.isrunning();
457                         if ok and not running then
458                                 break;
459                         elseif i == 5 then
460                                 show_message("Still waiting...");
461                         elseif i >= prosodyctl_timeout then
462                                 show_message("Prosody is still running. Please give it some time or check your log files for errors.");
463                                 return 2;
464                         end
465                         socket.sleep(0.5);
466                         i = i + 1;
467                 end
468                 show_message("Stopped");
469                 return 0;
470         end
471
472         show_message(error_messages[ret]);
473         return 1;
474 end
475
476 function commands.restart(arg)
477         if arg[1] == "--help" then
478                 show_usage([[restart]], [[Restart a running Prosody server]]);
479                 return 1;
480         end
481         
482         commands.stop(arg);
483         return commands.start(arg);
484 end
485
486 -- ejabberdctl compatibility
487
488 function commands.register(arg)
489         local user, host, password = unpack(arg);
490         if (not (user and host)) or arg[1] == "--help" then
491                 if user ~= "--help" then
492                         if not user then
493                                 show_message [[No username specified]]
494                         elseif not host then
495                                 show_message [[Please specify which host you want to register the user on]];
496                         end
497                 end
498                 show_usage("register USER HOST [PASSWORD]", "Register a user on the server, with the given password");
499                 return 1;
500         end
501         if not password then
502                 password = read_password();
503                 if not password then
504                         show_message [[Unable to register user with no password]];
505                         return 1;
506                 end
507         end
508         
509         local ok, msg = prosodyctl.adduser { user = user, host = host, password = password };
510         
511         if ok then return 0; end
512         
513         show_message(error_messages[msg])
514         return 1;
515 end
516
517 function commands.unregister(arg)
518         local user, host = unpack(arg);
519         if (not (user and host)) or arg[1] == "--help" then
520                 if user ~= "--help" then
521                         if not user then
522                                 show_message [[No username specified]]
523                         elseif not host then
524                                 show_message [[Please specify which host you want to unregister the user from]];
525                         end
526                 end
527                 show_usage("unregister USER HOST [PASSWORD]", "Permanently remove a user account from the server");
528                 return 1;
529         end
530
531         local ok, msg = prosodyctl.deluser { user = user, host = host };
532         
533         if ok then return 0; end
534         
535         show_message(error_messages[msg])
536         return 1;
537 end
538
539 ---------------------
540
541 if command and command:match("^mod_") then -- Is a command in a module
542         local module_name = command:match("^mod_(.+)");
543         local ret, err = modulemanager.load("*", module_name);
544         if not ret then
545                 show_message("Failed to load module '"..module_name.."': "..err);
546                 os.exit(1);
547         end
548         
549         table.remove(arg, 1);
550         
551         local module = modulemanager.get_module("*", module_name);
552         if not module then
553                 show_message("Failed to load module '"..module_name.."': Unknown error");
554                 os.exit(1);
555         end
556         
557         if not modulemanager.module_has_method(module, "command") then
558                 show_message("Fail: mod_"..module_name.." does not support any commands");
559                 os.exit(1);
560         end
561         
562         local ok, ret = modulemanager.call_module_method(module, "command", arg);
563         if ok then
564                 if type(ret) == "number" then
565                         os.exit(ret);
566                 elseif type(ret) == "string" then
567                         show_message(ret);
568                 end
569                 os.exit(0); -- :)
570         else
571                 show_message("Failed to execute command: "..error_messages[ret]);
572                 os.exit(1); -- :(
573         end
574 end
575
576 if not commands[command] then -- Show help for all commands
577         function show_usage(usage, desc)
578                 print(" "..usage);
579                 print("    "..desc);
580         end
581
582         print("prosodyctl - Manage a Prosody server");
583         print("");
584         print("Usage: "..arg[0].." COMMAND [OPTIONS]");
585         print("");
586         print("Where COMMAND may be one of:\n");
587
588         local hidden_commands = require "util.set".new{ "register", "unregister", "addplugin" };
589         local commands_order = { "adduser", "passwd", "deluser", "start", "stop", "restart" };
590
591         local done = {};
592
593         for _, command_name in ipairs(commands_order) do
594                 local command = commands[command_name];
595                 if command then
596                         command{ "--help" };
597                         print""
598                         done[command_name] = true;
599                 end
600         end
601
602         for command_name, command in pairs(commands) do
603                 if not done[command_name] and not hidden_commands:contains(command_name) then
604                         command{ "--help" };
605                         print""
606                         done[command_name] = true;
607                 end
608         end
609         
610         
611         os.exit(0);
612 end
613
614 os.exit(commands[command]({ select(2, unpack(arg)) }));