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