util.pposix: Replace the unwieldy module table generation with luaL_register() call...
[prosody.git] / prosodyctl
1 #!/usr/bin/env lua
2 -- Prosody IM
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 config = require "core.configmanager"
36
37 do
38         -- TODO: Check for other formats when we add support for them
39         -- Use lfs? Make a new conf/ dir?
40         local ok, level, err = config.load((CFG_CONFIGDIR or ".").."/prosody.cfg.lua");
41         if not ok then
42                 print("\n");
43                 print("**************************");
44                 if level == "parser" then
45                         print("A problem occured while reading the config file "..(CFG_CONFIGDIR or ".").."/prosody.cfg.lua");
46                         local err_line, err_message = tostring(err):match("%[string .-%]:(%d*): (.*)");
47                         print("Error"..(err_line and (" on line "..err_line) or "")..": "..(err_message or tostring(err)));
48                         print("");
49                 elseif level == "file" then
50                         print("Prosody was unable to find the configuration file.");
51                         print("We looked for: "..(CFG_CONFIGDIR or ".").."/prosody.cfg.lua");
52                         print("A sample config file is included in the Prosody download called prosody.cfg.lua.dist");
53                         print("Copy or rename it to prosody.cfg.lua and edit as necessary.");
54                 end
55                 print("More help on configuring Prosody can be found at http://prosody.im/doc/configure");
56                 print("Good luck!");
57                 print("**************************");
58                 print("");
59                 os.exit(1);
60         end
61 end
62
63 local data_path = config.get("*", "core", "data_path") or CFG_DATADIR or "data";
64 require "util.datamanager".set_data_path(data_path);
65
66 -- Switch away from root and into the prosody user --
67 local switched_user, current_uid;
68
69 local want_pposix_version = "0.3.2";
70 local ok, pposix = pcall(require, "util.pposix");
71
72 if ok and pposix then
73         if pposix._VERSION ~= want_pposix_version then print(string.format("Unknown version (%s) of binary pposix module, expected %s", tostring(pposix._VERSION), want_pposix_version)); return; end
74         current_uid = pposix.getuid();
75         if current_uid == 0 then
76                 -- We haz root!
77                 local desired_user = config.get("*", "core", "prosody_user") or "prosody";
78                 local desired_group = config.get("*", "core", "prosody_group") or desired_user;
79                 local ok, err = pposix.setgid(desired_group);
80                 if ok then
81                         ok, err = pposix.setuid(desired_user);
82                         if ok then
83                                 -- Yay!
84                                 switched_user = true;
85                         end
86                 end
87                 if not switched_user then
88                         -- Boo!
89                         print("Warning: Couldn't switch to Prosody user/group '"..tostring(desired_user).."'/'"..tostring(desired_group).."': "..tostring(err));
90                 end
91         end
92         
93         -- Set our umask to protect data files
94         pposix.umask(config.get("*", "core", "umask") or "027");
95 else
96         print("Error: Unable to load pposix module. Check that Prosody is installed correctly.")
97         print("For more help send the below error to us through http://prosody.im/discuss");
98         print(tostring(pposix))
99 end
100
101 local error_messages = setmetatable({ 
102                 ["invalid-username"] = "The given username is invalid in a Jabber ID";
103                 ["invalid-hostname"] = "The given hostname is invalid";
104                 ["no-password"] = "No password was supplied";
105                 ["no-such-user"] = "The given user does not exist on the server";
106                 ["unable-to-save-data"] = "Unable to store, perhaps you don't have permission?";
107                 ["no-pidfile"] = "There is no 'pidfile' option in the configuration file, see http://prosody.im/doc/prosodyctl#pidfile for help";
108                 ["no-such-method"] = "This module has no commands";
109                 ["not-running"] = "Prosody is not running";
110                 }, { __index = function (t,k) return "Error: "..(tostring(k):gsub("%-", " "):gsub("^.", string.upper)); end });
111
112 local events = require "util.events".new();
113
114 hosts = {};
115 prosody = { hosts = hosts, events = events };
116
117 for hostname, config in pairs(config.getconfig()) do
118         hosts[hostname] = { events = events };
119 end
120         
121 require "core.modulemanager"
122
123 require "util.prosodyctl"
124 require "socket"
125 -----------------------
126
127 function show_message(msg, ...)
128         print(msg:format(...));
129 end
130
131 function show_warning(msg, ...)
132         print(msg:format(...));
133 end
134
135 function show_usage(usage, desc)
136         print("Usage: "..arg[0].." "..usage);
137         if desc then
138                 print(" "..desc);
139         end
140 end
141
142 local function getchar(n)
143         local stty_ret = os.execute("stty raw -echo 2>/dev/null");
144         local ok, char;
145         if stty_ret == 0 then
146                 ok, char = pcall(io.read, n or 1);
147                 os.execute("stty sane");
148         else
149                 ok, char = pcall(io.read, "*l");
150                 if ok then
151                         char = char:sub(1, n or 1);
152                 end
153         end
154         if ok then
155                 return char;
156         end
157 end
158         
159 local function getpass()
160         local stty_ret = os.execute("stty -echo 2>/dev/null");
161         if stty_ret ~= 0 then
162                 io.write("\027[08m"); -- ANSI 'hidden' text attribute
163         end
164         local ok, pass = pcall(io.read, "*l");
165         if stty_ret == 0 then
166                 os.execute("stty sane");
167         else
168                 io.write("\027[00m");
169         end
170         io.write("\n");
171         if ok then
172                 return pass;
173         end
174 end
175
176 function show_yesno(prompt)
177         io.write(prompt, " ");
178         local choice = getchar():lower();
179         io.write("\n");
180         if not choice:match("%a") then
181                 choice = prompt:match("%[.-(%U).-%]$");
182                 if not choice then return nil; end
183         end
184         return (choice == "y");
185 end
186
187 local function read_password()
188         local password;
189         while true do
190                 io.write("Enter new password: ");
191                 password = getpass();
192                 if not password then
193                         show_message("No password - cancelled");
194                         return;
195                 end
196                 io.write("Retype new password: ");
197                 if getpass() ~= password then
198                         if not show_yesno [=[Passwords did not match, try again? [Y/n]]=] then
199                                 return;
200                         end
201                 else
202                         break;
203                 end
204         end
205         return password;
206 end
207
208 local prosodyctl_timeout = (config.get("*", "core", "prosodyctl_timeout") or 5) * 2;
209 -----------------------
210 local commands = {};
211 local command = arg[1];
212
213 function commands.adduser(arg)
214         if not arg[1] or arg[1] == "--help" then
215                 show_usage([[adduser JID]], [[Create the specified user account in Prosody]]);
216                 return 1;
217         end
218         local user, host = arg[1]:match("([^@]+)@(.+)");
219         if not user and host then
220                 show_message [[Failed to understand JID, please supply the JID you want to create]]
221                 show_usage [[adduser user@host]]
222                 return 1;
223         end
224         
225         if not host then
226                 show_message [[Please specify a JID, including a host. e.g. alice@example.com]];
227                 return 1;
228         end
229         
230         if prosodyctl.user_exists{ user = user, host = host } then
231                 show_message [[That user already exists]];
232                 return 1;
233         end
234         
235         if not hosts[host] then
236                 show_warning("The host '%s' is not listed in the configuration file (or is not enabled).", host)
237                 show_warning("The user will not be able to log in until this is changed.");
238         end
239         
240         local password = read_password();
241         if not password then return 1; end
242         
243         local ok, msg = prosodyctl.adduser { user = user, host = host, password = password };
244         
245         if ok then return 0; end
246         
247         show_message(error_messages[msg])
248         return 1;
249 end
250
251 function commands.passwd(arg)
252         if not arg[1] or arg[1] == "--help" then
253                 show_usage([[passwd JID]], [[Set the password for the specified user account in Prosody]]);
254                 return 1;
255         end
256         local user, host = arg[1]:match("([^@]+)@(.+)");
257         if not user and host then
258                 show_message [[Failed to understand JID, please supply the JID you want to set the password for]]
259                 show_usage [[passwd user@host]]
260                 return 1;
261         end
262         
263         if not host then
264                 show_message [[Please specify a JID, including a host. e.g. alice@example.com]];
265                 return 1;
266         end
267         
268         if not prosodyctl.user_exists { user = user, host = host } then
269                 show_message [[That user does not exist, use prosodyctl adduser to create a new user]]
270                 return 1;
271         end
272         
273         local password = read_password();
274         if not password then return 1; end
275         
276         local ok, msg = prosodyctl.passwd { user = user, host = host, password = password };
277         
278         if ok then return 0; end
279         
280         show_message(error_messages[msg])
281         return 1;
282 end
283
284 function commands.deluser(arg)
285         if not arg[1] or arg[1] == "--help" then
286                 show_usage([[deluser JID]], [[Permanently remove the specified user account from Prosody]]);
287                 return 1;
288         end
289         local user, host = arg[1]:match("([^@]+)@(.+)");
290         if not user and host then
291                 show_message [[Failed to understand JID, please supply the JID you want to set the password for]]
292                 show_usage [[passwd user@host]]
293                 return 1;
294         end
295         
296         if not host then
297                 show_message [[Please specify a JID, including a host. e.g. alice@example.com]];
298                 return 1;
299         end
300         
301         if not prosodyctl.user_exists { user = user, host = host } then
302                 show_message [[That user does not exist on this server]]
303                 return 1;
304         end
305         
306         local ok, msg = prosodyctl.passwd { user = user, host = host };
307         
308         if ok then return 0; end
309         
310         show_message(error_messages[msg])
311         return 1;
312 end
313
314 function commands.start(arg)
315         if arg[1] == "--help" then
316                 show_usage([[start]], [[Start Prosody]]);
317                 return 1;
318         end
319         local ok, ret = prosodyctl.isrunning();
320         if not ok then
321                 show_message(error_messages[ret]);
322                 return 1;
323         end
324         
325         if ret then
326                 local ok, ret = prosodyctl.getpid();
327                 if not ok then
328                         show_message("Couldn't get running Prosody's PID");
329                         show_message(error_messages[ret]);
330                         return 1;
331                 end
332                 show_message("Prosody is already running with PID %s", ret or "(unknown)");
333                 return 1;
334         end
335         
336         local ok, ret = prosodyctl.start();
337         if ok then
338                 local i=1;
339                 while true do
340                         local ok, running = prosodyctl.isrunning();
341                         if ok and running then
342                                 break;
343                         elseif i == 5 then
344                                 show_message("Still waiting...");
345                         elseif i >= prosodyctl_timeout then
346                                 show_message("Prosody is still not running. Please give it some time or check your log files for errors.");
347                                 return 2;
348                         end
349                         socket.sleep(0.5);
350                         i = i + 1;
351                 end
352                 show_message("Started");
353                 return 0;
354         end
355
356         show_message("Failed to start Prosody");
357         show_message(error_messages[ret])       
358         return 1;       
359 end
360
361 function commands.status(arg)
362         if arg[1] == "--help" then
363                 show_usage([[status]], [[Reports the running status of Prosody]]);
364                 return 1;
365         end
366
367         local ok, ret = prosodyctl.isrunning();
368         if not ok then
369                 show_message(error_messages[ret]);
370                 return 1;
371         end
372         
373         if ret then
374                 local ok, ret = prosodyctl.getpid();
375                 if not ok then
376                         show_message("Couldn't get running Prosody's PID");
377                         show_message(error_messages[ret]);
378                         return 1;
379                 end
380                 show_message("Prosody is running with PID %s", ret or "(unknown)");
381                 return 0;
382         else
383                 show_message("Prosody is not running");
384                 if not switched_user and current_uid ~= 0 then
385                         print("\nNote:")
386                         print(" You will also see this if prosodyctl is not running under");
387                         print(" the same user account as Prosody. Try running as root (e.g. ");
388                         print(" with 'sudo' in front) to gain access to Prosody's real status.");
389                 end
390                 return 2
391         end
392         return 1;
393 end
394
395 function commands.stop(arg)
396         if arg[1] == "--help" then
397                 show_usage([[stop]], [[Stop a running Prosody server]]);
398                 return 1;
399         end
400
401         if not prosodyctl.isrunning() then
402                 show_message("Prosody is not running");
403                 return 1;
404         end
405         
406         local ok, ret = prosodyctl.stop();
407         if ok then
408                 local i=1;
409                 while true do
410                         local ok, running = prosodyctl.isrunning();
411                         if ok and not running then
412                                 break;
413                         elseif i == 5 then
414                                 show_message("Still waiting...");
415                         elseif i >= prosodyctl_timeout then
416                                 show_message("Prosody is still running. Please give it some time or check your log files for errors.");
417                                 return 2;
418                         end
419                         socket.sleep(0.5);
420                         i = i + 1;
421                 end
422                 show_message("Stopped");
423                 return 0;
424         end
425
426         show_message(error_messages[ret]);
427         return 1;
428 end
429
430 -- ejabberdctl compatibility
431
432 function commands.register(arg)
433         local user, host, password = unpack(arg);
434         if (not (user and host)) or arg[1] == "--help" then
435                 if user ~= "--help" then
436                         if not user then
437                                 show_message [[No username specified]]
438                         elseif not host then
439                                 show_message [[Please specify which host you want to register the user on]];
440                         end
441                 end
442                 show_usage("register USER HOST [PASSWORD]", "Register a user on the server, with the given password");
443                 return 1;
444         end
445         if not password then
446                 password = read_password();
447                 if not password then
448                         show_message [[Unable to register user with no password]];
449                         return 1;
450                 end
451         end
452         
453         local ok, msg = prosodyctl.adduser { user = user, host = host, password = password };
454         
455         if ok then return 0; end
456         
457         show_message(error_messages[msg])
458         return 1;
459 end
460
461 function commands.unregister(arg)
462         local user, host = unpack(arg);
463         if (not (user and host)) or arg[1] == "--help" then
464                 if user ~= "--help" then
465                         if not user then
466                                 show_message [[No username specified]]
467                         elseif not host then
468                                 show_message [[Please specify which host you want to unregister the user from]];
469                         end
470                 end
471                 show_usage("unregister USER HOST [PASSWORD]", "Permanently remove a user account from the server");
472                 return 1;
473         end
474
475         local ok, msg = prosodyctl.deluser { user = user, host = host };
476         
477         if ok then return 0; end
478         
479         show_message(error_messages[msg])
480         return 1;
481 end
482
483 local http_errors = {
484         [404] = "Plugin not found, did you type the address correctly?"
485         };
486
487 function commands.addplugin(arg)
488         local url = arg[1];
489         if url:match("^http://") then
490                 local http = require "socket.http";
491                 show_message("Fetching...");
492                 local code, err = http.request(url);
493                 if not code or not tostring(err):match("^[23]") then
494                         show_message("Failed: "..(http_errors[err] or ("HTTP error "..err)));
495                         return 1;
496                 end
497                 if url:match("%.lua$") then
498                         local ok, err = datamanager.store(url:match("/mod_([^/]+)$"), "*", "plugins", {code});
499                         if not ok then
500                                 show_message("Failed to save to data store: "..err);
501                                 return 1;
502                         end
503                 end
504                 show_message("Saved. Don't forget to load the module using the config file or admin console!");
505         else
506                 show_message("Sorry, I don't understand how to fetch plugins from there.");
507         end
508 end
509
510 ---------------------
511
512 if command and command:match("^mod_") then -- Is a command in a module
513         local module_name = command:match("^mod_(.+)");
514         local ret, err = modulemanager.load("*", module_name);
515         if not ret then
516                 show_message("Failed to load module '"..module_name.."': "..err);
517                 os.exit(1);
518         end
519         
520         table.remove(arg, 1);
521         
522         local module = modulemanager.get_module("*", module_name);
523         if not module then
524                 show_message("Failed to load module '"..module_name.."': Unknown error");
525                 os.exit(1);
526         end
527         
528         if not modulemanager.module_has_method(module, "command") then
529                 show_message("Fail: mod_"..module_name.." does not support any commands");
530                 os.exit(1);
531         end
532         
533         local ok, ret = modulemanager.call_module_method(module, "command", arg);
534         if ok then
535                 if type(ret) == "number" then
536                         os.exit(ret);
537                 elseif type(ret) == "string" then
538                         show_message(ret);
539                 end
540                 os.exit(0); -- :)
541         else
542                 show_message("Failed to execute command: "..error_messages[ret]);
543                 os.exit(1); -- :(
544         end
545 end
546
547 if not commands[command] then -- Show help for all commands
548         function show_usage(usage, desc)
549                 print(" "..usage);
550                 print("    "..desc);
551         end
552
553         print("prosodyctl - Manage a Prosody server");
554         print("");
555         print("Usage: "..arg[0].." COMMAND [OPTIONS]");
556         print("");
557         print("Where COMMAND may be one of:\n");
558
559         local hidden_commands = require "util.set".new{ "register", "unregister" };
560         local commands_order = { "adduser", "passwd", "deluser" };
561
562         local done = {};
563
564         for _, command_name in ipairs(commands_order) do
565                 local command = commands[command_name];
566                 if command then
567                         command{ "--help" };
568                         print""
569                         done[command_name] = true;
570                 end
571         end
572
573         for command_name, command in pairs(commands) do
574                 if not done[command_name] and not hidden_commands:contains(command_name) then
575                         command{ "--help" };
576                         print""
577                         done[command_name] = true;
578                 end
579         end
580         
581         
582         os.exit(0);
583 end
584
585 os.exit(commands[command]({ select(2, unpack(arg)) }));