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