Merge 0.7->trunk
[prosody.git] / plugins / mod_proxy65.lua
1 -- Copyright (C) 2009 Thilo Cestonaro
2 -- 
3 -- This project is MIT/X11 licensed. Please see the
4 -- COPYING file in the source package for more information.
5 --
6 --[[
7 * to restart the proxy in the console: e.g.
8 module:unload("proxy65");
9 > server.removeserver(<proxy65_port>);
10 module:load("proxy65", <proxy65_jid>);
11 ]]--
12
13 if module:get_host_type() ~= "component" then
14         error("proxy65 should be loaded as a component, please see http://prosody.im/doc/components", 0);
15 end
16
17 local jid_split, jid_join = require "util.jid".split, require "util.jid".join;
18 local st = require "util.stanza";
19 local componentmanager = require "core.componentmanager";
20 local config_get = require "core.configmanager".get;
21 local connlisteners = require "net.connlisteners";
22 local sha1 = require "util.hashes".sha1;
23 local server = require "net.server";
24
25 local host, name = module:get_host(), "SOCKS5 Bytestreams Service";
26 local sessions, transfers, component, replies_cache = {}, {}, nil, {};
27
28 local proxy_port = config_get(host, "core", "proxy65_port") or 5000;
29 local proxy_interface = config_get(host, "core", "proxy65_interface") or "*";
30 local proxy_address = config_get(host, "core", "proxy65_address") or (proxy_interface ~= "*" and proxy_interface) or host;
31 local proxy_acl = config_get(host, "core", "proxy65_acl");
32 local max_buffer_size = 4096;
33
34 local connlistener = { default_port = proxy_port, default_interface = proxy_interface, default_mode = "*a" };
35
36 function connlistener.onincoming(conn, data)
37         local session = sessions[conn] or {};
38         
39         if session.setup == nil and data ~= nil and data:sub(1):byte() == 0x05 and data:len() > 2 then
40                 local nmethods = data:sub(2):byte();
41                 local methods = data:sub(3);
42                 local supported = false;
43                 for i=1, nmethods, 1 do
44                         if(methods:sub(i):byte() == 0x00) then -- 0x00 == method: NO AUTH
45                                 supported = true;
46                                 break;
47                         end
48                 end
49                 if(supported) then
50                         module:log("debug", "new session found ... ")
51                         session.setup = true;
52                         sessions[conn] = session;
53                         conn:write(string.char(5, 0));
54                 end
55                 return;
56         end
57         if session.setup then
58                 if session.sha ~= nil and transfers[session.sha] ~= nil then
59                         local sha = session.sha;
60                         if transfers[sha].activated == true and transfers[sha].target ~= nil then
61                                 if  transfers[sha].initiator == conn then
62                                         transfers[sha].target:write(data);
63                                 else
64                                         transfers[sha].initiator:write(data);
65                                 end
66                                 return;
67                         end
68                 end
69                 if data ~= nil and data:len() == 0x2F and  -- 40 == length of SHA1 HASH, and 7 other bytes => 47 => 0x2F
70                         data:sub(1):byte() == 0x05 and -- SOCKS5 has 5 in first byte
71                         data:sub(2):byte() == 0x01 and -- CMD must be 1
72                         data:sub(3):byte() == 0x00 and -- RSV must be 0
73                         data:sub(4):byte() == 0x03 and -- ATYP must be 3
74                         data:sub(5):byte() == 40 and -- SHA1 HASH length must be 40 (0x28)
75                         data:sub(-2):byte() == 0x00 and -- PORT must be 0, size 2 byte
76                         data:sub(-1):byte() == 0x00
77                 then
78                         local sha = data:sub(6, 45); -- second param is not count! it's the ending index (included!)
79                         if transfers[sha] == nil then
80                                 transfers[sha] = {};
81                                 transfers[sha].activated = false;
82                                 transfers[sha].target = conn;
83                                 session.sha = sha;
84                                 module:log("debug", "target connected ... ");
85                         elseif transfers[sha].target ~= nil then
86                                 transfers[sha].initiator = conn;
87                                 session.sha = sha;
88                                 module:log("debug", "initiator connected ... ");
89                                 server.link(conn, transfers[sha].target, max_buffer_size);
90                                 server.link(transfers[sha].target, conn, max_buffer_size);
91                         end
92                         conn:write(string.char(5, 0, 0, 3, sha:len()) .. sha .. string.char(0, 0)); -- VER, REP, RSV, ATYP, BND.ADDR (sha), BND.PORT (2 Byte)
93                         conn:lock_read(true)
94                 else
95                         module:log("warn", "Neither data transfer nor initial connect of a participator of a transfer.")
96                         conn:close();
97                 end
98         else
99                 if data ~= nil then
100                         module:log("warn", "unknown connection with no authentication data -> closing it");
101                         conn:close();
102                 end
103         end
104 end
105
106 function connlistener.ondisconnect(conn, err)
107         local session = sessions[conn];
108         if session then
109                 if session.sha and transfers[session.sha] then
110                         local initiator, target = transfers[session.sha].initiator, transfers[session.sha].target;
111                         if initiator == conn and target ~= nil then
112                                 target:close();
113                         elseif target == conn and initiator ~= nil then
114                                 initiator:close();
115                         end
116                         transfers[session.sha] = nil;
117                 end
118                 -- Clean up any session-related stuff here
119                 sessions[conn] = nil;
120         end
121 end
122
123 local function get_disco_info(stanza)
124         local reply = replies_cache.disco_info;
125         if reply == nil then
126                 reply = st.iq({type='result', from=host}):query("http://jabber.org/protocol/disco#info")
127                         :tag("identity", {category='proxy', type='bytestreams', name=name}):up()
128                         :tag("feature", {var="http://jabber.org/protocol/bytestreams"});
129                 replies_cache.disco_info = reply;
130         end
131
132         reply.attr.id = stanza.attr.id;
133         reply.attr.to = stanza.attr.from;
134         return reply;
135 end
136
137 local function get_disco_items(stanza)
138         local reply = replies_cache.disco_items;
139         if reply == nil then
140                 reply = st.iq({type='result', from=host}):query("http://jabber.org/protocol/disco#items");
141                 replies_cache.disco_items = reply;
142         end
143         
144         reply.attr.id = stanza.attr.id;
145         reply.attr.to = stanza.attr.from;
146         return reply;
147 end
148
149 local function get_stream_host(origin, stanza)
150         local reply = replies_cache.stream_host;
151         local err_reply = replies_cache.stream_host_err;
152         local sid = stanza.tags[1].attr.sid;
153         local allow = false;
154         local jid_node, jid_host, jid_resource = jid_split(stanza.attr.from);
155         
156         if stanza.attr.from == nil then
157                 jid_node = origin.username;
158                 jid_host = origin.host;
159                 jid_resource = origin.resource;
160         end
161         
162         if proxy_acl and #proxy_acl > 0 then
163                 if host ~= nil then -- at least a domain is needed.
164                         for _, acl in ipairs(proxy_acl) do
165                                 local acl_node, acl_host, acl_resource = jid_split(acl);
166                                 if ((acl_node ~= nil and acl_node == jid_node) or acl_node == nil) and
167                                    ((acl_host ~= nil and acl_host == jid_host) or acl_host == nil) and
168                                    ((acl_resource ~= nil and acl_resource == jid_resource) or acl_resource == nil) then
169                                         allow = true;
170                                 end
171                         end
172                 end
173         else
174                 allow = true;
175         end
176         if allow == true then
177                 if reply == nil then
178                         reply = st.iq({type="result", from=host})
179                                 :query("http://jabber.org/protocol/bytestreams")
180                                 :tag("streamhost", {jid=host, host=proxy_address, port=proxy_port});
181                         replies_cache.stream_host = reply;
182                 end
183         else
184                 module:log("warn", "Denying use of proxy for %s", tostring(jid_join(jid_node, jid_host, jid_resource)));
185                 if err_reply == nil then
186                         err_reply = st.iq({type="error", from=host})
187                                 :query("http://jabber.org/protocol/bytestreams")
188                                 :tag("error", {code='403', type='auth'})
189                                 :tag("forbidden", {xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'});
190                         replies_cache.stream_host_err = err_reply;
191                 end
192                 reply = err_reply;
193         end
194         reply.attr.id = stanza.attr.id;
195         reply.attr.to = stanza.attr.from;
196         reply.tags[1].attr.sid = sid;
197         return reply;
198 end
199
200 module.unload = function()
201         componentmanager.deregister_component(host);
202         connlisteners.deregister(module.host .. ':proxy65');
203 end
204
205 local function set_activation(stanza)
206         local from, to, sid, reply = nil;
207         from = stanza.attr.from;
208         if stanza.tags[1] ~= nil and tostring(stanza.tags[1].name) == "query" then
209                 if stanza.tags[1].attr ~= nil then
210                         sid = stanza.tags[1].attr.sid;
211                 end
212                 if stanza.tags[1].tags[1] ~= nil and tostring(stanza.tags[1].tags[1].name) == "activate" then
213                         to = stanza.tags[1].tags[1][1];
214                 end
215         end
216         if from ~= nil and to ~= nil and sid ~= nil then
217                 reply = st.iq({type="result", from=host, to=from});
218                 reply.attr.id = stanza.attr.id;
219         end
220         return reply, from, to, sid;
221 end
222
223 function handle_to_domain(origin, stanza)
224         local to_node, to_host, to_resource = jid_split(stanza.attr.to);
225         if to_node == nil then
226                 local type = stanza.attr.type;
227                 if type == "error" or type == "result" then return; end
228                 if stanza.name == "iq" and type == "get" then
229                         local xmlns = stanza.tags[1].attr.xmlns
230                         if xmlns == "http://jabber.org/protocol/disco#info" then
231                                 origin.send(get_disco_info(stanza));
232                                 return true;
233                         elseif xmlns == "http://jabber.org/protocol/disco#items" then
234                                 origin.send(get_disco_items(stanza));
235                                 return true;
236                         elseif xmlns == "http://jabber.org/protocol/bytestreams" then
237                                 origin.send(get_stream_host(origin, stanza));
238                                 return true;
239                         else
240                                 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
241                                 return true;
242                         end
243                 elseif stanza.name == "iq" and type == "set" then
244                         module:log("debug", "Received activation request from %s", stanza.attr.from);
245                         local reply, from, to, sid = set_activation(stanza);
246                         if reply ~= nil and from ~= nil and to ~= nil and sid ~= nil then
247                                 local sha = sha1(sid .. from .. to, true);
248                                 if transfers[sha] == nil then
249                                         module:log("error", "transfers[sha]: nil");
250                                 elseif(transfers[sha] ~= nil and transfers[sha].initiator ~= nil and transfers[sha].target ~= nil) then
251                                         origin.send(reply);
252                                         transfers[sha].activated = true;
253                                         transfers[sha].target:lock_read(false);
254                                         transfers[sha].initiator:lock_read(false);
255                                 else
256                                         module:log("debug", "Both parties were not yet connected");
257                                         local message = "Neither party is connected to the proxy";
258                                         if transfers[sha].initiator then
259                                                 message = "The recipient is not connected to the proxy";
260                                         elseif transfers[sha].target then
261                                                 message = "The sender (you) is not connected to the proxy";
262                                         end
263                                         origin.send(st.error_reply(stanza, "cancel", "not-allowed", message));
264                                 end
265                         else
266                                 module:log("error", "activation failed: sid: %s, initiator: %s, target: %s", tostring(sid), tostring(from), tostring(to));
267                         end
268                 end
269         end
270         return;
271 end
272
273 if not connlisteners.register(module.host .. ':proxy65', connlistener) then
274         module:log("error", "mod_proxy65: Could not establish a connection listener. Check your configuration please.");
275         module:log("error", "Possibly two proxy65 components are configured to share the same port.");
276 end
277
278 connlisteners.start(module.host .. ':proxy65');
279 component = componentmanager.register_component(host, handle_to_domain);