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