Merge with waqas
[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 prosody.paths = { source = CFG_SOURCEDIR, config = CFG_CONFIGDIR, 
114                   plugins = CFG_PLUGINDIR, data = data_path };
115
116 require "core.loggingmanager"
117
118 dependencies.log_warnings();
119
120 -- Switch away from root and into the prosody user --
121 local switched_user, current_uid;
122
123 local want_pposix_version = "0.3.5";
124 local ok, pposix = pcall(require, "util.pposix");
125
126 if ok and pposix then
127         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
128         current_uid = pposix.getuid();
129         if current_uid == 0 then
130                 -- We haz root!
131                 local desired_user = config.get("*", "core", "prosody_user") or "prosody";
132                 local desired_group = config.get("*", "core", "prosody_group") or desired_user;
133                 local ok, err = pposix.setgid(desired_group);
134                 if ok then
135                         ok, err = pposix.initgroups(desired_user);
136                 end
137                 if ok then
138                         ok, err = pposix.setuid(desired_user);
139                         if ok then
140                                 -- Yay!
141                                 switched_user = true;
142                         end
143                 end
144                 if not switched_user then
145                         -- Boo!
146                         print("Warning: Couldn't switch to Prosody user/group '"..tostring(desired_user).."'/'"..tostring(desired_group).."': "..tostring(err));
147                 end
148         end
149         
150         -- Set our umask to protect data files
151         pposix.umask(config.get("*", "core", "umask") or "027");
152 else
153         print("Error: Unable to load pposix module. Check that Prosody is installed correctly.")
154         print("For more help send the below error to us through http://prosody.im/discuss");
155         print(tostring(pposix))
156 end
157
158 local function test_writeable(filename)
159         local f, err = io.open(filename, "a");
160         if not f then
161                 return false, err;
162         end
163         f:close();
164         return true;
165 end
166
167 local unwriteable_files = {};
168 if type(original_logging_config) == "string" and original_logging_config:sub(1,1) ~= "*" then
169         local ok, err = test_writeable(original_logging_config);
170         if not ok then
171                 table.insert(unwriteable_files, err);
172         end
173 elseif type(original_logging_config) == "table" then
174         for _, rule in ipairs(original_logging_config) do
175                 if rule.filename then
176                         local ok, err = test_writeable(rule.filename);
177                         if not ok then
178                                 table.insert(unwriteable_files, err);
179                         end
180                 end
181         end
182 end
183
184 if #unwriteable_files > 0 then
185         print("One of more of the Prosody log files are not");
186         print("writeable, please correct the errors and try");
187         print("starting prosodyctl again.");
188         print("");
189         for _, err in ipairs(unwriteable_files) do
190                 print(err);
191         end
192         print("");
193         os.exit(1);
194 end
195
196
197 local error_messages = setmetatable({ 
198                 ["invalid-username"] = "The given username is invalid in a Jabber ID";
199                 ["invalid-hostname"] = "The given hostname is invalid";
200                 ["no-password"] = "No password was supplied";
201                 ["no-such-user"] = "The given user does not exist on the server";
202                 ["unable-to-save-data"] = "Unable to store, perhaps you don't have permission?";
203                 ["no-pidfile"] = "There is no 'pidfile' option in the configuration file, see http://prosody.im/doc/prosodyctl#pidfile for help";
204                 ["no-posix"] = "The mod_posix module is not enabled in the Prosody config file, see http://prosody.im/doc/prosodyctl for more info";
205                 ["no-such-method"] = "This module has no commands";
206                 ["not-running"] = "Prosody is not running";
207                 }, { __index = function (t,k) return "Error: "..(tostring(k):gsub("%-", " "):gsub("^.", string.upper)); end });
208
209 hosts = prosody.hosts;
210
211 local function make_host(hostname)
212         return {
213                 type = "local",
214                 events = prosody.events,
215                 users = require "core.usermanager".new_null_provider(hostname)
216         };
217 end
218
219 for hostname, config in pairs(config.getconfig()) do
220         hosts[hostname] = make_host(hostname);
221 end
222         
223 require "core.modulemanager"
224
225 require "util.prosodyctl"
226 require "socket"
227 -----------------------
228
229 local show_message, show_warning = prosodyctl.show_message, prosodyctl.show_warning;
230 local show_usage = prosodyctl.show_usage;
231 local getchar, getpass = prosodyctl.getchar, prosodyctl.getpass;
232 local show_yesno = prosodyctl.show_yesno;
233 local read_password = prosodyctl.read_password;
234
235 local prosodyctl_timeout = (config.get("*", "core", "prosodyctl_timeout") or 5) * 2;
236 -----------------------
237 local commands = {};
238 local command = arg[1];
239
240 function commands.adduser(arg)
241         if not arg[1] or arg[1] == "--help" then
242                 show_usage([[adduser JID]], [[Create the specified user account in Prosody]]);
243                 return 1;
244         end
245         local user, host = arg[1]:match("([^@]+)@(.+)");
246         if not user and host then
247                 show_message [[Failed to understand JID, please supply the JID you want to create]]
248                 show_usage [[adduser user@host]]
249                 return 1;
250         end
251         
252         if not host then
253                 show_message [[Please specify a JID, including a host. e.g. alice@example.com]];
254                 return 1;
255         end
256         
257         if not hosts[host] then
258                 show_warning("The host '%s' is not listed in the configuration file (or is not enabled).", host)
259                 show_warning("The user will not be able to log in until this is changed.");
260                 hosts[host] = make_host(host);
261         end
262         
263         if prosodyctl.user_exists{ user = user, host = host } then
264                 show_message [[That user already exists]];
265                 return 1;
266         end
267         
268         local password = read_password();
269         if not password then return 1; end
270         
271         local ok, msg = prosodyctl.adduser { user = user, host = host, password = password };
272         
273         if ok then return 0; end
274         
275         show_message(msg)
276         return 1;
277 end
278
279 function commands.passwd(arg)
280         if not arg[1] or arg[1] == "--help" then
281                 show_usage([[passwd JID]], [[Set the password for the specified user account in Prosody]]);
282                 return 1;
283         end
284         local user, host = arg[1]:match("([^@]+)@(.+)");
285         if not user and host then
286                 show_message [[Failed to understand JID, please supply the JID you want to set the password for]]
287                 show_usage [[passwd user@host]]
288                 return 1;
289         end
290         
291         if not host then
292                 show_message [[Please specify a JID, including a host. e.g. alice@example.com]];
293                 return 1;
294         end
295         
296         if not hosts[host] then
297                 show_warning("The host '%s' is not listed in the configuration file (or is not enabled).", host)
298                 show_warning("The user will not be able to log in until this is changed.");
299                 hosts[host] = make_host(host);
300         end
301         
302         if not prosodyctl.user_exists { user = user, host = host } then
303                 show_message [[That user does not exist, use prosodyctl adduser to create a new user]]
304                 return 1;
305         end
306         
307         local password = read_password();
308         if not password then return 1; end
309         
310         local ok, msg = prosodyctl.passwd { user = user, host = host, password = password };
311         
312         if ok then return 0; end
313         
314         show_message(error_messages[msg])
315         return 1;
316 end
317
318 function commands.deluser(arg)
319         if not arg[1] or arg[1] == "--help" then
320                 show_usage([[deluser JID]], [[Permanently remove the specified user account from Prosody]]);
321                 return 1;
322         end
323         local user, host = arg[1]:match("([^@]+)@(.+)");
324         if not user and host then
325                 show_message [[Failed to understand JID, please supply the JID you want to set the password for]]
326                 show_usage [[passwd user@host]]
327                 return 1;
328         end
329         
330         if not host then
331                 show_message [[Please specify a JID, including a host. e.g. alice@example.com]];
332                 return 1;
333         end
334         
335         if not hosts[host] then
336                 show_warning("The host '%s' is not listed in the configuration file (or is not enabled).", host)
337                 show_warning("The user will not be able to log in until this is changed.");
338                 hosts[host] = make_host(host);
339         end
340
341         if not prosodyctl.user_exists { user = user, host = host } then
342                 show_message [[That user does not exist on this server]]
343                 return 1;
344         end
345         
346         local ok, msg = prosodyctl.passwd { user = user, host = host };
347         
348         if ok then return 0; end
349         
350         show_message(error_messages[msg])
351         return 1;
352 end
353
354 function commands.start(arg)
355         if arg[1] == "--help" then
356                 show_usage([[start]], [[Start Prosody]]);
357                 return 1;
358         end
359         local ok, ret = prosodyctl.isrunning();
360         if not ok then
361                 show_message(error_messages[ret]);
362                 return 1;
363         end
364         
365         if ret then
366                 local ok, ret = prosodyctl.getpid();
367                 if not ok then
368                         show_message("Couldn't get running Prosody's PID");
369                         show_message(error_messages[ret]);
370                         return 1;
371                 end
372                 show_message("Prosody is already running with PID %s", ret or "(unknown)");
373                 return 1;
374         end
375         
376         local ok, ret = prosodyctl.start();
377         if ok then
378                 if config.get("*", "core", "daemonize") ~= false then
379                         local i=1;
380                         while true do
381                                 local ok, running = prosodyctl.isrunning();
382                                 if ok and running then
383                                         break;
384                                 elseif i == 5 then
385                                         show_message("Still waiting...");
386                                 elseif i >= prosodyctl_timeout then
387                                         show_message("Prosody is still not running. Please give it some time or check your log files for errors.");
388                                         return 2;
389                                 end
390                                 socket.sleep(0.5);
391                                 i = i + 1;
392                         end
393                         show_message("Started");
394                 end
395                 return 0;
396         end
397
398         show_message("Failed to start Prosody");
399         show_message(error_messages[ret])       
400         return 1;       
401 end
402
403 function commands.status(arg)
404         if arg[1] == "--help" then
405                 show_usage([[status]], [[Reports the running status of Prosody]]);
406                 return 1;
407         end
408
409         local ok, ret = prosodyctl.isrunning();
410         if not ok then
411                 show_message(error_messages[ret]);
412                 return 1;
413         end
414         
415         if ret then
416                 local ok, ret = prosodyctl.getpid();
417                 if not ok then
418                         show_message("Couldn't get running Prosody's PID");
419                         show_message(error_messages[ret]);
420                         return 1;
421                 end
422                 show_message("Prosody is running with PID %s", ret or "(unknown)");
423                 return 0;
424         else
425                 show_message("Prosody is not running");
426                 if not switched_user and current_uid ~= 0 then
427                         print("\nNote:")
428                         print(" You will also see this if prosodyctl is not running under");
429                         print(" the same user account as Prosody. Try running as root (e.g. ");
430                         print(" with 'sudo' in front) to gain access to Prosody's real status.");
431                 end
432                 return 2
433         end
434         return 1;
435 end
436
437 function commands.stop(arg)
438         if arg[1] == "--help" then
439                 show_usage([[stop]], [[Stop a running Prosody server]]);
440                 return 1;
441         end
442
443         if not prosodyctl.isrunning() then
444                 show_message("Prosody is not running");
445                 return 1;
446         end
447         
448         local ok, ret = prosodyctl.stop();
449         if ok then
450                 local i=1;
451                 while true do
452                         local ok, running = prosodyctl.isrunning();
453                         if ok and not running then
454                                 break;
455                         elseif i == 5 then
456                                 show_message("Still waiting...");
457                         elseif i >= prosodyctl_timeout then
458                                 show_message("Prosody is still running. Please give it some time or check your log files for errors.");
459                                 return 2;
460                         end
461                         socket.sleep(0.5);
462                         i = i + 1;
463                 end
464                 show_message("Stopped");
465                 return 0;
466         end
467
468         show_message(error_messages[ret]);
469         return 1;
470 end
471
472 function commands.restart(arg)
473         if arg[1] == "--help" then
474                 show_usage([[restart]], [[Restart a running Prosody server]]);
475                 return 1;
476         end
477         
478         commands.stop(arg);
479         return commands.start(arg);
480 end
481
482 -- ejabberdctl compatibility
483
484 function commands.register(arg)
485         local user, host, password = unpack(arg);
486         if (not (user and host)) or arg[1] == "--help" then
487                 if user ~= "--help" then
488                         if not user then
489                                 show_message [[No username specified]]
490                         elseif not host then
491                                 show_message [[Please specify which host you want to register the user on]];
492                         end
493                 end
494                 show_usage("register USER HOST [PASSWORD]", "Register a user on the server, with the given password");
495                 return 1;
496         end
497         if not password then
498                 password = read_password();
499                 if not password then
500                         show_message [[Unable to register user with no password]];
501                         return 1;
502                 end
503         end
504         
505         local ok, msg = prosodyctl.adduser { user = user, host = host, password = password };
506         
507         if ok then return 0; end
508         
509         show_message(error_messages[msg])
510         return 1;
511 end
512
513 function commands.unregister(arg)
514         local user, host = unpack(arg);
515         if (not (user and host)) or arg[1] == "--help" then
516                 if user ~= "--help" then
517                         if not user then
518                                 show_message [[No username specified]]
519                         elseif not host then
520                                 show_message [[Please specify which host you want to unregister the user from]];
521                         end
522                 end
523                 show_usage("unregister USER HOST [PASSWORD]", "Permanently remove a user account from the server");
524                 return 1;
525         end
526
527         local ok, msg = prosodyctl.deluser { user = user, host = host };
528         
529         if ok then return 0; end
530         
531         show_message(error_messages[msg])
532         return 1;
533 end
534
535 ---------------------
536
537 if command and command:match("^mod_") then -- Is a command in a module
538         local module_name = command:match("^mod_(.+)");
539         local ret, err = modulemanager.load("*", module_name);
540         if not ret then
541                 show_message("Failed to load module '"..module_name.."': "..err);
542                 os.exit(1);
543         end
544         
545         table.remove(arg, 1);
546         
547         local module = modulemanager.get_module("*", module_name);
548         if not module then
549                 show_message("Failed to load module '"..module_name.."': Unknown error");
550                 os.exit(1);
551         end
552         
553         if not modulemanager.module_has_method(module, "command") then
554                 show_message("Fail: mod_"..module_name.." does not support any commands");
555                 os.exit(1);
556         end
557         
558         local ok, ret = modulemanager.call_module_method(module, "command", arg);
559         if ok then
560                 if type(ret) == "number" then
561                         os.exit(ret);
562                 elseif type(ret) == "string" then
563                         show_message(ret);
564                 end
565                 os.exit(0); -- :)
566         else
567                 show_message("Failed to execute command: "..error_messages[ret]);
568                 os.exit(1); -- :(
569         end
570 end
571
572 if not commands[command] then -- Show help for all commands
573         function show_usage(usage, desc)
574                 print(" "..usage);
575                 print("    "..desc);
576         end
577
578         print("prosodyctl - Manage a Prosody server");
579         print("");
580         print("Usage: "..arg[0].." COMMAND [OPTIONS]");
581         print("");
582         print("Where COMMAND may be one of:\n");
583
584         local hidden_commands = require "util.set".new{ "register", "unregister", "addplugin" };
585         local commands_order = { "adduser", "passwd", "deluser", "start", "stop", "restart" };
586
587         local done = {};
588
589         for _, command_name in ipairs(commands_order) do
590                 local command = commands[command_name];
591                 if command then
592                         command{ "--help" };
593                         print""
594                         done[command_name] = true;
595                 end
596         end
597
598         for command_name, command in pairs(commands) do
599                 if not done[command_name] and not hidden_commands:contains(command_name) then
600                         command{ "--help" };
601                         print""
602                         done[command_name] = true;
603                 end
604         end
605         
606         
607         os.exit(0);
608 end
609
610 os.exit(commands[command]({ select(2, unpack(arg)) }));