2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
11 local t_concat = table.concat;
12 local xpcall, tostring, type = xpcall, tostring, type;
13 local traceback = debug.traceback;
15 local logger = require "util.logger";
16 local sha1 = require "util.hashes".sha1;
17 local st = require "util.stanza";
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;
23 local core_process_stanza = prosody.core_process_stanza;
24 local hosts = prosody.hosts;
26 local log = module._log;
28 local opt_keepalives = module:get_option_boolean("component_tcp_keepalives", module:get_option_boolean("tcp_keepalives", true));
30 local sessions = module:shared("sessions");
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);
37 local env = module.environment;
38 env.connected = false;
42 local function on_destroy(session, err)
43 env.connected = false;
45 session.on_destroy = nil;
48 -- Handle authentication attempts by component
49 local function handle_component_auth(event)
50 local session, stanza = event.origin, event.stanza;
52 if session.type ~= "component_unauthed" then return; end
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");
60 local secret = module:get_option("component_secret");
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");
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" };
76 module:log("error", "Second component attempted to connect, denying connection");
77 session:close{ condition = "conflict", text = "Component already connected" };
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 module:fire_event("component-authenticated", { session = session });
92 module:hook("stanza/jabber:component:accept:handshake", handle_component_auth, -1);
94 -- Handle stanzas addressed to this component
95 local function handle_stanza(event)
96 local stanza = event.stanza;
98 stanza.attr.xmlns = nil;
101 if stanza.name == "iq" and stanza.attr.type == "get" and stanza.attr.to == module.host then
102 local query = stanza.tags[1];
103 local node = query.attr.node;
104 if query.name == "query" and query.attr.xmlns == "http://jabber.org/protocol/disco#info" and (not node or node == "") then
105 local name = module:get_option_string("name");
107 event.origin.send(st.reply(stanza):tag("query", { xmlns = "http://jabber.org/protocol/disco#info" })
108 :tag("identity", { category = "component", type = "generic", name = module:get_option_string("name", "Prosody") }))
113 module:log("warn", "Component not connected, bouncing error for: %s", stanza:top_tag());
114 if stanza.attr.type ~= "error" and stanza.attr.type ~= "result" then
115 event.origin.send(st.error_reply(stanza, "wait", "service-unavailable", "Component unavailable"));
121 module:hook("iq/bare", handle_stanza, -1);
122 module:hook("message/bare", handle_stanza, -1);
123 module:hook("presence/bare", handle_stanza, -1);
124 module:hook("iq/full", handle_stanza, -1);
125 module:hook("message/full", handle_stanza, -1);
126 module:hook("presence/full", handle_stanza, -1);
127 module:hook("iq/host", handle_stanza, -1);
128 module:hook("message/host", handle_stanza, -1);
129 module:hook("presence/host", handle_stanza, -1);
132 --- Network and stream part ---
134 local xmlns_component = 'jabber:component:accept';
138 --- Callbacks/data for xmppstream to handle streams for us ---
140 local stream_callbacks = { default_ns = xmlns_component };
142 local xmlns_xmpp_streams = "urn:ietf:params:xml:ns:xmpp-streams";
144 function stream_callbacks.error(session, error, data, data2)
145 if session.destroyed then return; end
146 module:log("warn", "Error processing component stream: %s", tostring(error));
147 if error == "no-stream" then
148 session:close("invalid-namespace");
149 elseif error == "parse-error" then
150 session.log("warn", "External component %s XML parse error: %s", tostring(session.host), tostring(data));
151 session:close("not-well-formed");
152 elseif error == "stream-error" then
153 local condition, text = "undefined-condition";
154 for child in data:children() do
155 if child.attr.xmlns == xmlns_xmpp_streams then
156 if child.name ~= "text" then
157 condition = child.name;
159 text = child:get_text();
161 if condition ~= "undefined-condition" and text then
166 text = condition .. (text and (" ("..text..")") or "");
167 session.log("info", "Session closed by remote with error: %s", text);
168 session:close(nil, text);
172 function stream_callbacks.streamopened(session, attr)
173 if not hosts[attr.to] or not hosts[attr.to].modules.component then
174 session:close{ condition = "host-unknown", text = tostring(attr.to).." does not match any configured external components" };
177 session.host = attr.to;
178 session.streamid = uuid_gen();
179 session.notopen = nil;
180 -- Return stream header
181 session.send("<?xml version='1.0'?>");
182 session.send(st.stanza("stream:stream", { xmlns=xmlns_component,
183 ["xmlns:stream"]='http://etherx.jabber.org/streams', id=session.streamid, from=session.host }):top_tag());
186 function stream_callbacks.streamclosed(session)
187 session.log("debug", "Received </stream:stream>");
191 local function handleerr(err) log("error", "Traceback[component]: %s", traceback(tostring(err), 2)); end
192 function stream_callbacks.handlestanza(session, stanza)
193 -- Namespaces are icky.
194 if not stanza.attr.xmlns and stanza.name == "handshake" then
195 stanza.attr.xmlns = xmlns_component;
197 if not stanza.attr.xmlns or stanza.attr.xmlns == "jabber:client" then
198 local from = stanza.attr.from;
200 if session.component_validate_from then
201 local _, domain = jid_split(stanza.attr.from);
202 if domain ~= session.host then
204 session.log("warn", "Component sent stanza with missing or invalid 'from' address");
206 condition = "invalid-from";
207 text = "Component tried to send from address <"..tostring(from)
208 .."> which is not in domain <"..tostring(session.host)..">";
214 stanza.attr.from = session.host; -- COMPAT: Strictly we shouldn't allow this
216 if not stanza.attr.to then
217 session.log("warn", "Rejecting stanza with no 'to' address");
218 session.send(st.error_reply(stanza, "modify", "bad-request", "Components MUST specify a 'to' address on stanzas"));
224 return xpcall(function () return core_process_stanza(session, stanza) end, handleerr);
228 --- Closing a component connection
229 local stream_xmlns_attr = {xmlns='urn:ietf:params:xml:ns:xmpp-streams'};
230 local default_stream_attr = { ["xmlns:stream"] = "http://etherx.jabber.org/streams", xmlns = stream_callbacks.default_ns, version = "1.0", id = "" };
231 local function session_close(session, reason)
232 if session.destroyed then return; end
234 if session.notopen then
235 session.send("<?xml version='1.0'?>");
236 session.send(st.stanza("stream:stream", default_stream_attr):top_tag());
239 if type(reason) == "string" then -- assume stream error
240 module:log("info", "Disconnecting component, <stream:error> is: %s", reason);
241 session.send(st.stanza("stream:error"):tag(reason, {xmlns = 'urn:ietf:params:xml:ns:xmpp-streams' }));
242 elseif type(reason) == "table" then
243 if reason.condition then
244 local stanza = st.stanza("stream:error"):tag(reason.condition, stream_xmlns_attr):up();
246 stanza:tag("text", stream_xmlns_attr):text(reason.text):up();
249 stanza:add_child(reason.extra);
251 module:log("info", "Disconnecting component, <stream:error> is: %s", tostring(stanza));
252 session.send(stanza);
253 elseif reason.name then -- a stanza
254 module:log("info", "Disconnecting component, <stream:error> is: %s", tostring(reason));
255 session.send(reason);
259 session.send("</stream:stream>");
260 session.conn:close();
261 listener.ondisconnect(session.conn, "stream error");
265 --- Component connlistener
267 function listener.onconnect(conn)
268 local _send = conn.write;
269 local session = { type = "component_unauthed", conn = conn, send = function (data) return _send(conn, tostring(data)); end };
271 -- Logging functions --
272 local conn_name = "jcp"..tostring(session):match("[a-f0-9]+$");
273 session.log = logger.init(conn_name);
274 session.close = session_close;
276 if opt_keepalives then
277 conn:setoption("keepalive", opt_keepalives);
280 session.log("info", "Incoming Jabber component connection");
282 local stream = new_xmpp_stream(session, stream_callbacks);
283 session.stream = stream;
285 session.notopen = true;
287 function session.reset_stream()
288 session.notopen = true;
289 session.stream:reset();
292 function session.data(conn, data)
293 local ok, err = stream:feed(data);
294 if ok then return; end
295 module:log("debug", "Received invalid XML (%s) %d bytes: %s", tostring(err), #data, data:sub(1, 300):gsub("[\r\n]+", " "):gsub("[%z\1-\31]", "_"));
296 session:close("not-well-formed");
299 session.dispatch_stanza = stream_callbacks.handlestanza;
301 sessions[conn] = session;
303 function listener.onincoming(conn, data)
304 local session = sessions[conn];
305 session.data(conn, data);
307 function listener.ondisconnect(conn, err)
308 local session = sessions[conn];
310 (session.log or log)("info", "component disconnected: %s (%s)", tostring(session.host), tostring(err));
311 if session.on_destroy then session:on_destroy(err); end
312 sessions[conn] = nil;
313 for k in pairs(session) do
314 if k ~= "log" and k ~= "close" then
318 session.destroyed = true;
323 function listener.ondetach(conn)
324 sessions[conn] = nil;
327 module:provides("net", {
333 pattern = "^<.*:stream.*%sxmlns%s*=%s*(['\"])jabber:component:accept%1.*>";