Merge with 0.5
[prosody.git] / plugins / mod_xmlrpc.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2009 Matthew Wild
3 -- Copyright (C) 2008-2009 Waqas Hussain
4 -- 
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
7 --
8
9
10 module.host = "*" -- Global module
11
12 local httpserver = require "net.httpserver";
13 local st = require "util.stanza";
14 local pcall = pcall;
15 local unpack = unpack;
16 local tostring = tostring;
17 local is_admin = require "core.usermanager".is_admin;
18 local jid_split = require "util.jid".split;
19 local jid_bare = require "util.jid".bare;
20 local b64_decode = require "util.encodings".base64.decode;
21 local get_method = require "core.objectmanager".get_object;
22 local validate_credentials = require "core.usermanager".validate_credentials;
23
24 local translate_request = require "util.xmlrpc".translate_request;
25 local create_response = require "util.xmlrpc".create_response;
26 local create_error_response = require "util.xmlrpc".create_error_response;
27
28 local entity_map = setmetatable({
29         ["amp"] = "&";
30         ["gt"] = ">";
31         ["lt"] = "<";
32         ["apos"] = "'";
33         ["quot"] = "\"";
34 }, {__index = function(_, s)
35                 if s:sub(1,1) == "#" then
36                         if s:sub(2,2) == "x" then
37                                 return string.char(tonumber(s:sub(3), 16));
38                         else
39                                 return string.char(tonumber(s:sub(2)));
40                         end
41                 end
42         end
43 });
44 local function xml_unescape(str)
45         return (str:gsub("&(.-);", entity_map));
46 end
47 local function parse_xml(xml)
48         local stanza = st.stanza("root");
49         local regexp = "<([^>]*)>([^<]*)";
50         for elem, text in xml:gmatch(regexp) do
51                 --print("[<"..elem..">|"..text.."]");
52                 if elem:sub(1,1) == "!" or elem:sub(1,1) == "?" then -- neglect comments and processing-instructions
53                 elseif elem:sub(1,1) == "/" then -- end tag
54                         elem = elem:sub(2);
55                         stanza:up(); -- TODO check for start-end tag name match
56                 elseif elem:sub(-1,-1) == "/" then -- empty tag
57                         elem = elem:sub(1,-2);
58                         stanza:tag(elem):up();
59                 else -- start tag
60                         stanza:tag(elem);
61                 end
62                 if #text ~= 0 then -- text
63                         stanza:text(xml_unescape(text));
64                 end
65         end
66         return stanza.tags[1];
67 end
68
69 local function handle_xmlrpc_request(jid, method, args)
70         local is_secure_call = (method:sub(1,7) == "secure/");
71         if not is_admin(jid) and not is_secure_call then
72                 return create_error_response(401, "not authorized");
73         end
74         method = get_method(method);
75         if not method then return create_error_response(404, "method not found"); end
76         args = args or {};
77         if is_secure_call then table.insert(args, 1, jid); end
78         local success, result = pcall(method, unpack(args));
79         if success then
80                 success, result = pcall(create_response, result or "nil");
81                 if success then
82                         return result;
83                 end
84                 return create_error_response(500, "Error in creating response: "..result);
85         end
86         return create_error_response(0, (result and result:gmatch("[^:]*:[^:]*: (.*)")()) or "nil");
87 end
88
89 local function handle_xmpp_request(origin, stanza)
90         local query = stanza.tags[1];
91         if query.name == "query" then
92                 if #query.tags == 1 then
93                         local success, method, args = pcall(translate_request, query.tags[1]);
94                         if success then
95                                 local result = handle_xmlrpc_request(jid_bare(stanza.attr.from), method, args);
96                                 origin.send(st.reply(stanza):tag('query', {xmlns='jabber:iq:rpc'}):add_child(result));
97                         else
98                                 origin.send(st.error_reply(stanza, "modify", "bad-request", method));
99                         end
100                 else origin.send(st.error_reply(stanza, "modify", "bad-request", "No content in XML-RPC request")); end
101         else origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); end
102 end
103 module:add_iq_handler({"c2s", "s2sin"}, "jabber:iq:rpc", handle_xmpp_request);
104 module:add_feature("jabber:iq:rpc");
105 -- TODO add <identity category='automation' type='rpc'/> to disco replies
106
107 local default_headers = { ['Content-Type'] = 'text/xml' };
108 local unauthorized_response = { status = '401 UNAUTHORIZED', headers = {['Content-Type']='text/html', ['WWW-Authenticate']='Basic realm="WallyWorld"'}; body = "<html><body>Authentication required</body></html>"; };
109 local function handle_http_request(method, body, request)
110         -- authenticate user
111         local username, password = b64_decode(request['authorization'] or ''):gmatch('([^:]*):(.*)')(); -- TODO digest auth
112         local node, host = jid_split(username);
113         if not validate_credentials(host, node, password) then
114                 return unauthorized_response;
115         end
116         -- parse request
117         local stanza = body and parse_xml(body);
118         if (not stanza) or request.method ~= "POST" then
119                 return "<html><body>You really don't look like an XML-RPC client to me... what do you want?</body></html>";
120         end
121         -- execute request
122         local success, method, args = pcall(translate_request, stanza);
123         if success then
124                 return { headers = default_headers; body = tostring(handle_xmlrpc_request(node.."@"..host, method, args)) };
125         end
126         return "<html><body>Error parsing XML-RPC request: "..tostring(method).."</body></html>";
127 end
128 httpserver.new{ port = 9000, base = "xmlrpc", handler = handle_http_request }