Blame etc/forward.lua

Packit b53373
-- load our favourite library
Packit b53373
local dispatch = require("dispatch")
Packit b53373
local handler = dispatch.newhandler()
Packit b53373
Packit b53373
-- make sure the user knows how to invoke us
Packit b53373
if #arg < 1 then
Packit b53373
    print("Usage")
Packit b53373
    print("    lua forward.lua <iport:ohost:oport> ...")
Packit b53373
    os.exit(1)
Packit b53373
end
Packit b53373
Packit b53373
-- function to move data from one socket to the other
Packit b53373
local function move(foo, bar)
Packit b53373
    local live
Packit b53373
    while 1 do
Packit b53373
        local data, error, partial = foo:receive(2048)
Packit b53373
        live = data or error == "timeout"
Packit b53373
        data = data or partial
Packit b53373
        local result, error = bar:send(data)
Packit b53373
        if not live or not result then
Packit b53373
            foo:close()
Packit b53373
            bar:close()
Packit b53373
            break
Packit b53373
        end
Packit b53373
    end
Packit b53373
end
Packit b53373
Packit b53373
-- for each tunnel, start a new server
Packit b53373
for i, v in ipairs(arg) do
Packit b53373
    -- capture forwarding parameters
Packit b53373
    local _, _, iport, ohost, oport = string.find(v, "([^:]+):([^:]+):([^:]+)")
Packit b53373
    assert(iport, "invalid arguments")
Packit b53373
    -- create our server socket
Packit b53373
    local server = assert(handler.tcp())
Packit b53373
    assert(server:setoption("reuseaddr", true))
Packit b53373
    assert(server:bind("*", iport))
Packit b53373
    assert(server:listen(32))
Packit b53373
    -- handler for the server object loops accepting new connections
Packit b53373
    handler:start(function()
Packit b53373
        while 1 do
Packit b53373
            local client = assert(server:accept())
Packit b53373
            assert(client:settimeout(0))
Packit b53373
            -- for each new connection, start a new client handler
Packit b53373
            handler:start(function()
Packit b53373
                -- handler tries to connect to peer
Packit b53373
                local peer = assert(handler.tcp())
Packit b53373
                assert(peer:settimeout(0))
Packit b53373
                assert(peer:connect(ohost, oport))
Packit b53373
                -- if sucessful, starts a new handler to send data from
Packit b53373
                -- client to peer
Packit b53373
                handler:start(function()
Packit b53373
                    move(client, peer)
Packit b53373
                end)
Packit b53373
                -- afte starting new handler, enter in loop sending data from
Packit b53373
                -- peer to client
Packit b53373
                move(peer, client)
Packit b53373
            end)
Packit b53373
        end
Packit b53373
    end)
Packit b53373
end
Packit b53373
Packit b53373
-- simply loop stepping the server
Packit b53373
while 1 do
Packit b53373
    handler:step()
Packit b53373
end