Merge with main branch.
[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                 ["not-running"] = "Prosody is not running";
99                 }, { __index = function (t,k) return "Error: "..(tostring(k):gsub("%-", " "):gsub("^.", string.upper)); end });
100
101 hosts = {};
102
103 require "core.hostmanager"
104 require "core.eventmanager".fire_event("server-starting");
105 require "core.modulemanager"
106
107 require "util.prosodyctl"
108 require "socket"
109 -----------------------
110
111 function show_message(msg, ...)
112         print(msg:format(...));
113 end
114
115 function show_warning(msg, ...)
116         print(msg:format(...));
117 end
118
119 function show_usage(usage, desc)
120         print("Usage: "..arg[0].." "..usage);
121         if desc then
122                 print(" "..desc);
123         end
124 end
125
126 local function getchar(n)
127         os.execute("stty raw -echo");
128         local char = io.read(n or 1);
129         os.execute("stty sane");
130         return char;
131 end
132         
133 local function getpass()
134         os.execute("stty -echo");
135         local pass = io.read("*l");
136         os.execute("stty sane");
137         io.write("\n");
138         return pass;
139 end
140
141 function show_yesno(prompt)
142         io.write(prompt, " ");
143         local choice = getchar():lower();
144         io.write("\n");
145         if not choice:match("%a") then
146                 choice = prompt:match("%[.-(%U).-%]$");
147                 if not choice then return nil; end
148         end
149         return (choice == "y");
150 end
151
152 local function read_password()
153         local password;
154         while true do
155                 io.write("Enter new password: ");
156                 password = getpass();
157                 io.write("Retype new password: ");
158                 if getpass() ~= password then
159                         if not show_yesno [=[Passwords did not match, try again? [Y/n]]=] then
160                                 return;
161                         end
162                 else
163                         break;
164                 end
165         end
166         return password;
167 end
168
169 local prosodyctl_timeout = (config.get("*", "core", "prosodyctl_timeout") or 5) * 2;
170 -----------------------
171 local commands = {};
172 local command = arg[1];
173
174 function commands.adduser(arg)
175         if not arg[1] or arg[1] == "--help" then
176                 show_usage([[adduser JID]], [[Create the specified user account in Prosody]]);
177                 return 1;
178         end
179         local user, host = arg[1]:match("([^@]+)@(.+)");
180         if not user and host then
181                 show_message [[Failed to understand JID, please supply the JID you want to create]]
182                 show_usage [[adduser user@host]]
183                 return 1;
184         end
185         
186         if not host then
187                 show_message [[Please specify a JID, including a host. e.g. alice@example.com]];
188                 return 1;
189         end
190         
191         if prosodyctl.user_exists{ user = user, host = host } then
192                 show_message [[That user already exists]];
193                 return 1;
194         end
195         
196         if not hosts[host] then
197                 show_warning("The host '%s' is not listed in the configuration file (or is not enabled).", host)
198                 show_warning("The user will not be able to log in until this is changed.");
199         end
200         
201         local password = read_password();
202         if not password then return 1; end
203         
204         local ok, msg = prosodyctl.adduser { user = user, host = host, password = password };
205         
206         if ok then return 0; end
207         
208         show_message(error_messages[msg])
209         return 1;
210 end
211
212 function commands.passwd(arg)
213         if not arg[1] or arg[1] == "--help" then
214                 show_usage([[passwd JID]], [[Set the password for the specified user account in Prosody]]);
215                 return 1;
216         end
217         local user, host = arg[1]:match("([^@]+)@(.+)");
218         if not user and host then
219                 show_message [[Failed to understand JID, please supply the JID you want to set the password for]]
220                 show_usage [[passwd user@host]]
221                 return 1;
222         end
223         
224         if not host then
225                 show_message [[Please specify a JID, including a host. e.g. alice@example.com]];
226                 return 1;
227         end
228         
229         if not prosodyctl.user_exists { user = user, host = host } then
230                 show_message [[That user does not exist, use prosodyctl adduser to create a new user]]
231                 return 1;
232         end
233         
234         local password = read_password();
235         if not password then return 1; end
236         
237         local ok, msg = prosodyctl.passwd { user = user, host = host, password = password };
238         
239         if ok then return 0; end
240         
241         show_message(error_messages[msg])
242         return 1;
243 end
244
245 function commands.deluser(arg)
246         if not arg[1] or arg[1] == "--help" then
247                 show_usage([[deluser JID]], [[Permanently remove the specified user account from Prosody]]);
248                 return 1;
249         end
250         local user, host = arg[1]:match("([^@]+)@(.+)");
251         if not user and host then
252                 show_message [[Failed to understand JID, please supply the JID you want to set the password for]]
253                 show_usage [[passwd user@host]]
254                 return 1;
255         end
256         
257         if not host then
258                 show_message [[Please specify a JID, including a host. e.g. alice@example.com]];
259                 return 1;
260         end
261         
262         if not prosodyctl.user_exists { user = user, host = host } then
263                 show_message [[That user does not exist on this server]]
264                 return 1;
265         end
266         
267         local ok, msg = prosodyctl.passwd { user = user, host = host };
268         
269         if ok then return 0; end
270         
271         show_message(error_messages[msg])
272         return 1;
273 end
274
275 function commands.start(arg)
276         if arg[1] == "--help" then
277                 show_usage([[start]], [[Start Prosody]]);
278                 return 1;
279         end
280         local ok, ret = prosodyctl.isrunning();
281         if not ok then
282                 show_message(error_messages[ret]);
283                 return 1;
284         end
285         
286         if ret then
287                 local ok, ret = prosodyctl.getpid();
288                 if not ok then
289                         show_message("Couldn't get running Prosody's PID");
290                         show_message(error_messages[ret]);
291                         return 1;
292                 end
293                 show_message("Prosody is already running with PID %s", ret or "(unknown)");
294                 return 1;
295         end
296         
297         local ok, ret = prosodyctl.start();
298         if ok then
299                 local i=1;
300                 while true do
301                         local ok, running = prosodyctl.isrunning();
302                         if ok and running then
303                                 break;
304                         elseif i == 5 then
305                                 show_message("Still waiting...");
306                         elseif i >= prosodyctl_timeout then
307                                 show_message("Prosody is still not running. Please give it some time or check your log files for errors.");
308                                 return 2;
309                         end
310                         socket.sleep(0.5);
311                         i = i + 1;
312                 end
313                 show_message("Started");
314                 return 0;
315         end
316
317         show_message("Failed to start Prosody");
318         show_message(error_messages[ret])       
319         return 1;       
320 end
321
322 function commands.status(arg)
323         if arg[1] == "--help" then
324                 show_usage([[status]], [[Reports the running status of Prosody]]);
325                 return 1;
326         end
327
328         local ok, ret = prosodyctl.isrunning();
329         if not ok then
330                 show_message(error_messages[ret]);
331                 return 1;
332         end
333         
334         if ret then
335                 local ok, ret = prosodyctl.getpid();
336                 if not ok then
337                         show_message("Couldn't get running Prosody's PID");
338                         show_message(error_messages[ret]);
339                         return 1;
340                 end
341                 show_message("Prosody is running with PID %s", ret or "(unknown)");
342                 return 0;
343         else
344                 show_message("Prosody is not running");
345                 if not switched_user and current_uid ~= 0 then
346                         print("\nNote:")
347                         print(" You will also see this if prosodyctl is not running under");
348                         print(" the same user account as Prosody. Try running as root (e.g. ");
349                         print(" with 'sudo' in front) to gain access to Prosody's real status.");
350                 end
351                 return 2
352         end
353         return 1;
354 end
355
356 function commands.stop(arg)
357         if arg[1] == "--help" then
358                 show_usage([[stop]], [[Stop a running Prosody server]]);
359                 return 1;
360         end
361
362         if not prosodyctl.isrunning() then
363                 show_message("Prosody is not running");
364                 return 1;
365         end
366         
367         local ok, ret = prosodyctl.stop();
368         if ok then
369                 local i=1;
370                 while true do
371                         local ok, running = prosodyctl.isrunning();
372                         if ok and not running then
373                                 break;
374                         elseif i == 5 then
375                                 show_message("Still waiting...");
376                         elseif i >= prosodyctl_timeout then
377                                 show_message("Prosody is still running. Please give it some time or check your log files for errors.");
378                                 return 2;
379                         end
380                         socket.sleep(0.5);
381                         i = i + 1;
382                 end
383                 show_message("Stopped");
384                 return 0;
385         end
386
387         show_message(error_messages[ret]);
388         return 1;
389 end
390
391 -- ejabberdctl compatibility
392
393 function commands.register(arg)
394         local user, host, password = unpack(arg);
395         if (not (user and host)) or arg[1] == "--help" then
396                 if user ~= "--help" then
397                         if not user then
398                                 show_message [[No username specified]]
399                         elseif not host then
400                                 show_message [[Please specify which host you want to register the user on]];
401                         end
402                 end
403                 show_usage("register USER HOST [PASSWORD]", "Register a user on the server, with the given password");
404                 return 1;
405         end
406         if not password then
407                 password = read_password();
408                 if not password then
409                         show_message [[Unable to register user with no password]];
410                         return 1;
411                 end
412         end
413         
414         local ok, msg = prosodyctl.adduser { user = user, host = host, password = password };
415         
416         if ok then return 0; end
417         
418         show_message(error_messages[msg])
419         return 1;
420 end
421
422 function commands.unregister(arg)
423         local user, host = unpack(arg);
424         if (not (user and host)) or arg[1] == "--help" then
425                 if user ~= "--help" then
426                         if not user then
427                                 show_message [[No username specified]]
428                         elseif not host then
429                                 show_message [[Please specify which host you want to unregister the user from]];
430                         end
431                 end
432                 show_usage("unregister USER HOST [PASSWORD]", "Permanently remove a user account from the server");
433                 return 1;
434         end
435
436         local ok, msg = prosodyctl.deluser { user = user, host = host };
437         
438         if ok then return 0; end
439         
440         show_message(error_messages[msg])
441         return 1;
442 end
443
444
445 ---------------------
446
447 if command:match("^mod_") then -- Is a command in a module
448         local module_name = command:match("^mod_(.+)");
449         local ret, err = modulemanager.load("*", module_name);
450         if not ret then
451                 show_message("Failed to load module '"..module_name.."': "..err);
452                 os.exit(1);
453         end
454         
455         table.remove(arg, 1);
456         
457         local module = modulemanager.get_module("*", module_name);
458         if not module then
459                 show_message("Failed to load module '"..module_name.."': Unknown error");
460                 os.exit(1);
461         end
462         
463         if not modulemanager.module_has_method(module, "command") then
464                 show_message("Fail: mod_"..module_name.." does not support any commands");
465                 os.exit(1);
466         end
467         
468         local ok, ret = modulemanager.call_module_method(module, "command", arg);
469         if ok then
470                 if type(ret) == "number" then
471                         os.exit(ret);
472                 elseif type(ret) == "string" then
473                         show_message(ret);
474                 end
475                 os.exit(0); -- :)
476         else
477                 show_message("Failed to execute command: "..error_messages[ret]);
478                 os.exit(1); -- :(
479         end
480 end
481
482 if not commands[command] then -- Show help for all commands
483         function show_usage(usage, desc)
484                 print(" "..usage);
485                 print("    "..desc);
486         end
487
488         print("prosodyctl - Manage a Prosody server");
489         print("");
490         print("Usage: "..arg[0].." COMMAND [OPTIONS]");
491         print("");
492         print("Where COMMAND may be one of:\n");
493
494         local hidden_commands = require "util.set".new{ "register", "unregister" };
495         local commands_order = { "adduser", "passwd", "deluser" };
496
497         local done = {};
498
499         for _, command_name in ipairs(commands_order) do
500                 local command = commands[command_name];
501                 if command then
502                         command{ "--help" };
503                         print""
504                         done[command_name] = true;
505                 end
506         end
507
508         for command_name, command in pairs(commands) do
509                 if not done[command_name] and not hidden_commands:contains(command_name) then
510                         command{ "--help" };
511                         print""
512                         done[command_name] = true;
513                 end
514         end
515         
516         
517         os.exit(0);
518 end
519
520 os.exit(commands[command]({ select(2, unpack(arg)) }));