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