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