aboutsummaryrefslogtreecommitdiff
path: root/samples/forward.lua
diff options
context:
space:
mode:
authorThijs Schreijer <thijs@thijsschreijer.nl>2022-08-24 12:31:18 +0200
committerGitHub <noreply@github.com>2022-08-24 12:31:18 +0200
commit87c48f3e4ddba13d9c014067e62568ba906cc410 (patch)
treec99889ec0b9bbab2bc5ee14cd9046d0a122eb226 /samples/forward.lua
parent95b7efa9da506ef968c1347edf3fc56370f0deed (diff)
parent97d5194f302d3fb9fe27874d9b5f73004a208d01 (diff)
downloadluasocket-87c48f3e4ddba13d9c014067e62568ba906cc410.tar.gz
luasocket-87c48f3e4ddba13d9c014067e62568ba906cc410.tar.bz2
luasocket-87c48f3e4ddba13d9c014067e62568ba906cc410.zip
Merge pull request #364 from lunarmodules/cleanup
Diffstat (limited to 'samples/forward.lua')
-rw-r--r--samples/forward.lua65
1 files changed, 65 insertions, 0 deletions
diff --git a/samples/forward.lua b/samples/forward.lua
new file mode 100644
index 0000000..05ced1a
--- /dev/null
+++ b/samples/forward.lua
@@ -0,0 +1,65 @@
1-- load our favourite library
2local dispatch = require("dispatch")
3local handler = dispatch.newhandler()
4
5-- make sure the user knows how to invoke us
6if #arg < 1 then
7 print("Usage")
8 print(" lua forward.lua <iport:ohost:oport> ...")
9 os.exit(1)
10end
11
12-- function to move data from one socket to the other
13local function move(foo, bar)
14 local live
15 while 1 do
16 local data, error, partial = foo:receive(2048)
17 live = data or error == "timeout"
18 data = data or partial
19 local result, error = bar:send(data)
20 if not live or not result then
21 foo:close()
22 bar:close()
23 break
24 end
25 end
26end
27
28-- for each tunnel, start a new server
29for i, v in ipairs(arg) do
30 -- capture forwarding parameters
31 local _, _, iport, ohost, oport = string.find(v, "([^:]+):([^:]+):([^:]+)")
32 assert(iport, "invalid arguments")
33 -- create our server socket
34 local server = assert(handler.tcp())
35 assert(server:setoption("reuseaddr", true))
36 assert(server:bind("*", iport))
37 assert(server:listen(32))
38 -- handler for the server object loops accepting new connections
39 handler:start(function()
40 while 1 do
41 local client = assert(server:accept())
42 assert(client:settimeout(0))
43 -- for each new connection, start a new client handler
44 handler:start(function()
45 -- handler tries to connect to peer
46 local peer = assert(handler.tcp())
47 assert(peer:settimeout(0))
48 assert(peer:connect(ohost, oport))
49 -- if sucessful, starts a new handler to send data from
50 -- client to peer
51 handler:start(function()
52 move(client, peer)
53 end)
54 -- afte starting new handler, enter in loop sending data from
55 -- peer to client
56 move(peer, client)
57 end)
58 end
59 end)
60end
61
62-- simply loop stepping the server
63while 1 do
64 handler:step()
65end