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