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