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