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