prosodyctl: Instead of calling datamanager.set_path(), just ensure prosody.paths...
[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 prosody.paths = { source = CFG_SOURCEDIR, config = CFG_CONFIGDIR, 
114                   plugins = CFG_PLUGINDIR, data = data_path };
115
116 require "core.loggingmanager"
117
118 dependencies.log_warnings();
119
120 -- Switch away from root and into the prosody user --
121 local switched_user, current_uid;
122
123 local want_pposix_version = "0.3.5";
124 local ok, pposix = pcall(require, "util.pposix");
125
126 if ok and pposix then
127         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
128         current_uid = pposix.getuid();
129         if current_uid == 0 then
130                 -- We haz root!
131                 local desired_user = config.get("*", "core", "prosody_user") or "prosody";
132                 local desired_group = config.get("*", "core", "prosody_group") or desired_user;
133                 local ok, err = pposix.setgid(desired_group);
134                 if ok then
135                         ok, err = pposix.initgroups(desired_user);
136                 end
137                 if ok then
138                         ok, err = pposix.setuid(desired_user);
139                         if ok then
140                                 -- Yay!
141                                 switched_user = true;
142                         end
143                 end
144                 if not switched_user then
145                         -- Boo!
146                         print("Warning: Couldn't switch to Prosody user/group '"..tostring(desired_user).."'/'"..tostring(desired_group).."': "..tostring(err));
147                 end
148         end
149         
150         -- Set our umask to protect data files
151         pposix.umask(config.get("*", "core", "umask") or "027");
152 else
153         print("Error: Unable to load pposix module. Check that Prosody is installed correctly.")
154         print("For more help send the below error to us through http://prosody.im/discuss");
155         print(tostring(pposix))
156 end
157
158 local function test_writeable(filename)
159         local f, err = io.open(filename, "a");
160         if not f then
161                 return false, err;
162         end
163         f:close();
164         return true;
165 end
166
167 local unwriteable_files = {};
168 if type(original_logging_config) == "string" and original_logging_config:sub(1,1) ~= "*" then
169         local ok, err = test_writeable(original_logging_config);
170         if not ok then
171                 table.insert(unwriteable_files, err);
172         end
173 elseif type(original_logging_config) == "table" then
174         for _, rule in ipairs(original_logging_config) do
175                 if rule.filename then
176                         local ok, err = test_writeable(rule.filename);
177                         if not ok then
178                                 table.insert(unwriteable_files, err);
179                         end
180                 end
181         end
182 end
183
184 if #unwriteable_files > 0 then
185         print("One of more of the Prosody log files are not");
186         print("writeable, please correct the errors and try");
187         print("starting prosodyctl again.");
188         print("");
189         for _, err in ipairs(unwriteable_files) do
190                 print(err);
191         end
192         print("");
193         os.exit(1);
194 end
195
196
197 local error_messages = setmetatable({ 
198                 ["invalid-username"] = "The given username is invalid in a Jabber ID";
199                 ["invalid-hostname"] = "The given hostname is invalid";
200                 ["no-password"] = "No password was supplied";
201                 ["no-such-user"] = "The given user does not exist on the server";
202                 ["unable-to-save-data"] = "Unable to store, perhaps you don't have permission?";
203                 ["no-pidfile"] = "There is no 'pidfile' option in the configuration file, see http://prosody.im/doc/prosodyctl#pidfile for help";
204                 ["no-posix"] = "The mod_posix module is not enabled in the Prosody config file, see http://prosody.im/doc/prosodyctl for more info";
205                 ["no-such-method"] = "This module has no commands";
206                 ["not-running"] = "Prosody is not running";
207                 }, { __index = function (t,k) return "Error: "..(tostring(k):gsub("%-", " "):gsub("^.", string.upper)); end });
208
209 hosts = prosody.hosts;
210
211 local function make_host(hostname)
212         return {
213                 type = "local",
214                 events = prosody.events,
215                 users = require "core.usermanager".new_null_provider(hostname)
216         };
217 end
218
219 for hostname, config in pairs(config.getconfig()) do
220         hosts[hostname] = make_host(hostname);
221 end
222         
223 require "core.modulemanager"
224
225 require "util.prosodyctl"
226 require "socket"
227 -----------------------
228
229 function show_message(msg, ...)
230         print(msg:format(...));
231 end
232
233 function show_warning(msg, ...)
234         print(msg:format(...));
235 end
236
237 function show_usage(usage, desc)
238         print("Usage: "..arg[0].." "..usage);
239         if desc then
240                 print(" "..desc);
241         end
242 end
243
244 local function getchar(n)
245         local stty_ret = os.execute("stty raw -echo 2>/dev/null");
246         local ok, char;
247         if stty_ret == 0 then
248                 ok, char = pcall(io.read, n or 1);
249                 os.execute("stty sane");
250         else
251                 ok, char = pcall(io.read, "*l");
252                 if ok then
253                         char = char:sub(1, n or 1);
254                 end
255         end
256         if ok then
257                 return char;
258         end
259 end
260         
261 local function getpass()
262         local stty_ret = os.execute("stty -echo 2>/dev/null");
263         if stty_ret ~= 0 then
264                 io.write("\027[08m"); -- ANSI 'hidden' text attribute
265         end
266         local ok, pass = pcall(io.read, "*l");
267         if stty_ret == 0 then
268                 os.execute("stty sane");
269         else
270                 io.write("\027[00m");
271         end
272         io.write("\n");
273         if ok then
274                 return pass;
275         end
276 end
277
278 function show_yesno(prompt)
279         io.write(prompt, " ");
280         local choice = getchar():lower();
281         io.write("\n");
282         if not choice:match("%a") then
283                 choice = prompt:match("%[.-(%U).-%]$");
284                 if not choice then return nil; end
285         end
286         return (choice == "y");
287 end
288
289 local function read_password()
290         local password;
291         while true do
292                 io.write("Enter new password: ");
293                 password = getpass();
294                 if not password then
295                         show_message("No password - cancelled");
296                         return;
297                 end
298                 io.write("Retype new password: ");
299                 if getpass() ~= password then
300                         if not show_yesno [=[Passwords did not match, try again? [Y/n]]=] then
301                                 return;
302                         end
303                 else
304                         break;
305                 end
306         end
307         return password;
308 end
309
310 local prosodyctl_timeout = (config.get("*", "core", "prosodyctl_timeout") or 5) * 2;
311 -----------------------
312 local commands = {};
313 local command = arg[1];
314
315 function commands.adduser(arg)
316         if not arg[1] or arg[1] == "--help" then
317                 show_usage([[adduser JID]], [[Create the specified user account in Prosody]]);
318                 return 1;
319         end
320         local user, host = arg[1]:match("([^@]+)@(.+)");
321         if not user and host then
322                 show_message [[Failed to understand JID, please supply the JID you want to create]]
323                 show_usage [[adduser user@host]]
324                 return 1;
325         end
326         
327         if not host then
328                 show_message [[Please specify a JID, including a host. e.g. alice@example.com]];
329                 return 1;
330         end
331         
332         if not hosts[host] then
333                 show_warning("The host '%s' is not listed in the configuration file (or is not enabled).", host)
334                 show_warning("The user will not be able to log in until this is changed.");
335                 hosts[host] = make_host(host);
336         end
337         
338         if prosodyctl.user_exists{ user = user, host = host } then
339                 show_message [[That user already exists]];
340                 return 1;
341         end
342         
343         local password = read_password();
344         if not password then return 1; end
345         
346         local ok, msg = prosodyctl.adduser { user = user, host = host, password = password };
347         
348         if ok then return 0; end
349         
350         show_message(msg)
351         return 1;
352 end
353
354 function commands.passwd(arg)
355         if not arg[1] or arg[1] == "--help" then
356                 show_usage([[passwd JID]], [[Set the password for the specified user account in Prosody]]);
357                 return 1;
358         end
359         local user, host = arg[1]:match("([^@]+)@(.+)");
360         if not user and host then
361                 show_message [[Failed to understand JID, please supply the JID you want to set the password for]]
362                 show_usage [[passwd user@host]]
363                 return 1;
364         end
365         
366         if not host then
367                 show_message [[Please specify a JID, including a host. e.g. alice@example.com]];
368                 return 1;
369         end
370         
371         if not hosts[host] then
372                 show_warning("The host '%s' is not listed in the configuration file (or is not enabled).", host)
373                 show_warning("The user will not be able to log in until this is changed.");
374                 hosts[host] = make_host(host);
375         end
376         
377         if not prosodyctl.user_exists { user = user, host = host } then
378                 show_message [[That user does not exist, use prosodyctl adduser to create a new user]]
379                 return 1;
380         end
381         
382         local password = read_password();
383         if not password then return 1; end
384         
385         local ok, msg = prosodyctl.passwd { user = user, host = host, password = password };
386         
387         if ok then return 0; end
388         
389         show_message(error_messages[msg])
390         return 1;
391 end
392
393 function commands.deluser(arg)
394         if not arg[1] or arg[1] == "--help" then
395                 show_usage([[deluser JID]], [[Permanently remove the specified user account from Prosody]]);
396                 return 1;
397         end
398         local user, host = arg[1]:match("([^@]+)@(.+)");
399         if not user and host then
400                 show_message [[Failed to understand JID, please supply the JID you want to set the password for]]
401                 show_usage [[passwd user@host]]
402                 return 1;
403         end
404         
405         if not host then
406                 show_message [[Please specify a JID, including a host. e.g. alice@example.com]];
407                 return 1;
408         end
409         
410         if not hosts[host] then
411                 show_warning("The host '%s' is not listed in the configuration file (or is not enabled).", host)
412                 show_warning("The user will not be able to log in until this is changed.");
413                 hosts[host] = make_host(host);
414         end
415
416         if not prosodyctl.user_exists { user = user, host = host } then
417                 show_message [[That user does not exist on this server]]
418                 return 1;
419         end
420         
421         local ok, msg = prosodyctl.passwd { user = user, host = host };
422         
423         if ok then return 0; end
424         
425         show_message(error_messages[msg])
426         return 1;
427 end
428
429 function commands.start(arg)
430         if arg[1] == "--help" then
431                 show_usage([[start]], [[Start Prosody]]);
432                 return 1;
433         end
434         local ok, ret = prosodyctl.isrunning();
435         if not ok then
436                 show_message(error_messages[ret]);
437                 return 1;
438         end
439         
440         if ret then
441                 local ok, ret = prosodyctl.getpid();
442                 if not ok then
443                         show_message("Couldn't get running Prosody's PID");
444                         show_message(error_messages[ret]);
445                         return 1;
446                 end
447                 show_message("Prosody is already running with PID %s", ret or "(unknown)");
448                 return 1;
449         end
450         
451         local ok, ret = prosodyctl.start();
452         if ok then
453                 if config.get("*", "core", "daemonize") ~= false then
454                         local i=1;
455                         while true do
456                                 local ok, running = prosodyctl.isrunning();
457                                 if ok and running then
458                                         break;
459                                 elseif i == 5 then
460                                         show_message("Still waiting...");
461                                 elseif i >= prosodyctl_timeout then
462                                         show_message("Prosody is still not running. Please give it some time or check your log files for errors.");
463                                         return 2;
464                                 end
465                                 socket.sleep(0.5);
466                                 i = i + 1;
467                         end
468                         show_message("Started");
469                 end
470                 return 0;
471         end
472
473         show_message("Failed to start Prosody");
474         show_message(error_messages[ret])       
475         return 1;       
476 end
477
478 function commands.status(arg)
479         if arg[1] == "--help" then
480                 show_usage([[status]], [[Reports the running status of Prosody]]);
481                 return 1;
482         end
483
484         local ok, ret = prosodyctl.isrunning();
485         if not ok then
486                 show_message(error_messages[ret]);
487                 return 1;
488         end
489         
490         if ret then
491                 local ok, ret = prosodyctl.getpid();
492                 if not ok then
493                         show_message("Couldn't get running Prosody's PID");
494                         show_message(error_messages[ret]);
495                         return 1;
496                 end
497                 show_message("Prosody is running with PID %s", ret or "(unknown)");
498                 return 0;
499         else
500                 show_message("Prosody is not running");
501                 if not switched_user and current_uid ~= 0 then
502                         print("\nNote:")
503                         print(" You will also see this if prosodyctl is not running under");
504                         print(" the same user account as Prosody. Try running as root (e.g. ");
505                         print(" with 'sudo' in front) to gain access to Prosody's real status.");
506                 end
507                 return 2
508         end
509         return 1;
510 end
511
512 function commands.stop(arg)
513         if arg[1] == "--help" then
514                 show_usage([[stop]], [[Stop a running Prosody server]]);
515                 return 1;
516         end
517
518         if not prosodyctl.isrunning() then
519                 show_message("Prosody is not running");
520                 return 1;
521         end
522         
523         local ok, ret = prosodyctl.stop();
524         if ok then
525                 local i=1;
526                 while true do
527                         local ok, running = prosodyctl.isrunning();
528                         if ok and not running then
529                                 break;
530                         elseif i == 5 then
531                                 show_message("Still waiting...");
532                         elseif i >= prosodyctl_timeout then
533                                 show_message("Prosody is still running. Please give it some time or check your log files for errors.");
534                                 return 2;
535                         end
536                         socket.sleep(0.5);
537                         i = i + 1;
538                 end
539                 show_message("Stopped");
540                 return 0;
541         end
542
543         show_message(error_messages[ret]);
544         return 1;
545 end
546
547 function commands.restart(arg)
548         if arg[1] == "--help" then
549                 show_usage([[restart]], [[Restart a running Prosody server]]);
550                 return 1;
551         end
552         
553         commands.stop(arg);
554         return commands.start(arg);
555 end
556
557 -- ejabberdctl compatibility
558
559 function commands.register(arg)
560         local user, host, password = unpack(arg);
561         if (not (user and host)) or arg[1] == "--help" then
562                 if user ~= "--help" then
563                         if not user then
564                                 show_message [[No username specified]]
565                         elseif not host then
566                                 show_message [[Please specify which host you want to register the user on]];
567                         end
568                 end
569                 show_usage("register USER HOST [PASSWORD]", "Register a user on the server, with the given password");
570                 return 1;
571         end
572         if not password then
573                 password = read_password();
574                 if not password then
575                         show_message [[Unable to register user with no password]];
576                         return 1;
577                 end
578         end
579         
580         local ok, msg = prosodyctl.adduser { user = user, host = host, password = password };
581         
582         if ok then return 0; end
583         
584         show_message(error_messages[msg])
585         return 1;
586 end
587
588 function commands.unregister(arg)
589         local user, host = unpack(arg);
590         if (not (user and host)) or arg[1] == "--help" then
591                 if user ~= "--help" then
592                         if not user then
593                                 show_message [[No username specified]]
594                         elseif not host then
595                                 show_message [[Please specify which host you want to unregister the user from]];
596                         end
597                 end
598                 show_usage("unregister USER HOST [PASSWORD]", "Permanently remove a user account from the server");
599                 return 1;
600         end
601
602         local ok, msg = prosodyctl.deluser { user = user, host = host };
603         
604         if ok then return 0; end
605         
606         show_message(error_messages[msg])
607         return 1;
608 end
609
610 ---------------------
611
612 if command and command:match("^mod_") then -- Is a command in a module
613         local module_name = command:match("^mod_(.+)");
614         local ret, err = modulemanager.load("*", module_name);
615         if not ret then
616                 show_message("Failed to load module '"..module_name.."': "..err);
617                 os.exit(1);
618         end
619         
620         table.remove(arg, 1);
621         
622         local module = modulemanager.get_module("*", module_name);
623         if not module then
624                 show_message("Failed to load module '"..module_name.."': Unknown error");
625                 os.exit(1);
626         end
627         
628         if not modulemanager.module_has_method(module, "command") then
629                 show_message("Fail: mod_"..module_name.." does not support any commands");
630                 os.exit(1);
631         end
632         
633         local ok, ret = modulemanager.call_module_method(module, "command", arg);
634         if ok then
635                 if type(ret) == "number" then
636                         os.exit(ret);
637                 elseif type(ret) == "string" then
638                         show_message(ret);
639                 end
640                 os.exit(0); -- :)
641         else
642                 show_message("Failed to execute command: "..error_messages[ret]);
643                 os.exit(1); -- :(
644         end
645 end
646
647 if not commands[command] then -- Show help for all commands
648         function show_usage(usage, desc)
649                 print(" "..usage);
650                 print("    "..desc);
651         end
652
653         print("prosodyctl - Manage a Prosody server");
654         print("");
655         print("Usage: "..arg[0].." COMMAND [OPTIONS]");
656         print("");
657         print("Where COMMAND may be one of:\n");
658
659         local hidden_commands = require "util.set".new{ "register", "unregister", "addplugin" };
660         local commands_order = { "adduser", "passwd", "deluser", "start", "stop", "restart" };
661
662         local done = {};
663
664         for _, command_name in ipairs(commands_order) do
665                 local command = commands[command_name];
666                 if command then
667                         command{ "--help" };
668                         print""
669                         done[command_name] = true;
670                 end
671         end
672
673         for command_name, command in pairs(commands) do
674                 if not done[command_name] and not hidden_commands:contains(command_name) then
675                         command{ "--help" };
676                         print""
677                         done[command_name] = true;
678                 end
679         end
680         
681         
682         os.exit(0);
683 end
684
685 os.exit(commands[command]({ select(2, unpack(arg)) }));