]> git.lizzy.rs Git - dragonfireclient.git/blobdiff - src/server.cpp
Change i++ to ++i
[dragonfireclient.git] / src / server.cpp
index 8c76fdc16749f8dc5fd6b334586d479b219ffb46..646e8465bf54b9b977c2db7fdf470d61c1bbd08c 100644 (file)
@@ -26,8 +26,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
 #include "ban.h"
 #include "environment.h"
 #include "map.h"
-#include "jthread/jmutexautolock.h"
-#include "main.h"
+#include "threading/mutex_auto_lock.h"
 #include "constants.h"
 #include "voxel.h"
 #include "config.h"
@@ -72,61 +71,44 @@ class ClientNotFoundException : public BaseException
        {}
 };
 
-class ServerThread : public JThread
+class ServerThread : public Thread
 {
-       Server *m_server;
-
 public:
 
        ServerThread(Server *server):
-               JThread(),
+               Thread("Server"),
                m_server(server)
-       {
-       }
+       {}
+
+       void *run();
 
-       void * Thread();
+private:
+       Server *m_server;
 };
 
-void * ServerThread::Thread()
+void *ServerThread::run()
 {
-       log_register_thread("ServerThread");
-
        DSTACK(__FUNCTION_NAME);
        BEGIN_DEBUG_EXCEPTION_HANDLER
 
        m_server->AsyncRunStep(true);
 
-       ThreadStarted();
-
-       porting::setThreadName("ServerThread");
-
-       while(!StopRequested())
-       {
-               try{
+       while (!stopRequested()) {
+               try {
                        //TimeTaker timer("AsyncRunStep() + Receive()");
 
                        m_server->AsyncRunStep();
 
                        m_server->Receive();
 
-               }
-               catch(con::NoIncomingDataException &e)
-               {
-               }
-               catch(con::PeerNotFoundException &e)
-               {
+               } 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)
-               {
+               } catch (ClientNotFoundException &e) {
+               } catch (con::ConnectionBindFailed &e) {
                        m_server->setAsyncFatalError(e.what());
+               } catch (LuaError &e) {
+                       m_server->setAsyncFatalError("Lua: " + std::string(e.what()));
                }
        }
 
@@ -192,6 +174,7 @@ Server::Server(
        m_uptime(0),
        m_clients(&m_con),
        m_shutdown_requested(false),
+       m_shutdown_ask_reconnect(false),
        m_ignore_map_edit_events(false),
        m_ignore_map_edit_events_peer_id(0),
        m_next_sound_id(0)
@@ -240,11 +223,9 @@ Server::Server(
        m_mods = modconf.getMods();
        std::vector<ModSpec> unsatisfied_mods = modconf.getUnsatisfiedMods();
        // complain about mods with unsatisfied dependencies
-       if(!modconf.isConsistent())
-       {
+       if(!modconf.isConsistent()) {
                for(std::vector<ModSpec>::iterator it = unsatisfied_mods.begin();
-                       it != unsatisfied_mods.end(); ++it)
-               {
+                       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();
@@ -260,8 +241,7 @@ Server::Server(
        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)
-       {
+               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));
@@ -273,8 +253,7 @@ Server::Server(
        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())
-       {
+       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)
@@ -282,8 +261,8 @@ Server::Server(
                errorstream << std::endl;
        }
 
-       // Lock environment
-       JMutexAutoLock envlock(m_env_mutex);
+       //lock environment
+       MutexAutoLock envlock(m_env_mutex);
 
        // Load mapgen params from Settings
        m_emerge->loadMapgenParams();
@@ -296,31 +275,41 @@ Server::Server(
 
        m_script = new GameScripting(this);
 
-       std::string scriptpath = getBuiltinLuaPath() + DIR_DELIM "init.lua";
+       std::string script_path = getBuiltinLuaPath() + DIR_DELIM "init.lua";
+       std::string error_msg;
 
-       if (!m_script->loadScript(scriptpath))
-               throw ModError("Failed to load and run " + scriptpath);
+       if (!m_script->loadMod(script_path, BUILTIN_MOD_NAME, &error_msg))
+               throw ModError("Failed to load and run " + script_path
+                               + "\nError from Lua:\n" + error_msg);
 
-       // Print 'em
-       infostream<<"Server: Loading mods: ";
+       // Print mods
+       infostream << "Server: Loading mods: ";
        for(std::vector<ModSpec>::iterator i = m_mods.begin();
-                       i != m_mods.end(); i++){
+                       i != m_mods.end(); ++i) {
                const ModSpec &mod = *i;
-               infostream<<mod.name<<" ";
+               infostream << mod.name << " ";
        }
-       infostream<<std::endl;
+       infostream << std::endl;
        // Load and run "mod" scripts
-       for(std::vector<ModSpec>::iterator i = m_mods.begin();
-                       i != m_mods.end(); i++){
+       for (std::vector<ModSpec>::iterator i = m_mods.begin();
+                       i != m_mods.end(); ++i) {
                const ModSpec &mod = *i;
-               std::string scriptpath = mod.path + DIR_DELIM + "init.lua";
-               infostream<<"  ["<<padStringRight(mod.name, 12)<<"] [\""
-                               <<scriptpath<<"\"]"<<std::endl;
-               bool success = m_script->loadMod(scriptpath, mod.name);
-               if(!success){
-                       errorstream<<"Server: Failed to load and run "
-                                       <<scriptpath<<std::endl;
-                       throw ModError("Failed to load and run "+scriptpath);
+               if (!string_allowed(mod.name, MODNAME_ALLOWED_CHARS)) {
+                       std::ostringstream err;
+                       err << "Error loading mod \"" << mod.name
+                                       << "\": mod_name does not follow naming conventions: "
+                                       << "Only chararacters [a-z0-9_] are allowed." << std::endl;
+                       errorstream << err.str().c_str();
+                       throw ModError(err.str());
+               }
+               std::string script_path = mod.path + DIR_DELIM "init.lua";
+               infostream << "  [" << padStringRight(mod.name, 12) << "] [\""
+                               << script_path << "\"]" << std::endl;
+               if (!m_script->loadMod(script_path, mod.name, &error_msg)) {
+                       errorstream << "Server: Failed to load and run "
+                                       << script_path << std::endl;
+                       throw ModError("Failed to load and run " + script_path
+                                       + "\nError from Lua:\n" + error_msg);
                }
        }
 
@@ -330,10 +319,18 @@ Server::Server(
        // 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->runNodeResolverCallbacks();
+       m_nodedef->runNodeResolveCallbacks();
+
+       // 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);
@@ -376,15 +373,28 @@ Server::~Server()
        SendChatMessage(PEER_ID_INEXISTENT, L"*** Server shutting down");
 
        {
-               JMutexAutoLock envlock(m_env_mutex);
+               MutexAutoLock envlock(m_env_mutex);
 
                // Execute script shutdown hooks
                m_script->on_shutdown();
 
-               infostream<<"Server: Saving players"<<std::endl;
+               infostream << "Server: Saving players" << std::endl;
                m_env->saveLoadedPlayers();
 
-               infostream<<"Server: Saving environment metadata"<<std::endl;
+               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();
        }
 
@@ -416,7 +426,7 @@ Server::~Server()
        // Delete detached inventories
        for (std::map<std::string, Inventory*>::iterator
                        i = m_detached_inventories.begin();
-                       i != m_detached_inventories.end(); i++) {
+                       i != m_detached_inventories.end(); ++i) {
                delete i->second;
        }
 }
@@ -431,14 +441,14 @@ void Server::start(Address bind_addr)
                        << bind_addr.serializeString() <<"..."<<std::endl;
 
        // Stop thread if already running
-       m_thread->Stop();
+       m_thread->stop();
 
        // Initialize connection
        m_con.SetTimeoutMs(30);
        m_con.Serve(bind_addr);
 
        // Start thread
-       m_thread->Start();
+       m_thread->start();
 
        // ASCII art for the win!
        actionstream
@@ -461,9 +471,9 @@ void Server::stop()
        infostream<<"Server: Stopping and waiting threads"<<std::endl;
 
        // Stop threads (set run=false first so both start stopping)
-       m_thread->Stop();
+       m_thread->stop();
        //m_emergethread.setRun(false);
-       m_thread->Wait();
+       m_thread->wait();
        //m_emergethread.stop();
 
        infostream<<"Server: Threads stopped"<<std::endl;
@@ -476,7 +486,7 @@ void Server::step(float dtime)
        if(dtime > 2.0)
                dtime = 2.0;
        {
-               JMutexAutoLock lock(m_step_dtime_mutex);
+               MutexAutoLock lock(m_step_dtime_mutex);
                m_step_dtime += dtime;
        }
        // Throw if fatal error occurred in thread
@@ -486,6 +496,9 @@ void Server::step(float dtime)
                        throw ServerError(async_err);
                }
                else {
+                       m_env->kickAllPlayers(SERVER_ACCESSDENIED_CRASH,
+                               g_settings->get("kick_msg_crash"),
+                               g_settings->getBool("ask_reconnect_on_crash"));
                        errorstream << "UNRECOVERABLE error occurred. Stopping server. "
                                        << "Please fix the following error:" << std::endl
                                        << async_err << std::endl;
@@ -502,7 +515,7 @@ void Server::AsyncRunStep(bool initial_step)
 
        float dtime;
        {
-               JMutexAutoLock lock1(m_step_dtime_mutex);
+               MutexAutoLock lock1(m_step_dtime_mutex);
                dtime = m_step_dtime;
        }
 
@@ -520,7 +533,7 @@ void Server::AsyncRunStep(bool initial_step)
        //infostream<<"Server::AsyncRunStep(): dtime="<<dtime<<std::endl;
 
        {
-               JMutexAutoLock lock1(m_step_dtime_mutex);
+               MutexAutoLock lock1(m_step_dtime_mutex);
                m_step_dtime -= dtime;
        }
 
@@ -551,7 +564,7 @@ void Server::AsyncRunStep(bool initial_step)
        }
 
        {
-               JMutexAutoLock lock(m_env_mutex);
+               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)
@@ -571,11 +584,12 @@ void Server::AsyncRunStep(bool initial_step)
        static const float map_timer_and_unload_dtime = 2.92;
        if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime))
        {
-               JMutexAutoLock lock(m_env_mutex);
+               MutexAutoLock lock(m_env_mutex);
                // Run Map's timers and unload unused data
                ScopeProfiler sp(g_profiler, "Server: map timer and unload");
                m_env->getMap().timerUpdate(map_timer_and_unload_dtime,
-                               g_settings->getFloat("server_unload_unused_data_timeout"));
+                       g_settings->getFloat("server_unload_unused_data_timeout"),
+                       (u32)-1);
        }
 
        /*
@@ -588,7 +602,7 @@ void Server::AsyncRunStep(bool initial_step)
        {
                m_liquid_transform_timer -= m_liquid_transform_every;
 
-               JMutexAutoLock lock(m_env_mutex);
+               MutexAutoLock lock(m_env_mutex);
 
                ScopeProfiler sp(g_profiler, "Server: liquid transform");
 
@@ -649,9 +663,9 @@ void Server::AsyncRunStep(bool initial_step)
        */
        {
                //infostream<<"Server: Checking added and deleted active objects"<<std::endl;
-               JMutexAutoLock envlock(m_env_mutex);
+               MutexAutoLock envlock(m_env_mutex);
 
-               m_clients.Lock();
+               m_clients.lock();
                std::map<u16, RemoteClient*> clients = m_clients.getClientList();
                ScopeProfiler sp(g_profiler, "Server: checking added and deleted objs");
 
@@ -772,14 +786,14 @@ void Server::AsyncRunStep(bool initial_step)
                                        << added_objects.size() << " added, "
                                        << "packet size is " << pktSize << std::endl;
                }
-               m_clients.Unlock();
+               m_clients.unlock();
        }
 
        /*
                Send object messages
        */
        {
-               JMutexAutoLock envlock(m_env_mutex);
+               MutexAutoLock envlock(m_env_mutex);
                ScopeProfiler sp(g_profiler, "Server: sending object messages");
 
                // Key = object id
@@ -805,7 +819,7 @@ void Server::AsyncRunStep(bool initial_step)
                        message_list->push_back(aom);
                }
 
-               m_clients.Lock();
+               m_clients.lock();
                std::map<u16, RemoteClient*> clients = m_clients.getClientList();
                // Route data to every client
                for (std::map<u16, RemoteClient*>::iterator
@@ -856,7 +870,7 @@ void Server::AsyncRunStep(bool initial_step)
                                SendActiveObjectMessages(client->peer_id, unreliable_data, false);
                        }
                }
-               m_clients.Unlock();
+               m_clients.unlock();
 
                // Clear buffered_messages
                for(std::map<u16, std::vector<ActiveObjectMessage>* >::iterator
@@ -871,7 +885,7 @@ void Server::AsyncRunStep(bool initial_step)
        */
        {
                // We will be accessing the environment
-               JMutexAutoLock lock(m_env_mutex);
+               MutexAutoLock lock(m_env_mutex);
 
                // Don't send too many at a time
                //u32 count = 0;
@@ -992,7 +1006,7 @@ void Server::AsyncRunStep(bool initial_step)
                if(counter >= g_settings->getFloat("server_map_save_interval"))
                {
                        counter = 0.0;
-                       JMutexAutoLock lock(m_env_mutex);
+                       MutexAutoLock lock(m_env_mutex);
 
                        ScopeProfiler sp(g_profiler, "Server: saving stuff");
 
@@ -1018,10 +1032,11 @@ void Server::Receive()
        DSTACK(__FUNCTION_NAME);
        SharedBuffer<u8> data;
        u16 peer_id;
-       u32 datasize;
        try {
-               datasize = m_con.Receive(peer_id,data);
-               ProcessData(*data, datasize, peer_id);
+               NetworkPacket pkt;
+               m_con.Receive(&pkt);
+               peer_id = pkt.getPeerId();
+               ProcessData(&pkt);
        }
        catch(con::InvalidIncomingDataException &e) {
                infostream<<"Server::Receive(): "
@@ -1047,33 +1062,33 @@ PlayerSAO* Server::StageTwoClientInit(u16 peer_id)
 {
        std::string playername = "";
        PlayerSAO *playersao = NULL;
-       m_clients.Lock();
+       m_clients.lock();
        try {
                RemoteClient* client = m_clients.lockedGetClientNoEx(peer_id, CS_InitDone);
                if (client != NULL) {
                        playername = client->getName();
-                       playersao = emergePlayer(playername.c_str(), peer_id);
+                       playersao = emergePlayer(playername.c_str(), peer_id, client->net_proto_version);
                }
        } catch (std::exception &e) {
-               m_clients.Unlock();
+               m_clients.unlock();
                throw;
        }
-       m_clients.Unlock();
+       m_clients.unlock();
 
        RemotePlayer *player =
                static_cast<RemotePlayer*>(m_env->getPlayer(playername.c_str()));
 
        // If failed, cancel
-       if((playersao == NULL) || (player == NULL)) {
-               if(player && player->peer_id != 0) {
-                       errorstream<<"Server: "<<playername<<": Failed to emerge player"
-                                       <<" (player allocated to an another client)"<<std::endl;
+       if ((playersao == NULL) || (player == NULL)) {
+               if (player && player->peer_id != 0) {
+                       actionstream << "Server: Failed to emerge player \"" << playername
+                                       << "\" (player allocated to an another client)" << std::endl;
                        DenyAccess_Legacy(peer_id, L"Another client is connected with this "
                                        L"name. If your client closed unexpectedly, try again in "
                                        L"a minute.");
                } else {
-                       errorstream<<"Server: "<<playername<<": Failed to emerge player"
-                                       <<std::endl;
+                       errorstream << "Server: " << playername << ": Failed to emerge player"
+                                       << std::endl;
                        DenyAccess_Legacy(peer_id, L"Could not allocate player.");
                }
                return NULL;
@@ -1094,7 +1109,7 @@ PlayerSAO* Server::StageTwoClientInit(u16 peer_id)
        SendInventory(playersao);
 
        // Send HP
-       SendPlayerHPOrDie(peer_id, playersao->getHP() == 0);
+       SendPlayerHPOrDie(playersao);
 
        // Send Breath
        SendPlayerBreath(peer_id);
@@ -1134,7 +1149,7 @@ PlayerSAO* Server::StageTwoClientInit(u16 peer_id)
                actionstream<<player->getName() <<" joins game. List of players: ";
 
                for (std::vector<std::string>::iterator i = names.begin();
-                               i != names.end(); i++) {
+                               i != names.end(); ++i) {
                        actionstream << *i << " ";
                }
 
@@ -1149,13 +1164,14 @@ inline void Server::handleCommand(NetworkPacket* pkt)
        (this->*opHandle.handler)(pkt);
 }
 
-void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
+void Server::ProcessData(NetworkPacket *pkt)
 {
        DSTACK(__FUNCTION_NAME);
        // Environment is locked first.
-       JMutexAutoLock envlock(m_env_mutex);
+       MutexAutoLock envlock(m_env_mutex);
 
        ScopeProfiler sp(g_profiler, "Server::ProcessData");
+       u32 peer_id = pkt->getPeerId();
 
        try {
                Address address = getPeerAddress(peer_id);
@@ -1168,7 +1184,7 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
                                        << ban_name << std::endl;
                        // This actually doesn't seem to transfer to the client
                        DenyAccess_Legacy(peer_id, L"Your ip is banned. Banned name was "
-                                       + narrow_to_wide(ban_name));
+                                       + utf8_to_wide(ban_name));
                        return;
                }
        }
@@ -1179,27 +1195,23 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
                 * respond for some time, your server was overloaded or
                 * things like that.
                 */
-               infostream << "Server::ProcessData(): Cancelling: peer "
+               infostream << "Server::ProcessData(): Canceling: peer "
                                << peer_id << " not found" << std::endl;
                return;
        }
 
        try {
-               if(datasize < 2)
-                       return;
-
-               NetworkPacket pkt(data, datasize, peer_id);
-
-               ToServerCommand command = (ToServerCommand) pkt.getCommand();
+               ToServerCommand command = (ToServerCommand) pkt->getCommand();
 
                // Command must be handled into ToServerCommandHandler
                if (command >= TOSERVER_NUM_MSG_TYPES) {
                        infostream << "Server: Ignoring unknown command "
                                         << command << std::endl;
+                       return;
                }
 
                if (toServerCommandTable[command].state == TOSERVER_STATE_NOT_CONNECTED) {
-                       handleCommand(&pkt);
+                       handleCommand(pkt);
                        return;
                }
 
@@ -1214,7 +1226,7 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
 
                /* Handle commands related to client startup */
                if (toServerCommandTable[command].state == TOSERVER_STATE_STARTUP) {
-                       handleCommand(&pkt);
+                       handleCommand(pkt);
                        return;
                }
 
@@ -1227,12 +1239,15 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
                        return;
                }
 
-               handleCommand(&pkt);
-       }
-       catch(SendFailedException &e) {
+               handleCommand(pkt);
+       } catch (SendFailedException &e) {
                errorstream << "Server::ProcessData(): SendFailedException: "
                                << "what=" << e.what()
                                << std::endl;
+       } catch (PacketError &e) {
+               actionstream << "Server::ProcessData(): PacketError: "
+                               << "what=" << e.what()
+                               << std::endl;
        }
 }
 
@@ -1335,14 +1350,14 @@ void Server::setInventoryModified(const InventoryLocation &loc, bool playerSend)
 void Server::SetBlocksNotSent(std::map<v3s16, MapBlock *>& block)
 {
        std::vector<u16> clients = m_clients.getClientIDs();
-       m_clients.Lock();
+       m_clients.lock();
        // Set the modified blocks unsent for all the clients
        for (std::vector<u16>::iterator i = clients.begin();
                 i != clients.end(); ++i) {
                        if (RemoteClient *client = m_clients.lockedGetClientNoEx(*i))
                                client->SetBlocksNotSent(block);
        }
-       m_clients.Unlock();
+       m_clients.unlock();
 }
 
 void Server::peerAdded(con::Peer *peer)
@@ -1392,11 +1407,11 @@ bool Server::getClientInfo(
        )
 {
        *state = m_clients.getClientState(peer_id);
-       m_clients.Lock();
+       m_clients.lock();
        RemoteClient* client = m_clients.lockedGetClientNoEx(peer_id, CS_Invalid);
 
        if (client == NULL) {
-               m_clients.Unlock();
+               m_clients.unlock();
                return false;
        }
 
@@ -1409,7 +1424,7 @@ bool Server::getClientInfo(
        *patch = client->getPatch();
        *vers_string = client->getPatch();
 
-       m_clients.Unlock();
+       m_clients.unlock();
 
        return true;
 }
@@ -1473,6 +1488,20 @@ void Server::SendMovement(u16 peer_id)
        Send(&pkt);
 }
 
+void Server::SendPlayerHPOrDie(PlayerSAO *playersao)
+{
+       if (!g_settings->getBool("enable_damage"))
+               return;
+
+       u16 peer_id   = playersao->getPeerID();
+       bool is_alive = playersao->getHP() > 0;
+
+       if (is_alive)
+               SendPlayerHP(peer_id);
+       else
+               DiePlayer(peer_id);
+}
+
 void Server::SendHP(u16 peer_id, u8 hp)
 {
        DSTACK(__FUNCTION_NAME);
@@ -1491,16 +1520,18 @@ void Server::SendBreath(u16 peer_id, u16 breath)
        Send(&pkt);
 }
 
-void Server::SendAccessDenied(u16 peer_id, AccessDeniedCode reason, const std::wstring &custom_reason)
+void Server::SendAccessDenied(u16 peer_id, AccessDeniedCode reason,
+               const std::string &custom_reason, bool reconnect)
 {
-       DSTACK(__FUNCTION_NAME);
+       assert(reason < SERVER_ACCESSDENIED_MAX);
 
        NetworkPacket pkt(TOCLIENT_ACCESS_DENIED, 1, peer_id);
-       pkt << (u8) reason;
-
-       if (reason == SERVER_ACCESSDENIED_CUSTOM_STRING) {
+       pkt << (u8)reason;
+       if (reason == SERVER_ACCESSDENIED_CUSTOM_STRING)
                pkt << custom_reason;
-       }
+       else if (reason == SERVER_ACCESSDENIED_SHUTDOWN ||
+                       reason == SERVER_ACCESSDENIED_CRASH)
+               pkt << custom_reason << (u8)reconnect;
        Send(&pkt);
 }
 
@@ -1803,7 +1834,11 @@ void Server::SendPlayerHP(u16 peer_id)
 {
        DSTACK(__FUNCTION_NAME);
        PlayerSAO *playersao = getPlayerSAO(peer_id);
-       assert(playersao);
+       // In some rare case, if the player is disconnected
+       // while Lua call l_punch, for example, this can be NULL
+       if (!playersao)
+               return;
+
        SendHP(peer_id, playersao->getHP());
        m_script->player_event(playersao,"health_changed");
 
@@ -1877,7 +1912,7 @@ void Server::SendPlayerPrivileges(u16 peer_id)
        pkt << (u16) privs.size();
 
        for(std::set<std::string>::const_iterator i = privs.begin();
-                       i != privs.end(); i++) {
+                       i != privs.end(); ++i) {
                pkt << (*i);
        }
 
@@ -1898,7 +1933,7 @@ void Server::SendPlayerInventoryFormspec(u16 peer_id)
 
 u32 Server::SendActiveObjectRemoveAdd(u16 peer_id, const std::string &datas)
 {
-       NetworkPacket pkt(TOCLIENT_ACTIVE_OBJECT_REMOVE_ADD, 0, peer_id);
+       NetworkPacket pkt(TOCLIENT_ACTIVE_OBJECT_REMOVE_ADD, datas.size(), peer_id);
        pkt.putRawString(datas.c_str(), datas.size());
        Send(&pkt);
        return pkt.getSize();
@@ -1907,12 +1942,12 @@ u32 Server::SendActiveObjectRemoveAdd(u16 peer_id, const std::string &datas)
 void Server::SendActiveObjectMessages(u16 peer_id, const std::string &datas, bool reliable)
 {
        NetworkPacket pkt(TOCLIENT_ACTIVE_OBJECT_MESSAGES,
-                       0, peer_id);
+                       datas.size(), peer_id);
 
        pkt.putRawString(datas.c_str(), datas.size());
 
        m_clients.send(pkt.getPeerId(),
-                       clientCommandFactoryTable[pkt.getCommand()].channel,
+                       reliable ? clientCommandFactoryTable[pkt.getCommand()].channel : 1,
                        &pkt, reliable);
 
 }
@@ -1977,7 +2012,7 @@ s32 Server::playSound(const SimpleSoundSpec &spec,
                        << (u8) params.type << pos << params.object << params.loop;
 
        for(std::vector<u16>::iterator i = dst_clients.begin();
-                       i != dst_clients.end(); i++) {
+                       i != dst_clients.end(); ++i) {
                psound.clients.insert(*i);
                m_clients.send(*i, 0, &pkt, true);
        }
@@ -1996,7 +2031,7 @@ void Server::stopSound(s32 handle)
        pkt << handle;
 
        for(std::set<u16>::iterator i = psound.clients.begin();
-                       i != psound.clients.end(); i++) {
+                       i != psound.clients.end(); ++i) {
                // Send as reliable
                m_clients.send(*i, 0, &pkt, true);
        }
@@ -2057,7 +2092,7 @@ void Server::sendAddNode(v3s16 p, MapNode n, u16 ignore_id,
                }
 
                NetworkPacket pkt(TOCLIENT_ADDNODE, 6 + 2 + 1 + 1 + 1);
-               m_clients.Lock();
+               m_clients.lock();
                RemoteClient* client = m_clients.lockedGetClientNoEx(*i);
                if (client != 0) {
                        pkt << p << n.param0 << n.param1 << n.param2
@@ -2071,7 +2106,7 @@ void Server::sendAddNode(v3s16 p, MapNode n, u16 ignore_id,
                                }
                        }
                }
-               m_clients.Unlock();
+               m_clients.unlock();
 
                // Send as reliable
                if (pkt.getSize() > 0)
@@ -2082,13 +2117,13 @@ void Server::sendAddNode(v3s16 p, MapNode n, u16 ignore_id,
 void Server::setBlockNotSent(v3s16 p)
 {
        std::vector<u16> clients = m_clients.getClientIDs();
-       m_clients.Lock();
+       m_clients.lock();
        for(std::vector<u16>::iterator i = clients.begin();
                i != clients.end(); ++i) {
                RemoteClient *client = m_clients.lockedGetClientNoEx(*i);
                client->SetBlockNotSent(p);
        }
-       m_clients.Unlock();
+       m_clients.unlock();
 }
 
 void Server::SendBlockNoLock(u16 peer_id, MapBlock *block, u8 ver, u16 net_proto_version)
@@ -2117,7 +2152,7 @@ void Server::SendBlocks(float dtime)
 {
        DSTACK(__FUNCTION_NAME);
 
-       JMutexAutoLock envlock(m_env_mutex);
+       MutexAutoLock envlock(m_env_mutex);
        //TODO check if one big lock could be faster then multiple small ones
 
        ScopeProfiler sp(g_profiler, "Server: sel and send blocks to clients");
@@ -2131,7 +2166,7 @@ void Server::SendBlocks(float dtime)
 
                std::vector<u16> clients = m_clients.getClientIDs();
 
-               m_clients.Lock();
+               m_clients.lock();
                for(std::vector<u16>::iterator i = clients.begin();
                        i != clients.end(); ++i) {
                        RemoteClient *client = m_clients.lockedGetClientNoEx(*i, CS_Active);
@@ -2142,7 +2177,7 @@ void Server::SendBlocks(float dtime)
                        total_sending += client->SendingCount();
                        client->GetNextBlocks(m_env,m_emerge, dtime, queue);
                }
-               m_clients.Unlock();
+               m_clients.unlock();
        }
 
        // Sort.
@@ -2150,7 +2185,7 @@ void Server::SendBlocks(float dtime)
        // Lowest is most important.
        std::sort(queue.begin(), queue.end());
 
-       m_clients.Lock();
+       m_clients.lock();
        for(u32 i=0; i<queue.size(); i++)
        {
                //TODO: Calculate limit dynamically
@@ -2180,7 +2215,7 @@ void Server::SendBlocks(float dtime)
                client->SentBlock(q.pos);
                total_sending++;
        }
-       m_clients.Unlock();
+       m_clients.unlock();
 }
 
 void Server::fillMediaCache()
@@ -2192,7 +2227,7 @@ void Server::fillMediaCache()
        // Collect all media file paths
        std::vector<std::string> paths;
        for(std::vector<ModSpec>::iterator i = m_mods.begin();
-                       i != m_mods.end(); i++) {
+                       i != m_mods.end(); ++i) {
                const ModSpec &mod = *i;
                paths.push_back(mod.path + DIR_DELIM + "textures");
                paths.push_back(mod.path + DIR_DELIM + "sounds");
@@ -2203,7 +2238,7 @@ void Server::fillMediaCache()
 
        // Collect media file information from paths into cache
        for(std::vector<std::string>::iterator i = paths.begin();
-                       i != paths.end(); i++) {
+                       i != paths.end(); ++i) {
                std::string mediapath = *i;
                std::vector<fs::DirListNode> dirlist = fs::GetDirListing(mediapath);
                for (u32 j = 0; j < dirlist.size(); j++) {
@@ -2279,44 +2314,22 @@ void Server::fillMediaCache()
        }
 }
 
-struct SendableMediaAnnouncement
-{
-       std::string name;
-       std::string sha1_digest;
-
-       SendableMediaAnnouncement(const std::string &name_="",
-                                 const std::string &sha1_digest_=""):
-               name(name_),
-               sha1_digest(sha1_digest_)
-       {}
-};
-
 void Server::sendMediaAnnouncement(u16 peer_id)
 {
        DSTACK(__FUNCTION_NAME);
 
-       verbosestream<<"Server: Announcing files to id("<<peer_id<<")"
-                       <<std::endl;
-
-       std::vector<SendableMediaAnnouncement> file_announcements;
-
-       for (std::map<std::string, MediaInfo>::iterator i = m_media.begin();
-                       i != m_media.end(); i++){
-               // Put in list
-               file_announcements.push_back(
-                               SendableMediaAnnouncement(i->first, i->second.sha1_digest));
-       }
+       verbosestream << "Server: Announcing files to id(" << peer_id << ")"
+               << std::endl;
 
        // Make packet
        std::ostringstream os(std::ios_base::binary);
 
        NetworkPacket pkt(TOCLIENT_ANNOUNCE_MEDIA, 0, peer_id);
-       pkt << (u16) file_announcements.size();
+       pkt << (u16) m_media.size();
 
-       for (std::vector<SendableMediaAnnouncement>::iterator
-                       j = file_announcements.begin();
-                       j != file_announcements.end(); ++j) {
-               pkt << j->name << j->sha1_digest;
+       for (std::map<std::string, MediaInfo>::iterator i = m_media.begin();
+                       i != m_media.end(); ++i) {
+               pkt << i->first << i->second.sha1_digest;
        }
 
        pkt << g_settings->get("remote_media");
@@ -2476,7 +2489,7 @@ void Server::sendDetachedInventories(u16 peer_id)
 
        for(std::map<std::string, Inventory*>::iterator
                        i = m_detached_inventories.begin();
-                       i != m_detached_inventories.end(); i++) {
+                       i != m_detached_inventories.end(); ++i) {
                const std::string &name = i->first;
                //Inventory *inv = i->second;
                sendDetachedInventory(name, peer_id);
@@ -2526,13 +2539,40 @@ void Server::RespawnPlayer(u16 peer_id)
 
        bool repositioned = m_script->on_respawnplayer(playersao);
        if(!repositioned){
-               v3f pos = findSpawnPos(m_env->getServerMap());
+               v3f pos = findSpawnPos();
                // setPos will send the new position to client
                playersao->setPos(pos);
        }
 }
 
-void Server::DenyAccess(u16 peer_id, AccessDeniedCode reason, const std::wstring &custom_reason)
+
+void Server::DenySudoAccess(u16 peer_id)
+{
+       DSTACK(__FUNCTION_NAME);
+
+       NetworkPacket pkt(TOCLIENT_DENY_SUDO_MODE, 0, peer_id);
+       Send(&pkt);
+}
+
+
+void Server::DenyAccessVerCompliant(u16 peer_id, u16 proto_ver, AccessDeniedCode reason,
+               const std::string &str_reason, bool reconnect)
+{
+       if (proto_ver >= 25) {
+               SendAccessDenied(peer_id, reason, str_reason);
+       } else {
+               std::wstring wreason = utf8_to_wide(
+                       reason == SERVER_ACCESSDENIED_CUSTOM_STRING ? str_reason :
+                       accessDeniedStrings[(u8)reason]);
+               SendAccessDenied_Legacy(peer_id, wreason);
+       }
+
+       m_clients.event(peer_id, CSE_SetDenied);
+       m_con.DisconnectPeer(peer_id);
+}
+
+
+void Server::DenyAccess(u16 peer_id, AccessDeniedCode reason, const std::string &custom_reason)
 {
        DSTACK(__FUNCTION_NAME);
 
@@ -2552,6 +2592,37 @@ void Server::DenyAccess_Legacy(u16 peer_id, const std::wstring &reason)
        m_con.DisconnectPeer(peer_id);
 }
 
+void Server::acceptAuth(u16 peer_id, bool forSudoMode)
+{
+       DSTACK(__FUNCTION_NAME);
+
+       if (!forSudoMode) {
+               RemoteClient* client = getClient(peer_id, CS_Invalid);
+
+               NetworkPacket resp_pkt(TOCLIENT_AUTH_ACCEPT, 1 + 6 + 8 + 4, peer_id);
+
+               // Right now, the auth mechs don't change between login and sudo mode.
+               u32 sudo_auth_mechs = client->allowed_auth_mechs;
+               client->allowed_sudo_mechs = sudo_auth_mechs;
+
+               resp_pkt << v3f(0,0,0) << (u64) m_env->getServerMap().getSeed()
+                               << g_settings->getFloat("dedicated_server_step")
+                               << sudo_auth_mechs;
+
+               Send(&resp_pkt);
+               m_clients.event(peer_id, CSE_AuthAccept);
+       } else {
+               NetworkPacket resp_pkt(TOCLIENT_ACCEPT_SUDO_MODE, 1 + 6 + 8 + 4, peer_id);
+
+               // We only support SRP right now
+               u32 sudo_auth_mechs = AUTH_MECHANISM_FIRST_SRP;
+
+               resp_pkt << sudo_auth_mechs;
+               Send(&resp_pkt);
+               m_clients.event(peer_id, CSE_SudoSuccess);
+       }
+}
+
 void Server::DeleteClient(u16 peer_id, ClientDeletionReason reason)
 {
        DSTACK(__FUNCTION_NAME);
@@ -2569,7 +2640,7 @@ void Server::DeleteClient(u16 peer_id, ClientDeletionReason reason)
                        if(psound.clients.empty())
                                m_playing_sounds.erase(i++);
                        else
-                               i++;
+                               ++i;
                }
 
                Player *player = m_env->getPlayer(peer_id);
@@ -2625,7 +2696,7 @@ void Server::DeleteClient(u16 peer_id, ClientDeletionReason reason)
                        }
                }
                {
-                       JMutexAutoLock env_lock(m_env_mutex);
+                       MutexAutoLock env_lock(m_env_mutex);
                        m_clients.DeleteClient(peer_id);
                }
        }
@@ -2643,7 +2714,8 @@ void Server::UpdateCrafting(Player* player)
        ItemStack preview;
        InventoryLocation loc;
        loc.setPlayer(player->getName());
-       getCraftingResult(&player->inventory, preview, false, this);
+       std::vector<ItemStack> output_replacements;
+       getCraftingResult(&player->inventory, preview, output_replacements, false, this);
        m_env->getScriptIface()->item_CraftPredict(preview, player->getPlayerSAO(), (&player->inventory)->getList("craft"), loc);
 
        // Put the new preview in
@@ -2687,7 +2759,7 @@ std::wstring Server::getStatusString()
        std::wostringstream os(std::ios_base::binary);
        os<<L"# Server: ";
        // Version
-       os<<L"version="<<narrow_to_wide(minetest_version_simple);
+       os<<L"version="<<narrow_to_wide(g_version_string);
        // Uptime
        os<<L", uptime="<<m_uptime.get();
        // Max lag estimate
@@ -2780,8 +2852,12 @@ std::string Server::getBanDescription(const std::string &ip_or_name)
 
 void Server::notifyPlayer(const char *name, const std::wstring &msg)
 {
+       // m_env will be NULL if the server is initializing
+       if (!m_env)
+               return;
+
        Player *player = m_env->getPlayer(name);
-       if(!player)
+       if (!player)
                return;
 
        if (player->peer_id == PEER_ID_INEXISTENT)
@@ -2790,21 +2866,23 @@ void Server::notifyPlayer(const char *name, const std::wstring &msg)
        SendChatMessage(player->peer_id, msg);
 }
 
-bool Server::showFormspec(const char *playername, const std::string &formspec, const std::string &formname)
+bool Server::showFormspec(const char *playername, const std::string &formspec,
+       const std::string &formname)
 {
-       Player *player = m_env->getPlayer(playername);
+       // m_env will be NULL if the server is initializing
+       if (!m_env)
+               return false;
 
-       if(!player)
-       {
-               infostream<<"showFormspec: couldn't find player:"<<playername<<std::endl;
+       Player *player = m_env->getPlayer(playername);
+       if (!player)
                return false;
-       }
 
        SendShowFormspecMessage(player->peer_id, formspec, formname);
        return true;
 }
 
-u32 Server::hudAdd(Player *player, HudElement *form) {
+u32 Server::hudAdd(Player *player, HudElement *form)
+{
        if (!player)
                return -1;
 
@@ -2830,7 +2908,8 @@ bool Server::hudRemove(Player *player, u32 id) {
        return true;
 }
 
-bool Server::hudChange(Player *player, u32 id, HudElementStat stat, void *data) {
+bool Server::hudChange(Player *player, u32 id, HudElementStat stat, void *data)
+{
        if (!player)
                return false;
 
@@ -2838,7 +2917,8 @@ bool Server::hudChange(Player *player, u32 id, HudElementStat stat, void *data)
        return true;
 }
 
-bool Server::hudSetFlags(Player *player, u32 flags, u32 mask) {
+bool Server::hudSetFlags(Player *player, u32 flags, u32 mask)
+{
        if (!player)
                return false;
 
@@ -2854,37 +2934,67 @@ bool Server::hudSetFlags(Player *player, u32 flags, u32 mask) {
        return true;
 }
 
-bool Server::hudSetHotbarItemcount(Player *player, s32 hotbar_itemcount) {
+bool Server::hudSetHotbarItemcount(Player *player, s32 hotbar_itemcount)
+{
        if (!player)
                return false;
        if (hotbar_itemcount <= 0 || hotbar_itemcount > HUD_HOTBAR_ITEMCOUNT_MAX)
                return false;
 
+       player->setHotbarItemcount(hotbar_itemcount);
        std::ostringstream os(std::ios::binary);
        writeS32(os, hotbar_itemcount);
        SendHUDSetParam(player->peer_id, HUD_PARAM_HOTBAR_ITEMCOUNT, os.str());
        return true;
 }
 
-void Server::hudSetHotbarImage(Player *player, std::string name) {
+s32 Server::hudGetHotbarItemcount(Player *player)
+{
+       if (!player)
+               return 0;
+       return player->getHotbarItemcount();
+}
+
+void Server::hudSetHotbarImage(Player *player, std::string name)
+{
        if (!player)
                return;
 
+       player->setHotbarImage(name);
        SendHUDSetParam(player->peer_id, HUD_PARAM_HOTBAR_IMAGE, name);
 }
 
-void Server::hudSetHotbarSelectedImage(Player *player, std::string name) {
+std::string Server::hudGetHotbarImage(Player *player)
+{
+       if (!player)
+               return "";
+       return player->getHotbarImage();
+}
+
+void Server::hudSetHotbarSelectedImage(Player *player, std::string name)
+{
        if (!player)
                return;
 
+       player->setHotbarSelectedImage(name);
        SendHUDSetParam(player->peer_id, HUD_PARAM_HOTBAR_SELECTED_IMAGE, name);
 }
 
-bool Server::setLocalPlayerAnimations(Player *player, v2s32 animation_frames[4], f32 frame_speed)
+std::string Server::hudGetHotbarSelectedImage(Player *player)
+{
+       if (!player)
+               return "";
+
+       return player->getHotbarSelectedImage();
+}
+
+bool Server::setLocalPlayerAnimations(Player *player,
+       v2s32 animation_frames[4], f32 frame_speed)
 {
        if (!player)
                return false;
 
+       player->setLocalAnimations(animation_frames, frame_speed);
        SendLocalPlayerAnimations(player->peer_id, animation_frames, frame_speed);
        return true;
 }
@@ -2894,26 +3004,30 @@ bool Server::setPlayerEyeOffset(Player *player, v3f first, v3f third)
        if (!player)
                return false;
 
+       player->eye_offset_first = first;
+       player->eye_offset_third = third;
        SendEyeOffset(player->peer_id, first, third);
        return true;
 }
 
 bool Server::setSky(Player *player, const video::SColor &bgcolor,
-               const std::string &type, const std::vector<std::string> &params)
+       const std::string &type, const std::vector<std::string> &params)
 {
        if (!player)
                return false;
 
+       player->setSky(bgcolor, type, params);
        SendSetSky(player->peer_id, bgcolor, type, params);
        return true;
 }
 
 bool Server::overrideDayNightRatio(Player *player, bool do_override,
-               float ratio)
+       float ratio)
 {
        if (!player)
                return false;
 
+       player->overrideDayNightRatio(do_override, ratio);
        SendOverrideDayNightRatio(player->peer_id, do_override, ratio);
        return true;
 }
@@ -2923,68 +3037,45 @@ void Server::notifyPlayers(const std::wstring &msg)
        SendChatMessage(PEER_ID_INEXISTENT,msg);
 }
 
-void Server::spawnParticle(const char *playername, v3f pos,
-               v3f velocity, v3f acceleration,
-               float expirationtime, float size, bool
-               collisiondetection, bool vertical, std::string texture)
+void Server::spawnParticle(const std::string &playername, v3f pos,
+       v3f velocity, v3f acceleration,
+       float expirationtime, float size, bool
+       collisiondetection, bool vertical, const std::string &texture)
 {
-       Player *player = m_env->getPlayer(playername);
-       if(!player)
+       // m_env will be NULL if the server is initializing
+       if (!m_env)
                return;
-       SendSpawnParticle(player->peer_id, pos, velocity, acceleration,
-                       expirationtime, size, collisiondetection, vertical, texture);
-}
 
-void Server::spawnParticleAll(v3f pos, v3f velocity, v3f acceleration,
-               float expirationtime, float size,
-               bool collisiondetection, bool vertical, std::string texture)
-{
-       SendSpawnParticle(PEER_ID_INEXISTENT,pos, velocity, acceleration,
+       u16 peer_id = PEER_ID_INEXISTENT;
+       if (playername != "") {
+               Player* player = m_env->getPlayer(playername.c_str());
+               if (!player)
+                       return;
+               peer_id = player->peer_id;
+       }
+
+       SendSpawnParticle(peer_id, pos, velocity, acceleration,
                        expirationtime, size, collisiondetection, vertical, texture);
 }
 
-u32 Server::addParticleSpawner(const char *playername,
-               u16 amount, float spawntime,
-               v3f minpos, v3f maxpos,
-               v3f minvel, v3f maxvel,
-               v3f minacc, v3f maxacc,
-               float minexptime, float maxexptime,
-               float minsize, float maxsize,
-               bool collisiondetection, bool vertical, std::string texture)
+u32 Server::addParticleSpawner(u16 amount, float spawntime,
+       v3f minpos, v3f maxpos, v3f minvel, v3f maxvel, v3f minacc, v3f maxacc,
+       float minexptime, float maxexptime, float minsize, float maxsize,
+       bool collisiondetection, bool vertical, const std::string &texture,
+       const std::string &playername)
 {
-       Player *player = m_env->getPlayer(playername);
-       if(!player)
+       // m_env will be NULL if the server is initializing
+       if (!m_env)
                return -1;
 
-       u32 id = 0;
-       for(;;) // look for unused particlespawner id
-       {
-               id++;
-               if (std::find(m_particlespawner_ids.begin(),
-                               m_particlespawner_ids.end(), id)
-                               == m_particlespawner_ids.end())
-               {
-                       m_particlespawner_ids.push_back(id);
-                       break;
-               }
+       u16 peer_id = PEER_ID_INEXISTENT;
+       if (playername != "") {
+               Player* player = m_env->getPlayer(playername.c_str());
+               if (!player)
+                       return -1;
+               peer_id = player->peer_id;
        }
 
-       SendAddParticleSpawner(player->peer_id, amount, spawntime,
-               minpos, maxpos, minvel, maxvel, minacc, maxacc,
-               minexptime, maxexptime, minsize, maxsize,
-               collisiondetection, vertical, texture, id);
-
-       return id;
-}
-
-u32 Server::addParticleSpawnerAll(u16 amount, float spawntime,
-               v3f minpos, v3f maxpos,
-               v3f minvel, v3f maxvel,
-               v3f minacc, v3f maxacc,
-               float minexptime, float maxexptime,
-               float minsize, float maxsize,
-               bool collisiondetection, bool vertical, std::string texture)
-{
        u32 id = 0;
        for(;;) // look for unused particlespawner id
        {
@@ -2998,7 +3089,7 @@ u32 Server::addParticleSpawnerAll(u16 amount, float spawntime,
                }
        }
 
-       SendAddParticleSpawner(PEER_ID_INEXISTENT, amount, spawntime,
+       SendAddParticleSpawner(peer_id, amount, spawntime,
                minpos, maxpos, minvel, maxvel, minacc, maxacc,
                minexptime, maxexptime, minsize, maxsize,
                collisiondetection, vertical, texture, id);
@@ -3006,26 +3097,25 @@ u32 Server::addParticleSpawnerAll(u16 amount, float spawntime,
        return id;
 }
 
-void Server::deleteParticleSpawner(const char *playername, u32 id)
+void Server::deleteParticleSpawner(const std::string &playername, u32 id)
 {
-       Player *player = m_env->getPlayer(playername);
-       if(!player)
-               return;
+       // m_env will be NULL if the server is initializing
+       if (!m_env)
+               throw ServerError("Can't delete particle spawners during initialisation!");
 
-       m_particlespawner_ids.erase(
-                       std::remove(m_particlespawner_ids.begin(),
-                       m_particlespawner_ids.end(), id),
-                       m_particlespawner_ids.end());
-       SendDeleteParticleSpawner(player->peer_id, id);
-}
+       u16 peer_id = PEER_ID_INEXISTENT;
+       if (playername != "") {
+               Player* player = m_env->getPlayer(playername.c_str());
+               if (!player)
+                       return;
+               peer_id = player->peer_id;
+       }
 
-void Server::deleteParticleSpawnerAll(u32 id)
-{
        m_particlespawner_ids.erase(
                        std::remove(m_particlespawner_ids.begin(),
                        m_particlespawner_ids.end(), id),
                        m_particlespawner_ids.end());
-       SendDeleteParticleSpawner(PEER_ID_INEXISTENT, id);
+       SendDeleteParticleSpawner(peer_id, id);
 }
 
 Inventory* Server::createDetachedInventory(const std::string &name)
@@ -3044,24 +3134,6 @@ Inventory* Server::createDetachedInventory(const std::string &name)
        return inv;
 }
 
-class BoolScopeSet
-{
-public:
-       BoolScopeSet(bool *dst, bool val):
-               m_dst(dst)
-       {
-               m_orig_state = *m_dst;
-               *m_dst = val;
-       }
-       ~BoolScopeSet()
-       {
-               *m_dst = m_orig_state;
-       }
-private:
-       bool *m_dst;
-       bool m_orig_state;
-};
-
 // actions: time-reversed list
 // Return value: success/failure
 bool Server::rollbackRevertActions(const std::list<RollbackAction> &actions,
@@ -3081,7 +3153,7 @@ bool Server::rollbackRevertActions(const std::list<RollbackAction> &actions,
 
        for(std::list<RollbackAction>::const_iterator
                        i = actions.begin();
-                       i != actions.end(); i++)
+                       i != actions.end(); ++i)
        {
                const RollbackAction &action = *i;
                num_tried++;
@@ -3111,27 +3183,29 @@ bool Server::rollbackRevertActions(const std::list<RollbackAction> &actions,
 
 // IGameDef interface
 // Under envlock
-IItemDefManagerServer::getItemDefManager()
+IItemDefManager *Server::getItemDefManager()
 {
        return m_itemdef;
 }
-INodeDefManager* Server::getNodeDefManager()
+
+INodeDefManager *Server::getNodeDefManager()
 {
        return m_nodedef;
 }
-ICraftDefManager* Server::getCraftDefManager()
+
+ICraftDefManager *Server::getCraftDefManager()
 {
        return m_craftdef;
 }
-ITextureSourceServer::getTextureSource()
+ITextureSource *Server::getTextureSource()
 {
        return NULL;
 }
-IShaderSourceServer::getShaderSource()
+IShaderSource *Server::getShaderSource()
 {
        return NULL;
 }
-scene::ISceneManagerServer::getSceneManager()
+scene::ISceneManager *Server::getSceneManager()
 {
        return NULL;
 }
@@ -3140,66 +3214,73 @@ u16 Server::allocateUnknownNodeId(const std::string &name)
 {
        return m_nodedef->allocateDummy(name);
 }
-ISoundManager* Server::getSoundManager()
+
+ISoundManager *Server::getSoundManager()
 {
        return &dummySoundManager;
 }
-MtEventManager* Server::getEventManager()
+
+MtEventManager *Server::getEventManager()
 {
        return m_event;
 }
 
-IWritableItemDefManagerServer::getWritableItemDefManager()
+IWritableItemDefManager *Server::getWritableItemDefManager()
 {
        return m_itemdef;
 }
-IWritableNodeDefManager* Server::getWritableNodeDefManager()
+
+IWritableNodeDefManager *Server::getWritableNodeDefManager()
 {
        return m_nodedef;
 }
-IWritableCraftDefManager* Server::getWritableCraftDefManager()
+
+IWritableCraftDefManager *Server::getWritableCraftDefManager()
 {
        return m_craftdef;
 }
 
-const ModSpec* Server::getModSpec(const std::string &modname)
+const ModSpec *Server::getModSpec(const std::string &modname) const
 {
-       for(std::vector<ModSpec>::iterator i = m_mods.begin();
-                       i != m_mods.end(); i++){
-               const ModSpec &mod = *i;
-               if(mod.name == modname)
+       std::vector<ModSpec>::const_iterator it;
+       for (it = m_mods.begin(); it != m_mods.end(); ++it) {
+               const ModSpec &mod = *it;
+               if (mod.name == modname)
                        return &mod;
        }
        return NULL;
 }
+
 void Server::getModNames(std::vector<std::string> &modlist)
 {
-       for(std::vector<ModSpec>::iterator i = m_mods.begin(); i != m_mods.end(); i++) {
-               modlist.push_back(i->name);
-       }
+       std::vector<ModSpec>::iterator it;
+       for (it = m_mods.begin(); it != m_mods.end(); ++it)
+               modlist.push_back(it->name);
 }
+
 std::string Server::getBuiltinLuaPath()
 {
        return porting::path_share + DIR_DELIM + "builtin";
 }
 
-v3f findSpawnPos(ServerMap &map)
+v3f Server::findSpawnPos()
 {
-       //return v3f(50,50,50)*BS;
-
-       v3s16 nodepos;
+       ServerMap &map = m_env->getServerMap();
+       v3f nodeposf;
+       if (g_settings->getV3FNoEx("static_spawnpoint", nodeposf)) {
+               return nodeposf * BS;
+       }
 
-#if 0
-       nodepos = v2s16(0,0);
-       groundheight = 20;
-#endif
+       // Default position is static_spawnpoint
+       // We will return it if we don't found a good place
+       v3s16 nodepos(nodeposf.X, nodeposf.Y, nodeposf.Z);
 
-#if 1
        s16 water_level = map.getWaterLevel();
 
+       bool is_good = false;
+
        // Try to find a good place a few times
-       for(s32 i=0; i<1000; i++)
-       {
+       for(s32 i = 0; i < 1000 && !is_good; i++) {
                s32 range = 1 + i;
                // We're going to try to throw the player to this position
                v2s16 nodepos2d = v2s16(
@@ -3214,7 +3295,7 @@ v3f findSpawnPos(ServerMap &map)
                        continue;
 
                nodepos = v3s16(nodepos2d.X, groundheight, nodepos2d.Y);
-               bool is_good = false;
+
                s32 air_count = 0;
                for (s32 i = 0; i < 10; i++) {
                        v3s16 blockpos = getNodeBlockPos(nodepos);
@@ -3229,18 +3310,12 @@ v3f findSpawnPos(ServerMap &map)
                        }
                        nodepos.Y++;
                }
-               if(is_good){
-                       // Found a good place
-                       //infostream<<"Searched through "<<i<<" places."<<std::endl;
-                       break;
-               }
        }
-#endif
 
        return intToFloat(nodepos, BS);
 }
 
-PlayerSAO* Server::emergePlayer(const char *name, u16 peer_id)
+PlayerSAO* Server::emergePlayer(const char *name, u16 peer_id, u16 proto_version)
 {
        bool newplayer = false;
 
@@ -3278,7 +3353,7 @@ PlayerSAO* Server::emergePlayer(const char *name, u16 peer_id)
                // Set player position
                infostream<<"Server: Finding spawn place for player \""
                                <<name<<"\""<<std::endl;
-               v3f pos = findSpawnPos(m_env->getServerMap());
+               v3f pos = findSpawnPos();
                player->setPosition(pos);
 
                // Make sure the player is saved
@@ -3293,6 +3368,8 @@ PlayerSAO* Server::emergePlayer(const char *name, u16 peer_id)
                        getPlayerEffectivePrivs(player->getName()),
                        isSingleplayer());
 
+       player->protocol_version = proto_version;
+
        /* Clean up old HUD elements from previous sessions */
        player->clearHud();
 
@@ -3352,5 +3429,3 @@ void dedicated_server_loop(Server &server, bool &kill)
                }
        }
 }
-
-