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