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