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