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