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