diff --git a/game/engine/init.lua b/game/engine/init.lua
index 9892664012275b78eb11c412489747ff75036573..4b1ace363cafa03ed541ec9aeac42c6c076d5c55 100644
--- a/game/engine/init.lua
+++ b/game/engine/init.lua
@@ -1,3 +1,8 @@
+--[[ Allows for remote debugging, but it makes things *SLOW*
+require"remdebug.engine"
+remdebug.engine.start()
+]]
+
 -- load some utility functions
 dofile("/engine/utils.lua")
 
diff --git a/game/thirdparty/ltn12.lua b/game/thirdparty/ltn12.lua
new file mode 100644
index 0000000000000000000000000000000000000000..b42689a34ab01703732510b295d6209e527f4446
--- /dev/null
+++ b/game/thirdparty/ltn12.lua
@@ -0,0 +1,292 @@
+-----------------------------------------------------------------------------
+-- LTN12 - Filters, sources, sinks and pumps.
+-- LuaSocket toolkit.
+-- Author: Diego Nehab
+-- RCS ID: $Id: ltn12.lua,v 1.31 2006/04/03 04:45:42 diego Exp $
+-----------------------------------------------------------------------------
+
+-----------------------------------------------------------------------------
+-- Declare module
+-----------------------------------------------------------------------------
+local string = require("string")
+local table = require("table")
+local base = _G
+module("ltn12")
+
+filter = {}
+source = {}
+sink = {}
+pump = {}
+
+-- 2048 seems to be better in windows...
+BLOCKSIZE = 2048
+_VERSION = "LTN12 1.0.1"
+
+-----------------------------------------------------------------------------
+-- Filter stuff
+-----------------------------------------------------------------------------
+-- returns a high level filter that cycles a low-level filter
+function filter.cycle(low, ctx, extra)
+    base.assert(low)
+    return function(chunk)
+        local ret
+        ret, ctx = low(ctx, chunk, extra)
+        return ret
+    end
+end
+
+-- chains a bunch of filters together
+-- (thanks to Wim Couwenberg)
+function filter.chain(...)
+    local n = table.getn(arg)
+    local top, index = 1, 1
+    local retry = ""
+    return function(chunk)
+        retry = chunk and retry
+        while true do
+            if index == top then
+                chunk = arg[index](chunk)
+                if chunk == "" or top == n then return chunk
+                elseif chunk then index = index + 1
+                else
+                    top = top+1
+                    index = top
+                end
+            else
+                chunk = arg[index](chunk or "")
+                if chunk == "" then
+                    index = index - 1
+                    chunk = retry
+                elseif chunk then
+                    if index == n then return chunk
+                    else index = index + 1 end
+                else base.error("filter returned inappropriate nil") end
+            end
+        end
+    end
+end
+
+-----------------------------------------------------------------------------
+-- Source stuff
+-----------------------------------------------------------------------------
+-- create an empty source
+local function empty()
+    return nil
+end
+
+function source.empty()
+    return empty
+end
+
+-- returns a source that just outputs an error
+function source.error(err)
+    return function()
+        return nil, err
+    end
+end
+
+-- creates a file source
+function source.file(handle, io_err)
+    if handle then
+        return function()
+            local chunk = handle:read(BLOCKSIZE)
+            if not chunk then handle:close() end
+            return chunk
+        end
+    else return source.error(io_err or "unable to open file") end
+end
+
+-- turns a fancy source into a simple source
+function source.simplify(src)
+    base.assert(src)
+    return function()
+        local chunk, err_or_new = src()
+        src = err_or_new or src
+        if not chunk then return nil, err_or_new
+        else return chunk end
+    end
+end
+
+-- creates string source
+function source.string(s)
+    if s then
+        local i = 1
+        return function()
+            local chunk = string.sub(s, i, i+BLOCKSIZE-1)
+            i = i + BLOCKSIZE
+            if chunk ~= "" then return chunk
+            else return nil end
+        end
+    else return source.empty() end
+end
+
+-- creates rewindable source
+function source.rewind(src)
+    base.assert(src)
+    local t = {}
+    return function(chunk)
+        if not chunk then
+            chunk = table.remove(t)
+            if not chunk then return src()
+            else return chunk end
+        else
+            table.insert(t, chunk)
+        end
+    end
+end
+
+function source.chain(src, f)
+    base.assert(src and f)
+    local last_in, last_out = "", ""
+    local state = "feeding"
+    local err
+    return function()
+        if not last_out then
+            base.error('source is empty!', 2)
+        end
+        while true do
+            if state == "feeding" then
+                last_in, err = src()
+                if err then return nil, err end
+                last_out = f(last_in)
+                if not last_out then
+                    if last_in then
+                        base.error('filter returned inappropriate nil')
+                    else
+                        return nil
+                    end
+                elseif last_out ~= "" then
+                    state = "eating"
+                    if last_in then last_in = "" end
+                    return last_out
+                end
+            else
+                last_out = f(last_in)
+                if last_out == "" then
+                    if last_in == "" then
+                        state = "feeding"
+                    else
+                        base.error('filter returned ""')
+                    end
+                elseif not last_out then
+                    if last_in then
+                        base.error('filter returned inappropriate nil')
+                    else
+                        return nil
+                    end
+                else
+                    return last_out
+                end
+            end
+        end
+    end
+end
+
+-- creates a source that produces contents of several sources, one after the
+-- other, as if they were concatenated
+-- (thanks to Wim Couwenberg)
+function source.cat(...)
+    local src = table.remove(arg, 1)
+    return function()
+        while src do
+            local chunk, err = src()
+            if chunk then return chunk end
+            if err then return nil, err end
+            src = table.remove(arg, 1)
+        end
+    end
+end
+
+-----------------------------------------------------------------------------
+-- Sink stuff
+-----------------------------------------------------------------------------
+-- creates a sink that stores into a table
+function sink.table(t)
+    t = t or {}
+    local f = function(chunk, err)
+        if chunk then table.insert(t, chunk) end
+        return 1
+    end
+    return f, t
+end
+
+-- turns a fancy sink into a simple sink
+function sink.simplify(snk)
+    base.assert(snk)
+    return function(chunk, err)
+        local ret, err_or_new = snk(chunk, err)
+        if not ret then return nil, err_or_new end
+        snk = err_or_new or snk
+        return 1
+    end
+end
+
+-- creates a file sink
+function sink.file(handle, io_err)
+    if handle then
+        return function(chunk, err)
+            if not chunk then
+                handle:close()
+                return 1
+            else return handle:write(chunk) end
+        end
+    else return sink.error(io_err or "unable to open file") end
+end
+
+-- creates a sink that discards data
+local function null()
+    return 1
+end
+
+function sink.null()
+    return null
+end
+
+-- creates a sink that just returns an error
+function sink.error(err)
+    return function()
+        return nil, err
+    end
+end
+
+-- chains a sink with a filter
+function sink.chain(f, snk)
+    base.assert(f and snk)
+    return function(chunk, err)
+        if chunk ~= "" then
+            local filtered = f(chunk)
+            local done = chunk and ""
+            while true do
+                local ret, snkerr = snk(filtered, err)
+                if not ret then return nil, snkerr end
+                if filtered == done then return 1 end
+                filtered = f(done)
+            end
+        else return 1 end
+    end
+end
+
+-----------------------------------------------------------------------------
+-- Pump stuff
+-----------------------------------------------------------------------------
+-- pumps one chunk from the source to the sink
+function pump.step(src, snk)
+    local chunk, src_err = src()
+    local ret, snk_err = snk(chunk, src_err)
+    if chunk and ret then return 1
+    else return nil, src_err or snk_err end
+end
+
+-- pumps all data from a source to a sink, using a step function
+function pump.all(src, snk, step)
+    base.assert(src and snk)
+    step = step or pump.step
+    while true do
+        local ret, err = step(src, snk)
+        if not ret then
+            if err then return nil, err
+            else return 1 end
+        end
+    end
+end
+
diff --git a/game/thirdparty/mime.lua b/game/thirdparty/mime.lua
new file mode 100644
index 0000000000000000000000000000000000000000..169eda29a941aea9c59d9a0fb10a241843b5afc5
--- /dev/null
+++ b/game/thirdparty/mime.lua
@@ -0,0 +1,87 @@
+-----------------------------------------------------------------------------
+-- MIME support for the Lua language.
+-- Author: Diego Nehab
+-- Conforming to RFCs 2045-2049
+-- RCS ID: $Id: mime.lua,v 1.29 2007/06/11 23:44:54 diego Exp $
+-----------------------------------------------------------------------------
+
+-----------------------------------------------------------------------------
+-- Declare module and import dependencies
+-----------------------------------------------------------------------------
+local base = _G
+local ltn12 = require("ltn12")
+local mime = require("mime.core")
+local io = require("io")
+local string = require("string")
+module("mime")
+
+-- encode, decode and wrap algorithm tables
+encodet = {}
+decodet = {}
+wrapt = {}
+
+-- creates a function that chooses a filter by name from a given table
+local function choose(table)
+    return function(name, opt1, opt2)
+        if base.type(name) ~= "string" then
+            name, opt1, opt2 = "default", name, opt1
+        end
+        local f = table[name or "nil"]
+        if not f then 
+            base.error("unknown key (" .. base.tostring(name) .. ")", 3)
+        else return f(opt1, opt2) end
+    end
+end
+
+-- define the encoding filters
+encodet['base64'] = function()
+    return ltn12.filter.cycle(b64, "")
+end
+
+encodet['quoted-printable'] = function(mode)
+    return ltn12.filter.cycle(qp, "",
+        (mode == "binary") and "=0D=0A" or "\r\n")
+end
+
+-- define the decoding filters
+decodet['base64'] = function()
+    return ltn12.filter.cycle(unb64, "")
+end
+
+decodet['quoted-printable'] = function()
+    return ltn12.filter.cycle(unqp, "")
+end
+
+local function format(chunk)
+    if chunk then
+        if chunk == "" then return "''"
+        else return string.len(chunk) end
+    else return "nil" end
+end
+
+-- define the line-wrap filters
+wrapt['text'] = function(length)
+    length = length or 76
+    return ltn12.filter.cycle(wrp, length, length)
+end
+wrapt['base64'] = wrapt['text']
+wrapt['default'] = wrapt['text']
+
+wrapt['quoted-printable'] = function()
+    return ltn12.filter.cycle(qpwrp, 76, 76)
+end
+
+-- function that choose the encoding, decoding or wrap algorithm
+encode = choose(encodet)
+decode = choose(decodet)
+wrap = choose(wrapt)
+
+-- define the end-of-line normalization filter
+function normalize(marker)
+    return ltn12.filter.cycle(eol, 0, marker)
+end
+
+-- high level stuffing filter
+function stuff()
+    return ltn12.filter.cycle(dot, 2)
+end
diff --git a/game/thirdparty/remdebug/engine.lua b/game/thirdparty/remdebug/engine.lua
new file mode 100644
index 0000000000000000000000000000000000000000..ec783b074adfb0ae119393be756e4a67e29c2541
--- /dev/null
+++ b/game/thirdparty/remdebug/engine.lua
@@ -0,0 +1,283 @@
+--
+-- RemDebug 1.0 Beta
+-- Copyright Kepler Project 2005 (http://www.keplerproject.org/remdebug)
+--
+
+local socket = require"socket"
+--local lfs = require"lfs"
+local debug = require"debug"
+
+module("remdebug.engine", package.seeall)
+
+_COPYRIGHT = "2006 - Kepler Project"
+_DESCRIPTION = "Remote Debugger for the Lua programming language"
+_VERSION = "1.0"
+
+local coro_debugger
+local events = { BREAK = 1, WATCH = 2 }
+local breakpoints = {}
+local watches = {}
+local step_into = false
+local step_over = false
+local step_level = 0
+local stack_level = 0
+
+local controller_host = "localhost"
+local controller_port = 8171
+
+local function set_breakpoint(file, line)
+  if not breakpoints[file] then
+    breakpoints[file] = {}
+  end
+  breakpoints[file][line] = true
+end
+
+local function remove_breakpoint(file, line)
+  if breakpoints[file] then
+    breakpoints[file][line] = nil
+  end
+end
+
+local function has_breakpoint(file, line)
+  return breakpoints[file] and breakpoints[file][line]
+end
+
+local function restore_vars(vars)
+  if type(vars) ~= 'table' then return end
+  local func = debug.getinfo(3, "f").func
+  local i = 1
+  local written_vars = {}
+  while true do
+    local name = debug.getlocal(3, i)
+    if not name then break end
+    debug.setlocal(3, i, vars[name])
+    written_vars[name] = true
+    i = i + 1
+  end
+  i = 1
+  while true do
+    local name = debug.getupvalue(func, i)
+    if not name then break end
+    if not written_vars[name] then
+      debug.setupvalue(func, i, vars[name])
+      written_vars[name] = true
+    end
+    i = i + 1
+  end
+end
+
+local function capture_vars()
+  local vars = {}
+  local func = debug.getinfo(3, "f").func
+  local i = 1
+  while true do
+    local name, value = debug.getupvalue(func, i)
+    if not name then break end
+    vars[name] = value
+    i = i + 1
+  end
+  i = 1
+  while true do
+    local name, value = debug.getlocal(3, i)
+    if not name then break end
+    vars[name] = value
+    i = i + 1
+  end
+  setmetatable(vars, { __index = getfenv(func), __newindex = getfenv(func) })
+  return vars
+end
+
+local function break_dir(path)
+  local paths = {}
+  path = string.gsub(path, "\\", "/")
+  for w in string.gfind(path, "[^\/]+") do
+    table.insert(paths, w)
+  end
+  return paths
+end
+
+local function merge_paths(path1, path2)
+  local paths1 = break_dir(path1)
+  local paths2 = break_dir(path2)
+  for i, path in ipairs(paths2) do
+    if path == ".." then
+      table.remove(paths1, table.getn(paths1))
+    elseif path ~= "." then
+      table.insert(paths1, path)
+    end
+  end
+  return table.concat(paths1, "/")
+end
+
+local function debug_hook(event, line)
+  if event == "call" then
+    stack_level = stack_level + 1
+  elseif event == "return" then
+    stack_level = stack_level - 1
+  else
+    local file = debug.getinfo(2, "S").source
+    if string.find(file, "@") == 1 then
+      file = string.sub(file, 2)
+    end
+    file = merge_paths("/", file)
+    local vars = capture_vars()
+    table.foreach(watches, function (index, value)
+      setfenv(value, vars)
+      local status, res = pcall(value)
+      if status and res then
+        coroutine.resume(coro_debugger, events.WATCH, vars, file, line, index)
+      end
+    end)
+    if step_into or (step_over and stack_level <= step_level) or has_breakpoint(file, line) then
+      step_into = false
+      step_over = false
+      coroutine.resume(coro_debugger, events.BREAK, vars, file, line)
+      restore_vars(vars)
+    end
+  end
+end
+
+local function debugger_loop(server)
+  local command
+  local eval_env = {}
+
+  while true do
+    local line, status = server:receive()
+    command = string.sub(line, string.find(line, "^[A-Z]+"))
+    if command == "SETB" then
+      local _, _, _, filename, line = string.find(line, "^([A-Z]+)%s+([%w%p]+)%s+(%d+)$")
+      if filename and line then
+        set_breakpoint(filename, tonumber(line))
+        server:send("200 OK\n")
+      else
+        server:send("400 Bad Request\n")
+      end
+    elseif command == "DELB" then
+      local _, _, _, filename, line = string.find(line, "^([A-Z]+)%s+([%w%p]+)%s+(%d+)$")
+      if filename and line then
+        remove_breakpoint(filename, tonumber(line))
+        server:send("200 OK\n")
+      else
+        server:send("400 Bad Request\n")
+      end
+    elseif command == "EXEC" then
+      local _, _, chunk = string.find(line, "^[A-Z]+%s+(.+)$")
+      if chunk then
+        local func = loadstring(chunk)
+        local status, res
+        if func then
+          setfenv(func, eval_env)
+          status, res = xpcall(func, debug.traceback)
+        end
+        res = tostring(res)
+        if status then
+          server:send("200 OK " .. string.len(res) .. "\n")
+          server:send(res)
+        else
+          server:send("401 Error in Expression " .. string.len(res) .. "\n")
+          server:send(res)
+        end
+      else
+        server:send("400 Bad Request\n")
+      end
+    elseif command == "SETW" then
+      local _, _, exp = string.find(line, "^[A-Z]+%s+(.+)$")
+      if exp then
+        local func = loadstring("return(" .. exp .. ")")
+        local newidx = table.getn(watches) + 1
+        watches[newidx] = func
+        table.setn(watches, newidx)
+        server:send("200 OK " .. newidx .. "\n")
+      else
+        server:send("400 Bad Request\n")
+      end
+    elseif command == "DELW" then
+      local _, _, index = string.find(line, "^[A-Z]+%s+(%d+)$")
+      index = tonumber(index)
+      if index then
+        watches[index] = nil
+        server:send("200 OK\n")
+      else
+        server:send("400 Bad Request\n")
+      end
+    elseif command == "RUN" then
+      server:send("200 OK\n")
+      local ev, vars, file, line, idx_watch = coroutine.yield()
+      eval_env = vars
+      if ev == events.BREAK then
+        server:send("202 Paused " .. file .. " " .. line .. "\n")
+      elseif ev == events.WATCH then
+        server:send("203 Paused " .. file .. " " .. line .. " " .. idx_watch .. "\n")
+      else
+        server:send("401 Error in Execution " .. string.len(file) .. "\n")
+        server:send(file)
+      end
+    elseif command == "STEP" then
+      server:send("200 OK\n")
+      step_into = true
+      local ev, vars, file, line, idx_watch = coroutine.yield()
+      eval_env = vars
+      if ev == events.BREAK then
+        server:send("202 Paused " .. file .. " " .. line .. "\n")
+      elseif ev == events.WATCH then
+        server:send("203 Paused " .. file .. " " .. line .. " " .. idx_watch .. "\n")
+      else
+        server:send("401 Error in Execution " .. string.len(file) .. "\n")
+        server:send(file)
+      end
+    elseif command == "OVER" then
+      server:send("200 OK\n")
+      step_over = true
+      step_level = stack_level
+      local ev, vars, file, line, idx_watch = coroutine.yield()
+      eval_env = vars
+      if ev == events.BREAK then
+        server:send("202 Paused " .. file .. " " .. line .. "\n")
+      elseif ev == events.WATCH then
+        server:send("203 Paused " .. file .. " " .. line .. " " .. idx_watch .. "\n")
+      else
+        server:send("401 Error in Execution " .. string.len(file) .. "\n")
+        server:send(file)
+      end
+    else
+      server:send("400 Bad Request\n")
+    end
+  end
+end
+
+coro_debugger = coroutine.create(debugger_loop)
+
+--
+-- remdebug.engine.config(tab)
+-- Configures the engine
+--
+function config(tab)
+  if tab.host then
+    controller_host = tab.host
+  end
+  if tab.port then
+    controller_port = tab.port
+  end
+end
+
+--
+-- remdebug.engine.start()
+-- Tries to start the debug session by connecting with a controller
+--
+function start()
+  pcall(require, "remdebug.config")
+  local server = socket.tcp()
+  server:connect(controller_host, controller_port)
+  if server then
+    _TRACEBACK = function (message)
+      local err = debug.traceback(message)
+      server:send("401 Error in Execution " .. string.len(err) .. "\n")
+      server:send(err)
+      server:close()
+      return err
+    end
+    debug.sethook(debug_hook, "lcr")
+    return coroutine.resume(coro_debugger, server)
+  end
+end
+
diff --git a/game/thirdparty/socket.lua b/game/thirdparty/socket.lua
new file mode 100644
index 0000000000000000000000000000000000000000..211adcd1d98f0c0b3b93c687adf9e2640a4bfc79
--- /dev/null
+++ b/game/thirdparty/socket.lua
@@ -0,0 +1,133 @@
+-----------------------------------------------------------------------------
+-- LuaSocket helper module
+-- Author: Diego Nehab
+-- RCS ID: $Id: socket.lua,v 1.22 2005/11/22 08:33:29 diego Exp $
+-----------------------------------------------------------------------------
+
+-----------------------------------------------------------------------------
+-- Declare module and import dependencies
+-----------------------------------------------------------------------------
+local base = _G
+local string = require("string")
+local math = require("math")
+local socket = require("socket.core")
+module("socket")
+
+-----------------------------------------------------------------------------
+-- Exported auxiliar functions
+-----------------------------------------------------------------------------
+function connect(address, port, laddress, lport)
+    local sock, err = socket.tcp()
+    if not sock then return nil, err end
+    if laddress then
+        local res, err = sock:bind(laddress, lport, -1)
+        if not res then return nil, err end
+    end
+    local res, err = sock:connect(address, port)
+    if not res then return nil, err end
+    return sock
+end
+
+function bind(host, port, backlog)
+    local sock, err = socket.tcp()
+    if not sock then return nil, err end
+    sock:setoption("reuseaddr", true)
+    local res, err = sock:bind(host, port)
+    if not res then return nil, err end
+    res, err = sock:listen(backlog)
+    if not res then return nil, err end
+    return sock
+end
+
+try = newtry()
+
+function choose(table)
+    return function(name, opt1, opt2)
+        if base.type(name) ~= "string" then
+            name, opt1, opt2 = "default", name, opt1
+        end
+        local f = table[name or "nil"]
+        if not f then base.error("unknown key (".. base.tostring(name) ..")", 3)
+        else return f(opt1, opt2) end
+    end
+end
+
+-----------------------------------------------------------------------------
+-- Socket sources and sinks, conforming to LTN12
+-----------------------------------------------------------------------------
+-- create namespaces inside LuaSocket namespace
+sourcet = {}
+sinkt = {}
+
+BLOCKSIZE = 2048
+
+sinkt["close-when-done"] = function(sock)
+    return base.setmetatable({
+        getfd = function() return sock:getfd() end,
+        dirty = function() return sock:dirty() end
+    }, {
+        __call = function(self, chunk, err)
+            if not chunk then
+                sock:close()
+                return 1
+            else return sock:send(chunk) end
+        end
+    })
+end
+
+sinkt["keep-open"] = function(sock)
+    return base.setmetatable({
+        getfd = function() return sock:getfd() end,
+        dirty = function() return sock:dirty() end
+    }, {
+        __call = function(self, chunk, err)
+            if chunk then return sock:send(chunk)
+            else return 1 end
+        end
+    })
+end
+
+sinkt["default"] = sinkt["keep-open"]
+
+sink = choose(sinkt)
+
+sourcet["by-length"] = function(sock, length)
+    return base.setmetatable({
+        getfd = function() return sock:getfd() end,
+        dirty = function() return sock:dirty() end
+    }, {
+        __call = function()
+            if length <= 0 then return nil end
+            local size = math.min(socket.BLOCKSIZE, length)
+            local chunk, err = sock:receive(size)
+            if err then return nil, err end
+            length = length - string.len(chunk)
+            return chunk
+        end
+    })
+end
+
+sourcet["until-closed"] = function(sock)
+    local done
+    return base.setmetatable({
+        getfd = function() return sock:getfd() end,
+        dirty = function() return sock:dirty() end
+    }, {
+        __call = function()
+            if done then return nil end
+            local chunk, err, partial = sock:receive(socket.BLOCKSIZE)
+            if not err then return chunk
+            elseif err == "closed" then
+                sock:close()
+                done = 1
+                return partial
+            else return nil, err end
+        end
+    })
+end
+
+
+sourcet["default"] = sourcet["until-closed"]
+
+source = choose(sourcet)
+
diff --git a/game/thirdparty/socket/ftp.lua b/game/thirdparty/socket/ftp.lua
new file mode 100644
index 0000000000000000000000000000000000000000..598f65dcaf07b07db28f9c80dac236884cb8ba12
--- /dev/null
+++ b/game/thirdparty/socket/ftp.lua
@@ -0,0 +1,281 @@
+-----------------------------------------------------------------------------
+-- FTP support for the Lua language
+-- LuaSocket toolkit.
+-- Author: Diego Nehab
+-- RCS ID: $Id: ftp.lua,v 1.45 2007/07/11 19:25:47 diego Exp $
+-----------------------------------------------------------------------------
+
+-----------------------------------------------------------------------------
+-- Declare module and import dependencies
+-----------------------------------------------------------------------------
+local base = _G
+local table = require("table")
+local string = require("string")
+local math = require("math")
+local socket = require("socket")
+local url = require("socket.url")
+local tp = require("socket.tp")
+local ltn12 = require("ltn12")
+module("socket.ftp")
+
+-----------------------------------------------------------------------------
+-- Program constants
+-----------------------------------------------------------------------------
+-- timeout in seconds before the program gives up on a connection
+TIMEOUT = 60
+-- default port for ftp service
+PORT = 21
+-- this is the default anonymous password. used when no password is
+-- provided in url. should be changed to your e-mail.
+USER = "ftp"
+PASSWORD = "anonymous@anonymous.org"
+
+-----------------------------------------------------------------------------
+-- Low level FTP API
+-----------------------------------------------------------------------------
+local metat = { __index = {} }
+
+function open(server, port, create)
+    local tp = socket.try(tp.connect(server, port or PORT, TIMEOUT, create))
+    local f = base.setmetatable({ tp = tp }, metat)
+    -- make sure everything gets closed in an exception
+    f.try = socket.newtry(function() f:close() end)
+    return f
+end
+
+function metat.__index:portconnect()
+    self.try(self.server:settimeout(TIMEOUT))
+    self.data = self.try(self.server:accept())
+    self.try(self.data:settimeout(TIMEOUT))
+end
+
+function metat.__index:pasvconnect()
+    self.data = self.try(socket.tcp())
+    self.try(self.data:settimeout(TIMEOUT))
+    self.try(self.data:connect(self.pasvt.ip, self.pasvt.port))
+end
+
+function metat.__index:login(user, password)
+    self.try(self.tp:command("user", user or USER))
+    local code, reply = self.try(self.tp:check{"2..", 331})
+    if code == 331 then
+        self.try(self.tp:command("pass", password or PASSWORD))
+        self.try(self.tp:check("2.."))
+    end
+    return 1
+end
+
+function metat.__index:pasv()
+    self.try(self.tp:command("pasv"))
+    local code, reply = self.try(self.tp:check("2.."))
+    local pattern = "(%d+)%D(%d+)%D(%d+)%D(%d+)%D(%d+)%D(%d+)"
+    local a, b, c, d, p1, p2 = socket.skip(2, string.find(reply, pattern))
+    self.try(a and b and c and d and p1 and p2, reply)
+    self.pasvt = {
+        ip = string.format("%d.%d.%d.%d", a, b, c, d),
+        port = p1*256 + p2
+    }
+    if self.server then
+        self.server:close()
+        self.server = nil
+    end
+    return self.pasvt.ip, self.pasvt.port
+end
+
+function metat.__index:port(ip, port)
+    self.pasvt = nil
+    if not ip then
+        ip, port = self.try(self.tp:getcontrol():getsockname())
+        self.server = self.try(socket.bind(ip, 0))
+        ip, port = self.try(self.server:getsockname())
+        self.try(self.server:settimeout(TIMEOUT))
+    end
+    local pl = math.mod(port, 256)
+    local ph = (port - pl)/256
+    local arg = string.gsub(string.format("%s,%d,%d", ip, ph, pl), "%.", ",")
+    self.try(self.tp:command("port", arg))
+    self.try(self.tp:check("2.."))
+    return 1
+end
+
+function metat.__index:send(sendt)
+    self.try(self.pasvt or self.server, "need port or pasv first")
+    -- if there is a pasvt table, we already sent a PASV command
+    -- we just get the data connection into self.data
+    if self.pasvt then self:pasvconnect() end
+    -- get the transfer argument and command
+    local argument = sendt.argument or
+        url.unescape(string.gsub(sendt.path or "", "^[/\\]", ""))
+    if argument == "" then argument = nil end
+    local command = sendt.command or "stor"
+    -- send the transfer command and check the reply
+    self.try(self.tp:command(command, argument))
+    local code, reply = self.try(self.tp:check{"2..", "1.."})
+    -- if there is not a a pasvt table, then there is a server
+    -- and we already sent a PORT command
+    if not self.pasvt then self:portconnect() end
+    -- get the sink, source and step for the transfer
+    local step = sendt.step or ltn12.pump.step
+    local readt = {self.tp.c}
+    local checkstep = function(src, snk)
+        -- check status in control connection while downloading
+        local readyt = socket.select(readt, nil, 0)
+        if readyt[tp] then code = self.try(self.tp:check("2..")) end
+        return step(src, snk)
+    end
+    local sink = socket.sink("close-when-done", self.data)
+    -- transfer all data and check error
+    self.try(ltn12.pump.all(sendt.source, sink, checkstep))
+    if string.find(code, "1..") then self.try(self.tp:check("2..")) end
+    -- done with data connection
+    self.data:close()
+    -- find out how many bytes were sent
+    local sent = socket.skip(1, self.data:getstats())
+    self.data = nil
+    return sent
+end
+
+function metat.__index:receive(recvt)
+    self.try(self.pasvt or self.server, "need port or pasv first")
+    if self.pasvt then self:pasvconnect() end
+    local argument = recvt.argument or
+        url.unescape(string.gsub(recvt.path or "", "^[/\\]", ""))
+    if argument == "" then argument = nil end
+    local command = recvt.command or "retr"
+    self.try(self.tp:command(command, argument))
+    local code = self.try(self.tp:check{"1..", "2.."})
+    if not self.pasvt then self:portconnect() end
+    local source = socket.source("until-closed", self.data)
+    local step = recvt.step or ltn12.pump.step
+    self.try(ltn12.pump.all(source, recvt.sink, step))
+    if string.find(code, "1..") then self.try(self.tp:check("2..")) end
+    self.data:close()
+    self.data = nil
+    return 1
+end
+
+function metat.__index:cwd(dir)
+    self.try(self.tp:command("cwd", dir))
+    self.try(self.tp:check(250))
+    return 1
+end
+
+function metat.__index:type(type)
+    self.try(self.tp:command("type", type))
+    self.try(self.tp:check(200))
+    return 1
+end
+
+function metat.__index:greet()
+    local code = self.try(self.tp:check{"1..", "2.."})
+    if string.find(code, "1..") then self.try(self.tp:check("2..")) end
+    return 1
+end
+
+function metat.__index:quit()
+    self.try(self.tp:command("quit"))
+    self.try(self.tp:check("2.."))
+    return 1
+end
+
+function metat.__index:close()
+    if self.data then self.data:close() end
+    if self.server then self.server:close() end
+    return self.tp:close()
+end
+
+-----------------------------------------------------------------------------
+-- High level FTP API
+-----------------------------------------------------------------------------
+local function override(t)
+    if t.url then
+        local u = url.parse(t.url)
+        for i,v in base.pairs(t) do
+            u[i] = v
+        end
+        return u
+    else return t end
+end
+
+local function tput(putt)
+    putt = override(putt)
+    socket.try(putt.host, "missing hostname")
+    local f = open(putt.host, putt.port, putt.create)
+    f:greet()
+    f:login(putt.user, putt.password)
+    if putt.type then f:type(putt.type) end
+    f:pasv()
+    local sent = f:send(putt)
+    f:quit()
+    f:close()
+    return sent
+end
+
+local default = {
+	path = "/",
+	scheme = "ftp"
+}
+
+local function parse(u)
+    local t = socket.try(url.parse(u, default))
+    socket.try(t.scheme == "ftp", "wrong scheme '" .. t.scheme .. "'")
+    socket.try(t.host, "missing hostname")
+    local pat = "^type=(.)$"
+    if t.params then
+        t.type = socket.skip(2, string.find(t.params, pat))
+        socket.try(t.type == "a" or t.type == "i",
+            "invalid type '" .. t.type .. "'")
+    end
+    return t
+end
+
+local function sput(u, body)
+    local putt = parse(u)
+    putt.source = ltn12.source.string(body)
+    return tput(putt)
+end
+
+put = socket.protect(function(putt, body)
+    if base.type(putt) == "string" then return sput(putt, body)
+    else return tput(putt) end
+end)
+
+local function tget(gett)
+    gett = override(gett)
+    socket.try(gett.host, "missing hostname")
+    local f = open(gett.host, gett.port, gett.create)
+    f:greet()
+    f:login(gett.user, gett.password)
+    if gett.type then f:type(gett.type) end
+    f:pasv()
+    f:receive(gett)
+    f:quit()
+    return f:close()
+end
+
+local function sget(u)
+    local gett = parse(u)
+    local t = {}
+    gett.sink = ltn12.sink.table(t)
+    tget(gett)
+    return table.concat(t)
+end
+
+command = socket.protect(function(cmdt)
+    cmdt = override(cmdt)
+    socket.try(cmdt.host, "missing hostname")
+    socket.try(cmdt.command, "missing command")
+    local f = open(cmdt.host, cmdt.port, cmdt.create)
+    f:greet()
+    f:login(cmdt.user, cmdt.password)
+    f.try(f.tp:command(cmdt.command, cmdt.argument))
+    if cmdt.check then f.try(f.tp:check(cmdt.check)) end
+    f:quit()
+    return f:close()
+end)
+
+get = socket.protect(function(gett)
+    if base.type(gett) == "string" then return sget(gett)
+    else return tget(gett) end
+end)
+
diff --git a/game/thirdparty/socket/http.lua b/game/thirdparty/socket/http.lua
new file mode 100644
index 0000000000000000000000000000000000000000..ad8db1ee06589d8af05e3722d2a5dc472129b446
--- /dev/null
+++ b/game/thirdparty/socket/http.lua
@@ -0,0 +1,350 @@
+-----------------------------------------------------------------------------
+-- HTTP/1.1 client support for the Lua language.
+-- LuaSocket toolkit.
+-- Author: Diego Nehab
+-- RCS ID: $Id: http.lua,v 1.71 2007/10/13 23:55:20 diego Exp $
+-----------------------------------------------------------------------------
+
+-----------------------------------------------------------------------------
+-- Declare module and import dependencies
+-------------------------------------------------------------------------------
+local socket = require("socket")
+local url = require("socket.url")
+local ltn12 = require("ltn12")
+local mime = require("mime")
+local string = require("string")
+local base = _G
+local table = require("table")
+module("socket.http")
+
+-----------------------------------------------------------------------------
+-- Program constants
+-----------------------------------------------------------------------------
+-- connection timeout in seconds
+TIMEOUT = 60
+-- default port for document retrieval
+PORT = 80
+-- user agent field sent in request
+USERAGENT = socket._VERSION
+
+-----------------------------------------------------------------------------
+-- Reads MIME headers from a connection, unfolding where needed
+-----------------------------------------------------------------------------
+local function receiveheaders(sock, headers)
+    local line, name, value, err
+    headers = headers or {}
+    -- get first line
+    line, err = sock:receive()
+    if err then return nil, err end
+    -- headers go until a blank line is found
+    while line ~= "" do
+        -- get field-name and value
+        name, value = socket.skip(2, string.find(line, "^(.-):%s*(.*)"))
+        if not (name and value) then return nil, "malformed reponse headers" end
+        name = string.lower(name)
+        -- get next line (value might be folded)
+        line, err  = sock:receive()
+        if err then return nil, err end
+        -- unfold any folded values
+        while string.find(line, "^%s") do
+            value = value .. line
+            line = sock:receive()
+            if err then return nil, err end
+        end
+        -- save pair in table
+        if headers[name] then headers[name] = headers[name] .. ", " .. value
+        else headers[name] = value end
+    end
+    return headers
+end
+
+-----------------------------------------------------------------------------
+-- Extra sources and sinks
+-----------------------------------------------------------------------------
+socket.sourcet["http-chunked"] = function(sock, headers)
+    return base.setmetatable({
+        getfd = function() return sock:getfd() end,
+        dirty = function() return sock:dirty() end
+    }, {
+        __call = function()
+            -- get chunk size, skip extention
+            local line, err = sock:receive()
+            if err then return nil, err end
+            local size = base.tonumber(string.gsub(line, ";.*", ""), 16)
+            if not size then return nil, "invalid chunk size" end
+            -- was it the last chunk?
+            if size > 0 then
+                -- if not, get chunk and skip terminating CRLF
+                local chunk, err, part = sock:receive(size)
+                if chunk then sock:receive() end
+                return chunk, err
+            else
+                -- if it was, read trailers into headers table
+                headers, err = receiveheaders(sock, headers)
+                if not headers then return nil, err end
+            end
+        end
+    })
+end
+
+socket.sinkt["http-chunked"] = function(sock)
+    return base.setmetatable({
+        getfd = function() return sock:getfd() end,
+        dirty = function() return sock:dirty() end
+    }, {
+        __call = function(self, chunk, err)
+            if not chunk then return sock:send("0\r\n\r\n") end
+            local size = string.format("%X\r\n", string.len(chunk))
+            return sock:send(size ..  chunk .. "\r\n")
+        end
+    })
+end
+
+-----------------------------------------------------------------------------
+-- Low level HTTP API
+-----------------------------------------------------------------------------
+local metat = { __index = {} }
+
+function open(host, port, create)
+    -- create socket with user connect function, or with default
+    local c = socket.try((create or socket.tcp)())
+    local h = base.setmetatable({ c = c }, metat)
+    -- create finalized try
+    h.try = socket.newtry(function() h:close() end)
+    -- set timeout before connecting
+    h.try(c:settimeout(TIMEOUT))
+    h.try(c:connect(host, port or PORT))
+    -- here everything worked
+    return h
+end
+
+function metat.__index:sendrequestline(method, uri)
+    local reqline = string.format("%s %s HTTP/1.1\r\n", method or "GET", uri)
+    return self.try(self.c:send(reqline))
+end
+
+function metat.__index:sendheaders(headers)
+    local h = "\r\n"
+    for i, v in base.pairs(headers) do
+        h = i .. ": " .. v .. "\r\n" .. h
+    end
+    self.try(self.c:send(h))
+    return 1
+end
+
+function metat.__index:sendbody(headers, source, step)
+    source = source or ltn12.source.empty()
+    step = step or ltn12.pump.step
+    -- if we don't know the size in advance, send chunked and hope for the best
+    local mode = "http-chunked"
+    if headers["content-length"] then mode = "keep-open" end
+    return self.try(ltn12.pump.all(source, socket.sink(mode, self.c), step))
+end
+
+function metat.__index:receivestatusline()
+    local status = self.try(self.c:receive(5))
+    -- identify HTTP/0.9 responses, which do not contain a status line
+    -- this is just a heuristic, but is what the RFC recommends
+    if status ~= "HTTP/" then return nil, status end
+    -- otherwise proceed reading a status line
+    status = self.try(self.c:receive("*l", status))
+    local code = socket.skip(2, string.find(status, "HTTP/%d*%.%d* (%d%d%d)"))
+    return self.try(base.tonumber(code), status)
+end
+
+function metat.__index:receiveheaders()
+    return self.try(receiveheaders(self.c))
+end
+
+function metat.__index:receivebody(headers, sink, step)
+    sink = sink or ltn12.sink.null()
+    step = step or ltn12.pump.step
+    local length = base.tonumber(headers["content-length"])
+    local t = headers["transfer-encoding"] -- shortcut
+    local mode = "default" -- connection close
+    if t and t ~= "identity" then mode = "http-chunked"
+    elseif base.tonumber(headers["content-length"]) then mode = "by-length" end
+    return self.try(ltn12.pump.all(socket.source(mode, self.c, length),
+        sink, step))
+end
+
+function metat.__index:receive09body(status, sink, step)
+    local source = ltn12.source.rewind(socket.source("until-closed", self.c))
+    source(status)
+    return self.try(ltn12.pump.all(source, sink, step))
+end
+
+function metat.__index:close()
+    return self.c:close()
+end
+
+-----------------------------------------------------------------------------
+-- High level HTTP API
+-----------------------------------------------------------------------------
+local function adjusturi(reqt)
+    local u = reqt
+    -- if there is a proxy, we need the full url. otherwise, just a part.
+    if not reqt.proxy and not PROXY then
+        u = {
+           path = socket.try(reqt.path, "invalid path 'nil'"),
+           params = reqt.params,
+           query = reqt.query,
+           fragment = reqt.fragment
+        }
+    end
+    return url.build(u)
+end
+
+local function adjustproxy(reqt)
+    local proxy = reqt.proxy or PROXY
+    if proxy then
+        proxy = url.parse(proxy)
+        return proxy.host, proxy.port or 3128
+    else
+        return reqt.host, reqt.port
+    end
+end
+
+local function adjustheaders(reqt)
+    -- default headers
+    local lower = {
+        ["user-agent"] = USERAGENT,
+        ["host"] = reqt.host,
+        ["connection"] = "close, TE",
+        ["te"] = "trailers"
+    }
+    -- if we have authentication information, pass it along
+    if reqt.user and reqt.password then
+        lower["authorization"] = 
+            "Basic " ..  (mime.b64(reqt.user .. ":" .. reqt.password))
+    end
+    -- override with user headers
+    for i,v in base.pairs(reqt.headers or lower) do
+        lower[string.lower(i)] = v
+    end
+    return lower
+end
+
+-- default url parts
+local default = {
+    host = "",
+    port = PORT,
+    path ="/",
+    scheme = "http"
+}
+
+local function adjustrequest(reqt)
+    -- parse url if provided
+    local nreqt = reqt.url and url.parse(reqt.url, default) or {}
+    -- explicit components override url
+    for i,v in base.pairs(reqt) do nreqt[i] = v end
+    if nreqt.port == "" then nreqt.port = 80 end
+    socket.try(nreqt.host and nreqt.host ~= "", 
+        "invalid host '" .. base.tostring(nreqt.host) .. "'")
+    -- compute uri if user hasn't overriden
+    nreqt.uri = reqt.uri or adjusturi(nreqt)
+    -- ajust host and port if there is a proxy
+    nreqt.host, nreqt.port = adjustproxy(nreqt)
+    -- adjust headers in request
+    nreqt.headers = adjustheaders(nreqt)
+    return nreqt
+end
+
+local function shouldredirect(reqt, code, headers)
+    return headers.location and
+           string.gsub(headers.location, "%s", "") ~= "" and
+           (reqt.redirect ~= false) and
+           (code == 301 or code == 302) and
+           (not reqt.method or reqt.method == "GET" or reqt.method == "HEAD")
+           and (not reqt.nredirects or reqt.nredirects < 5)
+end
+
+local function shouldreceivebody(reqt, code)
+    if reqt.method == "HEAD" then return nil end
+    if code == 204 or code == 304 then return nil end
+    if code >= 100 and code < 200 then return nil end
+    return 1
+end
+
+-- forward declarations
+local trequest, tredirect
+
+function tredirect(reqt, location)
+    local result, code, headers, status = trequest {
+        -- the RFC says the redirect URL has to be absolute, but some
+        -- servers do not respect that
+        url = url.absolute(reqt.url, location),
+        source = reqt.source,
+        sink = reqt.sink,
+        headers = reqt.headers,
+        proxy = reqt.proxy, 
+        nredirects = (reqt.nredirects or 0) + 1,
+        create = reqt.create
+    }   
+    -- pass location header back as a hint we redirected
+    headers = headers or {}
+    headers.location = headers.location or location
+    return result, code, headers, status
+end
+
+function trequest(reqt)
+    -- we loop until we get what we want, or
+    -- until we are sure there is no way to get it
+    local nreqt = adjustrequest(reqt)
+    local h = open(nreqt.host, nreqt.port, nreqt.create)
+    -- send request line and headers
+    h:sendrequestline(nreqt.method, nreqt.uri)
+    h:sendheaders(nreqt.headers)
+    -- if there is a body, send it
+    if nreqt.source then
+        h:sendbody(nreqt.headers, nreqt.source, nreqt.step) 
+    end
+    local code, status = h:receivestatusline()
+    -- if it is an HTTP/0.9 server, simply get the body and we are done
+    if not code then
+        h:receive09body(status, nreqt.sink, nreqt.step)
+        return 1, 200
+    end
+    local headers
+    -- ignore any 100-continue messages
+    while code == 100 do 
+        headers = h:receiveheaders()
+        code, status = h:receivestatusline()
+    end
+    headers = h:receiveheaders()
+    -- at this point we should have a honest reply from the server
+    -- we can't redirect if we already used the source, so we report the error 
+    if shouldredirect(nreqt, code, headers) and not nreqt.source then
+        h:close()
+        return tredirect(reqt, headers.location)
+    end
+    -- here we are finally done
+    if shouldreceivebody(nreqt, code) then
+        h:receivebody(headers, nreqt.sink, nreqt.step)
+    end
+    h:close()
+    return 1, code, headers, status
+end
+
+local function srequest(u, b)
+    local t = {}
+    local reqt = {
+        url = u,
+        sink = ltn12.sink.table(t)
+    }
+    if b then
+        reqt.source = ltn12.source.string(b)
+        reqt.headers = {
+            ["content-length"] = string.len(b),
+            ["content-type"] = "application/x-www-form-urlencoded"
+        }
+        reqt.method = "POST"
+    end
+    local code, headers, status = socket.skip(1, trequest(reqt))
+    return table.concat(t), code, headers, status
+end
+
+request = socket.protect(function(reqt, body)
+    if base.type(reqt) == "string" then return srequest(reqt, body)
+    else return trequest(reqt) end
+end)
diff --git a/game/thirdparty/socket/smtp.lua b/game/thirdparty/socket/smtp.lua
new file mode 100644
index 0000000000000000000000000000000000000000..8f3cfcff6e4162c484acf66fb93c09ac23feae49
--- /dev/null
+++ b/game/thirdparty/socket/smtp.lua
@@ -0,0 +1,251 @@
+-----------------------------------------------------------------------------
+-- SMTP client support for the Lua language.
+-- LuaSocket toolkit.
+-- Author: Diego Nehab
+-- RCS ID: $Id: smtp.lua,v 1.46 2007/03/12 04:08:40 diego Exp $
+-----------------------------------------------------------------------------
+
+-----------------------------------------------------------------------------
+-- Declare module and import dependencies
+-----------------------------------------------------------------------------
+local base = _G
+local coroutine = require("coroutine")
+local string = require("string")
+local math = require("math")
+local os = require("os")
+local socket = require("socket")
+local tp = require("socket.tp")
+local ltn12 = require("ltn12")
+local mime = require("mime")
+module("socket.smtp")
+
+-----------------------------------------------------------------------------
+-- Program constants
+-----------------------------------------------------------------------------
+-- timeout for connection
+TIMEOUT = 60
+-- default server used to send e-mails
+SERVER = "localhost"
+-- default port
+PORT = 25
+-- domain used in HELO command and default sendmail
+-- If we are under a CGI, try to get from environment
+DOMAIN = os.getenv("SERVER_NAME") or "localhost"
+-- default time zone (means we don't know)
+ZONE = "-0000"
+
+---------------------------------------------------------------------------
+-- Low level SMTP API
+-----------------------------------------------------------------------------
+local metat = { __index = {} }
+
+function metat.__index:greet(domain)
+    self.try(self.tp:check("2.."))
+    self.try(self.tp:command("EHLO", domain or DOMAIN))
+    return socket.skip(1, self.try(self.tp:check("2..")))
+end
+
+function metat.__index:mail(from)
+    self.try(self.tp:command("MAIL", "FROM:" .. from))
+    return self.try(self.tp:check("2.."))
+end
+
+function metat.__index:rcpt(to)
+    self.try(self.tp:command("RCPT", "TO:" .. to))
+    return self.try(self.tp:check("2.."))
+end
+
+function metat.__index:data(src, step)
+    self.try(self.tp:command("DATA"))
+    self.try(self.tp:check("3.."))
+    self.try(self.tp:source(src, step))
+    self.try(self.tp:send("\r\n.\r\n"))
+    return self.try(self.tp:check("2.."))
+end
+
+function metat.__index:quit()
+    self.try(self.tp:command("QUIT"))
+    return self.try(self.tp:check("2.."))
+end
+
+function metat.__index:close()
+    return self.tp:close()
+end
+
+function metat.__index:login(user, password)
+    self.try(self.tp:command("AUTH", "LOGIN"))
+    self.try(self.tp:check("3.."))
+    self.try(self.tp:command(mime.b64(user)))
+    self.try(self.tp:check("3.."))
+    self.try(self.tp:command(mime.b64(password)))
+    return self.try(self.tp:check("2.."))
+end
+
+function metat.__index:plain(user, password)
+    local auth = "PLAIN " .. mime.b64("\0" .. user .. "\0" .. password)
+    self.try(self.tp:command("AUTH", auth))
+    return self.try(self.tp:check("2.."))
+end
+
+function metat.__index:auth(user, password, ext)
+    if not user or not password then return 1 end
+    if string.find(ext, "AUTH[^\n]+LOGIN") then
+        return self:login(user, password)
+    elseif string.find(ext, "AUTH[^\n]+PLAIN") then
+        return self:plain(user, password)
+    else
+        self.try(nil, "authentication not supported")
+    end
+end
+
+-- send message or throw an exception
+function metat.__index:send(mailt)
+    self:mail(mailt.from)
+    if base.type(mailt.rcpt) == "table" then
+        for i,v in base.ipairs(mailt.rcpt) do
+            self:rcpt(v)
+        end
+    else
+        self:rcpt(mailt.rcpt)
+    end
+    self:data(ltn12.source.chain(mailt.source, mime.stuff()), mailt.step)
+end
+
+function open(server, port, create)
+    local tp = socket.try(tp.connect(server or SERVER, port or PORT,
+        TIMEOUT, create))
+    local s = base.setmetatable({tp = tp}, metat)
+    -- make sure tp is closed if we get an exception
+    s.try = socket.newtry(function()
+        s:close()
+    end)
+    return s
+end
+
+-- convert headers to lowercase
+local function lower_headers(headers)
+    local lower = {}
+    for i,v in base.pairs(headers or lower) do
+        lower[string.lower(i)] = v
+    end
+    return lower
+end
+
+---------------------------------------------------------------------------
+-- Multipart message source
+-----------------------------------------------------------------------------
+-- returns a hopefully unique mime boundary
+local seqno = 0
+local function newboundary()
+    seqno = seqno + 1
+    return string.format('%s%05d==%05u', os.date('%d%m%Y%H%M%S'),
+        math.random(0, 99999), seqno)
+end
+
+-- send_message forward declaration
+local send_message
+
+-- yield the headers all at once, it's faster
+local function send_headers(headers)
+    local h = "\r\n"
+    for i,v in base.pairs(headers) do
+        h = i .. ': ' .. v .. "\r\n" .. h
+    end
+    coroutine.yield(h)
+end
+
+-- yield multipart message body from a multipart message table
+local function send_multipart(mesgt)
+    -- make sure we have our boundary and send headers
+    local bd = newboundary()
+    local headers = lower_headers(mesgt.headers or {})
+    headers['content-type'] = headers['content-type'] or 'multipart/mixed'
+    headers['content-type'] = headers['content-type'] ..
+        '; boundary="' ..  bd .. '"'
+    send_headers(headers)
+    -- send preamble
+    if mesgt.body.preamble then
+        coroutine.yield(mesgt.body.preamble)
+        coroutine.yield("\r\n")
+    end
+    -- send each part separated by a boundary
+    for i, m in base.ipairs(mesgt.body) do
+        coroutine.yield("\r\n--" .. bd .. "\r\n")
+        send_message(m)
+    end
+    -- send last boundary
+    coroutine.yield("\r\n--" .. bd .. "--\r\n\r\n")
+    -- send epilogue
+    if mesgt.body.epilogue then
+        coroutine.yield(mesgt.body.epilogue)
+        coroutine.yield("\r\n")
+    end
+end
+
+-- yield message body from a source
+local function send_source(mesgt)
+    -- make sure we have a content-type
+    local headers = lower_headers(mesgt.headers or {})
+    headers['content-type'] = headers['content-type'] or
+        'text/plain; charset="iso-8859-1"'
+    send_headers(headers)
+    -- send body from source
+    while true do
+        local chunk, err = mesgt.body()
+        if err then coroutine.yield(nil, err)
+        elseif chunk then coroutine.yield(chunk)
+        else break end
+    end
+end
+
+-- yield message body from a string
+local function send_string(mesgt)
+    -- make sure we have a content-type
+    local headers = lower_headers(mesgt.headers or {})
+    headers['content-type'] = headers['content-type'] or
+        'text/plain; charset="iso-8859-1"'
+    send_headers(headers)
+    -- send body from string
+    coroutine.yield(mesgt.body)
+end
+
+-- message source
+function send_message(mesgt)
+    if base.type(mesgt.body) == "table" then send_multipart(mesgt)
+    elseif base.type(mesgt.body) == "function" then send_source(mesgt)
+    else send_string(mesgt) end
+end
+
+-- set defaul headers
+local function adjust_headers(mesgt)
+    local lower = lower_headers(mesgt.headers)
+    lower["date"] = lower["date"] or
+        os.date("!%a, %d %b %Y %H:%M:%S ") .. (mesgt.zone or ZONE)
+    lower["x-mailer"] = lower["x-mailer"] or socket._VERSION
+    -- this can't be overriden
+    lower["mime-version"] = "1.0"
+    return lower
+end
+
+function message(mesgt)
+    mesgt.headers = adjust_headers(mesgt)
+    -- create and return message source
+    local co = coroutine.create(function() send_message(mesgt) end)
+    return function()
+        local ret, a, b = coroutine.resume(co)
+        if ret then return a, b
+        else return nil, a end
+    end
+end
+
+---------------------------------------------------------------------------
+-- High level SMTP API
+-----------------------------------------------------------------------------
+send = socket.protect(function(mailt)
+    local s = open(mailt.server, mailt.port, mailt.create)
+    local ext = s:greet(mailt.domain)
+    s:auth(mailt.user, mailt.password, ext)
+    s:send(mailt)
+    s:quit()
+    return s:close()
+end)
diff --git a/game/thirdparty/socket/tp.lua b/game/thirdparty/socket/tp.lua
new file mode 100644
index 0000000000000000000000000000000000000000..0683869499f3e89237a1958de2ec217d2dcfc64e
--- /dev/null
+++ b/game/thirdparty/socket/tp.lua
@@ -0,0 +1,123 @@
+-----------------------------------------------------------------------------
+-- Unified SMTP/FTP subsystem
+-- LuaSocket toolkit.
+-- Author: Diego Nehab
+-- RCS ID: $Id: tp.lua,v 1.22 2006/03/14 09:04:15 diego Exp $
+-----------------------------------------------------------------------------
+
+-----------------------------------------------------------------------------
+-- Declare module and import dependencies
+-----------------------------------------------------------------------------
+local base = _G
+local string = require("string")
+local socket = require("socket")
+local ltn12 = require("ltn12")
+module("socket.tp")
+
+-----------------------------------------------------------------------------
+-- Program constants
+-----------------------------------------------------------------------------
+TIMEOUT = 60
+
+-----------------------------------------------------------------------------
+-- Implementation
+-----------------------------------------------------------------------------
+-- gets server reply (works for SMTP and FTP)
+local function get_reply(c)
+    local code, current, sep
+    local line, err = c:receive()
+    local reply = line
+    if err then return nil, err end
+    code, sep = socket.skip(2, string.find(line, "^(%d%d%d)(.?)"))
+    if not code then return nil, "invalid server reply" end
+    if sep == "-" then -- reply is multiline
+        repeat
+            line, err = c:receive()
+            if err then return nil, err end
+            current, sep = socket.skip(2, string.find(line, "^(%d%d%d)(.?)"))
+            reply = reply .. "\n" .. line
+        -- reply ends with same code
+        until code == current and sep == " "
+    end
+    return code, reply
+end
+
+-- metatable for sock object
+local metat = { __index = {} }
+
+function metat.__index:check(ok)
+    local code, reply = get_reply(self.c)
+    if not code then return nil, reply end
+    if base.type(ok) ~= "function" then
+        if base.type(ok) == "table" then
+            for i, v in base.ipairs(ok) do
+                if string.find(code, v) then
+                    return base.tonumber(code), reply
+                end
+            end
+            return nil, reply
+        else
+            if string.find(code, ok) then return base.tonumber(code), reply
+            else return nil, reply end
+        end
+    else return ok(base.tonumber(code), reply) end
+end
+
+function metat.__index:command(cmd, arg)
+    if arg then
+        return self.c:send(cmd .. " " .. arg.. "\r\n")
+    else
+        return self.c:send(cmd .. "\r\n")
+    end
+end
+
+function metat.__index:sink(snk, pat)
+    local chunk, err = c:receive(pat)
+    return snk(chunk, err)
+end
+
+function metat.__index:send(data)
+    return self.c:send(data)
+end
+
+function metat.__index:receive(pat)
+    return self.c:receive(pat)
+end
+
+function metat.__index:getfd()
+    return self.c:getfd()
+end
+
+function metat.__index:dirty()
+    return self.c:dirty()
+end
+
+function metat.__index:getcontrol()
+    return self.c
+end
+
+function metat.__index:source(source, step)
+    local sink = socket.sink("keep-open", self.c)
+    local ret, err = ltn12.pump.all(source, sink, step or ltn12.pump.step)
+    return ret, err
+end
+
+-- closes the underlying c
+function metat.__index:close()
+    self.c:close()
+	return 1
+end
+
+-- connect with server and return c object
+function connect(host, port, timeout, create)
+    local c, e = (create or socket.tcp)()
+    if not c then return nil, e end
+    c:settimeout(timeout or TIMEOUT)
+    local r, e = c:connect(host, port)
+    if not r then
+        c:close()
+        return nil, e
+    end
+    return base.setmetatable({c = c}, metat)
+end
+
diff --git a/game/thirdparty/socket/url.lua b/game/thirdparty/socket/url.lua
new file mode 100644
index 0000000000000000000000000000000000000000..0e31d8af20d362b8843002a5cf9eb1f5caa6e7b0
--- /dev/null
+++ b/game/thirdparty/socket/url.lua
@@ -0,0 +1,297 @@
+-----------------------------------------------------------------------------
+-- URI parsing, composition and relative URL resolution
+-- LuaSocket toolkit.
+-- Author: Diego Nehab
+-- RCS ID: $Id: url.lua,v 1.38 2006/04/03 04:45:42 diego Exp $
+-----------------------------------------------------------------------------
+
+-----------------------------------------------------------------------------
+-- Declare module
+-----------------------------------------------------------------------------
+local string = require("string")
+local base = _G
+local table = require("table")
+module("socket.url")
+
+-----------------------------------------------------------------------------
+-- Module version
+-----------------------------------------------------------------------------
+_VERSION = "URL 1.0.1"
+
+-----------------------------------------------------------------------------
+-- Encodes a string into its escaped hexadecimal representation
+-- Input
+--   s: binary string to be encoded
+-- Returns
+--   escaped representation of string binary
+-----------------------------------------------------------------------------
+function escape(s)
+    return string.gsub(s, "([^A-Za-z0-9_])", function(c)
+        return string.format("%%%02x", string.byte(c))
+    end)
+end
+
+-----------------------------------------------------------------------------
+-- Protects a path segment, to prevent it from interfering with the
+-- url parsing.
+-- Input
+--   s: binary string to be encoded
+-- Returns
+--   escaped representation of string binary
+-----------------------------------------------------------------------------
+local function make_set(t)
+	local s = {}
+	for i,v in base.ipairs(t) do
+		s[t[i]] = 1
+	end
+	return s
+end
+
+-- these are allowed withing a path segment, along with alphanum
+-- other characters must be escaped
+local segment_set = make_set {
+    "-", "_", ".", "!", "~", "*", "'", "(",
+	")", ":", "@", "&", "=", "+", "$", ",",
+}
+
+local function protect_segment(s)
+	return string.gsub(s, "([^A-Za-z0-9_])", function (c)
+		if segment_set[c] then return c
+		else return string.format("%%%02x", string.byte(c)) end
+	end)
+end
+
+-----------------------------------------------------------------------------
+-- Encodes a string into its escaped hexadecimal representation
+-- Input
+--   s: binary string to be encoded
+-- Returns
+--   escaped representation of string binary
+-----------------------------------------------------------------------------
+function unescape(s)
+    return string.gsub(s, "%%(%x%x)", function(hex)
+        return string.char(base.tonumber(hex, 16))
+    end)
+end
+
+-----------------------------------------------------------------------------
+-- Builds a path from a base path and a relative path
+-- Input
+--   base_path
+--   relative_path
+-- Returns
+--   corresponding absolute path
+-----------------------------------------------------------------------------
+local function absolute_path(base_path, relative_path)
+    if string.sub(relative_path, 1, 1) == "/" then return relative_path end
+    local path = string.gsub(base_path, "[^/]*$", "")
+    path = path .. relative_path
+    path = string.gsub(path, "([^/]*%./)", function (s)
+        if s ~= "./" then return s else return "" end
+    end)
+    path = string.gsub(path, "/%.$", "/")
+    local reduced
+    while reduced ~= path do
+        reduced = path
+        path = string.gsub(reduced, "([^/]*/%.%./)", function (s)
+            if s ~= "../../" then return "" else return s end
+        end)
+    end
+    path = string.gsub(reduced, "([^/]*/%.%.)$", function (s)
+        if s ~= "../.." then return "" else return s end
+    end)
+    return path
+end
+
+-----------------------------------------------------------------------------
+-- Parses a url and returns a table with all its parts according to RFC 2396
+-- The following grammar describes the names given to the URL parts
+-- <url> ::= <scheme>://<authority>/<path>;<params>?<query>#<fragment>
+-- <authority> ::= <userinfo>@<host>:<port>
+-- <userinfo> ::= <user>[:<password>]
+-- <path> :: = {<segment>/}<segment>
+-- Input
+--   url: uniform resource locator of request
+--   default: table with default values for each field
+-- Returns
+--   table with the following fields, where RFC naming conventions have
+--   been preserved:
+--     scheme, authority, userinfo, user, password, host, port,
+--     path, params, query, fragment
+-- Obs:
+--   the leading '/' in {/<path>} is considered part of <path>
+-----------------------------------------------------------------------------
+function parse(url, default)
+    -- initialize default parameters
+    local parsed = {}
+    for i,v in base.pairs(default or parsed) do parsed[i] = v end
+    -- empty url is parsed to nil
+    if not url or url == "" then return nil, "invalid url" end
+    -- remove whitespace
+    -- url = string.gsub(url, "%s", "")
+    -- get fragment
+    url = string.gsub(url, "#(.*)$", function(f)
+        parsed.fragment = f
+        return ""
+    end)
+    -- get scheme
+    url = string.gsub(url, "^([%w][%w%+%-%.]*)%:",
+        function(s) parsed.scheme = s; return "" end)
+    -- get authority
+    url = string.gsub(url, "^//([^/]*)", function(n)
+        parsed.authority = n
+        return ""
+    end)
+    -- get query stringing
+    url = string.gsub(url, "%?(.*)", function(q)
+        parsed.query = q
+        return ""
+    end)
+    -- get params
+    url = string.gsub(url, "%;(.*)", function(p)
+        parsed.params = p
+        return ""
+    end)
+    -- path is whatever was left
+    if url ~= "" then parsed.path = url end
+    local authority = parsed.authority
+    if not authority then return parsed end
+    authority = string.gsub(authority,"^([^@]*)@",
+        function(u) parsed.userinfo = u; return "" end)
+    authority = string.gsub(authority, ":([^:]*)$",
+        function(p) parsed.port = p; return "" end)
+    if authority ~= "" then parsed.host = authority end
+    local userinfo = parsed.userinfo
+    if not userinfo then return parsed end
+    userinfo = string.gsub(userinfo, ":([^:]*)$",
+        function(p) parsed.password = p; return "" end)
+    parsed.user = userinfo
+    return parsed
+end
+
+-----------------------------------------------------------------------------
+-- Rebuilds a parsed URL from its components.
+-- Components are protected if any reserved or unallowed characters are found
+-- Input
+--   parsed: parsed URL, as returned by parse
+-- Returns
+--   a stringing with the corresponding URL
+-----------------------------------------------------------------------------
+function build(parsed)
+    local ppath = parse_path(parsed.path or "")
+    local url = build_path(ppath)
+    if parsed.params then url = url .. ";" .. parsed.params end
+    if parsed.query then url = url .. "?" .. parsed.query end
+	local authority = parsed.authority
+	if parsed.host then
+		authority = parsed.host
+		if parsed.port then authority = authority .. ":" .. parsed.port end
+		local userinfo = parsed.userinfo
+		if parsed.user then
+			userinfo = parsed.user
+			if parsed.password then
+				userinfo = userinfo .. ":" .. parsed.password
+			end
+		end
+		if userinfo then authority = userinfo .. "@" .. authority end
+	end
+    if authority then url = "//" .. authority .. url end
+    if parsed.scheme then url = parsed.scheme .. ":" .. url end
+    if parsed.fragment then url = url .. "#" .. parsed.fragment end
+    -- url = string.gsub(url, "%s", "")
+    return url
+end
+
+-----------------------------------------------------------------------------
+-- Builds a absolute URL from a base and a relative URL according to RFC 2396
+-- Input
+--   base_url
+--   relative_url
+-- Returns
+--   corresponding absolute url
+-----------------------------------------------------------------------------
+function absolute(base_url, relative_url)
+    if base.type(base_url) == "table" then
+        base_parsed = base_url
+        base_url = build(base_parsed)
+    else
+        base_parsed = parse(base_url)
+    end
+    local relative_parsed = parse(relative_url)
+    if not base_parsed then return relative_url
+    elseif not relative_parsed then return base_url
+    elseif relative_parsed.scheme then return relative_url
+    else
+        relative_parsed.scheme = base_parsed.scheme
+        if not relative_parsed.authority then
+            relative_parsed.authority = base_parsed.authority
+            if not relative_parsed.path then
+                relative_parsed.path = base_parsed.path
+                if not relative_parsed.params then
+                    relative_parsed.params = base_parsed.params
+                    if not relative_parsed.query then
+                        relative_parsed.query = base_parsed.query
+                    end
+                end
+            else    
+                relative_parsed.path = absolute_path(base_parsed.path or "",
+                    relative_parsed.path)
+            end
+        end
+        return build(relative_parsed)
+    end
+end
+
+-----------------------------------------------------------------------------
+-- Breaks a path into its segments, unescaping the segments
+-- Input
+--   path
+-- Returns
+--   segment: a table with one entry per segment
+-----------------------------------------------------------------------------
+function parse_path(path)
+	local parsed = {}
+	path = path or ""
+	--path = string.gsub(path, "%s", "")
+	string.gsub(path, "([^/]+)", function (s) table.insert(parsed, s) end)
+	for i = 1, table.getn(parsed) do
+		parsed[i] = unescape(parsed[i])
+	end
+	if string.sub(path, 1, 1) == "/" then parsed.is_absolute = 1 end
+	if string.sub(path, -1, -1) == "/" then parsed.is_directory = 1 end
+	return parsed
+end
+
+-----------------------------------------------------------------------------
+-- Builds a path component from its segments, escaping protected characters.
+-- Input
+--   parsed: path segments
+--   unsafe: if true, segments are not protected before path is built
+-- Returns
+--   path: corresponding path stringing
+-----------------------------------------------------------------------------
+function build_path(parsed, unsafe)
+	local path = ""
+	local n = table.getn(parsed)
+	if unsafe then
+		for i = 1, n-1 do
+			path = path .. parsed[i]
+			path = path .. "/"
+		end
+		if n > 0 then
+			path = path .. parsed[n]
+			if parsed.is_directory then path = path .. "/" end
+		end
+	else
+		for i = 1, n-1 do
+			path = path .. protect_segment(parsed[i])
+			path = path .. "/"
+		end
+		if n > 0 then
+			path = path .. protect_segment(parsed[n])
+			if parsed.is_directory then path = path .. "/" end
+		end
+	end
+	if parsed.is_absolute then path = "/" .. path end
+	return path
+end
diff --git a/premake4.lua b/premake4.lua
index 3f529164a28c314ca90bee9675cdbc7fb9d42a47..852a9b117156060f6f574d8a29b3012ab1ddff16 100644
--- a/premake4.lua
+++ b/premake4.lua
@@ -5,6 +5,7 @@ solution "TEngine"
 	includedirs {
 		"src",
 		"src/lua",
+		"src/luasocket",
 		"src/fov",
 		"src/physfs",
 		"src/physfs/zlib123",
@@ -32,7 +33,7 @@ project "TEngine"
 	language "C"
 	targetname "t-engine"
 	files { "src/*.c", }
-	links { "physfs", "lua", "fov", "sge2d" }
+	links { "physfs", "lua", "fov", "sge2d", "luasocket" }
 
 configuration "macosx"
 	linkoptions { "mac/SDLmain.m", "-framework SDL", "-framework SDL_image", "-framework SDL_ttf", "-framework SDL_mixer", "-framework Cocoa" }
@@ -64,6 +65,44 @@ project "lua"
 
 	files { "src/lua/*.c", }
 
+project "luasocket"
+	kind "StaticLib"
+	language "C"
+	targetname "luasocket"
+
+	configuration "not windows"
+		files {
+			"src/luasocket/auxiliar.c",
+			"src/luasocket/buffer.c",
+			"src/luasocket/except.c",
+			"src/luasocket/inet.c",
+			"src/luasocket/io.c",
+			"src/luasocket/luasocket.c",
+			"src/luasocket/options.c",
+			"src/luasocket/select.c",
+			"src/luasocket/tcp.c",
+			"src/luasocket/timeout.c",
+			"src/luasocket/udp.c",
+			"src/luasocket/usocket.c",
+			"src/luasocket/mime.c",
+		}
+	configuration "windows"
+		files {
+			"src/luasocket/auxiliar.c",
+			"src/luasocket/buffer.c",
+			"src/luasocket/except.c",
+			"src/luasocket/inet.c",
+			"src/luasocket/io.c",
+			"src/luasocket/luasocket.c",
+			"src/luasocket/options.c",
+			"src/luasocket/select.c",
+			"src/luasocket/tcp.c",
+			"src/luasocket/timeout.c",
+			"src/luasocket/udp.c",
+			"src/luasocket/wsocket.c",
+			"src/luasocket/mime.c",
+		}
+
 project "fov"
 	kind "StaticLib"
 	language "C"
diff --git a/src/lua/ldblib.c b/src/lua/ldblib.c
index 67de1222a948ca2e20e078d35e2e497bf833a986..380ab75a1e7d7e7aa501b533951000327726b35a 100644
--- a/src/lua/ldblib.c
+++ b/src/lua/ldblib.c
@@ -138,7 +138,7 @@ static int db_getinfo (lua_State *L) {
     treatstackoption(L, L1, "func");
   return 1;  /* return table */
 }
-    
+
 
 static int db_getlocal (lua_State *L) {
   int arg;
@@ -318,7 +318,7 @@ static int db_debug (lua_State *L) {
 #define LEVELS1	12	/* size of the first part of the stack */
 #define LEVELS2	10	/* size of the second part of the stack */
 
-static int db_errorfb (lua_State *L) {
+int db_errorfb (lua_State *L) {
   int level;
   int firstpart = 1;  /* still before eventual `...' */
   int arg;
diff --git a/src/luasocket/auxiliar.c b/src/luasocket/auxiliar.c
new file mode 100644
index 0000000000000000000000000000000000000000..9514970119ff8e8be7540ceb768639173f7b1fcc
--- /dev/null
+++ b/src/luasocket/auxiliar.c
@@ -0,0 +1,149 @@
+/*=========================================================================*\
+* Auxiliar routines for class hierarchy manipulation
+* LuaSocket toolkit
+*
+* RCS ID: $Id: auxiliar.c,v 1.14 2005/10/07 04:40:59 diego Exp $
+\*=========================================================================*/
+#include <string.h>
+#include <stdio.h>
+
+#include "auxiliar.h"
+
+/*=========================================================================*\
+* Exported functions
+\*=========================================================================*/
+/*-------------------------------------------------------------------------*\
+* Initializes the module
+\*-------------------------------------------------------------------------*/
+int auxiliar_open(lua_State *L) {
+    (void) L;
+    return 0;
+}
+
+/*-------------------------------------------------------------------------*\
+* Creates a new class with given methods
+* Methods whose names start with __ are passed directly to the metatable.
+\*-------------------------------------------------------------------------*/
+void auxiliar_newclass(lua_State *L, const char *classname, luaL_reg *func) {
+    luaL_newmetatable(L, classname); /* mt */
+    /* create __index table to place methods */
+    lua_pushstring(L, "__index");    /* mt,"__index" */
+    lua_newtable(L);                 /* mt,"__index",it */ 
+    /* put class name into class metatable */
+    lua_pushstring(L, "class");      /* mt,"__index",it,"class" */
+    lua_pushstring(L, classname);    /* mt,"__index",it,"class",classname */
+    lua_rawset(L, -3);               /* mt,"__index",it */
+    /* pass all methods that start with _ to the metatable, and all others
+     * to the index table */
+    for (; func->name; func++) {     /* mt,"__index",it */
+        lua_pushstring(L, func->name);
+        lua_pushcfunction(L, func->func);
+        lua_rawset(L, func->name[0] == '_' ? -5: -3);
+    }
+    lua_rawset(L, -3);               /* mt */
+    lua_pop(L, 1);
+}
+
+/*-------------------------------------------------------------------------*\
+* Prints the value of a class in a nice way
+\*-------------------------------------------------------------------------*/
+int auxiliar_tostring(lua_State *L) {
+    char buf[32];
+    if (!lua_getmetatable(L, 1)) goto error;
+    lua_pushstring(L, "__index");
+    lua_gettable(L, -2);
+    if (!lua_istable(L, -1)) goto error;
+    lua_pushstring(L, "class");
+    lua_gettable(L, -2);
+    if (!lua_isstring(L, -1)) goto error;
+    sprintf(buf, "%p", lua_touserdata(L, 1));
+    lua_pushfstring(L, "%s: %s", lua_tostring(L, -1), buf);
+    return 1;
+error:
+    lua_pushstring(L, "invalid object passed to 'auxiliar.c:__tostring'");
+    lua_error(L);
+    return 1;
+}
+
+/*-------------------------------------------------------------------------*\
+* Insert class into group
+\*-------------------------------------------------------------------------*/
+void auxiliar_add2group(lua_State *L, const char *classname, const char *groupname) {
+    luaL_getmetatable(L, classname);
+    lua_pushstring(L, groupname);
+    lua_pushboolean(L, 1);
+    lua_rawset(L, -3);
+    lua_pop(L, 1);
+}
+
+/*-------------------------------------------------------------------------*\
+* Make sure argument is a boolean
+\*-------------------------------------------------------------------------*/
+int auxiliar_checkboolean(lua_State *L, int objidx) {
+    if (!lua_isboolean(L, objidx))
+        luaL_typerror(L, objidx, lua_typename(L, LUA_TBOOLEAN));
+    return lua_toboolean(L, objidx);
+}
+
+/*-------------------------------------------------------------------------*\
+* Return userdata pointer if object belongs to a given class, abort with 
+* error otherwise
+\*-------------------------------------------------------------------------*/
+void *auxiliar_checkclass(lua_State *L, const char *classname, int objidx) {
+    void *data = auxiliar_getclassudata(L, classname, objidx);
+    if (!data) {
+        char msg[45];
+        sprintf(msg, "%.35s expected", classname);
+        luaL_argerror(L, objidx, msg);
+    }
+    return data;
+}
+
+/*-------------------------------------------------------------------------*\
+* Return userdata pointer if object belongs to a given group, abort with 
+* error otherwise
+\*-------------------------------------------------------------------------*/
+void *auxiliar_checkgroup(lua_State *L, const char *groupname, int objidx) {
+    void *data = auxiliar_getgroupudata(L, groupname, objidx);
+    if (!data) {
+        char msg[45];
+        sprintf(msg, "%.35s expected", groupname);
+        luaL_argerror(L, objidx, msg);
+    }
+    return data;
+}
+
+/*-------------------------------------------------------------------------*\
+* Set object class
+\*-------------------------------------------------------------------------*/
+void auxiliar_setclass(lua_State *L, const char *classname, int objidx) {
+    luaL_getmetatable(L, classname);
+    if (objidx < 0) objidx--;
+    lua_setmetatable(L, objidx);
+}
+
+/*-------------------------------------------------------------------------*\
+* Get a userdata pointer if object belongs to a given group. Return NULL 
+* otherwise
+\*-------------------------------------------------------------------------*/
+void *auxiliar_getgroupudata(lua_State *L, const char *groupname, int objidx) {
+    if (!lua_getmetatable(L, objidx))
+        return NULL;
+    lua_pushstring(L, groupname);
+    lua_rawget(L, -2);
+    if (lua_isnil(L, -1)) {
+        lua_pop(L, 2);
+        return NULL;
+    } else {
+        lua_pop(L, 2);
+        return lua_touserdata(L, objidx);
+    }
+}
+
+/*-------------------------------------------------------------------------*\
+* Get a userdata pointer if object belongs to a given class. Return NULL 
+* otherwise
+\*-------------------------------------------------------------------------*/
+void *auxiliar_getclassudata(lua_State *L, const char *classname, int objidx) {
+    return luaL_checkudata(L, objidx, classname);
+}
diff --git a/src/luasocket/auxiliar.h b/src/luasocket/auxiliar.h
new file mode 100644
index 0000000000000000000000000000000000000000..18b849554ff3c6a99ecbd6cea21b1fa72e1fad7a
--- /dev/null
+++ b/src/luasocket/auxiliar.h
@@ -0,0 +1,48 @@
+#ifndef AUXILIAR_H
+#define AUXILIAR_H
+/*=========================================================================*\
+* Auxiliar routines for class hierarchy manipulation
+* LuaSocket toolkit (but completely independent of other LuaSocket modules)
+*
+* A LuaSocket class is a name associated with Lua metatables. A LuaSocket 
+* group is a name associated with a class. A class can belong to any number 
+* of groups. This module provides the functionality to:
+*
+*   - create new classes 
+*   - add classes to groups 
+*   - set the class of objects
+*   - check if an object belongs to a given class or group
+*   - get the userdata associated to objects
+*   - print objects in a pretty way
+*
+* LuaSocket class names follow the convention <module>{<class>}. Modules
+* can define any number of classes and groups. The module tcp.c, for
+* example, defines the classes tcp{master}, tcp{client} and tcp{server} and
+* the groups tcp{client,server} and tcp{any}. Module functions can then
+* perform type-checking on their arguments by either class or group.
+*
+* LuaSocket metatables define the __index metamethod as being a table. This
+* table has one field for each method supported by the class, and a field
+* "class" with the class name.
+*
+* The mapping from class name to the corresponding metatable and the
+* reverse mapping are done using lauxlib. 
+*
+* RCS ID: $Id: auxiliar.h,v 1.9 2005/10/07 04:40:59 diego Exp $
+\*=========================================================================*/
+
+#include "lua.h"
+#include "lauxlib.h"
+
+int auxiliar_open(lua_State *L);
+void auxiliar_newclass(lua_State *L, const char *classname, luaL_reg *func);
+void auxiliar_add2group(lua_State *L, const char *classname, const char *group);
+void auxiliar_setclass(lua_State *L, const char *classname, int objidx);
+void *auxiliar_checkclass(lua_State *L, const char *classname, int objidx);
+void *auxiliar_checkgroup(lua_State *L, const char *groupname, int objidx);
+void *auxiliar_getclassudata(lua_State *L, const char *groupname, int objidx);
+void *auxiliar_getgroupudata(lua_State *L, const char *groupname, int objidx);
+int auxiliar_checkboolean(lua_State *L, int objidx);
+int auxiliar_tostring(lua_State *L);
+
+#endif /* AUXILIAR_H */
diff --git a/src/luasocket/buffer.c b/src/luasocket/buffer.c
new file mode 100644
index 0000000000000000000000000000000000000000..73f4ffa85e6136682f9a6000f83cac62b17d588d
--- /dev/null
+++ b/src/luasocket/buffer.c
@@ -0,0 +1,268 @@
+/*=========================================================================*\
+* Input/Output interface for Lua programs
+* LuaSocket toolkit
+*
+* RCS ID: $Id: buffer.c,v 1.28 2007/06/11 23:44:54 diego Exp $
+\*=========================================================================*/
+#include "lua.h"
+#include "lauxlib.h"
+
+#include "buffer.h"
+
+/*=========================================================================*\
+* Internal function prototypes
+\*=========================================================================*/
+static int recvraw(p_buffer buf, size_t wanted, luaL_Buffer *b);
+static int recvline(p_buffer buf, luaL_Buffer *b);
+static int recvall(p_buffer buf, luaL_Buffer *b);
+static int buffer_get(p_buffer buf, const char **data, size_t *count);
+static void buffer_skip(p_buffer buf, size_t count);
+static int sendraw(p_buffer buf, const char *data, size_t count, size_t *sent);
+
+/* min and max macros */
+#ifndef MIN
+#define MIN(x, y) ((x) < (y) ? x : y)
+#endif
+#ifndef MAX
+#define MAX(x, y) ((x) > (y) ? x : y)
+#endif
+
+/*=========================================================================*\
+* Exported functions
+\*=========================================================================*/
+/*-------------------------------------------------------------------------*\
+* Initializes module
+\*-------------------------------------------------------------------------*/
+int buffer_open(lua_State *L) {
+    (void) L;
+    return 0;
+}
+
+/*-------------------------------------------------------------------------*\
+* Initializes C structure 
+\*-------------------------------------------------------------------------*/
+void buffer_init(p_buffer buf, p_io io, p_timeout tm) {
+	buf->first = buf->last = 0;
+    buf->io = io;
+    buf->tm = tm;
+    buf->received = buf->sent = 0;
+    buf->birthday = timeout_gettime();
+}
+
+/*-------------------------------------------------------------------------*\
+* object:getstats() interface
+\*-------------------------------------------------------------------------*/
+int buffer_meth_getstats(lua_State *L, p_buffer buf) {
+    lua_pushnumber(L, buf->received);
+    lua_pushnumber(L, buf->sent);
+    lua_pushnumber(L, timeout_gettime() - buf->birthday);
+    return 3;
+}
+
+/*-------------------------------------------------------------------------*\
+* object:setstats() interface
+\*-------------------------------------------------------------------------*/
+int buffer_meth_setstats(lua_State *L, p_buffer buf) {
+    buf->received = (long) luaL_optnumber(L, 2, buf->received); 
+    buf->sent = (long) luaL_optnumber(L, 3, buf->sent); 
+    if (lua_isnumber(L, 4)) buf->birthday = timeout_gettime() - lua_tonumber(L, 4);
+    lua_pushnumber(L, 1);
+    return 1;
+}
+
+/*-------------------------------------------------------------------------*\
+* object:send() interface
+\*-------------------------------------------------------------------------*/
+int buffer_meth_send(lua_State *L, p_buffer buf) {
+    int top = lua_gettop(L);
+    int err = IO_DONE;
+    size_t size = 0, sent = 0;
+    const char *data = luaL_checklstring(L, 2, &size);
+    long start = (long) luaL_optnumber(L, 3, 1);
+    long end = (long) luaL_optnumber(L, 4, -1);
+    p_timeout tm = timeout_markstart(buf->tm);
+    if (start < 0) start = (long) (size+start+1);
+    if (end < 0) end = (long) (size+end+1);
+    if (start < 1) start = (long) 1;
+    if (end > (long) size) end = (long) size;
+    if (start <= end) err = sendraw(buf, data+start-1, end-start+1, &sent);
+    /* check if there was an error */
+    if (err != IO_DONE) {
+        lua_pushnil(L);
+        lua_pushstring(L, buf->io->error(buf->io->ctx, err)); 
+        lua_pushnumber(L, sent+start-1);
+    } else {
+        lua_pushnumber(L, sent+start-1);
+        lua_pushnil(L);
+        lua_pushnil(L);
+    }
+#ifdef LUASOCKET_DEBUG
+    /* push time elapsed during operation as the last return value */
+    lua_pushnumber(L, timeout_gettime() - timeout_getstart(tm));
+#endif
+    return lua_gettop(L) - top;
+}
+
+/*-------------------------------------------------------------------------*\
+* object:receive() interface
+\*-------------------------------------------------------------------------*/
+int buffer_meth_receive(lua_State *L, p_buffer buf) {
+    int err = IO_DONE, top = lua_gettop(L);
+    luaL_Buffer b;
+    size_t size;
+    const char *part = luaL_optlstring(L, 3, "", &size);
+    p_timeout tm = timeout_markstart(buf->tm);
+    /* initialize buffer with optional extra prefix 
+     * (useful for concatenating previous partial results) */
+    luaL_buffinit(L, &b);
+    luaL_addlstring(&b, part, size);
+    /* receive new patterns */
+    if (!lua_isnumber(L, 2)) {
+        const char *p= luaL_optstring(L, 2, "*l");
+        if (p[0] == '*' && p[1] == 'l') err = recvline(buf, &b);
+        else if (p[0] == '*' && p[1] == 'a') err = recvall(buf, &b); 
+        else luaL_argcheck(L, 0, 2, "invalid receive pattern");
+        /* get a fixed number of bytes (minus what was already partially 
+         * received) */
+    } else err = recvraw(buf, (size_t) lua_tonumber(L, 2)-size, &b);
+    /* check if there was an error */
+    if (err != IO_DONE) {
+        /* we can't push anyting in the stack before pushing the
+         * contents of the buffer. this is the reason for the complication */
+        luaL_pushresult(&b);
+        lua_pushstring(L, buf->io->error(buf->io->ctx, err)); 
+        lua_pushvalue(L, -2); 
+        lua_pushnil(L);
+        lua_replace(L, -4);
+    } else {
+        luaL_pushresult(&b);
+        lua_pushnil(L);
+        lua_pushnil(L);
+    }
+#ifdef LUASOCKET_DEBUG
+    /* push time elapsed during operation as the last return value */
+    lua_pushnumber(L, timeout_gettime() - timeout_getstart(tm));
+#endif
+    return lua_gettop(L) - top;
+}
+
+/*-------------------------------------------------------------------------*\
+* Determines if there is any data in the read buffer
+\*-------------------------------------------------------------------------*/
+int buffer_isempty(p_buffer buf) {
+    return buf->first >= buf->last;
+}
+
+/*=========================================================================*\
+* Internal functions
+\*=========================================================================*/
+/*-------------------------------------------------------------------------*\
+* Sends a block of data (unbuffered)
+\*-------------------------------------------------------------------------*/
+#define STEPSIZE 8192
+static int sendraw(p_buffer buf, const char *data, size_t count, size_t *sent) {
+    p_io io = buf->io;
+    p_timeout tm = buf->tm;
+    size_t total = 0;
+    int err = IO_DONE;
+    while (total < count && err == IO_DONE) {
+        size_t done;
+        size_t step = (count-total <= STEPSIZE)? count-total: STEPSIZE;
+        err = io->send(io->ctx, data+total, step, &done, tm);
+        total += done;
+    }
+    *sent = total;
+    buf->sent += total;
+    return err;
+}
+
+/*-------------------------------------------------------------------------*\
+* Reads a fixed number of bytes (buffered)
+\*-------------------------------------------------------------------------*/
+static int recvraw(p_buffer buf, size_t wanted, luaL_Buffer *b) {
+    int err = IO_DONE;
+    size_t total = 0;
+    while (err == IO_DONE) {
+        size_t count; const char *data;
+        err = buffer_get(buf, &data, &count);
+        count = MIN(count, wanted - total);
+        luaL_addlstring(b, data, count);
+        buffer_skip(buf, count);
+        total += count;
+        if (total >= wanted) break;
+    }
+    return err;
+}
+
+/*-------------------------------------------------------------------------*\
+* Reads everything until the connection is closed (buffered)
+\*-------------------------------------------------------------------------*/
+static int recvall(p_buffer buf, luaL_Buffer *b) {
+    int err = IO_DONE;
+    size_t total = 0;
+    while (err == IO_DONE) {
+        const char *data; size_t count;
+        err = buffer_get(buf, &data, &count);
+        total += count;
+        luaL_addlstring(b, data, count);
+        buffer_skip(buf, count);
+    }
+    if (err == IO_CLOSED) {
+        if (total > 0) return IO_DONE;
+        else return IO_CLOSED;
+    } else return err;
+}
+
+/*-------------------------------------------------------------------------*\
+* Reads a line terminated by a CR LF pair or just by a LF. The CR and LF 
+* are not returned by the function and are discarded from the buffer
+\*-------------------------------------------------------------------------*/
+static int recvline(p_buffer buf, luaL_Buffer *b) {
+    int err = IO_DONE;
+    while (err == IO_DONE) {
+        size_t count, pos; const char *data;
+        err = buffer_get(buf, &data, &count);
+        pos = 0;
+        while (pos < count && data[pos] != '\n') {
+            /* we ignore all \r's */
+            if (data[pos] != '\r') luaL_putchar(b, data[pos]);
+            pos++;
+        }
+        if (pos < count) { /* found '\n' */
+            buffer_skip(buf, pos+1); /* skip '\n' too */
+            break; /* we are done */
+        } else /* reached the end of the buffer */
+            buffer_skip(buf, pos);
+    }
+    return err;
+}
+
+/*-------------------------------------------------------------------------*\
+* Skips a given number of bytes from read buffer. No data is read from the
+* transport layer
+\*-------------------------------------------------------------------------*/
+static void buffer_skip(p_buffer buf, size_t count) {
+    buf->received += count;
+    buf->first += count;
+    if (buffer_isempty(buf)) 
+        buf->first = buf->last = 0;
+}
+
+/*-------------------------------------------------------------------------*\
+* Return any data available in buffer, or get more data from transport layer
+* if buffer is empty
+\*-------------------------------------------------------------------------*/
+static int buffer_get(p_buffer buf, const char **data, size_t *count) {
+    int err = IO_DONE;
+    p_io io = buf->io;
+    p_timeout tm = buf->tm;
+    if (buffer_isempty(buf)) {
+        size_t got;
+        err = io->recv(io->ctx, buf->data, BUF_SIZE, &got, tm);
+        buf->first = 0;
+        buf->last = got;
+    }
+    *count = buf->last - buf->first;
+    *data = buf->data + buf->first;
+    return err;
+}
diff --git a/src/luasocket/buffer.h b/src/luasocket/buffer.h
new file mode 100644
index 0000000000000000000000000000000000000000..baf93caa031890b6f23bf9080a00acdc13d07b07
--- /dev/null
+++ b/src/luasocket/buffer.h
@@ -0,0 +1,47 @@
+#ifndef BUF_H
+#define BUF_H 
+/*=========================================================================*\
+* Input/Output interface for Lua programs
+* LuaSocket toolkit
+*
+* Line patterns require buffering. Reading one character at a time involves
+* too many system calls and is very slow. This module implements the
+* LuaSocket interface for input/output on connected objects, as seen by 
+* Lua programs. 
+*
+* Input is buffered. Output is *not* buffered because there was no simple
+* way of making sure the buffered output data would ever be sent.
+*
+* The module is built on top of the I/O abstraction defined in io.h and the
+* timeout management is done with the timeout.h interface.
+*
+* RCS ID: $Id: buffer.h,v 1.12 2005/10/07 04:40:59 diego Exp $
+\*=========================================================================*/
+#include "lua.h"
+
+#include "io.h"
+#include "timeout.h"
+
+/* buffer size in bytes */
+#define BUF_SIZE 8192
+
+/* buffer control structure */
+typedef struct t_buffer_ {
+    double birthday;        /* throttle support info: creation time, */
+    size_t sent, received;  /* bytes sent, and bytes received */
+    p_io io;                /* IO driver used for this buffer */
+    p_timeout tm;           /* timeout management for this buffer */
+	size_t first, last;     /* index of first and last bytes of stored data */
+	char data[BUF_SIZE];    /* storage space for buffer data */
+} t_buffer;
+typedef t_buffer *p_buffer;
+
+int buffer_open(lua_State *L);
+void buffer_init(p_buffer buf, p_io io, p_timeout tm);
+int buffer_meth_send(lua_State *L, p_buffer buf);
+int buffer_meth_receive(lua_State *L, p_buffer buf);
+int buffer_meth_getstats(lua_State *L, p_buffer buf);
+int buffer_meth_setstats(lua_State *L, p_buffer buf);
+int buffer_isempty(p_buffer buf);
+
+#endif /* BUF_H */
diff --git a/src/luasocket/except.c b/src/luasocket/except.c
new file mode 100644
index 0000000000000000000000000000000000000000..5faa5be0039467f19cd8a93fc3f84f47d3854307
--- /dev/null
+++ b/src/luasocket/except.c
@@ -0,0 +1,99 @@
+/*=========================================================================*\
+* Simple exception support
+* LuaSocket toolkit
+*
+* RCS ID: $Id: except.c,v 1.8 2005/09/29 06:11:41 diego Exp $
+\*=========================================================================*/
+#include <stdio.h>
+
+#include "lua.h"
+#include "lauxlib.h"
+
+#include "except.h"
+
+/*=========================================================================*\
+* Internal function prototypes.
+\*=========================================================================*/
+static int global_protect(lua_State *L);
+static int global_newtry(lua_State *L);
+static int protected_(lua_State *L);
+static int finalize(lua_State *L);
+static int do_nothing(lua_State *L);
+
+/* except functions */
+static luaL_reg func[] = {
+    {"newtry",    global_newtry},
+    {"protect",   global_protect},
+    {NULL,        NULL}
+};
+
+/*-------------------------------------------------------------------------*\
+* Try factory
+\*-------------------------------------------------------------------------*/
+static void wrap(lua_State *L) {
+    lua_newtable(L);
+    lua_pushnumber(L, 1);
+    lua_pushvalue(L, -3);
+    lua_settable(L, -3);
+    lua_insert(L, -2);
+    lua_pop(L, 1);
+}
+
+static int finalize(lua_State *L) {
+    if (!lua_toboolean(L, 1)) {
+        lua_pushvalue(L, lua_upvalueindex(1));
+        lua_pcall(L, 0, 0, 0);
+        lua_settop(L, 2);
+        wrap(L);
+        lua_error(L);
+        return 0;
+    } else return lua_gettop(L);
+}
+
+static int do_nothing(lua_State *L) { 
+    (void) L;
+    return 0; 
+}
+
+static int global_newtry(lua_State *L) {
+    lua_settop(L, 1);
+    if (lua_isnil(L, 1)) lua_pushcfunction(L, do_nothing);
+    lua_pushcclosure(L, finalize, 1);
+    return 1;
+}
+
+/*-------------------------------------------------------------------------*\
+* Protect factory
+\*-------------------------------------------------------------------------*/
+static int unwrap(lua_State *L) {
+    if (lua_istable(L, -1)) {
+        lua_pushnumber(L, 1);
+        lua_gettable(L, -2);
+        lua_pushnil(L);
+        lua_insert(L, -2);
+        return 1;
+    } else return 0;
+}
+
+static int protected_(lua_State *L) {
+    lua_pushvalue(L, lua_upvalueindex(1));
+    lua_insert(L, 1);
+    if (lua_pcall(L, lua_gettop(L) - 1, LUA_MULTRET, 0) != 0) {
+        if (unwrap(L)) return 2;
+        else lua_error(L);
+        return 0;
+    } else return lua_gettop(L);
+}
+
+static int global_protect(lua_State *L) {
+    lua_pushcclosure(L, protected_, 1);
+    return 1;
+}
+
+/*-------------------------------------------------------------------------*\
+* Init module
+\*-------------------------------------------------------------------------*/
+int except_open(lua_State *L) {
+    luaL_openlib(L, NULL, func, 0);
+    return 0;
+}
diff --git a/src/luasocket/except.h b/src/luasocket/except.h
new file mode 100644
index 0000000000000000000000000000000000000000..81efb29be53838307d107313e95151fc2f8bc8ba
--- /dev/null
+++ b/src/luasocket/except.h
@@ -0,0 +1,35 @@
+#ifndef EXCEPT_H
+#define EXCEPT_H
+/*=========================================================================*\
+* Exception control
+* LuaSocket toolkit (but completely independent from other modules)
+*
+* This provides support for simple exceptions in Lua. During the
+* development of the HTTP/FTP/SMTP support, it became aparent that
+* error checking was taking a substantial amount of the coding. These
+* function greatly simplify the task of checking errors.
+*
+* The main idea is that functions should return nil as its first return
+* value when it finds an error, and return an error message (or value)
+* following nil. In case of success, as long as the first value is not nil,
+* the other values don't matter.
+*
+* The idea is to nest function calls with the "try" function. This function
+* checks the first value, and calls "error" on the second if the first is
+* nil. Otherwise, it returns all values it received. 
+*
+* The protect function returns a new function that behaves exactly like the
+* function it receives, but the new function doesn't throw exceptions: it
+* returns nil followed by the error message instead.
+*
+* With these two function, it's easy to write functions that throw
+* exceptions on error, but that don't interrupt the user script. 
+*
+* RCS ID: $Id: except.h,v 1.2 2005/09/29 06:11:41 diego Exp $
+\*=========================================================================*/
+
+#include "lua.h"
+
+int except_open(lua_State *L);
+
+#endif
diff --git a/src/luasocket/inet.c b/src/luasocket/inet.c
new file mode 100644
index 0000000000000000000000000000000000000000..f2cddeeab3d1d60e87834fc570b80ebd1969a1d5
--- /dev/null
+++ b/src/luasocket/inet.c
@@ -0,0 +1,281 @@
+/*=========================================================================*\
+* Internet domain functions
+* LuaSocket toolkit
+*
+* RCS ID: $Id: inet.c,v 1.28 2005/10/07 04:40:59 diego Exp $
+\*=========================================================================*/
+#include <stdio.h>
+#include <string.h>
+
+#include "lua.h"
+#include "lauxlib.h"
+
+#include "inet.h"
+
+/*=========================================================================*\
+* Internal function prototypes.
+\*=========================================================================*/
+static int inet_global_toip(lua_State *L);
+static int inet_global_tohostname(lua_State *L);
+static void inet_pushresolved(lua_State *L, struct hostent *hp);
+static int inet_global_gethostname(lua_State *L);
+
+/* DNS functions */
+static luaL_reg func[] = {
+    { "toip", inet_global_toip },
+    { "tohostname", inet_global_tohostname },
+    { "gethostname", inet_global_gethostname},
+    { NULL, NULL}
+};
+
+/*=========================================================================*\
+* Exported functions
+\*=========================================================================*/
+/*-------------------------------------------------------------------------*\
+* Initializes module
+\*-------------------------------------------------------------------------*/
+int inet_open(lua_State *L)
+{
+    lua_pushstring(L, "dns");
+    lua_newtable(L);
+    luaL_openlib(L, NULL, func, 0);
+    lua_settable(L, -3);
+    return 0;
+}
+
+/*=========================================================================*\
+* Global Lua functions
+\*=========================================================================*/
+/*-------------------------------------------------------------------------*\
+* Returns all information provided by the resolver given a host name
+* or ip address
+\*-------------------------------------------------------------------------*/
+static int inet_gethost(const char *address, struct hostent **hp) {
+    struct in_addr addr;
+    if (inet_aton(address, &addr))
+        return socket_gethostbyaddr((char *) &addr, sizeof(addr), hp);
+    else 
+        return socket_gethostbyname(address, hp);
+}
+
+/*-------------------------------------------------------------------------*\
+* Returns all information provided by the resolver given a host name
+* or ip address
+\*-------------------------------------------------------------------------*/
+static int inet_global_tohostname(lua_State *L) {
+    const char *address = luaL_checkstring(L, 1);
+    struct hostent *hp = NULL; 
+    int err = inet_gethost(address, &hp);
+    if (err != IO_DONE) {
+        lua_pushnil(L);
+        lua_pushstring(L, socket_hoststrerror(err));
+        return 2;
+    }
+    lua_pushstring(L, hp->h_name);
+    inet_pushresolved(L, hp);
+    return 2;
+}
+
+/*-------------------------------------------------------------------------*\
+* Returns all information provided by the resolver given a host name
+* or ip address
+\*-------------------------------------------------------------------------*/
+static int inet_global_toip(lua_State *L)
+{
+    const char *address = luaL_checkstring(L, 1);
+    struct hostent *hp = NULL; 
+    int err = inet_gethost(address, &hp);
+    if (err != IO_DONE) {
+        lua_pushnil(L);
+        lua_pushstring(L, socket_hoststrerror(err));
+        return 2;
+    }
+    lua_pushstring(L, inet_ntoa(*((struct in_addr *) hp->h_addr)));
+    inet_pushresolved(L, hp);
+    return 2;
+}
+
+
+/*-------------------------------------------------------------------------*\
+* Gets the host name
+\*-------------------------------------------------------------------------*/
+static int inet_global_gethostname(lua_State *L)
+{
+    char name[257];
+    name[256] = '\0';
+    if (gethostname(name, 256) < 0) {
+        lua_pushnil(L);
+        lua_pushstring(L, "gethostname failed");
+        return 2;
+    } else {
+        lua_pushstring(L, name);
+        return 1;
+    }
+}
+
+
+
+/*=========================================================================*\
+* Lua methods
+\*=========================================================================*/
+/*-------------------------------------------------------------------------*\
+* Retrieves socket peer name
+\*-------------------------------------------------------------------------*/
+int inet_meth_getpeername(lua_State *L, p_socket ps)
+{
+    struct sockaddr_in peer;
+    socklen_t peer_len = sizeof(peer);
+    if (getpeername(*ps, (SA *) &peer, &peer_len) < 0) {
+        lua_pushnil(L);
+        lua_pushstring(L, "getpeername failed");
+    } else {
+        lua_pushstring(L, inet_ntoa(peer.sin_addr));
+        lua_pushnumber(L, ntohs(peer.sin_port));
+    }
+    return 2;
+}
+
+/*-------------------------------------------------------------------------*\
+* Retrieves socket local name
+\*-------------------------------------------------------------------------*/
+int inet_meth_getsockname(lua_State *L, p_socket ps)
+{
+    struct sockaddr_in local;
+    socklen_t local_len = sizeof(local);
+    if (getsockname(*ps, (SA *) &local, &local_len) < 0) {
+        lua_pushnil(L);
+        lua_pushstring(L, "getsockname failed");
+    } else {
+        lua_pushstring(L, inet_ntoa(local.sin_addr));
+        lua_pushnumber(L, ntohs(local.sin_port));
+    }
+    return 2;
+}
+
+/*=========================================================================*\
+* Internal functions
+\*=========================================================================*/
+/*-------------------------------------------------------------------------*\
+* Passes all resolver information to Lua as a table
+\*-------------------------------------------------------------------------*/
+static void inet_pushresolved(lua_State *L, struct hostent *hp)
+{
+    char **alias;
+    struct in_addr **addr;
+    int i, resolved;
+    lua_newtable(L); resolved = lua_gettop(L);
+    lua_pushstring(L, "name");
+    lua_pushstring(L, hp->h_name);
+    lua_settable(L, resolved);
+    lua_pushstring(L, "ip");
+    lua_pushstring(L, "alias");
+    i = 1;
+    alias = hp->h_aliases;
+    lua_newtable(L);
+    if (alias) {
+        while (*alias) {
+            lua_pushnumber(L, i);
+            lua_pushstring(L, *alias);
+            lua_settable(L, -3);
+            i++; alias++;
+        }
+    }
+    lua_settable(L, resolved);
+    i = 1;
+    lua_newtable(L);
+    addr = (struct in_addr **) hp->h_addr_list;
+    if (addr) {
+        while (*addr) {
+            lua_pushnumber(L, i);
+            lua_pushstring(L, inet_ntoa(**addr));
+            lua_settable(L, -3);
+            i++; addr++;
+        }
+    }
+    lua_settable(L, resolved);
+}
+
+/*-------------------------------------------------------------------------*\
+* Tries to create a new inet socket
+\*-------------------------------------------------------------------------*/
+const char *inet_trycreate(p_socket ps, int type) {
+    return socket_strerror(socket_create(ps, AF_INET, type, 0));
+}
+
+/*-------------------------------------------------------------------------*\
+* Tries to connect to remote address (address, port)
+\*-------------------------------------------------------------------------*/
+const char *inet_tryconnect(p_socket ps, const char *address, 
+        unsigned short port, p_timeout tm)
+{
+    struct sockaddr_in remote;
+    int err;
+    memset(&remote, 0, sizeof(remote));
+    remote.sin_family = AF_INET;
+    remote.sin_port = htons(port);
+	if (strcmp(address, "*")) {
+        if (!inet_aton(address, &remote.sin_addr)) {
+            struct hostent *hp = NULL;
+            struct in_addr **addr;
+            err = socket_gethostbyname(address, &hp);
+            if (err != IO_DONE) return socket_hoststrerror(err);
+            addr = (struct in_addr **) hp->h_addr_list;
+            memcpy(&remote.sin_addr, *addr, sizeof(struct in_addr));
+        }
+    } else remote.sin_family = AF_UNSPEC;
+    err = socket_connect(ps, (SA *) &remote, sizeof(remote), tm);
+    return socket_strerror(err);
+}
+
+/*-------------------------------------------------------------------------*\
+* Tries to bind socket to (address, port)
+\*-------------------------------------------------------------------------*/
+const char *inet_trybind(p_socket ps, const char *address, unsigned short port)
+{
+    struct sockaddr_in local;
+    int err;
+    memset(&local, 0, sizeof(local));
+    /* address is either wildcard or a valid ip address */
+    local.sin_addr.s_addr = htonl(INADDR_ANY);
+    local.sin_port = htons(port);
+    local.sin_family = AF_INET;
+    if (strcmp(address, "*") && !inet_aton(address, &local.sin_addr)) {
+        struct hostent *hp = NULL;
+        struct in_addr **addr;
+        err = socket_gethostbyname(address, &hp);
+        if (err != IO_DONE) return socket_hoststrerror(err);
+        addr = (struct in_addr **) hp->h_addr_list;
+        memcpy(&local.sin_addr, *addr, sizeof(struct in_addr));
+    }
+    err = socket_bind(ps, (SA *) &local, sizeof(local));
+    if (err != IO_DONE) socket_destroy(ps);
+    return socket_strerror(err); 
+}
+
+/*-------------------------------------------------------------------------*\
+* Some systems do not provide this so that we provide our own. It's not
+* marvelously fast, but it works just fine.
+\*-------------------------------------------------------------------------*/
+#ifdef INET_ATON
+int inet_aton(const char *cp, struct in_addr *inp)
+{
+    unsigned int a = 0, b = 0, c = 0, d = 0;
+    int n = 0, r;
+    unsigned long int addr = 0;
+    r = sscanf(cp, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n);
+    if (r == 0 || n == 0) return 0;
+    cp += n;
+    if (*cp) return 0;
+    if (a > 255 || b > 255 || c > 255 || d > 255) return 0;
+    if (inp) {
+        addr += a; addr <<= 8;
+        addr += b; addr <<= 8;
+        addr += c; addr <<= 8;
+        addr += d;
+        inp->s_addr = htonl(addr);
+    }
+    return 1;
+}
+#endif
+
+
diff --git a/src/luasocket/inet.h b/src/luasocket/inet.h
new file mode 100644
index 0000000000000000000000000000000000000000..7662266110ab94ac7b18bf937e2ff3cd67018916
--- /dev/null
+++ b/src/luasocket/inet.h
@@ -0,0 +1,42 @@
+#ifndef INET_H 
+#define INET_H 
+/*=========================================================================*\
+* Internet domain functions
+* LuaSocket toolkit
+*
+* This module implements the creation and connection of internet domain
+* sockets, on top of the socket.h interface, and the interface of with the
+* resolver. 
+*
+* The function inet_aton is provided for the platforms where it is not
+* available. The module also implements the interface of the internet
+* getpeername and getsockname functions as seen by Lua programs.
+*
+* The Lua functions toip and tohostname are also implemented here.
+*
+* RCS ID: $Id: inet.h,v 1.16 2005/10/07 04:40:59 diego Exp $
+\*=========================================================================*/
+#include "lua.h"
+#include "socket.h"
+#include "timeout.h"
+
+#ifdef _WIN32
+#define INET_ATON
+#endif
+
+int inet_open(lua_State *L);
+
+const char *inet_trycreate(p_socket ps, int type);
+const char *inet_tryconnect(p_socket ps, const char *address, 
+        unsigned short port, p_timeout tm);
+const char *inet_trybind(p_socket ps, const char *address, 
+        unsigned short port);
+
+int inet_meth_getpeername(lua_State *L, p_socket ps);
+int inet_meth_getsockname(lua_State *L, p_socket ps);
+
+#ifdef INET_ATON
+int inet_aton(const char *cp, struct in_addr *inp);
+#endif
+
+#endif /* INET_H */
diff --git a/src/luasocket/io.c b/src/luasocket/io.c
new file mode 100644
index 0000000000000000000000000000000000000000..06dc50ecacc287aa852896ad12dc6f728139ba19
--- /dev/null
+++ b/src/luasocket/io.c
@@ -0,0 +1,32 @@
+/*=========================================================================*\
+* Input/Output abstraction
+* LuaSocket toolkit
+*
+* RCS ID: $Id: io.c,v 1.6 2005/09/29 06:11:41 diego Exp $
+\*=========================================================================*/
+#include "io.h"
+
+/*=========================================================================*\
+* Exported functions
+\*=========================================================================*/
+/*-------------------------------------------------------------------------*\
+* Initializes C structure
+\*-------------------------------------------------------------------------*/
+void io_init(p_io io, p_send send, p_recv recv, p_error error, void *ctx) {
+    io->send = send;
+    io->recv = recv;
+    io->error = error;
+    io->ctx = ctx;
+}
+
+/*-------------------------------------------------------------------------*\
+* I/O error strings
+\*-------------------------------------------------------------------------*/
+const char *io_strerror(int err) {
+    switch (err) {
+        case IO_DONE: return NULL;
+        case IO_CLOSED: return "closed";
+        case IO_TIMEOUT: return "timeout";
+        default: return "unknown error"; 
+    }
+}
diff --git a/src/luasocket/io.h b/src/luasocket/io.h
new file mode 100644
index 0000000000000000000000000000000000000000..cce3aaf556ba865dfd51a31d36e895f382b0da9f
--- /dev/null
+++ b/src/luasocket/io.h
@@ -0,0 +1,67 @@
+#ifndef IO_H
+#define IO_H
+/*=========================================================================*\
+* Input/Output abstraction
+* LuaSocket toolkit
+*
+* This module defines the interface that LuaSocket expects from the
+* transport layer for streamed input/output. The idea is that if any
+* transport implements this interface, then the buffer.c functions
+* automatically work on it.
+*
+* The module socket.h implements this interface, and thus the module tcp.h
+* is very simple.
+*
+* RCS ID: $Id: io.h,v 1.11 2005/10/07 04:40:59 diego Exp $
+\*=========================================================================*/
+#include <stdio.h>
+#include "lua.h"
+
+#include "timeout.h"
+
+/* IO error codes */
+enum {
+    IO_DONE = 0,        /* operation completed successfully */
+    IO_TIMEOUT = -1,    /* operation timed out */
+    IO_CLOSED = -2,     /* the connection has been closed */
+	IO_UNKNOWN = -3
+};
+
+/* interface to error message function */
+typedef const char *(*p_error) (
+    void *ctx,          /* context needed by send */
+    int err             /* error code */
+);
+
+/* interface to send function */
+typedef int (*p_send) (
+    void *ctx,          /* context needed by send */
+    const char *data,   /* pointer to buffer with data to send */
+    size_t count,       /* number of bytes to send from buffer */
+    size_t *sent,       /* number of bytes sent uppon return */
+    p_timeout tm        /* timeout control */
+);
+
+/* interface to recv function */
+typedef int (*p_recv) (
+    void *ctx,          /* context needed by recv */
+    char *data,         /* pointer to buffer where data will be writen */
+    size_t count,       /* number of bytes to receive into buffer */
+    size_t *got,        /* number of bytes received uppon return */
+    p_timeout tm        /* timeout control */
+);
+
+/* IO driver definition */
+typedef struct t_io_ {
+    void *ctx;          /* context needed by send/recv */
+    p_send send;        /* send function pointer */
+    p_recv recv;        /* receive function pointer */
+    p_error error;      /* strerror function */
+} t_io;
+typedef t_io *p_io;
+
+void io_init(p_io io, p_send send, p_recv recv, p_error error, void *ctx);
+const char *io_strerror(int err);
+
+#endif /* IO_H */
+
diff --git a/src/luasocket/luasocket.c b/src/luasocket/luasocket.c
new file mode 100644
index 0000000000000000000000000000000000000000..11ffee94c46ff834d9a91aa2e3c3b3c90c9a0fbe
--- /dev/null
+++ b/src/luasocket/luasocket.c
@@ -0,0 +1,118 @@
+/*=========================================================================*\
+* LuaSocket toolkit
+* Networking support for the Lua language
+* Diego Nehab
+* 26/11/1999
+*
+* This library is part of an  effort to progressively increase the network
+* connectivity  of  the Lua  language.  The  Lua interface  to  networking
+* functions follows the Sockets API  closely, trying to simplify all tasks
+* involved in setting up both  client and server connections. The provided
+* IO routines, however, follow the Lua  style, being very similar  to the
+* standard Lua read and write functions.
+*
+* RCS ID: $Id: luasocket.c,v 1.53 2005/10/07 04:40:59 diego Exp $
+\*=========================================================================*/
+
+/*=========================================================================*\
+* Standard include files
+\*=========================================================================*/
+#include "lua.h"
+#include "lauxlib.h"
+
+#if !defined(LUA_VERSION_NUM) || (LUA_VERSION_NUM < 501)
+#include "compat-5.1.h"
+#endif
+
+/*=========================================================================*\
+* LuaSocket includes
+\*=========================================================================*/
+#include "luasocket.h"
+#include "auxiliar.h"
+#include "except.h"
+#include "timeout.h"
+#include "buffer.h"
+#include "inet.h"
+#include "tcp.h"
+#include "udp.h"
+#include "select.h"
+
+/*-------------------------------------------------------------------------*\
+* Internal function prototypes
+\*-------------------------------------------------------------------------*/
+static int global_skip(lua_State *L);
+static int global_unload(lua_State *L);
+static int base_open(lua_State *L);
+
+/*-------------------------------------------------------------------------*\
+* Modules and functions
+\*-------------------------------------------------------------------------*/
+static const luaL_reg mod[] = {
+    {"auxiliar", auxiliar_open},
+    {"except", except_open},
+    {"timeout", timeout_open},
+    {"buffer", buffer_open},
+    {"inet", inet_open},
+    {"tcp", tcp_open},
+    {"udp", udp_open},
+    {"select", select_open},
+    {NULL, NULL}
+};
+
+static luaL_reg func[] = {
+    {"skip",      global_skip},
+    {"__unload",  global_unload},
+    {NULL,        NULL}
+};
+
+/*-------------------------------------------------------------------------*\
+* Skip a few arguments
+\*-------------------------------------------------------------------------*/
+static int global_skip(lua_State *L) {
+    int amount = luaL_checkint(L, 1);
+    int ret = lua_gettop(L) - amount - 1;
+    return ret >= 0 ? ret : 0;
+}
+
+/*-------------------------------------------------------------------------*\
+* Unloads the library
+\*-------------------------------------------------------------------------*/
+static int global_unload(lua_State *L) {
+    (void) L;
+    socket_close();
+    return 0;
+}
+
+/*-------------------------------------------------------------------------*\
+* Setup basic stuff.
+\*-------------------------------------------------------------------------*/
+static int base_open(lua_State *L) {
+    if (socket_open()) {
+        /* export functions (and leave namespace table on top of stack) */
+        luaL_openlib(L, "socket", func, 0);
+#ifdef LUASOCKET_DEBUG
+        lua_pushstring(L, "_DEBUG");
+        lua_pushboolean(L, 1);
+        lua_rawset(L, -3);
+#endif
+        /* make version string available to scripts */
+        lua_pushstring(L, "_VERSION");
+        lua_pushstring(L, LUASOCKET_VERSION);
+        lua_rawset(L, -3);
+        return 1;
+    } else {
+        lua_pushstring(L, "unable to initialize library");
+        lua_error(L);
+        return 0;
+    }
+}
+
+/*-------------------------------------------------------------------------*\
+* Initializes all library modules.
+\*-------------------------------------------------------------------------*/
+LUASOCKET_API int luaopen_socket_core(lua_State *L) {
+    int i;
+    base_open(L);
+    for (i = 0; mod[i].name; i++) mod[i].func(L);
+    return 1;
+}
diff --git a/src/luasocket/luasocket.h b/src/luasocket/luasocket.h
new file mode 100644
index 0000000000000000000000000000000000000000..67270abb9375bbe1150fb45d03b09404f374c638
--- /dev/null
+++ b/src/luasocket/luasocket.h
@@ -0,0 +1,32 @@
+#ifndef LUASOCKET_H
+#define LUASOCKET_H
+/*=========================================================================*\
+* LuaSocket toolkit
+* Networking support for the Lua language
+* Diego Nehab
+* 9/11/1999
+*
+* RCS ID: $Id: luasocket.h,v 1.25 2007/06/11 23:44:54 diego Exp $
+\*=========================================================================*/
+#include "lua.h"
+
+/*-------------------------------------------------------------------------*\
+* Current socket library version
+\*-------------------------------------------------------------------------*/
+#define LUASOCKET_VERSION    "LuaSocket 2.0.2"
+#define LUASOCKET_COPYRIGHT  "Copyright (C) 2004-2007 Diego Nehab"
+#define LUASOCKET_AUTHORS    "Diego Nehab"
+
+/*-------------------------------------------------------------------------*\
+* This macro prefixes all exported API functions
+\*-------------------------------------------------------------------------*/
+#ifndef LUASOCKET_API
+#define LUASOCKET_API extern
+#endif
+
+/*-------------------------------------------------------------------------*\
+* Initializes the library.
+\*-------------------------------------------------------------------------*/
+LUASOCKET_API int luaopen_socket_core(lua_State *L);
+
+#endif /* LUASOCKET_H */
diff --git a/src/luasocket/mime.c b/src/luasocket/mime.c
new file mode 100644
index 0000000000000000000000000000000000000000..700fa05e9304f4ccc3be8630891078e06ddf077e
--- /dev/null
+++ b/src/luasocket/mime.c
@@ -0,0 +1,711 @@
+/*=========================================================================*\
+* MIME support functions
+* LuaSocket toolkit
+*
+* RCS ID: $Id: mime.c,v 1.28 2005/11/20 07:20:23 diego Exp $
+\*=========================================================================*/
+#include <string.h>
+
+#include "lua.h"
+#include "lauxlib.h"
+
+#if !defined(LUA_VERSION_NUM) || (LUA_VERSION_NUM < 501)
+#include "compat-5.1.h"
+#endif
+
+#include "mime.h"
+
+/*=========================================================================*\
+* Don't want to trust escape character constants
+\*=========================================================================*/
+typedef unsigned char UC;
+static const char CRLF[] = "\r\n";
+static const char EQCRLF[] = "=\r\n";
+
+/*=========================================================================*\
+* Internal function prototypes.
+\*=========================================================================*/
+static int mime_global_wrp(lua_State *L);
+static int mime_global_b64(lua_State *L);
+static int mime_global_unb64(lua_State *L);
+static int mime_global_qp(lua_State *L);
+static int mime_global_unqp(lua_State *L);
+static int mime_global_qpwrp(lua_State *L);
+static int mime_global_eol(lua_State *L);
+static int mime_global_dot(lua_State *L);
+
+static size_t dot(int c, size_t state, luaL_Buffer *buffer);
+static void b64setup(UC *b64unbase);
+static size_t b64encode(UC c, UC *input, size_t size, luaL_Buffer *buffer);
+static size_t b64pad(const UC *input, size_t size, luaL_Buffer *buffer);
+static size_t b64decode(UC c, UC *input, size_t size, luaL_Buffer *buffer);
+
+static void qpsetup(UC *qpclass, UC *qpunbase);
+static void qpquote(UC c, luaL_Buffer *buffer);
+static size_t qpdecode(UC c, UC *input, size_t size, luaL_Buffer *buffer);
+static size_t qpencode(UC c, UC *input, size_t size, 
+        const char *marker, luaL_Buffer *buffer);
+static size_t qppad(UC *input, size_t size, luaL_Buffer *buffer);
+
+/* code support functions */
+static luaL_reg func[] = {
+    { "dot", mime_global_dot },
+    { "b64", mime_global_b64 },
+    { "eol", mime_global_eol },
+    { "qp", mime_global_qp },
+    { "qpwrp", mime_global_qpwrp },
+    { "unb64", mime_global_unb64 },
+    { "unqp", mime_global_unqp },
+    { "wrp", mime_global_wrp },
+    { NULL, NULL }
+};
+
+/*-------------------------------------------------------------------------*\
+* Quoted-printable globals
+\*-------------------------------------------------------------------------*/
+static UC qpclass[256];
+static UC qpbase[] = "0123456789ABCDEF";
+static UC qpunbase[256];
+enum {QP_PLAIN, QP_QUOTED, QP_CR, QP_IF_LAST};
+
+/*-------------------------------------------------------------------------*\
+* Base64 globals
+\*-------------------------------------------------------------------------*/
+static const UC b64base[] =
+        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+static UC b64unbase[256];
+
+/*=========================================================================*\
+* Exported functions
+\*=========================================================================*/
+/*-------------------------------------------------------------------------*\
+* Initializes module
+\*-------------------------------------------------------------------------*/
+MIME_API int luaopen_mime_core(lua_State *L)
+{
+    luaL_openlib(L, "mime", func, 0);
+    /* make version string available to scripts */
+    lua_pushstring(L, "_VERSION");
+    lua_pushstring(L, MIME_VERSION);
+    lua_rawset(L, -3);
+    /* initialize lookup tables */
+    qpsetup(qpclass, qpunbase);
+    b64setup(b64unbase);
+    return 1;
+}
+
+/*=========================================================================*\
+* Global Lua functions
+\*=========================================================================*/
+/*-------------------------------------------------------------------------*\
+* Incrementaly breaks a string into lines. The string can have CRLF breaks.
+* A, n = wrp(l, B, length)
+* A is a copy of B, broken into lines of at most 'length' bytes. 
+* 'l' is how many bytes are left for the first line of B. 
+* 'n' is the number of bytes left in the last line of A. 
+\*-------------------------------------------------------------------------*/
+static int mime_global_wrp(lua_State *L)
+{
+    size_t size = 0;
+    int left = (int) luaL_checknumber(L, 1);
+    const UC *input = (UC *) luaL_optlstring(L, 2, NULL, &size);
+    const UC *last = input + size;
+    int length = (int) luaL_optnumber(L, 3, 76);
+    luaL_Buffer buffer;
+    /* end of input black-hole */
+    if (!input) {
+        /* if last line has not been terminated, add a line break */
+        if (left < length) lua_pushstring(L, CRLF);
+        /* otherwise, we are done */
+        else lua_pushnil(L);
+        lua_pushnumber(L, length);
+        return 2;
+    } 
+    luaL_buffinit(L, &buffer);
+    while (input < last) {
+        switch (*input) {
+            case '\r':
+                break;
+            case '\n':
+                luaL_addstring(&buffer, CRLF);
+                left = length;
+                break;
+            default:
+                if (left <= 0) {
+                    left = length;
+                    luaL_addstring(&buffer, CRLF);
+                }
+                luaL_putchar(&buffer, *input);
+                left--;
+                break;
+        }
+        input++;
+    }
+    luaL_pushresult(&buffer);
+    lua_pushnumber(L, left);
+    return 2;
+}
+
+/*-------------------------------------------------------------------------*\
+* Fill base64 decode map. 
+\*-------------------------------------------------------------------------*/
+static void b64setup(UC *b64unbase) 
+{
+    int i;
+    for (i = 0; i <= 255; i++) b64unbase[i] = (UC) 255;
+    for (i = 0; i < 64; i++) b64unbase[b64base[i]] = (UC) i;
+    b64unbase['='] = 0;
+}
+
+/*-------------------------------------------------------------------------*\
+* Acumulates bytes in input buffer until 3 bytes are available. 
+* Translate the 3 bytes into Base64 form and append to buffer.
+* Returns new number of bytes in buffer.
+\*-------------------------------------------------------------------------*/
+static size_t b64encode(UC c, UC *input, size_t size, 
+        luaL_Buffer *buffer)
+{
+    input[size++] = c;
+    if (size == 3) {
+        UC code[4];
+        unsigned long value = 0;
+        value += input[0]; value <<= 8;
+        value += input[1]; value <<= 8;
+        value += input[2]; 
+        code[3] = b64base[value & 0x3f]; value >>= 6;
+        code[2] = b64base[value & 0x3f]; value >>= 6;
+        code[1] = b64base[value & 0x3f]; value >>= 6;
+        code[0] = b64base[value];
+        luaL_addlstring(buffer, (char *) code, 4);
+        size = 0;
+    }
+    return size;
+}
+
+/*-------------------------------------------------------------------------*\
+* Encodes the Base64 last 1 or 2 bytes and adds padding '=' 
+* Result, if any, is appended to buffer.
+* Returns 0.
+\*-------------------------------------------------------------------------*/
+static size_t b64pad(const UC *input, size_t size, 
+        luaL_Buffer *buffer)
+{
+    unsigned long value = 0;
+    UC code[4] = {'=', '=', '=', '='};
+    switch (size) {
+        case 1:
+            value = input[0] << 4;
+            code[1] = b64base[value & 0x3f]; value >>= 6;
+            code[0] = b64base[value];
+            luaL_addlstring(buffer, (char *) code, 4);
+            break;
+        case 2:
+            value = input[0]; value <<= 8; 
+            value |= input[1]; value <<= 2;
+            code[2] = b64base[value & 0x3f]; value >>= 6;
+            code[1] = b64base[value & 0x3f]; value >>= 6;
+            code[0] = b64base[value];
+            luaL_addlstring(buffer, (char *) code, 4);
+            break;
+        default:
+            break;
+    }
+    return 0;
+}
+
+/*-------------------------------------------------------------------------*\
+* Acumulates bytes in input buffer until 4 bytes are available. 
+* Translate the 4 bytes from Base64 form and append to buffer.
+* Returns new number of bytes in buffer.
+\*-------------------------------------------------------------------------*/
+static size_t b64decode(UC c, UC *input, size_t size, 
+        luaL_Buffer *buffer)
+{
+    /* ignore invalid characters */
+    if (b64unbase[c] > 64) return size;
+    input[size++] = c;
+    /* decode atom */
+    if (size == 4) {
+        UC decoded[3];
+        int valid, value = 0;
+        value =  b64unbase[input[0]]; value <<= 6;
+        value |= b64unbase[input[1]]; value <<= 6;
+        value |= b64unbase[input[2]]; value <<= 6;
+        value |= b64unbase[input[3]];
+        decoded[2] = (UC) (value & 0xff); value >>= 8;
+        decoded[1] = (UC) (value & 0xff); value >>= 8;
+        decoded[0] = (UC) value;
+        /* take care of paddding */
+        valid = (input[2] == '=') ? 1 : (input[3] == '=') ? 2 : 3; 
+        luaL_addlstring(buffer, (char *) decoded, valid);
+        return 0;
+    /* need more data */
+    } else return size;
+}
+
+/*-------------------------------------------------------------------------*\
+* Incrementally applies the Base64 transfer content encoding to a string
+* A, B = b64(C, D)
+* A is the encoded version of the largest prefix of C .. D that is
+* divisible by 3. B has the remaining bytes of C .. D, *without* encoding.
+* The easiest thing would be to concatenate the two strings and 
+* encode the result, but we can't afford that or Lua would dupplicate
+* every chunk we received.
+\*-------------------------------------------------------------------------*/
+static int mime_global_b64(lua_State *L)
+{
+    UC atom[3];
+    size_t isize = 0, asize = 0;
+    const UC *input = (UC *) luaL_optlstring(L, 1, NULL, &isize);
+    const UC *last = input + isize;
+    luaL_Buffer buffer;
+    /* end-of-input blackhole */
+    if (!input) {
+        lua_pushnil(L);
+        lua_pushnil(L);
+        return 2;
+    }
+    /* process first part of the input */
+    luaL_buffinit(L, &buffer);
+    while (input < last) 
+        asize = b64encode(*input++, atom, asize, &buffer);
+    input = (UC *) luaL_optlstring(L, 2, NULL, &isize);
+    /* if second part is nil, we are done */
+    if (!input) {
+        asize = b64pad(atom, asize, &buffer);
+        luaL_pushresult(&buffer);
+        if (!(*lua_tostring(L, -1))) lua_pushnil(L);
+        lua_pushnil(L);
+        return 2;
+    }
+    /* otherwise process the second part */
+    last = input + isize;
+    while (input < last) 
+        asize = b64encode(*input++, atom, asize, &buffer);
+    luaL_pushresult(&buffer);
+    lua_pushlstring(L, (char *) atom, asize);
+    return 2;
+}
+
+/*-------------------------------------------------------------------------*\
+* Incrementally removes the Base64 transfer content encoding from a string
+* A, B = b64(C, D)
+* A is the encoded version of the largest prefix of C .. D that is
+* divisible by 4. B has the remaining bytes of C .. D, *without* encoding.
+\*-------------------------------------------------------------------------*/
+static int mime_global_unb64(lua_State *L)
+{
+    UC atom[4];
+    size_t isize = 0, asize = 0;
+    const UC *input = (UC *) luaL_optlstring(L, 1, NULL, &isize);
+    const UC *last = input + isize;
+    luaL_Buffer buffer;
+    /* end-of-input blackhole */
+    if (!input) {
+        lua_pushnil(L);
+        lua_pushnil(L);
+        return 2;
+    }
+    /* process first part of the input */
+    luaL_buffinit(L, &buffer);
+    while (input < last) 
+        asize = b64decode(*input++, atom, asize, &buffer);
+    input = (UC *) luaL_optlstring(L, 2, NULL, &isize);
+    /* if second is nil, we are done */
+    if (!input) {
+        luaL_pushresult(&buffer);
+        if (!(*lua_tostring(L, -1))) lua_pushnil(L);
+        lua_pushnil(L);
+        return 2;
+    }
+    /* otherwise, process the rest of the input */
+    last = input + isize;
+    while (input < last) 
+        asize = b64decode(*input++, atom, asize, &buffer);
+    luaL_pushresult(&buffer);
+    lua_pushlstring(L, (char *) atom, asize);
+    return 2;
+}
+
+/*-------------------------------------------------------------------------*\
+* Quoted-printable encoding scheme
+* all (except CRLF in text) can be =XX
+* CLRL in not text must be =XX=XX
+* 33 through 60 inclusive can be plain
+* 62 through 126 inclusive can be plain
+* 9 and 32 can be plain, unless in the end of a line, where must be =XX
+* encoded lines must be no longer than 76 not counting CRLF
+* soft line-break are =CRLF
+* To encode one byte, we need to see the next two. 
+* Worst case is when we see a space, and wonder if a CRLF is comming
+\*-------------------------------------------------------------------------*/
+/*-------------------------------------------------------------------------*\
+* Split quoted-printable characters into classes
+* Precompute reverse map for encoding
+\*-------------------------------------------------------------------------*/
+static void qpsetup(UC *qpclass, UC *qpunbase)
+{
+    int i;
+    for (i = 0; i < 256; i++) qpclass[i] = QP_QUOTED;
+    for (i = 33; i <= 60; i++) qpclass[i] = QP_PLAIN;
+    for (i = 62; i <= 126; i++) qpclass[i] = QP_PLAIN;
+    qpclass['\t'] = QP_IF_LAST; 
+    qpclass[' '] = QP_IF_LAST;
+    qpclass['\r'] = QP_CR;
+    for (i = 0; i < 256; i++) qpunbase[i] = 255;
+    qpunbase['0'] = 0; qpunbase['1'] = 1; qpunbase['2'] = 2;
+    qpunbase['3'] = 3; qpunbase['4'] = 4; qpunbase['5'] = 5;
+    qpunbase['6'] = 6; qpunbase['7'] = 7; qpunbase['8'] = 8;
+    qpunbase['9'] = 9; qpunbase['A'] = 10; qpunbase['a'] = 10;
+    qpunbase['B'] = 11; qpunbase['b'] = 11; qpunbase['C'] = 12;
+    qpunbase['c'] = 12; qpunbase['D'] = 13; qpunbase['d'] = 13;
+    qpunbase['E'] = 14; qpunbase['e'] = 14; qpunbase['F'] = 15;
+    qpunbase['f'] = 15;
+}
+
+/*-------------------------------------------------------------------------*\
+* Output one character in form =XX
+\*-------------------------------------------------------------------------*/
+static void qpquote(UC c, luaL_Buffer *buffer)
+{
+    luaL_putchar(buffer, '=');
+    luaL_putchar(buffer, qpbase[c >> 4]);
+    luaL_putchar(buffer, qpbase[c & 0x0F]);
+}
+
+/*-------------------------------------------------------------------------*\
+* Accumulate characters until we are sure about how to deal with them.
+* Once we are sure, output to the buffer, in the correct form. 
+\*-------------------------------------------------------------------------*/
+static size_t qpencode(UC c, UC *input, size_t size, 
+        const char *marker, luaL_Buffer *buffer)
+{
+    input[size++] = c;
+    /* deal with all characters we can have */
+    while (size > 0) {
+        switch (qpclass[input[0]]) {
+            /* might be the CR of a CRLF sequence */
+            case QP_CR:
+                if (size < 2) return size;
+                if (input[1] == '\n') {
+                    luaL_addstring(buffer, marker);
+                    return 0;
+                } else qpquote(input[0], buffer);
+                break;
+            /* might be a space and that has to be quoted if last in line */
+            case QP_IF_LAST:
+                if (size < 3) return size;
+                /* if it is the last, quote it and we are done */
+                if (input[1] == '\r' && input[2] == '\n') {
+                    qpquote(input[0], buffer);
+                    luaL_addstring(buffer, marker);
+                    return 0;
+                } else luaL_putchar(buffer, input[0]);
+                break;
+                /* might have to be quoted always */
+            case QP_QUOTED:
+                qpquote(input[0], buffer);
+                break;
+                /* might never have to be quoted */
+            default:
+                luaL_putchar(buffer, input[0]);
+                break;
+        }
+        input[0] = input[1]; input[1] = input[2];
+        size--;
+    }
+    return 0;
+}
+
+/*-------------------------------------------------------------------------*\
+* Deal with the final characters 
+\*-------------------------------------------------------------------------*/
+static size_t qppad(UC *input, size_t size, luaL_Buffer *buffer)
+{
+    size_t i;
+    for (i = 0; i < size; i++) {
+        if (qpclass[input[i]] == QP_PLAIN) luaL_putchar(buffer, input[i]);
+        else qpquote(input[i], buffer);
+    }
+    if (size > 0) luaL_addstring(buffer, EQCRLF);
+    return 0;
+}
+
+/*-------------------------------------------------------------------------*\
+* Incrementally converts a string to quoted-printable
+* A, B = qp(C, D, marker)
+* Marker is the text to be used to replace CRLF sequences found in A.
+* A is the encoded version of the largest prefix of C .. D that 
+* can be encoded without doubts. 
+* B has the remaining bytes of C .. D, *without* encoding.
+\*-------------------------------------------------------------------------*/
+static int mime_global_qp(lua_State *L)
+{
+
+    size_t asize = 0, isize = 0;
+    UC atom[3];
+    const UC *input = (UC *) luaL_optlstring(L, 1, NULL, &isize);
+    const UC *last = input + isize;
+    const char *marker = luaL_optstring(L, 3, CRLF);
+    luaL_Buffer buffer;
+    /* end-of-input blackhole */
+    if (!input) {
+        lua_pushnil(L);
+        lua_pushnil(L);
+        return 2;
+    }
+    /* process first part of input */
+    luaL_buffinit(L, &buffer);
+    while (input < last)
+        asize = qpencode(*input++, atom, asize, marker, &buffer);
+    input = (UC *) luaL_optlstring(L, 2, NULL, &isize);
+    /* if second part is nil, we are done */
+    if (!input) {
+        asize = qppad(atom, asize, &buffer);
+        luaL_pushresult(&buffer);
+        if (!(*lua_tostring(L, -1))) lua_pushnil(L);
+        lua_pushnil(L);
+        return 2;
+    }
+    /* otherwise process rest of input */
+    last = input + isize;
+    while (input < last)
+        asize = qpencode(*input++, atom, asize, marker, &buffer);
+    luaL_pushresult(&buffer);
+    lua_pushlstring(L, (char *) atom, asize);
+    return 2;
+}
+
+/*-------------------------------------------------------------------------*\
+* Accumulate characters until we are sure about how to deal with them.
+* Once we are sure, output the to the buffer, in the correct form. 
+\*-------------------------------------------------------------------------*/
+static size_t qpdecode(UC c, UC *input, size_t size, luaL_Buffer *buffer) {
+    int d;
+    input[size++] = c;
+    /* deal with all characters we can deal */
+    switch (input[0]) {
+        /* if we have an escape character */
+        case '=': 
+            if (size < 3) return size; 
+            /* eliminate soft line break */
+            if (input[1] == '\r' && input[2] == '\n') return 0;
+            /* decode quoted representation */
+            c = qpunbase[input[1]]; d = qpunbase[input[2]];
+            /* if it is an invalid, do not decode */
+            if (c > 15 || d > 15) luaL_addlstring(buffer, (char *)input, 3);
+            else luaL_putchar(buffer, (c << 4) + d);
+            return 0;
+        case '\r':
+            if (size < 2) return size; 
+            if (input[1] == '\n') luaL_addlstring(buffer, (char *)input, 2);
+            return 0;
+        default:
+            if (input[0] == '\t' || (input[0] > 31 && input[0] < 127))
+                luaL_putchar(buffer, input[0]);
+            return 0;
+    }
+}
+
+/*-------------------------------------------------------------------------*\
+* Incrementally decodes a string in quoted-printable
+* A, B = qp(C, D)
+* A is the decoded version of the largest prefix of C .. D that 
+* can be decoded without doubts. 
+* B has the remaining bytes of C .. D, *without* decoding.
+\*-------------------------------------------------------------------------*/
+static int mime_global_unqp(lua_State *L)
+{
+    size_t asize = 0, isize = 0;
+    UC atom[3];
+    const UC *input = (UC *) luaL_optlstring(L, 1, NULL, &isize);
+    const UC *last = input + isize;
+    luaL_Buffer buffer;
+    /* end-of-input blackhole */
+    if (!input) {
+        lua_pushnil(L);
+        lua_pushnil(L);
+        return 2;
+    }
+    /* process first part of input */
+    luaL_buffinit(L, &buffer);
+    while (input < last)
+        asize = qpdecode(*input++, atom, asize, &buffer);
+    input = (UC *) luaL_optlstring(L, 2, NULL, &isize);
+    /* if second part is nil, we are done */
+    if (!input) {
+        luaL_pushresult(&buffer);
+        if (!(*lua_tostring(L, -1))) lua_pushnil(L);
+        lua_pushnil(L);
+        return 2;
+    } 
+    /* otherwise process rest of input */
+    last = input + isize;
+    while (input < last)
+        asize = qpdecode(*input++, atom, asize, &buffer);
+    luaL_pushresult(&buffer);
+    lua_pushlstring(L, (char *) atom, asize);
+    return 2;
+}
+
+/*-------------------------------------------------------------------------*\
+* Incrementally breaks a quoted-printed string into lines
+* A, n = qpwrp(l, B, length)
+* A is a copy of B, broken into lines of at most 'length' bytes. 
+* 'l' is how many bytes are left for the first line of B. 
+* 'n' is the number of bytes left in the last line of A. 
+* There are two complications: lines can't be broken in the middle
+* of an encoded =XX, and there might be line breaks already
+\*-------------------------------------------------------------------------*/
+static int mime_global_qpwrp(lua_State *L)
+{
+    size_t size = 0;
+    int left = (int) luaL_checknumber(L, 1);
+    const UC *input = (UC *) luaL_optlstring(L, 2, NULL, &size);
+    const UC *last = input + size;
+    int length = (int) luaL_optnumber(L, 3, 76);
+    luaL_Buffer buffer;
+    /* end-of-input blackhole */
+    if (!input) {
+        if (left < length) lua_pushstring(L, EQCRLF);
+        else lua_pushnil(L);
+        lua_pushnumber(L, length);
+        return 2;
+    }
+    /* process all input */
+    luaL_buffinit(L, &buffer);
+    while (input < last) {
+        switch (*input) {
+            case '\r':
+                break;
+            case '\n':
+                left = length;
+                luaL_addstring(&buffer, CRLF);
+                break;
+            case '=':
+                if (left <= 3) {
+                    left = length;
+                    luaL_addstring(&buffer, EQCRLF);
+                } 
+                luaL_putchar(&buffer, *input);
+                left--;
+                break;
+            default: 
+                if (left <= 1) {
+                    left = length;
+                    luaL_addstring(&buffer, EQCRLF);
+                }
+                luaL_putchar(&buffer, *input);
+                left--;
+                break;
+        }
+        input++;
+    }
+    luaL_pushresult(&buffer);
+    lua_pushnumber(L, left);
+    return 2;
+}
+
+/*-------------------------------------------------------------------------*\
+* Here is what we do: \n, and \r are considered candidates for line
+* break. We issue *one* new line marker if any of them is seen alone, or
+* followed by a different one. That is, \n\n and \r\r will issue two
+* end of line markers each, but \r\n, \n\r etc will only issue *one*
+* marker.  This covers Mac OS, Mac OS X, VMS, Unix and DOS, as well as
+* probably other more obscure conventions.
+*
+* c is the current character being processed
+* last is the previous character
+\*-------------------------------------------------------------------------*/
+#define eolcandidate(c) (c == '\r' || c == '\n')
+static int eolprocess(int c, int last, const char *marker, 
+        luaL_Buffer *buffer)
+{
+    if (eolcandidate(c)) {
+        if (eolcandidate(last)) {
+            if (c == last) luaL_addstring(buffer, marker);
+            return 0;
+        } else {
+            luaL_addstring(buffer, marker);
+            return c;
+        }
+    } else {
+        luaL_putchar(buffer, c);
+        return 0;
+    }
+}
+
+/*-------------------------------------------------------------------------*\
+* Converts a string to uniform EOL convention. 
+* A, n = eol(o, B, marker)
+* A is the converted version of the largest prefix of B that can be
+* converted unambiguously. 'o' is the context returned by the previous 
+* call. 'n' is the new context.
+\*-------------------------------------------------------------------------*/
+static int mime_global_eol(lua_State *L)
+{
+    int ctx = luaL_checkint(L, 1);
+    size_t isize = 0;
+    const char *input = luaL_optlstring(L, 2, NULL, &isize);
+    const char *last = input + isize;
+    const char *marker = luaL_optstring(L, 3, CRLF);
+    luaL_Buffer buffer;
+    luaL_buffinit(L, &buffer);
+    /* end of input blackhole */
+    if (!input) {
+       lua_pushnil(L);
+       lua_pushnumber(L, 0);
+       return 2;
+    }
+    /* process all input */
+    while (input < last)
+        ctx = eolprocess(*input++, ctx, marker, &buffer);
+    luaL_pushresult(&buffer);
+    lua_pushnumber(L, ctx);
+    return 2;
+}
+
+/*-------------------------------------------------------------------------*\
+* Takes one byte and stuff it if needed. 
+\*-------------------------------------------------------------------------*/
+static size_t dot(int c, size_t state, luaL_Buffer *buffer)
+{
+    luaL_putchar(buffer, c);
+    switch (c) {
+        case '\r': 
+            return 1;
+        case '\n': 
+            return (state == 1)? 2: 0; 
+        case '.':  
+            if (state == 2) 
+                luaL_putchar(buffer, '.');
+        default:
+            return 0;
+    }
+}
+
+/*-------------------------------------------------------------------------*\
+* Incrementally applies smtp stuffing to a string
+* A, n = dot(l, D)
+\*-------------------------------------------------------------------------*/
+static int mime_global_dot(lua_State *L)
+{
+    size_t isize = 0, state = (size_t) luaL_checknumber(L, 1);
+    const char *input = luaL_optlstring(L, 2, NULL, &isize);
+    const char *last = input + isize;
+    luaL_Buffer buffer;
+    /* end-of-input blackhole */
+    if (!input) {
+        lua_pushnil(L);
+        lua_pushnumber(L, 2);
+        return 2;
+    }
+    /* process all input */
+    luaL_buffinit(L, &buffer);
+    while (input < last) 
+        state = dot(*input++, state, &buffer);
+    luaL_pushresult(&buffer);
+    lua_pushnumber(L, state);
+    return 2;
+}
+
diff --git a/src/luasocket/mime.h b/src/luasocket/mime.h
new file mode 100644
index 0000000000000000000000000000000000000000..85ee2a39856dddeee4e770c2bc5af5d17a0d77a8
--- /dev/null
+++ b/src/luasocket/mime.h
@@ -0,0 +1,31 @@
+#ifndef MIME_H 
+#define MIME_H 
+/*=========================================================================*\
+* Core MIME support
+* LuaSocket toolkit
+*
+* This module provides functions to implement transfer content encodings
+* and formatting conforming to RFC 2045. It is used by mime.lua, which
+* provide a higher level interface to this functionality. 
+*
+* RCS ID: $Id: mime.h,v 1.15 2007/06/11 23:44:54 diego Exp $
+\*=========================================================================*/
+#include "lua.h"
+
+/*-------------------------------------------------------------------------*\
+* Current MIME library version
+\*-------------------------------------------------------------------------*/
+#define MIME_VERSION    "MIME 1.0.2"
+#define MIME_COPYRIGHT  "Copyright (C) 2004-2007 Diego Nehab"
+#define MIME_AUTHORS    "Diego Nehab"
+
+/*-------------------------------------------------------------------------*\
+* This macro prefixes all exported API functions
+\*-------------------------------------------------------------------------*/
+#ifndef MIME_API
+#define MIME_API extern
+#endif
+
+MIME_API int luaopen_mime_core(lua_State *L);
+
+#endif /* MIME_H */
diff --git a/src/luasocket/options.c b/src/luasocket/options.c
new file mode 100644
index 0000000000000000000000000000000000000000..5da3c518c285e6db88b2bc3158668fb0582a91f7
--- /dev/null
+++ b/src/luasocket/options.c
@@ -0,0 +1,149 @@
+/*=========================================================================*\
+* Common option interface 
+* LuaSocket toolkit
+*
+* RCS ID: $Id: options.c,v 1.6 2005/11/20 07:20:23 diego Exp $
+\*=========================================================================*/
+#include <string.h> 
+
+#include "lauxlib.h"
+
+#include "auxiliar.h"
+#include "options.h"
+#include "inet.h"
+
+
+/*=========================================================================*\
+* Internal functions prototypes
+\*=========================================================================*/
+static int opt_setmembership(lua_State *L, p_socket ps, int level, int name);
+static int opt_setboolean(lua_State *L, p_socket ps, int level, int name);
+static int opt_set(lua_State *L, p_socket ps, int level, int name, 
+        void *val, int len);
+
+/*=========================================================================*\
+* Exported functions
+\*=========================================================================*/
+/*-------------------------------------------------------------------------*\
+* Calls appropriate option handler
+\*-------------------------------------------------------------------------*/
+int opt_meth_setoption(lua_State *L, p_opt opt, p_socket ps)
+{
+    const char *name = luaL_checkstring(L, 2);      /* obj, name, ... */
+    while (opt->name && strcmp(name, opt->name))
+        opt++;
+    if (!opt->func) {
+        char msg[45];
+        sprintf(msg, "unsupported option `%.35s'", name);
+        luaL_argerror(L, 2, msg);
+    }
+    return opt->func(L, ps);
+}
+
+/* enables reuse of local address */
+int opt_reuseaddr(lua_State *L, p_socket ps)
+{
+    return opt_setboolean(L, ps, SOL_SOCKET, SO_REUSEADDR); 
+}
+
+/* disables the Naggle algorithm */
+int opt_tcp_nodelay(lua_State *L, p_socket ps)
+{
+    return opt_setboolean(L, ps, IPPROTO_TCP, TCP_NODELAY); 
+}
+
+int opt_keepalive(lua_State *L, p_socket ps)
+{
+    return opt_setboolean(L, ps, SOL_SOCKET, SO_KEEPALIVE); 
+}
+
+int opt_dontroute(lua_State *L, p_socket ps)
+{
+    return opt_setboolean(L, ps, SOL_SOCKET, SO_DONTROUTE);
+}
+
+int opt_broadcast(lua_State *L, p_socket ps)
+{
+    return opt_setboolean(L, ps, SOL_SOCKET, SO_BROADCAST);
+}
+
+int opt_ip_multicast_loop(lua_State *L, p_socket ps)
+{
+    return opt_setboolean(L, ps, IPPROTO_IP, IP_MULTICAST_LOOP);
+}
+
+int opt_linger(lua_State *L, p_socket ps)
+{
+    struct linger li;                      /* obj, name, table */
+    if (!lua_istable(L, 3)) luaL_typerror(L, 3, lua_typename(L, LUA_TTABLE));
+    lua_pushstring(L, "on");
+    lua_gettable(L, 3);
+    if (!lua_isboolean(L, -1)) 
+        luaL_argerror(L, 3, "boolean 'on' field expected");
+    li.l_onoff = (u_short) lua_toboolean(L, -1);
+    lua_pushstring(L, "timeout");
+    lua_gettable(L, 3);
+    if (!lua_isnumber(L, -1)) 
+        luaL_argerror(L, 3, "number 'timeout' field expected");
+    li.l_linger = (u_short) lua_tonumber(L, -1);
+    return opt_set(L, ps, SOL_SOCKET, SO_LINGER, (char *) &li, sizeof(li));
+}
+
+int opt_ip_multicast_ttl(lua_State *L, p_socket ps)
+{
+    int val = (int) luaL_checknumber(L, 3);    /* obj, name, int */
+    return opt_set(L, ps, SOL_SOCKET, SO_LINGER, (char *) &val, sizeof(val));
+}
+
+int opt_ip_add_membership(lua_State *L, p_socket ps)
+{
+    return opt_setmembership(L, ps, IPPROTO_IP, IP_ADD_MEMBERSHIP);
+}
+
+int opt_ip_drop_membersip(lua_State *L, p_socket ps)
+{
+    return opt_setmembership(L, ps, IPPROTO_IP, IP_DROP_MEMBERSHIP);
+}
+
+/*=========================================================================*\
+* Auxiliar functions
+\*=========================================================================*/
+static int opt_setmembership(lua_State *L, p_socket ps, int level, int name)
+{
+    struct ip_mreq val;                   /* obj, name, table */
+    if (!lua_istable(L, 3)) luaL_typerror(L, 3, lua_typename(L, LUA_TTABLE));
+    lua_pushstring(L, "multiaddr");
+    lua_gettable(L, 3);
+    if (!lua_isstring(L, -1)) 
+        luaL_argerror(L, 3, "string 'multiaddr' field expected");
+    if (!inet_aton(lua_tostring(L, -1), &val.imr_multiaddr)) 
+        luaL_argerror(L, 3, "invalid 'multiaddr' ip address");
+    lua_pushstring(L, "interface");
+    lua_gettable(L, 3);
+    if (!lua_isstring(L, -1)) 
+        luaL_argerror(L, 3, "string 'interface' field expected");
+    val.imr_interface.s_addr = htonl(INADDR_ANY);
+    if (strcmp(lua_tostring(L, -1), "*") &&
+            !inet_aton(lua_tostring(L, -1), &val.imr_interface)) 
+        luaL_argerror(L, 3, "invalid 'interface' ip address");
+    return opt_set(L, ps, level, name, (char *) &val, sizeof(val));
+}
+
+static 
+int opt_set(lua_State *L, p_socket ps, int level, int name, void *val, int len)
+{
+    if (setsockopt(*ps, level, name, (char *) val, len) < 0) {
+        lua_pushnil(L);
+        lua_pushstring(L, "setsockopt failed");
+        return 2;
+    }
+    lua_pushnumber(L, 1);
+    return 1;
+}
+
+static int opt_setboolean(lua_State *L, p_socket ps, int level, int name)
+{
+    int val = auxiliar_checkboolean(L, 3);             /* obj, name, bool */
+    return opt_set(L, ps, level, name, (char *) &val, sizeof(val));
+}
+
diff --git a/src/luasocket/options.h b/src/luasocket/options.h
new file mode 100644
index 0000000000000000000000000000000000000000..4981cf2a0ef77b97a5eebb291683acef55cde2bb
--- /dev/null
+++ b/src/luasocket/options.h
@@ -0,0 +1,39 @@
+#ifndef OPTIONS_H
+#define OPTIONS_H
+/*=========================================================================*\
+* Common option interface 
+* LuaSocket toolkit
+*
+* This module provides a common interface to socket options, used mainly by
+* modules UDP and TCP. 
+*
+* RCS ID: $Id: options.h,v 1.4 2005/10/07 04:40:59 diego Exp $
+\*=========================================================================*/
+
+#include "lua.h"
+#include "socket.h"
+
+/* option registry */
+typedef struct t_opt {
+  const char *name;
+  int (*func)(lua_State *L, p_socket ps);
+} t_opt;
+typedef t_opt *p_opt;
+
+/* supported options */
+int opt_dontroute(lua_State *L, p_socket ps);
+int opt_broadcast(lua_State *L, p_socket ps);
+int opt_reuseaddr(lua_State *L, p_socket ps);
+int opt_tcp_nodelay(lua_State *L, p_socket ps);
+int opt_keepalive(lua_State *L, p_socket ps);
+int opt_linger(lua_State *L, p_socket ps);
+int opt_reuseaddr(lua_State *L, p_socket ps);
+int opt_ip_multicast_ttl(lua_State *L, p_socket ps);
+int opt_ip_multicast_loop(lua_State *L, p_socket ps);
+int opt_ip_add_membership(lua_State *L, p_socket ps);
+int opt_ip_drop_membersip(lua_State *L, p_socket ps);
+
+/* invokes the appropriate option handler */
+int opt_meth_setoption(lua_State *L, p_opt opt, p_socket ps);
+
+#endif
diff --git a/src/luasocket/select.c b/src/luasocket/select.c
new file mode 100644
index 0000000000000000000000000000000000000000..d70f662713acbabcbd1a4ff3c515e24dcb64d08f
--- /dev/null
+++ b/src/luasocket/select.c
@@ -0,0 +1,200 @@
+/*=========================================================================*\
+* Select implementation
+* LuaSocket toolkit
+*
+* RCS ID: $Id: select.c,v 1.22 2005/11/20 07:20:23 diego Exp $
+\*=========================================================================*/
+#include <string.h>
+
+#include "lua.h"
+#include "lauxlib.h"
+
+#include "socket.h"
+#include "timeout.h"
+#include "select.h"
+
+/*=========================================================================*\
+* Internal function prototypes.
+\*=========================================================================*/
+static t_socket getfd(lua_State *L);
+static int dirty(lua_State *L);
+static t_socket collect_fd(lua_State *L, int tab, t_socket max_fd, 
+        int itab, fd_set *set);
+static int check_dirty(lua_State *L, int tab, int dtab, fd_set *set);
+static void return_fd(lua_State *L, fd_set *set, t_socket max_fd, 
+        int itab, int tab, int start);
+static void make_assoc(lua_State *L, int tab);
+static int global_select(lua_State *L);
+
+/* functions in library namespace */
+static luaL_reg func[] = {
+    {"select", global_select},
+    {NULL,     NULL}
+};
+
+/*=========================================================================*\
+* Exported functions
+\*=========================================================================*/
+/*-------------------------------------------------------------------------*\
+* Initializes module
+\*-------------------------------------------------------------------------*/
+int select_open(lua_State *L) {
+    luaL_openlib(L, NULL, func, 0);
+    return 0;
+}
+
+/*=========================================================================*\
+* Global Lua functions
+\*=========================================================================*/
+/*-------------------------------------------------------------------------*\
+* Waits for a set of sockets until a condition is met or timeout.
+\*-------------------------------------------------------------------------*/
+static int global_select(lua_State *L) {
+    int rtab, wtab, itab, ret, ndirty;
+    t_socket max_fd;
+    fd_set rset, wset;
+    t_timeout tm;
+    double t = luaL_optnumber(L, 3, -1);
+    FD_ZERO(&rset); FD_ZERO(&wset);
+    lua_settop(L, 3);
+    lua_newtable(L); itab = lua_gettop(L);
+    lua_newtable(L); rtab = lua_gettop(L);
+    lua_newtable(L); wtab = lua_gettop(L);
+    max_fd = collect_fd(L, 1, SOCKET_INVALID, itab, &rset);
+    ndirty = check_dirty(L, 1, rtab, &rset);
+    t = ndirty > 0? 0.0: t;
+    timeout_init(&tm, t, -1);
+    timeout_markstart(&tm);
+    max_fd = collect_fd(L, 2, max_fd, itab, &wset);
+    ret = socket_select(max_fd+1, &rset, &wset, NULL, &tm);
+    if (ret > 0 || ndirty > 0) {
+        return_fd(L, &rset, max_fd+1, itab, rtab, ndirty);
+        return_fd(L, &wset, max_fd+1, itab, wtab, 0);
+        make_assoc(L, rtab);
+        make_assoc(L, wtab);
+        return 2;
+    } else if (ret == 0) {
+        lua_pushstring(L, "timeout");
+        return 3;
+    } else {
+        lua_pushstring(L, "error");
+        return 3;
+    }
+}
+
+/*=========================================================================*\
+* Internal functions
+\*=========================================================================*/
+static t_socket getfd(lua_State *L) {
+    t_socket fd = SOCKET_INVALID;
+    lua_pushstring(L, "getfd");
+    lua_gettable(L, -2);
+    if (!lua_isnil(L, -1)) {
+        lua_pushvalue(L, -2);
+        lua_call(L, 1, 1);
+        if (lua_isnumber(L, -1)) 
+            fd = (t_socket) lua_tonumber(L, -1); 
+    } 
+    lua_pop(L, 1);
+    return fd;
+}
+
+static int dirty(lua_State *L) {
+    int is = 0;
+    lua_pushstring(L, "dirty");
+    lua_gettable(L, -2);
+    if (!lua_isnil(L, -1)) {
+        lua_pushvalue(L, -2);
+        lua_call(L, 1, 1);
+        is = lua_toboolean(L, -1);
+    } 
+    lua_pop(L, 1);
+    return is;
+}
+
+static t_socket collect_fd(lua_State *L, int tab, t_socket max_fd, 
+        int itab, fd_set *set) {
+    int i = 1;
+    if (lua_isnil(L, tab)) 
+        return max_fd;
+    while (1) {
+        t_socket fd;
+        lua_pushnumber(L, i);
+        lua_gettable(L, tab);
+        if (lua_isnil(L, -1)) {
+            lua_pop(L, 1);
+            break;
+        }
+        fd = getfd(L);
+        if (fd != SOCKET_INVALID) {
+            FD_SET(fd, set);
+            if (max_fd == SOCKET_INVALID || max_fd < fd) 
+                max_fd = fd;
+            lua_pushnumber(L, fd);
+            lua_pushvalue(L, -2);
+            lua_settable(L, itab);
+        }
+        lua_pop(L, 1);
+        i = i + 1;
+    }
+    return max_fd;
+}
+
+static int check_dirty(lua_State *L, int tab, int dtab, fd_set *set) {
+    int ndirty = 0, i = 1;
+    if (lua_isnil(L, tab)) 
+        return 0;
+    while (1) { 
+        t_socket fd;
+        lua_pushnumber(L, i);
+        lua_gettable(L, tab);
+        if (lua_isnil(L, -1)) {
+            lua_pop(L, 1);
+            break;
+        }
+        fd = getfd(L);
+        if (fd != SOCKET_INVALID && dirty(L)) {
+            lua_pushnumber(L, ++ndirty);
+            lua_pushvalue(L, -2);
+            lua_settable(L, dtab);
+            FD_CLR(fd, set);
+        }
+        lua_pop(L, 1);
+        i = i + 1;
+    }
+    return ndirty;
+}
+
+static void return_fd(lua_State *L, fd_set *set, t_socket max_fd, 
+        int itab, int tab, int start) {
+    t_socket fd;
+    for (fd = 0; fd < max_fd; fd++) {
+        if (FD_ISSET(fd, set)) {
+            lua_pushnumber(L, ++start);
+            lua_pushnumber(L, fd);
+            lua_gettable(L, itab);
+            lua_settable(L, tab);
+        }
+    }
+}
+
+static void make_assoc(lua_State *L, int tab) {
+    int i = 1, atab;
+    lua_newtable(L); atab = lua_gettop(L);
+    while (1) {
+        lua_pushnumber(L, i);
+        lua_gettable(L, tab);
+        if (!lua_isnil(L, -1)) {
+            lua_pushnumber(L, i);
+            lua_pushvalue(L, -2);
+            lua_settable(L, atab);
+            lua_pushnumber(L, i);
+            lua_settable(L, atab);
+        } else {
+            lua_pop(L, 1);
+            break;
+        }
+        i = i+1;
+    }
+}
+
diff --git a/src/luasocket/select.h b/src/luasocket/select.h
new file mode 100644
index 0000000000000000000000000000000000000000..aa3db4adf3bacb90e8a43af052b649cdac8a7aff
--- /dev/null
+++ b/src/luasocket/select.h
@@ -0,0 +1,17 @@
+#ifndef SELECT_H
+#define SELECT_H
+/*=========================================================================*\
+* Select implementation
+* LuaSocket toolkit
+*
+* Each object that can be passed to the select function has to export 
+* method getfd() which returns the descriptor to be passed to the
+* underlying select function. Another method, dirty(), should return 
+* true if there is data ready for reading (required for buffered input).
+*
+* RCS ID: $Id: select.h,v 1.7 2004/06/16 01:02:07 diego Exp $
+\*=========================================================================*/
+
+int select_open(lua_State *L);
+
+#endif /* SELECT_H */
diff --git a/src/luasocket/socket.h b/src/luasocket/socket.h
new file mode 100644
index 0000000000000000000000000000000000000000..656c7f5d5ce9392d1ae2e1228c7e784e32330446
--- /dev/null
+++ b/src/luasocket/socket.h
@@ -0,0 +1,76 @@
+#ifndef SOCKET_H
+#define SOCKET_H
+/*=========================================================================*\
+* Socket compatibilization module
+* LuaSocket toolkit
+*
+* BSD Sockets and WinSock are similar, but there are a few irritating
+* differences. Also, not all *nix platforms behave the same. This module
+* (and the associated usocket.h and wsocket.h) factor these differences and
+* creates a interface compatible with the io.h module.
+*
+* RCS ID: $Id: socket.h,v 1.20 2005/11/20 07:20:23 diego Exp $
+\*=========================================================================*/
+#include "io.h"
+
+/*=========================================================================*\
+* Platform specific compatibilization
+\*=========================================================================*/
+#ifdef _WIN32
+#include "wsocket.h"
+#else
+#include "usocket.h"
+#endif
+
+/*=========================================================================*\
+* The connect and accept functions accept a timeout and their
+* implementations are somewhat complicated. We chose to move
+* the timeout control into this module for these functions in
+* order to simplify the modules that use them. 
+\*=========================================================================*/
+#include "timeout.h"
+
+/* we are lazy... */
+typedef struct sockaddr SA;
+
+/*=========================================================================*\
+* Functions bellow implement a comfortable platform independent 
+* interface to sockets
+\*=========================================================================*/
+int socket_open(void);
+int socket_close(void);
+void socket_destroy(p_socket ps);
+void socket_shutdown(p_socket ps, int how); 
+int socket_sendto(p_socket ps, const char *data, size_t count, 
+        size_t *sent, SA *addr, socklen_t addr_len, p_timeout tm);
+int socket_recvfrom(p_socket ps, char *data, size_t count, 
+        size_t *got, SA *addr, socklen_t *addr_len, p_timeout tm);
+
+void socket_setnonblocking(p_socket ps);
+void socket_setblocking(p_socket ps);
+
+int socket_waitfd(p_socket ps, int sw, p_timeout tm);
+int socket_select(t_socket n, fd_set *rfds, fd_set *wfds, fd_set *efds, 
+        p_timeout tm);
+
+int socket_connect(p_socket ps, SA *addr, socklen_t addr_len, p_timeout tm); 
+int socket_create(p_socket ps, int domain, int type, int protocol);
+int socket_bind(p_socket ps, SA *addr, socklen_t addr_len); 
+int socket_listen(p_socket ps, int backlog);
+int socket_accept(p_socket ps, p_socket pa, SA *addr, 
+        socklen_t *addr_len, p_timeout tm);
+
+const char *socket_hoststrerror(int err);
+const char *socket_strerror(int err);
+
+/* these are perfect to use with the io abstraction module 
+   and the buffered input module */
+int socket_send(p_socket ps, const char *data, size_t count, 
+        size_t *sent, p_timeout tm);
+int socket_recv(p_socket ps, char *data, size_t count, size_t *got, p_timeout tm);
+const char *socket_ioerror(p_socket ps, int err);
+
+int socket_gethostbyaddr(const char *addr, socklen_t len, struct hostent **hp);
+int socket_gethostbyname(const char *addr, struct hostent **hp);
+
+#endif /* SOCKET_H */
diff --git a/src/luasocket/tcp.c b/src/luasocket/tcp.c
new file mode 100644
index 0000000000000000000000000000000000000000..6b8a79b4bc555dad97aac8e6c82b01c170bbec47
--- /dev/null
+++ b/src/luasocket/tcp.c
@@ -0,0 +1,339 @@
+/*=========================================================================*\
+* TCP object 
+* LuaSocket toolkit
+*
+* RCS ID: $Id: tcp.c,v 1.41 2005/10/07 04:40:59 diego Exp $
+\*=========================================================================*/
+#include <string.h> 
+
+#include "lua.h"
+#include "lauxlib.h"
+
+#include "auxiliar.h"
+#include "socket.h"
+#include "inet.h"
+#include "options.h"
+#include "tcp.h"
+
+/*=========================================================================*\
+* Internal function prototypes
+\*=========================================================================*/
+static int global_create(lua_State *L);
+static int meth_connect(lua_State *L);
+static int meth_listen(lua_State *L);
+static int meth_bind(lua_State *L);
+static int meth_send(lua_State *L);
+static int meth_getstats(lua_State *L);
+static int meth_setstats(lua_State *L);
+static int meth_getsockname(lua_State *L);
+static int meth_getpeername(lua_State *L);
+static int meth_shutdown(lua_State *L);
+static int meth_receive(lua_State *L);
+static int meth_accept(lua_State *L);
+static int meth_close(lua_State *L);
+static int meth_setoption(lua_State *L);
+static int meth_settimeout(lua_State *L);
+static int meth_getfd(lua_State *L);
+static int meth_setfd(lua_State *L);
+static int meth_dirty(lua_State *L);
+
+/* tcp object methods */
+static luaL_reg tcp[] = {
+    {"__gc",        meth_close},
+    {"__tostring",  auxiliar_tostring},
+    {"accept",      meth_accept},
+    {"bind",        meth_bind},
+    {"close",       meth_close},
+    {"connect",     meth_connect},
+    {"dirty",       meth_dirty},
+    {"getfd",       meth_getfd},
+    {"getpeername", meth_getpeername},
+    {"getsockname", meth_getsockname},
+    {"getstats",    meth_getstats},
+    {"setstats",    meth_setstats},
+    {"listen",      meth_listen},
+    {"receive",     meth_receive},
+    {"send",        meth_send},
+    {"setfd",       meth_setfd},
+    {"setoption",   meth_setoption},
+    {"setpeername", meth_connect},
+    {"setsockname", meth_bind},
+    {"settimeout",  meth_settimeout},
+    {"shutdown",    meth_shutdown},
+    {NULL,          NULL}
+};
+
+/* socket option handlers */
+static t_opt opt[] = {
+    {"keepalive",   opt_keepalive},
+    {"reuseaddr",   opt_reuseaddr},
+    {"tcp-nodelay", opt_tcp_nodelay},
+    {"linger",      opt_linger},
+    {NULL,          NULL}
+};
+
+/* functions in library namespace */
+static luaL_reg func[] = {
+    {"tcp", global_create},
+    {NULL, NULL}
+};
+
+/*-------------------------------------------------------------------------*\
+* Initializes module
+\*-------------------------------------------------------------------------*/
+int tcp_open(lua_State *L)
+{
+    /* create classes */
+    auxiliar_newclass(L, "tcp{master}", tcp);
+    auxiliar_newclass(L, "tcp{client}", tcp);
+    auxiliar_newclass(L, "tcp{server}", tcp);
+    /* create class groups */
+    auxiliar_add2group(L, "tcp{master}", "tcp{any}");
+    auxiliar_add2group(L, "tcp{client}", "tcp{any}");
+    auxiliar_add2group(L, "tcp{server}", "tcp{any}");
+    /* define library functions */
+    luaL_openlib(L, NULL, func, 0); 
+    return 0;
+}
+
+/*=========================================================================*\
+* Lua methods
+\*=========================================================================*/
+/*-------------------------------------------------------------------------*\
+* Just call buffered IO methods
+\*-------------------------------------------------------------------------*/
+static int meth_send(lua_State *L) {
+    p_tcp tcp = (p_tcp) auxiliar_checkclass(L, "tcp{client}", 1);
+    return buffer_meth_send(L, &tcp->buf);
+}
+
+static int meth_receive(lua_State *L) {
+    p_tcp tcp = (p_tcp) auxiliar_checkclass(L, "tcp{client}", 1);
+    return buffer_meth_receive(L, &tcp->buf);
+}
+
+static int meth_getstats(lua_State *L) {
+    p_tcp tcp = (p_tcp) auxiliar_checkclass(L, "tcp{client}", 1);
+    return buffer_meth_getstats(L, &tcp->buf);
+}
+
+static int meth_setstats(lua_State *L) {
+    p_tcp tcp = (p_tcp) auxiliar_checkclass(L, "tcp{client}", 1);
+    return buffer_meth_setstats(L, &tcp->buf);
+}
+
+/*-------------------------------------------------------------------------*\
+* Just call option handler
+\*-------------------------------------------------------------------------*/
+static int meth_setoption(lua_State *L)
+{
+    p_tcp tcp = (p_tcp) auxiliar_checkgroup(L, "tcp{any}", 1);
+    return opt_meth_setoption(L, opt, &tcp->sock);
+}
+
+/*-------------------------------------------------------------------------*\
+* Select support methods
+\*-------------------------------------------------------------------------*/
+static int meth_getfd(lua_State *L)
+{
+    p_tcp tcp = (p_tcp) auxiliar_checkgroup(L, "tcp{any}", 1);
+    lua_pushnumber(L, (int) tcp->sock);
+    return 1;
+}
+
+/* this is very dangerous, but can be handy for those that are brave enough */
+static int meth_setfd(lua_State *L)
+{
+    p_tcp tcp = (p_tcp) auxiliar_checkgroup(L, "tcp{any}", 1);
+    tcp->sock = (t_socket) luaL_checknumber(L, 2); 
+    return 0;
+}
+
+static int meth_dirty(lua_State *L)
+{
+    p_tcp tcp = (p_tcp) auxiliar_checkgroup(L, "tcp{any}", 1);
+    lua_pushboolean(L, !buffer_isempty(&tcp->buf));
+    return 1;
+}
+
+/*-------------------------------------------------------------------------*\
+* Waits for and returns a client object attempting connection to the 
+* server object 
+\*-------------------------------------------------------------------------*/
+static int meth_accept(lua_State *L)
+{
+    p_tcp server = (p_tcp) auxiliar_checkclass(L, "tcp{server}", 1);
+    p_timeout tm = timeout_markstart(&server->tm);
+    t_socket sock;
+    int err = socket_accept(&server->sock, &sock, NULL, NULL, tm);
+    /* if successful, push client socket */
+    if (err == IO_DONE) {
+        p_tcp clnt = (p_tcp) lua_newuserdata(L, sizeof(t_tcp));
+        auxiliar_setclass(L, "tcp{client}", -1);
+        /* initialize structure fields */
+        socket_setnonblocking(&sock);
+        clnt->sock = sock;
+        io_init(&clnt->io, (p_send) socket_send, (p_recv) socket_recv, 
+                (p_error) socket_ioerror, &clnt->sock);
+        timeout_init(&clnt->tm, -1, -1);
+        buffer_init(&clnt->buf, &clnt->io, &clnt->tm);
+        return 1;
+    } else {
+        lua_pushnil(L); 
+        lua_pushstring(L, socket_strerror(err));
+        return 2;
+    }
+}
+
+/*-------------------------------------------------------------------------*\
+* Binds an object to an address 
+\*-------------------------------------------------------------------------*/
+static int meth_bind(lua_State *L)
+{
+    p_tcp tcp = (p_tcp) auxiliar_checkclass(L, "tcp{master}", 1);
+    const char *address =  luaL_checkstring(L, 2);
+    unsigned short port = (unsigned short) luaL_checknumber(L, 3);
+    const char *err = inet_trybind(&tcp->sock, address, port);
+    if (err) {
+        lua_pushnil(L);
+        lua_pushstring(L, err);
+        return 2;
+    }
+    lua_pushnumber(L, 1);
+    return 1;
+}
+
+/*-------------------------------------------------------------------------*\
+* Turns a master tcp object into a client object.
+\*-------------------------------------------------------------------------*/
+static int meth_connect(lua_State *L)
+{
+    p_tcp tcp = (p_tcp) auxiliar_checkgroup(L, "tcp{any}", 1);
+    const char *address =  luaL_checkstring(L, 2);
+    unsigned short port = (unsigned short) luaL_checknumber(L, 3);
+    p_timeout tm = timeout_markstart(&tcp->tm);
+    const char *err = inet_tryconnect(&tcp->sock, address, port, tm);
+    /* have to set the class even if it failed due to non-blocking connects */
+    auxiliar_setclass(L, "tcp{client}", 1);
+    if (err) {
+        lua_pushnil(L);
+        lua_pushstring(L, err);
+        return 2;
+    }
+    /* turn master object into a client object */
+    lua_pushnumber(L, 1);
+    return 1;
+}
+
+/*-------------------------------------------------------------------------*\
+* Closes socket used by object 
+\*-------------------------------------------------------------------------*/
+static int meth_close(lua_State *L)
+{
+    p_tcp tcp = (p_tcp) auxiliar_checkgroup(L, "tcp{any}", 1);
+    socket_destroy(&tcp->sock);
+    lua_pushnumber(L, 1);
+    return 1;
+}
+
+/*-------------------------------------------------------------------------*\
+* Puts the sockt in listen mode
+\*-------------------------------------------------------------------------*/
+static int meth_listen(lua_State *L)
+{
+    p_tcp tcp = (p_tcp) auxiliar_checkclass(L, "tcp{master}", 1);
+    int backlog = (int) luaL_optnumber(L, 2, 32);
+    int err = socket_listen(&tcp->sock, backlog);
+    if (err != IO_DONE) {
+        lua_pushnil(L);
+        lua_pushstring(L, socket_strerror(err));
+        return 2;
+    }
+    /* turn master object into a server object */
+    auxiliar_setclass(L, "tcp{server}", 1);
+    lua_pushnumber(L, 1);
+    return 1;
+}
+
+/*-------------------------------------------------------------------------*\
+* Shuts the connection down partially
+\*-------------------------------------------------------------------------*/
+static int meth_shutdown(lua_State *L)
+{
+    p_tcp tcp = (p_tcp) auxiliar_checkclass(L, "tcp{client}", 1);
+    const char *how = luaL_optstring(L, 2, "both");
+    switch (how[0]) {
+        case 'b':
+            if (strcmp(how, "both")) goto error;
+            socket_shutdown(&tcp->sock, 2);
+            break;
+        case 's':
+            if (strcmp(how, "send")) goto error;
+            socket_shutdown(&tcp->sock, 1);
+            break;
+        case 'r':
+            if (strcmp(how, "receive")) goto error;
+            socket_shutdown(&tcp->sock, 0);
+            break;
+    }
+    lua_pushnumber(L, 1);
+    return 1;
+error:
+    luaL_argerror(L, 2, "invalid shutdown method");
+    return 0;
+}
+
+/*-------------------------------------------------------------------------*\
+* Just call inet methods
+\*-------------------------------------------------------------------------*/
+static int meth_getpeername(lua_State *L)
+{
+    p_tcp tcp = (p_tcp) auxiliar_checkgroup(L, "tcp{any}", 1);
+    return inet_meth_getpeername(L, &tcp->sock);
+}
+
+static int meth_getsockname(lua_State *L)
+{
+    p_tcp tcp = (p_tcp) auxiliar_checkgroup(L, "tcp{any}", 1);
+    return inet_meth_getsockname(L, &tcp->sock);
+}
+
+/*-------------------------------------------------------------------------*\
+* Just call tm methods
+\*-------------------------------------------------------------------------*/
+static int meth_settimeout(lua_State *L)
+{
+    p_tcp tcp = (p_tcp) auxiliar_checkgroup(L, "tcp{any}", 1);
+    return timeout_meth_settimeout(L, &tcp->tm);
+}
+
+/*=========================================================================*\
+* Library functions
+\*=========================================================================*/
+/*-------------------------------------------------------------------------*\
+* Creates a master tcp object 
+\*-------------------------------------------------------------------------*/
+static int global_create(lua_State *L)
+{
+    t_socket sock;
+    const char *err = inet_trycreate(&sock, SOCK_STREAM);
+    /* try to allocate a system socket */
+    if (!err) { 
+        /* allocate tcp object */
+        p_tcp tcp = (p_tcp) lua_newuserdata(L, sizeof(t_tcp));
+        /* set its type as master object */
+        auxiliar_setclass(L, "tcp{master}", -1);
+        /* initialize remaining structure fields */
+        socket_setnonblocking(&sock);
+        tcp->sock = sock;
+        io_init(&tcp->io, (p_send) socket_send, (p_recv) socket_recv, 
+                (p_error) socket_ioerror, &tcp->sock);
+        timeout_init(&tcp->tm, -1, -1);
+        buffer_init(&tcp->buf, &tcp->io, &tcp->tm);
+        return 1;
+    } else {
+        lua_pushnil(L);
+        lua_pushstring(L, err);
+        return 2;
+    }
+}
diff --git a/src/luasocket/tcp.h b/src/luasocket/tcp.h
new file mode 100644
index 0000000000000000000000000000000000000000..511357f371ad9d5e17ffa28861964578b5e4c179
--- /dev/null
+++ b/src/luasocket/tcp.h
@@ -0,0 +1,36 @@
+#ifndef TCP_H
+#define TCP_H
+/*=========================================================================*\
+* TCP object
+* LuaSocket toolkit
+*
+* The tcp.h module is basicly a glue that puts together modules buffer.h,
+* timeout.h socket.h and inet.h to provide the LuaSocket TCP (AF_INET,
+* SOCK_STREAM) support.
+*
+* Three classes are defined: master, client and server. The master class is
+* a newly created tcp object, that has not been bound or connected. Server
+* objects are tcp objects bound to some local address. Client objects are
+* tcp objects either connected to some address or returned by the accept
+* method of a server object.
+*
+* RCS ID: $Id: tcp.h,v 1.7 2005/10/07 04:40:59 diego Exp $
+\*=========================================================================*/
+#include "lua.h"
+
+#include "buffer.h"
+#include "timeout.h"
+#include "socket.h"
+
+typedef struct t_tcp_ {
+    t_socket sock;
+    t_io io;
+    t_buffer buf;
+    t_timeout tm;
+} t_tcp;
+
+typedef t_tcp *p_tcp;
+
+int tcp_open(lua_State *L);
+
+#endif /* TCP_H */
diff --git a/src/luasocket/timeout.c b/src/luasocket/timeout.c
new file mode 100644
index 0000000000000000000000000000000000000000..c1df102181119b083be04cea81ba848cc1224a78
--- /dev/null
+++ b/src/luasocket/timeout.c
@@ -0,0 +1,207 @@
+/*=========================================================================*\
+* Timeout management functions
+* LuaSocket toolkit
+*
+* RCS ID: $Id: timeout.c,v 1.30 2005/10/07 04:40:59 diego Exp $
+\*=========================================================================*/
+#include <stdio.h>
+
+#include "lua.h"
+#include "lauxlib.h"
+
+#include "auxiliar.h"
+#include "timeout.h"
+
+#ifdef _WIN32
+#include <windows.h>
+#else
+#include <time.h>
+#include <sys/time.h>
+#endif
+
+/* min and max macros */
+#ifndef MIN
+#define MIN(x, y) ((x) < (y) ? x : y)
+#endif
+#ifndef MAX
+#define MAX(x, y) ((x) > (y) ? x : y)
+#endif
+
+/*=========================================================================*\
+* Internal function prototypes
+\*=========================================================================*/
+static int timeout_lua_gettime(lua_State *L);
+static int timeout_lua_sleep(lua_State *L);
+
+static luaL_reg func[] = {
+    { "gettime", timeout_lua_gettime },
+    { "sleep", timeout_lua_sleep },
+    { NULL, NULL }
+};
+
+/*=========================================================================*\
+* Exported functions.
+\*=========================================================================*/
+/*-------------------------------------------------------------------------*\
+* Initialize structure
+\*-------------------------------------------------------------------------*/
+void timeout_init(p_timeout tm, double block, double total) {
+    tm->block = block;
+    tm->total = total;
+}
+
+/*-------------------------------------------------------------------------*\
+* Determines how much time we have left for the next system call,
+* if the previous call was successful 
+* Input
+*   tm: timeout control structure
+* Returns
+*   the number of ms left or -1 if there is no time limit
+\*-------------------------------------------------------------------------*/
+double timeout_get(p_timeout tm) {
+    if (tm->block < 0.0 && tm->total < 0.0) {
+        return -1;
+    } else if (tm->block < 0.0) {
+        double t = tm->total - timeout_gettime() + tm->start;
+        return MAX(t, 0.0);
+    } else if (tm->total < 0.0) {
+        return tm->block;
+    } else {
+        double t = tm->total - timeout_gettime() + tm->start;
+        return MIN(tm->block, MAX(t, 0.0));
+    }
+}
+
+/*-------------------------------------------------------------------------*\
+* Returns time since start of operation
+* Input
+*   tm: timeout control structure
+* Returns
+*   start field of structure
+\*-------------------------------------------------------------------------*/
+double timeout_getstart(p_timeout tm) {
+    return tm->start;
+}
+
+/*-------------------------------------------------------------------------*\
+* Determines how much time we have left for the next system call,
+* if the previous call was a failure
+* Input
+*   tm: timeout control structure
+* Returns
+*   the number of ms left or -1 if there is no time limit
+\*-------------------------------------------------------------------------*/
+double timeout_getretry(p_timeout tm) {
+    if (tm->block < 0.0 && tm->total < 0.0) {
+        return -1;
+    } else if (tm->block < 0.0) {
+        double t = tm->total - timeout_gettime() + tm->start;
+        return MAX(t, 0.0);
+    } else if (tm->total < 0.0) {
+        double t = tm->block - timeout_gettime() + tm->start;
+        return MAX(t, 0.0);
+    } else {
+        double t = tm->total - timeout_gettime() + tm->start;
+        return MIN(tm->block, MAX(t, 0.0));
+    }
+}
+
+/*-------------------------------------------------------------------------*\
+* Marks the operation start time in structure 
+* Input
+*   tm: timeout control structure
+\*-------------------------------------------------------------------------*/
+p_timeout timeout_markstart(p_timeout tm) {
+    tm->start = timeout_gettime();
+    return tm;
+}
+
+/*-------------------------------------------------------------------------*\
+* Gets time in s, relative to January 1, 1970 (UTC) 
+* Returns
+*   time in s.
+\*-------------------------------------------------------------------------*/
+#ifdef _WIN32
+double timeout_gettime(void) {
+    FILETIME ft;
+    double t;
+    GetSystemTimeAsFileTime(&ft);
+    /* Windows file time (time since January 1, 1601 (UTC)) */
+    t  = ft.dwLowDateTime/1.0e7 + ft.dwHighDateTime*(4294967296.0/1.0e7);
+    /* convert to Unix Epoch time (time since January 1, 1970 (UTC)) */
+    return (t - 11644473600.0);
+}
+#else
+double timeout_gettime(void) {
+    struct timeval v;
+    gettimeofday(&v, (struct timezone *) NULL);
+    /* Unix Epoch time (time since January 1, 1970 (UTC)) */
+    return v.tv_sec + v.tv_usec/1.0e6;
+}
+#endif
+
+/*-------------------------------------------------------------------------*\
+* Initializes module
+\*-------------------------------------------------------------------------*/
+int timeout_open(lua_State *L) {
+    luaL_openlib(L, NULL, func, 0);
+    return 0;
+}
+
+/*-------------------------------------------------------------------------*\
+* Sets timeout values for IO operations
+* Lua Input: base, time [, mode]
+*   time: time out value in seconds
+*   mode: "b" for block timeout, "t" for total timeout. (default: b)
+\*-------------------------------------------------------------------------*/
+int timeout_meth_settimeout(lua_State *L, p_timeout tm) {
+    double t = luaL_optnumber(L, 2, -1);
+    const char *mode = luaL_optstring(L, 3, "b");
+    switch (*mode) {
+        case 'b':
+            tm->block = t; 
+            break;
+        case 'r': case 't':
+            tm->total = t;
+            break;
+        default:
+            luaL_argcheck(L, 0, 3, "invalid timeout mode");
+            break;
+    }
+    lua_pushnumber(L, 1);
+    return 1;
+}
+
+/*=========================================================================*\
+* Test support functions
+\*=========================================================================*/
+/*-------------------------------------------------------------------------*\
+* Returns the time the system has been up, in secconds.
+\*-------------------------------------------------------------------------*/
+static int timeout_lua_gettime(lua_State *L)
+{
+    lua_pushnumber(L, timeout_gettime());
+    return 1;
+}
+
+/*-------------------------------------------------------------------------*\
+* Sleep for n seconds.
+\*-------------------------------------------------------------------------*/
+int timeout_lua_sleep(lua_State *L)
+{
+    double n = luaL_checknumber(L, 1);
+#ifdef _WIN32
+    Sleep((int)(n*1000));
+#else
+    struct timespec t, r;
+    t.tv_sec = (int) n;
+    n -= t.tv_sec;
+    t.tv_nsec = (int) (n * 1000000000);
+    if (t.tv_nsec >= 1000000000) t.tv_nsec = 999999999;
+    while (nanosleep(&t, &r) != 0) {
+        t.tv_sec = r.tv_sec;
+        t.tv_nsec = r.tv_nsec;
+    }
+#endif
+    return 0;
+}
diff --git a/src/luasocket/timeout.h b/src/luasocket/timeout.h
new file mode 100644
index 0000000000000000000000000000000000000000..d2d8964100f0bd93d6e8e14db36e4cded5e8e164
--- /dev/null
+++ b/src/luasocket/timeout.h
@@ -0,0 +1,30 @@
+#ifndef TIMEOUT_H
+#define TIMEOUT_H
+/*=========================================================================*\
+* Timeout management functions
+* LuaSocket toolkit
+*
+* RCS ID: $Id: timeout.h,v 1.14 2005/10/07 04:40:59 diego Exp $
+\*=========================================================================*/
+#include "lua.h"
+
+/* timeout control structure */
+typedef struct t_timeout_ {
+    double block;          /* maximum time for blocking calls */
+    double total;          /* total number of miliseconds for operation */
+    double start;          /* time of start of operation */
+} t_timeout;
+typedef t_timeout *p_timeout;
+
+int timeout_open(lua_State *L);
+void timeout_init(p_timeout tm, double block, double total);
+double timeout_get(p_timeout tm);
+double timeout_getretry(p_timeout tm);
+p_timeout timeout_markstart(p_timeout tm);
+double timeout_getstart(p_timeout tm);
+double timeout_gettime(void);
+int timeout_meth_settimeout(lua_State *L, p_timeout tm);
+
+#define timeout_iszero(tm)   ((tm)->block == 0.0)
+
+#endif /* TIMEOUT_H */
diff --git a/src/luasocket/udp.c b/src/luasocket/udp.c
new file mode 100644
index 0000000000000000000000000000000000000000..fc25aa027dc0c51a694c7c42207465d24d94680b
--- /dev/null
+++ b/src/luasocket/udp.c
@@ -0,0 +1,336 @@
+/*=========================================================================*\
+* UDP object 
+* LuaSocket toolkit
+*
+* RCS ID: $Id: udp.c,v 1.29 2005/10/07 04:40:59 diego Exp $
+\*=========================================================================*/
+#include <string.h> 
+
+#include "lua.h"
+#include "lauxlib.h"
+
+#include "auxiliar.h"
+#include "socket.h"
+#include "inet.h"
+#include "options.h"
+#include "udp.h"
+
+/* min and max macros */
+#ifndef MIN
+#define MIN(x, y) ((x) < (y) ? x : y)
+#endif 
+#ifndef MAX
+#define MAX(x, y) ((x) > (y) ? x : y)
+#endif 
+
+/*=========================================================================*\
+* Internal function prototypes
+\*=========================================================================*/
+static int global_create(lua_State *L);
+static int meth_send(lua_State *L);
+static int meth_sendto(lua_State *L);
+static int meth_receive(lua_State *L);
+static int meth_receivefrom(lua_State *L);
+static int meth_getsockname(lua_State *L);
+static int meth_getpeername(lua_State *L);
+static int meth_setsockname(lua_State *L);
+static int meth_setpeername(lua_State *L);
+static int meth_close(lua_State *L);
+static int meth_setoption(lua_State *L);
+static int meth_settimeout(lua_State *L);
+static int meth_getfd(lua_State *L);
+static int meth_setfd(lua_State *L);
+static int meth_dirty(lua_State *L);
+
+/* udp object methods */
+static luaL_reg udp[] = {
+    {"__gc",        meth_close},
+    {"__tostring",  auxiliar_tostring},
+    {"close",       meth_close},
+    {"dirty",       meth_dirty},
+    {"getfd",       meth_getfd},
+    {"getpeername", meth_getpeername},
+    {"getsockname", meth_getsockname},
+    {"receive",     meth_receive},
+    {"receivefrom", meth_receivefrom},
+    {"send",        meth_send},
+    {"sendto",      meth_sendto},
+    {"setfd",       meth_setfd},
+    {"setoption",   meth_setoption},
+    {"setpeername", meth_setpeername},
+    {"setsockname", meth_setsockname},
+    {"settimeout",  meth_settimeout},
+    {NULL,          NULL}
+};
+
+/* socket options */
+static t_opt opt[] = {
+    {"dontroute",          opt_dontroute},
+    {"broadcast",          opt_broadcast},
+    {"reuseaddr",          opt_reuseaddr},
+    {"ip-multicast-ttl",   opt_ip_multicast_ttl},
+    {"ip-multicast-loop",  opt_ip_multicast_loop},
+    {"ip-add-membership",  opt_ip_add_membership},
+    {"ip-drop-membership", opt_ip_drop_membersip},
+    {NULL,          NULL}
+};
+
+/* functions in library namespace */
+static luaL_reg func[] = {
+    {"udp", global_create},
+    {NULL, NULL}
+};
+
+/*-------------------------------------------------------------------------*\
+* Initializes module
+\*-------------------------------------------------------------------------*/
+int udp_open(lua_State *L)
+{
+    /* create classes */
+    auxiliar_newclass(L, "udp{connected}", udp);
+    auxiliar_newclass(L, "udp{unconnected}", udp);
+    /* create class groups */
+    auxiliar_add2group(L, "udp{connected}",   "udp{any}");
+    auxiliar_add2group(L, "udp{unconnected}", "udp{any}");
+    auxiliar_add2group(L, "udp{connected}",   "select{able}");
+    auxiliar_add2group(L, "udp{unconnected}", "select{able}");
+    /* define library functions */
+    luaL_openlib(L, NULL, func, 0); 
+    return 0;
+}
+
+/*=========================================================================*\
+* Lua methods
+\*=========================================================================*/
+const char *udp_strerror(int err) {
+    /* a 'closed' error on an unconnected means the target address was not
+     * accepted by the transport layer */
+    if (err == IO_CLOSED) return "refused";
+    else return socket_strerror(err);
+}
+
+/*-------------------------------------------------------------------------*\
+* Send data through connected udp socket
+\*-------------------------------------------------------------------------*/
+static int meth_send(lua_State *L) {
+    p_udp udp = (p_udp) auxiliar_checkclass(L, "udp{connected}", 1);
+    p_timeout tm = &udp->tm;
+    size_t count, sent = 0;
+    int err;
+    const char *data = luaL_checklstring(L, 2, &count);
+    timeout_markstart(tm);
+    err = socket_send(&udp->sock, data, count, &sent, tm);
+    if (err != IO_DONE) {
+        lua_pushnil(L);
+        lua_pushstring(L, udp_strerror(err));
+        return 2;
+    }
+    lua_pushnumber(L, sent);
+    return 1;
+}
+
+/*-------------------------------------------------------------------------*\
+* Send data through unconnected udp socket
+\*-------------------------------------------------------------------------*/
+static int meth_sendto(lua_State *L) {
+    p_udp udp = (p_udp) auxiliar_checkclass(L, "udp{unconnected}", 1);
+    size_t count, sent = 0;
+    const char *data = luaL_checklstring(L, 2, &count);
+    const char *ip = luaL_checkstring(L, 3);
+    unsigned short port = (unsigned short) luaL_checknumber(L, 4);
+    p_timeout tm = &udp->tm;
+    struct sockaddr_in addr;
+    int err;
+    memset(&addr, 0, sizeof(addr));
+    if (!inet_aton(ip, &addr.sin_addr)) 
+        luaL_argerror(L, 3, "invalid ip address");
+    addr.sin_family = AF_INET;
+    addr.sin_port = htons(port);
+    timeout_markstart(tm);
+    err = socket_sendto(&udp->sock, data, count, &sent, 
+            (SA *) &addr, sizeof(addr), tm);
+    if (err != IO_DONE) {
+        lua_pushnil(L);
+        lua_pushstring(L, udp_strerror(err));
+        return 2;
+    }
+    lua_pushnumber(L, sent);
+    return 1;
+}
+
+/*-------------------------------------------------------------------------*\
+* Receives data from a UDP socket
+\*-------------------------------------------------------------------------*/
+static int meth_receive(lua_State *L) {
+    p_udp udp = (p_udp) auxiliar_checkgroup(L, "udp{any}", 1);
+    char buffer[UDP_DATAGRAMSIZE];
+    size_t got, count = (size_t) luaL_optnumber(L, 2, sizeof(buffer));
+    int err;
+    p_timeout tm = &udp->tm;
+    count = MIN(count, sizeof(buffer));
+    timeout_markstart(tm);
+    err = socket_recv(&udp->sock, buffer, count, &got, tm);
+    if (err != IO_DONE) {
+        lua_pushnil(L);
+        lua_pushstring(L, udp_strerror(err));
+        return 2;
+    }
+    lua_pushlstring(L, buffer, got);
+    return 1;
+}
+
+/*-------------------------------------------------------------------------*\
+* Receives data and sender from a UDP socket
+\*-------------------------------------------------------------------------*/
+static int meth_receivefrom(lua_State *L) {
+    p_udp udp = (p_udp) auxiliar_checkclass(L, "udp{unconnected}", 1);
+    struct sockaddr_in addr;
+    socklen_t addr_len = sizeof(addr);
+    char buffer[UDP_DATAGRAMSIZE];
+    size_t got, count = (size_t) luaL_optnumber(L, 2, sizeof(buffer));
+    int err;
+    p_timeout tm = &udp->tm;
+    timeout_markstart(tm);
+    count = MIN(count, sizeof(buffer));
+    err = socket_recvfrom(&udp->sock, buffer, count, &got, 
+            (SA *) &addr, &addr_len, tm);
+    if (err == IO_DONE) {
+        lua_pushlstring(L, buffer, got);
+        lua_pushstring(L, inet_ntoa(addr.sin_addr));
+        lua_pushnumber(L, ntohs(addr.sin_port));
+        return 3;
+    } else {
+        lua_pushnil(L);
+        lua_pushstring(L, udp_strerror(err));
+        return 2;
+    }
+}
+
+/*-------------------------------------------------------------------------*\
+* Select support methods
+\*-------------------------------------------------------------------------*/
+static int meth_getfd(lua_State *L) {
+    p_udp udp = (p_udp) auxiliar_checkgroup(L, "udp{any}", 1);
+    lua_pushnumber(L, (int) udp->sock);
+    return 1;
+}
+
+/* this is very dangerous, but can be handy for those that are brave enough */
+static int meth_setfd(lua_State *L) {
+    p_udp udp = (p_udp) auxiliar_checkgroup(L, "udp{any}", 1);
+    udp->sock = (t_socket) luaL_checknumber(L, 2);
+    return 0;
+}
+
+static int meth_dirty(lua_State *L) {
+    p_udp udp = (p_udp) auxiliar_checkgroup(L, "udp{any}", 1);
+    (void) udp;
+    lua_pushboolean(L, 0);
+    return 1;
+}
+
+/*-------------------------------------------------------------------------*\
+* Just call inet methods
+\*-------------------------------------------------------------------------*/
+static int meth_getpeername(lua_State *L) {
+    p_udp udp = (p_udp) auxiliar_checkclass(L, "udp{connected}", 1);
+    return inet_meth_getpeername(L, &udp->sock);
+}
+
+static int meth_getsockname(lua_State *L) {
+    p_udp udp = (p_udp) auxiliar_checkgroup(L, "udp{any}", 1);
+    return inet_meth_getsockname(L, &udp->sock);
+}
+
+/*-------------------------------------------------------------------------*\
+* Just call option handler
+\*-------------------------------------------------------------------------*/
+static int meth_setoption(lua_State *L) {
+    p_udp udp = (p_udp) auxiliar_checkgroup(L, "udp{any}", 1);
+    return opt_meth_setoption(L, opt, &udp->sock);
+}
+
+/*-------------------------------------------------------------------------*\
+* Just call tm methods
+\*-------------------------------------------------------------------------*/
+static int meth_settimeout(lua_State *L) {
+    p_udp udp = (p_udp) auxiliar_checkgroup(L, "udp{any}", 1);
+    return timeout_meth_settimeout(L, &udp->tm);
+}
+
+/*-------------------------------------------------------------------------*\
+* Turns a master udp object into a client object.
+\*-------------------------------------------------------------------------*/
+static int meth_setpeername(lua_State *L) {
+    p_udp udp = (p_udp) auxiliar_checkgroup(L, "udp{any}", 1);
+    p_timeout tm = &udp->tm;
+    const char *address =  luaL_checkstring(L, 2);
+    int connecting = strcmp(address, "*");
+    unsigned short port = connecting ? 
+        (unsigned short) luaL_checknumber(L, 3) : 
+        (unsigned short) luaL_optnumber(L, 3, 0);
+    const char *err = inet_tryconnect(&udp->sock, address, port, tm);
+    if (err) {
+        lua_pushnil(L);
+        lua_pushstring(L, err);
+        return 2;
+    }
+    /* change class to connected or unconnected depending on address */
+    if (connecting) auxiliar_setclass(L, "udp{connected}", 1);
+    else auxiliar_setclass(L, "udp{unconnected}", 1);
+    lua_pushnumber(L, 1);
+    return 1;
+}
+
+/*-------------------------------------------------------------------------*\
+* Closes socket used by object 
+\*-------------------------------------------------------------------------*/
+static int meth_close(lua_State *L) {
+    p_udp udp = (p_udp) auxiliar_checkgroup(L, "udp{any}", 1);
+    socket_destroy(&udp->sock);
+    lua_pushnumber(L, 1);
+    return 1;
+}
+
+/*-------------------------------------------------------------------------*\
+* Turns a master object into a server object
+\*-------------------------------------------------------------------------*/
+static int meth_setsockname(lua_State *L) {
+    p_udp udp = (p_udp) auxiliar_checkclass(L, "udp{unconnected}", 1);
+    const char *address =  luaL_checkstring(L, 2);
+    unsigned short port = (unsigned short) luaL_checknumber(L, 3);
+    const char *err = inet_trybind(&udp->sock, address, port);
+    if (err) {
+        lua_pushnil(L);
+        lua_pushstring(L, err);
+        return 2;
+    }
+    lua_pushnumber(L, 1);
+    return 1;
+}
+
+/*=========================================================================*\
+* Library functions
+\*=========================================================================*/
+/*-------------------------------------------------------------------------*\
+* Creates a master udp object 
+\*-------------------------------------------------------------------------*/
+static int global_create(lua_State *L) {
+    t_socket sock;
+    const char *err = inet_trycreate(&sock, SOCK_DGRAM);
+    /* try to allocate a system socket */
+    if (!err) { 
+        /* allocate tcp object */
+        p_udp udp = (p_udp) lua_newuserdata(L, sizeof(t_udp));
+        auxiliar_setclass(L, "udp{unconnected}", -1);
+        /* initialize remaining structure fields */
+        socket_setnonblocking(&sock);
+        udp->sock = sock;
+        timeout_init(&udp->tm, -1, -1);
+        return 1;
+    } else {
+        lua_pushnil(L);
+        lua_pushstring(L, err);
+        return 2;
+    }
+}
diff --git a/src/luasocket/udp.h b/src/luasocket/udp.h
new file mode 100644
index 0000000000000000000000000000000000000000..28017121714691bb99963bb6b57058dcf169fa93
--- /dev/null
+++ b/src/luasocket/udp.h
@@ -0,0 +1,33 @@
+#ifndef UDP_H
+#define UDP_H
+/*=========================================================================*\
+* UDP object
+* LuaSocket toolkit
+*
+* The udp.h module provides LuaSocket with support for UDP protocol
+* (AF_INET, SOCK_DGRAM).
+*
+* Two classes are defined: connected and unconnected. UDP objects are
+* originally unconnected. They can be "connected" to a given address 
+* with a call to the setpeername function. The same function can be used to
+* break the connection.
+*
+* RCS ID: $Id: udp.h,v 1.10 2005/10/07 04:40:59 diego Exp $
+\*=========================================================================*/
+#include "lua.h"
+
+#include "timeout.h"
+#include "socket.h"
+
+/* can't be larger than wsocket.c MAXCHUNK!!! */
+#define UDP_DATAGRAMSIZE 8192
+
+typedef struct t_udp_ {
+    t_socket sock;
+    t_timeout tm;
+} t_udp;
+typedef t_udp *p_udp;
+
+int udp_open(lua_State *L);
+
+#endif /* UDP_H */
diff --git a/src/luasocket/unix.c b/src/luasocket/unix.c
new file mode 100644
index 0000000000000000000000000000000000000000..158d319a5f2d9eb44eaa2c6ebb03e2f6e71dafc4
--- /dev/null
+++ b/src/luasocket/unix.c
@@ -0,0 +1,356 @@
+/*=========================================================================*\
+* Unix domain socket 
+* LuaSocket toolkit
+*
+* RCS ID: $Id: unix.c,v 1.13 2006/03/13 07:16:39 diego Exp $
+\*=========================================================================*/
+#include <string.h> 
+
+#include "lua.h"
+#include "lauxlib.h"
+
+#include "auxiliar.h"
+#include "socket.h"
+#include "options.h"
+#include "unix.h"
+#include <sys/un.h> 
+
+/*=========================================================================*\
+* Internal function prototypes
+\*=========================================================================*/
+static int global_create(lua_State *L);
+static int meth_connect(lua_State *L);
+static int meth_listen(lua_State *L);
+static int meth_bind(lua_State *L);
+static int meth_send(lua_State *L);
+static int meth_shutdown(lua_State *L);
+static int meth_receive(lua_State *L);
+static int meth_accept(lua_State *L);
+static int meth_close(lua_State *L);
+static int meth_setoption(lua_State *L);
+static int meth_settimeout(lua_State *L);
+static int meth_getfd(lua_State *L);
+static int meth_setfd(lua_State *L);
+static int meth_dirty(lua_State *L);
+static int meth_getstats(lua_State *L);
+static int meth_setstats(lua_State *L);
+
+static const char *unix_tryconnect(p_unix un, const char *path);
+static const char *unix_trybind(p_unix un, const char *path);
+
+/* unix object methods */
+static luaL_reg un[] = {
+    {"__gc",        meth_close},
+    {"__tostring",  auxiliar_tostring},
+    {"accept",      meth_accept},
+    {"bind",        meth_bind},
+    {"close",       meth_close},
+    {"connect",     meth_connect},
+    {"dirty",       meth_dirty},
+    {"getfd",       meth_getfd},
+    {"getstats",    meth_getstats},
+    {"setstats",    meth_setstats},
+    {"listen",      meth_listen},
+    {"receive",     meth_receive},
+    {"send",        meth_send},
+    {"setfd",       meth_setfd},
+    {"setoption",   meth_setoption},
+    {"setpeername", meth_connect},
+    {"setsockname", meth_bind},
+    {"settimeout",  meth_settimeout},
+    {"shutdown",    meth_shutdown},
+    {NULL,          NULL}
+};
+
+/* socket option handlers */
+static t_opt opt[] = {
+    {"keepalive",   opt_keepalive},
+    {"reuseaddr",   opt_reuseaddr},
+    {"linger",      opt_linger},
+    {NULL,          NULL}
+};
+
+/* our socket creation function */
+static luaL_reg func[] = {
+    {"unix", global_create},
+    {NULL,          NULL}
+};
+
+
+/*-------------------------------------------------------------------------*\
+* Initializes module
+\*-------------------------------------------------------------------------*/
+int luaopen_socket_unix(lua_State *L) {
+    /* create classes */
+    auxiliar_newclass(L, "unix{master}", un);
+    auxiliar_newclass(L, "unix{client}", un);
+    auxiliar_newclass(L, "unix{server}", un);
+    /* create class groups */
+    auxiliar_add2group(L, "unix{master}", "unix{any}");
+    auxiliar_add2group(L, "unix{client}", "unix{any}");
+    auxiliar_add2group(L, "unix{server}", "unix{any}");
+    /* make sure the function ends up in the package table */
+    luaL_openlib(L, "socket", func, 0);
+    /* return the function instead of the 'socket' table */
+    lua_pushstring(L, "unix");
+    lua_gettable(L, -2);
+    return 1;
+}
+
+/*=========================================================================*\
+* Lua methods
+\*=========================================================================*/
+/*-------------------------------------------------------------------------*\
+* Just call buffered IO methods
+\*-------------------------------------------------------------------------*/
+static int meth_send(lua_State *L) {
+    p_unix un = (p_unix) auxiliar_checkclass(L, "unix{client}", 1);
+    return buffer_meth_send(L, &un->buf);
+}
+
+static int meth_receive(lua_State *L) {
+    p_unix un = (p_unix) auxiliar_checkclass(L, "unix{client}", 1);
+    return buffer_meth_receive(L, &un->buf);
+}
+
+static int meth_getstats(lua_State *L) {
+    p_unix un = (p_unix) auxiliar_checkclass(L, "unix{client}", 1);
+    return buffer_meth_getstats(L, &un->buf);
+}
+
+static int meth_setstats(lua_State *L) {
+    p_unix un = (p_unix) auxiliar_checkclass(L, "unix{client}", 1);
+    return buffer_meth_setstats(L, &un->buf);
+}
+
+/*-------------------------------------------------------------------------*\
+* Just call option handler
+\*-------------------------------------------------------------------------*/
+static int meth_setoption(lua_State *L) {
+    p_unix un = (p_unix) auxiliar_checkgroup(L, "unix{any}", 1);
+    return opt_meth_setoption(L, opt, &un->sock);
+}
+
+/*-------------------------------------------------------------------------*\
+* Select support methods
+\*-------------------------------------------------------------------------*/
+static int meth_getfd(lua_State *L) {
+    p_unix un = (p_unix) auxiliar_checkgroup(L, "unix{any}", 1);
+    lua_pushnumber(L, (int) un->sock);
+    return 1;
+}
+
+/* this is very dangerous, but can be handy for those that are brave enough */
+static int meth_setfd(lua_State *L) {
+    p_unix un = (p_unix) auxiliar_checkgroup(L, "unix{any}", 1);
+    un->sock = (t_socket) luaL_checknumber(L, 2); 
+    return 0;
+}
+
+static int meth_dirty(lua_State *L) {
+    p_unix un = (p_unix) auxiliar_checkgroup(L, "unix{any}", 1);
+    lua_pushboolean(L, !buffer_isempty(&un->buf));
+    return 1;
+}
+
+/*-------------------------------------------------------------------------*\
+* Waits for and returns a client object attempting connection to the 
+* server object 
+\*-------------------------------------------------------------------------*/
+static int meth_accept(lua_State *L) {
+    p_unix server = (p_unix) auxiliar_checkclass(L, "unix{server}", 1);
+    p_timeout tm = timeout_markstart(&server->tm);
+    t_socket sock;
+    int err = socket_accept(&server->sock, &sock, NULL, NULL, tm);
+    /* if successful, push client socket */
+    if (err == IO_DONE) {
+        p_unix clnt = (p_unix) lua_newuserdata(L, sizeof(t_unix));
+        auxiliar_setclass(L, "unix{client}", -1);
+        /* initialize structure fields */
+        socket_setnonblocking(&sock);
+        clnt->sock = sock;
+        io_init(&clnt->io, (p_send)socket_send, (p_recv)socket_recv, 
+                (p_error) socket_ioerror, &clnt->sock);
+        timeout_init(&clnt->tm, -1, -1);
+        buffer_init(&clnt->buf, &clnt->io, &clnt->tm);
+        return 1;
+    } else {
+        lua_pushnil(L); 
+        lua_pushstring(L, socket_strerror(err));
+        return 2;
+    }
+}
+
+/*-------------------------------------------------------------------------*\
+* Binds an object to an address 
+\*-------------------------------------------------------------------------*/
+static const char *unix_trybind(p_unix un, const char *path) {
+    struct sockaddr_un local;
+    size_t len = strlen(path);
+    int err;
+    if (len >= sizeof(local.sun_path)) return "path too long";
+    memset(&local, 0, sizeof(local));
+    strcpy(local.sun_path, path);
+    local.sun_family = AF_UNIX;
+#ifdef UNIX_HAS_SUN_LEN
+    local.sun_len = sizeof(local.sun_family) + sizeof(local.sun_len) 
+        + len + 1;
+    err = socket_bind(&un->sock, (SA *) &local, local.sun_len);
+
+#else 
+    err = socket_bind(&un->sock, (SA *) &local, 
+            sizeof(local.sun_family) + len);
+#endif
+    if (err != IO_DONE) socket_destroy(&un->sock);
+    return socket_strerror(err); 
+}
+
+static int meth_bind(lua_State *L) {
+    p_unix un = (p_unix) auxiliar_checkclass(L, "unix{master}", 1);
+    const char *path =  luaL_checkstring(L, 2);
+    const char *err = unix_trybind(un, path);
+    if (err) {
+        lua_pushnil(L);
+        lua_pushstring(L, err);
+        return 2;
+    }
+    lua_pushnumber(L, 1);
+    return 1;
+}
+
+/*-------------------------------------------------------------------------*\
+* Turns a master unix object into a client object.
+\*-------------------------------------------------------------------------*/
+static const char *unix_tryconnect(p_unix un, const char *path)
+{
+    struct sockaddr_un remote;
+    int err;
+    size_t len = strlen(path);
+    if (len >= sizeof(remote.sun_path)) return "path too long";
+    memset(&remote, 0, sizeof(remote));
+    strcpy(remote.sun_path, path);
+    remote.sun_family = AF_UNIX;
+    timeout_markstart(&un->tm);
+#ifdef UNIX_HAS_SUN_LEN
+    remote.sun_len = sizeof(remote.sun_family) + sizeof(remote.sun_len) 
+        + len + 1;
+    err = socket_connect(&un->sock, (SA *) &remote, remote.sun_len, &un->tm);
+#else
+    err = socket_connect(&un->sock, (SA *) &remote, 
+            sizeof(remote.sun_family) + len, &un->tm);
+#endif
+    if (err != IO_DONE) socket_destroy(&un->sock);
+    return socket_strerror(err);
+}
+
+static int meth_connect(lua_State *L)
+{
+    p_unix un = (p_unix) auxiliar_checkclass(L, "unix{master}", 1);
+    const char *path =  luaL_checkstring(L, 2);
+    const char *err = unix_tryconnect(un, path);
+    if (err) {
+        lua_pushnil(L);
+        lua_pushstring(L, err);
+        return 2;
+    }
+    /* turn master object into a client object */
+    auxiliar_setclass(L, "unix{client}", 1);
+    lua_pushnumber(L, 1);
+    return 1;
+}
+
+/*-------------------------------------------------------------------------*\
+* Closes socket used by object 
+\*-------------------------------------------------------------------------*/
+static int meth_close(lua_State *L)
+{
+    p_unix un = (p_unix) auxiliar_checkgroup(L, "unix{any}", 1);
+    socket_destroy(&un->sock);
+    lua_pushnumber(L, 1);
+    return 1;
+}
+
+/*-------------------------------------------------------------------------*\
+* Puts the sockt in listen mode
+\*-------------------------------------------------------------------------*/
+static int meth_listen(lua_State *L)
+{
+    p_unix un = (p_unix) auxiliar_checkclass(L, "unix{master}", 1);
+    int backlog = (int) luaL_optnumber(L, 2, 32);
+    int err = socket_listen(&un->sock, backlog);
+    if (err != IO_DONE) {
+        lua_pushnil(L);
+        lua_pushstring(L, socket_strerror(err));
+        return 2;
+    }
+    /* turn master object into a server object */
+    auxiliar_setclass(L, "unix{server}", 1);
+    lua_pushnumber(L, 1);
+    return 1;
+}
+
+/*-------------------------------------------------------------------------*\
+* Shuts the connection down partially
+\*-------------------------------------------------------------------------*/
+static int meth_shutdown(lua_State *L)
+{
+    p_unix un = (p_unix) auxiliar_checkclass(L, "unix{client}", 1);
+    const char *how = luaL_optstring(L, 2, "both");
+    switch (how[0]) {
+        case 'b':
+            if (strcmp(how, "both")) goto error;
+            socket_shutdown(&un->sock, 2);
+            break;
+        case 's':
+            if (strcmp(how, "send")) goto error;
+            socket_shutdown(&un->sock, 1);
+            break;
+        case 'r':
+            if (strcmp(how, "receive")) goto error;
+            socket_shutdown(&un->sock, 0);
+            break;
+    }
+    lua_pushnumber(L, 1);
+    return 1;
+error:
+    luaL_argerror(L, 2, "invalid shutdown method");
+    return 0;
+}
+
+/*-------------------------------------------------------------------------*\
+* Just call tm methods
+\*-------------------------------------------------------------------------*/
+static int meth_settimeout(lua_State *L) {
+    p_unix un = (p_unix) auxiliar_checkgroup(L, "unix{any}", 1);
+    return timeout_meth_settimeout(L, &un->tm);
+}
+
+/*=========================================================================*\
+* Library functions
+\*=========================================================================*/
+/*-------------------------------------------------------------------------*\
+* Creates a master unix object 
+\*-------------------------------------------------------------------------*/
+static int global_create(lua_State *L) {
+    t_socket sock;
+    int err = socket_create(&sock, AF_UNIX, SOCK_STREAM, 0);
+    /* try to allocate a system socket */
+    if (err == IO_DONE) { 
+        /* allocate unix object */
+        p_unix un = (p_unix) lua_newuserdata(L, sizeof(t_unix));
+        /* set its type as master object */
+        auxiliar_setclass(L, "unix{master}", -1);
+        /* initialize remaining structure fields */
+        socket_setnonblocking(&sock);
+        un->sock = sock;
+        io_init(&un->io, (p_send) socket_send, (p_recv) socket_recv, 
+                (p_error) socket_ioerror, &un->sock);
+        timeout_init(&un->tm, -1, -1);
+        buffer_init(&un->buf, &un->io, &un->tm);
+        return 1;
+    } else {
+        lua_pushnil(L);
+        lua_pushstring(L, socket_strerror(err));
+        return 2;
+    }
+}
diff --git a/src/luasocket/unix.h b/src/luasocket/unix.h
new file mode 100644
index 0000000000000000000000000000000000000000..32b7380fffa2d7085add71343f54b2d3d2072a68
--- /dev/null
+++ b/src/luasocket/unix.h
@@ -0,0 +1,28 @@
+#ifndef UNIX_H
+#define UNIX_H
+/*=========================================================================*\
+* Unix domain object
+* LuaSocket toolkit
+*
+* This module is just an example of how to extend LuaSocket with a new 
+* domain.
+*
+* RCS ID: $Id: unix.h,v 1.9 2006/03/13 07:16:39 diego Exp $
+\*=========================================================================*/
+#include "lua.h"
+
+#include "buffer.h"
+#include "timeout.h"
+#include "socket.h"
+
+typedef struct t_unix_ {
+    t_socket sock;
+    t_io io;
+    t_buffer buf;
+    t_timeout tm;
+} t_unix;
+typedef t_unix *p_unix;
+
+int luaopen_socket_unix(lua_State *L);
+
+#endif /* UNIX_H */
diff --git a/src/luasocket/usocket.c b/src/luasocket/usocket.c
new file mode 100644
index 0000000000000000000000000000000000000000..70c6e1e39e49a61abb1f19df7667ea6e5247719b
--- /dev/null
+++ b/src/luasocket/usocket.c
@@ -0,0 +1,370 @@
+/*=========================================================================*\
+* Socket compatibilization module for Unix
+* LuaSocket toolkit
+*
+* The code is now interrupt-safe.
+* The penalty of calling select to avoid busy-wait is only paid when
+* the I/O call fail in the first place. 
+*
+* RCS ID: $Id: usocket.c,v 1.38 2007/10/13 23:55:20 diego Exp $
+\*=========================================================================*/
+#include <string.h> 
+#include <signal.h>
+
+#include "socket.h"
+
+/*-------------------------------------------------------------------------*\
+* Wait for readable/writable/connected socket with timeout
+\*-------------------------------------------------------------------------*/
+#ifdef SOCKET_POLL
+#include <sys/poll.h>
+
+#define WAITFD_R        POLLIN
+#define WAITFD_W        POLLOUT
+#define WAITFD_C        (POLLIN|POLLOUT)
+int socket_waitfd(p_socket ps, int sw, p_timeout tm) {
+    int ret;
+    struct pollfd pfd;
+    pfd.fd = *ps;
+    pfd.events = sw;
+    pfd.revents = 0;
+    if (timeout_iszero(tm)) return IO_TIMEOUT;  /* optimize timeout == 0 case */
+    do {
+		int t = (int)(timeout_getretry(tm)*1e3);
+		ret = poll(&pfd, 1, t >= 0? t: -1);
+	} while (ret == -1 && errno == EINTR);
+    if (ret == -1) return errno;
+    if (ret == 0) return IO_TIMEOUT;
+    if (sw == WAITFD_C && (pfd.revents & (POLLIN|POLLERR))) return IO_CLOSED;
+    return IO_DONE;
+}
+#else
+
+#define WAITFD_R        1
+#define WAITFD_W        2
+#define WAITFD_C        (WAITFD_R|WAITFD_W)
+
+int socket_waitfd(p_socket ps, int sw, p_timeout tm) {
+    int ret;
+    fd_set rfds, wfds, *rp, *wp;
+    struct timeval tv, *tp;
+    double t;
+    if (timeout_iszero(tm)) return IO_TIMEOUT;  /* optimize timeout == 0 case */
+    do {
+        /* must set bits within loop, because select may have modifed them */
+        rp = wp = NULL;
+        if (sw & WAITFD_R) { FD_ZERO(&rfds); FD_SET(*ps, &rfds); rp = &rfds; }
+        if (sw & WAITFD_W) { FD_ZERO(&wfds); FD_SET(*ps, &wfds); wp = &wfds; }
+        t = timeout_getretry(tm);
+        tp = NULL;
+        if (t >= 0.0) {
+            tv.tv_sec = (int)t;
+            tv.tv_usec = (int)((t-tv.tv_sec)*1.0e6);
+            tp = &tv;
+        }
+        ret = select(*ps+1, rp, wp, NULL, tp);
+    } while (ret == -1 && errno == EINTR);
+    if (ret == -1) return errno;
+    if (ret == 0) return IO_TIMEOUT;
+    if (sw == WAITFD_C && FD_ISSET(*ps, &rfds)) return IO_CLOSED;
+    return IO_DONE;
+}
+#endif
+
+
+/*-------------------------------------------------------------------------*\
+* Initializes module 
+\*-------------------------------------------------------------------------*/
+int socket_open(void) {
+    /* instals a handler to ignore sigpipe or it will crash us */
+    signal(SIGPIPE, SIG_IGN);
+    return 1;
+}
+
+/*-------------------------------------------------------------------------*\
+* Close module 
+\*-------------------------------------------------------------------------*/
+int socket_close(void) {
+    return 1;
+}
+
+/*-------------------------------------------------------------------------*\
+* Close and inutilize socket
+\*-------------------------------------------------------------------------*/
+void socket_destroy(p_socket ps) {
+    if (*ps != SOCKET_INVALID) {
+        socket_setblocking(ps);
+        close(*ps);
+        *ps = SOCKET_INVALID;
+    }
+}
+
+/*-------------------------------------------------------------------------*\
+* Select with timeout control
+\*-------------------------------------------------------------------------*/
+int socket_select(t_socket n, fd_set *rfds, fd_set *wfds, fd_set *efds, 
+        p_timeout tm) {
+    int ret;
+    do {
+        struct timeval tv;
+        double t = timeout_getretry(tm);
+        tv.tv_sec = (int) t;
+        tv.tv_usec = (int) ((t - tv.tv_sec) * 1.0e6);
+        /* timeout = 0 means no wait */
+        ret = select(n, rfds, wfds, efds, t >= 0.0 ? &tv: NULL);
+    } while (ret < 0 && errno == EINTR);
+    return ret;
+}
+
+/*-------------------------------------------------------------------------*\
+* Creates and sets up a socket
+\*-------------------------------------------------------------------------*/
+int socket_create(p_socket ps, int domain, int type, int protocol) {
+    *ps = socket(domain, type, protocol);
+    if (*ps != SOCKET_INVALID) return IO_DONE; 
+    else return errno; 
+}
+
+/*-------------------------------------------------------------------------*\
+* Binds or returns error message
+\*-------------------------------------------------------------------------*/
+int socket_bind(p_socket ps, SA *addr, socklen_t len) {
+    int err = IO_DONE;
+    socket_setblocking(ps);
+    if (bind(*ps, addr, len) < 0) err = errno; 
+    socket_setnonblocking(ps);
+    return err;
+}
+
+/*-------------------------------------------------------------------------*\
+* 
+\*-------------------------------------------------------------------------*/
+int socket_listen(p_socket ps, int backlog) {
+    int err = IO_DONE; 
+    socket_setblocking(ps);
+    if (listen(*ps, backlog)) err = errno; 
+    socket_setnonblocking(ps);
+    return err;
+}
+
+/*-------------------------------------------------------------------------*\
+* 
+\*-------------------------------------------------------------------------*/
+void socket_shutdown(p_socket ps, int how) {
+    socket_setblocking(ps);
+    shutdown(*ps, how);
+    socket_setnonblocking(ps);
+}
+
+/*-------------------------------------------------------------------------*\
+* Connects or returns error message
+\*-------------------------------------------------------------------------*/
+int socket_connect(p_socket ps, SA *addr, socklen_t len, p_timeout tm) {
+    int err;
+    /* avoid calling on closed sockets */
+    if (*ps == SOCKET_INVALID) return IO_CLOSED;
+    /* call connect until done or failed without being interrupted */
+    do if (connect(*ps, addr, len) == 0) return IO_DONE;
+    while ((err = errno) == EINTR);
+    /* if connection failed immediately, return error code */
+    if (err != EINPROGRESS && err != EAGAIN) return err; 
+    /* zero timeout case optimization */
+    if (timeout_iszero(tm)) return IO_TIMEOUT;
+    /* wait until we have the result of the connection attempt or timeout */
+    err = socket_waitfd(ps, WAITFD_C, tm);
+    if (err == IO_CLOSED) {
+        if (recv(*ps, (char *) &err, 0, 0) == 0) return IO_DONE;
+        else return errno;
+    } else return err;
+}
+
+/*-------------------------------------------------------------------------*\
+* Accept with timeout
+\*-------------------------------------------------------------------------*/
+int socket_accept(p_socket ps, p_socket pa, SA *addr, socklen_t *len, p_timeout tm) {
+    SA daddr;
+    socklen_t dlen = sizeof(daddr);
+    if (*ps == SOCKET_INVALID) return IO_CLOSED; 
+    if (!addr) addr = &daddr;
+    if (!len) len = &dlen;
+    for ( ;; ) {
+        int err;
+        if ((*pa = accept(*ps, addr, len)) != SOCKET_INVALID) return IO_DONE;
+        err = errno;
+        if (err == EINTR) continue;
+        if (err != EAGAIN && err != ECONNABORTED) return err;
+        if ((err = socket_waitfd(ps, WAITFD_R, tm)) != IO_DONE) return err;
+    }
+    /* can't reach here */
+    return IO_UNKNOWN;
+}
+
+/*-------------------------------------------------------------------------*\
+* Send with timeout
+\*-------------------------------------------------------------------------*/
+int socket_send(p_socket ps, const char *data, size_t count, 
+        size_t *sent, p_timeout tm)
+{
+    int err;
+    *sent = 0;
+    /* avoid making system calls on closed sockets */
+    if (*ps == SOCKET_INVALID) return IO_CLOSED;
+    /* loop until we send something or we give up on error */
+    for ( ;; ) {
+        long put = (long) send(*ps, data, count, 0);
+        /* if we sent anything, we are done */
+        if (put > 0) {
+            *sent = put;
+            return IO_DONE;
+        }
+        err = errno;
+        /* send can't really return 0, but EPIPE means the connection was 
+           closed */
+        if (put == 0 || err == EPIPE) return IO_CLOSED;
+        /* we call was interrupted, just try again */
+        if (err == EINTR) continue;
+        /* if failed fatal reason, report error */
+        if (err != EAGAIN) return err;
+        /* wait until we can send something or we timeout */
+        if ((err = socket_waitfd(ps, WAITFD_W, tm)) != IO_DONE) return err;
+    }
+    /* can't reach here */
+    return IO_UNKNOWN;
+}
+
+/*-------------------------------------------------------------------------*\
+* Sendto with timeout
+\*-------------------------------------------------------------------------*/
+int socket_sendto(p_socket ps, const char *data, size_t count, size_t *sent, 
+        SA *addr, socklen_t len, p_timeout tm)
+{
+    int err;
+    *sent = 0;
+    if (*ps == SOCKET_INVALID) return IO_CLOSED;
+    for ( ;; ) {
+        long put = (long) sendto(*ps, data, count, 0, addr, len);  
+        if (put > 0) {
+            *sent = put;
+            return IO_DONE;
+        }
+        err = errno;
+        if (put == 0 || err == EPIPE) return IO_CLOSED;
+        if (err == EINTR) continue;
+        if (err != EAGAIN) return err;
+        if ((err = socket_waitfd(ps, WAITFD_W, tm)) != IO_DONE) return err;
+    }
+    return IO_UNKNOWN;
+}
+
+/*-------------------------------------------------------------------------*\
+* Receive with timeout
+\*-------------------------------------------------------------------------*/
+int socket_recv(p_socket ps, char *data, size_t count, size_t *got, p_timeout tm) {
+    int err;
+    *got = 0;
+    if (*ps == SOCKET_INVALID) return IO_CLOSED;
+    for ( ;; ) {
+        long taken = (long) recv(*ps, data, count, 0);
+        if (taken > 0) {
+            *got = taken;
+            return IO_DONE;
+        }
+        err = errno;
+        if (taken == 0) return IO_CLOSED;
+        if (err == EINTR) continue;
+        if (err != EAGAIN) return err; 
+        if ((err = socket_waitfd(ps, WAITFD_R, tm)) != IO_DONE) return err; 
+    }
+    return IO_UNKNOWN;
+}
+
+/*-------------------------------------------------------------------------*\
+* Recvfrom with timeout
+\*-------------------------------------------------------------------------*/
+int socket_recvfrom(p_socket ps, char *data, size_t count, size_t *got, 
+        SA *addr, socklen_t *len, p_timeout tm) {
+    int err;
+    *got = 0;
+    if (*ps == SOCKET_INVALID) return IO_CLOSED;
+    for ( ;; ) {
+        long taken = (long) recvfrom(*ps, data, count, 0, addr, len);
+        if (taken > 0) {
+            *got = taken;
+            return IO_DONE;
+        }
+        err = errno;
+        if (taken == 0) return IO_CLOSED;
+        if (err == EINTR) continue;
+        if (err != EAGAIN) return err; 
+        if ((err = socket_waitfd(ps, WAITFD_R, tm)) != IO_DONE) return err; 
+    }
+    return IO_UNKNOWN;
+}
+
+/*-------------------------------------------------------------------------*\
+* Put socket into blocking mode
+\*-------------------------------------------------------------------------*/
+void socket_setblocking(p_socket ps) {
+    int flags = fcntl(*ps, F_GETFL, 0);
+    flags &= (~(O_NONBLOCK));
+    fcntl(*ps, F_SETFL, flags);
+}
+
+/*-------------------------------------------------------------------------*\
+* Put socket into non-blocking mode
+\*-------------------------------------------------------------------------*/
+void socket_setnonblocking(p_socket ps) {
+    int flags = fcntl(*ps, F_GETFL, 0);
+    flags |= O_NONBLOCK;
+    fcntl(*ps, F_SETFL, flags);
+}
+
+/*-------------------------------------------------------------------------*\
+* DNS helpers 
+\*-------------------------------------------------------------------------*/
+int socket_gethostbyaddr(const char *addr, socklen_t len, struct hostent **hp) {
+    *hp = gethostbyaddr(addr, len, AF_INET);
+    if (*hp) return IO_DONE;
+    else if (h_errno) return h_errno;
+    else if (errno) return errno;
+    else return IO_UNKNOWN;
+}
+
+int socket_gethostbyname(const char *addr, struct hostent **hp) {
+    *hp = gethostbyname(addr);
+    if (*hp) return IO_DONE;
+    else if (h_errno) return h_errno;
+    else if (errno) return errno;
+    else return IO_UNKNOWN;
+}
+
+/*-------------------------------------------------------------------------*\
+* Error translation functions
+* Make sure important error messages are standard
+\*-------------------------------------------------------------------------*/
+const char *socket_hoststrerror(int err) {
+    if (err <= 0) return io_strerror(err);
+    switch (err) {
+        case HOST_NOT_FOUND: return "host not found";
+        default: return hstrerror(err);
+    }
+}
+
+const char *socket_strerror(int err) {
+    if (err <= 0) return io_strerror(err);
+    switch (err) {
+        case EADDRINUSE: return "address already in use";
+        case EISCONN: return "already connected";
+        case EACCES: return "permission denied";
+        case ECONNREFUSED: return "connection refused";
+        case ECONNABORTED: return "closed";
+        case ECONNRESET: return "closed";
+        case ETIMEDOUT: return "timeout";
+        default: return strerror(errno);
+    }
+}
+
+const char *socket_ioerror(p_socket ps, int err) {
+    (void) ps;
+    return socket_strerror(err);
+} 
diff --git a/src/luasocket/usocket.h b/src/luasocket/usocket.h
new file mode 100644
index 0000000000000000000000000000000000000000..f2a89aa0d21ed4779d28a7844a1ec95cabfbc448
--- /dev/null
+++ b/src/luasocket/usocket.h
@@ -0,0 +1,40 @@
+#ifndef USOCKET_H
+#define USOCKET_H
+/*=========================================================================*\
+* Socket compatibilization module for Unix
+* LuaSocket toolkit
+*
+* RCS ID: $Id: usocket.h,v 1.7 2005/10/07 04:40:59 diego Exp $
+\*=========================================================================*/
+
+/*=========================================================================*\
+* BSD include files
+\*=========================================================================*/
+/* error codes */
+#include <errno.h>
+/* close function */
+#include <unistd.h>
+/* fnctnl function and associated constants */
+#include <fcntl.h>
+/* struct sockaddr */
+#include <sys/types.h>
+/* socket function */
+#include <sys/socket.h>
+/* struct timeval */
+#include <sys/time.h>
+/* gethostbyname and gethostbyaddr functions */
+#include <netdb.h>
+/* sigpipe handling */
+#include <signal.h>
+/* IP stuff*/
+#include <netinet/in.h>
+#include <arpa/inet.h>
+/* TCP options (nagle algorithm disable) */
+#include <netinet/tcp.h>
+
+typedef int t_socket;
+typedef t_socket *p_socket;
+
+#define SOCKET_INVALID (-1)
+
+#endif /* USOCKET_H */
diff --git a/src/luasocket/wsocket.c b/src/luasocket/wsocket.c
new file mode 100644
index 0000000000000000000000000000000000000000..6022565188a6c3be21a2d5c90b63f95929d1448f
--- /dev/null
+++ b/src/luasocket/wsocket.c
@@ -0,0 +1,401 @@
+/*=========================================================================*\
+* Socket compatibilization module for Win32
+* LuaSocket toolkit
+*
+* The penalty of calling select to avoid busy-wait is only paid when
+* the I/O call fail in the first place. 
+*
+* RCS ID: $Id: wsocket.c,v 1.36 2007/06/11 23:44:54 diego Exp $
+\*=========================================================================*/
+#include <string.h>
+
+#include "socket.h"
+
+/* WinSock doesn't have a strerror... */
+static const char *wstrerror(int err);
+
+/*-------------------------------------------------------------------------*\
+* Initializes module 
+\*-------------------------------------------------------------------------*/
+int socket_open(void) {
+    WSADATA wsaData;
+    WORD wVersionRequested = MAKEWORD(2, 0); 
+    int err = WSAStartup(wVersionRequested, &wsaData );
+    if (err != 0) return 0;
+    if ((LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 0) &&
+        (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1)) {
+        WSACleanup();
+        return 0; 
+    }
+    return 1;
+}
+
+/*-------------------------------------------------------------------------*\
+* Close module 
+\*-------------------------------------------------------------------------*/
+int socket_close(void) {
+    WSACleanup();
+    return 1;
+}
+
+/*-------------------------------------------------------------------------*\
+* Wait for readable/writable/connected socket with timeout
+\*-------------------------------------------------------------------------*/
+#define WAITFD_R        1
+#define WAITFD_W        2
+#define WAITFD_E        4
+#define WAITFD_C        (WAITFD_E|WAITFD_W)
+
+int socket_waitfd(p_socket ps, int sw, p_timeout tm) {
+    int ret;
+    fd_set rfds, wfds, efds, *rp = NULL, *wp = NULL, *ep = NULL;
+    struct timeval tv, *tp = NULL;
+    double t;
+    if (timeout_iszero(tm)) return IO_TIMEOUT;  /* optimize timeout == 0 case */
+    if (sw & WAITFD_R) { 
+        FD_ZERO(&rfds); 
+		FD_SET(*ps, &rfds);
+        rp = &rfds; 
+    }
+    if (sw & WAITFD_W) { FD_ZERO(&wfds); FD_SET(*ps, &wfds); wp = &wfds; }
+    if (sw & WAITFD_C) { FD_ZERO(&efds); FD_SET(*ps, &efds); ep = &efds; }
+    if ((t = timeout_get(tm)) >= 0.0) {
+        tv.tv_sec = (int) t;
+        tv.tv_usec = (int) ((t-tv.tv_sec)*1.0e6);
+        tp = &tv;
+    }
+    ret = select(0, rp, wp, ep, tp);
+    if (ret == -1) return WSAGetLastError();
+    if (ret == 0) return IO_TIMEOUT;
+    if (sw == WAITFD_C && FD_ISSET(*ps, &efds)) return IO_CLOSED;
+    return IO_DONE;
+}
+
+/*-------------------------------------------------------------------------*\
+* Select with int timeout in ms
+\*-------------------------------------------------------------------------*/
+int socket_select(t_socket n, fd_set *rfds, fd_set *wfds, fd_set *efds, 
+        p_timeout tm) {
+    struct timeval tv; 
+    double t = timeout_get(tm);
+    tv.tv_sec = (int) t;
+    tv.tv_usec = (int) ((t - tv.tv_sec) * 1.0e6);
+    if (n <= 0) {
+        Sleep((DWORD) (1000*t));
+        return 0;
+    } else return select(0, rfds, wfds, efds, t >= 0.0? &tv: NULL);
+}
+
+/*-------------------------------------------------------------------------*\
+* Close and inutilize socket
+\*-------------------------------------------------------------------------*/
+void socket_destroy(p_socket ps) {
+    if (*ps != SOCKET_INVALID) {
+        socket_setblocking(ps); /* close can take a long time on WIN32 */
+        closesocket(*ps);
+        *ps = SOCKET_INVALID;
+    }
+}
+
+/*-------------------------------------------------------------------------*\
+* 
+\*-------------------------------------------------------------------------*/
+void socket_shutdown(p_socket ps, int how) {
+    socket_setblocking(ps);
+    shutdown(*ps, how);
+    socket_setnonblocking(ps);
+}
+
+/*-------------------------------------------------------------------------*\
+* Creates and sets up a socket
+\*-------------------------------------------------------------------------*/
+int socket_create(p_socket ps, int domain, int type, int protocol) {
+    *ps = socket(domain, type, protocol);
+    if (*ps != SOCKET_INVALID) return IO_DONE;
+    else return WSAGetLastError();
+}
+
+/*-------------------------------------------------------------------------*\
+* Connects or returns error message
+\*-------------------------------------------------------------------------*/
+int socket_connect(p_socket ps, SA *addr, socklen_t len, p_timeout tm) {
+    int err;
+    /* don't call on closed socket */
+    if (*ps == SOCKET_INVALID) return IO_CLOSED;
+    /* ask system to connect */
+    if (connect(*ps, addr, len) == 0) return IO_DONE;
+    /* make sure the system is trying to connect */
+    err = WSAGetLastError();
+    if (err != WSAEWOULDBLOCK && err != WSAEINPROGRESS) return err;
+    /* zero timeout case optimization */
+    if (timeout_iszero(tm)) return IO_TIMEOUT;
+    /* we wait until something happens */
+    err = socket_waitfd(ps, WAITFD_C, tm);
+    if (err == IO_CLOSED) {
+        int len = sizeof(err);
+        /* give windows time to set the error (yes, disgusting) */
+        Sleep(10);
+        /* find out why we failed */
+        getsockopt(*ps, SOL_SOCKET, SO_ERROR, (char *)&err, &len); 
+        /* we KNOW there was an error. if 'why' is 0, we will return
+        * "unknown error", but it's not really our fault */
+        return err > 0? err: IO_UNKNOWN; 
+    } else return err;
+
+}
+
+/*-------------------------------------------------------------------------*\
+* Binds or returns error message
+\*-------------------------------------------------------------------------*/
+int socket_bind(p_socket ps, SA *addr, socklen_t len) {
+    int err = IO_DONE;
+    socket_setblocking(ps);
+    if (bind(*ps, addr, len) < 0) err = WSAGetLastError();
+    socket_setnonblocking(ps);
+    return err;
+}
+
+/*-------------------------------------------------------------------------*\
+* 
+\*-------------------------------------------------------------------------*/
+int socket_listen(p_socket ps, int backlog) {
+    int err = IO_DONE;
+    socket_setblocking(ps);
+    if (listen(*ps, backlog) < 0) err = WSAGetLastError();
+    socket_setnonblocking(ps);
+    return err;
+}
+
+/*-------------------------------------------------------------------------*\
+* Accept with timeout
+\*-------------------------------------------------------------------------*/
+int socket_accept(p_socket ps, p_socket pa, SA *addr, socklen_t *len, 
+        p_timeout tm) {
+    SA daddr;
+    socklen_t dlen = sizeof(daddr);
+    if (*ps == SOCKET_INVALID) return IO_CLOSED;
+    if (!addr) addr = &daddr;
+    if (!len) len = &dlen;
+    for ( ;; ) {
+        int err;
+        /* try to get client socket */
+        if ((*pa = accept(*ps, addr, len)) != SOCKET_INVALID) return IO_DONE;
+        /* find out why we failed */
+        err = WSAGetLastError(); 
+        /* if we failed because there was no connectoin, keep trying */
+        if (err != WSAEWOULDBLOCK && err != WSAECONNABORTED) return err;
+        /* call select to avoid busy wait */
+        if ((err = socket_waitfd(ps, WAITFD_R, tm)) != IO_DONE) return err;
+    } 
+    /* can't reach here */
+    return IO_UNKNOWN; 
+}
+
+/*-------------------------------------------------------------------------*\
+* Send with timeout
+* On windows, if you try to send 10MB, the OS will buffer EVERYTHING 
+* this can take an awful lot of time and we will end up blocked. 
+* Therefore, whoever calls this function should not pass a huge buffer.
+\*-------------------------------------------------------------------------*/
+int socket_send(p_socket ps, const char *data, size_t count, 
+        size_t *sent, p_timeout tm)
+{
+    int err;
+    *sent = 0;
+    /* avoid making system calls on closed sockets */
+    if (*ps == SOCKET_INVALID) return IO_CLOSED;
+    /* loop until we send something or we give up on error */
+    for ( ;; ) {
+        /* try to send something */
+		int put = send(*ps, data, (int) count, 0);
+        /* if we sent something, we are done */
+        if (put > 0) {
+            *sent = put;
+            return IO_DONE;
+        }
+        /* deal with failure */
+        err = WSAGetLastError(); 
+        /* we can only proceed if there was no serious error */
+        if (err != WSAEWOULDBLOCK) return err;
+        /* avoid busy wait */
+        if ((err = socket_waitfd(ps, WAITFD_W, tm)) != IO_DONE) return err;
+    } 
+    /* can't reach here */
+    return IO_UNKNOWN;
+}
+
+/*-------------------------------------------------------------------------*\
+* Sendto with timeout
+\*-------------------------------------------------------------------------*/
+int socket_sendto(p_socket ps, const char *data, size_t count, size_t *sent, 
+        SA *addr, socklen_t len, p_timeout tm)
+{
+    int err;
+    *sent = 0;
+    if (*ps == SOCKET_INVALID) return IO_CLOSED;
+    for ( ;; ) {
+        int put = sendto(*ps, data, (int) count, 0, addr, len);
+        if (put > 0) {
+            *sent = put;
+            return IO_DONE;
+        }
+        err = WSAGetLastError(); 
+        if (err != WSAEWOULDBLOCK) return err;
+        if ((err = socket_waitfd(ps, WAITFD_W, tm)) != IO_DONE) return err;
+    } 
+    return IO_UNKNOWN;
+}
+
+/*-------------------------------------------------------------------------*\
+* Receive with timeout
+\*-------------------------------------------------------------------------*/
+int socket_recv(p_socket ps, char *data, size_t count, size_t *got, p_timeout tm) {
+    int err;
+    *got = 0;
+    if (*ps == SOCKET_INVALID) return IO_CLOSED;
+    for ( ;; ) {
+        int taken = recv(*ps, data, (int) count, 0);
+        if (taken > 0) {
+            *got = taken;
+            return IO_DONE;
+        }
+        if (taken == 0) return IO_CLOSED;
+        err = WSAGetLastError();
+        if (err != WSAEWOULDBLOCK) return err;
+        if ((err = socket_waitfd(ps, WAITFD_R, tm)) != IO_DONE) return err;
+    }
+    return IO_UNKNOWN;
+}
+
+/*-------------------------------------------------------------------------*\
+* Recvfrom with timeout
+\*-------------------------------------------------------------------------*/
+int socket_recvfrom(p_socket ps, char *data, size_t count, size_t *got, 
+        SA *addr, socklen_t *len, p_timeout tm) {
+    int err;
+    *got = 0;
+    if (*ps == SOCKET_INVALID) return IO_CLOSED;
+    for ( ;; ) {
+        int taken = recvfrom(*ps, data, (int) count, 0, addr, len);
+        if (taken > 0) {
+            *got = taken;
+            return IO_DONE;
+        }
+        if (taken == 0) return IO_CLOSED;
+        err = WSAGetLastError();
+        if (err != WSAEWOULDBLOCK) return err;
+        if ((err = socket_waitfd(ps, WAITFD_R, tm)) != IO_DONE) return err;
+    }
+    return IO_UNKNOWN;
+}
+
+/*-------------------------------------------------------------------------*\
+* Put socket into blocking mode
+\*-------------------------------------------------------------------------*/
+void socket_setblocking(p_socket ps) {
+    u_long argp = 0;
+    ioctlsocket(*ps, FIONBIO, &argp);
+}
+
+/*-------------------------------------------------------------------------*\
+* Put socket into non-blocking mode
+\*-------------------------------------------------------------------------*/
+void socket_setnonblocking(p_socket ps) {
+    u_long argp = 1;
+    ioctlsocket(*ps, FIONBIO, &argp);
+}
+
+/*-------------------------------------------------------------------------*\
+* DNS helpers 
+\*-------------------------------------------------------------------------*/
+int socket_gethostbyaddr(const char *addr, socklen_t len, struct hostent **hp) {
+    *hp = gethostbyaddr(addr, len, AF_INET);
+    if (*hp) return IO_DONE;
+    else return WSAGetLastError();
+}
+
+int socket_gethostbyname(const char *addr, struct hostent **hp) {
+    *hp = gethostbyname(addr);
+    if (*hp) return IO_DONE;
+    else return  WSAGetLastError();
+}
+
+/*-------------------------------------------------------------------------*\
+* Error translation functions
+\*-------------------------------------------------------------------------*/
+const char *socket_hoststrerror(int err) {
+    if (err <= 0) return io_strerror(err);
+    switch (err) {
+        case WSAHOST_NOT_FOUND: return "host not found";
+        default: return wstrerror(err); 
+    }
+}
+
+const char *socket_strerror(int err) {
+    if (err <= 0) return io_strerror(err);
+    switch (err) {
+        case WSAEADDRINUSE: return "address already in use";
+        case WSAECONNREFUSED: return "connection refused";
+        case WSAEISCONN: return "already connected";
+        case WSAEACCES: return "permission denied";
+        case WSAECONNABORTED: return "closed";
+        case WSAECONNRESET: return "closed";
+        case WSAETIMEDOUT: return "timeout";
+        default: return wstrerror(err);
+    }
+}
+
+const char *socket_ioerror(p_socket ps, int err) {
+	(void) ps;
+	return socket_strerror(err);
+}
+
+static const char *wstrerror(int err) {
+    switch (err) {
+        case WSAEINTR: return "Interrupted function call";
+        case WSAEACCES: return "Permission denied";
+        case WSAEFAULT: return "Bad address";
+        case WSAEINVAL: return "Invalid argument";
+        case WSAEMFILE: return "Too many open files";
+        case WSAEWOULDBLOCK: return "Resource temporarily unavailable";
+        case WSAEINPROGRESS: return "Operation now in progress";
+        case WSAEALREADY: return "Operation already in progress";
+        case WSAENOTSOCK: return "Socket operation on nonsocket";
+        case WSAEDESTADDRREQ: return "Destination address required";
+        case WSAEMSGSIZE: return "Message too long";
+        case WSAEPROTOTYPE: return "Protocol wrong type for socket";
+        case WSAENOPROTOOPT: return "Bad protocol option";
+        case WSAEPROTONOSUPPORT: return "Protocol not supported";
+        case WSAESOCKTNOSUPPORT: return "Socket type not supported";
+        case WSAEOPNOTSUPP: return "Operation not supported";
+        case WSAEPFNOSUPPORT: return "Protocol family not supported";
+        case WSAEAFNOSUPPORT: 
+            return "Address family not supported by protocol family"; 
+        case WSAEADDRINUSE: return "Address already in use";
+        case WSAEADDRNOTAVAIL: return "Cannot assign requested address";
+        case WSAENETDOWN: return "Network is down";
+        case WSAENETUNREACH: return "Network is unreachable";
+        case WSAENETRESET: return "Network dropped connection on reset";
+        case WSAECONNABORTED: return "Software caused connection abort";
+        case WSAECONNRESET: return "Connection reset by peer";
+        case WSAENOBUFS: return "No buffer space available";
+        case WSAEISCONN: return "Socket is already connected";
+        case WSAENOTCONN: return "Socket is not connected";
+        case WSAESHUTDOWN: return "Cannot send after socket shutdown";
+        case WSAETIMEDOUT: return "Connection timed out";
+        case WSAECONNREFUSED: return "Connection refused";
+        case WSAEHOSTDOWN: return "Host is down";
+        case WSAEHOSTUNREACH: return "No route to host";
+        case WSAEPROCLIM: return "Too many processes";
+        case WSASYSNOTREADY: return "Network subsystem is unavailable";
+        case WSAVERNOTSUPPORTED: return "Winsock.dll version out of range";
+        case WSANOTINITIALISED: 
+            return "Successful WSAStartup not yet performed";
+        case WSAEDISCON: return "Graceful shutdown in progress";
+        case WSAHOST_NOT_FOUND: return "Host not found";
+        case WSATRY_AGAIN: return "Nonauthoritative host not found";
+        case WSANO_RECOVERY: return "Nonrecoverable name lookup error"; 
+        case WSANO_DATA: return "Valid name, no data record of requested type";
+        default: return "Unknown error";
+    }
+}
diff --git a/src/luasocket/wsocket.h b/src/luasocket/wsocket.h
new file mode 100644
index 0000000000000000000000000000000000000000..b536683685ca6d46d5ddb13608f7c7ede541e04c
--- /dev/null
+++ b/src/luasocket/wsocket.h
@@ -0,0 +1,21 @@
+#ifndef WSOCKET_H
+#define WSOCKET_H
+/*=========================================================================*\
+* Socket compatibilization module for Win32
+* LuaSocket toolkit
+*
+* RCS ID: $Id: wsocket.h,v 1.4 2005/10/07 04:40:59 diego Exp $
+\*=========================================================================*/
+
+/*=========================================================================*\
+* WinSock include files
+\*=========================================================================*/
+#include <winsock.h>
+
+typedef int socklen_t;
+typedef SOCKET t_socket;
+typedef t_socket *p_socket;
+
+#define SOCKET_INVALID (INVALID_SOCKET)
+
+#endif /* WSOCKET_H */
diff --git a/src/main.c b/src/main.c
index c55d5318722761c9b8a427315be5743aeee825d1..661bac045a26d43555cab22888ba0cd8f63888e6 100644
--- a/src/main.c
+++ b/src/main.c
@@ -20,6 +20,31 @@ int current_keyhandler = LUA_NOREF;
 int current_game = LUA_NOREF;
 int px = 1, py = 1;
 
+static int traceback (lua_State *L) {
+	lua_Debug ar;
+	int n;
+	n = 0;
+	printf("Lua Error: %s\n", lua_tostring(L, 1));
+	while(lua_getstack(L, n++, &ar)) {
+		lua_getinfo(L, "nSl", &ar);
+		printf("\tAt %s:%d %s\n", ar.short_src, ar.currentline, ar.name?ar.name:"");
+	}
+	return 1;
+}
+
+static int docall (lua_State *L, int narg, int nret)
+{
+	int status;
+	int base = lua_gettop(L) - narg;  /* function index */
+	lua_pushcfunction(L, traceback);  /* push traceback function */
+	lua_insert(L, base);  /* put it under chunk and args */
+	status = lua_pcall(L, narg, nret, base);
+	lua_remove(L, base);  /* remove traceback function */
+	/* force a complete garbage collection in case of errors */
+	if (status != 0) lua_gc(L, LUA_GCCOLLECT, 0);
+	return status;
+}
+
 void display_utime()
 {
 	struct timeval tv;
@@ -77,7 +102,7 @@ void on_event(SGEGAMESTATE *state, SDL_Event *event)
 			}
 			else
 				lua_pushnil(L);
-			lua_call(L, 7, 0);
+			docall(L, 7, 0);
 		}
 		break;
 	}
@@ -104,7 +129,7 @@ void on_redraw(SGEGAMESTATE *state)
 		lua_gettable(L, -2);
 		lua_remove(L, -2);
 		lua_rawgeti(L, LUA_REGISTRYINDEX, current_game);
-		lua_call(L, 1, 0);
+		docall(L, 1, 0);
 	}
 
 	sgeLock(screen);
@@ -117,7 +142,7 @@ void on_redraw(SGEGAMESTATE *state)
 		lua_gettable(L, -2);
 		lua_remove(L, -2);
 		lua_rawgeti(L, LUA_REGISTRYINDEX, current_game);
-		lua_call(L, 1, 0);
+		docall(L, 1, 0);
 	}
 
 	sgeUnlock(screen);
@@ -126,22 +151,6 @@ void on_redraw(SGEGAMESTATE *state)
 	sgeFlip();
 }
 
-static int traceback (lua_State *L) {
-	printf("Lua Error: %s\n", lua_tostring(L, 1));
-}
-
-static int docall (lua_State *L, int narg, int clear) {
-	int status;
-	int base = lua_gettop(L) - narg;  /* function index */
-	lua_pushcfunction(L, traceback);  /* push traceback function */
-	lua_insert(L, base);  /* put it under chunk and args */
-	status = lua_pcall(L, narg, (clear ? 0 : LUA_MULTRET), base);
-	lua_remove(L, base);  /* remove traceback function */
-	/* force a complete garbage collection in case of errors */
-	if (status != 0) lua_gc(L, LUA_GCCOLLECT, 0);
-	return status;
-}
-
 /**
  * Program entry point.
  */
@@ -152,6 +161,7 @@ int run(int argc, char *argv[])
 
 	/***************** Physfs Init *****************/
 	PHYSFS_init(argv[0]);
+	PHYSFS_mount("game/thirdparty", "/", 1);
 	PHYSFS_mount("game/", "/", 1);
 	PHYSFS_mount("game/modules/tome", "/mod", 1);
 	PHYSFS_mount("game/modules/tome/data", "/data", 1);
@@ -160,6 +170,8 @@ int run(int argc, char *argv[])
 	L = lua_open();  /* create state */
 	luaL_openlibs(L);  /* open libraries */
 	luaopen_core(L);
+	luaopen_socket_core(L);
+	luaopen_mime_core(L);
 
 	// Make the uids repository
 	lua_newtable(L);
@@ -191,7 +203,7 @@ int run(int argc, char *argv[])
 
 	// And run the lua engine scripts
 	luaL_loadfile(L, "/engine/init.lua");
-	docall(L, 0, LUA_MULTRET);
+	docall(L, 0, 0);
 
 	// start the game running with 25 frames per seconds
 	sgeGameStateManagerRun(manager, 25);