mod_component: xpcall() stanza processing, as per other listeners, preventing potenti...
[prosody.git] / plugins / mod_component.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 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 module:set_global();
10
11 local t_concat = table.concat;
12 local traceback = debug.traceback;
13
14 local logger = require "util.logger";
15 local sha1 = require "util.hashes".sha1;
16 local st = require "util.stanza";
17
18 local jid_split = require "util.jid".split;
19 local new_xmpp_stream = require "util.xmppstream".new;
20 local uuid_gen = require "util.uuid".generate;
21
22 local core_process_stanza = prosody.core_process_stanza;
23 local hosts = prosody.hosts;
24
25 local log = module._log;
26
27 local sessions = module:shared("sessions");
28
29 function module.add_host(module)
30         if module:get_host_type() ~= "component" then
31                 error("Don't load mod_component manually, it should be for a component, please see http://prosody.im/doc/components", 0);
32         end
33         
34         local env = module.environment;
35         env.connected = false;
36
37         local send;
38
39         local function on_destroy(session, err)
40                 env.connected = false;
41                 send = nil;
42                 session.on_destroy = nil;
43         end
44         
45         -- Handle authentication attempts by component
46         local function handle_component_auth(event)
47                 local session, stanza = event.origin, event.stanza;
48                 
49                 if session.type ~= "component_unauthed" then return; end
50         
51                 if (not session.host) or #stanza.tags > 0 then
52                         (session.log or log)("warn", "Invalid component handshake for host: %s", session.host);
53                         session:close("not-authorized");
54                         return true;
55                 end
56                 
57                 local secret = module:get_option("component_secret");
58                 if not secret then
59                         (session.log or log)("warn", "Component attempted to identify as %s, but component_secret is not set", session.host);
60                         session:close("not-authorized");
61                         return true;
62                 end
63                 
64                 local supplied_token = t_concat(stanza);
65                 local calculated_token = sha1(session.streamid..secret, true);
66                 if supplied_token:lower() ~= calculated_token:lower() then
67                         module:log("info", "Component authentication failed for %s", session.host);
68                         session:close{ condition = "not-authorized", text = "Given token does not match calculated token" };
69                         return true;
70                 end
71                 
72                 if env.connected then
73                         module:log("error", "Second component attempted to connect, denying connection");
74                         session:close{ condition = "conflict", text = "Component already connected" };
75                         return true;
76                 end
77                 
78                 env.connected = true;
79                 send = session.send;
80                 session.on_destroy = on_destroy;
81                 session.component_validate_from = module:get_option_boolean("validate_from_addresses", true);
82                 session.type = "component";
83                 module:log("info", "External component successfully authenticated");
84                 session.send(st.stanza("handshake"));
85         
86                 return true;
87         end
88         module:hook("stanza/jabber:component:accept:handshake", handle_component_auth);
89
90         -- Handle stanzas addressed to this component
91         local function handle_stanza(event)
92                 local stanza = event.stanza;
93                 if send then
94                         stanza.attr.xmlns = nil;
95                         send(stanza);
96                 else
97                         if stanza.name == "iq" and stanza.attr.type == "get" and stanza.attr.to == module.host then
98                                 local query = stanza.tags[1];
99                                 local node = query.attr.node;
100                                 if query.name == "query" and query.attr.xmlns == "http://jabber.org/protocol/disco#info" and (not node or node == "") then
101                                         local name = module:get_option_string("name");
102                                         if name then
103                                                 event.origin.send(st.reply(stanza):tag("query", { xmlns = "http://jabber.org/protocol/disco#info" })
104                                                         :tag("identity", { category = "component", type = "generic", name = module:get_option_string("name", "Prosody") }))
105                                                 return true;
106                                         end
107                                 end
108                         end
109                         module:log("warn", "Component not connected, bouncing error for: %s", stanza:top_tag());
110                         if stanza.attr.type ~= "error" and stanza.attr.type ~= "result" then
111                                 event.origin.send(st.error_reply(stanza, "wait", "service-unavailable", "Component unavailable"));
112                         end
113                 end
114                 return true;
115         end
116         
117         module:hook("iq/bare", handle_stanza, -1);
118         module:hook("message/bare", handle_stanza, -1);
119         module:hook("presence/bare", handle_stanza, -1);
120         module:hook("iq/full", handle_stanza, -1);
121         module:hook("message/full", handle_stanza, -1);
122         module:hook("presence/full", handle_stanza, -1);
123         module:hook("iq/host", handle_stanza, -1);
124         module:hook("message/host", handle_stanza, -1);
125         module:hook("presence/host", handle_stanza, -1);
126 end
127
128 --- Network and stream part ---
129
130 local xmlns_component = 'jabber:component:accept';
131
132 local listener = {};
133
134 --- Callbacks/data for xmppstream to handle streams for us ---
135
136 local stream_callbacks = { default_ns = xmlns_component };
137
138 local xmlns_xmpp_streams = "urn:ietf:params:xml:ns:xmpp-streams";
139
140 function stream_callbacks.error(session, error, data, data2)
141         if session.destroyed then return; end
142         module:log("warn", "Error processing component stream: %s", tostring(error));
143         if error == "no-stream" then
144                 session:close("invalid-namespace");
145         elseif error == "parse-error" then
146                 session.log("warn", "External component %s XML parse error: %s", tostring(session.host), tostring(data));
147                 session:close("not-well-formed");
148         elseif error == "stream-error" then
149                 local condition, text = "undefined-condition";
150                 for child in data:children() do
151                         if child.attr.xmlns == xmlns_xmpp_streams then
152                                 if child.name ~= "text" then
153                                         condition = child.name;
154                                 else
155                                         text = child:get_text();
156                                 end
157                                 if condition ~= "undefined-condition" and text then
158                                         break;
159                                 end
160                         end
161                 end
162                 text = condition .. (text and (" ("..text..")") or "");
163                 session.log("info", "Session closed by remote with error: %s", text);
164                 session:close(nil, text);
165         end
166 end
167
168 function stream_callbacks.streamopened(session, attr)
169         if not hosts[attr.to] or not hosts[attr.to].modules.component then
170                 session:close{ condition = "host-unknown", text = tostring(attr.to).." does not match any configured external components" };
171                 return;
172         end
173         session.host = attr.to;
174         session.streamid = uuid_gen();
175         session.notopen = nil;
176         -- Return stream header
177         session.send("<?xml version='1.0'?>");
178         session.send(st.stanza("stream:stream", { xmlns=xmlns_component,
179                         ["xmlns:stream"]='http://etherx.jabber.org/streams', id=session.streamid, from=session.host }):top_tag());
180 end
181
182 function stream_callbacks.streamclosed(session)
183         session.log("debug", "Received </stream:stream>");
184         session:close();
185 end
186
187 local function handleerr(err) log("error", "Traceback[component]: %s", traceback(tostring(err), 2)); end
188 function stream_callbacks.handlestanza(session, stanza)
189         -- Namespaces are icky.
190         if not stanza.attr.xmlns and stanza.name == "handshake" then
191                 stanza.attr.xmlns = xmlns_component;
192         end
193         if not stanza.attr.xmlns or stanza.attr.xmlns == "jabber:client" then
194                 local from = stanza.attr.from;
195                 if from then
196                         if session.component_validate_from then
197                                 local _, domain = jid_split(stanza.attr.from);
198                                 if domain ~= session.host then
199                                         -- Return error
200                                         session.log("warn", "Component sent stanza with missing or invalid 'from' address");
201                                         session:close{
202                                                 condition = "invalid-from";
203                                                 text = "Component tried to send from address <"..tostring(from)
204                                                            .."> which is not in domain <"..tostring(session.host)..">";
205                                         };
206                                         return;
207                                 end
208                         end
209                 else
210                         stanza.attr.from = session.host; -- COMPAT: Strictly we shouldn't allow this
211                 end
212                 if not stanza.attr.to then
213                         session.log("warn", "Rejecting stanza with no 'to' address");
214                         session.send(st.error_reply(stanza, "modify", "bad-request", "Components MUST specify a 'to' address on stanzas"));
215                         return;
216                 end
217         end
218
219         if stanza then
220                 return xpcall(function () return core_process_stanza(session, stanza) end, handleerr);
221         end
222 end
223
224 --- Closing a component connection
225 local stream_xmlns_attr = {xmlns='urn:ietf:params:xml:ns:xmpp-streams'};
226 local default_stream_attr = { ["xmlns:stream"] = "http://etherx.jabber.org/streams", xmlns = stream_callbacks.default_ns, version = "1.0", id = "" };
227 local function session_close(session, reason)
228         if session.destroyed then return; end
229         if session.conn then
230                 if session.notopen then
231                         session.send("<?xml version='1.0'?>");
232                         session.send(st.stanza("stream:stream", default_stream_attr):top_tag());
233                 end
234                 if reason then
235                         if type(reason) == "string" then -- assume stream error
236                                 module:log("info", "Disconnecting component, <stream:error> is: %s", reason);
237                                 session.send(st.stanza("stream:error"):tag(reason, {xmlns = 'urn:ietf:params:xml:ns:xmpp-streams' }));
238                         elseif type(reason) == "table" then
239                                 if reason.condition then
240                                         local stanza = st.stanza("stream:error"):tag(reason.condition, stream_xmlns_attr):up();
241                                         if reason.text then
242                                                 stanza:tag("text", stream_xmlns_attr):text(reason.text):up();
243                                         end
244                                         if reason.extra then
245                                                 stanza:add_child(reason.extra);
246                                         end
247                                         module:log("info", "Disconnecting component, <stream:error> is: %s", tostring(stanza));
248                                         session.send(stanza);
249                                 elseif reason.name then -- a stanza
250                                         module:log("info", "Disconnecting component, <stream:error> is: %s", tostring(reason));
251                                         session.send(reason);
252                                 end
253                         end
254                 end
255                 session.send("</stream:stream>");
256                 session.conn:close();
257                 listener.ondisconnect(session.conn, "stream error");
258         end
259 end
260
261 --- Component connlistener
262
263 function listener.onconnect(conn)
264         local _send = conn.write;
265         local session = { type = "component_unauthed", conn = conn, send = function (data) return _send(conn, tostring(data)); end };
266
267         -- Logging functions --
268         local conn_name = "jcp"..tostring(session):match("[a-f0-9]+$");
269         session.log = logger.init(conn_name);
270         session.close = session_close;
271         
272         session.log("info", "Incoming Jabber component connection");
273         
274         local stream = new_xmpp_stream(session, stream_callbacks);
275         session.stream = stream;
276         
277         session.notopen = true;
278         
279         function session.reset_stream()
280                 session.notopen = true;
281                 session.stream:reset();
282         end
283
284         function session.data(conn, data)
285                 local ok, err = stream:feed(data);
286                 if ok then return; end
287                 module:log("debug", "Received invalid XML (%s) %d bytes: %s", tostring(err), #data, data:sub(1, 300):gsub("[\r\n]+", " "):gsub("[%z\1-\31]", "_"));
288                 session:close("not-well-formed");
289         end
290         
291         session.dispatch_stanza = stream_callbacks.handlestanza;
292
293         sessions[conn] = session;
294 end
295 function listener.onincoming(conn, data)
296         local session = sessions[conn];
297         session.data(conn, data);
298 end
299 function listener.ondisconnect(conn, err)
300         local session = sessions[conn];
301         if session then
302                 (session.log or log)("info", "component disconnected: %s (%s)", tostring(session.host), tostring(err));
303                 if session.on_destroy then session:on_destroy(err); end
304                 sessions[conn] = nil;
305                 for k in pairs(session) do
306                         if k ~= "log" and k ~= "close" then
307                                 session[k] = nil;
308                         end
309                 end
310                 session.destroyed = true;
311                 session = nil;
312         end
313 end
314
315 module:provides("net", {
316         name = "component";
317         private = true;
318         listener = listener;
319         default_port = 5347;
320         multiplex = {
321                 pattern = "^<.*:stream.*%sxmlns%s*=%s*(['\"])jabber:component:accept%1.*>";
322         };
323 });