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