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