prosodyctl: Make the 'restart' command start Prosody even if it wasn't already running
[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 {
172                 type = "local",
173                 events = prosody.events,
174                 users = require "core.usermanager".new_null_provider(hostname)
175         };
176 end
177
178 for hostname, config in pairs(config.getconfig()) do
179         hosts[hostname] = make_host(hostname);
180 end
181         
182 require "core.modulemanager"
183
184 require "util.prosodyctl"
185 require "socket"
186 -----------------------
187
188 function show_message(msg, ...)
189         print(msg:format(...));
190 end
191
192 function show_warning(msg, ...)
193         print(msg:format(...));
194 end
195
196 function show_usage(usage, desc)
197         print("Usage: "..arg[0].." "..usage);
198         if desc then
199                 print(" "..desc);
200         end
201 end
202
203 local function getchar(n)
204         local stty_ret = os.execute("stty raw -echo 2>/dev/null");
205         local ok, char;
206         if stty_ret == 0 then
207                 ok, char = pcall(io.read, n or 1);
208                 os.execute("stty sane");
209         else
210                 ok, char = pcall(io.read, "*l");
211                 if ok then
212                         char = char:sub(1, n or 1);
213                 end
214         end
215         if ok then
216                 return char;
217         end
218 end
219         
220 local function getpass()
221         local stty_ret = os.execute("stty -echo 2>/dev/null");
222         if stty_ret ~= 0 then
223                 io.write("\027[08m"); -- ANSI 'hidden' text attribute
224         end
225         local ok, pass = pcall(io.read, "*l");
226         if stty_ret == 0 then
227                 os.execute("stty sane");
228         else
229                 io.write("\027[00m");
230         end
231         io.write("\n");
232         if ok then
233                 return pass;
234         end
235 end
236
237 function show_yesno(prompt)
238         io.write(prompt, " ");
239         local choice = getchar():lower();
240         io.write("\n");
241         if not choice:match("%a") then
242                 choice = prompt:match("%[.-(%U).-%]$");
243                 if not choice then return nil; end
244         end
245         return (choice == "y");
246 end
247
248 local function read_password()
249         local password;
250         while true do
251                 io.write("Enter new password: ");
252                 password = getpass();
253                 if not password then
254                         show_message("No password - cancelled");
255                         return;
256                 end
257                 io.write("Retype new password: ");
258                 if getpass() ~= password then
259                         if not show_yesno [=[Passwords did not match, try again? [Y/n]]=] then
260                                 return;
261                         end
262                 else
263                         break;
264                 end
265         end
266         return password;
267 end
268
269 local prosodyctl_timeout = (config.get("*", "core", "prosodyctl_timeout") or 5) * 2;
270 -----------------------
271 local commands = {};
272 local command = arg[1];
273
274 function commands.adduser(arg)
275         if not arg[1] or arg[1] == "--help" then
276                 show_usage([[adduser JID]], [[Create the specified user account in Prosody]]);
277                 return 1;
278         end
279         local user, host = arg[1]:match("([^@]+)@(.+)");
280         if not user and host then
281                 show_message [[Failed to understand JID, please supply the JID you want to create]]
282                 show_usage [[adduser user@host]]
283                 return 1;
284         end
285         
286         if not host then
287                 show_message [[Please specify a JID, including a host. e.g. alice@example.com]];
288                 return 1;
289         end
290         
291         if not hosts[host] then
292                 show_warning("The host '%s' is not listed in the configuration file (or is not enabled).", host)
293                 show_warning("The user will not be able to log in until this is changed.");
294                 hosts[host] = make_host(host);
295         end
296         
297         if prosodyctl.user_exists{ user = user, host = host } then
298                 show_message [[That user already exists]];
299                 return 1;
300         end
301         
302         local password = read_password();
303         if not password then return 1; end
304         
305         local ok, msg = prosodyctl.adduser { user = user, host = host, password = password };
306         
307         if ok then return 0; end
308         
309         show_message(error_messages[msg])
310         return 1;
311 end
312
313 function commands.passwd(arg)
314         if not arg[1] or arg[1] == "--help" then
315                 show_usage([[passwd JID]], [[Set the password for the specified user account in Prosody]]);
316                 return 1;
317         end
318         local user, host = arg[1]:match("([^@]+)@(.+)");
319         if not user and host then
320                 show_message [[Failed to understand JID, please supply the JID you want to set the password for]]
321                 show_usage [[passwd user@host]]
322                 return 1;
323         end
324         
325         if not host then
326                 show_message [[Please specify a JID, including a host. e.g. alice@example.com]];
327                 return 1;
328         end
329         
330         if not hosts[host] then
331                 show_warning("The host '%s' is not listed in the configuration file (or is not enabled).", host)
332                 show_warning("The user will not be able to log in until this is changed.");
333                 hosts[host] = make_host(host);
334         end
335         
336         if not prosodyctl.user_exists { user = user, host = host } then
337                 show_message [[That user does not exist, use prosodyctl adduser to create a new user]]
338                 return 1;
339         end
340         
341         local password = read_password();
342         if not password then return 1; end
343         
344         local ok, msg = prosodyctl.passwd { user = user, host = host, password = password };
345         
346         if ok then return 0; end
347         
348         show_message(error_messages[msg])
349         return 1;
350 end
351
352 function commands.deluser(arg)
353         if not arg[1] or arg[1] == "--help" then
354                 show_usage([[deluser JID]], [[Permanently remove the specified user account from Prosody]]);
355                 return 1;
356         end
357         local user, host = arg[1]:match("([^@]+)@(.+)");
358         if not user and host then
359                 show_message [[Failed to understand JID, please supply the JID you want to set the password for]]
360                 show_usage [[passwd user@host]]
361                 return 1;
362         end
363         
364         if not host then
365                 show_message [[Please specify a JID, including a host. e.g. alice@example.com]];
366                 return 1;
367         end
368         
369         if not hosts[host] then
370                 show_warning("The host '%s' is not listed in the configuration file (or is not enabled).", host)
371                 show_warning("The user will not be able to log in until this is changed.");
372                 hosts[host] = make_host(host);
373         end
374
375         if not prosodyctl.user_exists { user = user, host = host } then
376                 show_message [[That user does not exist on this server]]
377                 return 1;
378         end
379         
380         local ok, msg = prosodyctl.passwd { user = user, host = host };
381         
382         if ok then return 0; end
383         
384         show_message(error_messages[msg])
385         return 1;
386 end
387
388 function commands.start(arg)
389         if arg[1] == "--help" then
390                 show_usage([[start]], [[Start Prosody]]);
391                 return 1;
392         end
393         local ok, ret = prosodyctl.isrunning();
394         if not ok then
395                 show_message(error_messages[ret]);
396                 return 1;
397         end
398         
399         if ret then
400                 local ok, ret = prosodyctl.getpid();
401                 if not ok then
402                         show_message("Couldn't get running Prosody's PID");
403                         show_message(error_messages[ret]);
404                         return 1;
405                 end
406                 show_message("Prosody is already running with PID %s", ret or "(unknown)");
407                 return 1;
408         end
409         
410         local ok, ret = prosodyctl.start();
411         if ok then
412                 if config.get("*", "core", "daemonize") ~= false then
413                         local i=1;
414                         while true do
415                                 local ok, running = prosodyctl.isrunning();
416                                 if ok and running then
417                                         break;
418                                 elseif i == 5 then
419                                         show_message("Still waiting...");
420                                 elseif i >= prosodyctl_timeout then
421                                         show_message("Prosody is still not running. Please give it some time or check your log files for errors.");
422                                         return 2;
423                                 end
424                                 socket.sleep(0.5);
425                                 i = i + 1;
426                         end
427                         show_message("Started");
428                 end
429                 return 0;
430         end
431
432         show_message("Failed to start Prosody");
433         show_message(error_messages[ret])       
434         return 1;       
435 end
436
437 function commands.status(arg)
438         if arg[1] == "--help" then
439                 show_usage([[status]], [[Reports the running status of Prosody]]);
440                 return 1;
441         end
442
443         local ok, ret = prosodyctl.isrunning();
444         if not ok then
445                 show_message(error_messages[ret]);
446                 return 1;
447         end
448         
449         if ret then
450                 local ok, ret = prosodyctl.getpid();
451                 if not ok then
452                         show_message("Couldn't get running Prosody's PID");
453                         show_message(error_messages[ret]);
454                         return 1;
455                 end
456                 show_message("Prosody is running with PID %s", ret or "(unknown)");
457                 return 0;
458         else
459                 show_message("Prosody is not running");
460                 if not switched_user and current_uid ~= 0 then
461                         print("\nNote:")
462                         print(" You will also see this if prosodyctl is not running under");
463                         print(" the same user account as Prosody. Try running as root (e.g. ");
464                         print(" with 'sudo' in front) to gain access to Prosody's real status.");
465                 end
466                 return 2
467         end
468         return 1;
469 end
470
471 function commands.stop(arg)
472         if arg[1] == "--help" then
473                 show_usage([[stop]], [[Stop a running Prosody server]]);
474                 return 1;
475         end
476
477         if not prosodyctl.isrunning() then
478                 show_message("Prosody is not running");
479                 return 1;
480         end
481         
482         local ok, ret = prosodyctl.stop();
483         if ok then
484                 local i=1;
485                 while true do
486                         local ok, running = prosodyctl.isrunning();
487                         if ok and not running then
488                                 break;
489                         elseif i == 5 then
490                                 show_message("Still waiting...");
491                         elseif i >= prosodyctl_timeout then
492                                 show_message("Prosody is still running. Please give it some time or check your log files for errors.");
493                                 return 2;
494                         end
495                         socket.sleep(0.5);
496                         i = i + 1;
497                 end
498                 show_message("Stopped");
499                 return 0;
500         end
501
502         show_message(error_messages[ret]);
503         return 1;
504 end
505
506 function commands.restart(arg)
507         if arg[1] == "--help" then
508                 show_usage([[restart]], [[Restart a running Prosody server]]);
509                 return 1;
510         end
511         
512         commands.stop(arg);
513         return commands.start(arg);
514 end
515
516 -- ejabberdctl compatibility
517
518 function commands.register(arg)
519         local user, host, password = unpack(arg);
520         if (not (user and host)) or arg[1] == "--help" then
521                 if user ~= "--help" then
522                         if not user then
523                                 show_message [[No username specified]]
524                         elseif not host then
525                                 show_message [[Please specify which host you want to register the user on]];
526                         end
527                 end
528                 show_usage("register USER HOST [PASSWORD]", "Register a user on the server, with the given password");
529                 return 1;
530         end
531         if not password then
532                 password = read_password();
533                 if not password then
534                         show_message [[Unable to register user with no password]];
535                         return 1;
536                 end
537         end
538         
539         local ok, msg = prosodyctl.adduser { user = user, host = host, password = password };
540         
541         if ok then return 0; end
542         
543         show_message(error_messages[msg])
544         return 1;
545 end
546
547 function commands.unregister(arg)
548         local user, host = unpack(arg);
549         if (not (user and host)) or arg[1] == "--help" then
550                 if user ~= "--help" then
551                         if not user then
552                                 show_message [[No username specified]]
553                         elseif not host then
554                                 show_message [[Please specify which host you want to unregister the user from]];
555                         end
556                 end
557                 show_usage("unregister USER HOST [PASSWORD]", "Permanently remove a user account from the server");
558                 return 1;
559         end
560
561         local ok, msg = prosodyctl.deluser { user = user, host = host };
562         
563         if ok then return 0; end
564         
565         show_message(error_messages[msg])
566         return 1;
567 end
568
569 ---------------------
570
571 if command and command:match("^mod_") then -- Is a command in a module
572         local module_name = command:match("^mod_(.+)");
573         local ret, err = modulemanager.load("*", module_name);
574         if not ret then
575                 show_message("Failed to load module '"..module_name.."': "..err);
576                 os.exit(1);
577         end
578         
579         table.remove(arg, 1);
580         
581         local module = modulemanager.get_module("*", module_name);
582         if not module then
583                 show_message("Failed to load module '"..module_name.."': Unknown error");
584                 os.exit(1);
585         end
586         
587         if not modulemanager.module_has_method(module, "command") then
588                 show_message("Fail: mod_"..module_name.." does not support any commands");
589                 os.exit(1);
590         end
591         
592         local ok, ret = modulemanager.call_module_method(module, "command", arg);
593         if ok then
594                 if type(ret) == "number" then
595                         os.exit(ret);
596                 elseif type(ret) == "string" then
597                         show_message(ret);
598                 end
599                 os.exit(0); -- :)
600         else
601                 show_message("Failed to execute command: "..error_messages[ret]);
602                 os.exit(1); -- :(
603         end
604 end
605
606 if not commands[command] then -- Show help for all commands
607         function show_usage(usage, desc)
608                 print(" "..usage);
609                 print("    "..desc);
610         end
611
612         print("prosodyctl - Manage a Prosody server");
613         print("");
614         print("Usage: "..arg[0].." COMMAND [OPTIONS]");
615         print("");
616         print("Where COMMAND may be one of:\n");
617
618         local hidden_commands = require "util.set".new{ "register", "unregister", "addplugin" };
619         local commands_order = { "adduser", "passwd", "deluser", "start", "stop", "restart" };
620
621         local done = {};
622
623         for _, command_name in ipairs(commands_order) do
624                 local command = commands[command_name];
625                 if command then
626                         command{ "--help" };
627                         print""
628                         done[command_name] = true;
629                 end
630         end
631
632         for command_name, command in pairs(commands) do
633                 if not done[command_name] and not hidden_commands:contains(command_name) then
634                         command{ "--help" };
635                         print""
636                         done[command_name] = true;
637                 end
638         end
639         
640         
641         os.exit(0);
642 end
643
644 os.exit(commands[command]({ select(2, unpack(arg)) }));