Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Protocol lua API #3461

Closed
wants to merge 25 commits into from
Closed
Show file tree
Hide file tree
Changes from 18 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions config.lua.dist
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,12 @@ expFromPlayersLevelRange = 75
-- NOTE: maxPlayers set to 0 means no limit
-- NOTE: allowWalkthrough is only applicable to players
ip = "127.0.0.1"
luaApiIp = "127.0.0.1"
bindOnlyGlobalAddress = false
loginProtocolPort = 7171
gameProtocolPort = 7172
statusProtocolPort = 7171
luaApiProtocolPort = 7179
EvilHero90 marked this conversation as resolved.
Show resolved Hide resolved
maxPlayers = 0
motd = "Welcome to The Forgotten Server!"
onePlayerOnlinePerAccount = true
Expand Down
3 changes: 3 additions & 0 deletions data/events/events.xml
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,7 @@
<!-- Monster methods -->
<event class="Monster" method="onDropLoot" enabled="1" />
<event class="Monster" method="onSpawn" enabled="0" />

<!-- Game Methods -->
<event class="Game" method="onLuaApiResponse" enabled="1" />
</events>
43 changes: 43 additions & 0 deletions data/events/scripts/game.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
function onLuaApiResponse(recvbyte, name, data)
-- saving server
if recvbyte == 102 then
saveServer()
return
end

-- cleaning server map
if recvbyte == 103 then
cleanMap()
return
end

-- close server
if recvbyte == 104 then
Game.setGameState(GAME_STATE_SHUTDOWN)
return
end

-- start raid
if recvbyte == 105 then
local returnValue = Game.startRaid(data)
if returnValue ~= RETURNVALUE_NOERROR then
print("Raid: ".. Game.getReturnMessage(returnValue))
else
print("Raid: ".. data .." started.")
end
return
end

-- reloading scripts
if recvbyte == 200 then
EventCallback:clear()
Game.reload(RELOAD_TYPE_SCRIPTS)
print("reloaded scripts successfuly")
return
end

print("[lua protocol api] unhandled packet recieved!")
print(">> recvbyte: ".. recvbyte)
print(">> name: ".. name)
print(">> data: ".. data)
end
8 changes: 4 additions & 4 deletions data/globalevents/scripts/serversave.lua
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
local function ServerSave()
function ServerSave()
EvilHero90 marked this conversation as resolved.
Show resolved Hide resolved
if configManager.getBoolean(configKeys.SERVER_SAVE_CLEAN_MAP) then
cleanMap()
end
Expand All @@ -12,11 +12,11 @@ local function ServerSave()
end
end

local function ServerSaveWarning(time)
function ServerSaveWarning(time)
local remaningTime = tonumber(time) - 60000

if configManager.getBoolean(configKeys.SERVER_SAVE_NOTIFY_MESSAGE) then
Game.broadcastMessage("Server is saving game in " .. (remaningTime/60000) .." minute(s). Please logout.", MESSAGE_STATUS_WARNING)
Game.broadcastMessage("Server is saving game in " .. (remaningTime/60000) .." minute(s). Please logout.", MESSAGE_STATUS_WARNING)
end

if remaningTime > 60000 then
Expand All @@ -29,7 +29,7 @@ end
function onTime(interval)
local remaningTime = configManager.getNumber(configKeys.SERVER_SAVE_NOTIFY_DURATION) * 60000
if configManager.getBoolean(configKeys.SERVER_SAVE_NOTIFY_MESSAGE) then
Game.broadcastMessage("Server is saving game in " .. (remaningTime/60000) .." minute(s). Please logout.", MESSAGE_STATUS_WARNING)
Game.broadcastMessage("Server is saving game in " .. (remaningTime/60000) .." minute(s). Please logout.", MESSAGE_STATUS_WARNING)
end

addEvent(ServerSaveWarning, 60000, remaningTime)
Expand Down
1 change: 1 addition & 0 deletions src/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ set(tfs_SRC
${CMAKE_CURRENT_LIST_DIR}/protocollogin.cpp
${CMAKE_CURRENT_LIST_DIR}/protocolold.cpp
${CMAKE_CURRENT_LIST_DIR}/protocolstatus.cpp
${CMAKE_CURRENT_LIST_DIR}/protocolluaapi.cpp
${CMAKE_CURRENT_LIST_DIR}/quests.cpp
${CMAKE_CURRENT_LIST_DIR}/raids.cpp
${CMAKE_CURRENT_LIST_DIR}/rsa.cpp
Expand Down
2 changes: 2 additions & 0 deletions src/configmanager.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,7 @@ bool ConfigManager::load()
string[MYSQL_PASS] = getGlobalString(L, "mysqlPass", "");
string[MYSQL_DB] = getGlobalString(L, "mysqlDatabase", "forgottenserver");
string[MYSQL_SOCK] = getGlobalString(L, "mysqlSock", "");
string[LUA_API_IP] = getGlobalString(L, "luaApiIp", "127.0.0.1");

integer[SQL_PORT] = getGlobalNumber(L, "mysqlPort", 3306);

Expand All @@ -207,6 +208,7 @@ bool ConfigManager::load()
}

integer[STATUS_PORT] = getGlobalNumber(L, "statusProtocolPort", 7171);
integer[LUA_API_PORT] = getGlobalNumber(L, "luaApiProtocolPort", 7179);

integer[MARKET_OFFER_DURATION] = getGlobalNumber(L, "marketOfferDuration", 30 * 24 * 60 * 60);
}
Expand Down
4 changes: 2 additions & 2 deletions src/configmanager.h
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ class ConfigManager
DEFAULT_PRIORITY,
MAP_AUTHOR,
CONFIG_FILE,

LUA_API_IP,
LAST_STRING_CONFIG /* this must be the last one */
};

Expand Down Expand Up @@ -130,7 +130,7 @@ class ConfigManager
YELL_MINIMUM_LEVEL,
VIP_FREE_LIMIT,
VIP_PREMIUM_LIMIT,

LUA_API_PORT,
LAST_INTEGER_CONFIG /* this must be the last one */
};

Expand Down
31 changes: 31 additions & 0 deletions src/events.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,12 @@ bool Events::load()
} else {
std::cout << "[Warning - Events::load] Unknown monster method: " << methodName << std::endl;
}
} else if (className == "Game") {
if (methodName == "onLuaApiResponse") {
info.gameOnLuaApiResponse = scriptInterface.getEvent(methodName);
} else {
std::cout << "[Warning - Events::load] Unknown game method: " << methodName << std::endl;
}
} else {
std::cout << "[Warning - Events::load] Unknown class: " << className << std::endl;
}
Expand Down Expand Up @@ -1021,3 +1027,28 @@ void Events::eventMonsterOnDropLoot(Monster* monster, Container* corpse)
return scriptInterface.callVoidFunction(2);
}

void Events::eventGameOnLuaApiResponse(uint16_t recvbyte, const std::string& name, const std::string& data)
{
// onLuaApiResponse(recvbyte, name, data)
if (info.gameOnLuaApiResponse == -1) {
return;
}

if (!scriptInterface.reserveScriptEnv()) {
std::cout << "[Error - Events::eventMiscOnLuaApiResponse] Call stack overflow" << std::endl;
return;
}

ScriptEnvironment* env = scriptInterface.getScriptEnv();
env->setScriptId(info.gameOnLuaApiResponse, &scriptInterface);

lua_State* L = scriptInterface.getLuaState();
scriptInterface.pushFunction(info.gameOnLuaApiResponse);

lua_pushnumber(L, recvbyte);
LuaScriptInterface::pushString(L, name);
LuaScriptInterface::pushString(L, data);

return scriptInterface.callVoidFunction(3);
}

6 changes: 6 additions & 0 deletions src/events.h
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,9 @@ class Events
// Monster
int32_t monsterOnDropLoot = -1;
int32_t monsterOnSpawn = -1;

// Game
int32_t gameOnLuaApiResponse = -1;
};

public:
Expand Down Expand Up @@ -108,6 +111,9 @@ class Events
void eventMonsterOnDropLoot(Monster* monster, Container* corpse);
bool eventMonsterOnSpawn(Monster* monster, const Position& position, bool startup, bool artificial);

// Game
void eventGameOnLuaApiResponse(uint16_t recvbyte, const std::string& name, const std::string& data);

private:
LuaScriptInterface scriptInterface;
EventsInfo info;
Expand Down
36 changes: 36 additions & 0 deletions src/luascript.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,42 @@ int32_t LuaScriptInterface::loadFile(const std::string& file, Npc* npc /* = null
return 0;
}

std::string LuaScriptInterface::loadString(const std::string& string, const std::string& fileName)
{
//loads string as a chunk at stack top
int ret = luaL_loadstring(luaState, string.c_str());
if (ret != 0) {
lastLuaError = popString(luaState);
return lastLuaError;
EvilHero90 marked this conversation as resolved.
Show resolved Hide resolved
}

//check that it is loaded as a function
if (!isFunction(luaState, -1)) {
return "not handled";
}

loadingFile = "lua api: " + fileName;

if (!reserveScriptEnv()) {
return "not handled";
}

ScriptEnvironment* env = getScriptEnv();
env->setScriptId(EVENT_ID_LOADING, this);

//execute it
ret = protectedCall(luaState, 0, 0);
if (ret != 0) {
lastLuaError = popString(luaState);
reportError(nullptr, lastLuaError);
resetScriptEnv();
return lastLuaError;
}

resetScriptEnv();
return "";
}

int32_t LuaScriptInterface::getEvent(const std::string& eventName)
{
//get our events table
Expand Down
1 change: 1 addition & 0 deletions src/luascript.h
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,7 @@ class LuaScriptInterface
bool reInitState();

int32_t loadFile(const std::string& file, Npc* npc = nullptr);
std::string loadString(const std::string& string, const std::string& fileName);

const std::string& getFileById(int32_t scriptId);
int32_t getEvent(const std::string& eventName);
Expand Down
4 changes: 4 additions & 0 deletions src/otserv.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
#include "protocolold.h"
#include "protocollogin.h"
#include "protocolstatus.h"
#include "protocolluaapi.h"
#include "databasemanager.h"
#include "scheduler.h"
#include "databasetasks.h"
Expand Down Expand Up @@ -303,6 +304,9 @@ void mainLoader(int, char*[], ServiceManager* services)
// Legacy login protocol
services->add<ProtocolOld>(static_cast<uint16_t>(g_config.getNumber(ConfigManager::LOGIN_PORT)));

// Lua API protocol
services->add<ProtocolLuaApi>(static_cast<uint16_t>(g_config.getNumber(ConfigManager::LUA_API_PORT)));

RentPeriod_t rentPeriod;
std::string strRentPeriod = asLowerCaseString(g_config.getString(ConfigManager::HOUSE_RENT_PERIOD));

Expand Down
131 changes: 131 additions & 0 deletions src/protocolluaapi.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
/**
* The Forgotten Server - a free and open-source MMORPG server emulator
* Copyright (C) 2019 Mark Samman <mark.samman@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

#include "otpch.h"
#include "protocolluaapi.h"
#include "outputmessage.h"
#include "script.h"
#include "configmanager.h"
#include "game.h"
#include "events.h"

extern Scripts* g_scripts;
extern ConfigManager g_config;
extern Events* g_events;

/*
* List of Packets used for communication
* --------------------------------------------------------------------
*
* Server ----> API (structure of packet)
* --------------------------------------------------------------------
* 100 => ping
* 101 => sending a callback message (string)
* 102 => sending lua error back to API (string)
* 103 => request to exchange lua code, if the API has any
* --------------------------------------------------------------------
*
* API ----> Server (structure of packet)
* --------------------------------------------------------------------
* 100 => pong
* 101 => sending raw string lua code with immediate execution (string[name], string[data])
* 102 => save server
* 103 => clean server
* 104 => close server
* 105 => start raid (string)
* 200 => reload scripts
* --------------------------------------------------------------------
*/

void ProtocolLuaApi::onRecvFirstMessage(NetworkMessage& msg)
{
// we only allow connection from the ip set in config.lua "luaApiIp = "xx.xxx.x.xx"" or from localhost.
if (convertIPToString(getIP()) != g_config.getString(ConfigManager::LUA_API_IP) || convertIPToString(getIP()) != "127.0.0.1") {
EvilHero90 marked this conversation as resolved.
Show resolved Hide resolved
std::cout << "IP: " << convertIPToString(getIP()) << " tried to connect." << std::endl;
disconnect();
return;
}

auto recvbyte = msg.get<uint16_t>();
auto name = msg.getString();
auto data = msg.getString();

switch (recvbyte) {
case 100: {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hex values?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can make it hex once the testing stage is through, not sure if we change the values at some point, or what do you think?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Client packets are parsed using hex values too, so for consistency's sake it should stay that way.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As I mentioned, I'll change them to hex once they're 100% set in stone and wont get changed

setResponse(true);
g_dispatcher.addTask(createTask(std::bind(&ProtocolLuaApi::sendCallbackMessage, std::static_pointer_cast<ProtocolLuaApi>(shared_from_this()),
"pong was successful")));
return;
}
case 101: {
auto returnvalue = g_scripts->executeString(data, name);
if (!returnvalue.empty()) {
g_dispatcher.addTask(createTask(std::bind(&ProtocolLuaApi::sendErrorMessage, std::static_pointer_cast<ProtocolLuaApi>(shared_from_this()),
returnvalue)));
return;
}
g_dispatcher.addTask(createTask(std::bind(&ProtocolLuaApi::sendCallbackMessage, std::static_pointer_cast<ProtocolLuaApi>(shared_from_this()),
"successfully executed " + name)));
return;
}
default:
g_events->eventGameOnLuaApiResponse(recvbyte, name, data);
g_dispatcher.addTask(createTask(std::bind(&ProtocolLuaApi::sendCallbackMessage, std::static_pointer_cast<ProtocolLuaApi>(shared_from_this()),
"transmission disconnected")));
}
}

// packet 100
void ProtocolLuaApi::sendPing()
{
setResponse(false);
auto output = OutputMessagePool::getOutputMessage();
EvilHero90 marked this conversation as resolved.
Show resolved Hide resolved
output->add<uint16_t>(100);
send(output);
disconnect();
}

// packet 101
void ProtocolLuaApi::sendCallbackMessage(const std::string& message)
{
auto output = OutputMessagePool::getOutputMessage();
output->add<uint16_t>(101);
output->addString(message);
send(output);
disconnect();
}

// packet 102
void ProtocolLuaApi::sendErrorMessage(const std::string& error)
{
auto output = OutputMessagePool::getOutputMessage();
output->add<uint16_t>(102);
output->addString(error);
send(output);
disconnect();
}

//packet 103
void ProtocolLuaApi::sendRequestFileExchange()
{
auto output = OutputMessagePool::getOutputMessage();
output->add<uint16_t>(103);
send(output);
disconnect();
}