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