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