5b59ca70eb659eee717c997c4ed542bf39e63b25
[prosody.git] / plugins / mod_component.lua
1 -- Prosody IM v0.4
2 -- Copyright (C) 2008-2009 Matthew Wild
3 -- Copyright (C) 2008-2009 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 if module:get_host_type() ~= "component" then
10         error("Don't load mod_component manually, it should be for a component, please see http://prosody.im/doc/components", 0);
11 end
12
13 local t_concat = table.concat;
14
15 local connlisteners = require "net.connlisteners";
16 local cm_register_component = require "core.componentmanager".register_component;
17 local uuid_gen = require "util.uuid".generate;
18 local sha1 = require "util.hashes".sha1;
19 local st = stanza;
20 local init_xmlhandlers = require "core.xmlhandlers";
21
22 local sessions = {};
23
24 local log = module._log;
25
26 local component_listener = { default_port = 5347; default_mode = "*a"; default_interface = config.get("*", "core", "component_interface") or "127.0.0.1" };
27
28 local xmlns_component = 'jabber:component:accept';
29
30 --- Callbacks/data for xmlhandlers to handle streams for us ---
31
32 local stream_callbacks = { stream_tag = "http://etherx.jabber.org/streams|stream", default_ns = xmlns_component };
33
34 function stream_callbacks.error(session, error, data, data2)
35         log("warn", "Error processing component stream: "..tostring(error));
36         if error == "no-stream" then
37                 session:close("invalid-namespace");
38         elseif error == "xml-parse-error" and data == "unexpected-element-close" then
39                 session.log("debug", "Unexpected close of '%s' tag", data2);
40                 session:close("xml-not-well-formed");
41         else
42                 session.log("debug", "External component %s XML parse error: %s", tostring(session.host), tostring(error));
43                 print(data, debug.traceback())
44                 session:close("xml-not-well-formed");
45         end
46 end
47
48 function stream_callbacks.streamopened(session, attr)
49         if config.get(attr.to, "core", "component_module") ~= "component" then
50                 -- Trying to act as a component domain which 
51                 -- hasn't been configured
52                 session:close{ condition = "host-unknown", text = tostring(attr.to).." does not match any configured external components" };
53                 return;
54         end
55         
56         -- Store the original host (this is used for config, etc.)
57         session.user = attr.to;
58         -- Set the host for future reference
59         session.host = config.get(attr.to, "core", "component_address") or attr.to;
60         -- Note that we don't create the internal component 
61         -- until after the external component auths successfully
62
63         session.streamid = uuid_gen();
64         session.notopen = nil;
65         
66         session.send(st.stanza("stream:stream", { xmlns=xmlns_component,
67                         ["xmlns:stream"]='http://etherx.jabber.org/streams', id=session.streamid, from=session.host }):top_tag());
68
69 end
70
71 function stream_callbacks.streamclosed(session)
72 end
73
74 local core_process_stanza = core_process_stanza;
75
76 function stream_callbacks.handlestanza(session, stanza)
77         -- Namespaces are icky.
78         log("warn", "Handing stanza with name %s", stanza.name);
79         if stanza.name ~= "handshake" then
80                 return core_process_stanza(session, stanza);
81         else
82                 handle_component_auth(session, stanza);
83         end
84 end
85
86 --- Handle authentication attempts by components
87 function handle_component_auth(session, stanza)
88         if (not session.host) or #stanza.tags > 0 then
89                 session:close("not-authorized");
90                 return;
91         end
92         
93         local secret = config.get(session.user, "core", "component_secret");
94         if not secret then
95                 log("warn", "Component attempted to identify as %s, but component_password is not set", session.user);
96                 session:close("not-authorized");
97                 return;
98         end
99         
100         local supplied_token = t_concat(stanza);
101         local calculated_token = sha1(session.streamid..secret, true);
102         if supplied_token:lower() ~= calculated_token:lower() then
103                 session:close{ condition = "not-authorized", text = "Given token does not match calculated token" };
104                 return;
105         end
106         
107         
108         -- Authenticated now
109         
110         -- If component not already created for this host, create one now
111         if not hosts[session.host].connected then
112                 local send = session.send;
113                 session.component_session = cm_register_component(session.host, function (_, data) return send(data); end);
114                 hosts[session.host].connected = true;
115         else
116                 log("error", "Multiple components bound to the same address, first one wins (TODO: Implement stanza distribution)");
117         end
118         
119         -- Signal successful authentication
120         session.send(st.stanza("handshake"));
121 end
122
123 module:add_handler("component", "handshake", xmlns_component, handle_component_auth);
124
125 --- Closing a component connection
126 local stream_xmlns_attr = {xmlns='urn:ietf:params:xml:ns:xmpp-streams'};
127 local function session_close(session, reason)
128         local log = session.log or log;
129         if session.conn then
130                 if reason then
131                         if type(reason) == "string" then -- assume stream error
132                                 log("info", "Disconnecting component, <stream:error> is: %s", reason);
133                                 session.send(st.stanza("stream:error"):tag(reason, {xmlns = 'urn:ietf:params:xml:ns:xmpp-streams' }));
134                         elseif type(reason) == "table" then
135                                 if reason.condition then
136                                         local stanza = st.stanza("stream:error"):tag(reason.condition, stream_xmlns_attr):up();
137                                         if reason.text then
138                                                 stanza:tag("text", stream_xmlns_attr):text(reason.text):up();
139                                         end
140                                         if reason.extra then
141                                                 stanza:add_child(reason.extra);
142                                         end
143                                         log("info", "Disconnecting component, <stream:error> is: %s", tostring(stanza));
144                                         session.send(stanza);
145                                 elseif reason.name then -- a stanza
146                                         log("info", "Disconnecting component, <stream:error> is: %s", tostring(reason));
147                                         session.send(reason);
148                                 end
149                         end
150                 end
151                 session.send("</stream:stream>");
152                 session.conn.close();
153                 component_listener.disconnect(session.conn, "stream error");
154         end
155 end
156
157 --- Component connlistener
158 function component_listener.listener(conn, data)
159         local session = sessions[conn];
160         if not session then
161                 local _send = conn.write;
162                 session = { type = "component", conn = conn, send = function (data) return _send(tostring(data)); end };
163                 sessions[conn] = session;
164
165                 -- Logging functions --
166                 
167                 local conn_name = "xep114-"..tostring(conn):match("[a-f0-9]+$");
168                 session.log = logger.init(conn_name);
169                 session.close = session_close;
170                 
171                 session.log("info", "Incoming XEP-0114 connection");
172                 
173                 local parser = lxp.new(init_xmlhandlers(session, stream_callbacks), "|");
174                 session.parser = parser;
175                 
176                 session.notopen = true;
177                 
178                 function session.data(conn, data)
179                         local ok, err = parser:parse(data);
180                         if ok then return; end
181                         session:close("xml-not-well-formed");
182                 end
183                 
184                 session.dispatch_stanza = stream_callbacks.handlestanza;
185                 
186         end
187         if data then
188                 session.data(conn, data);
189         end
190 end
191         
192 function component_listener.disconnect(conn, err)
193         local session = sessions[conn];
194         if session then
195                 (session.log or log)("info", "component disconnected: %s (%s)", tostring(session.host), tostring(err));
196                 if session.host then
197                         if session.component then
198                                 deregister_component(session.host);
199                         end
200                 end
201                 sessions[conn]  = nil;
202                 session = nil;
203                 collectgarbage("collect");
204         end
205 end
206
207 connlisteners.register('component', component_listener);
208
209 module:add_event_hook("server-started", 
210         function ()
211                 if net_activate_ports then
212                         net_activate_ports("component_ports", "component", {5437}, "tcp");
213                 else
214                         error("No net_activate_ports: Using an incompatible version of Prosody?");
215                 end
216         end);