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