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