d71c3d99cb610394a2d418e6fd4eb2a44095cb31
[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 connlisteners = require "net.connlisteners";
20 local sha1 = require "util.hashes".sha1;
21 local server = require "net.server";
22
23 local host, name = module:get_host(), "SOCKS5 Bytestreams Service";
24 local sessions, transfers, component, replies_cache = {}, {}, nil, {};
25
26 local proxy_port = module:get_option("proxy65_port") or 5000;
27 local proxy_interface = module:get_option("proxy65_interface") or "*";
28 local proxy_address = module:get_option("proxy65_address") or (proxy_interface ~= "*" and proxy_interface) or host;
29 local proxy_acl = module:get_option("proxy65_acl");
30 local max_buffer_size = 4096;
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                                 server.link(conn, transfers[sha].target, max_buffer_size);
88                                 server.link(transfers[sha].target, conn, max_buffer_size);
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 module:hook("iq-get/host/http://jabber.org/protocol/disco#info:query", function(event)
122         local origin, stanza = event.origin, event.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         origin.send(reply);
134         return true;
135 end, -1);
136
137 module:hook("iq-get/host/http://jabber.org/protocol/disco#items:query", function(event)
138         local origin, stanza = event.origin, event.stanza;
139         local reply = replies_cache.disco_items;
140         if reply == nil then
141                 reply = st.iq({type='result', from=host}):query("http://jabber.org/protocol/disco#items");
142                 replies_cache.disco_items = reply;
143         end
144         
145         reply.attr.id = stanza.attr.id;
146         reply.attr.to = stanza.attr.from;
147         origin.send(reply);
148         return true;
149 end, -1);
150
151 module:hook("iq-get/host/http://jabber.org/protocol/bytestreams:query", function(event)
152         local origin, stanza = event.origin, event.stanza;
153         local reply = replies_cache.stream_host;
154         local err_reply = replies_cache.stream_host_err;
155         local sid = stanza.tags[1].attr.sid;
156         local allow = false;
157         local jid = stanza.attr.from;
158         
159         if proxy_acl and #proxy_acl > 0 then
160                 for _, acl in ipairs(proxy_acl) do
161                         if jid_compare(jid, acl) then allow = true; end
162                 end
163         else
164                 allow = true;
165         end
166         if allow == true then
167                 if reply == nil then
168                         reply = st.iq({type="result", from=host})
169                                 :query("http://jabber.org/protocol/bytestreams")
170                                 :tag("streamhost", {jid=host, host=proxy_address, port=proxy_port});
171                         replies_cache.stream_host = reply;
172                 end
173         else
174                 module:log("warn", "Denying use of proxy for %s", tostring(jid));
175                 if err_reply == nil then
176                         err_reply = st.iq({type="error", from=host})
177                                 :query("http://jabber.org/protocol/bytestreams")
178                                 :tag("error", {code='403', type='auth'})
179                                 :tag("forbidden", {xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'});
180                         replies_cache.stream_host_err = err_reply;
181                 end
182                 reply = err_reply;
183         end
184         reply.attr.id = stanza.attr.id;
185         reply.attr.to = stanza.attr.from;
186         reply.tags[1].attr.sid = sid;
187         origin.send(reply);
188         return true;
189 end);
190
191 module.unload = function()
192         connlisteners.deregister(module.host .. ':proxy65');
193 end
194
195 local function set_activation(stanza)
196         local from, to, sid, reply = nil;
197         from = stanza.attr.from;
198         if stanza.tags[1] ~= nil and tostring(stanza.tags[1].name) == "query" then
199                 if stanza.tags[1].attr ~= nil then
200                         sid = stanza.tags[1].attr.sid;
201                 end
202                 if stanza.tags[1].tags[1] ~= nil and tostring(stanza.tags[1].tags[1].name) == "activate" then
203                         to = stanza.tags[1].tags[1][1];
204                 end
205         end
206         if from ~= nil and to ~= nil and sid ~= nil then
207                 reply = st.iq({type="result", from=host, to=from});
208                 reply.attr.id = stanza.attr.id;
209         end
210         return reply, from, to, sid;
211 end
212
213 module:hook("iq-set/host/http://jabber.org/protocol/bytestreams:query", function(event)
214         local origin, stanza = event.origin, event.stanza;
215
216         module:log("debug", "Received activation request from %s", stanza.attr.from);
217         local reply, from, to, sid = set_activation(stanza);
218         if reply ~= nil and from ~= nil and to ~= nil and sid ~= nil then
219                 local sha = sha1(sid .. from .. to, true);
220                 if transfers[sha] == nil then
221                         module:log("error", "transfers[sha]: nil");
222                 elseif(transfers[sha] ~= nil and transfers[sha].initiator ~= nil and transfers[sha].target ~= nil) then
223                         origin.send(reply);
224                         transfers[sha].activated = true;
225                         transfers[sha].target:lock_read(false);
226                         transfers[sha].initiator:lock_read(false);
227                 else
228                         module:log("debug", "Both parties were not yet connected");
229                         local message = "Neither party is connected to the proxy";
230                         if transfers[sha].initiator then
231                                 message = "The recipient is not connected to the proxy";
232                         elseif transfers[sha].target then
233                                 message = "The sender (you) is not connected to the proxy";
234                         end
235                         origin.send(st.error_reply(stanza, "cancel", "not-allowed", message));
236                 end
237                 return true;
238         else
239                 module:log("error", "activation failed: sid: %s, initiator: %s, target: %s", tostring(sid), tostring(from), tostring(to));
240         end
241 end);
242
243 if not connlisteners.register(module.host .. ':proxy65', connlistener) then
244         module:log("error", "mod_proxy65: Could not establish a connection listener. Check your configuration please.");
245         module:log("error", "Possibly two proxy65 components are configured to share the same port.");
246 end
247
248 connlisteners.start(module.host .. ':proxy65');