Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 13 additions & 7 deletions docs/game_data/spel2.lua

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 10 additions & 10 deletions docs/src/includes/_globals.md
Original file line number Diff line number Diff line change
Expand Up @@ -2523,16 +2523,6 @@ Send a synchronous HTTP GET request and return response as a string or nil on an
Send an asynchronous HTTP GET request and run the callback when done. If there is an error, response will be nil and vice versa.
The callback signature is nil on_data(string response, string error)

### udp_listen


> Search script examples for [udp_listen](https://github.com/spelunky-fyi/overlunky/search?l=Lua&q=udp_listen)

#### [UdpServer](#UdpServer) udp_listen(string host, int port, function cb)

Start an UDP server on specified address and run callback when data arrives. Return a string from the callback to reply. Requires unsafe mode.
The server will be closed once the handle is released.

### udp_send


Expand Down Expand Up @@ -4076,6 +4066,16 @@ Use [GuiDrawContext](#GuiDrawContext)`.win_popid` instead
`nil win_image(IMAGE image, float width, float height)`<br/>
Use [GuiDrawContext](#GuiDrawContext)`.win_image` instead

### udp_listen


> Search script examples for [udp_listen](https://github.com/spelunky-fyi/overlunky/search?l=Lua&q=udp_listen)

`nil udp_listen(string host, int port, function cb)`<br/>
Start an UDP server on specified address and run callback when data arrives. Set port to 0 to use a random ephemeral port. Return a string from the callback to reply.
The server will be closed lazily by garbage collection once the handle is released, or immediately by calling close(). Requires unsafe mode.
<br/>The callback signature is optional<string> on_message(string msg, string src)

### read_prng


Expand Down
8 changes: 8 additions & 0 deletions docs/src/includes/_types.md
Original file line number Diff line number Diff line change
Expand Up @@ -1096,6 +1096,14 @@ tuple&lt;[Vec2](#Vec2), [Vec2](#Vec2), [Vec2](#Vec2)&gt; | [split()](https://git

Type | Name | Description
---- | ---- | -----------
[UdpServer](#UdpServer) | [new(string host, int port)](https://github.com/spelunky-fyi/overlunky/search?l=Lua&q=UdpServer) |
nil | [close()](https://github.com/spelunky-fyi/overlunky/search?l=Lua&q=close) | Closes the server.
bool | [is_open()](https://github.com/spelunky-fyi/overlunky/search?l=Lua&q=is_open) | Returns true if the port was opened successfully and the server hasn't been closed yet.
string | [last_error()](https://github.com/spelunky-fyi/overlunky/search?l=Lua&q=last_error) | Returns a string explaining the last error
string | [host()](https://github.com/spelunky-fyi/overlunky/search?l=Lua&q=host) |
int | [port()](https://github.com/spelunky-fyi/overlunky/search?l=Lua&q=port) |
sint | [send(string message, string host, int port)](https://github.com/spelunky-fyi/overlunky/search?l=Lua&q=send) | Send message to given host and port, returns numbers of bytes send, or -1 on failure
sint | [read(function<ReadFun> fun)](https://github.com/spelunky-fyi/overlunky/search?l=Lua&q=read) | Read message from the socket buffer. Reads maximum of 32KiB at the time. If the message is longer, it will be split to portions of 32KiB.<br/>On failure or empty buffer returns -1, on success calls the function with signature `nil(message, source)`

### Vec2

Expand Down
82 changes: 82 additions & 0 deletions examples/udp.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
meta = {
name = "UDP echo example",
description = "Opens UDP server on a random port and echoes sent messages, closes the server on 'gg'",
author = "Dregu",
unsafe = true
}

options = {
host = "127.0.0.1",
port = 0
}

function init()
deinit()

server = {
-- Save messages to queue instead of printing directly, cause that doesn't work from the server thread
queue = {},

-- Open server on an ephemeral random port, push messages to queue and echo back to sender
socket = udp_listen(options.host, options.port, function(msg, src)
msg = msg:gsub("%s*$", "")
table.insert(server.queue, { msg = msg, src = src })
if msg == "gg" then
return "bye!\n"
else
return "echo: " .. msg .. "\n"
end
end)
}

-- If port was opened successfully, start checking the message queue
if server.socket:open() then
print(F "Listening on {server.socket.port}, please send some UDP datagrams or 'gg' to close")
server.inter = set_global_interval(function()
for _, msg in pairs(server.queue) do
print(F "Received: '{msg.msg}' from {msg.src}")
if msg.msg == "gg" then
server.socket:close()
clear_callback()
print("Server is now closed, have a nice day")
end
end
server.queue = {}
end, 1)
else
print(F "Failed to open server: {server.socket:error()}")
end
end

function deinit()
if server then
server.socket:close()
if server.inter then clear_callback(server.inter) end
server = nil
end
end

set_callback(init, ON.LOAD)
set_callback(init, ON.SCRIPT_ENABLE)
set_callback(deinit, ON.SCRIPT_DISABLE)

register_option_callback("x", nil, function(ctx)
options.host = ctx:win_input_text("Host", options.host)
options.port = ctx:win_input_int("Port", options.port)
if options.port < 0 then options.port = 0 end
if options.port > 65535 then options.port = 65535 end
if ctx:win_button("Start server") then init() end
ctx:win_inline()
if ctx:win_button("Stop server") then deinit() end
if server then
ctx:win_text(server.socket:error())
end
if server and server.socket:open() then
ctx:win_text(F "Listening on {server.socket.host}:{server.socket.port}\nTry sending something with udp_send:")
if ctx:win_button("Send 'Hello World!'") then udp_send(server.socket.host, server.socket.port, "Hello World!") end
ctx:win_inline()
if ctx:win_button("Send 'gg'") then udp_send(server.socket.host, server.socket.port, "gg") end
else
ctx:win_text("Stopped")
end
end)
3 changes: 3 additions & 0 deletions src/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,9 @@ if(BUILD_OVERLUNKY)
endif()
endif()

set(SOCKPP_BUILD_SHARED OFF CACHE BOOL "No shared")
set(SOCKPP_BUILD_STATIC ON CACHE BOOL "Static")

add_subdirectory(sockpp)
target_include_directories(spel2_api PUBLIC sockpp/include)
target_link_libraries_system(spel2_api PUBLIC sockpp-static)
Expand Down
41 changes: 34 additions & 7 deletions src/game_api/script/usertypes/socket_lua.cpp
Original file line number Diff line number Diff line change
@@ -1,27 +1,54 @@
#include "socket_lua.hpp"
#include "socket.hpp"

#include <memory> // for unique_ptr
#include <sol/sol.hpp> // for global_table, proxy_key_t, function
#include <sys/types.h> // for ssize_t

#include "logger.h" // for DEBUG, ByteStr
#include "script/lua_backend.hpp" // for LuaBackend
#include "script/safe_cb.hpp" // for make_safe_cb

class UdpServer_lua
{
std::unique_ptr<UdpServer> m_ptr;

public:
UdpServer_lua(std::unique_ptr<UdpServer> ptr)
: m_ptr(std::move(ptr)){};
};

namespace NSocket
{
void register_usertypes(sol::state& lua)
{
lua.new_usertype<UdpServer>(
"UdpServer",
sol::no_constructor);
/// Start an UDP server on specified address and run callback when data arrives. Return a string from the callback to reply. Requires unsafe mode.
/// The server will be closed once the handle is released.
lua["udp_listen"] = [](std::string host, in_port_t port, sol::function cb) -> UdpServer*
sol::constructors<UdpServer(std::string, in_port_t)>(),
"close",
&UdpServer::close,
"is_open",
&UdpServer::is_open,
"last_error",
&UdpServer::last_error,
"host",
&UdpServer::get_host,
"port",
&UdpServer::get_port,
"send",
&UdpServer::send,
"read",
&UdpServer::read);

/// Deprecated
/// Start an UDP server on specified address and run callback when data arrives. Set port to 0 to use a random ephemeral port. Return a string from the callback to reply.
/// The server will be closed lazily by garbage collection once the handle is released, or immediately by calling close(). Requires unsafe mode.
/// <br/>The callback signature is optional<string> on_message(string msg, string src)
lua["udp_listen"] = [](std::string host, in_port_t port, sol::function cb) //-> sol::any
{
// TODO: change the return to std::unique_ptr after fixing the dead lock with the destructor
UdpServer* server = new UdpServer(std::move(host), std::move(port), make_safe_cb<UdpServer::SocketCb>(std::move(cb)));
return server;
auto server = std::unique_ptr<UdpServer>{new UdpServer(std::move(host), port)};
server->start_callback(make_safe_cb<UdpServer::SocketCb>(std::move(cb)));
return UdpServer_lua(std::move(server));
};

/// Send data to specified UDP address. Requires unsafe mode.
Expand Down
94 changes: 70 additions & 24 deletions src/game_api/socket.cpp
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
#include "socket.hpp"

#include <Windows.h> // for GetModuleHandleA, GetProcAddress
#include <algorithm> // for max
#include <chrono> // for chrono
#include <detours.h> // for DetourAttach, DetourTransactionBegin
#include <exception> // for exception
#include <new> // for operator new
#include <sockpp/inet_address.h> // for inet_address
#include <sockpp/udp_socket.h> // for udp_socket
#include <thread> // for thread
#include <tuple> // for get
#include <type_traits> // for move
#include <utility> // for max, min
#include <wininet.h> // for InternetCloseHandle, InternetOpenA, InternetG...
#include <winsock2.h> // for sockaddr_in, SOCKET
#include <ws2tcpip.h> // for inet_ntop
Expand Down Expand Up @@ -53,41 +51,89 @@ void dump_network()
}
}

void udp_data(sockpp::udp_socket socket, UdpServer* server)
void UdpServer::callback(sockpp::udp_socket sock, std::function<UdpServer::SocketCb> cb)
{
ssize_t n;
char buf[500];
sockpp::inet_address src;
while (server->kill_thr.test(std::memory_order_acquire) && (n = socket.recv_from(buf, sizeof(buf), &src)) > 0)
static thread_local char buf[32768];
while (m_opened.load(std::memory_order::relaxed) && m_sock.is_open())
{
std::optional<std::string> ret = server->cb(std::string(buf, n));
if (ret)
sockpp::inet_address src;
ssize_t n;
while ((n = sock.recv_from(buf, sizeof(buf), &src)) > 0)
{
socket.send_to(ret.value(), src);
std::optional<std::string> ret = cb(std::string(buf, n), src.to_string());
if (ret.has_value())
sock.send_to(ret.value(), src);
}
std::this_thread::sleep_for(std::chrono::microseconds(1));
}
m_opened = false;
sock.shutdown();
}

UdpServer::UdpServer(std::string host_, in_port_t port_, std::function<SocketCb> cb_)
: host(host_), port(port_), cb(cb_)
UdpServer::UdpServer(std::string host, in_port_t port)
: m_host(host), m_port(port)
{
sock.bind(sockpp::inet_address(host, port));
kill_thr.test_and_set();
thr = std::thread(udp_data, std::move(sock), this);
if (m_sock.bind(sockpp::inet_address(host, port)))
{
const auto addr = sockpp::inet_address(m_sock.address());
port = addr.port();
m_opened = true;
m_sock.set_non_blocking();
}
}
void UdpServer::clear() // TODO: fix and expose: this and the destructor causes deadlock
void UdpServer::close()
{
kill_thr.clear(std::memory_order_release);
thr.join();
m_opened = false;
if (!m_thread.joinable())
m_sock.close();
}
UdpServer::~UdpServer()
ssize_t UdpServer::send(std::string message, std::string host, in_port_t port)
{
if (!is_open())
return -1;

return m_sock.send_to(message, sockpp::inet_address(host, port));
}
ssize_t UdpServer::read(std::function<ReadFun> fun)
{
if (!is_open())
return -1;

static char buf[32768];
sockpp::inet_address src;
auto ret = m_sock.recv_from(buf, sizeof(buf), &src);

if (ret > -1)
fun(std::string(buf, static_cast<size_t>(ret)), src.to_string());

return ret;
}
bool UdpServer::is_open() const
{
if (thr.joinable())
return m_opened.load(std::memory_order::memory_order_relaxed) && m_sock.is_open() && m_sock.last_error() > -1;
}
void UdpServer::start_callback(std::function<SocketCb> cb)
{
if (!m_thread.joinable())
{
kill_thr.clear(std::memory_order_release);
thr.join();
auto sock_copy = m_sock.clone();
m_thread = std::thread(&UdpServer::callback, this, std::move(sock_copy), std::move(cb));
}
}
std::string UdpServer::last_error() const
{
auto err = m_sock.last_error_str();
err.resize(err.size() - 2);
return err;
}
UdpServer::~UdpServer()
{
close();
if (m_thread.joinable())
m_thread.join();

m_sock.close();
}

bool http_get(const char* sURL, std::string& out, std::string& err)
{
Expand All @@ -97,7 +143,7 @@ bool http_get(const char* sURL, std::string& out, std::string& err)
const char* sHeader = NULL;
HINTERNET hInternet;
HINTERNET hConnect;
char acBuffer[BUFFER_SIZE];
static thread_local char acBuffer[BUFFER_SIZE];
DWORD iReadBytes;
DWORD iBytesToRead = 0;
DWORD iReadBytesOfRq = 4;
Expand Down
Loading
Loading