Fix MSVC build broken by 34d32ce
[oweals/minetest.git] / src / server.cpp
index 9d70ad7b76477c9ac813fc4347e30aab9c18e7b7..a9e5c3d08820f0e441ab2b6e1c09066feca34b52 100644 (file)
@@ -26,7 +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 "threading/mutex_auto_lock.h"
 #include "constants.h"
 #include "voxel.h"
 #include "config.h"
@@ -38,7 +38,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
 #include "settings.h"
 #include "profiler.h"
 #include "log.h"
-#include "scripting_game.h"
+#include "serverscripting.h"
 #include "nodedef.h"
 #include "itemdef.h"
 #include "craftdef.h"
@@ -50,11 +50,9 @@ with this program; if not, write to the Free Software Foundation, Inc.,
 #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"
@@ -71,65 +69,49 @@ public:
        {}
 };
 
-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);
+       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(
+                                       "ServerThread::run Lua: " + std::string(e.what()));
                }
        }
 
-       END_DEBUG_EXCEPTION_HANDLER(errorstream)
+       END_DEBUG_EXCEPTION_HANDLER
 
        return NULL;
 }
@@ -165,11 +147,14 @@ Server::Server(
                const std::string &path_world,
                const SubgameSpec &gamespec,
                bool simple_singleplayer_mode,
-               bool ipv6
+               bool ipv6,
+               bool dedicated,
+               ChatInterface *iface
        ):
        m_path_world(path_world),
        m_gamespec(gamespec),
        m_simple_singleplayer_mode(simple_singleplayer_mode),
+       m_dedicated(dedicated),
        m_async_fatal_error(""),
        m_env(NULL),
        m_con(PROTOCOL_ID,
@@ -191,16 +176,17 @@ Server::Server(
        m_uptime(0),
        m_clients(&m_con),
        m_shutdown_requested(false),
+       m_shutdown_ask_reconnect(false),
+       m_shutdown_timer(0.0f),
+       m_admin_chat(iface),
        m_ignore_map_edit_events(false),
        m_ignore_map_edit_events_peer_id(0),
-       m_next_sound_id(0)
-
+       m_next_sound_id(0),
+       m_mod_storage_save_timer(10.0f)
 {
        m_liquid_transform_timer = 0.0;
        m_liquid_transform_every = 1.0;
-       m_print_info_timer = 0.0;
        m_masterserver_timer = 0.0;
-       m_objectdata_timer = 0.0;
        m_emergethread_trigger_timer = 0.0;
        m_savemap_timer = 0.0;
 
@@ -235,20 +221,12 @@ Server::Server(
        std::string ban_path = m_path_world + DIR_DELIM "ipban.txt";
        m_banmanager = new BanManager(ban_path);
 
-       ModConfiguration modconf(m_path_world);
+       ServerModConfiguration 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;
-               }
+       if (!modconf.isConsistent()) {
+               modconf.printUnsatisfiedModsError();
        }
 
        Settings worldmt_settings;
@@ -277,11 +255,8 @@ Server::Server(
                errorstream << std::endl;
        }
 
-       // Lock environment
-       JMutexAutoLock envlock(m_env_mutex);
-
-       // Load mapgen params from Settings
-       m_emerge->loadMapgenParams();
+       //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);
@@ -289,44 +264,30 @@ Server::Server(
        // Initialize scripting
        infostream<<"Server: Initializing Lua"<<std::endl;
 
-       m_script = new GameScripting(this);
+       m_script = new ServerScripting(this);
 
-       std::string script_path = getBuiltinLuaPath() + DIR_DELIM "init.lua";
-       std::string error_msg;
-
-       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);
+       m_script->loadMod(getBuiltinLuaPath() + DIR_DELIM "init.lua", 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 << " ";
+       for (std::vector<ModSpec>::const_iterator i = m_mods.begin();
+                       i != m_mods.end(); ++i) {
+               infostream << (*i).name << " ";
        }
        infostream << std::endl;
        // Load and run "mod" scripts
-       for (std::vector<ModSpec>::iterator i = m_mods.begin();
-                       i != m_mods.end(); i++) {
-               const ModSpec &mod = *i;
+       for (std::vector<ModSpec>::const_iterator it = m_mods.begin();
+                       it != m_mods.end(); ++it) {
+               const ModSpec &mod = *it;
                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());
+                       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";
+               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);
-               }
+               m_script->loadMod(script_path, mod.name);
        }
 
        // Read Textures and calculate sha1 sums
@@ -345,6 +306,9 @@ Server::Server(
        // 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);
 
@@ -353,8 +317,11 @@ Server::Server(
 
        m_clients.setEnv(m_env);
 
+       if (!servermap->settings_mgr.makeMapgenParams())
+               FATAL_ERROR("Couldn't create any mapgen type");
+
        // Initialize mapgens
-       m_emerge->initMapgens();
+       m_emerge->initMapgens(servermap->getMapgenParams());
 
        m_enable_rollback_recording = g_settings->getBool("enable_rollback_recording");
        if (m_enable_rollback_recording) {
@@ -369,16 +336,18 @@ Server::Server(
        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;
+       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()
@@ -389,15 +358,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();
        }
 
@@ -410,11 +392,8 @@ Server::~Server()
        m_emerge->stopThreads();
 
        // Delete things in the reverse order of creation
-       delete m_env;
-
-       // N.B. the EmergeManager should be deleted after the Environment since Map
-       // depends on EmergeManager to write its current params to the map meta
        delete m_emerge;
+       delete m_env;
        delete m_rollback;
        delete m_banmanager;
        delete m_event;
@@ -429,14 +408,14 @@ 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;
        }
 }
 
 void Server::start(Address bind_addr)
 {
-       DSTACK(__FUNCTION_NAME);
+       DSTACK(FUNCTION_NAME);
 
        m_bind_addr = bind_addr;
 
@@ -444,14 +423,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
@@ -469,14 +448,14 @@ void Server::start(Address bind_addr)
 
 void Server::stop()
 {
-       DSTACK(__FUNCTION_NAME);
+       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_thread->stop();
        //m_emergethread.setRun(false);
-       m_thread->Wait();
+       m_thread->wait();
        //m_emergethread.stop();
 
        infostream<<"Server: Threads stopped"<<std::endl;
@@ -484,38 +463,35 @@ void Server::stop()
 
 void Server::step(float dtime)
 {
-       DSTACK(__FUNCTION_NAME);
+       DSTACK(FUNCTION_NAME);
        // Limit a bit
-       if(dtime > 2.0)
+       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
        std::string async_err = m_async_fatal_error.get();
-       if(async_err != "") {
-               if (m_simple_singleplayer_mode) {
-                       throw ServerError(async_err);
-               }
-               else {
-                       errorstream << "UNRECOVERABLE error occurred. Stopping server. "
-                                       << "Please fix the following error:" << std::endl
-                                       << async_err << std::endl;
-                       FATAL_ERROR(async_err.c_str());
+       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("AsyncErr: " + async_err);
        }
 }
 
 void Server::AsyncRunStep(bool initial_step)
 {
-       DSTACK(__FUNCTION_NAME);
+       DSTACK(FUNCTION_NAME);
 
        g_profiler->add("Server::AsyncRunStep (num)", 1);
 
        float dtime;
        {
-               JMutexAutoLock lock1(m_step_dtime_mutex);
+               MutexAutoLock lock1(m_step_dtime_mutex);
                dtime = m_step_dtime;
        }
 
@@ -533,7 +509,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;
        }
 
@@ -564,7 +540,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)
@@ -584,11 +560,28 @@ 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_MAX);
+       }
+
+       /*
+               Listen to the admin chat, if available
+       */
+       if (m_admin_chat) {
+               if (!m_admin_chat->command_queue.empty()) {
+                       MutexAutoLock lock(m_env_mutex);
+                       while (!m_admin_chat->command_queue.empty()) {
+                               ChatEvent *evt = m_admin_chat->command_queue.pop_frontNoEx();
+                               handleChatInterfaceEvent(evt);
+                               delete evt;
+                       }
+               }
+               m_admin_chat->outgoing_queue.push_back(
+                       new ChatEventTimeInfo(m_env->getGameTime(), m_env->getTimeOfDay()));
        }
 
        /*
@@ -601,7 +594,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");
 
@@ -639,18 +632,19 @@ void Server::AsyncRunStep(bool initial_step)
        // send masterserver announce
        {
                float &counter = m_masterserver_timer;
-               if(!isSingleplayer() && (!counter || counter >= 300.0) &&
-                               g_settings->getBool("server_announce"))
-               {
-                       ServerList::sendAnnounce(counter ? "update" : "start",
+               if (!isSingleplayer() && (!counter || counter >= 300.0) &&
+                               g_settings->getBool("server_announce")) {
+                       ServerList::sendAnnounce(counter ? ServerList::AA_UPDATE :
+                                               ServerList::AA_START,
                                        m_bind_addr.getPort(),
                                        m_clients.getPlayerNames(),
                                        m_uptime.get(),
                                        m_env->getGameTime(),
                                        m_lag,
                                        m_gamespec.id,
-                                       m_emerge->params.mg_name,
-                                       m_mods);
+                                       Mapgen::getMapgenName(m_emerge->mgparams->mgtype),
+                                       m_mods,
+                                       m_dedicated);
                        counter = 0.01;
                }
                counter += dtime;
@@ -662,27 +656,27 @@ 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();
-               std::map<u16, RemoteClient*> clients = m_clients.getClientList();
+               m_clients.lock();
+               UNORDERED_MAP<u16, RemoteClient*> clients = m_clients.getClientList();
                ScopeProfiler sp(g_profiler, "Server: checking added and deleted objs");
 
                // Radius inside which objects are active
-               s16 radius = g_settings->getS16("active_object_send_range_blocks");
-               s16 player_radius = g_settings->getS16("player_transfer_distance");
-
-               if (player_radius == 0 && g_settings->exists("unlimited_player_transfer_distance") &&
-                               !g_settings->getBool("unlimited_player_transfer_distance"))
+               static const s16 radius =
+                       g_settings->getS16("active_object_send_range_blocks") * MAP_BLOCKSIZE;
+
+               // Radius inside which players are active
+               static const bool is_transfer_limited =
+                       g_settings->exists("unlimited_player_transfer_distance") &&
+                       !g_settings->getBool("unlimited_player_transfer_distance");
+               static const s16 player_transfer_dist = g_settings->getS16("player_transfer_distance") * MAP_BLOCKSIZE;
+               s16 player_radius = player_transfer_dist;
+               if (player_radius == 0 && is_transfer_limited)
                        player_radius = radius;
 
-               radius *= MAP_BLOCKSIZE;
-               player_radius *= MAP_BLOCKSIZE;
-
-               for(std::map<u16, RemoteClient*>::iterator
-                       i = clients.begin();
-                       i != clients.end(); ++i)
-               {
+               for (UNORDERED_MAP<u16, RemoteClient*>::iterator i = clients.begin();
+                       i != clients.end(); ++i) {
                        RemoteClient *client = i->second;
 
                        // If definitions and textures have not been sent, don't
@@ -690,28 +684,32 @@ void Server::AsyncRunStep(bool initial_step)
                        if (client->getState() < CS_DefinitionsSent)
                                continue;
 
-                       Player *player = m_env->getPlayer(client->peer_id);
-                       if(player==NULL)
-                       {
+                       RemotePlayer *player = m_env->getPlayer(client->peer_id);
+                       if (player == NULL) {
                                // This can happen if the client timeouts somehow
-                               /*infostream<<"WARNING: "<<__FUNCTION_NAME<<": Client "
+                               /*warningstream<<FUNCTION_NAME<<": Client "
                                                <<client->peer_id
                                                <<" has no associated player"<<std::endl;*/
                                continue;
                        }
-                       v3s16 pos = floatToInt(player->getPosition(), BS);
 
-                       std::set<u16> removed_objects;
-                       std::set<u16> added_objects;
-                       m_env->getRemovedActiveObjects(pos, radius, player_radius,
+                       PlayerSAO *playersao = player->getPlayerSAO();
+                       if (playersao == NULL)
+                               continue;
+
+                       s16 my_radius = MYMIN(radius, playersao->getWantedRange() * MAP_BLOCKSIZE);
+                       if (my_radius <= 0) my_radius = radius;
+                       //infostream << "Server: Active Radius " << my_radius << std::endl;
+
+                       std::queue<u16> removed_objects;
+                       std::queue<u16> added_objects;
+                       m_env->getRemovedActiveObjects(playersao, my_radius, player_radius,
                                        client->m_known_objects, removed_objects);
-                       m_env->getAddedActiveObjects(pos, radius, player_radius,
+                       m_env->getAddedActiveObjects(playersao, my_radius, player_radius,
                                        client->m_known_objects, added_objects);
 
                        // Ignore if nothing happened
-                       if(removed_objects.empty() && added_objects.empty())
-                       {
-                               //infostream<<"active objects: none changed"<<std::endl;
+                       if (removed_objects.empty() && added_objects.empty()) {
                                continue;
                        }
 
@@ -722,12 +720,9 @@ void Server::AsyncRunStep(bool initial_step)
                        // Handle removed objects
                        writeU16((u8*)buf, removed_objects.size());
                        data_buffer.append(buf, 2);
-                       for(std::set<u16>::iterator
-                                       i = removed_objects.begin();
-                                       i != removed_objects.end(); ++i)
-                       {
+                       while (!removed_objects.empty()) {
                                // Get object
-                               u16 id = *i;
+                               u16 id = removed_objects.front();
                                ServerActiveObject* obj = m_env->getActiveObject(id);
 
                                // Add to data buffer for sending
@@ -739,23 +734,21 @@ void Server::AsyncRunStep(bool initial_step)
 
                                if(obj && obj->m_known_by_count > 0)
                                        obj->m_known_by_count--;
+                               removed_objects.pop();
                        }
 
                        // Handle added objects
                        writeU16((u8*)buf, added_objects.size());
                        data_buffer.append(buf, 2);
-                       for(std::set<u16>::iterator
-                                       i = added_objects.begin();
-                                       i != added_objects.end(); ++i)
-                       {
+                       while (!added_objects.empty()) {
                                // Get object
-                               u16 id = *i;
+                               u16 id = added_objects.front();
                                ServerActiveObject* obj = m_env->getActiveObject(id);
 
                                // Get object type
                                u8 type = ACTIVEOBJECT_TYPE_INVALID;
                                if(obj == NULL)
-                                       infostream<<"WARNING: "<<__FUNCTION_NAME
+                                       warningstream<<FUNCTION_NAME
                                                        <<": NULL object"<<std::endl;
                                else
                                        type = obj->getSendType();
@@ -777,6 +770,8 @@ void Server::AsyncRunStep(bool initial_step)
 
                                if(obj)
                                        obj->m_known_by_count++;
+
+                               added_objects.pop();
                        }
 
                        u32 pktSize = SendActiveObjectRemoveAdd(client->peer_id, data_buffer);
@@ -785,19 +780,31 @@ void Server::AsyncRunStep(bool initial_step)
                                        << added_objects.size() << " added, "
                                        << "packet size is " << pktSize << std::endl;
                }
-               m_clients.Unlock();
+               m_clients.unlock();
+
+               m_mod_storage_save_timer -= dtime;
+               if (m_mod_storage_save_timer <= 0.0f) {
+                       infostream << "Saving registered mod storages." << std::endl;
+                       m_mod_storage_save_timer = g_settings->getFloat("server_map_save_interval");
+                       for (UNORDERED_MAP<std::string, ModMetadata *>::const_iterator
+                               it = m_mod_storages.begin(); it != m_mod_storages.end(); ++it) {
+                               if (it->second->isModified()) {
+                                       it->second->save(getModStoragePath());
+                               }
+                       }
+               }
        }
 
        /*
                Send object messages
        */
        {
-               JMutexAutoLock envlock(m_env_mutex);
+               MutexAutoLock envlock(m_env_mutex);
                ScopeProfiler sp(g_profiler, "Server: sending object messages");
 
                // Key = object id
                // Value = data sent by object
-               std::map<u16, std::vector<ActiveObjectMessage>* > buffered_messages;
+               UNORDERED_MAP<u16, std::vector<ActiveObjectMessage>* > buffered_messages;
 
                // Get active object messages from environment
                for(;;) {
@@ -806,7 +813,7 @@ void Server::AsyncRunStep(bool initial_step)
                                break;
 
                        std::vector<ActiveObjectMessage>* message_list = NULL;
-                       std::map<u16, std::vector<ActiveObjectMessage>* >::iterator n;
+                       UNORDERED_MAP<u16, std::vector<ActiveObjectMessage>* >::iterator n;
                        n = buffered_messages.find(aom.id);
                        if (n == buffered_messages.end()) {
                                message_list = new std::vector<ActiveObjectMessage>;
@@ -818,17 +825,16 @@ void Server::AsyncRunStep(bool initial_step)
                        message_list->push_back(aom);
                }
 
-               m_clients.Lock();
-               std::map<u16, RemoteClient*> clients = m_clients.getClientList();
+               m_clients.lock();
+               UNORDERED_MAP<u16, RemoteClient*> clients = m_clients.getClientList();
                // Route data to every client
-               for (std::map<u16, RemoteClient*>::iterator
-                       i = clients.begin();
+               for (UNORDERED_MAP<u16, RemoteClient*>::iterator i = clients.begin();
                        i != clients.end(); ++i) {
                        RemoteClient *client = i->second;
                        std::string reliable_data;
                        std::string unreliable_data;
                        // Go through all objects in message buffer
-                       for (std::map<u16, std::vector<ActiveObjectMessage>* >::iterator
+                       for (UNORDERED_MAP<u16, std::vector<ActiveObjectMessage>* >::iterator
                                        j = buffered_messages.begin();
                                        j != buffered_messages.end(); ++j) {
                                // If object is not known by client, skip it
@@ -869,10 +875,10 @@ 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
+               for (UNORDERED_MAP<u16, std::vector<ActiveObjectMessage>* >::iterator
                                i = buffered_messages.begin();
                                i != buffered_messages.end(); ++i) {
                        delete i->second;
@@ -884,7 +890,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;
@@ -938,7 +944,7 @@ void Server::AsyncRunStep(bool initial_step)
                                break;
                        default:
                                prof.add("unknown", 1);
-                               infostream << "WARNING: Server: Unknown MapEditEvent "
+                               warningstream << "Server: Unknown MapEditEvent "
                                                << ((u32)event->type) << std::endl;
                                break;
                        }
@@ -990,8 +996,7 @@ void Server::AsyncRunStep(bool initial_step)
        {
                float &counter = m_emergethread_trigger_timer;
                counter += dtime;
-               if(counter >= 2.0)
-               {
+               if (counter >= 2.0) {
                        counter = 0.0;
 
                        m_emerge->startThreads();
@@ -1002,10 +1007,11 @@ void Server::AsyncRunStep(bool initial_step)
        {
                float &counter = m_savemap_timer;
                counter += dtime;
-               if(counter >= g_settings->getFloat("server_map_save_interval"))
-               {
+               static const float save_interval =
+                       g_settings->getFloat("server_map_save_interval");
+               if (counter >= save_interval) {
                        counter = 0.0;
-                       JMutexAutoLock lock(m_env_mutex);
+                       MutexAutoLock lock(m_env_mutex);
 
                        ScopeProfiler sp(g_profiler, "Server: saving stuff");
 
@@ -1024,11 +1030,44 @@ void Server::AsyncRunStep(bool initial_step)
                        m_env->saveMeta();
                }
        }
+
+       // Timed shutdown
+       static const float shutdown_msg_times[] =
+       {
+               1, 2, 3, 4, 5, 10, 15, 20, 25, 30, 45, 60, 120, 180, 300, 600, 1200, 1800, 3600
+       };
+
+       if (m_shutdown_timer > 0.0f) {
+               // Automated messages
+               if (m_shutdown_timer < shutdown_msg_times[ARRLEN(shutdown_msg_times) - 1]) {
+                       for (u16 i = 0; i < ARRLEN(shutdown_msg_times) - 1; i++) {
+                               // If shutdown timer matches an automessage, shot it
+                               if (m_shutdown_timer > shutdown_msg_times[i] &&
+                                       m_shutdown_timer - dtime < shutdown_msg_times[i]) {
+                                       std::wstringstream ws;
+
+                                       ws << L"*** Server shutting down in "
+                                               << duration_to_string(myround(m_shutdown_timer - dtime)).c_str()
+                                               << ".";
+
+                                       infostream << wide_to_utf8(ws.str()).c_str() << std::endl;
+                                       SendChatMessage(PEER_ID_INEXISTENT, ws.str());
+                                       break;
+                               }
+                       }
+               }
+
+               m_shutdown_timer -= dtime;
+               if (m_shutdown_timer < 0.0f) {
+                       m_shutdown_timer = 0.0f;
+                       m_shutdown_requested = true;
+               }
+       }
 }
 
 void Server::Receive()
 {
-       DSTACK(__FUNCTION_NAME);
+       DSTACK(FUNCTION_NAME);
        SharedBuffer<u8> data;
        u16 peer_id;
        try {
@@ -1061,21 +1100,20 @@ 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()));
+       RemotePlayer *player = m_env->getPlayer(playername.c_str());
 
        // If failed, cancel
        if ((playersao == NULL) || (player == NULL)) {
@@ -1107,34 +1145,19 @@ PlayerSAO* Server::StageTwoClientInit(u16 peer_id)
        // Send inventory
        SendInventory(playersao);
 
-       // Send HP
-       SendPlayerHPOrDie(playersao);
+       // Send HP or death screen
+       if (playersao->isDead())
+               SendDeathscreen(peer_id, false, v3f(0,0,0));
+       else
+               SendPlayerHPOrDie(playersao);
 
        // Send Breath
-       SendPlayerBreath(peer_id);
-
-       // Show death screen if necessary
-       if(player->isDead())
-               SendDeathscreen(peer_id, false, v3f(0,0,0));
+       SendPlayerBreath(playersao);
 
        // Note things in chat if not in simple singleplayer mode
-       if(!m_simple_singleplayer_mode) {
+       if (!m_simple_singleplayer_mode && g_settings->getBool("show_statusline_on_connect")) {
                // Send information about server to player in chat
                SendChatMessage(peer_id, getStatusString());
-
-               // Send information about joining in chat
-               {
-                       std::wstring name = L"unknown";
-                       Player *player = m_env->getPlayer(peer_id);
-                       if(player != NULL)
-                               name = narrow_to_wide(player->getName());
-
-                       std::wstring message;
-                       message += L"*** ";
-                       message += name;
-                       message += L" joined the game.";
-                       SendChatMessage(PEER_ID_INEXISTENT,message);
-               }
        }
        Address addr = getPeerAddress(player->peer_id);
        std::string ip_str = addr.serializeString();
@@ -1143,12 +1166,12 @@ PlayerSAO* Server::StageTwoClientInit(u16 peer_id)
                Print out action
        */
        {
-               std::vector<std::string> names = m_clients.getPlayerNames();
+               const std::vector<std::string> &names = m_clients.getPlayerNames();
 
-               actionstream<<player->getName() <<" joins game. List of players: ";
+               actionstream << player->getName() << " joins game. List of players: ";
 
-               for (std::vector<std::string>::iterator i = names.begin();
-                               i != names.end(); i++) {
+               for (std::vector<std::string>::const_iterator i = names.begin();
+                               i != names.end(); ++i) {
                        actionstream << *i << " ";
                }
 
@@ -1165,9 +1188,9 @@ inline void Server::handleCommand(NetworkPacket* pkt)
 
 void Server::ProcessData(NetworkPacket *pkt)
 {
-       DSTACK(__FUNCTION_NAME);
+       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();
@@ -1274,7 +1297,7 @@ Inventory* Server::getInventory(const InventoryLocation &loc)
                break;
        case InventoryLocation::PLAYER:
        {
-               Player *player = m_env->getPlayer(loc.name.c_str());
+               RemotePlayer *player = dynamic_cast<RemotePlayer *>(m_env->getPlayer(loc.name.c_str()));
                if(!player)
                        return NULL;
                PlayerSAO *playersao = player->getPlayerSAO();
@@ -1314,9 +1337,12 @@ void Server::setInventoryModified(const InventoryLocation &loc, bool playerSend)
                if (!playerSend)
                        return;
 
-               Player *player = m_env->getPlayer(loc.name.c_str());
-               if(!player)
+               RemotePlayer *player =
+                       dynamic_cast<RemotePlayer *>(m_env->getPlayer(loc.name.c_str()));
+
+               if (!player)
                        return;
+
                PlayerSAO *playersao = player->getPlayerSAO();
                if(!playersao)
                        return;
@@ -1349,19 +1375,19 @@ 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)
 {
-       DSTACK(__FUNCTION_NAME);
+       DSTACK(FUNCTION_NAME);
        verbosestream<<"Server::peerAdded(): peer->id="
                        <<peer->id<<std::endl;
 
@@ -1374,7 +1400,7 @@ void Server::peerAdded(con::Peer *peer)
 
 void Server::deletingPeer(con::Peer *peer, bool timeout)
 {
-       DSTACK(__FUNCTION_NAME);
+       DSTACK(FUNCTION_NAME);
        verbosestream<<"Server::deletingPeer(): peer->id="
                        <<peer->id<<", timeout="<<timeout<<std::endl;
 
@@ -1406,11 +1432,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;
        }
 
@@ -1423,7 +1449,7 @@ bool Server::getClientInfo(
        *patch = client->getPatch();
        *vers_string = client->getPatch();
 
-       m_clients.Unlock();
+       m_clients.unlock();
 
        return true;
 }
@@ -1456,6 +1482,16 @@ void Server::handlePeerChanges()
        }
 }
 
+void Server::printToConsoleOnly(const std::string &text)
+{
+       if (m_admin_chat) {
+               m_admin_chat->outgoing_queue.push_back(
+                       new ChatEventChat("", utf8_to_wide(text)));
+       } else {
+               std::cout << text << std::endl;
+       }
+}
+
 void Server::Send(NetworkPacket* pkt)
 {
        m_clients.send(pkt->getPeerId(),
@@ -1466,7 +1502,7 @@ void Server::Send(NetworkPacket* pkt)
 
 void Server::SendMovement(u16 peer_id)
 {
-       DSTACK(__FUNCTION_NAME);
+       DSTACK(FUNCTION_NAME);
        std::ostringstream os(std::ios_base::binary);
 
        NetworkPacket pkt(TOCLIENT_MOVEMENT, 12 * sizeof(float), peer_id);
@@ -1503,7 +1539,7 @@ void Server::SendPlayerHPOrDie(PlayerSAO *playersao)
 
 void Server::SendHP(u16 peer_id, u8 hp)
 {
-       DSTACK(__FUNCTION_NAME);
+       DSTACK(FUNCTION_NAME);
 
        NetworkPacket pkt(TOCLIENT_HP, 1, peer_id);
        pkt << hp;
@@ -1512,29 +1548,31 @@ void Server::SendHP(u16 peer_id, u8 hp)
 
 void Server::SendBreath(u16 peer_id, u16 breath)
 {
-       DSTACK(__FUNCTION_NAME);
+       DSTACK(FUNCTION_NAME);
 
        NetworkPacket pkt(TOCLIENT_BREATH, 2, peer_id);
        pkt << (u16) breath;
        Send(&pkt);
 }
 
-void Server::SendAccessDenied(u16 peer_id, AccessDeniedCode reason, const std::string &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);
 }
 
 void Server::SendAccessDenied_Legacy(u16 peer_id,const std::wstring &reason)
 {
-       DSTACK(__FUNCTION_NAME);
+       DSTACK(FUNCTION_NAME);
 
        NetworkPacket pkt(TOCLIENT_ACCESS_DENIED_LEGACY, 0, peer_id);
        pkt << reason;
@@ -1544,7 +1582,7 @@ void Server::SendAccessDenied_Legacy(u16 peer_id,const std::wstring &reason)
 void Server::SendDeathscreen(u16 peer_id,bool set_camera_point_target,
                v3f camera_point_target)
 {
-       DSTACK(__FUNCTION_NAME);
+       DSTACK(FUNCTION_NAME);
 
        NetworkPacket pkt(TOCLIENT_DEATHSCREEN, 1 + sizeof(v3f), peer_id);
        pkt << set_camera_point_target << camera_point_target;
@@ -1554,7 +1592,7 @@ void Server::SendDeathscreen(u16 peer_id,bool set_camera_point_target,
 void Server::SendItemDef(u16 peer_id,
                IItemDefManager *itemdef, u16 protocol_version)
 {
-       DSTACK(__FUNCTION_NAME);
+       DSTACK(FUNCTION_NAME);
 
        NetworkPacket pkt(TOCLIENT_ITEMDEF, 0, peer_id);
 
@@ -1579,7 +1617,7 @@ void Server::SendItemDef(u16 peer_id,
 void Server::SendNodeDef(u16 peer_id,
                INodeDefManager *nodedef, u16 protocol_version)
 {
-       DSTACK(__FUNCTION_NAME);
+       DSTACK(FUNCTION_NAME);
 
        NetworkPacket pkt(TOCLIENT_NODEDEF, 0, peer_id);
 
@@ -1608,7 +1646,7 @@ void Server::SendNodeDef(u16 peer_id,
 
 void Server::SendInventory(PlayerSAO* playerSAO)
 {
-       DSTACK(__FUNCTION_NAME);
+       DSTACK(FUNCTION_NAME);
 
        UpdateCrafting(playerSAO->getPlayer());
 
@@ -1629,7 +1667,7 @@ void Server::SendInventory(PlayerSAO* playerSAO)
 
 void Server::SendChatMessage(u16 peer_id, const std::wstring &message)
 {
-       DSTACK(__FUNCTION_NAME);
+       DSTACK(FUNCTION_NAME);
 
        NetworkPacket pkt(TOCLIENT_CHAT_MESSAGE, 0, peer_id);
        pkt << message;
@@ -1638,29 +1676,50 @@ void Server::SendChatMessage(u16 peer_id, const std::wstring &message)
                Send(&pkt);
        }
        else {
-               m_clients.sendToAll(0, &pkt, true);
+               m_clients.sendToAll(&pkt);
        }
 }
 
 void Server::SendShowFormspecMessage(u16 peer_id, const std::string &formspec,
                                      const std::string &formname)
 {
-       DSTACK(__FUNCTION_NAME);
+       DSTACK(FUNCTION_NAME);
 
        NetworkPacket pkt(TOCLIENT_SHOW_FORMSPEC, 0 , peer_id);
-
-       pkt.putLongString(FORMSPEC_VERSION_STRING + formspec);
+       if (formspec == "" ){
+               //the client should close the formspec
+               pkt.putLongString("");
+       } else {
+               pkt.putLongString(FORMSPEC_VERSION_STRING + formspec);
+       }
        pkt << formname;
 
        Send(&pkt);
 }
 
 // Spawns a particle on peer with peer_id
-void Server::SendSpawnParticle(u16 peer_id, v3f pos, v3f velocity, v3f acceleration,
+void Server::SendSpawnParticle(u16 peer_id, u16 protocol_version,
+                               v3f pos, v3f velocity, v3f acceleration,
                                float expirationtime, float size, bool collisiondetection,
-                               bool vertical, std::string texture)
+                               bool collision_removal,
+                               bool vertical, const std::string &texture,
+                               const struct TileAnimationParams &animation, u8 glow)
 {
-       DSTACK(__FUNCTION_NAME);
+       DSTACK(FUNCTION_NAME);
+       if (peer_id == PEER_ID_INEXISTENT) {
+               // This sucks and should be replaced by a better solution in a refactor:
+               std::vector<u16> clients = m_clients.getClientIDs();
+               for (std::vector<u16>::iterator i = clients.begin(); i != clients.end(); ++i) {
+                       RemotePlayer *player = m_env->getPlayer(*i);
+                       if (!player)
+                               continue;
+                       SendSpawnParticle(*i, player->protocol_version,
+                                       pos, velocity, acceleration,
+                                       expirationtime, size, collisiondetection,
+                                       collision_removal, vertical, texture, animation, glow);
+               }
+               return;
+       }
 
        NetworkPacket pkt(TOCLIENT_SPAWN_PARTICLE, 0, peer_id);
 
@@ -1668,21 +1727,40 @@ void Server::SendSpawnParticle(u16 peer_id, v3f pos, v3f velocity, v3f accelerat
                        << size << collisiondetection;
        pkt.putLongString(texture);
        pkt << vertical;
+       pkt << collision_removal;
+       // This is horrible but required (why are there two ways to serialize pkts?)
+       std::ostringstream os(std::ios_base::binary);
+       animation.serialize(os, protocol_version);
+       pkt.putRawString(os.str());
+       pkt << glow;
 
-       if (peer_id != PEER_ID_INEXISTENT) {
-               Send(&pkt);
-       }
-       else {
-               m_clients.sendToAll(0, &pkt, true);
-       }
+       Send(&pkt);
 }
 
 // Adds a ParticleSpawner on peer with peer_id
-void Server::SendAddParticleSpawner(u16 peer_id, u16 amount, float spawntime, v3f minpos, v3f maxpos,
+void Server::SendAddParticleSpawner(u16 peer_id, u16 protocol_version,
+       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)
+       float minsize, float maxsize, bool collisiondetection, bool collision_removal,
+       u16 attached_id, bool vertical, const std::string &texture, u32 id,
+       const struct TileAnimationParams &animation, u8 glow)
 {
-       DSTACK(__FUNCTION_NAME);
+       DSTACK(FUNCTION_NAME);
+       if (peer_id == PEER_ID_INEXISTENT) {
+               // This sucks and should be replaced:
+               std::vector<u16> clients = m_clients.getClientIDs();
+               for (std::vector<u16>::iterator i = clients.begin(); i != clients.end(); ++i) {
+                       RemotePlayer *player = m_env->getPlayer(*i);
+                       if (!player)
+                               continue;
+                       SendAddParticleSpawner(*i, player->protocol_version,
+                                       amount, spawntime, minpos, maxpos,
+                                       minvel, maxvel, minacc, maxacc, minexptime, maxexptime,
+                                       minsize, maxsize, collisiondetection, collision_removal,
+                                       attached_id, vertical, texture, id, animation, glow);
+               }
+               return;
+       }
 
        NetworkPacket pkt(TOCLIENT_ADD_PARTICLESPAWNER, 0, peer_id);
 
@@ -1693,18 +1771,20 @@ void Server::SendAddParticleSpawner(u16 peer_id, u16 amount, float spawntime, v3
        pkt.putLongString(texture);
 
        pkt << id << vertical;
+       pkt << collision_removal;
+       pkt << attached_id;
+       // This is horrible but required
+       std::ostringstream os(std::ios_base::binary);
+       animation.serialize(os, protocol_version);
+       pkt.putRawString(os.str());
+       pkt << glow;
 
-       if (peer_id != PEER_ID_INEXISTENT) {
-               Send(&pkt);
-       }
-       else {
-               m_clients.sendToAll(0, &pkt, true);
-       }
+       Send(&pkt);
 }
 
 void Server::SendDeleteParticleSpawner(u16 peer_id, u32 id)
 {
-       DSTACK(__FUNCTION_NAME);
+       DSTACK(FUNCTION_NAME);
 
        NetworkPacket pkt(TOCLIENT_DELETE_PARTICLESPAWNER_LEGACY, 2, peer_id);
 
@@ -1715,7 +1795,7 @@ void Server::SendDeleteParticleSpawner(u16 peer_id, u32 id)
                Send(&pkt);
        }
        else {
-               m_clients.sendToAll(0, &pkt, true);
+               m_clients.sendToAll(&pkt);
        }
 
 }
@@ -1814,13 +1894,13 @@ void Server::SendOverrideDayNightRatio(u16 peer_id, bool do_override,
 
 void Server::SendTimeOfDay(u16 peer_id, u16 time, f32 time_speed)
 {
-       DSTACK(__FUNCTION_NAME);
+       DSTACK(FUNCTION_NAME);
 
        NetworkPacket pkt(TOCLIENT_TIME_OF_DAY, 0, peer_id);
        pkt << time << time_speed;
 
        if (peer_id == PEER_ID_INEXISTENT) {
-               m_clients.sendToAll(0, &pkt, true);
+               m_clients.sendToAll(&pkt);
        }
        else {
                Send(&pkt);
@@ -1829,9 +1909,9 @@ void Server::SendTimeOfDay(u16 peer_id, u16 time, f32 time_speed)
 
 void Server::SendPlayerHP(u16 peer_id)
 {
-       DSTACK(__FUNCTION_NAME);
+       DSTACK(FUNCTION_NAME);
        PlayerSAO *playersao = getPlayerSAO(peer_id);
-       // In some rare case, if the player is disconnected
+       // In some rare case if the player is disconnected
        // while Lua call l_punch, for example, this can be NULL
        if (!playersao)
                return;
@@ -1845,33 +1925,32 @@ void Server::SendPlayerHP(u16 peer_id)
        playersao->m_messages_out.push(aom);
 }
 
-void Server::SendPlayerBreath(u16 peer_id)
+void Server::SendPlayerBreath(PlayerSAO *sao)
 {
-       DSTACK(__FUNCTION_NAME);
-       PlayerSAO *playersao = getPlayerSAO(peer_id);
-       assert(playersao);
+       DSTACK(FUNCTION_NAME);
+       assert(sao);
 
-       m_script->player_event(playersao, "breath_changed");
-       SendBreath(peer_id, playersao->getBreath());
+       m_script->player_event(sao, "breath_changed");
+       SendBreath(sao->getPeerID(), sao->getBreath());
 }
 
 void Server::SendMovePlayer(u16 peer_id)
 {
-       DSTACK(__FUNCTION_NAME);
-       Player *player = m_env->getPlayer(peer_id);
+       DSTACK(FUNCTION_NAME);
+       RemotePlayer *player = m_env->getPlayer(peer_id);
        assert(player);
+       PlayerSAO *sao = player->getPlayerSAO();
+       assert(sao);
 
        NetworkPacket pkt(TOCLIENT_MOVE_PLAYER, sizeof(v3f) + sizeof(f32) * 2, peer_id);
-       pkt << player->getPosition() << player->getPitch() << player->getYaw();
+       pkt << sao->getBasePosition() << sao->getPitch() << sao->getYaw();
 
        {
-               v3f pos = player->getPosition();
-               f32 pitch = player->getPitch();
-               f32 yaw = player->getYaw();
+               v3f pos = sao->getBasePosition();
                verbosestream << "Server: Sending TOCLIENT_MOVE_PLAYER"
                                << " pos=(" << pos.X << "," << pos.Y << "," << pos.Z << ")"
-                               << " pitch=" << pitch
-                               << " yaw=" << yaw
+                               << " pitch=" << sao->getPitch()
+                               << " yaw=" << sao->getYaw()
                                << std::endl;
        }
 
@@ -1897,7 +1976,7 @@ void Server::SendEyeOffset(u16 peer_id, v3f first, v3f third)
 }
 void Server::SendPlayerPrivileges(u16 peer_id)
 {
-       Player *player = m_env->getPlayer(peer_id);
+       RemotePlayer *player = m_env->getPlayer(peer_id);
        assert(player);
        if(player->peer_id == PEER_ID_INEXISTENT)
                return;
@@ -1909,7 +1988,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);
        }
 
@@ -1918,7 +1997,7 @@ void Server::SendPlayerPrivileges(u16 peer_id)
 
 void Server::SendPlayerInventoryFormspec(u16 peer_id)
 {
-       Player *player = m_env->getPlayer(peer_id);
+       RemotePlayer *player = m_env->getPlayer(peer_id);
        assert(player);
        if(player->peer_id == PEER_ID_INEXISTENT)
                return;
@@ -1963,7 +2042,7 @@ s32 Server::playSound(const SimpleSoundSpec &spec,
        std::vector<u16> dst_clients;
        if(params.to_player != "")
        {
-               Player *player = m_env->getPlayer(params.to_player.c_str());
+               RemotePlayer *player = m_env->getPlayer(params.to_player.c_str());
                if(!player){
                        infostream<<"Server::playSound: Player \""<<params.to_player
                                        <<"\" not found"<<std::endl;
@@ -1979,14 +2058,17 @@ s32 Server::playSound(const SimpleSoundSpec &spec,
        else {
                std::vector<u16> clients = m_clients.getClientIDs();
 
-               for(std::vector<u16>::iterator
-                               i = clients.begin(); i != clients.end(); ++i) {
-                       Player *player = m_env->getPlayer(*i);
-                       if(!player)
+               for (std::vector<u16>::iterator i = clients.begin(); i != clients.end(); ++i) {
+                       RemotePlayer *player = m_env->getPlayer(*i);
+                       if (!player)
+                               continue;
+
+                       PlayerSAO *sao = player->getPlayerSAO();
+                       if (!sao)
                                continue;
 
-                       if(pos_exists) {
-                               if(player->getPosition().getDistanceFrom(pos) >
+                       if (pos_exists) {
+                               if(sao->getBasePosition().getDistanceFrom(pos) >
                                                params.max_hear_distance)
                                        continue;
                        }
@@ -2009,7 +2091,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);
        }
@@ -2018,17 +2100,16 @@ s32 Server::playSound(const SimpleSoundSpec &spec,
 void Server::stopSound(s32 handle)
 {
        // Get sound reference
-       std::map<s32, ServerPlayingSound>::iterator i =
-                       m_playing_sounds.find(handle);
-       if(i == m_playing_sounds.end())
+       UNORDERED_MAP<s32, ServerPlayingSound>::iterator i = m_playing_sounds.find(handle);
+       if (i == m_playing_sounds.end())
                return;
        ServerPlayingSound &psound = i->second;
 
        NetworkPacket pkt(TOCLIENT_STOP_SOUND, 4);
        pkt << handle;
 
-       for(std::set<u16>::iterator i = psound.clients.begin();
-                       i != psound.clients.end(); i++) {
+       for (UNORDERED_SET<u16>::iterator i = psound.clients.begin();
+                       i != psound.clients.end(); ++i) {
                // Send as reliable
                m_clients.send(*i, 0, &pkt, true);
        }
@@ -2046,14 +2127,17 @@ void Server::sendRemoveNode(v3s16 p, u16 ignore_id,
        pkt << p;
 
        std::vector<u16> clients = m_clients.getClientIDs();
-       for(std::vector<u16>::iterator i = clients.begin();
-               i != clients.end(); ++i) {
+       for (std::vector<u16>::iterator i = clients.begin(); i != clients.end(); ++i) {
                if (far_players) {
                        // Get player
-                       if(Player *player = m_env->getPlayer(*i)) {
+                       if (RemotePlayer *player = m_env->getPlayer(*i)) {
+                               PlayerSAO *sao = player->getPlayerSAO();
+                               if (!sao)
+                                       continue;
+
                                // If player is far away, only set modified blocks not sent
-                               v3f player_pos = player->getPosition();
-                               if(player_pos.getDistanceFrom(p_f) > maxd) {
+                               v3f player_pos = sao->getBasePosition();
+                               if (player_pos.getDistanceFrom(p_f) > maxd) {
                                        far_players->push_back(*i);
                                        continue;
                                }
@@ -2073,14 +2157,16 @@ void Server::sendAddNode(v3s16 p, MapNode n, u16 ignore_id,
        v3f p_f = intToFloat(p, BS);
 
        std::vector<u16> clients = m_clients.getClientIDs();
-       for(std::vector<u16>::iterator i = clients.begin();
-                       i != clients.end(); ++i) {
-
-               if(far_players) {
+       for(std::vector<u16>::iterator i = clients.begin();     i != clients.end(); ++i) {
+               if (far_players) {
                        // Get player
-                       if(Player *player = m_env->getPlayer(*i)) {
+                       if (RemotePlayer *player = m_env->getPlayer(*i)) {
+                               PlayerSAO *sao = player->getPlayerSAO();
+                               if (!sao)
+                                       continue;
+
                                // If player is far away, only set modified blocks not sent
-                               v3f player_pos = player->getPosition();
+                               v3f player_pos = sao->getBasePosition();
                                if(player_pos.getDistanceFrom(p_f) > maxd) {
                                        far_players->push_back(*i);
                                        continue;
@@ -2089,21 +2175,13 @@ 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
                                        << (u8) (remove_metadata ? 0 : 1);
-
-                       if (!remove_metadata) {
-                               if (client->net_proto_version <= 21) {
-                                       // Old clients always clear metadata; fix it
-                                       // by sending the full block again.
-                                       client->SetBlockNotSent(p);
-                               }
-                       }
                }
-               m_clients.Unlock();
+               m_clients.unlock();
 
                // Send as reliable
                if (pkt.getSize() > 0)
@@ -2114,18 +2192,18 @@ 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)
 {
-       DSTACK(__FUNCTION_NAME);
+       DSTACK(FUNCTION_NAME);
 
        v3s16 p = block->getPos();
 
@@ -2135,7 +2213,7 @@ void Server::SendBlockNoLock(u16 peer_id, MapBlock *block, u8 ver, u16 net_proto
 
        std::ostringstream os(std::ios_base::binary);
        block->serialize(os, ver, false);
-       block->serializeNetworkSpecific(os, net_proto_version);
+       block->serializeNetworkSpecific(os);
        std::string s = os.str();
 
        NetworkPacket pkt(TOCLIENT_BLOCKDATA, 2 + 2 + 2 + 2 + s.size(), peer_id);
@@ -2147,9 +2225,9 @@ void Server::SendBlockNoLock(u16 peer_id, MapBlock *block, u8 ver, u16 net_proto
 
 void Server::SendBlocks(float dtime)
 {
-       DSTACK(__FUNCTION_NAME);
+       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");
@@ -2163,7 +2241,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);
@@ -2174,7 +2252,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.
@@ -2182,7 +2260,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
@@ -2212,19 +2290,19 @@ void Server::SendBlocks(float dtime)
                client->SentBlock(q.pos);
                total_sending++;
        }
-       m_clients.Unlock();
+       m_clients.unlock();
 }
 
 void Server::fillMediaCache()
 {
-       DSTACK(__FUNCTION_NAME);
+       DSTACK(FUNCTION_NAME);
 
        infostream<<"Server: Calculating media file checksums"<<std::endl;
 
        // 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");
@@ -2235,7 +2313,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++) {
@@ -2311,44 +2389,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;
+       DSTACK(FUNCTION_NAME);
 
-       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 (UNORDERED_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");
@@ -2372,7 +2428,7 @@ struct SendableMedia
 void Server::sendRequestedMedia(u16 peer_id,
                const std::vector<std::string> &tosend)
 {
-       DSTACK(__FUNCTION_NAME);
+       DSTACK(FUNCTION_NAME);
 
        verbosestream<<"Server::sendRequestedMedia(): "
                        <<"Sending files to client"<<std::endl;
@@ -2391,7 +2447,7 @@ void Server::sendRequestedMedia(u16 peer_id,
                        i != tosend.end(); ++i) {
                const std::string &name = *i;
 
-               if(m_media.find(name) == m_media.end()) {
+               if (m_media.find(name) == m_media.end()) {
                        errorstream<<"Server::sendRequestedMedia(): Client asked for "
                                        <<"unknown file \""<<(name)<<"\""<<std::endl;
                        continue;
@@ -2479,7 +2535,7 @@ void Server::sendRequestedMedia(u16 peer_id,
 void Server::sendDetachedInventory(const std::string &name, u16 peer_id)
 {
        if(m_detached_inventories.count(name) == 0) {
-               errorstream<<__FUNCTION_NAME<<": \""<<name<<"\" not found"<<std::endl;
+               errorstream<<FUNCTION_NAME<<": \""<<name<<"\" not found"<<std::endl;
                return;
        }
        Inventory *inv = m_detached_inventories[name];
@@ -2494,21 +2550,26 @@ void Server::sendDetachedInventory(const std::string &name, u16 peer_id)
        NetworkPacket pkt(TOCLIENT_DETACHED_INVENTORY, 0, peer_id);
        pkt.putRawString(s.c_str(), s.size());
 
-       if (peer_id != PEER_ID_INEXISTENT) {
-               Send(&pkt);
-       }
-       else {
-               m_clients.sendToAll(0, &pkt, true);
+       const std::string &check = m_detached_inventories_player[name];
+       if (peer_id == PEER_ID_INEXISTENT) {
+               if (check == "")
+                       return m_clients.sendToAll(&pkt);
+               RemotePlayer *p = m_env->getPlayer(check.c_str());
+               if (p)
+                       m_clients.send(p->peer_id, 0, &pkt, true);
+       } else {
+               if (check == "" || getPlayerName(peer_id) == check)
+                       Send(&pkt);
        }
 }
 
 void Server::sendDetachedInventories(u16 peer_id)
 {
-       DSTACK(__FUNCTION_NAME);
+       DSTACK(FUNCTION_NAME);
 
        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);
@@ -2521,10 +2582,12 @@ void Server::sendDetachedInventories(u16 peer_id)
 
 void Server::DiePlayer(u16 peer_id)
 {
-       DSTACK(__FUNCTION_NAME);
-
+       DSTACK(FUNCTION_NAME);
        PlayerSAO *playersao = getPlayerSAO(peer_id);
-       assert(playersao);
+       // In some rare cases this can be NULL -- if the player is disconnected
+       // when a Lua function modifies l_punch, for example
+       if (!playersao)
+               return;
 
        infostream << "Server::DiePlayer(): Player "
                        << playersao->getPlayer()->getName()
@@ -2541,7 +2604,7 @@ void Server::DiePlayer(u16 peer_id)
 
 void Server::RespawnPlayer(u16 peer_id)
 {
-       DSTACK(__FUNCTION_NAME);
+       DSTACK(FUNCTION_NAME);
 
        PlayerSAO *playersao = getPlayerSAO(peer_id);
        assert(playersao);
@@ -2553,27 +2616,46 @@ void Server::RespawnPlayer(u16 peer_id)
        playersao->setHP(PLAYER_MAX_HP);
        playersao->setBreath(PLAYER_MAX_BREATH);
 
-       SendPlayerHP(peer_id);
-       SendPlayerBreath(peer_id);
-
        bool repositioned = m_script->on_respawnplayer(playersao);
-       if(!repositioned){
+       if (!repositioned) {
                v3f pos = findSpawnPos();
                // setPos will send the new position to client
                playersao->setPos(pos);
        }
+
+       SendPlayerHP(peer_id);
 }
+
+
 void Server::DenySudoAccess(u16 peer_id)
 {
-       DSTACK(__FUNCTION_NAME);
+       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, reconnect);
+       } 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);
+       DSTACK(FUNCTION_NAME);
 
        SendAccessDenied(peer_id, reason, custom_reason);
        m_clients.event(peer_id, CSE_SetDenied);
@@ -2584,7 +2666,7 @@ void Server::DenyAccess(u16 peer_id, AccessDeniedCode reason, const std::string
 // the minimum version for MT users, maybe in 1 year
 void Server::DenyAccess_Legacy(u16 peer_id, const std::wstring &reason)
 {
-       DSTACK(__FUNCTION_NAME);
+       DSTACK(FUNCTION_NAME);
 
        SendAccessDenied_Legacy(peer_id, reason);
        m_clients.event(peer_id, CSE_SetDenied);
@@ -2593,7 +2675,7 @@ void Server::DenyAccess_Legacy(u16 peer_id, const std::wstring &reason)
 
 void Server::acceptAuth(u16 peer_id, bool forSudoMode)
 {
-       DSTACK(__FUNCTION_NAME);
+       DSTACK(FUNCTION_NAME);
 
        if (!forSudoMode) {
                RemoteClient* client = getClient(peer_id, CS_Invalid);
@@ -2624,50 +2706,32 @@ void Server::acceptAuth(u16 peer_id, bool forSudoMode)
 
 void Server::DeleteClient(u16 peer_id, ClientDeletionReason reason)
 {
-       DSTACK(__FUNCTION_NAME);
+       DSTACK(FUNCTION_NAME);
        std::wstring message;
        {
                /*
                        Clear references to playing sounds
                */
-               for(std::map<s32, ServerPlayingSound>::iterator
-                               i = m_playing_sounds.begin();
-                               i != m_playing_sounds.end();)
-               {
+               for (UNORDERED_MAP<s32, ServerPlayingSound>::iterator
+                                i = m_playing_sounds.begin(); i != m_playing_sounds.end();) {
                        ServerPlayingSound &psound = i->second;
                        psound.clients.erase(peer_id);
-                       if(psound.clients.empty())
+                       if (psound.clients.empty())
                                m_playing_sounds.erase(i++);
                        else
-                               i++;
+                               ++i;
                }
 
-               Player *player = m_env->getPlayer(peer_id);
-
-               // Collect information about leaving in chat
-               {
-                       if(player != NULL && reason != CDR_DENY)
-                       {
-                               std::wstring name = narrow_to_wide(player->getName());
-                               message += L"*** ";
-                               message += name;
-                               message += L" left the game.";
-                               if(reason == CDR_TIMEOUT)
-                                       message += L" (timed out)";
-                       }
-               }
+               RemotePlayer *player = m_env->getPlayer(peer_id);
 
                /* Run scripts and remove from environment */
-               {
-                       if(player != NULL)
-                       {
-                               PlayerSAO *playersao = player->getPlayerSAO();
-                               assert(playersao);
+               if (player != NULL) {
+                       PlayerSAO *playersao = player->getPlayerSAO();
+                       assert(playersao);
 
-                               m_script->on_leaveplayer(playersao);
+                       m_script->on_leaveplayer(playersao, reason == CDR_TIMEOUT);
 
-                               playersao->disconnected();
-                       }
+                       playersao->disconnected();
                }
 
                /*
@@ -2681,21 +2745,25 @@ void Server::DeleteClient(u16 peer_id, ClientDeletionReason reason)
                                for(std::vector<u16>::iterator i = clients.begin();
                                        i != clients.end(); ++i) {
                                        // Get player
-                                       Player *player = m_env->getPlayer(*i);
-                                       if(!player)
+                                       RemotePlayer *player = m_env->getPlayer(*i);
+                                       if (!player)
                                                continue;
 
                                        // Get name of player
                                        os << player->getName() << " ";
                                }
 
-                               actionstream << player->getName() << " "
+                               std::string name = player->getName();
+                               actionstream << name << " "
                                                << (reason == CDR_TIMEOUT ? "times out." : "leaves game.")
                                                << " List of players: " << os.str() << std::endl;
+                               if (m_admin_chat)
+                                       m_admin_chat->outgoing_queue.push_back(
+                                               new ChatEventNick(CET_NICK_REMOVE, name));
                        }
                }
                {
-                       JMutexAutoLock env_lock(m_env_mutex);
+                       MutexAutoLock env_lock(m_env_mutex);
                        m_clients.DeleteClient(peer_id);
                }
        }
@@ -2705,9 +2773,9 @@ void Server::DeleteClient(u16 peer_id, ClientDeletionReason reason)
                SendChatMessage(PEER_ID_INEXISTENT,message);
 }
 
-void Server::UpdateCrafting(Player* player)
+void Server::UpdateCrafting(RemotePlayer *player)
 {
-       DSTACK(__FUNCTION_NAME);
+       DSTACK(FUNCTION_NAME);
 
        // Get a preview for crafting
        ItemStack preview;
@@ -2715,7 +2783,8 @@ void Server::UpdateCrafting(Player* player)
        loc.setPlayer(player->getName());
        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);
+       m_env->getScriptIface()->item_CraftPredict(preview, player->getPlayerSAO(),
+                       (&player->inventory)->getList("craft"), loc);
 
        // Put the new preview in
        InventoryList *plist = player->inventory.getList("craftpreview");
@@ -2724,6 +2793,122 @@ void Server::UpdateCrafting(Player* player)
        plist->changeItem(0, preview);
 }
 
+void Server::handleChatInterfaceEvent(ChatEvent *evt)
+{
+       if (evt->type == CET_NICK_ADD) {
+               // The terminal informed us of its nick choice
+               m_admin_nick = ((ChatEventNick *)evt)->nick;
+               if (!m_script->getAuth(m_admin_nick, NULL, NULL)) {
+                       errorstream << "You haven't set up an account." << std::endl
+                               << "Please log in using the client as '"
+                               << m_admin_nick << "' with a secure password." << std::endl
+                               << "Until then, you can't execute admin tasks via the console," << std::endl
+                               << "and everybody can claim the user account instead of you," << std::endl
+                               << "giving them full control over this server." << std::endl;
+               }
+       } else {
+               assert(evt->type == CET_CHAT);
+               handleAdminChat((ChatEventChat *)evt);
+       }
+}
+
+std::wstring Server::handleChat(const std::string &name, const std::wstring &wname,
+       const std::wstring &wmessage, bool check_shout_priv, RemotePlayer *player)
+{
+       // If something goes wrong, this player is to blame
+       RollbackScopeActor rollback_scope(m_rollback,
+               std::string("player:") + name);
+
+       if (player) {
+               switch (player->canSendChatMessage()) {
+                       case RPLAYER_CHATRESULT_FLOODING: {
+                               std::wstringstream ws;
+                               ws << L"You cannot send more messages. You are limited to "
+                                  << g_settings->getFloat("chat_message_limit_per_10sec")
+                                  << L" messages per 10 seconds.";
+                               return ws.str();
+                       }
+                       case RPLAYER_CHATRESULT_KICK:
+                               DenyAccess_Legacy(player->peer_id,
+                                               L"You have been kicked due to message flooding.");
+                               return L"";
+                       case RPLAYER_CHATRESULT_OK:
+                               break;
+                       default:
+                               FATAL_ERROR("Unhandled chat filtering result found.");
+               }
+       }
+
+       if (m_max_chatmessage_length > 0
+                       && wmessage.length() > m_max_chatmessage_length) {
+               return L"Your message exceed the maximum chat message limit set on the server. "
+                               L"It was refused. Send a shorter message";
+       }
+
+       // Run script hook, exit if script ate the chat message
+       if (m_script->on_chat_message(name, wide_to_utf8(wmessage)))
+               return L"";
+
+       // Line to send
+       std::wstring line;
+       // Whether to send line to the player that sent the message, or to all players
+       bool broadcast_line = true;
+
+       if (check_shout_priv && !checkPriv(name, "shout")) {
+               line += L"-!- You don't have permission to shout.";
+               broadcast_line = false;
+       } else {
+               line += L"<";
+               line += wname;
+               line += L"> ";
+               line += wmessage;
+       }
+
+       /*
+               Tell calling method to send the message to sender
+       */
+       if (!broadcast_line) {
+               return line;
+       } else {
+               /*
+                       Send the message to others
+               */
+               actionstream << "CHAT: " << wide_to_narrow(line) << std::endl;
+
+               std::vector<u16> clients = m_clients.getClientIDs();
+
+               /*
+                       Send the message back to the inital sender
+                       if they are using protocol version >= 29
+               */
+
+               u16 peer_id_to_avoid_sending = (player ? player->peer_id : PEER_ID_INEXISTENT);
+               if (player && player->protocol_version >= 29)
+                       peer_id_to_avoid_sending = PEER_ID_INEXISTENT;
+
+               for (u16 i = 0; i < clients.size(); i++) {
+                       u16 cid = clients[i];
+                       if (cid != peer_id_to_avoid_sending)
+                               SendChatMessage(cid, line);
+               }
+       }
+       return L"";
+}
+
+void Server::handleAdminChat(const ChatEventChat *evt)
+{
+       std::string name = evt->nick;
+       std::wstring wname = utf8_to_wide(name);
+       std::wstring wmessage = evt->evt_msg;
+
+       std::wstring answer = handleChat(name, wname, wmessage);
+
+       // If asked to send answer to sender
+       if (!answer.empty()) {
+               m_admin_chat->outgoing_queue.push_back(new ChatEventChat("", answer));
+       }
+}
+
 RemoteClient* Server::getClient(u16 peer_id, ClientState state_min)
 {
        RemoteClient *client = getClientNoEx(peer_id,state_min);
@@ -2739,16 +2924,16 @@ RemoteClient* Server::getClientNoEx(u16 peer_id, ClientState state_min)
 
 std::string Server::getPlayerName(u16 peer_id)
 {
-       Player *player = m_env->getPlayer(peer_id);
-       if(player == NULL)
+       RemotePlayer *player = m_env->getPlayer(peer_id);
+       if (player == NULL)
                return "[id="+itos(peer_id)+"]";
        return player->getName();
 }
 
 PlayerSAO* Server::getPlayerSAO(u16 peer_id)
 {
-       Player *player = m_env->getPlayer(peer_id);
-       if(player == NULL)
+       RemotePlayer *player = m_env->getPlayer(peer_id);
+       if (player == NULL)
                return NULL;
        return player->getPlayerSAO();
 }
@@ -2767,13 +2952,12 @@ std::wstring Server::getStatusString()
        bool first = true;
        os<<L", clients={";
        std::vector<u16> clients = m_clients.getClientIDs();
-       for(std::vector<u16>::iterator i = clients.begin();
-               i != clients.end(); ++i) {
+       for (std::vector<u16>::iterator i = clients.begin(); i != clients.end(); ++i) {
                // Get player
-               Player *player = m_env->getPlayer(*i);
+               RemotePlayer *player = m_env->getPlayer(*i);
                // Get name of player
                std::wstring name = L"unknown";
-               if(player != NULL)
+               if (player != NULL)
                        name = narrow_to_wide(player->getName());
                // Add name to information string
                if(!first)
@@ -2809,12 +2993,12 @@ void Server::reportPrivsModified(const std::string &name)
                std::vector<u16> clients = m_clients.getClientIDs();
                for(std::vector<u16>::iterator i = clients.begin();
                                i != clients.end(); ++i) {
-                       Player *player = m_env->getPlayer(*i);
+                       RemotePlayer *player = m_env->getPlayer(*i);
                        reportPrivsModified(player->getName());
                }
        } else {
-               Player *player = m_env->getPlayer(name.c_str());
-               if(!player)
+               RemotePlayer *player = m_env->getPlayer(name.c_str());
+               if (!player)
                        return;
                SendPlayerPrivileges(player->peer_id);
                PlayerSAO *sao = player->getPlayerSAO();
@@ -2828,8 +3012,8 @@ void Server::reportPrivsModified(const std::string &name)
 
 void Server::reportInventoryFormspecModified(const std::string &name)
 {
-       Player *player = m_env->getPlayer(name.c_str());
-       if(!player)
+       RemotePlayer *player = m_env->getPlayer(name.c_str());
+       if (!player)
                return;
        SendPlayerInventoryFormspec(player->peer_id);
 }
@@ -2851,10 +3035,19 @@ std::string Server::getBanDescription(const std::string &ip_or_name)
 
 void Server::notifyPlayer(const char *name, const std::wstring &msg)
 {
-       Player *player = m_env->getPlayer(name);
-       if (!player)
+       // m_env will be NULL if the server is initializing
+       if (!m_env)
                return;
 
+       if (m_admin_nick == name && !m_admin_nick.empty()) {
+               m_admin_chat->outgoing_queue.push_back(new ChatEventChat("", msg));
+       }
+
+       RemotePlayer *player = m_env->getPlayer(name);
+       if (!player) {
+               return;
+       }
+
        if (player->peer_id == PEER_ID_INEXISTENT)
                return;
 
@@ -2864,7 +3057,11 @@ void Server::notifyPlayer(const char *name, const std::wstring &msg)
 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;
+
+       RemotePlayer *player = m_env->getPlayer(playername);
        if (!player)
                return false;
 
@@ -2872,7 +3069,7 @@ bool Server::showFormspec(const char *playername, const std::string &formspec,
        return true;
 }
 
-u32 Server::hudAdd(Player *player, HudElement *form)
+u32 Server::hudAdd(RemotePlayer *player, HudElement *form)
 {
        if (!player)
                return -1;
@@ -2884,7 +3081,7 @@ u32 Server::hudAdd(Player *player, HudElement *form)
        return id;
 }
 
-bool Server::hudRemove(Player *player, u32 id) {
+bool Server::hudRemove(RemotePlayer *player, u32 id) {
        if (!player)
                return false;
 
@@ -2899,7 +3096,7 @@ bool Server::hudRemove(Player *player, u32 id) {
        return true;
 }
 
-bool Server::hudChange(Player *player, u32 id, HudElementStat stat, void *data)
+bool Server::hudChange(RemotePlayer *player, u32 id, HudElementStat stat, void *data)
 {
        if (!player)
                return false;
@@ -2908,13 +3105,14 @@ 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(RemotePlayer *player, u32 flags, u32 mask)
 {
        if (!player)
                return false;
 
        SendHUDSetFlags(player->peer_id, flags, mask);
-       player->hud_flags = flags;
+       player->hud_flags &= ~mask;
+       player->hud_flags |= flags;
 
        PlayerSAO* playersao = player->getPlayerSAO();
 
@@ -2925,10 +3123,11 @@ bool Server::hudSetFlags(Player *player, u32 flags, u32 mask)
        return true;
 }
 
-bool Server::hudSetHotbarItemcount(Player *player, s32 hotbar_itemcount)
+bool Server::hudSetHotbarItemcount(RemotePlayer *player, s32 hotbar_itemcount)
 {
        if (!player)
                return false;
+
        if (hotbar_itemcount <= 0 || hotbar_itemcount > HUD_HOTBAR_ITEMCOUNT_MAX)
                return false;
 
@@ -2939,14 +3138,7 @@ bool Server::hudSetHotbarItemcount(Player *player, s32 hotbar_itemcount)
        return true;
 }
 
-s32 Server::hudGetHotbarItemcount(Player *player)
-{
-       if (!player)
-               return 0;
-       return player->getHotbarItemcount();
-}
-
-void Server::hudSetHotbarImage(Player *player, std::string name)
+void Server::hudSetHotbarImage(RemotePlayer *player, std::string name)
 {
        if (!player)
                return;
@@ -2955,14 +3147,14 @@ void Server::hudSetHotbarImage(Player *player, std::string name)
        SendHUDSetParam(player->peer_id, HUD_PARAM_HOTBAR_IMAGE, name);
 }
 
-std::string Server::hudGetHotbarImage(Player *player)
+std::string Server::hudGetHotbarImage(RemotePlayer *player)
 {
        if (!player)
                return "";
        return player->getHotbarImage();
 }
 
-void Server::hudSetHotbarSelectedImage(Player *player, std::string name)
+void Server::hudSetHotbarSelectedImage(RemotePlayer *player, std::string name)
 {
        if (!player)
                return;
@@ -2971,16 +3163,8 @@ void Server::hudSetHotbarSelectedImage(Player *player, std::string name)
        SendHUDSetParam(player->peer_id, HUD_PARAM_HOTBAR_SELECTED_IMAGE, name);
 }
 
-std::string Server::hudGetHotbarSelectedImage(Player *player)
-{
-       if (!player)
-               return "";
-
-       return player->getHotbarSelectedImage();
-}
-
-bool Server::setLocalPlayerAnimations(Player *player,
-       v2s32 animation_frames[4], f32 frame_speed)
+bool Server::setLocalPlayerAnimations(RemotePlayer *player,
+               v2s32 animation_frames[4], f32 frame_speed)
 {
        if (!player)
                return false;
@@ -2990,7 +3174,7 @@ bool Server::setLocalPlayerAnimations(Player *player,
        return true;
 }
 
-bool Server::setPlayerEyeOffset(Player *player, v3f first, v3f third)
+bool Server::setPlayerEyeOffset(RemotePlayer *player, v3f first, v3f third)
 {
        if (!player)
                return false;
@@ -3001,7 +3185,7 @@ bool Server::setPlayerEyeOffset(Player *player, v3f first, v3f third)
        return true;
 }
 
-bool Server::setSky(Player *player, const video::SColor &bgcolor,
+bool Server::setSky(RemotePlayer *player, const video::SColor &bgcolor,
        const std::string &type, const std::vector<std::string> &params)
 {
        if (!player)
@@ -3012,7 +3196,7 @@ bool Server::setSky(Player *player, const video::SColor &bgcolor,
        return true;
 }
 
-bool Server::overrideDayNightRatio(Player *player, bool do_override,
+bool Server::overrideDayNightRatio(RemotePlayer *player, bool do_override,
        float ratio)
 {
        if (!player)
@@ -3028,108 +3212,88 @@ void Server::notifyPlayers(const std::wstring &msg)
        SendChatMessage(PEER_ID_INEXISTENT,msg);
 }
 
-void Server::spawnParticle(const char *playername, v3f pos,
+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)
+       collisiondetection, bool collision_removal,
+       bool vertical, const std::string &texture,
+       const struct TileAnimationParams &animation, u8 glow)
 {
-       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, const std::string &texture)
-{
-       SendSpawnParticle(PEER_ID_INEXISTENT,pos, velocity, acceleration,
-                       expirationtime, size, collisiondetection, vertical, texture);
+       u16 peer_id = PEER_ID_INEXISTENT, proto_ver = 0;
+       if (playername != "") {
+               RemotePlayer *player = m_env->getPlayer(playername.c_str());
+               if (!player)
+                       return;
+               peer_id = player->peer_id;
+               proto_ver = player->protocol_version;
+       }
+
+       SendSpawnParticle(peer_id, proto_ver, pos, velocity, acceleration,
+                       expirationtime, size, collisiondetection,
+                       collision_removal, vertical, texture, animation, glow);
 }
 
-u32 Server::addParticleSpawner(const char *playername, u16 amount, float spawntime,
+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)
+       bool collisiondetection, bool collision_removal,
+       ServerActiveObject *attached, bool vertical, const std::string &texture,
+       const std::string &playername, const struct TileAnimationParams &animation,
+       u8 glow)
 {
-       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, proto_ver = 0;
+       if (playername != "") {
+               RemotePlayer *player = m_env->getPlayer(playername.c_str());
+               if (!player)
+                       return -1;
+               peer_id = player->peer_id;
+               proto_ver = player->protocol_version;
        }
 
-       SendAddParticleSpawner(player->peer_id, amount, spawntime,
-               minpos, maxpos, minvel, maxvel, minacc, maxacc,
-               minexptime, maxexptime, minsize, maxsize,
-               collisiondetection, vertical, texture, id);
+       u16 attached_id = attached ? attached->getId() : 0;
 
-       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, const std::string &texture)
-{
-       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;
-               }
-       }
+       u32 id;
+       if (attached_id == 0)
+               id = m_env->addParticleSpawner(spawntime);
+       else
+               id = m_env->addParticleSpawner(spawntime, attached_id);
 
-       SendAddParticleSpawner(PEER_ID_INEXISTENT, amount, spawntime,
+       SendAddParticleSpawner(peer_id, proto_ver, amount, spawntime,
                minpos, maxpos, minvel, maxvel, minacc, maxacc,
                minexptime, maxexptime, minsize, maxsize,
-               collisiondetection, vertical, texture, id);
+               collisiondetection, collision_removal, attached_id, vertical,
+               texture, id, animation, glow);
 
        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 != "") {
+               RemotePlayer *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);
+       m_env->deleteParticleSpawner(id);
+       SendDeleteParticleSpawner(peer_id, id);
 }
 
-Inventory* Server::createDetachedInventory(const std::string &name)
+Inventory* Server::createDetachedInventory(const std::string &name, const std::string &player)
 {
        if(m_detached_inventories.count(name) > 0){
                infostream<<"Server clearing detached inventory \""<<name<<"\""<<std::endl;
@@ -3140,6 +3304,7 @@ Inventory* Server::createDetachedInventory(const std::string &name)
        Inventory *inv = new Inventory(m_itemdef);
        sanity_check(inv);
        m_detached_inventories[name] = inv;
+       m_detached_inventories_player[name] = player;
        //TODO find a better way to do this
        sendDetachedInventory(name,PEER_ID_INEXISTENT);
        return inv;
@@ -3164,7 +3329,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++;
@@ -3208,29 +3373,12 @@ ICraftDefManager *Server::getCraftDefManager()
 {
        return m_craftdef;
 }
-ITextureSource *Server::getTextureSource()
-{
-       return NULL;
-}
-IShaderSource *Server::getShaderSource()
-{
-       return NULL;
-}
-scene::ISceneManager *Server::getSceneManager()
-{
-       return NULL;
-}
 
 u16 Server::allocateUnknownNodeId(const std::string &name)
 {
        return m_nodedef->allocateDummy(name);
 }
 
-ISoundManager *Server::getSoundManager()
-{
-       return &dummySoundManager;
-}
-
 MtEventManager *Server::getEventManager()
 {
        return m_event;
@@ -3274,6 +3422,11 @@ std::string Server::getBuiltinLuaPath()
        return porting::path_share + DIR_DELIM + "builtin";
 }
 
+std::string Server::getModStoragePath() const
+{
+       return m_path_world + DIR_DELIM + "mod_storage";
+}
+
 v3f Server::findSpawnPos()
 {
        ServerMap &map = m_env->getServerMap();
@@ -3282,30 +3435,24 @@ v3f Server::findSpawnPos()
                return nodeposf * BS;
        }
 
-       // 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);
-
-       s16 water_level = map.getWaterLevel();
-
        bool is_good = false;
 
        // Try to find a good place a few times
-       for(s32 i = 0; i < 1000 && !is_good; i++) {
+       for(s32 i = 0; i < 4000 && !is_good; i++) {
                s32 range = 1 + i;
                // We're going to try to throw the player to this position
                v2s16 nodepos2d = v2s16(
                                -range + (myrand() % (range * 2)),
                                -range + (myrand() % (range * 2)));
 
-               // Get ground height at point
-               s16 groundheight = map.findGroundLevel(nodepos2d);
-               if (groundheight <= water_level) // Don't go underwater
-                       continue;
-               if (groundheight > water_level + 6) // Don't go to high places
+               // Get spawn level at point
+               s16 spawn_level = m_emerge->getSpawnLevelAtPoint(nodepos2d);
+               // Continue if MAX_MAP_GENERATION_LIMIT was returned by
+               // the mapgen to signify an unsuitable spawn position
+               if (spawn_level == MAX_MAP_GENERATION_LIMIT)
                        continue;
 
-               nodepos = v3s16(nodepos2d.X, groundheight, nodepos2d.Y);
+               v3s16 nodepos(nodepos2d.X, spawn_level, nodepos2d.Y);
 
                s32 air_count = 0;
                for (s32 i = 0; i < 10; i++) {
@@ -3314,7 +3461,11 @@ v3f Server::findSpawnPos()
                        content_t c = map.getNodeNoEx(nodepos).getContent();
                        if (c == CONTENT_AIR || c == CONTENT_IGNORE) {
                                air_count++;
-                               if (air_count >= 2){
+                               if (air_count >= 2) {
+                                       nodeposf = intToFloat(nodepos, BS);
+                                       // Don't spawn the player outside map boundaries
+                                       if (objectpos_over_limit(nodeposf))
+                                               continue;
                                        is_good = true;
                                        break;
                                }
@@ -3323,21 +3474,53 @@ v3f Server::findSpawnPos()
                }
        }
 
-       return intToFloat(nodepos, BS);
+       return nodeposf;
+}
+
+void Server::requestShutdown(const std::string &msg, bool reconnect, float delay)
+{
+       if (delay == 0.0f) {
+       // No delay, shutdown immediately
+               m_shutdown_requested = true;
+       } else if (delay < 0.0f && m_shutdown_timer > 0.0f) {
+       // Negative delay, cancel shutdown if requested
+               m_shutdown_timer = 0.0f;
+               m_shutdown_msg = "";
+               m_shutdown_ask_reconnect = false;
+               m_shutdown_requested = false;
+               std::wstringstream ws;
+
+               ws << L"*** Server shutdown canceled.";
+
+               infostream << wide_to_utf8(ws.str()).c_str() << std::endl;
+               SendChatMessage(PEER_ID_INEXISTENT, ws.str());
+       } else if (delay > 0.0f) {
+       // Positive delay, delay the shutdown
+               m_shutdown_timer = delay;
+               m_shutdown_msg = msg;
+               m_shutdown_ask_reconnect = reconnect;
+               std::wstringstream ws;
+
+               ws << L"*** Server shutting down in "
+                               << duration_to_string(myround(m_shutdown_timer)).c_str()
+                               << ".";
+
+               infostream << wide_to_utf8(ws.str()).c_str() << std::endl;
+               SendChatMessage(PEER_ID_INEXISTENT, ws.str());
+       }
 }
 
-PlayerSAO* Server::emergePlayer(const char *name, u16 peer_id)
+PlayerSAO* Server::emergePlayer(const char *name, u16 peer_id, u16 proto_version)
 {
        bool newplayer = false;
 
        /*
                Try to get an existing player
        */
-       RemotePlayer *player = static_cast<RemotePlayer*>(m_env->getPlayer(name));
+       RemotePlayer *player = m_env->getPlayer(name);
 
        // If player is already connected, cancel
-       if(player != NULL && player->peer_id != 0)
-       {
+       if (player != NULL && player->peer_id != 0) {
                infostream<<"emergePlayer(): Player already connected"<<std::endl;
                return NULL;
        }
@@ -3345,39 +3528,44 @@ PlayerSAO* Server::emergePlayer(const char *name, u16 peer_id)
        /*
                If player with the wanted peer_id already exists, cancel.
        */
-       if(m_env->getPlayer(peer_id) != NULL)
-       {
+       if (m_env->getPlayer(peer_id) != NULL) {
                infostream<<"emergePlayer(): Player with wrong name but same"
                                " peer_id already exists"<<std::endl;
                return NULL;
        }
 
-       // Load player if it isn't already loaded
-       if (!player) {
-               player = static_cast<RemotePlayer*>(m_env->loadPlayer(name));
-       }
+       // Create a new player active object
+       PlayerSAO *playersao = new PlayerSAO(m_env, peer_id, isSingleplayer());
+       player = m_env->loadPlayer(name, playersao);
 
        // Create player if it doesn't exist
        if (!player) {
                newplayer = true;
-               player = new RemotePlayer(this, name);
+               player = new RemotePlayer(name, this->idef());
                // Set player position
                infostream<<"Server: Finding spawn place for player \""
                                <<name<<"\""<<std::endl;
-               v3f pos = findSpawnPos();
-               player->setPosition(pos);
+               playersao->setBasePosition(findSpawnPos());
 
                // Make sure the player is saved
                player->setModified(true);
 
                // Add player to environment
                m_env->addPlayer(player);
+       } else {
+               // If the player exists, ensure that they respawn inside legal bounds
+               // This fixes an assert crash when the player can't be added
+               // to the environment
+               if (objectpos_over_limit(playersao->getBasePosition())) {
+                       actionstream << "Respawn position for player \""
+                               << name << "\" outside limits, resetting" << std::endl;
+                       playersao->setBasePosition(findSpawnPos());
+               }
        }
 
-       // Create a new player active object
-       PlayerSAO *playersao = new PlayerSAO(m_env, player, peer_id,
-                       getPlayerEffectivePrivs(player->getName()),
-                       isSingleplayer());
+       playersao->initialize(player, getPlayerEffectivePrivs(player->getName()));
+
+       player->protocol_version = proto_version;
 
        /* Clean up old HUD elements from previous sessions */
        player->clearHud();
@@ -3393,17 +3581,41 @@ PlayerSAO* Server::emergePlayer(const char *name, u16 peer_id)
        return playersao;
 }
 
+bool Server::registerModStorage(ModMetadata *storage)
+{
+       if (m_mod_storages.find(storage->getModName()) != m_mod_storages.end()) {
+               errorstream << "Unable to register same mod storage twice. Storage name: "
+                               << storage->getModName() << std::endl;
+               return false;
+       }
+
+       m_mod_storages[storage->getModName()] = storage;
+       return true;
+}
+
+void Server::unregisterModStorage(const std::string &name)
+{
+       UNORDERED_MAP<std::string, ModMetadata *>::const_iterator it = m_mod_storages.find(name);
+       if (it != m_mod_storages.end()) {
+               // Save unconditionaly on unregistration
+               it->second->save(getModStoragePath());
+               m_mod_storages.erase(name);
+       }
+}
+
 void dedicated_server_loop(Server &server, bool &kill)
 {
-       DSTACK(__FUNCTION_NAME);
+       DSTACK(FUNCTION_NAME);
 
        verbosestream<<"dedicated_server_loop()"<<std::endl;
 
        IntervalLimiter m_profiler_interval;
 
-       for(;;)
-       {
-               float steplen = g_settings->getFloat("dedicated_server_step");
+       static const float steplen = g_settings->getFloat("dedicated_server_step");
+       static const float profiler_print_interval =
+                       g_settings->getFloat("profiler_print_interval");
+
+       for(;;) {
                // This is kind of a hack but can be done like this
                // because server.step() is very light
                {
@@ -3412,23 +3624,13 @@ void dedicated_server_loop(Server &server, bool &kill)
                }
                server.step(steplen);
 
-               if(server.getShutdownRequested() || kill)
-               {
-                       infostream<<"Dedicated server quitting"<<std::endl;
-#if USE_CURL
-                       if(g_settings->getBool("server_announce"))
-                               ServerList::sendAnnounce("delete", server.m_bind_addr.getPort());
-#endif
+               if (server.getShutdownRequested() || kill)
                        break;
-               }
 
                /*
                        Profiler
                */
-               float profiler_print_interval =
-                               g_settings->getFloat("profiler_print_interval");
-               if(profiler_print_interval != 0)
-               {
+               if (profiler_print_interval != 0) {
                        if(m_profiler_interval.step(steplen, profiler_print_interval))
                        {
                                infostream<<"Profiler:"<<std::endl;
@@ -3437,4 +3639,11 @@ void dedicated_server_loop(Server &server, bool &kill)
                        }
                }
        }
+
+       infostream << "Dedicated server quitting" << std::endl;
+#if USE_CURL
+       if (g_settings->getBool("server_announce"))
+               ServerList::sendAnnounce(ServerList::AA_DELETE,
+                       server.m_bind_addr.getPort());
+#endif
 }