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