/* * Connection.h, part of VCMI engine * * Authors: listed in file AUTHORS in main folder * * License: GNU General Public License v2.0 or later * Full text of license available in license.txt file, in main folder * */ #pragma once #include //XXX this is in namespace std if you want w/o use typeinfo.h? #include #include #include #include #include #include #include #include "ConstTransitivePtr.h" #include "CCreatureSet.h" //for CStackInstance #include "CObjectHandler.h" //for CArmedInstance #include "mapping/CCampaignHandler.h" //for CCampaignState #include "rmg/CMapGenerator.h" // for CMapGenOptions const ui32 version = 739; class CConnection; class CGObjectInstance; class CStackInstance; class CGameState; class CCreature; class LibClasses; class CHero; struct CPack; extern DLL_LINKAGE LibClasses * VLC; namespace mpl = boost::mpl; const std::string SAVEGAME_MAGIC = "VCMISVG"; namespace boost { namespace asio { namespace ip { class tcp; } class io_service; template class stream_socket_service; template class basic_stream_socket; template class socket_acceptor_service; template class basic_socket_acceptor; } class mutex; } enum SerializationLvl { Wrong=0, Boolean, Primitive, Array, Pointer, Enum, Serializable, BooleanVector }; struct TypeComparer { bool operator()(const std::type_info *a, const std::type_info *b) const { return a->before(*b); } }; class DLL_LINKAGE CTypeList { typedef std::multimap TTypeMap; TTypeMap types; public: CTypeList(); ui16 registerType(const std::type_info *type); template ui16 registerType(const T * t = NULL) { return registerType(getTypeInfo(t)); } ui16 getTypeID(const std::type_info *type); template ui16 getTypeID(const T * t = NULL) { return getTypeID(getTypeInfo(t)); } template const std::type_info * getTypeInfo(const T * t = NULL) { if(t) return &typeid(*t); else return &typeid(T); } }; extern DLL_LINKAGE CTypeList typeList; template struct SaveBoolean { static void invoke(Ser &s, const bool &data) { s.saveBoolean(data); } }; template struct LoadBoolean { static void invoke(Ser &s, bool &data) { s.loadBoolean(data); } }; template struct SaveBooleanVector { static void invoke(Ser &s, const std::vector &data) { s.saveBooleanVector(data); } }; template struct LoadBooleanVector { static void invoke(Ser &s, std::vector &data) { s.loadBooleanVector(data); } }; template struct SavePrimitive { static void invoke(Ser &s, const T &data) { s.savePrimitive(data); } }; template struct SaveSerializable { static void invoke(Ser &s, const T &data) { s.saveSerializable(data); } }; template struct SaveEnum { static void invoke(Ser &s, const T &data) { s.saveEnum(data); } }; template struct LoadEnum { static void invoke(Ser &s, T &data) { s.loadEnum(data); } }; template struct LoadPrimitive { static void invoke(Ser &s, T &data) { s.loadPrimitive(data); } }; template struct SavePointer { static void invoke(Ser &s, const T &data) { s.savePointer(data); } }; template struct LoadPointer { static void invoke(Ser &s, T &data) { s.loadPointer(data); } }; template struct SaveArray { static void invoke(Ser &s, const T &data) { s.saveArray(data); } }; template struct LoadArray { static void invoke(Ser &s, T &data) { s.loadArray(data); } }; template struct LoadSerializable { static void invoke(Ser &s, T &data) { s.loadSerializable(data); } }; template struct SaveWrong { static void invoke(Ser &s, const T &data) { throw std::runtime_error("Wrong save serialization call!"); } }; template struct LoadWrong { static void invoke(Ser &s, const T &data) { throw std::runtime_error("Wrong load serialization call!"); } }; template struct SerializationLevel { typedef mpl::integral_c_tag tag; typedef typename mpl::eval_if< boost::is_same, mpl::int_, //else typename mpl::eval_if< boost::is_same >, mpl::int_, //else typename mpl::eval_if< boost::is_fundamental, mpl::int_, //else typename mpl::eval_if< boost::is_enum, mpl::int_, //else typename mpl::eval_if< boost::is_class, mpl::int_, //else typename mpl::eval_if< boost::is_array, mpl::int_, //else typename mpl::eval_if< boost::is_pointer, mpl::int_, //else typename mpl::eval_if< boost::is_enum, mpl::int_, //else mpl::int_ > > > > > > > >::type type; static const int value = SerializationLevel::type::value; }; template struct VectorisedObjectInfo { const std::vector > *vector; //pointer to the appropriate vector const U T::*idPtr; //pointer to the field representing the position in the vector VectorisedObjectInfo(const std::vector< ConstTransitivePtr > *Vector, const U T::*IdPtr) :vector(Vector), idPtr(IdPtr) { } }; template si32 idToNumber(const T &t, typename boost::enable_if >::type * dummy = 0) { return t; } template NT idToNumber(const BaseForID &t) { return t.getNum(); } /// Class which is responsible for storing and loading data. class DLL_LINKAGE CSerializer { public: typedef std::map TTypeVecMap; TTypeVecMap vectors; //entry must be a pointer to vector containing pointers to the objects of key type bool smartVectorMembersSerialization; bool sendStackInstanceByIds; CSerializer(); ~CSerializer(); virtual void reportState(CLogger * out){}; template void registerVectoredType(const std::vector *Vector, const U T::*IdPtr) { vectors[&typeid(T)] = VectorisedObjectInfo(Vector, IdPtr); } template void registerVectoredType(const std::vector > *Vector, const U T::*IdPtr) { vectors[&typeid(T)] = VectorisedObjectInfo(Vector, IdPtr); } template const VectorisedObjectInfo *getVectorisedTypeInfo() { const std::type_info *myType = NULL; // // if(boost::is_base_of::value) //ugly workaround to support also types derived from CGObjectInstance -> if we encounter one, treat it aas CGObj.. // myType = &typeid(CGObjectInstance); // else myType = &typeid(T); TTypeVecMap::iterator i = vectors.find(myType); if(i == vectors.end()) return NULL; else { assert(!i->second.empty()); assert(i->second.type() == typeid(VectorisedObjectInfo)); VectorisedObjectInfo *ret = &(boost::any_cast&>(i->second)); return ret; } } template T* getVectorItemFromId(const VectorisedObjectInfo &oInfo, U id) const { /* if(id < 0) return NULL;*/ si32 idAsNumber = idToNumber(id); assert(oInfo.vector); assert(static_cast(oInfo.vector->size()) > idAsNumber); return const_cast((*oInfo.vector)[idAsNumber].get()); } template U getIdFromVectorItem(const VectorisedObjectInfo &oInfo, const T* obj) const { if(!obj) return U(-1); return obj->*oInfo.idPtr; } void addStdVecItems(CGameState *gs, LibClasses *lib = VLC); }; class DLL_LINKAGE CSaverBase : public virtual CSerializer { }; class CBasicPointerSaver { public: virtual void savePtr(CSaverBase &ar, const void *data) const =0; virtual ~CBasicPointerSaver(){} }; template class CPointerSaver : public CBasicPointerSaver { public: void savePtr(CSaverBase &ar, const void *data) const { Serializer &s = static_cast(ar); const T *ptr = static_cast(data); //T is most derived known type, it's time to call actual serialize const_cast(*ptr).serialize(s,version); } }; template //metafunction returning CGObjectInstance if T is its derivate or T elsewise struct VectorisedTypeFor { typedef typename //if mpl::eval_if, mpl::identity, //else mpl::identity >::type type; }; template struct VectorizedIDType { typedef typename //if mpl::eval_if, mpl::identity, //else if mpl::eval_if, mpl::identity, //else if mpl::eval_if, mpl::identity, //else if mpl::eval_if, mpl::identity, //else mpl::identity > > > >::type type; }; template struct VariantVisitorSaver : boost::static_visitor<> { Handler &h; VariantVisitorSaver(Handler &H):h(H) { } template void operator()(const T &t) { h << t; } }; template struct SaveIfStackInstance { static bool invoke(Ser &s, const T &data) { return false; } }; template struct SaveIfStackInstance { static bool invoke(Ser &s, const CStackInstance* const &data) { assert(data->armyObj); SlotID slot; if(data->getNodeType() == CBonusSystemNode::COMMANDER) slot = SlotID::COMMANDER_SLOT_PLACEHOLDER; else slot = data->armyObj->findStack(data); assert(slot != SlotID()); s << data->armyObj << slot; return true; } }; template struct LoadIfStackInstance { static bool invoke(Ser &s, T &data) { return false; } }; template struct LoadIfStackInstance { static bool invoke(Ser &s, CStackInstance* &data) { CArmedInstance *armedObj; SlotID slot; s >> armedObj >> slot; if(slot != SlotID::COMMANDER_SLOT_PLACEHOLDER) { assert(armedObj->hasStackAtSlot(slot)); data = armedObj->stacks[slot]; } else { auto hero = dynamic_cast(armedObj); assert(hero); assert(hero->commander); data = hero->commander; } return true; } }; /// The class which manages saving objects. template class DLL_LINKAGE COSer : public CSaverBase { public: bool saving; std::map savers; // typeID => CPointerSaver std::map savedPointers; bool smartPointerSerialization; COSer() { saving=true; smartPointerSerialization = true; } ~COSer() { std::map::iterator iter; for(iter = savers.begin(); iter != savers.end(); iter++) delete iter->second; } template void registerType(const T * t=NULL) { ui16 ID = typeList.registerType(t); savers[ID] = new CPointerSaver,T>; } Serializer * This() { return static_cast(this); } template Serializer & operator<<(const T &t) { this->This()->save(t); return * this->This(); } template COSer & operator&(const T & t) { return * this->This() << t; } int write(const void * data, unsigned size); template void savePrimitive(const T &data) { this->This()->write(&data,sizeof(data)); } template void savePointer(const T &data) { //write if pointer is not NULL ui8 hlp = (data!=NULL); *this << hlp; //if pointer is NULL then we don't need anything more... if(!hlp) return; if(smartVectorMembersSerialization) { typedef typename boost::remove_const::type>::type TObjectType; typedef typename VectorisedTypeFor::type VType; typedef typename VectorizedIDType::type IDType; if(const auto *info = getVectorisedTypeInfo()) { IDType id = getIdFromVectorItem(*info, data); *this << id; if(id != IDType(-1)) //vector id is enough return; } } if(sendStackInstanceByIds) { const bool gotSaved = SaveIfStackInstance::invoke(*This(), data); if(gotSaved) return; } if(smartPointerSerialization) { std::map::iterator i = savedPointers.find(data); if(i != savedPointers.end()) { //this pointer has been already serialized - write only it's id *this << i->second; return; } //give id to this pointer ui32 pid = (ui32)savedPointers.size(); savedPointers[data] = pid; *this << pid; } //write type identifier ui16 tid = typeList.getTypeID(data); *this << tid; This()->savePointerHlp(tid, data); } //that part of ptr serialization was extracted to allow customization of its behavior in derived classes template void savePointerHlp(ui16 tid, const T &data) { if(!tid) *this << *data; //if type is unregistered simply write all data in a standard way else savers[tid]->savePtr(*this,data); //call serializer specific for our real type } template void saveArray(const T &data) { ui32 size = ARRAY_COUNT(data); for(ui32 i=0; i < size; i++) *this << data[i]; } template void save(const T &data) { typedef //if typename mpl::eval_if< mpl::equal_to,mpl::int_ >, mpl::identity >, //else if typename mpl::eval_if< mpl::equal_to,mpl::int_ >, mpl::identity >, //else if typename mpl::eval_if< mpl::equal_to,mpl::int_ >, mpl::identity >, //else if typename mpl::eval_if,mpl::int_ >, mpl::identity >, //else if typename mpl::eval_if,mpl::int_ >, mpl::identity >, //else if typename mpl::eval_if,mpl::int_ >, mpl::identity >, //else if typename mpl::eval_if,mpl::int_ >, mpl::identity >, //else mpl::identity > > > > > > > >::type typex; typex::invoke(* this->This(), data); } template void saveSerializable(const T &data) { const_cast(data).serialize(*this,version); } template void saveSerializable(const shared_ptr &data) { T *internalPtr = data.get(); *this << internalPtr; } template void saveSerializable(const unique_ptr &data) { T *internalPtr = data.get(); *this << internalPtr; } template void saveSerializable(const std::vector &data) { ui32 length = data.size(); *this << length; for(ui32 i=0;i void saveSerializable(const std::set &data) { std::set &d = const_cast &>(data); ui32 length = d.size(); *this << length; for(typename std::set::iterator i=d.begin();i!=d.end();i++) *this << *i; } template void saveSerializable(const boost::unordered_set &data) { boost::unordered_set &d = const_cast &>(data); ui32 length = d.size(); *this << length; for(typename boost::unordered_set::iterator i=d.begin();i!=d.end();i++) *this << *i; } template void saveSerializable(const std::list &data) { std::list &d = const_cast &>(data); ui32 length = d.size(); *this << length; for(typename std::list::iterator i=d.begin();i!=d.end();i++) *this << *i; } void saveSerializable(const std::string &data) { *this << ui32(data.length()); this->This()->write(data.c_str(),data.size()); } template void saveSerializable(const std::pair &data) { *this << data.first << data.second; } template void saveSerializable(const std::map &data) { *this << ui32(data.size()); for(typename std::map::const_iterator i=data.begin();i!=data.end();i++) *this << i->first << i->second; } template void saveSerializable(const boost::variant &data) { si32 which = data.which(); *this << which; VariantVisitorSaver visitor(*this->This()); boost::apply_visitor(visitor, data); } template void saveSerializable(const boost::optional &data) { if(data) { *this << (ui8)1; *this << *data; } else { *this << (ui8)0; } } template void saveEnum(const E &data) { si32 writ = static_cast(data); *this << writ; } void saveBoolean(const bool & data) { ui8 writ = static_cast(data); *this << writ; } void saveBooleanVector(const std::vector & data) { std::vector convData; std::copy(data.begin(), data.end(), std::back_inserter(convData)); saveSerializable(convData); } }; class DLL_LINKAGE CLoaderBase : public virtual CSerializer {}; class CBasicPointerLoader { public: virtual void loadPtr(CLoaderBase &ar, void *data, ui32 pid) const =0; //data is pointer to the ACTUAL POINTER virtual ~CBasicPointerLoader(){} }; template class CPointerLoader : public CBasicPointerLoader { public: void loadPtr(CLoaderBase &ar, void *data, ui32 pid) const //data is pointer to the ACTUAL POINTER { Serializer &s = static_cast(ar); T *&ptr = *static_cast(data); //create new object under pointer typedef typename boost::remove_pointer::type npT; ptr = new npT; s.ptrAllocated(ptr, pid); //T is most derived known type, it's time to call actual serialize ptr->serialize(s,version); } }; /// The class which manages loading of objects. template class DLL_LINKAGE CISer : public CLoaderBase { public: bool saving; std::map loaders; // typeID => CPointerSaver ui32 fileVersion; bool reverseEndianess; //if source has different endianess than us, we reverse bytes std::map loadedPointers; bool smartPointerSerialization; CISer() { saving = false; fileVersion = 0; smartPointerSerialization = true; reverseEndianess = false; } ~CISer() { std::map::iterator iter; for(iter = loaders.begin(); iter != loaders.end(); iter++) delete iter->second; } template void registerType(const T * t=NULL) { ui16 ID = typeList.registerType(t); loaders[ID] = new CPointerLoader,T>; } Serializer * This() { return static_cast(this); } template Serializer & operator>>(T &t) { this->This()->load(t); return * this->This(); } template CISer & operator&(T & t) { return * this->This() >> t; } int write(const void * data, unsigned size); template void load(T &data) { typedef //if typename mpl::eval_if< mpl::equal_to,mpl::int_ >, mpl::identity >, //else if typename mpl::eval_if< mpl::equal_to,mpl::int_ >, mpl::identity >, //else if typename mpl::eval_if< mpl::equal_to,mpl::int_ >, mpl::identity >, //else if typename mpl::eval_if,mpl::int_ >, mpl::identity >, //else if typename mpl::eval_if,mpl::int_ >, mpl::identity >, //else if typename mpl::eval_if,mpl::int_ >, mpl::identity >, //else if typename mpl::eval_if,mpl::int_ >, mpl::identity >, //else mpl::identity > > > > > > > >::type typex; typex::invoke(* this->This(), data); } template void loadPrimitive(T &data) { if(0) //for testing #989 { this->This()->read(&data,sizeof(data)); } else { unsigned length = sizeof(data); char* dataPtr = (char*)&data; this->This()->read(dataPtr,length); if(reverseEndianess) std::reverse(dataPtr, dataPtr + length); } } template void loadSerializableBySerializeCall(T &data) { ////that const cast is evil because it allows to implicitly overwrite const objects when deserializing typedef typename boost::remove_const::type nonConstT; nonConstT &hlp = const_cast(data); hlp.serialize(*this,fileVersion); //data.serialize(*this,myVersion); } template void loadSerializable(T &data) { loadSerializableBySerializeCall(data); } template void loadArray(T &data) { ui32 size = ARRAY_COUNT(data); for(ui32 i = 0; i < size; i++) *this >> data[i]; } template void loadPointer(T &data) { ui8 hlp; *this >> hlp; if(!hlp) { data = NULL; return; } if(smartVectorMembersSerialization) { typedef typename boost::remove_const::type>::type TObjectType; //eg: const CGHeroInstance * => CGHeroInstance typedef typename VectorisedTypeFor::type VType; //eg: CGHeroInstance -> CGobjectInstance typedef typename VectorizedIDType::type IDType; if(const auto *info = getVectorisedTypeInfo()) { IDType id; *this >> id; if(id != IDType(-1)) { data = static_cast(getVectorItemFromId(*info, id)); return; } } } if(sendStackInstanceByIds) { bool gotLoaded = LoadIfStackInstance::invoke(*This(), data); if(gotLoaded) return; } ui32 pid = 0xffffffff; //pointer id (or maybe rather pointee id) if(smartPointerSerialization) { *this >> pid; //get the id std::map::iterator i = loadedPointers.find(pid); //lookup if(i != loadedPointers.end()) { //we already got this pointer data = static_cast(i->second); return; } } //get type id ui16 tid; *this >> tid; This()->loadPointerHlp(tid, data, pid); } //that part of ptr deserialization was extracted to allow customization of its behavior in derived classes template void loadPointerHlp( ui16 tid, T & data, ui32 pid ) { if(!tid) { typedef typename boost::remove_pointer::type npT; typedef typename boost::remove_const::type ncpT; data = new ncpT; ptrAllocated(data, pid); *this >> *data; } else { loaders[tid]->loadPtr(*this,&data, pid); } } template void ptrAllocated(const T *ptr, ui32 pid) { if(smartPointerSerialization && pid != 0xffffffff) loadedPointers[pid] = (void*)ptr; //add loaded pointer to our lookup map; cast is to avoid errors with const T* pt } #define READ_CHECK_U32(x) \ ui32 length; \ *this >> length; \ if(length > 500000) \ { \ logGlobal->warnStream() << "Warning: very big length: " << length;\ reportState(logGlobal); \ }; template void loadSerializable(shared_ptr &data) { T *internalPtr; *this >> internalPtr; data.reset(internalPtr); } template void loadSerializable(unique_ptr &data) { T *internalPtr; *this >> internalPtr; data.reset(internalPtr); } template void loadSerializable(std::vector &data) { READ_CHECK_U32(length); data.resize(length); for(ui32 i=0;i> data[i]; } template void loadSerializable(std::set &data) { READ_CHECK_U32(length); T ins; for(ui32 i=0;i> ins; data.insert(ins); } } template void loadSerializable(boost::unordered_set &data) { READ_CHECK_U32(length); T ins; for(ui32 i=0;i> ins; data.insert(ins); } } template void loadSerializable(std::list &data) { READ_CHECK_U32(length); T ins; for(ui32 i=0;i> ins; data.push_back(ins); } } template void loadSerializable(std::pair &data) { *this >> data.first >> data.second; } template void loadSerializable(std::map &data) { READ_CHECK_U32(length); T1 t; for(ui32 i=0;i> t; *this >> data[t]; } } void loadSerializable(std::string &data) { READ_CHECK_U32(length); data.resize(length); this->This()->read((void*)data.c_str(),length); } template void loadSerializable(boost::variant &data) { si32 which; *this >> which; if(which == 0) { T0 obj; *this >> obj; data = obj; } else if(which == 1) { T1 obj; *this >> obj; data = obj; } else assert(0); //TODO write more if needed, general solution would be much longer } template void loadSerializable(boost::optional & data) { ui8 present; *this >> present; if(present) { T t; *this >> t; data = t; } else { data = boost::optional(); } } void loadSerializable(CStackInstance *&s) { if(sendStackInstanceByIds) { CArmedInstance *armed; SlotID slot; *this >> armed >> slot; assert(armed->hasStackAtSlot(slot)); s = armed->stacks[slot]; } else loadSerializableBySerializeCall(s); } template void loadEnum(E &data) { si32 read; *this >> read; data = static_cast(read); } void loadBoolean(bool &data) { ui8 read; *this >> read; data = static_cast(read); } void loadBooleanVector(std::vector & data) { std::vector convData; loadSerializable(convData); std::copy(convData.begin(), convData.end(), std::back_inserter(data)); } }; class DLL_LINKAGE CSaveFile : public COSer { void dummyMagicFunction() { *this << std::string("This function makes stuff working."); } public: std::string fName; unique_ptr sfile; CSaveFile(const std::string &fname); //throws! ~CSaveFile(); int write(const void * data, unsigned size); void openNextFile(const std::string &fname); //throws! void clear(); void reportState(CLogger * out); void putMagicBytes(const std::string &text); }; class DLL_LINKAGE CLoadFile : public CISer { void dummyMagicFunction() { std::string dummy = "This function makes stuff working."; *this >> dummy; } public: std::string fName; unique_ptr sfile; CLoadFile(const std::string &fname, int minimalVersion = version); //throws! ~CLoadFile(); int read(const void * data, unsigned size); //throws! void openNextFile(const std::string &fname, int minimalVersion); //throws! void clear(); void reportState(CLogger * out); void checkMagicBytes(const std::string &text); }; class DLL_LINKAGE CLoadIntegrityValidator : public CISer { public: unique_ptr primaryFile, controlFile; bool foundDesync; CLoadIntegrityValidator(const std::string &primaryFileName, const std::string &controlFileName, int minimalVersion = version); //throws! int read(const void * data, unsigned size); //throws! void checkMagicBytes(const std::string &text); unique_ptr decay(); //returns primary file. CLoadIntegrityValidator stops being usable anymore }; typedef boost::asio::basic_stream_socket < boost::asio::ip::tcp , boost::asio::stream_socket_service > TSocket; typedef boost::asio::basic_socket_acceptor > TAcceptor; class DLL_LINKAGE CConnection :public CISer, public COSer { //CGameState *gs; CConnection(void); void init(); void reportState(CLogger * out); public: boost::mutex *rmx, *wmx; // read/write mutexes TSocket * socket; bool logging; bool connected; bool myEndianess, contactEndianess; //true if little endian, if endianess is different we'll have to revert received multi-byte vars boost::asio::io_service *io_service; std::string name; //who uses this connection int connectionID; boost::thread *handler; bool receivedStop, sendStop; CConnection(std::string host, std::string port, std::string Name); CConnection(TAcceptor * acceptor, boost::asio::io_service *Io_service, std::string Name); CConnection(TSocket * Socket, std::string Name); //use immediately after accepting connection into socket int write(const void * data, unsigned size); int read(void * data, unsigned size); void close(); bool isOpen() const; template CConnection &operator&(const T&); virtual ~CConnection(void); CPack *retreivePack(); //gets from server next pack (allocates it with new) void sendPackToServer(const CPack &pack, PlayerColor player, ui32 requestID); void disableStackSendingByID(); void enableStackSendingByID(); void disableSmartPointerSerialization(); void enableSmartPointerSerializatoin(); void prepareForSendingHeroes(); //disables sending vectorised, enables smart pointer serialization, clears saved/loaded ptr cache void enterPregameConnectionMode(); }; DLL_LINKAGE std::ostream &operator<<(std::ostream &str, const CConnection &cpc); template class CApplier { public: std::map apps; ~CApplier() { typename std::map::iterator iter; for(iter = apps.begin(); iter != apps.end(); iter++) delete iter->second; } template void registerType(const U * t=NULL) { ui16 ID = typeList.registerType(t); apps[ID] = T::getApplier(t); } };