#include "main.h"
#include "constants.h"
#include "voxel.h"
-#include "materials.h"
-#include "mineral.h"
#include "config.h"
#include "servercommand.h"
#include "filesys.h"
-#include "content_mapnode.h"
-#include "content_craft.h"
-#include "content_nodemeta.h"
#include "mapblock.h"
#include "serverobject.h"
#include "settings.h"
#include "script.h"
#include "scriptapi.h"
#include "nodedef.h"
-#include "tooldef.h"
+#include "itemdef.h"
#include "craftdef.h"
#include "mapgen.h"
+#include "content_mapnode.h"
+#include "content_nodemeta.h"
+#include "content_abm.h"
+#include "content_sao.h"
+#include "mods.h"
+#include "sha1.h"
+#include "base64.h"
+#include "tool.h"
+#include "utility_string.h"
+#include "sound.h" // dummySoundManager
+#include "event_manager.h"
+#include "hex.h"
#define PP(x) "("<<(x).X<<","<<(x).Y<<","<<(x).Z<<")"
bool *m_flag;
};
+class MapEditEventAreaIgnorer
+{
+public:
+ MapEditEventAreaIgnorer(VoxelArea *ignorevariable, const VoxelArea &a):
+ m_ignorevariable(ignorevariable)
+ {
+ if(m_ignorevariable->getVolume() == 0)
+ *m_ignorevariable = a;
+ else
+ m_ignorevariable = NULL;
+ }
+
+ ~MapEditEventAreaIgnorer()
+ {
+ if(m_ignorevariable)
+ {
+ assert(m_ignorevariable->getVolume() != 0);
+ *m_ignorevariable = VoxelArea();
+ }
+ }
+
+private:
+ VoxelArea *m_ignorevariable;
+};
+
void * ServerThread::Thread()
{
ThreadStarted();
{
infostream<<"Server: PeerNotFoundException"<<std::endl;
}
+ catch(con::ConnectionBindFailed &e)
+ {
+ m_server->setAsyncFatalError(e.what());
+ }
+ catch(LuaError &e)
+ {
+ m_server->setAsyncFatalError(e.what());
+ }
}
END_DEBUG_EXCEPTION_HANDLER(errorstream)
t.stop(true); // Hide output
}
- {
+ do{ // enable break
// Lock environment again to access the map
JMutexAutoLock envlock(m_server->m_env_mutex);
// Get central block
block = map.getBlockNoCreateNoEx(p);
+
+ // If block doesn't exist, don't try doing anything with it
+ // This happens if the block is not in generation boundaries
+ if(!block)
+ break;
/*
Do some post-generate stuff
*/
-
- v3s16 minp = block->getPos()*MAP_BLOCKSIZE;
- v3s16 maxp = minp + v3s16(1,1,1)*(MAP_BLOCKSIZE-1);
- scriptapi_environment_on_generated(m_server->m_lua,
- minp, maxp);
-
- if(enable_mapgen_debug_info)
- infostream<<"EmergeThread: ended up with: "
- <<analyze_block(block)<<std::endl;
+ v3s16 minp = data.blockpos_min*MAP_BLOCKSIZE;
+ v3s16 maxp = data.blockpos_max*MAP_BLOCKSIZE +
+ v3s16(1,1,1)*(MAP_BLOCKSIZE-1);
+
/*
Ignore map edit events, they will not need to be
sent to anybody because the block hasn't been sent
to anybody
*/
- MapEditEventIgnorer ign(&m_server->m_ignore_map_edit_events);
+ //MapEditEventIgnorer ign(&m_server->m_ignore_map_edit_events);
+ MapEditEventAreaIgnorer ign(
+ &m_server->m_ignore_map_edit_events_area,
+ VoxelArea(minp, maxp));
+ {
+ TimeTaker timer("on_generated");
+ scriptapi_environment_on_generated(m_server->m_lua,
+ minp, maxp, mapgen::get_blockseed(data.seed, minp));
+ /*int t = timer.stop(true);
+ dstream<<"on_generated took "<<t<<"ms"<<std::endl;*/
+ }
+ if(enable_mapgen_debug_info)
+ infostream<<"EmergeThread: ended up with: "
+ <<analyze_block(block)<<std::endl;
+
// Activate objects and stuff
- m_server->m_env->activateBlock(block, 3600);
- }
+ m_server->m_env->activateBlock(block, 0);
+ }while(false);
}
if(block == NULL)
return NULL;
}
+v3f ServerSoundParams::getPos(ServerEnvironment *env, bool *pos_exists) const
+{
+ if(pos_exists) *pos_exists = false;
+ switch(type){
+ case SSP_LOCAL:
+ return v3f(0,0,0);
+ case SSP_POSITIONAL:
+ if(pos_exists) *pos_exists = true;
+ return pos;
+ case SSP_OBJECT: {
+ if(object == 0)
+ return v3f(0,0,0);
+ ServerActiveObject *sao = env->getActiveObject(object);
+ if(!sao)
+ return v3f(0,0,0);
+ if(pos_exists) *pos_exists = true;
+ return sao->getBasePosition(); }
+ }
+ return v3f(0,0,0);
+}
+
void RemoteClient::GetNextBlocks(Server *server, float dtime,
core::array<PrioritySortedBlockTransfer> &dest)
{
*/
if(d >= 4)
{
- if(block->dayNightDiffed() == false)
+ if(block->getDayNightDiff() == false)
continue;
}
#endif
//if(server->m_emerge_queue.peerItemCount(peer_id) < 1)
// Allow two blocks in queue per client
//if(server->m_emerge_queue.peerItemCount(peer_id) < 2)
- u32 max_emerge = 25;
+ u32 max_emerge = 5;
// Make it more responsive when needing to generate stuff
if(surely_not_found_on_disk)
- max_emerge = 5;
+ max_emerge = 1;
if(server->m_emerge_queue.peerItemCount(peer_id) < max_emerge)
{
//infostream<<"Adding block to emerge queue"<<std::endl;
infostream<<"GetNextBlocks duration: "<<timer_result<<" (!=0)"<<std::endl;*/
}
-void RemoteClient::SendObjectData(
- Server *server,
- float dtime,
- core::map<v3s16, bool> &stepped_blocks
- )
-{
- DSTACK(__FUNCTION_NAME);
-
- // Can't send anything without knowing version
- if(serialization_version == SER_FMT_VER_INVALID)
- {
- infostream<<"RemoteClient::SendObjectData(): Not sending, no version."
- <<std::endl;
- return;
- }
-
- /*
- Send a TOCLIENT_OBJECTDATA packet.
- Sent as unreliable.
-
- u16 command
- u16 number of player positions
- for each player:
- u16 peer_id
- v3s32 position*100
- v3s32 speed*100
- s32 pitch*100
- s32 yaw*100
- u16 count of blocks
- for each block:
- block objects
- */
-
- std::ostringstream os(std::ios_base::binary);
- u8 buf[12];
-
- // Write command
- writeU16(buf, TOCLIENT_OBJECTDATA);
- os.write((char*)buf, 2);
-
- /*
- Get and write player data
- */
-
- // Get connected players
- core::list<Player*> players = server->m_env->getPlayers(true);
-
- // Write player count
- u16 playercount = players.size();
- writeU16(buf, playercount);
- os.write((char*)buf, 2);
-
- core::list<Player*>::Iterator i;
- for(i = players.begin();
- i != players.end(); i++)
- {
- Player *player = *i;
-
- v3f pf = player->getPosition();
- v3f sf = player->getSpeed();
-
- v3s32 position_i(pf.X*100, pf.Y*100, pf.Z*100);
- v3s32 speed_i (sf.X*100, sf.Y*100, sf.Z*100);
- s32 pitch_i (player->getPitch() * 100);
- s32 yaw_i (player->getYaw() * 100);
-
- writeU16(buf, player->peer_id);
- os.write((char*)buf, 2);
- writeV3S32(buf, position_i);
- os.write((char*)buf, 12);
- writeV3S32(buf, speed_i);
- os.write((char*)buf, 12);
- writeS32(buf, pitch_i);
- os.write((char*)buf, 4);
- writeS32(buf, yaw_i);
- os.write((char*)buf, 4);
- }
-
- /*
- Get and write object data (dummy, for compatibility)
- */
-
- // Write block count
- writeU16(buf, 0);
- os.write((char*)buf, 2);
-
- /*
- Send data
- */
-
- //infostream<<"Server: Sending object data to "<<peer_id<<std::endl;
-
- // Make data buffer
- std::string s = os.str();
- SharedBuffer<u8> data((u8*)s.c_str(), s.size());
- // Send as unreliable
- server->m_con.Send(peer_id, 0, data, false);
-}
-
void RemoteClient::GotBlock(v3s16 p)
{
if(m_blocks_sending.find(p) != NULL)
(*s)<<std::endl;
}
-u32 PIChecksum(core::list<PlayerInfo> &l)
-{
- core::list<PlayerInfo>::Iterator i;
- u32 checksum = 1;
- u32 a = 10;
- for(i=l.begin(); i!=l.end(); i++)
- {
- checksum += a * (i->id+1);
- checksum ^= 0x435aafcd;
- a *= 10;
- }
- return checksum;
-}
-
-/*
- Mods
-*/
-
-struct ModSpec
-{
- std::string name;
- std::string path;
- std::set<std::string> depends;
- std::set<std::string> unsatisfied_depends;
-
- ModSpec(const std::string &name_="", const std::string path_="",
- const std::set<std::string> &depends_=std::set<std::string>()):
- name(name_),
- path(path_),
- depends(depends_),
- unsatisfied_depends(depends_)
- {}
-};
-
-// Get a dependency-sorted list of ModSpecs
-static core::list<ModSpec> getMods(core::list<std::string> &modspaths)
-{
- std::queue<ModSpec> mods_satisfied;
- core::list<ModSpec> mods_unsorted;
- core::list<ModSpec> mods_sorted;
- for(core::list<std::string>::Iterator i = modspaths.begin();
- i != modspaths.end(); i++){
- std::string modspath = *i;
- std::vector<fs::DirListNode> dirlist = fs::GetDirListing(modspath);
- for(u32 j=0; j<dirlist.size(); j++){
- if(!dirlist[j].dir)
- continue;
- std::string modname = dirlist[j].name;
- std::string modpath = modspath + DIR_DELIM + modname;
- std::set<std::string> depends;
- std::ifstream is((modpath+DIR_DELIM+"depends.txt").c_str(),
- std::ios_base::binary);
- while(is.good()){
- std::string dep;
- std::getline(is, dep);
- dep = trim(dep);
- if(dep != "")
- depends.insert(dep);
- }
- ModSpec spec(modname, modpath, depends);
- mods_unsorted.push_back(spec);
- if(depends.empty())
- mods_satisfied.push(spec);
- }
- }
- // Sort by depencencies
- while(!mods_satisfied.empty()){
- ModSpec mod = mods_satisfied.front();
- mods_satisfied.pop();
- mods_sorted.push_back(mod);
- for(core::list<ModSpec>::Iterator i = mods_unsorted.begin();
- i != mods_unsorted.end(); i++){
- ModSpec &mod2 = *i;
- if(mod2.unsatisfied_depends.empty())
- continue;
- mod2.unsatisfied_depends.erase(mod.name);
- if(!mod2.unsatisfied_depends.empty())
- continue;
- mods_satisfied.push(mod2);
- }
- }
- // Check unsatisfied dependencies
- for(core::list<ModSpec>::Iterator i = mods_unsorted.begin();
- i != mods_unsorted.end(); i++){
- ModSpec &mod = *i;
- if(mod.unsatisfied_depends.empty())
- continue;
- errorstream<<"mod \""<<mod.name
- <<"\" has unsatisfied dependencies:";
- for(std::set<std::string>::iterator
- i = mod.unsatisfied_depends.begin();
- i != mod.unsatisfied_depends.end(); i++){
- errorstream<<" \""<<(*i)<<"\"";
- }
- errorstream<<". Loading nevertheless."<<std::endl;
- mods_sorted.push_back(mod);
- }
- return mods_sorted;
-}
-
/*
Server
*/
Server::Server(
- std::string mapsavedir,
- std::string configpath
+ const std::string &path_world,
+ const std::string &path_config,
+ const SubgameSpec &gamespec,
+ bool simple_singleplayer_mode
):
+ m_path_world(path_world),
+ m_path_config(path_config),
+ m_gamespec(gamespec),
+ m_simple_singleplayer_mode(simple_singleplayer_mode),
+ m_async_fatal_error(""),
m_env(NULL),
m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, this),
- m_authmanager(mapsavedir+DIR_DELIM+"auth.txt"),
- m_banmanager(mapsavedir+DIR_DELIM+"ipban.txt"),
+ m_banmanager(path_world+DIR_DELIM+"ipban.txt"),
m_lua(NULL),
- m_toolmgr(createToolDefManager()),
+ m_itemdef(createItemDefManager()),
m_nodedef(createNodeDefManager()),
m_craftdef(createCraftDefManager()),
+ m_event(new EventManager()),
m_thread(this),
m_emergethread(this),
- m_time_counter(0),
m_time_of_day_send_timer(0),
m_uptime(0),
- m_mapsavedir(mapsavedir),
- m_configpath(configpath),
m_shutdown_requested(false),
m_ignore_map_edit_events(false),
m_ignore_map_edit_events_peer_id(0)
m_step_dtime_mutex.Init();
m_step_dtime = 0.0;
- JMutexAutoLock envlock(m_env_mutex);
- JMutexAutoLock conlock(m_con_mutex);
-
- infostream<<"m_nodedef="<<m_nodedef<<std::endl;
+ if(path_world == "")
+ throw ServerError("Supplied empty world path");
+
+ if(!gamespec.isValid())
+ throw ServerError("Supplied invalid gamespec");
+
+ infostream<<"Server created for gameid \""<<m_gamespec.id<<"\"";
+ if(m_simple_singleplayer_mode)
+ infostream<<" in simple singleplayer mode"<<std::endl;
+ else
+ infostream<<std::endl;
+ infostream<<"- world: "<<m_path_world<<std::endl;
+ infostream<<"- config: "<<m_path_config<<std::endl;
+ infostream<<"- game: "<<m_gamespec.path<<std::endl;
+
+ // Add world mod search path
+ m_modspaths.push_front(m_path_world + DIR_DELIM + "worldmods");
+ // Add addon mod search path
+ for(std::set<std::string>::const_iterator i = m_gamespec.mods_paths.begin();
+ i != m_gamespec.mods_paths.end(); i++)
+ m_modspaths.push_front((*i));
+
+ // Print out mod search paths
+ for(core::list<std::string>::Iterator i = m_modspaths.begin();
+ i != m_modspaths.end(); i++){
+ std::string modspath = *i;
+ infostream<<"- mods: "<<modspath<<std::endl;
+ }
// Path to builtin.lua
- std::string builtinpath = porting::path_data + DIR_DELIM + "builtin.lua";
- // Add default global mod path
- m_modspaths.push_back(porting::path_data + DIR_DELIM + "mods");
+ std::string builtinpath = getBuiltinLuaPath() + DIR_DELIM + "builtin.lua";
+
+ // Create world if it doesn't exist
+ if(!initializeWorld(m_path_world, m_gamespec.id))
+ throw ServerError("Failed to initialize world");
+
+ // Lock environment
+ JMutexAutoLock envlock(m_env_mutex);
+ JMutexAutoLock conlock(m_con_mutex);
// Initialize scripting
- infostream<<"Server: Initializing scripting"<<std::endl;
+ infostream<<"Server: Initializing Lua"<<std::endl;
m_lua = script_init();
assert(m_lua);
// Export API
scriptapi_export(m_lua, this);
// Load and run builtin.lua
- infostream<<"Server: Loading builtin Lua stuff from \""<<builtinpath
- <<"\""<<std::endl;
- bool success = script_load(m_lua, builtinpath.c_str());
+ infostream<<"Server: Loading builtin.lua [\""
+ <<builtinpath<<"\"]"<<std::endl;
+ bool success = scriptapi_loadmod(m_lua, builtinpath, "__builtin");
if(!success){
errorstream<<"Server: Failed to load and run "
<<builtinpath<<std::endl;
- assert(0);
+ throw ModError("Failed to load and run "+builtinpath);
}
+ // Find mods in mod search paths
+ m_mods = getMods(m_modspaths);
+ // Print 'em
+ infostream<<"Server: Loading mods: ";
+ for(core::list<ModSpec>::Iterator i = m_mods.begin();
+ i != m_mods.end(); i++){
+ const ModSpec &mod = *i;
+ infostream<<mod.name<<" ";
+ }
+ infostream<<std::endl;
// Load and run "mod" scripts
- core::list<ModSpec> mods = getMods(m_modspaths);
- for(core::list<ModSpec>::Iterator i = mods.begin();
- i != mods.end(); i++){
- ModSpec mod = *i;
- infostream<<"Server: Loading mod \""<<mod.name<<"\""<<std::endl;
+ for(core::list<ModSpec>::Iterator i = m_mods.begin();
+ i != m_mods.end(); i++){
+ const ModSpec &mod = *i;
std::string scriptpath = mod.path + DIR_DELIM + "init.lua";
- bool success = script_load(m_lua, scriptpath.c_str());
+ infostream<<" ["<<padStringRight(mod.name, 12)<<"] [\""
+ <<scriptpath<<"\"]"<<std::endl;
+ bool success = scriptapi_loadmod(m_lua, scriptpath, mod.name);
if(!success){
errorstream<<"Server: Failed to load and run "
<<scriptpath<<std::endl;
- assert(0);
+ throw ModError("Failed to load and run "+scriptpath);
}
}
+ // Read Textures and calculate sha1 sums
+ fillMediaCache();
+
+ // Apply item aliases in the node definition manager
+ m_nodedef->updateAliases(m_itemdef);
+
// Initialize Environment
- m_env = new ServerEnvironment(new ServerMap(mapsavedir, this), m_lua,
+ m_env = new ServerEnvironment(new ServerMap(path_world, this), m_lua,
this, this);
// Give environment reference to scripting api
m_env->getMap().addEventReceiver(this);
// If file exists, load environment metadata
- if(fs::PathExists(m_mapsavedir+DIR_DELIM+"env_meta.txt"))
+ if(fs::PathExists(m_path_world+DIR_DELIM+"env_meta.txt"))
{
infostream<<"Server: Loading environment metadata"<<std::endl;
- m_env->loadMeta(m_mapsavedir);
+ m_env->loadMeta(m_path_world);
}
// Load players
infostream<<"Server: Loading players"<<std::endl;
- m_env->deSerializePlayers(m_mapsavedir);
+ m_env->deSerializePlayers(m_path_world);
+
+ /*
+ Add some test ActiveBlockModifiers to environment
+ */
+ add_legacy_abms(m_env, m_nodedef);
}
Server::~Server()
{
- infostream<<"Server::~Server()"<<std::endl;
+ infostream<<"Server destructing"<<std::endl;
/*
Send shutdown message
Save players
*/
infostream<<"Server: Saving players"<<std::endl;
- m_env->serializePlayers(m_mapsavedir);
+ m_env->serializePlayers(m_path_world);
/*
Save environment metadata
*/
infostream<<"Server: Saving environment metadata"<<std::endl;
- m_env->saveMeta(m_mapsavedir);
+ m_env->saveMeta(m_path_world);
}
/*
delete i.getNode()->getValue();
}
}
-
- // Delete Environment
+
+ // Delete things in the reverse order of creation
delete m_env;
-
- delete m_toolmgr;
+ delete m_event;
+ delete m_itemdef;
delete m_nodedef;
+ delete m_craftdef;
// Deinitialize scripting
infostream<<"Server: Deinitializing scripting"<<std::endl;
void Server::start(unsigned short port)
{
DSTACK(__FUNCTION_NAME);
+ infostream<<"Starting server on port "<<port<<"..."<<std::endl;
+
// Stop thread if already running
m_thread.stop();
m_thread.setRun(true);
m_thread.Start();
- infostream<<"Server: Started on port "<<port<<std::endl;
+ // ASCII art for the win!
+ actionstream
+ <<" .__ __ __ "<<std::endl
+ <<" _____ |__| ____ _____/ |_ ____ _______/ |_ "<<std::endl
+ <<" / \\| |/ \\_/ __ \\ __\\/ __ \\ / ___/\\ __\\"<<std::endl
+ <<"| Y Y \\ | | \\ ___/| | \\ ___/ \\___ \\ | | "<<std::endl
+ <<"|__|_| /__|___| /\\___ >__| \\___ >____ > |__| "<<std::endl
+ <<" \\/ \\/ \\/ \\/ \\/ "<<std::endl;
+ actionstream<<"World at ["<<m_path_world<<"]"<<std::endl;
+ actionstream<<"Server for gameid=\""<<m_gamespec.id
+ <<"\" listening on port "<<port<<"."<<std::endl;
}
void Server::stop()
JMutexAutoLock 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 != ""){
+ throw ServerError(async_err);
+ }
}
void Server::AsyncRunStep()
}
{
- ScopeProfiler sp(g_profiler, "Server: sel and send blocks to clients");
// Send blocks to clients
SendBlocks(dtime);
}
}
/*
- Update m_time_of_day and overall game time
+ Update time of day and overall game time
*/
{
JMutexAutoLock envlock(m_env_mutex);
- m_time_counter += dtime;
- f32 speed = g_settings->getFloat("time_speed") * 24000./(24.*3600);
- u32 units = (u32)(m_time_counter*speed);
- m_time_counter -= (f32)units / speed;
-
- m_env->setTimeOfDay((m_env->getTimeOfDay() + units) % 24000);
-
- //infostream<<"Server: m_time_of_day = "<<m_time_of_day.get()<<std::endl;
+ m_env->setTimeOfDaySpeed(g_settings->getFloat("time_speed"));
/*
Send to clients at constant intervals
i.atEnd() == false; i++)
{
RemoteClient *client = i.getNode()->getValue();
- //Player *player = m_env->getPlayer(client->peer_id);
-
SharedBuffer<u8> data = makePacket_TOCLIENT_TIME_OF_DAY(
- m_env->getTimeOfDay());
+ m_env->getTimeOfDay(), g_settings->getFloat("time_speed"));
// Send as reliable
m_con.Send(client->peer_id, 0, data, true);
}
*/
/*
- Check player movements
-
- NOTE: Actually the server should handle player physics like the
- client does and compare player's position to what is calculated
- on our side. This is required when eg. players fly due to an
- explosion.
+ Handle players
*/
{
JMutexAutoLock lock(m_env_mutex);
JMutexAutoLock lock2(m_con_mutex);
- //float player_max_speed = BS * 4.0; // Normal speed
- float player_max_speed = BS * 20; // Fast speed
- float player_max_speed_up = BS * 20;
-
- player_max_speed *= 2.5; // Tolerance
- player_max_speed_up *= 2.5;
+ ScopeProfiler sp(g_profiler, "Server: handle players");
for(core::map<u16, RemoteClient*>::Iterator
i = m_clients.getIterator();
i.atEnd() == false; i++)
{
RemoteClient *client = i.getNode()->getValue();
- ServerRemotePlayer *player =
- (ServerRemotePlayer*)m_env->getPlayer(client->peer_id);
- if(player==NULL)
+ PlayerSAO *playersao = getPlayerSAO(client->peer_id);
+ if(playersao == NULL)
continue;
- player->m_last_good_position_age += dtime;
- if(player->m_last_good_position_age >= 2.0){
- float age = player->m_last_good_position_age;
- v3f diff = (player->getPosition() - player->m_last_good_position);
- float d_vert = diff.Y;
- diff.Y = 0;
- float d_horiz = diff.getLength();
- /*infostream<<player->getName()<<"'s horizontal speed is "
- <<(d_horiz/age)<<std::endl;*/
- if(d_horiz <= age * player_max_speed &&
- (d_vert < 0 || d_vert < age * player_max_speed_up)){
- player->m_last_good_position = player->getPosition();
- } else {
- actionstream<<"Player "<<player->getName()
- <<" moved too fast; resetting position"
- <<std::endl;
- player->setPosition(player->m_last_good_position);
- SendMovePlayer(player);
- }
- player->m_last_good_position_age = 0;
+
+ /*
+ Handle player HPs (die if hp=0)
+ */
+ if(playersao->getHP() == 0 && playersao->m_hp_not_sent)
+ DiePlayer(client->peer_id);
+
+ /*
+ Send player inventories and HPs if necessary
+ */
+ if(playersao->m_teleported){
+ SendMovePlayer(client->peer_id);
+ playersao->m_teleported = false;
+ }
+ if(playersao->m_inventory_not_sent){
+ UpdateCrafting(client->peer_id);
+ SendInventory(client->peer_id);
+ }
+ if(playersao->m_hp_not_sent){
+ SendPlayerHP(client->peer_id);
}
}
}
i.atEnd() == false; i++)
{
RemoteClient *client = i.getNode()->getValue();
+
+ // If definitions and textures have not been sent, don't
+ // send objects either
+ if(!client->definitions_sent)
+ continue;
+
Player *player = m_env->getPlayer(client->peer_id);
if(player==NULL)
{
infostream<<"WARNING: "<<__FUNCTION_NAME
<<": NULL object"<<std::endl;
else
- type = obj->getType();
+ type = obj->getSendType();
// Add to data buffer for sending
writeU16((u8*)buf, id);
// Send as reliable
m_con.Send(client->peer_id, 0, reply, true);
- infostream<<"Server: Sent object remove/add: "
+ verbosestream<<"Server: Sent object remove/add: "
<<removed_objects.size()<<" removed, "
<<added_objects.size()<<" added, "
<<"packet size is "<<reply.getSize()<<std::endl;
JMutexAutoLock envlock(m_env_mutex);
JMutexAutoLock conlock(m_con_mutex);
- //ScopeProfiler sp(g_profiler, "Server: sending object messages");
+ ScopeProfiler sp(g_profiler, "Server: sending object messages");
// Key = object id
// Value = data sent by object
Send queued-for-sending map edit events.
*/
{
+ // We will be accessing the environment and the connection
+ JMutexAutoLock lock(m_env_mutex);
+ JMutexAutoLock conlock(m_con_mutex);
+
// Don't send too many at a time
//u32 count = 0;
if(m_unsent_map_edit_queue.size() >= 4)
disable_single_change_sending = true;
- bool got_any_events = false;
+ int event_count = m_unsent_map_edit_queue.size();
// We'll log the amount of each
Profiler prof;
while(m_unsent_map_edit_queue.size() != 0)
{
- got_any_events = true;
-
MapEditEvent* event = m_unsent_map_edit_queue.pop_front();
// Players far away from the change are stored here.
break;*/
}
- if(got_any_events)
- {
+ if(event_count >= 5){
infostream<<"Server: MapEditEvents:"<<std::endl;
prof.print(infostream);
+ } else if(event_count != 0){
+ verbosestream<<"Server: MapEditEvents:"<<std::endl;
+ prof.print(verbosestream);
}
}
- /*
- Send object positions
- */
- {
- float &counter = m_objectdata_timer;
- counter += dtime;
- if(counter >= g_settings->getFloat("objectdata_interval"))
- {
- JMutexAutoLock lock1(m_env_mutex);
- JMutexAutoLock lock2(m_con_mutex);
-
- //ScopeProfiler sp(g_profiler, "Server: sending player positions");
-
- SendObjectData(counter);
-
- counter = 0.0;
- }
- }
-
/*
Trigger emergethread (it somehow gets to a non-triggered but
bysy state sometimes)
if(counter >= g_settings->getFloat("server_map_save_interval"))
{
counter = 0.0;
+ JMutexAutoLock lock(m_env_mutex);
ScopeProfiler sp(g_profiler, "Server: saving stuff");
- // Auth stuff
- if(m_authmanager.isModified())
- m_authmanager.save();
-
- //Bann stuff
+ //Ban stuff
if(m_banmanager.isModified())
m_banmanager.save();
- // Map
- JMutexAutoLock lock(m_env_mutex);
-
- /*// Unload unused data (delete from memory)
- m_env->getMap().unloadUnusedData(
- g_settings->getFloat("server_unload_unused_sectors_timeout"));
- */
- /*u32 deleted_count = m_env->getMap().unloadUnusedData(
- g_settings->getFloat("server_unload_unused_sectors_timeout"));
- */
-
- // Save only changed parts
- m_env->getMap().save(true);
-
- /*if(deleted_count > 0)
- {
- infostream<<"Server: Unloaded "<<deleted_count
- <<" blocks from memory"<<std::endl;
- }*/
+ // Save changed parts of map
+ m_env->getMap().save(MOD_STATE_WRITE_NEEDED);
// Save players
- m_env->serializePlayers(m_mapsavedir);
+ m_env->serializePlayers(m_path_world);
// Save environment metadata
- m_env->saveMeta(m_mapsavedir);
+ m_env->saveMeta(m_path_world);
}
}
}
JMutexAutoLock envlock(m_env_mutex);
JMutexAutoLock conlock(m_con_mutex);
+ ScopeProfiler sp(g_profiler, "Server::ProcessData");
+
try{
Address address = m_con.GetPeerAddress(peer_id);
+ std::string addr_s = address.serializeString();
// drop player if is ip is banned
- if(m_banmanager.isIpBanned(address.serializeString())){
+ if(m_banmanager.isIpBanned(addr_s)){
+ infostream<<"Server: A banned client tried to connect from "
+ <<addr_s<<"; banned name was "
+ <<m_banmanager.getBanName(addr_s)<<std::endl;
+ // This actually doesn't seem to transfer to the client
SendAccessDenied(m_con, peer_id,
L"Your ip is banned. Banned name was "
- +narrow_to_wide(m_banmanager.getBanName(
- address.serializeString())));
+ +narrow_to_wide(m_banmanager.getBanName(addr_s)));
m_con.DeletePeer(peer_id);
return;
}
<<peer_id<<" not found"<<std::endl;
return;
}
+
+ std::string addr_s = m_con.GetPeerAddress(peer_id).serializeString();
u8 peer_ser_ver = getClient(peer_id)->serialization_version;
if(datasize < 2+1+PLAYERNAME_SIZE)
return;
- infostream<<"Server: Got TOSERVER_INIT from "
+ verbosestream<<"Server: Got TOSERVER_INIT from "
<<peer_id<<std::endl;
// First byte after command is maximum supported
if(deployed == SER_FMT_VER_INVALID)
{
+ actionstream<<"Server: A mismatched client tried to connect from "
+ <<addr_s<<std::endl;
infostream<<"Server: Cannot negotiate "
"serialization version with peer "
<<peer_id<<std::endl;
- SendAccessDenied(m_con, peer_id,
- L"Your client is too old (map format)");
+ SendAccessDenied(m_con, peer_id, std::wstring(
+ L"Your client's version is not supported.\n"
+ L"Server version is ")
+ + narrow_to_wide(VERSION_STRING) + L"."
+ );
return;
}
if(net_proto_version == 0)
{
- SendAccessDenied(m_con, peer_id,
- L"Your client is too old. Please upgrade.");
+ actionstream<<"Server: An old tried to connect from "<<addr_s
+ <<std::endl;
+ SendAccessDenied(m_con, peer_id, std::wstring(
+ L"Your client's version is not supported.\n"
+ L"Server version is ")
+ + narrow_to_wide(VERSION_STRING) + L"."
+ );
return;
}
- /* Uhh... this should actually be a warning but let's do it like this */
if(g_settings->getBool("strict_protocol_version_checking"))
{
- if(net_proto_version < PROTOCOL_VERSION)
+ if(net_proto_version != PROTOCOL_VERSION)
{
- SendAccessDenied(m_con, peer_id,
- L"Your client is too old. Please upgrade.");
+ actionstream<<"Server: A mismatched client tried to connect"
+ <<" from "<<addr_s<<std::endl;
+ SendAccessDenied(m_con, peer_id, std::wstring(
+ L"Your client's version is not supported.\n"
+ L"Server version is ")
+ + narrow_to_wide(VERSION_STRING) + L",\n"
+ + L"server's PROTOCOL_VERSION is "
+ + narrow_to_wide(itos(PROTOCOL_VERSION))
+ + L", client's PROTOCOL_VERSION is "
+ + narrow_to_wide(itos(net_proto_version))
+ );
return;
}
}
if(playername[0]=='\0')
{
- infostream<<"Server: Player has empty name"<<std::endl;
+ actionstream<<"Server: Player with an empty name "
+ <<"tried to connect from "<<addr_s<<std::endl;
SendAccessDenied(m_con, peer_id,
L"Empty name");
return;
if(string_allowed(playername, PLAYERNAME_ALLOWED_CHARS)==false)
{
- infostream<<"Server: Player has invalid name"<<std::endl;
+ actionstream<<"Server: Player with an invalid name "
+ <<"tried to connect from "<<addr_s<<std::endl;
SendAccessDenied(m_con, peer_id,
L"Name contains unallowed characters");
return;
}
+ infostream<<"Server: New connection: \""<<playername<<"\" from "
+ <<m_con.GetPeerAddress(peer_id).serializeString()<<std::endl;
+
// Get password
char password[PASSWORD_SIZE];
if(datasize < 2+1+PLAYERNAME_SIZE+PASSWORD_SIZE)
}
else
{
- for(u32 i=0; i<PASSWORD_SIZE-1; i++)
- {
- password[i] = data[23+i];
- }
- password[PASSWORD_SIZE-1] = 0;
+ for(u32 i=0; i<PASSWORD_SIZE-1; i++)
+ {
+ password[i] = data[23+i];
+ }
+ password[PASSWORD_SIZE-1] = 0;
}
std::string checkpwd;
- if(m_authmanager.exists(playername))
- {
- checkpwd = m_authmanager.getPassword(playername);
- }
- else
- {
- checkpwd = g_settings->get("default_password");
- }
+ bool has_auth = scriptapi_get_auth(m_lua, playername, &checkpwd, NULL);
- /*infostream<<"Server: Client gave password '"<<password
- <<"', the correct one is '"<<checkpwd<<"'"<<std::endl;*/
+ if(!has_auth){
+ std::wstring raw_default_password =
+ narrow_to_wide(g_settings->get("default_password"));
+ std::string use_password =
+ translatePassword(playername, raw_default_password);
+
+ // If default_password is empty, allow any initial password
+ if (raw_default_password.length() == 0)
+ use_password = password;
+
+ scriptapi_create_auth(m_lua, playername, use_password);
+ }
- if(password != checkpwd && m_authmanager.exists(playername))
- {
+ has_auth = scriptapi_get_auth(m_lua, playername, &checkpwd, NULL);
+
+ if(!has_auth){
+ SendAccessDenied(m_con, peer_id, L"Not allowed to login");
+ return;
+ }
+
+ if(password != checkpwd){
infostream<<"Server: peer_id="<<peer_id
<<": supplied invalid password for "
<<playername<<std::endl;
SendAccessDenied(m_con, peer_id, L"Invalid password");
return;
}
-
- // Add player to auth manager
- if(m_authmanager.exists(playername) == false)
- {
- infostream<<"Server: adding player "<<playername
- <<" to auth manager"<<std::endl;
- m_authmanager.add(playername);
- m_authmanager.setPassword(playername, checkpwd);
- m_authmanager.setPrivs(playername,
- stringToPrivs(g_settings->get("default_privs")));
- m_authmanager.save();
+
+ // Do not allow multiple players in simple singleplayer mode.
+ // This isn't a perfect way to do it, but will suffice for now.
+ if(m_simple_singleplayer_mode && m_clients.size() > 1){
+ infostream<<"Server: Not allowing another client to connect in"
+ <<" simple singleplayer mode"<<std::endl;
+ SendAccessDenied(m_con, peer_id,
+ L"Running in simple singleplayer mode.");
+ return;
}
// Enforce user limit.
// Don't enforce for users that have some admin right
if(m_clients.size() >= g_settings->getU16("max_users") &&
- (m_authmanager.getPrivs(playername)
- & (PRIV_SERVER|PRIV_BAN|PRIV_PRIVS)) == 0 &&
+ !checkPriv(playername, "server") &&
+ !checkPriv(playername, "ban") &&
+ !checkPriv(playername, "privs") &&
+ !checkPriv(playername, "password") &&
playername != g_settings->get("name"))
{
+ actionstream<<"Server: "<<playername<<" tried to join, but there"
+ <<" are already max_users="
+ <<g_settings->getU16("max_users")<<" players."<<std::endl;
SendAccessDenied(m_con, peer_id, L"Too many users.");
return;
}
// Get player
- Player *player = emergePlayer(playername, password, peer_id);
+ PlayerSAO *playersao = emergePlayer(playername, peer_id);
// If failed, cancel
- if(player == NULL)
+ if(playersao == NULL)
{
- infostream<<"Server: peer_id="<<peer_id
+ errorstream<<"Server: peer_id="<<peer_id
<<": failed to emerge player"<<std::endl;
return;
}
SharedBuffer<u8> reply(2+1+6+8);
writeU16(&reply[0], TOCLIENT_INIT);
writeU8(&reply[2], deployed);
- writeV3S16(&reply[2+1], floatToInt(player->getPosition()+v3f(0,BS/2,0), BS));
+ writeV3S16(&reply[2+1], floatToInt(playersao->getPlayer()->getPosition()+v3f(0,BS/2,0), BS));
writeU64(&reply[2+1+6], m_env->getServerMap().getSeed());
// Send as reliable
/*
Send complete position information
*/
- SendMovePlayer(player);
+ SendMovePlayer(peer_id);
return;
}
if(command == TOSERVER_INIT2)
{
- infostream<<"Server: Got TOSERVER_INIT2 from "
+ verbosestream<<"Server: Got TOSERVER_INIT2 from "
<<peer_id<<std::endl;
+ Player *player = m_env->getPlayer(peer_id);
+ if(!player){
+ verbosestream<<"Server: TOSERVER_INIT2: "
+ <<"Player not found; ignoring."<<std::endl;
+ return;
+ }
getClient(peer_id)->serialization_version
= getClient(peer_id)->pending_serialization_version;
Send some initialization data
*/
- // Send tool definitions
- SendToolDef(m_con, peer_id, m_toolmgr);
+ infostream<<"Server: Sending content to "
+ <<getPlayerName(peer_id)<<std::endl;
+
+ // Send item definitions
+ SendItemDef(m_con, peer_id, m_itemdef);
// Send node definitions
SendNodeDef(m_con, peer_id, m_nodedef);
- // Send textures
- SendTextures(peer_id);
+ // Send media announcement
+ sendMediaAnnouncement(peer_id);
- // Send player info to all players
- SendPlayerInfos();
-
- // Send inventory to player
+ // Send privileges
+ SendPlayerPrivileges(peer_id);
+
+ // Send inventory
UpdateCrafting(peer_id);
SendInventory(peer_id);
-
- // Send player items to all players
- SendPlayerItems();
-
- Player *player = m_env->getPlayer(peer_id);
-
+
// Send HP
- SendPlayerHP(player);
+ SendPlayerHP(peer_id);
+ // Show death screen if necessary
+ if(player->hp == 0)
+ SendDeathscreen(m_con, peer_id, false, v3f(0,0,0));
+
// Send time of day
{
SharedBuffer<u8> data = makePacket_TOCLIENT_TIME_OF_DAY(
- m_env->getTimeOfDay());
+ m_env->getTimeOfDay(), g_settings->getFloat("time_speed"));
m_con.Send(peer_id, 0, data, true);
}
- // Send information about server to player in chat
- SendChatMessage(peer_id, getStatusString());
-
- // Send information about joining in chat
+ // Note things in chat if not in simple singleplayer mode
+ if(!m_simple_singleplayer_mode)
{
- std::wstring name = L"unknown";
- Player *player = m_env->getPlayer(peer_id);
- if(player != NULL)
- name = narrow_to_wide(player->getName());
+ // Send information about server to player in chat
+ SendChatMessage(peer_id, getStatusString());
- std::wstring message;
- message += L"*** ";
- message += name;
- message += L" joined game";
- BroadcastChatMessage(message);
+ // 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 game";
+ BroadcastChatMessage(message);
+ }
}
// Warnings about protocol version can be issued here
SendChatMessage(peer_id, L"# Server: WARNING: YOUR CLIENT IS OLD AND MAY WORK PROPERLY WITH THIS SERVER");
}
- /*
- Check HP, respawn if necessary
- */
- HandlePlayerHP(player, 0);
-
/*
Print out action
*/
}
Player *player = m_env->getPlayer(peer_id);
-
if(player == NULL){
infostream<<"Server::ProcessData(): Cancelling: "
"No player for peer_id="<<peer_id
<<std::endl;
return;
}
+
+ PlayerSAO *playersao = player->getPlayerSAO();
+ if(playersao == NULL){
+ infostream<<"Server::ProcessData(): Cancelling: "
+ "No player object for peer_id="<<peer_id
+ <<std::endl;
+ return;
+ }
+
if(command == TOSERVER_PLAYERPOS)
{
if(datasize < 2+12+12+4+4)
}
else if(command == TOSERVER_CLICK_ACTIVEOBJECT)
{
- if(datasize < 7)
- return;
-
- if((getPlayerPrivs(player) & PRIV_BUILD) == 0)
- return;
-
- /*
- length: 7
- [0] u16 command
- [2] u8 button (0=left, 1=right)
- [3] u16 id
- [5] u16 item
- */
- u8 button = readU8(&data[2]);
- u16 id = readS16(&data[3]);
- u16 item_i = readU16(&data[5]);
-
- ServerActiveObject *obj = m_env->getActiveObject(id);
-
- if(obj == NULL)
- {
- infostream<<"Server: CLICK_ACTIVEOBJECT: object not found"
- <<std::endl;
- return;
- }
-
- // Skip if object has been removed
- if(obj->m_removed)
- return;
-
- //TODO: Check that object is reasonably close
-
- // Get ServerRemotePlayer
- ServerRemotePlayer *srp = (ServerRemotePlayer*)player;
-
- // Update wielded item
- srp->wieldItem(item_i);
-
- // Left click, pick/punch
- if(button == 0)
- {
- actionstream<<player->getName()<<" punches object "
- <<obj->getId()<<std::endl;
-
- // Do stuff
- obj->punch(srp);
-
-#if 0
- /*
- Try creating inventory item
- */
- InventoryItem *item = obj->createPickedUpItem();
-
- if(item)
- {
- InventoryList *ilist = player->inventory.getList("main");
- if(ilist != NULL)
- {
- actionstream<<player->getName()<<" picked up "
- <<item->getName()<<std::endl;
- if(g_settings->getBool("creative_mode") == false)
- {
- // Skip if inventory has no free space
- if(ilist->roomForItem(item) == false)
- {
- infostream<<"Player inventory has no free space"<<std::endl;
- return;
- }
-
- // Add to inventory and send inventory
- ilist->addItem(item);
- UpdateCrafting(player->peer_id);
- SendInventory(player->peer_id);
- }
-
- // Remove object from environment
- obj->m_removed = true;
- }
- }
- else
- {
- /*
- Item cannot be picked up. Punch it instead.
- */
-
- actionstream<<player->getName()<<" punches object "
- <<obj->getId()<<std::endl;
-
- ToolItem *titem = NULL;
- std::string toolname = "";
-
- InventoryList *mlist = player->inventory.getList("main");
- if(mlist != NULL)
- {
- InventoryItem *item = mlist->getItem(item_i);
- if(item && (std::string)item->getName() == "ToolItem")
- {
- titem = (ToolItem*)item;
- toolname = titem->getToolName();
- }
- }
-
- v3f playerpos = player->getPosition();
- v3f objpos = obj->getBasePosition();
- v3f dir = (objpos - playerpos).normalize();
-
- u16 wear = obj->punch(toolname, dir, player->getName());
-
- if(titem)
- {
- bool weared_out = titem->addWear(wear);
- if(weared_out)
- mlist->deleteItem(item_i);
- SendInventory(player->peer_id);
- }
- }
-#endif
- }
- // Right click, do something with object
- if(button == 1)
- {
- actionstream<<player->getName()<<" right clicks object "
- <<obj->getId()<<std::endl;
-
- // Do stuff
- obj->rightClick(srp);
- }
-
- /*
- Update player state to client
- */
- SendPlayerHP(player);
- UpdateCrafting(player->peer_id);
- SendInventory(player->peer_id);
+ infostream<<"Server: CLICK_ACTIVEOBJECT not supported anymore"<<std::endl;
+ return;
}
else if(command == TOSERVER_GROUND_ACTION)
{
- if(datasize < 17)
- return;
- /*
- length: 17
- [0] u16 command
- [2] u8 action
- [3] v3s16 nodepos_undersurface
- [9] v3s16 nodepos_abovesurface
- [15] u16 item
- actions:
- 0: start digging
- 1: place block
- 2: stop digging (all parameters ignored)
- 3: digging completed
- */
- u8 action = readU8(&data[2]);
- v3s16 p_under;
- p_under.X = readS16(&data[3]);
- p_under.Y = readS16(&data[5]);
- p_under.Z = readS16(&data[7]);
- v3s16 p_over;
- p_over.X = readS16(&data[9]);
- p_over.Y = readS16(&data[11]);
- p_over.Z = readS16(&data[13]);
- u16 item_i = readU16(&data[15]);
-
- ServerRemotePlayer *srp = (ServerRemotePlayer*)player;
-
- /*
- Check that target is reasonably close
- */
- if(action != 2) // action 2 has always position (0,0,0)
- {
- v3f np_f = intToFloat(p_under, BS);
- float max_d = BS * 10; // Just some large enough value
- float d = srp->m_last_good_position.getDistanceFrom(np_f);
- if(d > max_d){
- actionstream<<"Player "<<player->getName()
- <<" tried to access node from too far: "
- <<"d="<<d<<", max_d="<<max_d
- <<". ignoring."<<std::endl;
- // Re-send block to revert change on client-side
- RemoteClient *client = getClient(peer_id);
- v3s16 blockpos = getNodeBlockPos(p_under);
- client->SetBlockNotSent(blockpos);
- // Do nothing else
- return;
- }
- }
-
- /*
- 0: start digging
- */
- if(action == 0)
- {
- /*
- NOTE: This can be used in the future to check if
- somebody is cheating, by checking the timing.
- */
- bool cannot_punch_node = false;
-
- MapNode n(CONTENT_IGNORE);
-
- try
- {
- n = m_env->getMap().getNode(p_under);
- }
- catch(InvalidPositionException &e)
- {
- infostream<<"Server: Not punching: Node not found."
- <<" Adding block to emerge queue."
- <<std::endl;
- m_emerge_queue.addBlock(peer_id,
- getNodeBlockPos(p_over), BLOCK_EMERGE_FLAG_FROMDISK);
- cannot_punch_node = true;
- }
-
- if(cannot_punch_node)
- return;
-
- /*
- Run script hook
- */
- scriptapi_environment_on_punchnode(m_lua, p_under, n, srp);
-
- } // action == 0
-
- /*
- 2: stop digging
- */
- else if(action == 2)
- {
-#if 0
- RemoteClient *client = getClient(peer_id);
- JMutexAutoLock digmutex(client->m_dig_mutex);
- client->m_dig_tool_item = -1;
-#endif
- }
-
- /*
- 3: Digging completed
- */
- else if(action == 3)
- {
- // Mandatory parameter; actually used for nothing
- core::map<v3s16, MapBlock*> modified_blocks;
-
- content_t material = CONTENT_IGNORE;
- u8 mineral = MINERAL_NONE;
-
- bool cannot_remove_node = false;
-
- MapNode n(CONTENT_IGNORE);
- try
- {
- n = m_env->getMap().getNode(p_under);
- // Get mineral
- mineral = n.getMineral(m_nodedef);
- // Get material at position
- material = n.getContent();
- // If not yet cancelled
- if(cannot_remove_node == false)
- {
- // If it's not diggable, do nothing
- if(m_nodedef->get(material).diggable == false)
- {
- infostream<<"Server: Not finishing digging: "
- <<"Node not diggable"
- <<std::endl;
- cannot_remove_node = true;
- }
- }
- // If not yet cancelled
- if(cannot_remove_node == false)
- {
- // Get node metadata
- NodeMetadata *meta = m_env->getMap().getNodeMetadata(p_under);
- if(meta && meta->nodeRemovalDisabled() == true)
- {
- infostream<<"Server: Not finishing digging: "
- <<"Node metadata disables removal"
- <<std::endl;
- cannot_remove_node = true;
- }
- }
- }
- catch(InvalidPositionException &e)
- {
- infostream<<"Server: Not finishing digging: Node not found."
- <<" Adding block to emerge queue."
- <<std::endl;
- m_emerge_queue.addBlock(peer_id,
- getNodeBlockPos(p_over), BLOCK_EMERGE_FLAG_FROMDISK);
- cannot_remove_node = true;
- }
-
- // Make sure the player is allowed to do it
- if((getPlayerPrivs(player) & PRIV_BUILD) == 0)
- {
- infostream<<"Player "<<player->getName()<<" cannot remove node"
- <<" because privileges are "<<getPlayerPrivs(player)
- <<std::endl;
- cannot_remove_node = true;
- }
-
- /*
- If node can't be removed, set block to be re-sent to
- client and quit.
- */
- if(cannot_remove_node)
- {
- infostream<<"Server: Not finishing digging."<<std::endl;
-
- // Client probably has wrong data.
- // Set block not sent, so that client will get
- // a valid one.
- infostream<<"Client "<<peer_id<<" tried to dig "
- <<"node; but node cannot be removed."
- <<" setting MapBlock not sent."<<std::endl;
- RemoteClient *client = getClient(peer_id);
- v3s16 blockpos = getNodeBlockPos(p_under);
- client->SetBlockNotSent(blockpos);
-
- return;
- }
-
- actionstream<<player->getName()<<" digs "<<PP(p_under)
- <<", gets material "<<(int)material<<", mineral "
- <<(int)mineral<<std::endl;
-
- /*
- Send the removal to all close-by players.
- - If other player is close, send REMOVENODE
- - Otherwise set blocks not sent
- */
- core::list<u16> far_players;
- sendRemoveNode(p_under, peer_id, &far_players, 30);
-
- /*
- Update and send inventory
- */
-
- if(g_settings->getBool("creative_mode") == false)
- {
- /*
- Wear out tool
- */
- InventoryList *mlist = player->inventory.getList("main");
- if(mlist != NULL)
- {
- InventoryItem *item = mlist->getItem(item_i);
- if(item && (std::string)item->getName() == "ToolItem")
- {
- ToolItem *titem = (ToolItem*)item;
- std::string toolname = titem->getToolName();
-
- // Get digging properties for material and tool
- ToolDiggingProperties tp =
- m_toolmgr->getDiggingProperties(toolname);
- DiggingProperties prop =
- getDiggingProperties(material, &tp, m_nodedef);
-
- if(prop.diggable == false)
- {
- infostream<<"Server: WARNING: Player digged"
- <<" with impossible material + tool"
- <<" combination"<<std::endl;
- }
-
- bool weared_out = titem->addWear(prop.wear);
-
- if(weared_out)
- {
- mlist->deleteItem(item_i);
- }
- }
- }
-
- /*
- Add dug item to inventory
- */
-
- InventoryItem *item = NULL;
-
- if(mineral != MINERAL_NONE)
- item = getDiggedMineralItem(mineral, this);
-
- // If not mineral
- if(item == NULL)
- {
- const std::string &dug_s = m_nodedef->get(material).dug_item;
- if(dug_s != "")
- {
- std::istringstream is(dug_s, std::ios::binary);
- item = InventoryItem::deSerialize(is, this);
- }
- }
-
- if(item != NULL)
- {
- // Add a item to inventory
- player->inventory.addItem("main", item);
-
- // Send inventory
- UpdateCrafting(player->peer_id);
- SendInventory(player->peer_id);
- }
-
- item = NULL;
-
- if(mineral != MINERAL_NONE)
- item = getDiggedMineralItem(mineral, this);
-
- // If not mineral
- if(item == NULL)
- {
- const std::string &extra_dug_s = m_nodedef->get(material).extra_dug_item;
- s32 extra_rarity = m_nodedef->get(material).extra_dug_item_rarity;
- if(extra_dug_s != "" && extra_rarity != 0
- && myrand() % extra_rarity == 0)
- {
- std::istringstream is(extra_dug_s, std::ios::binary);
- item = InventoryItem::deSerialize(is, this);
- }
- }
-
- if(item != NULL)
- {
- // Add a item to inventory
- player->inventory.addItem("main", item);
-
- // Send inventory
- UpdateCrafting(player->peer_id);
- SendInventory(player->peer_id);
- }
- }
-
- /*
- Remove the node
- (this takes some time so it is done after the quick stuff)
- */
- {
- MapEditEventIgnorer ign(&m_ignore_map_edit_events);
-
- m_env->getMap().removeNodeAndUpdate(p_under, modified_blocks);
- }
- /*
- Set blocks not sent to far players
- */
- for(core::list<u16>::Iterator
- i = far_players.begin();
- i != far_players.end(); i++)
- {
- u16 peer_id = *i;
- RemoteClient *client = getClient(peer_id);
- if(client==NULL)
- continue;
- client->SetBlocksNotSent(modified_blocks);
- }
-
- /*
- Run script hook
- */
- scriptapi_environment_on_dignode(m_lua, p_under, n, srp);
- }
-
- /*
- 1: place block
- */
- else if(action == 1)
- {
-
- InventoryList *ilist = player->inventory.getList("main");
- if(ilist == NULL)
- return;
-
- // Get item
- InventoryItem *item = ilist->getItem(item_i);
-
- // If there is no item, it is not possible to add it anywhere
- if(item == NULL)
- return;
-
- /*
- Handle material items
- */
- if(std::string("MaterialItem") == item->getName())
- {
- try{
- // Don't add a node if this is not a free space
- MapNode n2 = m_env->getMap().getNode(p_over);
- bool no_enough_privs =
- ((getPlayerPrivs(player) & PRIV_BUILD)==0);
- if(no_enough_privs)
- infostream<<"Player "<<player->getName()<<" cannot add node"
- <<" because privileges are "<<getPlayerPrivs(player)
- <<std::endl;
-
- if(m_nodedef->get(n2).buildable_to == false
- || no_enough_privs)
- {
- // Client probably has wrong data.
- // Set block not sent, so that client will get
- // a valid one.
- infostream<<"Client "<<peer_id<<" tried to place"
- <<" node in invalid position; setting"
- <<" MapBlock not sent."<<std::endl;
- RemoteClient *client = getClient(peer_id);
- v3s16 blockpos = getNodeBlockPos(p_over);
- client->SetBlockNotSent(blockpos);
- return;
- }
- }
- catch(InvalidPositionException &e)
- {
- infostream<<"Server: Ignoring ADDNODE: Node not found"
- <<" Adding block to emerge queue."
- <<std::endl;
- m_emerge_queue.addBlock(peer_id,
- getNodeBlockPos(p_over), BLOCK_EMERGE_FLAG_FROMDISK);
- return;
- }
-
- // Reset build time counter
- getClient(peer_id)->m_time_from_building = 0.0;
-
- // Create node data
- MaterialItem *mitem = (MaterialItem*)item;
- MapNode n;
- n.setContent(mitem->getMaterial());
-
- actionstream<<player->getName()<<" places material "
- <<(int)mitem->getMaterial()
- <<" at "<<PP(p_under)<<std::endl;
-
- // Calculate direction for wall mounted stuff
- if(m_nodedef->get(n).wall_mounted)
- n.param2 = packDir(p_under - p_over);
-
- // Calculate the direction for furnaces and chests and stuff
- if(m_nodedef->get(n).param_type == CPT_FACEDIR_SIMPLE)
- {
- v3f playerpos = player->getPosition();
- v3f blockpos = intToFloat(p_over, BS) - playerpos;
- blockpos = blockpos.normalize();
- n.param1 = 0;
- if (fabs(blockpos.X) > fabs(blockpos.Z)) {
- if (blockpos.X < 0)
- n.param1 = 3;
- else
- n.param1 = 1;
- } else {
- if (blockpos.Z < 0)
- n.param1 = 2;
- else
- n.param1 = 0;
- }
- }
-
- /*
- Send to all close-by players
- */
- core::list<u16> far_players;
- sendAddNode(p_over, n, 0, &far_players, 30);
-
- /*
- Handle inventory
- */
- InventoryList *ilist = player->inventory.getList("main");
- if(g_settings->getBool("creative_mode") == false && ilist)
- {
- // Remove from inventory and send inventory
- if(mitem->getCount() == 1)
- ilist->deleteItem(item_i);
- else
- mitem->remove(1);
- // Send inventory
- UpdateCrafting(peer_id);
- SendInventory(peer_id);
- }
-
- /*
- Add node.
-
- This takes some time so it is done after the quick stuff
- */
- core::map<v3s16, MapBlock*> modified_blocks;
- {
- MapEditEventIgnorer ign(&m_ignore_map_edit_events);
-
- std::string p_name = std::string(player->getName());
- m_env->getMap().addNodeAndUpdate(p_over, n, modified_blocks, p_name);
- }
- /*
- Set blocks not sent to far players
- */
- for(core::list<u16>::Iterator
- i = far_players.begin();
- i != far_players.end(); i++)
- {
- u16 peer_id = *i;
- RemoteClient *client = getClient(peer_id);
- if(client==NULL)
- continue;
- client->SetBlocksNotSent(modified_blocks);
- }
-
- /*
- Run script hook
- */
- scriptapi_environment_on_placenode(m_lua, p_over, n, srp);
-
- /*
- Calculate special events
- */
-
- /*if(n.d == LEGN(m_nodedef, "CONTENT_MESE"))
- {
- u32 count = 0;
- for(s16 z=-1; z<=1; z++)
- for(s16 y=-1; y<=1; y++)
- for(s16 x=-1; x<=1; x++)
- {
-
- }
- }*/
- }
- /*
- Place other item (not a block)
- */
- else
- {
- v3s16 blockpos = getNodeBlockPos(p_over);
-
- /*
- Check that the block is loaded so that the item
- can properly be added to the static list too
- */
- MapBlock *block = m_env->getMap().getBlockNoCreateNoEx(blockpos);
- if(block==NULL)
- {
- infostream<<"Error while placing object: "
- "block not found"<<std::endl;
- return;
- }
-
- /*
- If in creative mode, item dropping is disabled unless
- player has build privileges
- */
- if(g_settings->getBool("creative_mode") &&
- (getPlayerPrivs(player) & PRIV_BUILD) == 0)
- {
- infostream<<"Not allowing player to drop item: "
- "creative mode and no build privs"<<std::endl;
- return;
- }
-
- // Calculate a position for it
- v3f pos = intToFloat(p_over, BS);
- //pos.Y -= BS*0.45;
- /*pos.Y -= BS*0.25; // let it drop a bit
- // Randomize a bit
- pos.X += BS*0.2*(float)myrand_range(-1000,1000)/1000.0;
- pos.Z += BS*0.2*(float)myrand_range(-1000,1000)/1000.0;*/
-
- /*
- Create the object
- */
- ServerActiveObject *obj = item->createSAO(m_env, pos);
-
- if(obj == NULL)
- {
- infostream<<"WARNING: item resulted in NULL object, "
- <<"not placing onto map"
- <<std::endl;
- }
- else
- {
- actionstream<<player->getName()<<" places "<<item->getName()
- <<" at "<<PP(p_over)<<std::endl;
-
- // Add the object to the environment
- m_env->addActiveObject(obj);
-
- infostream<<"Placed object"<<std::endl;
-
- if(g_settings->getBool("creative_mode") == false)
- {
- // Delete the right amount of items from the slot
- u16 dropcount = item->getDropCount();
-
- // Delete item if all gone
- if(item->getCount() <= dropcount)
- {
- if(item->getCount() < dropcount)
- infostream<<"WARNING: Server: dropped more items"
- <<" than the slot contains"<<std::endl;
-
- InventoryList *ilist = player->inventory.getList("main");
- if(ilist)
- // Remove from inventory and send inventory
- ilist->deleteItem(item_i);
- }
- // Else decrement it
- else
- item->remove(dropcount);
-
- // Send inventory
- UpdateCrafting(peer_id);
- SendInventory(peer_id);
- }
- }
- }
-
- } // action == 1
+ infostream<<"Server: GROUND_ACTION not supported anymore"<<std::endl;
+ return;
- /*
- Catch invalid actions
- */
- else
- {
- infostream<<"WARNING: Server: Invalid action "
- <<action<<std::endl;
- }
}
-#if 0
else if(command == TOSERVER_RELEASE)
{
- if(datasize < 3)
- return;
- /*
- length: 3
- [0] u16 command
- [2] u8 button
- */
- infostream<<"TOSERVER_RELEASE ignored"<<std::endl;
+ infostream<<"Server: RELEASE not supported anymore"<<std::endl;
+ return;
}
-#endif
else if(command == TOSERVER_SIGNTEXT)
{
- infostream<<"Server: TOSERVER_SIGNTEXT not supported anymore"
+ infostream<<"Server: SIGNTEXT not supported anymore"
<<std::endl;
return;
}
else if(command == TOSERVER_SIGNNODETEXT)
{
- if((getPlayerPrivs(player) & PRIV_BUILD) == 0)
+ if(!checkPriv(player->getName(), "interact"))
return;
/*
u16 command
NodeMetadata *meta = m_env->getMap().getNodeMetadata(p);
if(!meta)
return;
- if(meta->typeId() != LEGN(m_nodedef, "CONTENT_SIGN_WALL"))
- return;
- SignNodeMetadata *signmeta = (SignNodeMetadata*)meta;
- signmeta->setText(text);
+
+ meta->setText(text);
- actionstream<<player->getName()<<" writes \""<<text<<"\" to sign "
+ actionstream<<player->getName()<<" writes \""<<text<<"\" to sign"
<<" at "<<PP(p)<<std::endl;
v3s16 blockpos = getNodeBlockPos(p);
}
else if(command == TOSERVER_INVENTORY_ACTION)
{
- /*// Ignore inventory changes if in creative mode
- if(g_settings->getBool("creative_mode") == true)
- {
- infostream<<"TOSERVER_INVENTORY_ACTION: ignoring in creative mode"
- <<std::endl;
- return;
- }*/
// Strip command and create a stream
std::string datastring((char*)&data[2], datasize-2);
- infostream<<"TOSERVER_INVENTORY_ACTION: data="<<datastring<<std::endl;
+ verbosestream<<"TOSERVER_INVENTORY_ACTION: data="<<datastring<<std::endl;
std::istringstream is(datastring, std::ios_base::binary);
// Create an action
InventoryAction *a = InventoryAction::deSerialize(is);
- if(a != NULL)
+ if(a == NULL)
{
- // Create context
- InventoryContext c;
- c.current_player = player;
+ infostream<<"TOSERVER_INVENTORY_ACTION: "
+ <<"InventoryAction::deSerialize() returned NULL"
+ <<std::endl;
+ return;
+ }
+
+ /*
+ Note: Always set inventory not sent, to repair cases
+ where the client made a bad prediction.
+ */
+
+ /*
+ Handle restrictions and special cases of the move action
+ */
+ if(a->getType() == IACTION_MOVE)
+ {
+ IMoveAction *ma = (IMoveAction*)a;
+
+ ma->from_inv.applyCurrentPlayer(player->getName());
+ ma->to_inv.applyCurrentPlayer(player->getName());
+
+ setInventoryModified(ma->from_inv);
+ setInventoryModified(ma->to_inv);
+
+ bool from_inv_is_current_player =
+ (ma->from_inv.type == InventoryLocation::PLAYER) &&
+ (ma->from_inv.name == player->getName());
+
+ bool to_inv_is_current_player =
+ (ma->to_inv.type == InventoryLocation::PLAYER) &&
+ (ma->to_inv.name == player->getName());
+
+ /*
+ Disable moving items out of craftpreview
+ */
+ if(ma->from_list == "craftpreview")
+ {
+ infostream<<"Ignoring IMoveAction from "
+ <<(ma->from_inv.dump())<<":"<<ma->from_list
+ <<" to "<<(ma->to_inv.dump())<<":"<<ma->to_list
+ <<" because src is "<<ma->from_list<<std::endl;
+ delete a;
+ return;
+ }
+
+ /*
+ Disable moving items into craftresult and craftpreview
+ */
+ if(ma->to_list == "craftpreview" || ma->to_list == "craftresult")
+ {
+ infostream<<"Ignoring IMoveAction from "
+ <<(ma->from_inv.dump())<<":"<<ma->from_list
+ <<" to "<<(ma->to_inv.dump())<<":"<<ma->to_list
+ <<" because dst is "<<ma->to_list<<std::endl;
+ delete a;
+ return;
+ }
+
+ // Disallow moving items in elsewhere than player's inventory
+ // if not allowed to interact
+ if(!checkPriv(player->getName(), "interact") &&
+ (!from_inv_is_current_player ||
+ !to_inv_is_current_player))
+ {
+ infostream<<"Cannot move outside of player's inventory: "
+ <<"No interact privilege"<<std::endl;
+ delete a;
+ return;
+ }
- /*
- Handle craftresult specially if not in creative mode
- */
- bool disable_action = false;
- if(a->getType() == IACTION_MOVE
- && g_settings->getBool("creative_mode") == false)
+ // If player is not an admin, check for ownership of src and dst
+ if(!checkPriv(player->getName(), "server"))
{
- IMoveAction *ma = (IMoveAction*)a;
- if(ma->to_inv == "current_player" &&
- ma->from_inv == "current_player")
- {
- InventoryList *rlist = player->inventory.getList("craftresult");
- assert(rlist);
- InventoryList *clist = player->inventory.getList("craft");
- assert(clist);
- InventoryList *mlist = player->inventory.getList("main");
- assert(mlist);
- /*
- Craftresult is no longer preview if something
- is moved into it
- */
- if(ma->to_list == "craftresult"
- && ma->from_list != "craftresult")
- {
- // If it currently is a preview, remove
- // its contents
- if(player->craftresult_is_preview)
- {
- rlist->deleteItem(0);
- }
- player->craftresult_is_preview = false;
- }
- /*
- Crafting takes place if this condition is true.
- */
- if(player->craftresult_is_preview &&
- ma->from_list == "craftresult")
- {
- player->craftresult_is_preview = false;
- clist->decrementMaterials(1);
-
- /* Print out action */
- InventoryList *list =
- player->inventory.getList("craftresult");
- assert(list);
- InventoryItem *item = list->getItem(0);
- std::string itemname = "NULL";
- if(item)
- itemname = item->getName();
- actionstream<<player->getName()<<" crafts "
- <<itemname<<std::endl;
- }
- /*
- If the craftresult is placed on itself, move it to
- main inventory instead of doing the action
- */
- if(ma->to_list == "craftresult"
- && ma->from_list == "craftresult")
- {
- disable_action = true;
-
- InventoryItem *item1 = rlist->changeItem(0, NULL);
- mlist->addItem(item1);
- }
- }
- // Disallow moving items if not allowed to build
- else if((getPlayerPrivs(player) & PRIV_BUILD) == 0)
- {
- disable_action = true;
- }
- // if it's a locking chest, only allow the owner or server admins to move items
- else if (ma->from_inv != "current_player" && (getPlayerPrivs(player) & PRIV_SERVER) == 0)
+ std::string owner_from = getInventoryOwner(ma->from_inv);
+ if(owner_from != "" && owner_from != player->getName())
{
- Strfnd fn(ma->from_inv);
- std::string id0 = fn.next(":");
- if(id0 == "nodemeta")
- {
- v3s16 p;
- p.X = stoi(fn.next(","));
- p.Y = stoi(fn.next(","));
- p.Z = stoi(fn.next(","));
- NodeMetadata *meta = m_env->getMap().getNodeMetadata(p);
- if(meta && meta->typeId() == LEGN(m_nodedef, "CONTENT_LOCKABLE_CHEST")) {
- LockingChestNodeMetadata *lcm = (LockingChestNodeMetadata*)meta;
- if (lcm->getOwner() != player->getName())
- disable_action = true;
- }
- }
+ infostream<<"WARNING: "<<player->getName()
+ <<" tried to access an inventory that"
+ <<" belongs to "<<owner_from<<std::endl;
+ delete a;
+ return;
}
- else if (ma->to_inv != "current_player" && (getPlayerPrivs(player) & PRIV_SERVER) == 0)
+
+ std::string owner_to = getInventoryOwner(ma->to_inv);
+ if(owner_to != "" && owner_to != player->getName())
{
- Strfnd fn(ma->to_inv);
- std::string id0 = fn.next(":");
- if(id0 == "nodemeta")
- {
- v3s16 p;
- p.X = stoi(fn.next(","));
- p.Y = stoi(fn.next(","));
- p.Z = stoi(fn.next(","));
- NodeMetadata *meta = m_env->getMap().getNodeMetadata(p);
- if(meta && meta->typeId() == LEGN(m_nodedef, "CONTENT_LOCKABLE_CHEST")) {
- LockingChestNodeMetadata *lcm = (LockingChestNodeMetadata*)meta;
- if (lcm->getOwner() != player->getName())
- disable_action = true;
- }
- }
+ infostream<<"WARNING: "<<player->getName()
+ <<" tried to access an inventory that"
+ <<" belongs to "<<owner_to<<std::endl;
+ delete a;
+ return;
}
}
+ }
+ /*
+ Handle restrictions and special cases of the drop action
+ */
+ else if(a->getType() == IACTION_DROP)
+ {
+ IDropAction *da = (IDropAction*)a;
- if(a->getType() == IACTION_DROP)
+ da->from_inv.applyCurrentPlayer(player->getName());
+
+ setInventoryModified(da->from_inv);
+
+ // Disallow dropping items if not allowed to interact
+ if(!checkPriv(player->getName(), "interact"))
{
- IDropAction *da = (IDropAction*)a;
- // Disallow dropping items if not allowed to build
- if((getPlayerPrivs(player) & PRIV_BUILD) == 0)
- {
- disable_action = true;
- }
- // if it's a locking chest, only allow the owner or server admins to drop items
- else if (da->from_inv != "current_player" && (getPlayerPrivs(player) & PRIV_SERVER) == 0)
+ delete a;
+ return;
+ }
+ // If player is not an admin, check for ownership
+ else if(!checkPriv(player->getName(), "server"))
+ {
+ std::string owner_from = getInventoryOwner(da->from_inv);
+ if(owner_from != "" && owner_from != player->getName())
{
- Strfnd fn(da->from_inv);
- std::string id0 = fn.next(":");
- if(id0 == "nodemeta")
- {
- v3s16 p;
- p.X = stoi(fn.next(","));
- p.Y = stoi(fn.next(","));
- p.Z = stoi(fn.next(","));
- NodeMetadata *meta = m_env->getMap().getNodeMetadata(p);
- if(meta && meta->typeId() == LEGN(m_nodedef, "CONTENT_LOCKABLE_CHEST")) {
- LockingChestNodeMetadata *lcm = (LockingChestNodeMetadata*)meta;
- if (lcm->getOwner() != player->getName())
- disable_action = true;
- }
- }
+ infostream<<"WARNING: "<<player->getName()
+ <<" tried to access an inventory that"
+ <<" belongs to "<<owner_from<<std::endl;
+ delete a;
+ return;
}
}
-
- if(disable_action == false)
+ }
+ /*
+ Handle restrictions and special cases of the craft action
+ */
+ else if(a->getType() == IACTION_CRAFT)
+ {
+ ICraftAction *ca = (ICraftAction*)a;
+
+ ca->craft_inv.applyCurrentPlayer(player->getName());
+
+ setInventoryModified(ca->craft_inv);
+
+ //bool craft_inv_is_current_player =
+ // (ca->craft_inv.type == InventoryLocation::PLAYER) &&
+ // (ca->craft_inv.name == player->getName());
+
+ // Disallow crafting if not allowed to interact
+ if(!checkPriv(player->getName(), "interact"))
{
- // Feed action to player inventory
- a->apply(&c, this, m_env);
+ infostream<<"Cannot craft: "
+ <<"No interact privilege"<<std::endl;
+ delete a;
+ return;
}
- else
+
+ // If player is not an admin, check for ownership of inventory
+ if(!checkPriv(player->getName(), "server"))
{
- // Send inventory
- UpdateCrafting(player->peer_id);
- SendInventory(player->peer_id);
+ std::string owner_craft = getInventoryOwner(ca->craft_inv);
+ if(owner_craft != "" && owner_craft != player->getName())
+ {
+ infostream<<"WARNING: "<<player->getName()
+ <<" tried to access an inventory that"
+ <<" belongs to "<<owner_craft<<std::endl;
+ delete a;
+ return;
+ }
}
-
- // Eat the action
- delete a;
- }
- else
- {
- infostream<<"TOSERVER_INVENTORY_ACTION: "
- <<"InventoryAction::deSerialize() returned NULL"
- <<std::endl;
}
+
+ // Do the action
+ a->apply(this, playersao, this);
+ // Eat the action
+ delete a;
}
else if(command == TOSERVER_CHAT_MESSAGE)
{
// Whether to send to other players
bool send_to_others = false;
- // Local player gets all privileges regardless of
- // what's set on their account.
- u64 privs = getPlayerPrivs(player);
-
// Parse commands
if(message[0] == L'/')
{
paramstring,
this,
m_env,
- player,
- privs);
+ player);
std::wstring reply(processServerCommand(ctx));
send_to_sender = ctx->flags & SEND_TO_SENDER;
}
else
{
- if(privs & PRIV_SHOUT)
- {
+ if(checkPriv(player->getName(), "shout")){
line += L"<";
line += name;
line += L"> ";
line += message;
send_to_others = true;
- }
- else
- {
+ } else {
line += L"Server: You are not allowed to shout";
send_to_sender = true;
}
if(sender_selected == false && send_to_others == false)
continue;
- SendChatMessage(client->peer_id, line);
+ SendChatMessage(client->peer_id, line);
+ }
+ }
+ }
+ else if(command == TOSERVER_DAMAGE)
+ {
+ std::string datastring((char*)&data[2], datasize-2);
+ std::istringstream is(datastring, std::ios_base::binary);
+ u8 damage = readU8(is);
+
+ actionstream<<player->getName()<<" damaged by "
+ <<(int)damage<<" hp at "<<PP(player->getPosition()/BS)
+ <<std::endl;
+
+ playersao->setHP(playersao->getHP() - damage);
+
+ if(playersao->getHP() == 0 && playersao->m_hp_not_sent)
+ DiePlayer(peer_id);
+
+ if(playersao->m_hp_not_sent)
+ SendPlayerHP(peer_id);
+ }
+ else if(command == TOSERVER_PASSWORD)
+ {
+ /*
+ [0] u16 TOSERVER_PASSWORD
+ [2] u8[28] old password
+ [30] u8[28] new password
+ */
+
+ if(datasize != 2+PASSWORD_SIZE*2)
+ return;
+ /*char password[PASSWORD_SIZE];
+ for(u32 i=0; i<PASSWORD_SIZE-1; i++)
+ password[i] = data[2+i];
+ password[PASSWORD_SIZE-1] = 0;*/
+ std::string oldpwd;
+ for(u32 i=0; i<PASSWORD_SIZE-1; i++)
+ {
+ char c = data[2+i];
+ if(c == 0)
+ break;
+ oldpwd += c;
+ }
+ std::string newpwd;
+ for(u32 i=0; i<PASSWORD_SIZE-1; i++)
+ {
+ char c = data[2+PASSWORD_SIZE+i];
+ if(c == 0)
+ break;
+ newpwd += c;
+ }
+
+ infostream<<"Server: Client requests a password change from "
+ <<"'"<<oldpwd<<"' to '"<<newpwd<<"'"<<std::endl;
+
+ std::string playername = player->getName();
+
+ std::string checkpwd;
+ scriptapi_get_auth(m_lua, playername, &checkpwd, NULL);
+
+ if(oldpwd != checkpwd)
+ {
+ infostream<<"Server: invalid old password"<<std::endl;
+ // Wrong old password supplied!!
+ SendChatMessage(peer_id, L"Invalid old password supplied. Password NOT changed.");
+ return;
+ }
+
+ bool success = scriptapi_set_password(m_lua, playername, newpwd);
+ if(success){
+ actionstream<<player->getName()<<" changes password"<<std::endl;
+ SendChatMessage(peer_id, L"Password change successful");
+ } else {
+ actionstream<<player->getName()<<" tries to change password but "
+ <<"it fails"<<std::endl;
+ SendChatMessage(peer_id, L"Password change failed or inavailable");
+ }
+ }
+ else if(command == TOSERVER_PLAYERITEM)
+ {
+ if (datasize < 2+2)
+ return;
+
+ u16 item = readU16(&data[2]);
+ playersao->setWieldIndex(item);
+ }
+ else if(command == TOSERVER_RESPAWN)
+ {
+ if(player->hp != 0)
+ return;
+
+ RespawnPlayer(peer_id);
+
+ actionstream<<player->getName()<<" respawns at "
+ <<PP(player->getPosition()/BS)<<std::endl;
+
+ // ActiveObject is added to environment in AsyncRunStep after
+ // the previous addition has been succesfully removed
+ }
+ else if(command == TOSERVER_REQUEST_MEDIA) {
+ std::string datastring((char*)&data[2], datasize-2);
+ std::istringstream is(datastring, std::ios_base::binary);
+
+ core::list<MediaRequest> tosend;
+ u16 numfiles = readU16(is);
+
+ infostream<<"Sending "<<numfiles<<" files to "
+ <<getPlayerName(peer_id)<<std::endl;
+ verbosestream<<"TOSERVER_REQUEST_MEDIA: "<<std::endl;
+
+ for(int i = 0; i < numfiles; i++) {
+ std::string name = deSerializeString(is);
+ tosend.push_back(MediaRequest(name));
+ verbosestream<<"TOSERVER_REQUEST_MEDIA: requested file "
+ <<name<<std::endl;
+ }
+
+ sendRequestedMedia(peer_id, tosend);
+
+ // Now the client should know about everything
+ // (definitions and files)
+ getClient(peer_id)->definitions_sent = true;
+ }
+ else if(command == TOSERVER_INTERACT)
+ {
+ std::string datastring((char*)&data[2], datasize-2);
+ std::istringstream is(datastring, std::ios_base::binary);
+
+ /*
+ [0] u16 command
+ [2] u8 action
+ [3] u16 item
+ [5] u32 length of the next item
+ [9] serialized PointedThing
+ actions:
+ 0: start digging (from undersurface) or use
+ 1: stop digging (all parameters ignored)
+ 2: digging completed
+ 3: place block or item (to abovesurface)
+ 4: use item
+ */
+ u8 action = readU8(is);
+ u16 item_i = readU16(is);
+ std::istringstream tmp_is(deSerializeLongString(is), std::ios::binary);
+ PointedThing pointed;
+ pointed.deSerialize(tmp_is);
+
+ verbosestream<<"TOSERVER_INTERACT: action="<<(int)action<<", item="
+ <<item_i<<", pointed="<<pointed.dump()<<std::endl;
+
+ if(player->hp == 0)
+ {
+ verbosestream<<"TOSERVER_INTERACT: "<<player->getName()
+ <<" tried to interact, but is dead!"<<std::endl;
+ return;
+ }
+
+ v3f player_pos = playersao->getLastGoodPosition();
+
+ // Update wielded item
+ playersao->setWieldIndex(item_i);
+
+ // Get pointed to node (undefined if not POINTEDTYPE_NODE)
+ v3s16 p_under = pointed.node_undersurface;
+ v3s16 p_above = pointed.node_abovesurface;
+
+ // Get pointed to object (NULL if not POINTEDTYPE_OBJECT)
+ ServerActiveObject *pointed_object = NULL;
+ if(pointed.type == POINTEDTHING_OBJECT)
+ {
+ pointed_object = m_env->getActiveObject(pointed.object_id);
+ if(pointed_object == NULL)
+ {
+ verbosestream<<"TOSERVER_INTERACT: "
+ "pointed object is NULL"<<std::endl;
+ return;
+ }
+
+ }
+
+ v3f pointed_pos_under = player_pos;
+ v3f pointed_pos_above = player_pos;
+ if(pointed.type == POINTEDTHING_NODE)
+ {
+ pointed_pos_under = intToFloat(p_under, BS);
+ pointed_pos_above = intToFloat(p_above, BS);
+ }
+ else if(pointed.type == POINTEDTHING_OBJECT)
+ {
+ pointed_pos_under = pointed_object->getBasePosition();
+ pointed_pos_above = pointed_pos_under;
+ }
+
+ /*
+ Check that target is reasonably close
+ (only when digging or placing things)
+ */
+ if(action == 0 || action == 2 || action == 3)
+ {
+ float d = player_pos.getDistanceFrom(pointed_pos_under);
+ float max_d = BS * 14; // Just some large enough value
+ if(d > max_d){
+ actionstream<<"Player "<<player->getName()
+ <<" tried to access "<<pointed.dump()
+ <<" from too far: "
+ <<"d="<<d<<", max_d="<<max_d
+ <<". ignoring."<<std::endl;
+ // Re-send block to revert change on client-side
+ RemoteClient *client = getClient(peer_id);
+ v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
+ client->SetBlockNotSent(blockpos);
+ // Do nothing else
+ return;
+ }
+ }
+
+ /*
+ Make sure the player is allowed to do it
+ */
+ if(!checkPriv(player->getName(), "interact"))
+ {
+ actionstream<<player->getName()<<" attempted to interact with "
+ <<pointed.dump()<<" without 'interact' privilege"
+ <<std::endl;
+ // Re-send block to revert change on client-side
+ RemoteClient *client = getClient(peer_id);
+ v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
+ client->SetBlockNotSent(blockpos);
+ return;
+ }
+
+ /*
+ 0: start digging or punch object
+ */
+ if(action == 0)
+ {
+ if(pointed.type == POINTEDTHING_NODE)
+ {
+ /*
+ NOTE: This can be used in the future to check if
+ somebody is cheating, by checking the timing.
+ */
+ MapNode n(CONTENT_IGNORE);
+ try
+ {
+ n = m_env->getMap().getNode(p_under);
+ }
+ catch(InvalidPositionException &e)
+ {
+ infostream<<"Server: Not punching: Node not found."
+ <<" Adding block to emerge queue."
+ <<std::endl;
+ m_emerge_queue.addBlock(peer_id,
+ getNodeBlockPos(p_above), BLOCK_EMERGE_FLAG_FROMDISK);
+ }
+ if(n.getContent() != CONTENT_IGNORE)
+ scriptapi_node_on_punch(m_lua, p_under, n, playersao);
+ }
+ else if(pointed.type == POINTEDTHING_OBJECT)
+ {
+ // Skip if object has been removed
+ if(pointed_object->m_removed)
+ return;
+
+ actionstream<<player->getName()<<" punches object "
+ <<pointed.object_id<<": "
+ <<pointed_object->getDescription()<<std::endl;
+
+ ItemStack punchitem = playersao->getWieldedItem();
+ ToolCapabilities toolcap =
+ punchitem.getToolCapabilities(m_itemdef);
+ v3f dir = (pointed_object->getBasePosition() -
+ (player->getPosition() + player->getEyeOffset())
+ ).normalize();
+ float time_from_last_punch =
+ playersao->resetTimeFromLastPunch();
+ pointed_object->punch(dir, &toolcap, playersao,
+ time_from_last_punch);
+ }
+
+ } // action == 0
+
+ /*
+ 1: stop digging
+ */
+ else if(action == 1)
+ {
+ } // action == 1
+
+ /*
+ 2: Digging completed
+ */
+ else if(action == 2)
+ {
+ // Only complete digging of nodes
+ if(pointed.type == POINTEDTHING_NODE)
+ {
+ MapNode n(CONTENT_IGNORE);
+ try
+ {
+ n = m_env->getMap().getNode(p_under);
+ }
+ catch(InvalidPositionException &e)
+ {
+ infostream<<"Server: Not finishing digging: Node not found."
+ <<" Adding block to emerge queue."
+ <<std::endl;
+ m_emerge_queue.addBlock(peer_id,
+ getNodeBlockPos(p_above), BLOCK_EMERGE_FLAG_FROMDISK);
+ }
+ if(n.getContent() != CONTENT_IGNORE)
+ scriptapi_node_on_dig(m_lua, p_under, n, playersao);
+
+ if (m_env->getMap().getNodeNoEx(p_under).getContent() != CONTENT_AIR)
+ {
+ // Re-send block to revert change on client-side
+ RemoteClient *client = getClient(peer_id);
+ v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
+ client->SetBlockNotSent(blockpos);
+ }
+ }
+ } // action == 2
+
+ /*
+ 3: place block or right-click object
+ */
+ else if(action == 3)
+ {
+ ItemStack item = playersao->getWieldedItem();
+
+ // Reset build time counter
+ if(pointed.type == POINTEDTHING_NODE &&
+ item.getDefinition(m_itemdef).type == ITEM_NODE)
+ getClient(peer_id)->m_time_from_building = 0.0;
+
+ if(pointed.type == POINTEDTHING_OBJECT)
+ {
+ // Right click object
+
+ // Skip if object has been removed
+ if(pointed_object->m_removed)
+ return;
+
+ actionstream<<player->getName()<<" right-clicks object "
+ <<pointed.object_id<<": "
+ <<pointed_object->getDescription()<<std::endl;
+
+ // Do stuff
+ pointed_object->rightClick(playersao);
}
- }
- }
- else if(command == TOSERVER_DAMAGE)
- {
- std::string datastring((char*)&data[2], datasize-2);
- std::istringstream is(datastring, std::ios_base::binary);
- u8 damage = readU8(is);
+ else if(scriptapi_item_on_place(m_lua,
+ item, playersao, pointed))
+ {
+ // Placement was handled in lua
+
+ // Apply returned ItemStack
+ if(g_settings->getBool("creative_mode") == false)
+ playersao->setWieldedItem(item);
+ }
+
+ } // action == 3
- if(g_settings->getBool("enable_damage"))
- {
- actionstream<<player->getName()<<" damaged by "
- <<(int)damage<<" hp at "<<PP(player->getPosition()/BS)
- <<std::endl;
-
- HandlePlayerHP(player, damage);
- }
- else
- {
- SendPlayerHP(player);
- }
- }
- else if(command == TOSERVER_PASSWORD)
- {
/*
- [0] u16 TOSERVER_PASSWORD
- [2] u8[28] old password
- [30] u8[28] new password
+ 4: use
*/
-
- if(datasize != 2+PASSWORD_SIZE*2)
- return;
- /*char password[PASSWORD_SIZE];
- for(u32 i=0; i<PASSWORD_SIZE-1; i++)
- password[i] = data[2+i];
- password[PASSWORD_SIZE-1] = 0;*/
- std::string oldpwd;
- for(u32 i=0; i<PASSWORD_SIZE-1; i++)
- {
- char c = data[2+i];
- if(c == 0)
- break;
- oldpwd += c;
- }
- std::string newpwd;
- for(u32 i=0; i<PASSWORD_SIZE-1; i++)
+ else if(action == 4)
{
- char c = data[2+PASSWORD_SIZE+i];
- if(c == 0)
- break;
- newpwd += c;
- }
-
- infostream<<"Server: Client requests a password change from "
- <<"'"<<oldpwd<<"' to '"<<newpwd<<"'"<<std::endl;
+ ItemStack item = playersao->getWieldedItem();
- std::string playername = player->getName();
+ actionstream<<player->getName()<<" uses "<<item.name
+ <<", pointing at "<<pointed.dump()<<std::endl;
- if(m_authmanager.exists(playername) == false)
- {
- infostream<<"Server: playername not found in authmanager"<<std::endl;
- // Wrong old password supplied!!
- SendChatMessage(peer_id, L"playername not found in authmanager");
- return;
- }
+ if(scriptapi_item_on_use(m_lua,
+ item, playersao, pointed))
+ {
+ // Apply returned ItemStack
+ if(g_settings->getBool("creative_mode") == false)
+ playersao->setWieldedItem(item);
+ }
- std::string checkpwd = m_authmanager.getPassword(playername);
+ } // action == 4
- if(oldpwd != checkpwd)
+ /*
+ Catch invalid actions
+ */
+ else
{
- infostream<<"Server: invalid old password"<<std::endl;
- // Wrong old password supplied!!
- SendChatMessage(peer_id, L"Invalid old password supplied. Password NOT changed.");
- return;
+ infostream<<"WARNING: Server: Invalid action "
+ <<action<<std::endl;
}
-
- actionstream<<player->getName()<<" changes password"<<std::endl;
-
- m_authmanager.setPassword(playername, newpwd);
-
- infostream<<"Server: password change successful for "<<playername
- <<std::endl;
- SendChatMessage(peer_id, L"Password change successful");
}
- else if(command == TOSERVER_PLAYERITEM)
+ else if(command == TOSERVER_REMOVED_SOUNDS)
{
- if (datasize < 2+2)
- return;
+ std::string datastring((char*)&data[2], datasize-2);
+ std::istringstream is(datastring, std::ios_base::binary);
- u16 item = readU16(&data[2]);
- player->wieldItem(item);
- SendWieldedItem(player);
- }
- else if(command == TOSERVER_RESPAWN)
- {
- if(player->hp != 0)
- return;
-
- RespawnPlayer(player);
-
- actionstream<<player->getName()<<" respawns at "
- <<PP(player->getPosition()/BS)<<std::endl;
+ int num = readU16(is);
+ for(int k=0; k<num; k++){
+ s32 id = readS32(is);
+ std::map<s32, ServerPlayingSound>::iterator i =
+ m_playing_sounds.find(id);
+ if(i == m_playing_sounds.end())
+ continue;
+ ServerPlayingSound &psound = i->second;
+ psound.clients.erase(peer_id);
+ if(psound.clients.size() == 0)
+ m_playing_sounds.erase(i++);
+ }
}
else
{
//infostream<<"Server::onMapEditEvent()"<<std::endl;
if(m_ignore_map_edit_events)
return;
+ if(m_ignore_map_edit_events_area.contains(event->getArea()))
+ return;
MapEditEvent *e = event->clone();
m_unsent_map_edit_queue.push_back(e);
}
-Inventory* Server::getInventory(InventoryContext *c, std::string id)
+Inventory* Server::getInventory(const InventoryLocation &loc)
{
- if(id == "current_player")
+ switch(loc.type){
+ case InventoryLocation::UNDEFINED:
+ {}
+ break;
+ case InventoryLocation::CURRENT_PLAYER:
+ {}
+ break;
+ case InventoryLocation::PLAYER:
{
- assert(c->current_player);
- return &(c->current_player->inventory);
+ Player *player = m_env->getPlayer(loc.name.c_str());
+ if(!player)
+ return NULL;
+ PlayerSAO *playersao = player->getPlayerSAO();
+ if(!playersao)
+ return NULL;
+ return playersao->getInventory();
}
-
- Strfnd fn(id);
- std::string id0 = fn.next(":");
-
- if(id0 == "nodemeta")
+ break;
+ case InventoryLocation::NODEMETA:
{
- v3s16 p;
- p.X = stoi(fn.next(","));
- p.Y = stoi(fn.next(","));
- p.Z = stoi(fn.next(","));
- NodeMetadata *meta = m_env->getMap().getNodeMetadata(p);
- if(meta)
- return meta->getInventory();
- infostream<<"nodemeta at ("<<p.X<<","<<p.Y<<","<<p.Z<<"): "
- <<"no metadata found"<<std::endl;
- return NULL;
+ NodeMetadata *meta = m_env->getMap().getNodeMetadata(loc.p);
+ if(!meta)
+ return NULL;
+ return meta->getInventory();
+ }
+ break;
+ default:
+ assert(0);
}
-
- infostream<<__FUNCTION_NAME<<": unknown id "<<id<<std::endl;
return NULL;
}
-void Server::inventoryModified(InventoryContext *c, std::string id)
+std::string Server::getInventoryOwner(const InventoryLocation &loc)
{
- if(id == "current_player")
+ switch(loc.type){
+ case InventoryLocation::UNDEFINED:
+ {}
+ break;
+ case InventoryLocation::CURRENT_PLAYER:
+ {}
+ break;
+ case InventoryLocation::PLAYER:
{
- assert(c->current_player);
- // Send inventory
- UpdateCrafting(c->current_player->peer_id);
- SendInventory(c->current_player->peer_id);
- return;
+ return loc.name;
}
-
- Strfnd fn(id);
- std::string id0 = fn.next(":");
-
- if(id0 == "nodemeta")
+ break;
+ case InventoryLocation::NODEMETA:
{
- v3s16 p;
- p.X = stoi(fn.next(","));
- p.Y = stoi(fn.next(","));
- p.Z = stoi(fn.next(","));
- v3s16 blockpos = getNodeBlockPos(p);
+ NodeMetadata *meta = m_env->getMap().getNodeMetadata(loc.p);
+ if(!meta)
+ return "";
+ return meta->getOwner();
+ }
+ break;
+ default:
+ assert(0);
+ }
+ return "";
+}
+void Server::setInventoryModified(const InventoryLocation &loc)
+{
+ switch(loc.type){
+ case InventoryLocation::UNDEFINED:
+ {}
+ break;
+ case InventoryLocation::PLAYER:
+ {
+ Player *player = m_env->getPlayer(loc.name.c_str());
+ if(!player)
+ return;
+ PlayerSAO *playersao = player->getPlayerSAO();
+ if(!playersao)
+ return;
+ playersao->m_inventory_not_sent = true;
+ playersao->m_wielded_item_not_sent = true;
+ }
+ break;
+ case InventoryLocation::NODEMETA:
+ {
+ v3s16 blockpos = getNodeBlockPos(loc.p);
- NodeMetadata *meta = m_env->getMap().getNodeMetadata(p);
+ NodeMetadata *meta = m_env->getMap().getNodeMetadata(loc.p);
if(meta)
meta->inventoryModified();
block->raiseModified(MOD_STATE_WRITE_NEEDED);
setBlockNotSent(blockpos);
-
- return;
}
-
- infostream<<__FUNCTION_NAME<<": unknown id "<<id<<std::endl;
+ break;
+ default:
+ assert(0);
+ }
}
core::list<PlayerInfo> Server::getPlayerInfo()
void Server::peerAdded(con::Peer *peer)
{
DSTACK(__FUNCTION_NAME);
- infostream<<"Server::peerAdded(): peer->id="
+ verbosestream<<"Server::peerAdded(): peer->id="
<<peer->id<<std::endl;
PeerChange c;
void Server::deletingPeer(con::Peer *peer, bool timeout)
{
DSTACK(__FUNCTION_NAME);
- infostream<<"Server::deletingPeer(): peer->id="
+ verbosestream<<"Server::deletingPeer(): peer->id="
<<peer->id<<", timeout="<<timeout<<std::endl;
PeerChange c;
con.Send(peer_id, 0, data, true);
}
-void Server::SendToolDef(con::Connection &con, u16 peer_id,
- IToolDefManager *tooldef)
+void Server::SendItemDef(con::Connection &con, u16 peer_id,
+ IItemDefManager *itemdef)
{
DSTACK(__FUNCTION_NAME);
std::ostringstream os(std::ios_base::binary);
/*
u16 command
u32 length of the next item
- serialized ToolDefManager
+ zlib-compressed serialized ItemDefManager
*/
- writeU16(os, TOCLIENT_TOOLDEF);
+ writeU16(os, TOCLIENT_ITEMDEF);
std::ostringstream tmp_os(std::ios::binary);
- tooldef->serialize(tmp_os);
- os<<serializeLongString(tmp_os.str());
+ itemdef->serialize(tmp_os);
+ std::ostringstream tmp_os2(std::ios::binary);
+ compressZlib(tmp_os.str(), tmp_os2);
+ os<<serializeLongString(tmp_os2.str());
// Make data buffer
std::string s = os.str();
- infostream<<"Server::SendToolDef(): Sending tool definitions: size="
- <<s.size()<<std::endl;
+ verbosestream<<"Server: Sending item definitions to id("<<peer_id
+ <<"): size="<<s.size()<<std::endl;
SharedBuffer<u8> data((u8*)s.c_str(), s.size());
// Send as reliable
con.Send(peer_id, 0, data, true);
/*
u16 command
u32 length of the next item
- serialized NodeDefManager
+ zlib-compressed serialized NodeDefManager
*/
writeU16(os, TOCLIENT_NODEDEF);
std::ostringstream tmp_os(std::ios::binary);
nodedef->serialize(tmp_os);
- os<<serializeLongString(tmp_os.str());
+ std::ostringstream tmp_os2(std::ios::binary);
+ compressZlib(tmp_os.str(), tmp_os2);
+ os<<serializeLongString(tmp_os2.str());
// Make data buffer
std::string s = os.str();
- infostream<<"Server::SendNodeDef(): Sending node definitions: size="
- <<s.size()<<std::endl;
+ verbosestream<<"Server: Sending node definitions to id("<<peer_id
+ <<"): size="<<s.size()<<std::endl;
SharedBuffer<u8> data((u8*)s.c_str(), s.size());
// Send as reliable
con.Send(peer_id, 0, data, true);
Non-static send methods
*/
-void Server::SendObjectData(float dtime)
-{
- DSTACK(__FUNCTION_NAME);
-
- core::map<v3s16, bool> stepped_blocks;
-
- for(core::map<u16, RemoteClient*>::Iterator
- i = m_clients.getIterator();
- i.atEnd() == false; i++)
- {
- u16 peer_id = i.getNode()->getKey();
- RemoteClient *client = i.getNode()->getValue();
- assert(client->peer_id == peer_id);
-
- if(client->serialization_version == SER_FMT_VER_INVALID)
- continue;
-
- client->SendObjectData(this, dtime, stepped_blocks);
- }
-}
-
-void Server::SendPlayerInfos()
-{
- DSTACK(__FUNCTION_NAME);
-
- //JMutexAutoLock envlock(m_env_mutex);
-
- // Get connected players
- core::list<Player*> players = m_env->getPlayers(true);
-
- u32 player_count = players.getSize();
- u32 datasize = 2+(2+PLAYERNAME_SIZE)*player_count;
-
- SharedBuffer<u8> data(datasize);
- writeU16(&data[0], TOCLIENT_PLAYERINFO);
-
- u32 start = 2;
- core::list<Player*>::Iterator i;
- for(i = players.begin();
- i != players.end(); i++)
- {
- Player *player = *i;
-
- /*infostream<<"Server sending player info for player with "
- "peer_id="<<player->peer_id<<std::endl;*/
-
- writeU16(&data[start], player->peer_id);
- memset((char*)&data[start+2], 0, PLAYERNAME_SIZE);
- snprintf((char*)&data[start+2], PLAYERNAME_SIZE, "%s", player->getName());
- start += 2+PLAYERNAME_SIZE;
- }
-
- //JMutexAutoLock conlock(m_con_mutex);
-
- // Send as reliable
- m_con.SendToAll(0, data, true);
-}
-
void Server::SendInventory(u16 peer_id)
{
DSTACK(__FUNCTION_NAME);
- Player* player = m_env->getPlayer(peer_id);
- assert(player);
+ PlayerSAO *playersao = getPlayerSAO(peer_id);
+ assert(playersao);
+
+ playersao->m_inventory_not_sent = false;
/*
Serialize it
*/
std::ostringstream os;
- //os.imbue(std::locale("C"));
-
- player->inventory.serialize(os);
+ playersao->getInventory()->serialize(os);
std::string s = os.str();
m_con.Send(peer_id, 0, data, true);
}
-std::string getWieldedItemString(const Player *player)
-{
- const InventoryItem *item = player->getWieldItem();
- if (item == NULL)
- return std::string("");
- std::ostringstream os(std::ios_base::binary);
- item->serialize(os);
- return os.str();
-}
-
-void Server::SendWieldedItem(const Player* player)
-{
- DSTACK(__FUNCTION_NAME);
-
- assert(player);
-
- std::ostringstream os(std::ios_base::binary);
-
- writeU16(os, TOCLIENT_PLAYERITEM);
- writeU16(os, 1);
- writeU16(os, player->peer_id);
- os<<serializeString(getWieldedItemString(player));
-
- // Make data buffer
- std::string s = os.str();
- SharedBuffer<u8> data((u8*)s.c_str(), s.size());
-
- m_con.SendToAll(0, data, true);
-}
-
-void Server::SendPlayerItems()
-{
- DSTACK(__FUNCTION_NAME);
-
- std::ostringstream os(std::ios_base::binary);
- core::list<Player *> players = m_env->getPlayers(true);
-
- writeU16(os, TOCLIENT_PLAYERITEM);
- writeU16(os, players.size());
- core::list<Player *>::Iterator i;
- for(i = players.begin(); i != players.end(); ++i)
- {
- Player *p = *i;
- writeU16(os, p->peer_id);
- os<<serializeString(getWieldedItemString(p));
- }
-
- // Make data buffer
- std::string s = os.str();
- SharedBuffer<u8> data((u8*)s.c_str(), s.size());
-
- m_con.SendToAll(0, data, true);
-}
-
void Server::SendChatMessage(u16 peer_id, const std::wstring &message)
{
DSTACK(__FUNCTION_NAME);
}
}
-void Server::SendPlayerHP(Player *player)
+void Server::SendPlayerHP(u16 peer_id)
{
- SendHP(m_con, player->peer_id, player->hp);
+ DSTACK(__FUNCTION_NAME);
+ PlayerSAO *playersao = getPlayerSAO(peer_id);
+ assert(playersao);
+ playersao->m_hp_not_sent = false;
+ SendHP(m_con, peer_id, playersao->getHP());
}
-void Server::SendMovePlayer(Player *player)
+void Server::SendMovePlayer(u16 peer_id)
{
DSTACK(__FUNCTION_NAME);
- std::ostringstream os(std::ios_base::binary);
+ Player *player = m_env->getPlayer(peer_id);
+ assert(player);
+ std::ostringstream os(std::ios_base::binary);
writeU16(os, TOCLIENT_MOVE_PLAYER);
writeV3F1000(os, player->getPosition());
writeF1000(os, player->getPitch());
v3f pos = player->getPosition();
f32 pitch = player->getPitch();
f32 yaw = player->getYaw();
- infostream<<"Server sending TOCLIENT_MOVE_PLAYER"
+ verbosestream<<"Server: Sending TOCLIENT_MOVE_PLAYER"
<<" pos=("<<pos.X<<","<<pos.Y<<","<<pos.Z<<")"
<<" pitch="<<pitch
<<" yaw="<<yaw
// Make data buffer
std::string s = os.str();
SharedBuffer<u8> data((u8*)s.c_str(), s.size());
- // Send as reliable
- m_con.Send(player->peer_id, 0, data, true);
+ // Send as reliable
+ m_con.Send(peer_id, 0, data, true);
+}
+
+void Server::SendPlayerPrivileges(u16 peer_id)
+{
+ Player *player = m_env->getPlayer(peer_id);
+ assert(player);
+ std::set<std::string> privs;
+ scriptapi_get_auth(m_lua, player->getName(), NULL, &privs);
+
+ std::ostringstream os(std::ios_base::binary);
+ writeU16(os, TOCLIENT_PRIVILEGES);
+ writeU16(os, privs.size());
+ for(std::set<std::string>::const_iterator i = privs.begin();
+ i != privs.end(); i++){
+ os<<serializeString(*i);
+ }
+
+ // Make data buffer
+ std::string s = os.str();
+ SharedBuffer<u8> data((u8*)s.c_str(), s.size());
+ // Send as reliable
+ m_con.Send(peer_id, 0, data, true);
+}
+
+s32 Server::playSound(const SimpleSoundSpec &spec,
+ const ServerSoundParams ¶ms)
+{
+ // Find out initial position of sound
+ bool pos_exists = false;
+ v3f pos = params.getPos(m_env, &pos_exists);
+ // If position is not found while it should be, cancel sound
+ if(pos_exists != (params.type != ServerSoundParams::SSP_LOCAL))
+ return -1;
+ // Filter destination clients
+ std::set<RemoteClient*> dst_clients;
+ if(params.to_player != "")
+ {
+ Player *player = m_env->getPlayer(params.to_player.c_str());
+ if(!player){
+ infostream<<"Server::playSound: Player \""<<params.to_player
+ <<"\" not found"<<std::endl;
+ return -1;
+ }
+ if(player->peer_id == PEER_ID_INEXISTENT){
+ infostream<<"Server::playSound: Player \""<<params.to_player
+ <<"\" not connected"<<std::endl;
+ return -1;
+ }
+ RemoteClient *client = getClient(player->peer_id);
+ dst_clients.insert(client);
+ }
+ else
+ {
+ for(core::map<u16, RemoteClient*>::Iterator
+ i = m_clients.getIterator(); i.atEnd() == false; i++)
+ {
+ RemoteClient *client = i.getNode()->getValue();
+ Player *player = m_env->getPlayer(client->peer_id);
+ if(!player)
+ continue;
+ if(pos_exists){
+ if(player->getPosition().getDistanceFrom(pos) >
+ params.max_hear_distance)
+ continue;
+ }
+ dst_clients.insert(client);
+ }
+ }
+ if(dst_clients.size() == 0)
+ return -1;
+ // Create the sound
+ s32 id = m_next_sound_id++;
+ // The sound will exist as a reference in m_playing_sounds
+ m_playing_sounds[id] = ServerPlayingSound();
+ ServerPlayingSound &psound = m_playing_sounds[id];
+ psound.params = params;
+ for(std::set<RemoteClient*>::iterator i = dst_clients.begin();
+ i != dst_clients.end(); i++)
+ psound.clients.insert((*i)->peer_id);
+ // Create packet
+ std::ostringstream os(std::ios_base::binary);
+ writeU16(os, TOCLIENT_PLAY_SOUND);
+ writeS32(os, id);
+ os<<serializeString(spec.name);
+ writeF1000(os, spec.gain * params.gain);
+ writeU8(os, params.type);
+ writeV3F1000(os, pos);
+ writeU16(os, params.object);
+ writeU8(os, params.loop);
+ // Make data buffer
+ std::string s = os.str();
+ SharedBuffer<u8> data((u8*)s.c_str(), s.size());
+ // Send
+ for(std::set<RemoteClient*>::iterator i = dst_clients.begin();
+ i != dst_clients.end(); i++){
+ // Send as reliable
+ m_con.Send((*i)->peer_id, 0, data, true);
+ }
+ return id;
+}
+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())
+ return;
+ ServerPlayingSound &psound = i->second;
+ // Create packet
+ std::ostringstream os(std::ios_base::binary);
+ writeU16(os, TOCLIENT_STOP_SOUND);
+ writeS32(os, handle);
+ // Make data buffer
+ std::string s = os.str();
+ SharedBuffer<u8> data((u8*)s.c_str(), s.size());
+ // Send
+ for(std::set<u16>::iterator i = psound.clients.begin();
+ i != psound.clients.end(); i++){
+ // Send as reliable
+ m_con.Send(*i, 0, data, true);
+ }
+ // Remove sound reference
+ m_playing_sounds.erase(i);
}
void Server::sendRemoveNode(v3s16 p, u16 ignore_id,
*/
std::ostringstream os(std::ios_base::binary);
- block->serialize(os, ver);
+ block->serialize(os, ver, false);
std::string s = os.str();
SharedBuffer<u8> blockdata((u8*)s.c_str(), s.size());
JMutexAutoLock envlock(m_env_mutex);
JMutexAutoLock conlock(m_con_mutex);
- //TimeTaker timer("Server::SendBlocks");
+ ScopeProfiler sp(g_profiler, "Server: sel and send blocks to clients");
core::array<PrioritySortedBlockTransfer> queue;
RemoteClient *client = i.getNode()->getValue();
assert(client->peer_id == i.getNode()->getKey());
+ // If definitions and textures have not been sent, don't
+ // send MapBlocks either
+ if(!client->definitions_sent)
+ continue;
+
total_sending += client->SendingCount();
if(client->serialization_version == SER_FMT_VER_INVALID)
}
}
-struct SendableTexture
-{
- std::string name;
- std::string path;
- std::string data;
-
- SendableTexture(const std::string &name_="", const std::string path_="",
- const std::string &data_=""):
- name(name_),
- path(path_),
- data(data_)
- {}
-};
-
-void Server::SendTextures(u16 peer_id)
+void Server::fillMediaCache()
{
DSTACK(__FUNCTION_NAME);
- infostream<<"Server::SendTextures(): Sending textures to client"<<std::endl;
-
- /* Read textures */
+ infostream<<"Server: Calculating media file checksums"<<std::endl;
- // Put 5kB in one bunch (this is not accurate)
- u32 bytes_per_bunch = 5000;
-
- core::array< core::list<SendableTexture> > texture_bunches;
- texture_bunches.push_back(core::list<SendableTexture>());
+ // Collect all media file paths
+ std::list<std::string> paths;
+ for(core::list<ModSpec>::Iterator i = m_mods.begin();
+ 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");
+ paths.push_back(mod.path + DIR_DELIM + "media");
+ }
- u32 texture_size_bunch_total = 0;
- core::list<ModSpec> mods = getMods(m_modspaths);
- for(core::list<ModSpec>::Iterator i = mods.begin();
- i != mods.end(); i++){
- ModSpec mod = *i;
- std::string texturepath = mod.path + DIR_DELIM + "textures";
- std::vector<fs::DirListNode> dirlist = fs::GetDirListing(texturepath);
+ // Collect media file information from paths into cache
+ for(std::list<std::string>::iterator i = paths.begin();
+ i != paths.end(); i++)
+ {
+ std::string mediapath = *i;
+ std::vector<fs::DirListNode> dirlist = fs::GetDirListing(mediapath);
for(u32 j=0; j<dirlist.size(); j++){
if(dirlist[j].dir) // Ignode dirs
continue;
- std::string tname = dirlist[j].name;
- std::string tpath = texturepath + DIR_DELIM + tname;
+ std::string filename = dirlist[j].name;
+ // If name contains illegal characters, ignore the file
+ if(!string_allowed(filename, TEXTURENAME_ALLOWED_CHARS)){
+ infostream<<"Server: ignoring illegal file name: \""
+ <<filename<<"\""<<std::endl;
+ continue;
+ }
+ // If name is not in a supported format, ignore it
+ const char *supported_ext[] = {
+ ".png", ".jpg", ".bmp", ".tga",
+ ".pcx", ".ppm", ".psd", ".wal", ".rgb",
+ ".ogg",
+ NULL
+ };
+ if(removeStringEnd(filename, supported_ext) == ""){
+ infostream<<"Server: ignoring unsupported file extension: \""
+ <<filename<<"\""<<std::endl;
+ continue;
+ }
+ // Ok, attempt to load the file and add to cache
+ std::string filepath = mediapath + DIR_DELIM + filename;
// Read data
- std::ifstream fis(tpath.c_str(), std::ios_base::binary);
+ std::ifstream fis(filepath.c_str(), std::ios_base::binary);
if(fis.good() == false){
- errorstream<<"Server::SendTextures(): Could not open \""
- <<tname<<"\" for reading"<<std::endl;
+ errorstream<<"Server::fillMediaCache(): Could not open \""
+ <<filename<<"\" for reading"<<std::endl;
continue;
}
std::ostringstream tmp_os(std::ios_base::binary);
fis.read(buf, 1024);
std::streamsize len = fis.gcount();
tmp_os.write(buf, len);
- texture_size_bunch_total += len;
if(fis.eof())
break;
if(!fis.good()){
}
}
if(bad){
- errorstream<<"Server::SendTextures(): Failed to read \""
- <<tname<<"\""<<std::endl;
+ errorstream<<"Server::fillMediaCache(): Failed to read \""
+ <<filename<<"\""<<std::endl;
+ continue;
+ }
+ if(tmp_os.str().length() == 0){
+ errorstream<<"Server::fillMediaCache(): Empty file \""
+ <<filepath<<"\""<<std::endl;
continue;
}
- /*infostream<<"Server::SendTextures(): Loaded \""
- <<tname<<"\""<<std::endl;*/
+
+ SHA1 sha1;
+ sha1.addBytes(tmp_os.str().c_str(), tmp_os.str().length());
+
+ unsigned char *digest = sha1.getDigest();
+ std::string sha1_base64 = base64_encode(digest, 20);
+ std::string sha1_hex = hex_encode((char*)digest, 20);
+ free(digest);
+
// Put in list
- texture_bunches[texture_bunches.size()-1].push_back(
- SendableTexture(tname, tpath, tmp_os.str()));
-
- // Start next bunch if got enough data
- if(texture_size_bunch_total >= bytes_per_bunch){
- texture_bunches.push_back(core::list<SendableTexture>());
- texture_size_bunch_total = 0;
+ this->m_media[filename] = MediaInfo(filepath, sha1_base64);
+ verbosestream<<"Server: "<<sha1_hex<<" is "<<filename<<std::endl;
+ }
+ }
+}
+
+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;
+
+ core::list<SendableMediaAnnouncement> file_announcements;
+
+ for(std::map<std::string, MediaInfo>::iterator i = m_media.begin();
+ i != m_media.end(); i++){
+ // Put in list
+ file_announcements.push_back(
+ SendableMediaAnnouncement(i->first, i->second.sha1_digest));
+ }
+
+ // Make packet
+ std::ostringstream os(std::ios_base::binary);
+
+ /*
+ u16 command
+ u32 number of files
+ for each texture {
+ u16 length of name
+ string name
+ u16 length of sha1_digest
+ string sha1_digest
+ }
+ */
+
+ writeU16(os, TOCLIENT_ANNOUNCE_MEDIA);
+ writeU16(os, file_announcements.size());
+
+ for(core::list<SendableMediaAnnouncement>::Iterator
+ j = file_announcements.begin();
+ j != file_announcements.end(); j++){
+ os<<serializeString(j->name);
+ os<<serializeString(j->sha1_digest);
+ }
+
+ // Make data buffer
+ std::string s = os.str();
+ SharedBuffer<u8> data((u8*)s.c_str(), s.size());
+
+ // Send as reliable
+ m_con.Send(peer_id, 0, data, true);
+
+}
+
+struct SendableMedia
+{
+ std::string name;
+ std::string path;
+ std::string data;
+
+ SendableMedia(const std::string &name_="", const std::string path_="",
+ const std::string &data_=""):
+ name(name_),
+ path(path_),
+ data(data_)
+ {}
+};
+
+void Server::sendRequestedMedia(u16 peer_id,
+ const core::list<MediaRequest> &tosend)
+{
+ DSTACK(__FUNCTION_NAME);
+
+ verbosestream<<"Server::sendRequestedMedia(): "
+ <<"Sending files to client"<<std::endl;
+
+ /* Read files */
+
+ // Put 5kB in one bunch (this is not accurate)
+ u32 bytes_per_bunch = 5000;
+
+ core::array< core::list<SendableMedia> > file_bunches;
+ file_bunches.push_back(core::list<SendableMedia>());
+
+ u32 file_size_bunch_total = 0;
+
+ for(core::list<MediaRequest>::ConstIterator i = tosend.begin();
+ i != tosend.end(); i++)
+ {
+ if(m_media.find(i->name) == m_media.end()){
+ errorstream<<"Server::sendRequestedMedia(): Client asked for "
+ <<"unknown file \""<<(i->name)<<"\""<<std::endl;
+ continue;
+ }
+
+ //TODO get path + name
+ std::string tpath = m_media[(*i).name].path;
+
+ // Read data
+ std::ifstream fis(tpath.c_str(), std::ios_base::binary);
+ if(fis.good() == false){
+ errorstream<<"Server::sendRequestedMedia(): Could not open \""
+ <<tpath<<"\" for reading"<<std::endl;
+ continue;
+ }
+ std::ostringstream tmp_os(std::ios_base::binary);
+ bool bad = false;
+ for(;;){
+ char buf[1024];
+ fis.read(buf, 1024);
+ std::streamsize len = fis.gcount();
+ tmp_os.write(buf, len);
+ file_size_bunch_total += len;
+ if(fis.eof())
+ break;
+ if(!fis.good()){
+ bad = true;
+ break;
}
}
+ if(bad){
+ errorstream<<"Server::sendRequestedMedia(): Failed to read \""
+ <<(*i).name<<"\""<<std::endl;
+ continue;
+ }
+ /*infostream<<"Server::sendRequestedMedia(): Loaded \""
+ <<tname<<"\""<<std::endl;*/
+ // Put in list
+ file_bunches[file_bunches.size()-1].push_back(
+ SendableMedia((*i).name, tpath, tmp_os.str()));
+
+ // Start next bunch if got enough data
+ if(file_size_bunch_total >= bytes_per_bunch){
+ file_bunches.push_back(core::list<SendableMedia>());
+ file_size_bunch_total = 0;
+ }
+
}
/* Create and send packets */
-
- u32 num_bunches = texture_bunches.size();
+
+ u32 num_bunches = file_bunches.size();
for(u32 i=0; i<num_bunches; i++)
{
+ std::ostringstream os(std::ios_base::binary);
+
/*
u16 command
u16 total number of texture bunches
u16 index of this bunch
- u32 number of textures in this bunch
- for each texture {
+ u32 number of files in this bunch
+ for each file {
u16 length of name
string name
u32 length of data
data
}
*/
- std::ostringstream os(std::ios_base::binary);
- writeU16(os, TOCLIENT_TEXTURES);
+ writeU16(os, TOCLIENT_MEDIA);
writeU16(os, num_bunches);
writeU16(os, i);
- writeU32(os, texture_bunches[i].size());
-
- for(core::list<SendableTexture>::Iterator
- j = texture_bunches[i].begin();
- j != texture_bunches[i].end(); j++){
+ writeU32(os, file_bunches[i].size());
+
+ for(core::list<SendableMedia>::Iterator
+ j = file_bunches[i].begin();
+ j != file_bunches[i].end(); j++){
os<<serializeString(j->name);
os<<serializeLongString(j->data);
}
-
+
// Make data buffer
std::string s = os.str();
- infostream<<"Server::SendTextures(): bunch "<<i<<"/"<<num_bunches
- <<" textures="<<texture_bunches[i].size()
+ verbosestream<<"Server::sendRequestedMedia(): bunch "
+ <<i<<"/"<<num_bunches
+ <<" files="<<file_bunches[i].size()
<<" size=" <<s.size()<<std::endl;
SharedBuffer<u8> data((u8*)s.c_str(), s.size());
// Send as reliable
Something random
*/
-void Server::HandlePlayerHP(Player *player, s16 damage)
+void Server::DiePlayer(u16 peer_id)
{
- if(player->hp > damage)
- {
- player->hp -= damage;
- SendPlayerHP(player);
- }
- else
- {
- infostream<<"Server::HandlePlayerHP(): Player "
- <<player->getName()<<" dies"<<std::endl;
-
- player->hp = 0;
-
- //TODO: Throw items around
-
- // Handle players that are not connected
- if(player->peer_id == PEER_ID_INEXISTENT){
- RespawnPlayer(player);
- return;
- }
+ DSTACK(__FUNCTION_NAME);
+
+ PlayerSAO *playersao = getPlayerSAO(peer_id);
+ assert(playersao);
- SendPlayerHP(player);
-
- RemoteClient *client = getClient(player->peer_id);
- if(client->net_proto_version >= 3)
- {
- SendDeathscreen(m_con, player->peer_id, false, v3f(0,0,0));
- }
- else
- {
- RespawnPlayer(player);
- }
- }
+ infostream<<"Server::DiePlayer(): Player "
+ <<playersao->getPlayer()->getName()
+ <<" dies"<<std::endl;
+
+ playersao->setHP(0);
+
+ // Trigger scripted stuff
+ scriptapi_on_dieplayer(m_lua, playersao);
+
+ SendPlayerHP(peer_id);
+ SendDeathscreen(m_con, peer_id, false, v3f(0,0,0));
}
-void Server::RespawnPlayer(Player *player)
+void Server::RespawnPlayer(u16 peer_id)
{
- player->hp = 20;
- ServerRemotePlayer *srp = (ServerRemotePlayer*)player;
- bool repositioned = scriptapi_on_respawnplayer(m_lua, srp);
+ DSTACK(__FUNCTION_NAME);
+
+ PlayerSAO *playersao = getPlayerSAO(peer_id);
+ assert(playersao);
+
+ infostream<<"Server::RespawnPlayer(): Player "
+ <<playersao->getPlayer()->getName()
+ <<" respawns"<<std::endl;
+
+ playersao->setHP(PLAYER_MAX_HP);
+
+ bool repositioned = scriptapi_on_respawnplayer(m_lua, playersao);
if(!repositioned){
v3f pos = findSpawnPos(m_env->getServerMap());
- player->setPosition(pos);
- srp->m_last_good_position = pos;
- srp->m_last_good_position_age = 0;
+ playersao->setPos(pos);
}
- SendMovePlayer(player);
- SendPlayerHP(player);
}
void Server::UpdateCrafting(u16 peer_id)
Player* player = m_env->getPlayer(peer_id);
assert(player);
- /*
- Calculate crafting stuff
- */
+ // Get a preview for crafting
+ ItemStack preview;
+ // No crafting in creative mode
if(g_settings->getBool("creative_mode") == false)
- {
- InventoryList *clist = player->inventory.getList("craft");
- InventoryList *rlist = player->inventory.getList("craftresult");
-
- if(rlist && rlist->getUsedSlots() == 0)
- player->craftresult_is_preview = true;
+ getCraftingResult(&player->inventory, preview, false, this);
- if(rlist && player->craftresult_is_preview)
- {
- rlist->clearItems();
- }
- if(clist && rlist && player->craftresult_is_preview)
- {
- // Get result of crafting grid
-
- std::vector<InventoryItem*> items;
- for(u16 i=0; i<9; i++){
- if(clist->getItem(i) == NULL)
- items.push_back(NULL);
- else
- items.push_back(clist->getItem(i)->clone());
- }
- CraftPointerInput cpi(3, items);
-
- InventoryItem *result = m_craftdef->getCraftResult(cpi, this);
- //InventoryItem *result = craft_get_result(items, this);
- if(result)
- rlist->addItem(result);
- }
-
- } // if creative_mode == false
+ // Put the new preview in
+ InventoryList *plist = player->inventory.getList("craftpreview");
+ assert(plist);
+ assert(plist->getSize() >= 1);
+ plist->changeItem(0, preview);
}
RemoteClient* Server::getClient(u16 peer_id)
return os.str();
}
+std::set<std::string> Server::getPlayerEffectivePrivs(const std::string &name)
+{
+ std::set<std::string> privs;
+ scriptapi_get_auth(m_lua, name, NULL, &privs);
+ return privs;
+}
+
+bool Server::checkPriv(const std::string &name, const std::string &priv)
+{
+ std::set<std::string> privs = getPlayerEffectivePrivs(name);
+ return (privs.count(priv) != 0);
+}
+
+void Server::reportPrivsModified(const std::string &name)
+{
+ if(name == ""){
+ for(core::map<u16, RemoteClient*>::Iterator
+ i = m_clients.getIterator();
+ i.atEnd() == false; i++){
+ RemoteClient *client = i.getNode()->getValue();
+ Player *player = m_env->getPlayer(client->peer_id);
+ reportPrivsModified(player->getName());
+ }
+ } else {
+ Player *player = m_env->getPlayer(name.c_str());
+ if(!player)
+ return;
+ SendPlayerPrivileges(player->peer_id);
+ PlayerSAO *sao = player->getPlayerSAO();
+ if(!sao)
+ return;
+ sao->updatePrivileges(
+ getPlayerEffectivePrivs(name),
+ isSingleplayer());
+ }
+}
+
// Saves g_settings to configpath given at initialization
void Server::saveConfig()
{
- if(m_configpath != "")
- g_settings->updateConfigFile(m_configpath.c_str());
+ if(m_path_config != "")
+ g_settings->updateConfigFile(m_path_config.c_str());
}
void Server::notifyPlayer(const char *name, const std::wstring msg)
// IGameDef interface
// Under envlock
-IToolDefManager* Server::getToolDefManager()
+IItemDefManager* Server::getItemDefManager()
{
- return m_toolmgr;
+ return m_itemdef;
}
INodeDefManager* Server::getNodeDefManager()
{
{
return m_nodedef->allocateDummy(name);
}
+ISoundManager* Server::getSoundManager()
+{
+ return &dummySoundManager;
+}
+MtEventManager* Server::getEventManager()
+{
+ return m_event;
+}
-IWritableToolDefManager* Server::getWritableToolDefManager()
+IWritableItemDefManager* Server::getWritableItemDefManager()
{
- return m_toolmgr;
+ return m_itemdef;
}
IWritableNodeDefManager* Server::getWritableNodeDefManager()
{
return m_craftdef;
}
+const ModSpec* Server::getModSpec(const std::string &modname)
+{
+ for(core::list<ModSpec>::Iterator i = m_mods.begin();
+ i != m_mods.end(); i++){
+ const ModSpec &mod = *i;
+ if(mod.name == modname)
+ return &mod;
+ }
+ return NULL;
+}
+std::string Server::getBuiltinLuaPath()
+{
+ return porting::path_share + DIR_DELIM + "builtin";
+}
+
v3f findSpawnPos(ServerMap &map)
{
//return v3f(50,50,50)*BS;
return intToFloat(nodepos, BS);
}
-Player *Server::emergePlayer(const char *name, const char *password, u16 peer_id)
+PlayerSAO* Server::emergePlayer(const char *name, u16 peer_id)
{
+ RemotePlayer *player = NULL;
+ bool newplayer = false;
+
/*
Try to get an existing player
*/
- Player *player = m_env->getPlayer(name);
- if(player != NULL)
- {
- // If player is already connected, cancel
- if(player->peer_id != 0)
- {
- infostream<<"emergePlayer(): Player already connected"<<std::endl;
- return NULL;
- }
+ player = static_cast<RemotePlayer*>(m_env->getPlayer(name));
- // Got one.
- player->peer_id = peer_id;
-
- // Reset inventory to creative if in creative mode
- if(g_settings->getBool("creative_mode"))
- {
- // Warning: double code below
- // Backup actual inventory
- player->inventory_backup = new Inventory();
- *(player->inventory_backup) = player->inventory;
- // Set creative inventory
- craft_set_creative_inventory(player, this);
- }
-
- return player;
+ // If player is already connected, cancel
+ if(player != NULL && player->peer_id != 0)
+ {
+ infostream<<"emergePlayer(): Player already connected"<<std::endl;
+ return NULL;
}
/*
" peer_id already exists"<<std::endl;
return NULL;
}
-
+
/*
- Create a new player
+ Create a new player if it doesn't exist yet
*/
+ if(player == NULL)
{
- // Add authentication stuff
- m_authmanager.add(name);
- m_authmanager.setPassword(name, password);
- m_authmanager.setPrivs(name,
- stringToPrivs(g_settings->get("default_privs")));
+ newplayer = true;
+ player = new RemotePlayer(this);
+ player->updateName(name);
/* Set player position */
-
infostream<<"Server: Finding spawn place for player \""
<<name<<"\""<<std::endl;
-
v3f pos = findSpawnPos(m_env->getServerMap());
-
- player = new ServerRemotePlayer(m_env, pos, peer_id, name);
+ player->setPosition(pos);
/* Add player to environment */
m_env->addPlayer(player);
+ }
- /* Run scripts */
- ServerRemotePlayer *srp = (ServerRemotePlayer*)player;
- scriptapi_on_newplayer(m_lua, srp);
+ /*
+ Create a new player active object
+ */
+ PlayerSAO *playersao = new PlayerSAO(m_env, player, peer_id,
+ getPlayerEffectivePrivs(player->getName()),
+ isSingleplayer());
- /* Add stuff to inventory */
- if(g_settings->getBool("creative_mode"))
- {
- // Warning: double code above
- // Backup actual inventory
- player->inventory_backup = new Inventory();
- *(player->inventory_backup) = player->inventory;
- // Set creative inventory
- craft_set_creative_inventory(player, this);
- }
+ /* Add object to environment */
+ m_env->addActiveObject(playersao);
- return player;
-
- } // create new player
+ /* Run scripts */
+ if(newplayer)
+ scriptapi_on_newplayer(m_lua, playersao);
+
+ scriptapi_on_joinplayer(m_lua, playersao);
+
+ /* Creative mode */
+ if(g_settings->getBool("creative_mode"))
+ playersao->createCreativeInventory();
+
+ return playersao;
}
void Server::handlePeerChange(PeerChange &c)
obj->m_known_by_count--;
}
+ /*
+ Clear references to playing sounds
+ */
+ for(std::map<s32, ServerPlayingSound>::iterator
+ i = m_playing_sounds.begin();
+ i != m_playing_sounds.end();)
+ {
+ ServerPlayingSound &psound = i->second;
+ psound.clients.erase(c.peer_id);
+ if(psound.clients.size() == 0)
+ m_playing_sounds.erase(i++);
+ else
+ i++;
+ }
+
+ Player *player = m_env->getPlayer(c.peer_id);
+
// Collect information about leaving in chat
std::wstring message;
{
- Player *player = m_env->getPlayer(c.peer_id);
if(player != NULL)
{
std::wstring name = narrow_to_wide(player->getName());
message += L" (timed out)";
}
}
-
- /*// Delete player
+
+ /* Run scripts and remove from environment */
{
- m_env->removePlayer(c.peer_id);
- }*/
+ if(player != NULL)
+ {
+ PlayerSAO *playersao = player->getPlayerSAO();
+ assert(playersao);
+
+ scriptapi_on_leaveplayer(m_lua, playersao);
+
+ playersao->disconnected();
+ }
+ }
- // Set player client disconnected
+ /*
+ Print out action
+ */
{
- Player *player = m_env->getPlayer(c.peer_id);
- if(player != NULL)
- player->peer_id = 0;
-
- /*
- Print out action
- */
if(player != NULL)
{
std::ostringstream os(std::ios_base::binary);
m_clients.remove(c.peer_id);
// Send player info to all remaining clients
- SendPlayerInfos();
+ //SendPlayerInfos();
// Send leave chat message to all remaining clients
- BroadcastChatMessage(message);
+ if(message.length() != 0)
+ BroadcastChatMessage(message);
} // PEER_REMOVED
else
{
PeerChange c = m_peer_change_queue.pop_front();
- infostream<<"Server: Handling peer change: "
+ verbosestream<<"Server: Handling peer change: "
<<"id="<<c.peer_id<<", timeout="<<c.timeout
<<std::endl;
}
}
-u64 Server::getPlayerPrivs(Player *player)
-{
- if(player==NULL)
- return 0;
- std::string playername = player->getName();
- // Local player gets all privileges regardless of
- // what's set on their account.
- if(g_settings->get("name") == playername)
- {
- return PRIV_ALL;
- }
- else
- {
- return getPlayerAuthPrivs(playername);
- }
-}
-
void dedicated_server_loop(Server &server, bool &kill)
{
DSTACK(__FUNCTION_NAME);
- infostream<<DTIME<<std::endl;
- infostream<<"========================"<<std::endl;
- infostream<<"Running dedicated server"<<std::endl;
- infostream<<"========================"<<std::endl;
- infostream<<std::endl;
+ verbosestream<<"dedicated_server_loop()"<<std::endl;
IntervalLimiter m_profiler_interval;
for(;;)
{
+ float steplen = g_settings->getFloat("dedicated_server_step");
// This is kind of a hack but can be done like this
// because server.step() is very light
{
ScopeProfiler sp(g_profiler, "dedicated server sleep");
- sleep_ms(30);
+ sleep_ms((int)(steplen*1000.0));
}
- server.step(0.030);
+ server.step(steplen);
if(server.getShutdownRequested() || kill)
{
- infostream<<DTIME<<" dedicated_server_loop(): Quitting."<<std::endl;
+ infostream<<"Dedicated server quitting"<<std::endl;
break;
}
g_settings->getFloat("profiler_print_interval");
if(profiler_print_interval != 0)
{
- if(m_profiler_interval.step(0.030, profiler_print_interval))
+ if(m_profiler_interval.step(steplen, profiler_print_interval))
{
infostream<<"Profiler:"<<std::endl;
g_profiler->print(infostream);
g_profiler->clear();
}
}
-
- /*
- Player info
- */
- static int counter = 0;
- counter--;
- if(counter <= 0)
- {
- counter = 10;
-
- core::list<PlayerInfo> list = server.getPlayerInfo();
- core::list<PlayerInfo>::Iterator i;
- static u32 sum_old = 0;
- u32 sum = PIChecksum(list);
- if(sum != sum_old)
- {
- infostream<<DTIME<<"Player info:"<<std::endl;
- for(i=list.begin(); i!=list.end(); i++)
- {
- i->PrintLine(&infostream);
- }
- }
- sum_old = sum;
- }
}
}