/*
Minetest
Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser 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 "server.h"
#include <iostream>
#include <queue>
#include <algorithm>
#include "network/networkprotocol.h"
#include "network/serveropcodes.h"
#include "ban.h"
#include "environment.h"
#include "map.h"
#include "threading/mutex_auto_lock.h"
#include "constants.h"
#include "voxel.h"
#include "config.h"
#include "version.h"
#include "filesys.h"
#include "mapblock.h"
#include "serverobject.h"
#include "genericobject.h"
#include "settings.h"
#include "profiler.h"
#include "log.h"
#include "scripting_game.h"
#include "nodedef.h"
#include "itemdef.h"
#include "craftdef.h"
#include "emerge.h"
#include "mapgen.h"
#include "mg_biome.h"
#include "content_mapnode.h"
#include "content_nodemeta.h"
#include "content_abm.h"
#include "content_sao.h"
#include "mods.h"
#include "sound.h" // dummySoundManager
#include "event_manager.h"
#include "serverlist.h"
#include "util/string.h"
#include "util/mathconstants.h"
#include "rollback.h"
#include "util/serialize.h"
#include "util/thread.h"
#include "defaultsettings.h"
#include "util/base64.h"
#include "util/sha1.h"
#include "util/hex.h"
class ClientNotFoundException : public BaseException
{
public:
ClientNotFoundException(const char *s):
BaseException(s)
{}
};
class ServerThread : public Thread
{
public:
ServerThread(Server *server):
Thread("Server"),
m_server(server)
{}
void *run();
private:
Server *m_server;
};
void *ServerThread::run()
{
DSTACK(FUNCTION_NAME);
BEGIN_DEBUG_EXCEPTION_HANDLER
m_server->AsyncRunStep(true);
while (!stopRequested()) {
try {
//TimeTaker timer("AsyncRunStep() + Receive()");
m_server->AsyncRunStep();
m_server->Receive();
} catch (con::NoIncomingDataException &e) {
} catch (con::PeerNotFoundException &e) {
infostream<<"Server: PeerNotFoundException"<<std::endl;
} catch (ClientNotFoundException &e) {
} catch (con::ConnectionBindFailed &e) {
m_server->setAsyncFatalError(e.what());
} catch (LuaError &e) {
m_server->setAsyncFatalError("Lua: " + std::string(e.what()));
}
}
END_DEBUG_EXCEPTION_HANDLER
return NULL;
}
v3f ServerSoundParams::getPos(ServerEnvironment *env, bool *pos_exists) const
{
if(pos_exists) *pos_exists = false;
switch(type){
case SSP_LOCAL:
return v3f(0,0,0);
case SSP_POSITIONAL:
if(pos_exists) *pos_exists = true;
return pos;
case SSP_OBJECT: {
if(object == 0)
return v3f(0,0,0);
ServerActiveObject *sao = env->getActiveObject(object);
if(!sao)
return v3f(0,0,0);
if(pos_exists) *pos_exists = true;
return sao->getBasePosition(); }
}
return v3f(0,0,0);
}
/*
Server
*/
Server::Server(
const std::string &path_world,
const SubgameSpec &gamespec,
bool simple_singleplayer_mode,
bool ipv6,
ChatInterface *iface
):
m_path_world(path_world),
m_gamespec(gamespec),
m_simple_singleplayer_mode(simple_singleplayer_mode),
m_async_fatal_error(""),
m_env(NULL),
m_con(PROTOCOL_ID,
512,
CONNECTION_TIMEOUT,
ipv6,
this),
m_banmanager(NULL),
m_rollback(NULL),
m_enable_rollback_recording(false),
m_emerge(NULL),
m_script(NULL),
m_itemdef(createItemDefManager()),
m_nodedef(createNodeDefManager()),
m_craftdef(createCraftDefManager()),
m_event(new EventManager()),
m_thread(NULL),
m_time_of_day_send_timer(0),
m_uptime(0),
m_clients(&m_con),
m_shutdown_requested(false),
m_shutdown_ask_reconnect(false),
m_admin_chat(iface),
m_ignore_map_edit_events(false),
m_ignore_map_edit_events_peer_id(0),
m_next_sound_id(0)
{
m_liquid_transform_timer = 0.0;
m_liquid_transform_every = 1.0;
m_masterserver_timer = 0.0;
m_emergethread_trigger_timer = 0.0;
m_savemap_timer = 0.0;
m_step_dtime = 0.0;
m_lag = g_settings->getFloat("dedicated_server_step");
if(path_world == "")
throw ServerError("Supplied empty world path");
if(!gamespec.isValid())
throw ServerError("Supplied invalid gamespec");
infostream<<"Server created for gameid \""<<m_gamespec.id<<"\"";
if(m_simple_singleplayer_mode)
infostream<<" in simple singleplayer mode"<<std::endl;
else
infostream<<std::endl;
infostream<<"- world: "<<m_path_world<<std::endl;
infostream<<"- game: "<<m_gamespec.path<<std::endl;
// Create world if it doesn't exist
if(!loadGameConfAndInitWorld(m_path_world, m_gamespec))
throw ServerError("Failed to initialize world");
// Create server thread
m_thread = new ServerThread(this);
// Create emerge manager
m_emerge = new EmergeManager(this);
// Create ban manager
std::string ban_path = m_path_world + DIR_DELIM "ipban.txt";
m_banmanager = new BanManager(ban_path);
ModConfiguration modconf(m_path_world);
m_mods = modconf.getMods();
std::vector<ModSpec> unsatisfied_mods = modconf.getUnsatisfiedMods();
// complain about mods with unsatisfied dependencies
if(!modconf.isConsistent()) {
for(std::vector<ModSpec>::iterator it = unsatisfied_mods.begin();
it != unsatisfied_mods.end(); ++it) {
ModSpec mod = *it;
errorstream << "mod \"" << mod.name << "\" has unsatisfied dependencies: ";
for(std::set<std::string>::iterator dep_it = mod.unsatisfied_depends.begin();
dep_it != mod.unsatisfied_depends.end(); ++dep_it)
errorstream << " \"" << *dep_it << "\"";
errorstream << std::endl;
}
}
Settings worldmt_settings;
std::string worldmt = m_path_world + DIR_DELIM + "world.mt";
worldmt_settings.readConfigFile(worldmt.c_str());
std::vector<std::string> names = worldmt_settings.getNames();
std::set<std::string> load_mod_names;
for(std::vector<std::string>::iterator it = names.begin();
it != names.end(); ++it) {
std::string name = *it;
if(name.compare(0,9,"load_mod_")==0 && worldmt_settings.getBool(name))
load_mod_names.insert(name.substr(9));
}
// complain about mods declared to be loaded, but not found
for(std::vector<ModSpec>::iterator it = m_mods.begin();
it != m_mods.end(); ++it)
load_mod_names.erase((*it).name);
for(std::vector<ModSpec>::iterator it = unsatisfied_mods.begin();
it != unsatisfied_mods.end(); ++it)
load_mod_names.erase((*it).name);
if(!load_mod_names.empty()) {
errorstream << "The following mods could not be found:";
for(std::set<std::string>::iterator it = load_mod_names.begin();
it != load_mod_names.end(); ++it)
errorstream << " \"" << (*it) << "\"";
errorstream << std::endl;
}
//lock environment
MutexAutoLock envlock(m_env_mutex);
// Create the Map (loads map_meta.txt, overriding configured mapgen params)
ServerMap *servermap = new ServerMap(path_world, this, m_emerge);
// Initialize scripting
infostream<<"Server: Initializing Lua"<<std::endl;
m_script = new GameScripting(this);
std::string script_path = getBuiltinLuaPath() + DIR_DELIM "init.lua";
m_script->loadMod(script_path, BUILTIN_MOD_NAME);
// Print mods
infostream << "Server: Loading mods: ";
for(std::vector<ModSpec>::iterator i = m_mods.begin();
i != m_mods.end(); ++i) {
const ModSpec &mod = *i;
infostream << mod.name << " ";
}
infostream << std::endl;
// Load and run "mod" scripts
for (std::vector<ModSpec>::iterator it = m_mods.begin();
it != m_mods.end(); ++it) {
const ModSpec &mod = *it;
if (!string_allowed(mod.name, MODNAME_ALLOWED_CHARS)) {
throw ModError("Error loading mod \"" + mod.name +
"\": Mod name does not follow naming conventions: "
"Only chararacters [a-z0-9_] are allowed.");
}
std::string script_path = mod.path + DIR_DELIM + "init.lua";
infostream << " [" << padStringRight(mod.name, 12) << "] [\""
<< script_path << "\"]" << std::endl;
m_script->loadMod(script_path, mod.name);
}
// Read Textures and calculate sha1 sums
fillMediaCache();
// Apply item aliases in the node definition manager
m_nodedef->updateAliases(m_itemdef);
// Apply texture overrides from texturepack/override.txt
std::string texture_path = g_settings->get("texture_path");
if (texture_path != "" && fs::IsDir(texture_path))
m_nodedef->applyTextureOverrides(texture_path + DIR_DELIM + "override.txt");
m_nodedef->setNodeRegistrationStatus(true);
// Perform pending node name resolutions
m_nodedef->runNodeResolveCallbacks();
// unmap node names for connected nodeboxes
m_nodedef->mapNodeboxConnections();
// init the recipe hashes to speed up crafting
m_craftdef->initHashes(this);
// Initialize Environment
m_env = new ServerEnvironment(servermap, m_script, this, m_path_world);
m_clients.setEnv(m_env);
if (!servermap->settings_mgr.makeMapgenParams())
FATAL_ERROR("Couldn't create any mapgen type");
// Initialize mapgens
m_emerge->initMapgens(servermap->getMapgenParams());
m_enable_rollback_recording = g_settings->getBool("enable_rollback_recording");
if (m_enable_rollback_recording) {
// Create rollback manager
m_rollback = new RollbackManager(m_path_world, this);
}
// Give environment reference to scripting api
m_script->initializeEnvironment(m_env);
// Register us to receive map edit events
servermap->addEventReceiver(this);
// If file exists, load environment metadata
if (fs::PathExists(m_path_world + DIR_DELIM "env_meta.txt")) {
infostream << "Server: Loading environment metadata" << std::endl;
m_env->loadMeta();
} else {
m_env->loadDefaultMeta();
}
// Add some test ActiveBlockModifiers to environment
add_legacy_abms(m_env, m_nodedef);
m_liquid_transform_every = g_settings->getFloat("liquid_update");
m_max_chatmessage_length = g_settings->getU16("chat_message_max_size");
}
Server::~Server()
{
infostream<<"Server destructing"<<std::endl;
// Send shutdown message
SendChatMessage(PEER_ID_INEXISTENT, L"*** Server shutting down");
{
MutexAutoLock envlock(m_env_mutex);
// Execute script shutdown hooks
m_script->on_shutdown();
infostream << "Server: Saving players" << std::endl;
m_env->saveLoadedPlayers();
infostream << "Server: Kicking players" << std::endl;
std::string kick_msg;
bool reconnect = false;
if (getShutdownRequested()) {
reconnect = m_shutdown_ask_reconnect;
kick_msg = m_shutdown_msg;
}
if (kick_msg == "") {
kick_msg = g_settings->get("kick_msg_shutdown");
}
m_env->kickAllPlayers(SERVER_ACCESSDENIED_SHUTDOWN,
kick_msg, reconnect);
infostream << "Server: Saving environment metadata" << std::endl;
m_env->saveMeta();
}
// Stop threads
stop();
delete m_thread;
// stop all emerge threads before deleting players that may have
// requested blocks to be emerged
m_emerge->stopThreads();
// Delete things in the reverse order of creation
delete m_emerge;
delete m_env;
delete m_rollback;
delete m_banmanager;
delete m_event;
delete m_itemdef;
delete m_nodedef;
delete m_craftdef;
// Deinitialize scripting
infostream<<"Server: Deinitializing scripting"<<std::endl;
delete m_script;
// Delete detached inventories
for (std::map<std::string, Inventory*>::iterator
i = m_detached_inventories.begin();
i != m_detached_inventories.end(); ++i) {
delete i->second;
}
}
void Server::start(Address bind_addr)
{
DSTACK(FUNCTION_NAME);
m_bind_addr = bind_addr;
infostream<<"Starting server on "
<< bind_addr.serializeString() <<"..."<<std::endl;
// Stop thread if already running
m_thread->stop();
// Initialize connection
m_con.SetTimeoutMs(30);
m_con.Serve(bind_addr);
// Start thread
m_thread->start();
// ASCII art for the win!
actionstream
<<" .__ __ __ "<<std::endl
<<" _____ |__| ____ _____/ |_ ____ _______/ |_ "<<std::endl
<<" / \\| |/ \\_/ __ \\ __\\/ __ \\ / ___/\\ __\\"<<std::endl
<<"| Y Y \\ | | \\ ___/| | \\ ___/ \\___ \\ | | "<<std::endl
<<"|__|_| /__|___| /\\___ >__| \\___ >____ > |__| "<<std::endl
<<" \\/ \\/ \\/ \\/ \\/ "<<std::endl;
actionstream<<"World at ["<<m_path_world<<"]"<<std::endl;
actionstream<<"Server for gameid=\""<<m_gamespec.id
<<"\" listening on "<<bind_addr.serializeString()<<":"
<<bind_addr.getPort() << "."<<std::endl;
}
void Server::stop()
{
DSTACK(FUNCTION_NAME);
infostream<<"Server: Stopping and waiting threads"<<std::endl;
// Stop threads (set run=false first so both start stopping)
m_thread->stop();
//m_emergethread.setRun(false);
m_thread->wait();
//m_emergethread.stop();
infostream<<"Server: Threads stopped"<<std::endl;
}
void Server::step(float dtime)
{
DSTACK(FUNCTION_NAME);
// Limit a bit
if (dtime > 2.0)
dtime = 2.0;
{
MutexAutoLock lock(m_step_dtime_mutex);
m_step_dtime += dtime;
}
// Throw if fatal error occurred in thread
std::string async_err = m_async_fatal_error.get();
if (!async_err.empty()) {
if (!m_simple_singleplayer_mode) {
m_env->kickAllPlayers(SERVER_ACCESSDENIED_CRASH,
g_settings->get("kick_msg_crash"),
g_settings->getBool("ask_reconnect_on_crash"));
}
throw ServerError(async_err);
}
}
void Server::AsyncRunStep(bool initial_step)
{
DSTACK(FUNCTION_NAME);
g_profiler->add("Server::AsyncRunStep (num)", 1);
float dtime;
{
MutexAutoLock lock1(m_step_dtime_mutex);
dtime = m_step_dtime;
}
{
// Send blocks to clients
SendBlocks(dtime);
}
if((dtime < 0.001) && (initial_step == false))
return;
g_profiler->add("Server::AsyncRunStep with dtime (num)", 1);
//infostream<<"Server steps "<<dtime<<std::endl;
//infostream<<"Server::AsyncRunStep(): dtime="<<dtime<<std::endl;
{
MutexAutoLock lock1(m_step_dtime_mutex);
m_step_dtime -= dtime;
}
/*
Update uptime
*/
{
m_uptime.set(m_uptime.get() + dtime);
}
handlePeerChanges();
/*
Update time of day and overall game time
*/
m_env->setTimeOfDaySpeed(g_settings->getFloat("time_speed"));
/*
Send to clients at constant intervals
*/
m_time_of_day_send_timer -= dtime;
if(m_time_of_day_send_timer < 0.0) {
m_time_of_day_send_timer = g_settings->getFloat("time_send_interval");
u16 time = m_env->getTimeOfDay();
float time_speed = g_settings->getFloat("time_speed");
SendTimeOfDay(PEER_ID_INEXISTENT, time, time_speed);
}
{
MutexAutoLock lock(m_env_mutex);
// Figure out and report maximum lag to environment
float max_lag = m_env->getMaxLagEstimate();
max_lag *= 0.9998; // Decrease slowly (about half per 5 minutes)
if(dtime > max_lag){
if(dtime > 0.1 && dtime > max_lag * 2.0)
infostream<<"Server: Maximum lag peaked to "<<dtime
<<" s"<<std::endl;
|