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