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