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