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