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