Lots of little changes to libretroshare. Improvements mainly focused

on configuration storage and loading:
 * Improved Configuration Manager (almost finished)
 * Mutex protections for Configuration system
 * added Configuration storage to p3ConnectMgr.
 * added Configuration storage to p3MsgService.
 * bugfixes in p3GeneralConfig.
 * Added Config Save notification where necessary.
 * added safe FinalConfigSave before exit().
 * added RsPeerNetItem + RsPeerStunItem (serialiser)
 * reordered startup for correct config loading.
 * enabled Loading of certs in AuthXPGP.
 * move sockaddr_clear() to util/rsnet.h
 * switched p3MsgService sendMessage checking to pqiMonitor syste,.
 * corrected pqiarchive saving of PeerIds.
 * added setNetworkMode() & setVisState() to p3ConnectMgr.
 * added Mutex protection to p3ranking.



git-svn-id: http://svn.code.sf.net/p/retroshare/code/trunk@336 b45a01b8-16f6-495d-af2f-9b41ad6348cc
This commit is contained in:
drbob 2008-02-07 16:18:34 +00:00
parent 2c69fd7eaf
commit 806b8285f2
36 changed files with 1712 additions and 599 deletions

View File

@ -7,7 +7,9 @@ RS_TOP_DIR = ..
include $(RS_TOP_DIR)/scripts/config.mk
###############################################################
BASE_OBJ = pqi_base.o pqidebug.o pqisecurity.o pqinetwork.o
BASE_OBJ = pqidebug.o pqisecurity.o pqinetwork.o
#pqi_base.o
LOOP_OBJ = pqiloopback.o
STREAM_OBJ = pqistreamer.o pqiarchive.o pqibin.o
MGR_OBJ = pqimonitor.o p3dhtmgr.o p3connmgr.o p3cfgmgr.o p3authmgr.o

View File

@ -248,7 +248,7 @@ SSL_CTX *AuthXPGP::getCTX()
return sslctx;
}
int AuthXPGP::setConfigDirectories(const char *cdir, const char *ndir)
int AuthXPGP::setConfigDirectories(std::string configfile, std::string neighdir)
{
#ifdef AUTHXPGP_DEBUG
std::cerr << "AuthXPGP::setConfigDirectories()";
@ -256,8 +256,8 @@ int AuthXPGP::setConfigDirectories(const char *cdir, const char *ndir)
#endif
xpgpMtx.lock(); /***** LOCK *****/
mCertDir = cdir;
mNeighDir = ndir;
mCertConfigFile = configfile;
mNeighDir = neighdir;
xpgpMtx.unlock(); /**** UNLOCK ****/
return 1;
@ -1510,6 +1510,21 @@ std::list<std::string> getXPGPsigners(XPGP *cert)
return signers;
}
// other fns
std::string getCertName(XPGP *xpgp)
{
std::string name = xpgp->name;
// strip out bad chars.
for(int i = 0; i < (signed) name.length(); i++)
{
if ((name[i] == '/') || (name[i] == ' ') || (name[i] == '=') ||
(name[i] == '\\') || (name[i] == '\t') || (name[i] == '\n'))
{
name[i] = '_';
}
}
return name;
}
/********** SSL ERROR STUFF ******************************************/
@ -1563,39 +1578,69 @@ int printSSLError(SSL *ssl, int retval, int err, unsigned long err2,
}
#if 0
/***************************** OLD STORAGE of CERTS *************************
* We will retain the existing CERT storage format for the moment....
* This will enable the existing certs to be loaded in.
*
* BUT Save will change the format - removing the options from
* the configuration file. This will mean that we can catch NEW/OLD formats.
*
* We only want to load old format ONCE. as we'll use it to get
* the list of existing friends...
*
*
*
*/
int AuthXPGP::saveCertificates(const char *fname)
bool AuthXPGP::saveCertificates()
{
// construct file name.
//
// create the file in memory - hash + sign.
// write out data to a file.
std::string neighdir = certdir + "/" + neighbourdir + "/";
std::string configname = certdir + "/";
configname += fname;
xpgpMtx.lock(); /***** LOCK *****/
std::string configfile = mCertConfigFile;
std::string neighdir = mNeighDir;
xpgpMtx.unlock(); /**** UNLOCK ****/
std::map<std::string, std::string>::iterator mit;
std::string conftxt;
std::string empty("");
unsigned int i;
std::list<cert *>::iterator it;
for(it = peercerts.begin(); it != peercerts.end(); it++)
#ifdef AUTHXPGP_DEBUG
std::cerr << "AuthXPGP::saveCertificates()";
std::cerr << std::endl;
#endif
xpgpMtx.lock(); /***** LOCK *****/
/* iterate through both lists */
std::map<std::string, xpgpcert *>::iterator it;
for(it = mCerts.begin(); it != mCerts.end(); it++)
{
std::string neighfile = neighdir + getCertName(*it) + ".pqi";
savecertificate((*it), neighfile.c_str());
conftxt += "CERT ";
conftxt += getCertName(*it);
conftxt += "\n";
conftxt += (*it) -> Hash();
conftxt += "\n";
std::cerr << std::endl;
if (it->second->trustLvl > TRUST_SIGN_BASIC)
{
XPGP *xpgp = it->second->certificate;
std::string hash;
std::string neighfile = neighdir + getCertName(xpgp) + ".pqi";
if (saveXPGPToFile(xpgp, neighfile, hash))
{
conftxt += "CERT ";
conftxt += getCertName(xpgp);
conftxt += "\n";
conftxt += hash;
conftxt += "\n";
std::cerr << std::endl;
}
}
}
// now work out signature of it all. This relies on the
// EVP library of openSSL..... We are going to use signing
// for the moment.
@ -1631,37 +1676,75 @@ int AuthXPGP::saveCertificates(const char *fname)
}
std::cerr << std::endl;
FILE *cfd = fopen(configname.c_str(), "wb");
FILE *cfd = fopen(configfile.c_str(), "wb");
int wrec;
if (1 != (wrec = fwrite(conftxt.c_str(), conftxt.length(), 1, cfd)))
{
std::cerr << "Error writing: " << configname << std::endl;
std::cerr << "Error writing: " << configfile << std::endl;
std::cerr << "Wrote: " << wrec << "/" << 1 << " Records" << std::endl;
}
EVP_MD_CTX_destroy(mdctx);
fclose(cfd);
return 1;
xpgpMtx.unlock(); /**** UNLOCK ****/
return true;
}
int sslroot::loadCertificates(const char *conf_fname)
/******
* Special version for backwards compatibility
*
* has two extra parameters.
* bool oldFormat & std::map<std::string, std::string> keyvaluemap
*
* We'll leave these in for the next couple of months...
* so that old versions will automatically be converted to the
* new format!
*
*/
bool AuthXPGP::loadCertificates()
{
// open the configuration file.
//
// read in CERT + Hash.
bool oldFormat;
std::map<std::string, std::string> keyValueMap;
// construct file name.
//
// create the file in memory - hash + sign.
// write out data to a file.
return loadCertificates(oldFormat, keyValueMap);
}
std::string neighdir = certdir + "/" + neighbourdir + "/";
std::string configname = certdir + "/";
configname += conf_fname;
/*********************
* NOTE no need to Lock here. locking handled in ProcessXPGP()
*/
static const uint32_t OPT_LEN = 16;
static const uint32_t VAL_LEN = 1000;
// save name for later save attempts.
certfile = conf_fname;
bool AuthXPGP::loadCertificates(bool &oldFormat, std::map<std::string, std::string> &keyValueMap)
{
/*******************************************
* open the configuration file.
* read in CERT + Hash.
*
* construct file name.
* create the file in memory - hash + sign.
* write out data to a file.
*****************************************/
xpgpMtx.lock(); /***** LOCK *****/
std::string configfile = mCertConfigFile;
std::string neighdir = mNeighDir;
xpgpMtx.unlock(); /**** UNLOCK ****/
/* add on the slash */
if (neighdir != "")
{
neighdir += "/";
}
oldFormat = false;
std::string conftxt;
@ -1671,12 +1754,12 @@ int sslroot::loadCertificates(const char *conf_fname)
int c;
unsigned int i;
FILE *cfd = fopen(configname.c_str(), "rb");
FILE *cfd = fopen(configfile.c_str(), "rb");
if (cfd == NULL)
{
std::cerr << "Unable to Load Configuration File!" << std::endl;
std::cerr << "File: " << configname << std::endl;
return -1;
std::cerr << "File: " << configfile << std::endl;
return false;
}
std::list<std::string> fnames;
@ -1807,9 +1890,6 @@ int sslroot::loadCertificates(const char *conf_fname)
// continue...
for(i = 0; (name[i] != '\n') && (i < signlen); i++);
//printf("Stepping over [%d] %0x\n", i, name[i]);
if (i != signlen)
{
for(i++; i < signlen; i++)
@ -1881,32 +1961,34 @@ int sslroot::loadCertificates(const char *conf_fname)
{
std::cerr << "ERROR VALIDATING CONFIGURATION!" << std::endl;
std::cerr << "PLEASE FIX!" << std::endl;
return -1;
return false;
}
std::list<std::string>::iterator it;
std::list<std::string>::iterator it2;
for(it = fnames.begin(), it2 = hashes.begin(); it != fnames.end(); it++, it2++)
{
std::string neighfile = neighdir + (*it) + ".pqi";
cert *nc = loadcertificate(neighfile.c_str(), (*it2));
if (nc != NULL)
XPGP *xpgp = loadXPGPFromFile(neighfile, (*it2));
if (xpgp != NULL)
{
if (0 > addCertificate(nc))
std::string id;
if (ProcessXPGP(xpgp, id))
{
// cleanup.
std::cerr << "Updated Certificate....but no";
std::cerr << " need for addition";
std::cerr << "Loaded Certificate: " << id;
std::cerr << std::endl;
// X509_free(nc -> certificate);
//delete nc;
}
}
}
for(mit = tmpsettings.begin(); mit != tmpsettings.end(); mit++)
{
settings[mit -> first] = mit -> second;
keyValueMap[mit -> first] = mit -> second;
}
return 1;
if (keyValueMap.size() > 0)
{
oldFormat = true;
}
return true;
}
#endif

View File

@ -84,7 +84,7 @@ virtual bool active();
virtual int InitAuth(const char *srvr_cert, const char *priv_key,
const char *passwd);
virtual bool CloseAuth();
virtual int setConfigDirectories(const char *cdir, const char *ndir);
virtual int setConfigDirectories(std::string confFile, std::string neighDir);
/*********** Overloaded Functions from p3AuthMgr **********/
@ -102,8 +102,11 @@ virtual bool isAuthenticated(std::string id);
virtual std::string getName(std::string id);
virtual bool getDetails(std::string id, pqiAuthDetails &details);
/* Load/Save certificates */
/* High Level Load/Save Configuration */
virtual bool saveCertificates();
virtual bool loadCertificates();
/* Load/Save certificates */
virtual bool LoadCertificateFromString(std::string pem, std::string &id);
virtual std::string SaveCertificateToString(std::string id);
virtual bool LoadCertificateFromFile(std::string filename, std::string &id);
@ -131,6 +134,8 @@ bool ValidateCertificateXPGP(XPGP *xpgp, std::string &peerId); /* validate + ge
bool FailedCertificateXPGP(XPGP *xpgp, bool incoming); /* store for discovery */
bool CheckCertificateXPGP(std::string peerId, XPGP *xpgp); /* check that they are exact match */
/* Special Config Loading (backwards compatibility) */
bool loadCertificates(bool &oldFormat, std::map<std::string, std::string> &keyValueMap);
private:
@ -154,7 +159,7 @@ bool locked_FindCert(std::string id, xpgpcert **cert);
RsMutex xpgpMtx; /**** LOCKING */
int init;
std::string mCertDir;
std::string mCertConfigFile;
std::string mNeighDir;
SSL_CTX *sslctx;

View File

@ -102,7 +102,7 @@ bool p3DummyAuthMgr::CloseAuth()
return true;
}
int p3DummyAuthMgr::setConfigDirectories(const char *cdir, const char *ndir)
int p3DummyAuthMgr::setConfigDirectories(std::string confFile, std::string neighDir)
{
return 1;
}
@ -187,6 +187,16 @@ bool p3DummyAuthMgr::getDetails(std::string id, pqiAuthDetails &details)
return false;
}
bool p3DummyAuthMgr::saveCertificates()
{
return false;
}
bool p3DummyAuthMgr::loadCertificates()
{
return false;
}
bool p3DummyAuthMgr::LoadCertificateFromString(std::string pem, std::string &id)
{
return false;

View File

@ -79,7 +79,7 @@ virtual bool active() = 0;
virtual int InitAuth(const char *srvr_cert, const char *priv_key,
const char *passwd) = 0;
virtual bool CloseAuth() = 0;
virtual int setConfigDirectories(const char *cdir, const char *ndir) = 0;
virtual int setConfigDirectories(std::string confFile, std::string neighDir) = 0;
/* get Certificate Ids */
@ -95,6 +95,10 @@ virtual bool isAuthenticated(std::string id) = 0;
virtual std::string getName(std::string id) = 0;
virtual bool getDetails(std::string id, pqiAuthDetails &details) = 0;
/* High Level Load/Save Configuration */
virtual bool saveCertificates() = 0;
virtual bool loadCertificates() = 0;
/* Load/Save certificates */
virtual bool LoadCertificateFromString(std::string pem, std::string &id) = 0;
@ -117,6 +121,8 @@ virtual bool TrustCertificate(std::string id, bool trust) = 0;
/* Sign / Encrypt / Verify Data (TODO) */
//virtual bool encryptData(std::string recipientId, std::string plaindata, std::string &result);
};
@ -132,7 +138,7 @@ virtual bool active();
virtual int InitAuth(const char *srvr_cert, const char *priv_key,
const char *passwd);
virtual bool CloseAuth();
virtual int setConfigDirectories(const char *cdir, const char *ndir);
virtual int setConfigDirectories(std::string confFile, std::string neighDir);
/* get Certificate Ids */
@ -148,8 +154,11 @@ virtual bool isAuthenticated(std::string id);
virtual std::string getName(std::string id);
virtual bool getDetails(std::string id, pqiAuthDetails &details);
/* Load/Save certificates */
/* High Level Load/Save Configuration */
virtual bool saveCertificates();
virtual bool loadCertificates();
/* Load/Save certificates */
virtual bool LoadCertificateFromString(std::string pem, std::string &id);
virtual std::string SaveCertificateToString(std::string id);
virtual bool LoadCertificateFromFile(std::string filename, std::string &id);
@ -164,6 +173,7 @@ virtual bool SignCertificate(std::string id);
virtual bool RevokeCertificate(std::string id);
virtual bool TrustCertificate(std::string id, bool trust);
std::string mOwnId;
std::map<std::string, pqiAuthDetails> mPeerList;
};

View File

@ -26,13 +26,15 @@
#include "pqi/p3cfgmgr.h"
#include "pqi/pqibin.h"
#include "pqi/pqiarchive.h"
#include "pqi/pqistreamer.h"
#include "serialiser/rsconfigitems.h"
#define CONFIG_DEBUG 1
p3ConfigMgr::p3ConfigMgr(std::string dir, std::string fname, std::string signame)
:basedir(dir), metafname(fname), metasigfname(signame)
:basedir(dir), metafname(fname), metasigfname(signame),
mConfigSaveActive(true)
{
@ -42,16 +44,33 @@ void p3ConfigMgr::tick()
{
bool toSave = false;
{
RsStackMutex stack(cfgMtx); /***** LOCK STACK MUTEX ****/
/* iterate through and check if any have changed */
std::map<uint32_t, pqiConfig *>::iterator it;
for(it = configs.begin(); it != configs.end(); it++)
{
if (it->second->ConfInd.Changed(0))
if (it->second->HasConfigChanged(0))
{
#ifdef CONFIG_DEBUG
std::cerr << "p3ConfigMgr::tick() Config Changed - Element: ";
std::cerr << it->first;
std::cerr << std::endl;
#endif
toSave = true;
}
}
/* disable saving before exit */
if (!mConfigSaveActive)
{
toSave = false;
}
}
if (toSave)
{
saveConfiguration();
@ -61,67 +80,221 @@ void p3ConfigMgr::tick()
void p3ConfigMgr::saveConfiguration()
{
/* setup metaconfig */
RsStackMutex stack(cfgMtx); /***** LOCK STACK MUTEX ****/
#ifdef CONFIG_DEBUG
std::cerr << "p3ConfigMgr::saveConfiguration()";
std::cerr << std::endl;
#endif
RsConfigKeyValueSet *item = new RsConfigKeyValueSet();
std::map<uint32_t, pqiConfig *>::iterator it;
for(it = configs.begin(); it != configs.end(); it++)
{
if (it->second->ConfInd.Changed(1))
if (it->second->HasConfigChanged(1))
{
it->second->saveConfiguration(basedir);
#ifdef CONFIG_DEBUG
std::cerr << "p3ConfigMgr::saveConfiguration() Saving Element: ";
std::cerr << it->first;
std::cerr << std::endl;
#endif
it->second->saveConfiguration();
}
/* save metaconfig */
#ifdef CONFIG_DEBUG
std::cerr << "p3ConfigMgr::saveConfiguration() Element: ";
std::cerr << it->first << " Hash: " << it->second->Hash();
std::cerr << std::endl;
#endif
RsTlvKeyValue kv;
{
std::ostringstream out;
out << it->first;
kv.key = out.str();
}
kv.value = it->second->Hash();
item->tlvkvs.pairs.push_back(kv);
}
#ifdef CONFIG_DEBUG
std::cerr << "p3ConfigMgr::saveConfiguration() Complete MetaConfigItem: ";
std::cerr << std::endl;
item->print(std::cerr, 20);
#endif
/* Write the data to a stream */
uint32_t bioflags = BIN_FLAGS_HASH_DATA | BIN_FLAGS_WRITEABLE;
BinInterface *bio = new BinFileInterface(metafname.c_str(), bioflags);
RsSerialiser *rss = new RsSerialiser();
rss->addSerialType(new RsGeneralConfigSerialiser());
pqistreamer stream(rss, "CONFIG", bio, 0);
stream.SendItem(item);
stream.tick();
stream.tick();
/* get hash */
std::string totalhash = bio->gethash();
/* sign the hash of the data */
/* write signature to configuration */
}
void p3ConfigMgr::loadConfiguration()
{
RsStackMutex stack(cfgMtx); /***** LOCK STACK MUTEX ****/
#ifdef CONFIG_DEBUG
std::cerr << "p3ConfigMgr::loadConfiguration()";
std::cerr << std::endl;
#endif
/* Write the data to a stream */
uint32_t bioflags = BIN_FLAGS_HASH_DATA | BIN_FLAGS_READABLE;
BinInterface *bio = new BinFileInterface(metafname.c_str(), bioflags);
RsSerialiser *rss = new RsSerialiser();
rss->addSerialType(new RsGeneralConfigSerialiser());
pqistreamer stream(rss, "CONFIG", bio, 0);
stream.tick();
stream.tick();
RsItem *rsitem = stream.GetItem();
RsConfigKeyValueSet *item = dynamic_cast<RsConfigKeyValueSet *>(rsitem);
if (!item)
{
delete rsitem;
return;
}
#ifdef CONFIG_DEBUG
std::cerr << "p3ConfigMgr::loadConfiguration() Loaded MetaConfigItem: ";
std::cerr << std::endl;
item->print(std::cerr, 20);
#endif
std::string totalhash = bio->gethash();
/* check it TODO */
/* sign the hash of the data */
/* check signature with configuration */
/* extract info from KeyValueSet */
std::list<RsTlvKeyValue>::iterator it;
for(it = item->tlvkvs.pairs.begin(); it != item->tlvkvs.pairs.end(); it++)
{
/* find the configuration */
uint32_t confId = atoi(it->key.c_str());
std::string hashin = it->value;
std::map<uint32_t, pqiConfig *>::iterator cit;
cit = configs.find(confId);
if (cit != configs.end())
{
#ifdef CONFIG_DEBUG
std::cerr << "p3ConfigMgr::loadConfiguration() Element: ";
std::cerr << confId << " Hash: " << hashin;
std::cerr << std::endl;
#endif
(cit->second)->loadConfiguration(hashin);
/* force config to NOT CHANGED */
cit->second->HasConfigChanged(0);
cit->second->HasConfigChanged(1);
}
}
#ifdef CONFIG_DEBUG
std::cerr << "p3ConfigMgr::loadConfiguration() Done!";
std::cerr << std::endl;
#endif
}
void p3ConfigMgr::addConfiguration(uint32_t type, pqiConfig *conf)
void p3ConfigMgr::addConfiguration(std::string file, pqiConfig *conf)
{
configs[type] = conf;
RsStackMutex stack(cfgMtx); /***** LOCK STACK MUTEX ****/
/* construct filename */
std::string filename = basedir;
if (basedir != "")
{
filename += "/";
}
filename += file;
conf->setFilename(filename);
configs[conf->Type()] = conf;
}
p3Config::p3Config(uint32_t t, std::string name)
:pqiConfig(t, name)
void p3ConfigMgr::completeConfiguration()
{
saveConfiguration();
RsStackMutex stack(cfgMtx); /***** LOCK STACK MUTEX ****/
mConfigSaveActive = false;
}
p3Config::p3Config(uint32_t t)
:pqiConfig(t)
{
return;
}
bool p3Config::loadConfiguration(std::string basedir, std::string &loadHash)
bool p3Config::loadConfiguration(std::string &loadHash)
{
std::list<RsItem *> load;
std::list<RsItem *>::iterator it;
std::string fname = basedir;
if (fname != "")
fname += "/";
fname += Filename();
std::string fname = Filename();
BinFileInterface *bio = new BinFileInterface(fname.c_str(),
BIN_FLAGS_READABLE | BIN_FLAGS_HASH_DATA);
pqiarchive archive(setupSerialiser(), bio, BIN_FLAGS_READABLE);
uint32_t bioflags = BIN_FLAGS_HASH_DATA | BIN_FLAGS_READABLE;
uint32_t stream_flags = BIN_FLAGS_READABLE;
BinInterface *bio = new BinFileInterface(fname.c_str(), bioflags);
pqistreamer stream(setupSerialiser(), "CONFIG", bio, stream_flags);
RsItem *item = NULL;
while(NULL != (item = archive.GetItem()))
stream.tick();
while(NULL != (item = stream.GetItem()))
{
#ifdef CONFIG_DEBUG
std::cerr << "p3Config::loadConfiguration() loaded item:";
std::cerr << std::endl;
item->print(std::cerr, 0);
std::cerr << std::endl;
#endif
load.push_back(item);
stream.tick();
}
#ifdef CONFIG_DEBUG
std::cerr << "p3Config::loadConfiguration() loaded " << load.size();
std::cerr << " Elements from File: " << fname;
std::cerr << std::endl;
#endif
/* check hash */
std::string hashstr = archive.gethash();
std::string hashstr = bio->gethash();
if (hashstr != loadHash)
{
#ifdef CONFIG_DEBUG
std::cerr << "p3Config::loadConfiguration() ERROR: Hash != MATCHloaded";
std::cerr << std::endl;
#endif
/* bad load */
for(it = load.begin(); it != load.end(); it++)
{
@ -137,32 +310,49 @@ bool p3Config::loadConfiguration(std::string basedir, std::string &loadHash)
}
bool p3Config::saveConfiguration(std::string basedir)
bool p3Config::saveConfiguration()
{
bool toKeep;
std::list<RsItem *> toSave = saveList(toKeep);
std::string fname = basedir;
if (fname != "")
fname += "/";
fname += Filename();
bool cleanup = true;
std::list<RsItem *> toSave = saveList(cleanup);
BinFileInterface *bio = new BinFileInterface(fname.c_str(),
BIN_FLAGS_WRITEABLE | BIN_FLAGS_HASH_DATA);
std::string fname = Filename();
uint32_t arch_flags = BIN_FLAGS_WRITEABLE;
if (toKeep)
arch_flags |= BIN_FLAGS_NO_DELETE;
#ifdef CONFIG_DEBUG
std::cerr << "p3Config::saveConfiguration() toSave " << toSave.size();
std::cerr << " Elements to File: " << fname;
std::cerr << std::endl;
#endif
pqiarchive archive(setupSerialiser(), bio, arch_flags);
uint32_t bioflags = BIN_FLAGS_HASH_DATA | BIN_FLAGS_WRITEABLE;
uint32_t stream_flags = BIN_FLAGS_WRITEABLE;
if (!cleanup)
stream_flags |= BIN_FLAGS_NO_DELETE;
BinInterface *bio = new BinFileInterface(fname.c_str(), bioflags);
pqistreamer stream(setupSerialiser(), "CONFIG", bio, stream_flags);
std::list<RsItem *>::iterator it;
for(it = toSave.begin(); it != toSave.end(); it++)
{
archive.SendItem(*it);
#ifdef CONFIG_DEBUG
std::cerr << "p3Config::saveConfiguration() save item:";
std::cerr << std::endl;
(*it)->print(std::cerr, 0);
std::cerr << std::endl;
#endif
stream.SendItem(*it);
stream.tick();
}
/* final tick for anymore writing */
stream.tick();
/* store the hash */
setHash(archive.gethash());
setHash(bio->gethash());
saveDone(); /* callback to inherited class to unlock any Mutexes
* protecting saveList() data
*/
/* else okay */
return true;
@ -172,7 +362,7 @@ bool p3Config::saveConfiguration(std::string basedir)
/**************************** CONFIGURATION CLASSES ********************/
p3GeneralConfig::p3GeneralConfig()
:p3Config(CONFIG_TYPE_GENERAL, "gen.set")
:p3Config(CONFIG_TYPE_GENERAL)
{
return;
}
@ -180,6 +370,12 @@ p3GeneralConfig::p3GeneralConfig()
// General Configuration System
std::string p3GeneralConfig::getSetting(std::string opt)
{
#ifdef CONFIG_DEBUG
std::cerr << "p3GeneralConfig::getSetting(" << opt << ")";
std::cerr << std::endl;
#endif
RsStackMutex stack(cfgMtx); /***** LOCK STACK MUTEX ****/
/* extract from config */
std::map<std::string, std::string>::iterator it;
if (settings.end() == (it = settings.find(opt)))
@ -192,6 +388,13 @@ std::string p3GeneralConfig::getSetting(std::string opt)
void p3GeneralConfig::setSetting(std::string opt, std::string val)
{
#ifdef CONFIG_DEBUG
std::cerr << "p3GeneralConfig::setSetting(" << opt << " = " << val << ")";
std::cerr << std::endl;
#endif
{
RsStackMutex stack(cfgMtx); /***** LOCK STACK MUTEX ****/
/* extract from config */
std::map<std::string, std::string>::iterator it;
if (settings.end() != (it = settings.find(opt)))
@ -203,40 +406,149 @@ void p3GeneralConfig::setSetting(std::string opt, std::string val)
}
}
ConfInd.IndicateChanged();
settings[opt] = val;
}
/* outside mutex */
IndicateConfigChanged();
return;
}
/* TODO ******/
RsSerialiser *p3GeneralConfig::setupSerialiser()
{
RsSerialiser *rss = NULL;
RsSerialiser *rss = new RsSerialiser();
rss->addSerialType(new RsGeneralConfigSerialiser());
return rss;
}
std::list<RsItem *> p3GeneralConfig::saveList(bool &cleanup)
{
cleanup = false;
RsStackMutex stack(cfgMtx); /***** LOCK STACK MUTEX ****/
#ifdef CONFIG_DEBUG
std::cerr << "p3GeneralConfig::saveList() KV sets: " << settings.size();
std::cerr << std::endl;
#endif
cleanup = true;
std::list<RsItem *> savelist;
//RsGenConfItem *item = ...
RsConfigKeyValueSet *item = new RsConfigKeyValueSet();
std::map<std::string, std::string>::iterator it;
for(it = settings.begin(); it != settings.end(); it++)
{
RsTlvKeyValue kv;
kv.key = it->first;
kv.value = it->second;
item->tlvkvs.pairs.push_back(kv);
/* make sure we don't overload it */
if (item->tlvkvs.TlvSize() > 4000)
{
savelist.push_back(item);
item = new RsConfigKeyValueSet();
}
}
if (item->tlvkvs.pairs.size() > 0)
{
savelist.push_back(item);
}
return savelist;
}
bool p3GeneralConfig::loadList(std::list<RsItem *> load)
{
/* add into settings */
#ifdef CONFIG_DEBUG
std::cerr << "p3GeneralConfig::loadList() count: " << load.size();
std::cerr << std::endl;
#endif
return false;
RsStackMutex stack(cfgMtx); /***** LOCK STACK MUTEX ****/
/* add into settings */
RsConfigKeyValueSet *item = NULL;
std::list<RsItem *>::iterator it;
std::list<RsTlvKeyValue>::iterator kit;
for(it = load.begin(); it != load.end();)
{
item = dynamic_cast<RsConfigKeyValueSet *>(*it);
if (item)
{
for(kit = item->tlvkvs.pairs.begin();
kit != item->tlvkvs.pairs.end(); kit++)
{
settings[kit->key] = kit->value;
}
}
/* cleanup */
delete (*it);
it = load.erase(it);
}
return true;
}
/**** MUTEX NOTE:
* have protected all, but think that
* only the Indication and hash really need it
*/
pqiConfig::pqiConfig(uint32_t t)
:ConfInd(2), type(t)
{
return;
}
pqiConfig::~pqiConfig()
{
return;
}
uint32_t pqiConfig::Type()
{
RsStackMutex stack(cfgMtx); /***** LOCK STACK MUTEX ****/
return type;
}
std::string pqiConfig::Filename()
{
RsStackMutex stack(cfgMtx); /***** LOCK STACK MUTEX ****/
return filename;
}
std::string pqiConfig::Hash()
{
RsStackMutex stack(cfgMtx); /***** LOCK STACK MUTEX ****/
return hash;
}
void pqiConfig::IndicateConfigChanged()
{
RsStackMutex stack(cfgMtx); /***** LOCK STACK MUTEX ****/
ConfInd.IndicateChanged();
}
bool pqiConfig::HasConfigChanged(uint16_t idx)
{
RsStackMutex stack(cfgMtx); /***** LOCK STACK MUTEX ****/
return ConfInd.Changed(idx);
}
void pqiConfig::setFilename(std::string name)
{
RsStackMutex stack(cfgMtx); /***** LOCK STACK MUTEX ****/
filename = name;
}
void pqiConfig::setHash(std::string h)
{
RsStackMutex stack(cfgMtx); /***** LOCK STACK MUTEX ****/
hash = h;
}

View File

@ -34,6 +34,7 @@
#include "pqi/pqi_base.h"
#include "pqi/pqiindic.h"
#include "pqi/pqinetwork.h"
#include "util/rsthreads.h"
/***** Configuration Management *****
*
@ -52,40 +53,61 @@
*
*/
/**** THESE are STORED in CONFIGURATION FILES....
* Cannot be changed
*
*********************/
const uint32_t CONFIG_TYPE_GENERAL = 0x0001;
const uint32_t CONFIG_TYPE_STUNLIST = 0x0002;
const uint32_t CONFIG_TYPE_PEERS = 0x0002;
const uint32_t CONFIG_TYPE_FSERVER = 0x0003;
const uint32_t CONFIG_TYPE_PEERS = 0x0004;
const uint32_t CONFIG_TYPE_MSGS = 0x0004;
class p3ConfigMgr;
class pqiConfig
{
public:
pqiConfig(uint32_t t, std::string defaultname)
:ConfInd(2), type(t), filename(defaultname)
{
return;
}
virtual ~pqiConfig() { return; }
pqiConfig(uint32_t t);
virtual ~pqiConfig();
virtual bool loadConfiguration(std::string filename, std::string &load) = 0;
virtual bool saveConfiguration(std::string filename) = 0;
virtual bool loadConfiguration(std::string &loadHash) = 0;
virtual bool saveConfiguration() = 0;
uint32_t Type();
std::string Filename();
std::string Hash();
protected:
void IndicateConfigChanged();
void setHash(std::string h);
RsMutex cfgMtx;
private:
void setFilename(std::string name);
bool HasConfigChanged(uint16_t idx);
Indicator ConfInd;
uint32_t Type() { return type; }
std::string Filename() { return filename; }
std::string Hash() { return hash; }
protected:
void setHash(std::string h) { hash = h; }
private:
uint32_t type;
std::string filename;
std::string hash;
friend class p3ConfigMgr;
/* so it can access:
* setFilename() and HasConfigChanged()
*/
};
/**** MUTEX NOTE
* None - because no-one calls any functions
* besides tick() when the system is running.
*/
class p3ConfigMgr
{
public:
@ -94,16 +116,25 @@ class p3ConfigMgr
void tick();
void saveConfiguration();
void loadConfiguration();
void addConfiguration(uint32_t type, pqiConfig *conf);
void addConfiguration(std::string file, pqiConfig *conf);
/* saves config, and disables further saving
* used for exiting the system
*/
void completeConfiguration();
private:
/* these are constants - so shouldn't need mutex */
const std::string basedir;
const std::string metafname;
const std::string metasigfname;
RsMutex cfgMtx; /* below is protected */
bool mConfigSaveActive;
std::map<uint32_t, pqiConfig *> configs;
std::string basedir;
std::string metafname;
std::string metasigfname;
};
@ -111,10 +142,10 @@ class p3Config: public pqiConfig
{
public:
p3Config(uint32_t t, std::string name);
p3Config(uint32_t t);
virtual bool loadConfiguration(std::string basedir, std::string &loadHash);
virtual bool saveConfiguration(std::string basedir);
virtual bool loadConfiguration(std::string &loadHash);
virtual bool saveConfiguration();
protected:
@ -122,7 +153,11 @@ virtual bool saveConfiguration(std::string basedir);
virtual RsSerialiser *setupSerialiser() = 0;
virtual std::list<RsItem *> saveList(bool &cleanup) = 0;
virtual bool loadList(std::list<RsItem *> load) = 0;
/**
* callback for mutex unlocking
* in derived classes (should only be needed if cleanup = false)
*/
virtual void saveDone() { return; }
}; /* end of p3Config */
@ -145,6 +180,7 @@ virtual bool loadList(std::list<RsItem *> load);
private:
/* protected by pqiConfig mutex as well! */
std::map<std::string, std::string> settings;
};

View File

@ -27,6 +27,8 @@
#include "tcponudp/tou.h"
#include "util/rsprint.h"
#include "serialiser/rsconfigitems.h"
/* Network setup States */
const uint32_t RS_NET_UNKNOWN = 0x0001;
@ -45,23 +47,6 @@ const uint32_t MAX_UPNP_INIT = 10; /* seconds UPnP timeout */
#define CONN_DEBUG 1
p3ConnectMgr::p3ConnectMgr(p3AuthMgr *am)
:p3Config(CONFIG_TYPE_PEERS, "peers.cfg"),
mAuthMgr(am), mDhtMgr(NULL), mUpnpMgr(NULL), mNetStatus(RS_NET_UNKNOWN),
mStunStatus(0), mStatusChanged(false)
{
mUpnpAddrValid = false;
mStunAddrValid = false;
/* setup basics of own state */
if (am)
{
ownState.id = mAuthMgr->OwnId();
ownState.name = mAuthMgr->getName(ownState.id);
}
return;
}
peerConnectAddress::peerConnectAddress()
:type(0), ts(0)
@ -78,22 +63,56 @@ peerAddrInfo::peerAddrInfo()
}
peerConnectState::peerConnectState()
:id("unknown"), name("nameless"), state(0), actions(0),
:id("unknown"),
netMode(RS_NET_MODE_UNKNOWN), visState(RS_VIS_STATE_STD),
source(0),
inConnAttempt(0), connAttemptTS(0),
lastcontact(0)
lastcontact(0),
//lc_timestamp(0), lr_timestamp(0),
//nc_timestamp(0), nc_timeintvl(0)
name("nameless"), state(0), actions(0),
source(0),
inConnAttempt(0), connAttemptTS(0)
{
sockaddr_clear(&lastaddr);
sockaddr_clear(&localaddr);
sockaddr_clear(&serveraddr);
return;
}
p3ConnectMgr::p3ConnectMgr(p3AuthMgr *am)
:p3Config(CONFIG_TYPE_PEERS),
mAuthMgr(am), mDhtMgr(NULL), mUpnpMgr(NULL), mNetStatus(RS_NET_UNKNOWN),
mStunStatus(0), mStatusChanged(false)
{
mUpnpAddrValid = false;
mStunAddrValid = false;
/* setup basics of own state */
if (am)
{
ownState.id = mAuthMgr->OwnId();
ownState.name = mAuthMgr->getName(ownState.id);
ownState.netMode = RS_NET_MODE_UDP;
}
return;
}
void p3ConnectMgr::setOwnNetConfig(uint32_t netMode, uint32_t visState)
{
ownState.netMode = netMode;
ownState.visState = visState;
/* if we've started up - then tweak Dht On/Off */
if (mNetStatus != RS_NET_UNKNOWN)
{
mDhtMgr->setDhtOn(!(ownState.visState & RS_VIS_STATE_NODHT));
}
IndicateConfigChanged(); /**** INDICATE MSG CONFIG CHANGED! *****/
}
/***** Framework / initial implementation for a connection manager.
*
* This needs a state machine for Initialisation.
@ -374,6 +393,7 @@ void p3ConnectMgr::netUdpCheck()
{
mode |= RS_NET_CONN_TCP_EXTERNAL;
}
IndicateConfigChanged(); /**** INDICATE MSG CONFIG CHANGED! *****/
}
connMtx.unlock(); /* UNLOCK MUTEX */
@ -567,6 +587,8 @@ void p3ConnectMgr::stunCollect(std::string id, struct sockaddr_in addr, uint32_t
#endif
/* push to the front */
mStunList.push_front(id);
IndicateConfigChanged(); /**** INDICATE MSG CONFIG CHANGED! *****/
}
}
else
@ -581,6 +603,8 @@ void p3ConnectMgr::stunCollect(std::string id, struct sockaddr_in addr, uint32_t
/* move to front */
mStunList.erase(it);
mStunList.push_front(id);
IndicateConfigChanged(); /**** INDICATE MSG CONFIG CHANGED! *****/
}
}
@ -1036,6 +1060,7 @@ void p3ConnectMgr::peerStatus(std::string id,
}
/* not updating VIS status??? */
IndicateConfigChanged(); /**** INDICATE MSG CONFIG CHANGED! *****/
}
else if (source == RS_CB_PERSON)
{
@ -1083,6 +1108,7 @@ void p3ConnectMgr::peerStatus(std::string id,
{
it->second.visState |= RS_VIS_STATE_NODHT;
}
IndicateConfigChanged(); /**** INDICATE MSG CONFIG CHANGED! *****/
}
if (!isFriend)
@ -1216,7 +1242,7 @@ void p3ConnectMgr::peerConnectRequest(std::string id, uint32_t type)
/*******************************************************************/
/*******************************************************************/
bool p3ConnectMgr::addFriend(std::string id)
bool p3ConnectMgr::addFriend(std::string id, uint32_t netMode, uint32_t visState, time_t lastContact)
{
/* so three possibilities
* (1) already exists as friend -> do nothing.
@ -1276,12 +1302,18 @@ bool p3ConnectMgr::addFriend(std::string id)
it->second.state = RS_PEER_S_FRIEND;
it->second.actions = RS_PEER_NEW;
/* setup connectivity parameters */
it->second.visState = visState;
it->second.netMode = netMode;
it->second.lastcontact = lastContact;
mStatusChanged = true;
/* add peer to DHT (if not dark) */
if (it->second.visState & RS_VIS_STATE_NODHT)
{
/* hidden from DHT world */
mDhtMgr->dropPeer(id);
}
else
{
@ -1289,6 +1321,9 @@ bool p3ConnectMgr::addFriend(std::string id)
}
connMtx.unlock(); /* UNLOCK MUTEX */
IndicateConfigChanged(); /**** INDICATE MSG CONFIG CHANGED! *****/
return true;
}
@ -1320,8 +1355,9 @@ bool p3ConnectMgr::addFriend(std::string id)
pstate.state = RS_PEER_S_FRIEND;
pstate.actions = RS_PEER_NEW;
pstate.visState = RS_VIS_STATE_STD;
pstate.netMode = RS_NET_MODE_UNKNOWN;
pstate.visState = visState;
pstate.netMode = netMode;
pstate.lastcontact = lastContact;
/* addr & timestamps -> auto cleared */
@ -1334,6 +1370,8 @@ bool p3ConnectMgr::addFriend(std::string id)
connMtx.unlock(); /* UNLOCK MUTEX */
IndicateConfigChanged(); /**** INDICATE MSG CONFIG CHANGED! *****/
return true;
}
@ -1373,6 +1411,8 @@ bool p3ConnectMgr::removeFriend(std::string id)
connMtx.unlock(); /* UNLOCK MUTEX */
IndicateConfigChanged(); /**** INDICATE MSG CONFIG CHANGED! *****/
return success;
}
@ -1611,6 +1651,7 @@ bool p3ConnectMgr::setLocalAddress(std::string id, struct sockaddr_in addr)
if (id == mAuthMgr->OwnId())
{
ownState.localaddr = addr;
IndicateConfigChanged(); /**** INDICATE MSG CONFIG CHANGED! *****/
return true;
}
@ -1626,6 +1667,7 @@ bool p3ConnectMgr::setLocalAddress(std::string id, struct sockaddr_in addr)
/* "it" points to peer */
it->second.localaddr = addr;
IndicateConfigChanged(); /**** INDICATE MSG CONFIG CHANGED! *****/
return true;
}
@ -1637,6 +1679,7 @@ bool p3ConnectMgr::setExtAddress(std::string id, struct sockaddr_in addr)
if (id == mAuthMgr->OwnId())
{
ownState.serveraddr = addr;
IndicateConfigChanged(); /**** INDICATE MSG CONFIG CHANGED! *****/
return true;
}
@ -1652,17 +1695,93 @@ bool p3ConnectMgr::setExtAddress(std::string id, struct sockaddr_in addr)
/* "it" points to peer */
it->second.serveraddr = addr;
IndicateConfigChanged(); /**** INDICATE MSG CONFIG CHANGED! *****/
return true;
}
bool p3ConnectMgr::setNetworkMode(std::string id, uint32_t netMode)
{
if (id == mAuthMgr->OwnId())
{
uint32_t visState = ownState.visState;
setOwnNetConfig(netMode, visState);
return true;
}
/* check if it is a friend */
std::map<std::string, peerConnectState>::iterator it;
if (mFriendList.end() == (it = mFriendList.find(id)))
{
if (mOthersList.end() == (it = mOthersList.find(id)))
{
return false;
}
}
/* "it" points to peer */
it->second.netMode = netMode;
IndicateConfigChanged(); /**** INDICATE MSG CONFIG CHANGED! *****/
connMtx.lock(); /* LOCK MUTEX */
connMtx.unlock(); /* UNLOCK MUTEX */
return false;
}
bool p3ConnectMgr::setVisState(std::string id, uint32_t visState)
{
if (id == mAuthMgr->OwnId())
{
uint32_t netMode = ownState.netMode;
setOwnNetConfig(netMode, visState);
return true;
}
/* check if it is a friend */
std::map<std::string, peerConnectState>::iterator it;
bool isFriend = false;
if (mFriendList.end() == (it = mFriendList.find(id)))
{
if (mOthersList.end() == (it = mOthersList.find(id)))
{
return false;
}
}
else
{
isFriend = true;
}
/* "it" points to peer */
it->second.visState = visState;
if (isFriend)
{
/* toggle DHT state */
if (it->second.visState & RS_VIS_STATE_NODHT)
{
/* hidden from DHT world */
mDhtMgr->dropPeer(id);
}
else
{
mDhtMgr->findPeer(id);
}
}
IndicateConfigChanged(); /**** INDICATE MSG CONFIG CHANGED! *****/
connMtx.lock(); /* LOCK MUTEX */
connMtx.unlock(); /* UNLOCK MUTEX */
return false;
}
bool p3ConnectMgr::getUPnPState()
{
return mUpnpMgr->getUPnPActive();
@ -1718,6 +1837,8 @@ bool p3ConnectMgr::checkNetAddress()
std::cerr << inet_ntoa(ownState.localaddr.sin_addr);
std::cerr << std::endl;
IndicateConfigChanged(); /**** INDICATE MSG CONFIG CHANGED! *****/
}
if ((isPrivateNet(&(ownState.localaddr.sin_addr))) ||
(isLoopbackNet(&(ownState.localaddr.sin_addr))))
@ -1751,7 +1872,6 @@ bool p3ConnectMgr::checkNetAddress()
// ensure that address family is set, otherwise windows Barfs.
ownState.localaddr.sin_family = AF_INET;
ownState.serveraddr.sin_family = AF_INET;
ownState.lastaddr.sin_family = AF_INET;
std::cerr << "p3ConnectMgr::checkNetAddress() Final Local Address: ";
std::cerr << inet_ntoa(ownState.localaddr.sin_addr);
@ -1766,12 +1886,10 @@ bool p3ConnectMgr::checkNetAddress()
/*******************************************************************/
/* Key Functions to be overloaded for Full Configuration */
/**** TODO ****/
RsSerialiser *p3ConnectMgr::setupSerialiser()
{
RsSerialiser *rss = new RsSerialiser();
//rss->addSerialType(new RsConfigSerialiser());
rss->addSerialType(new RsPeerConfigSerialiser());
return rss;
}
@ -1782,101 +1900,129 @@ std::list<RsItem *> p3ConnectMgr::saveList(bool &cleanup)
/* create a list of current peers */
std::list<RsItem *> saveData;
cleanup = true;
connMtx.lock(); /* LOCK MUTEX */
connMtx.unlock(); /* UNLOCK MUTEX */
RsPeerNetItem *item = new RsPeerNetItem();
item->clear();
item->pid = getOwnId();
item->netMode = ownState.netMode;
item->visState = ownState.visState;
item->lastContact = ownState.lastcontact;
item->localaddr = ownState.localaddr;
item->remoteaddr = ownState.serveraddr;
#ifdef CONN_DEBUG
std::cerr << "p3ConnectMgr::saveList() Own Config Item:";
std::cerr << std::endl;
item->print(std::cerr, 10);
std::cerr << std::endl;
#endif
saveData.push_back(item);
/* iterate through all friends and save */
std::map<std::string, peerConnectState>::iterator it;
for(it = mFriendList.begin(); it != mFriendList.end(); it++)
{
item = new RsPeerNetItem();
item->clear();
item->pid = it->first;
item->netMode = (it->second).netMode;
item->visState = (it->second).visState;
item->lastContact = (it->second).lastcontact;
item->localaddr = (it->second).localaddr;
item->remoteaddr = (it->second).serveraddr;
saveData.push_back(item);
#ifdef CONN_DEBUG
std::cerr << "p3ConnectMgr::saveList() Peer Config Item:";
std::cerr << std::endl;
item->print(std::cerr, 10);
std::cerr << std::endl;
#endif
}
RsPeerStunItem *sitem = new RsPeerStunItem();
std::list<std::string>::iterator sit;
for(sit = mStunList.begin(); sit != mStunList.end(); sit++)
{
sitem->stunList.ids.push_back(*sit);
}
saveData.push_back(sitem);
return saveData;
}
bool p3ConnectMgr::loadList(std::list<RsItem *> load)
{
#ifdef CONN_DEBUG
std::cerr << "p3ConnectMgr::loadList() Item Count: " << load.size();
std::cerr << std::endl;
#endif
/* load the list of peers */
std::list<RsItem *>::iterator it;
for(it = load.begin(); it != load.end(); it++)
{
RsPeerNetItem *pitem = dynamic_cast<RsPeerNetItem *>(*it);
RsPeerStunItem *sitem = dynamic_cast<RsPeerStunItem *>(*it);
connMtx.lock(); /* LOCK MUTEX */
connMtx.unlock(); /* UNLOCK MUTEX */
if (pitem)
{
if (pitem->pid == getOwnId())
{
#ifdef CONN_DEBUG
std::cerr << "p3ConnectMgr::loadList() Own Config Item:";
std::cerr << std::endl;
pitem->print(std::cerr, 10);
std::cerr << std::endl;
#endif
/* add ownConfig */
setOwnNetConfig(pitem->netMode, pitem->visState);
setLocalAddress(pitem->pid, pitem->localaddr);
setExtAddress(pitem->pid, pitem->remoteaddr);
}
else
{
#ifdef CONN_DEBUG
std::cerr << "p3ConnectMgr::loadList() Peer Config Item:";
std::cerr << std::endl;
pitem->print(std::cerr, 10);
std::cerr << std::endl;
#endif
/* ************* */
addFriend(pitem->pid, pitem->netMode, pitem->visState, pitem->lastContact);
setLocalAddress(pitem->pid, pitem->localaddr);
setExtAddress(pitem->pid, pitem->remoteaddr);
}
}
else if (sitem)
{
#ifdef CONN_DEBUG
std::cerr << "p3ConnectMgr::loadList() Stun Config Item:";
std::cerr << std::endl;
sitem->print(std::cerr, 10);
std::cerr << std::endl;
#endif
std::list<std::string>::iterator sit;
for(sit = sitem->stunList.ids.begin();
sit != sitem->stunList.ids.end(); sit++)
{
mStunList.push_back(*sit);
}
}
connMtx.lock(); /* LOCK MUTEX */
connMtx.unlock(); /* UNLOCK MUTEX */
delete (*it);
}
return true;
}
/*******************************************************************/
#if 0
/******************************** Load/Save Config *********************************
* Configuration Loading / Saving.
*/
void p3ConnectMgr::saveConfiguration()
{
return;
}
void p3ConnectMgr::loadConfiguration()
{
/* open the config file....
* load:
* (1) a list of friends
* (2) a list of stun peers
*/
return;
}
std::string configFile = configMgr->getConfigDir();
configFile += "rsnet.state";
/* open file */
while(NULL != (item = config.read()))
{
switch(item->SubType())
{
case OWN_CONFIG:
{
RsPeerConfigItem *peeritem = (RsPeerConfigItem *) item;
setupConfig(peeritem);
break;
}
case PEER_CONFIG:
{
RsPeerConfigItem *peeritem = (RsPeerConfigItem *) item;
addPeer(peeritem);
break;
}
case STUNLIST:
{
RsStunConfigItem *slitem = (RsStunConfigItem *) item;
/* add to existing list */
for(it = slitem.begin();
it = slitem.end(); it++)
{
mStunList.push_back(*it);
}
break;
}
default:
break;
}
delete item;
}
}
void p3ConnectMgr::setupOwnNetConfig(RsPeerConfigItem *item)
{
return;
}
#endif

View File

@ -35,6 +35,15 @@
#include "util/rsthreads.h"
/* RS_VIS_STATE_XXXX
* determines how public this peer wants to be...
*
* STD = advertise to Peers / DHT checking etc
* GRAY = share with friends / but not DHT
* DARK = hidden from all
* BROWN? = hidden from friends / but on DHT
*/
const uint32_t RS_VIS_STATE_NODISC = 0x0001;
const uint32_t RS_VIS_STATE_NODHT = 0x0002;
@ -43,6 +52,8 @@ const uint32_t RS_VIS_STATE_GRAY = RS_VIS_STATE_NODHT;
const uint32_t RS_VIS_STATE_DARK = RS_VIS_STATE_NODISC | RS_VIS_STATE_NODHT;
const uint32_t RS_VIS_STATE_BROWN = RS_VIS_STATE_NODISC;
const uint32_t RS_NET_MODE_UNKNOWN = 0x0000;
const uint32_t RS_NET_MODE_EXT = 0x0001;
const uint32_t RS_NET_MODE_UPNP = 0x0002;
@ -92,28 +103,21 @@ class peerConnectState
peerConnectState(); /* init */
std::string id;
uint32_t netMode; /* EXT / UPNP / UDP / INVALID */
uint32_t visState; /* STD, GRAY, DARK */
struct sockaddr_in localaddr, serveraddr;
time_t lastcontact;
/***** Below here not stored permanently *****/
std::string name;
uint32_t state;
uint32_t actions;
uint32_t netMode; /* EXT / UPNP / UDP / INVALID */
/* Fix this up! */
// public for the moment.
struct sockaddr_in lastaddr, localaddr, serveraddr;
/* determines how public this peer wants to be...
*
* STD = advertise to Peers / DHT checking etc
* GRAY = share with friends / but not DHT
* DARK = hidden from all
* BROWN? = hidden from friends / but on DHT
*/
uint32_t visState; /* STD, GRAY, DARK */
uint32_t source; /* most current source */
peerAddrInfo dht;
peerAddrInfo disc;
@ -125,15 +129,6 @@ class peerConnectState
peerConnectAddress currentConnAddr;
std::list<peerConnectAddress> connAddrs;
time_t lastcontact;
/* stuff here un-used at the moment */
//time_t c_timestamp; // last connect timestamp
//time_t lr_timestamp; // last receive timestamp
//time_t nc_timestamp; // next connect timestamp.
//time_t nc_timeintvl; // next connect time interval.
};
@ -157,12 +152,17 @@ bool getUPnPState();
bool getUPnPEnabled();
bool getDHTEnabled();
void setOwnNetConfig(uint32_t netMode, uint32_t visState);
bool setLocalAddress(std::string id, struct sockaddr_in addr);
bool setExtAddress(std::string id, struct sockaddr_in addr);
bool setNetworkMode(std::string id, uint32_t netMode);
bool setVisState(std::string id, uint32_t visState);
/* add/remove friends */
bool addFriend(std::string);
bool addFriend(std::string id, uint32_t netMode = RS_NET_MODE_UDP,
uint32_t visState = RS_VIS_STATE_STD , time_t lastContact = 0);
bool removeFriend(std::string);
bool addNeighbour(std::string);

View File

@ -47,6 +47,10 @@
int getPQIsearchId();
int fixme(char *str, int n);
#if 0 /* removing old stuff */
struct chan_id
{
int route[10];
@ -200,6 +204,7 @@ private:
std::list<std::string> groups;
};
#endif /* removing old stuff */
class RateInterface
{
@ -377,9 +382,10 @@ virtual ~NetBinInterface() { return; }
};
#define CHAN_SIGN_SIZE 16
#define CERTSIGNLEN 16
#define PQI_PEERID_LENGTH 16
#define CERTSIGNLEN 16 /* actual byte length of signature */
#define PQI_PEERID_LENGTH 32 /* When expanded into a string */
#if 0
class certsign
{
public:
@ -421,5 +427,8 @@ const int PQI_FI_SUBTYPE_ERROR = 8;
const int PQI_FD_FLAG_ENDSTREAM = 1;
#endif /* removing old stuff */
#endif // PQI_BASE_ITEM_HEADER

View File

@ -55,7 +55,7 @@ struct pqiarchive_header
uint32_t type;
uint32_t length;
uint32_t ts;
uint8_t personSig[CERTSIGNLEN];
uint8_t personSig[PQI_PEERID_LENGTH];
};
const int PQIARCHIVE_TYPE_PQITEM = 0x0001;

View File

@ -298,7 +298,7 @@ int pqihandler::GetItems()
// check security... is output allowed.
if(0 < secpolicy_check((it -> second) -> sp,
PQI_ITEM_TYPE_ITEM, PQI_INCOMING))
0, PQI_INCOMING)) // PQI_ITEM_TYPE_ITEM, PQI_INCOMING))
{
// if yes... attempt to read.
while((item = (mod -> pqi) -> GetItem()) != NULL)

View File

@ -36,15 +36,15 @@
class Indicator
{
public:
Indicator(int n = 1)
Indicator(uint16_t n = 1)
:num(n), changeFlags(n) {IndicateChanged();}
void IndicateChanged()
{
for(int i = 0; i < num; i++)
for(uint16_t i = 0; i < num; i++)
changeFlags[i]=true;
}
bool Changed(int idx = 0)
bool Changed(uint16_t idx = 0)
{
/* catch overflow */
if (idx > num - 1)
@ -56,7 +56,7 @@ bool Changed(int idx = 0)
}
private:
int num;
uint16_t num;
std::vector<bool> changeFlags;
};

View File

@ -46,13 +46,6 @@ int errno;
#endif
void sockaddr_clear(struct sockaddr_in *addr)
{
memset(addr, 0, sizeof(struct sockaddr_in));
addr->sin_family = AF_INET;
}
/********************************** WINDOWS/UNIX SPECIFIC PART ******************/
#ifndef WINDOWS_SYS

View File

@ -97,8 +97,6 @@ extern int errno; /* Define extern errno, to duplicate unix behaviour */
#include <string>
#include <list>
void sockaddr_clear(struct sockaddr_in *addr1);
// Same def - different functions...
std::ostream &showSocketError(std::ostream &out);

View File

@ -26,6 +26,7 @@
#include "util/rsnet.h"
#include "pqi/pqissl.h"
#include "pqi/pqinetwork.h"

View File

@ -256,7 +256,7 @@ virtual int ConfigSetIncomingDir( std::string dir ) = 0;
virtual int ConfigSetDataRates( int total, int indiv ) = 0;
virtual int ConfigSetBootPrompt( bool on ) = 0;
//virtual int ConfigSave( ) = 0;
virtual void ConfigFinalSave( ) = 0;
/****************************************/

View File

@ -45,6 +45,10 @@ const uint32_t RS_NETMODE_UDP = 0x0001;
const uint32_t RS_NETMODE_UPNP = 0x0002;
const uint32_t RS_NETMODE_EXT = 0x0003;
/* Visibility */
const uint32_t RS_VS_DHT_ON = 0x0001;
const uint32_t RS_VS_DISC_ON = 0x0002;
/* State */
const uint32_t RS_PEER_STATE_FRIEND = 0x0001;
const uint32_t RS_PEER_STATE_ONLINE = 0x0002;
@ -90,6 +94,7 @@ class RsPeerDetails
uint16_t extPort;
uint32_t netMode;
uint32_t visState;
/* basic stats */
uint32_t lastConnect; /* how long ago */
@ -129,6 +134,7 @@ virtual bool connectAttempt(std::string id) = 0;
virtual bool setLocalAddress(std::string id, std::string addr, uint16_t port) = 0;
virtual bool setExtAddress( std::string id, std::string addr, uint16_t port) = 0;
virtual bool setNetworkMode(std::string id, uint32_t netMode) = 0;
virtual bool setVisState(std::string id, uint32_t vis) = 0;
/* Auth Stuff */
virtual std::string GetRetroshareInvite() = 0;

View File

@ -331,3 +331,11 @@ int RsServer::UpdateAllConfig()
void RsServer::ConfigFinalSave()
{
/* force saving of transfers */
server->saveFileTransferStatus();
mConfigMgr->completeConfiguration();
}

View File

@ -26,6 +26,7 @@
#include "rsserver/p3face.h"
#include <sstream>
#include <sys/time.h>
#include <time.h>
@ -215,6 +216,23 @@ void RsServer::run()
/* Tick slow services */
mRanking->tick();
/* force saving test */
#if 0
std::string opt;
std::string val = "VALUE";
{
std::ostringstream out;
out << "SEC:" << lastSec;
opt = out.str();
}
mGeneralConfig->setSetting(opt, val);
#endif
mConfigMgr->tick(); /* saves stuff */
}
// every 60 loops (> 1 min)
@ -222,29 +240,14 @@ void RsServer::run()
{
loop = 0;
// save the config every 5 minutes.
if (min % 5 == 1)
{
//ConfigSave();
#ifdef PQI_USE_CHANNELS
/* hack to update for now
* Only occassionally - cos disabled
*/
// channel_list_ok = false;
// update_channels();
#endif
//std::cerr << "RsServer::run() UpdateAllFiles()" << std::endl;
//UpdateAllFiles();
}
/* force saving FileTransferStatus */
server->saveFileTransferStatus();
/* hour loop */
if (++min >= 60)
{
min = 0;
}
// update_dirlist();
}
// slow update tick as well.

View File

@ -454,15 +454,24 @@ int RsServer::StartupRetroShare(RsInit *config)
/**************************************************************************/
// set the directories for full configuration load.
mAuthMgr -> setConfigDirectories(config->basedir.c_str(), configCertDir.c_str());
//sslr -> loadCertificates(configConfFile.c_str());
// Load up Certificates, and Old Configuration (if present)
// Create Classes.
// filedex server.
server = new filedexserver();
server->setConfigDir(config->basedir.c_str());
std::string certConfigFile = config->basedir.c_str();
std::string certNeighDir = config->basedir.c_str();
if (certConfigFile != "")
{
certConfigFile += "/";
certNeighDir += "/";
}
certConfigFile += configConfFile;
certNeighDir += configCertDir;
/* if we've loaded an old format file! */
bool oldFormat = false;
std::map<std::string, std::string> oldConfigMap;
mAuthMgr -> setConfigDirectories(certConfigFile, certNeighDir);
((AuthXPGP *) mAuthMgr) -> loadCertificates(oldFormat, oldConfigMap);
@ -479,15 +488,36 @@ int RsServer::StartupRetroShare(RsInit *config)
CacheStrapper *mCacheStrapper = new CacheStrapper(ownId, queryPeriod);
ftfiler *mCacheTransfer = new ftfiler(mCacheStrapper);
p3ConfigMgr *mConfigMgr = new p3ConfigMgr(config->basedir, "rs-v0.4.cfg", "rs-v0.4.sgn");
SecurityPolicy *none = secpolicy_create();
pqih = new pqisslpersongrp(none, flags);
//pqih = new pqipersongrpDummy(none, flags);
// filedex server.
server = new filedexserver();
server->setConfigDir(config->basedir.c_str());
server->setSaveDir(config->homePath.c_str()); /* Default Save Dir - config will overwrite */
server->setSearchInterface(pqih, mAuthMgr, mConnMgr);
mConfigMgr = new p3ConfigMgr(config->basedir, "rs-v0.4.cfg", "rs-v0.4.sgn");
mGeneralConfig = new p3GeneralConfig();
// Setup Peer Interface.
rsPeers = new p3Peers(mConnMgr, mAuthMgr);
/* create Services */
ad = new p3disc(mAuthMgr, mConnMgr);
msgSrv = new p3MsgService(mConnMgr);
chatSrv = new p3ChatService(mConnMgr);
p3GameLauncher *gameLauncher = new p3GameLauncher();
pqih -> addService(ad);
pqih -> addService(msgSrv);
pqih -> addService(chatSrv);
pqih -> addService(gameLauncher);
/* so need to Monitor too! */
/**************************************************************************/
mConnMgr->setDhtMgr(mDhtMgr);
mConnMgr->setUpnpMgr(mUpnpMgr);
@ -496,15 +526,17 @@ int RsServer::StartupRetroShare(RsInit *config)
mConnMgr->addMonitor(pqih);
mConnMgr->addMonitor(mCacheStrapper);
/**************************************************************************/
mConfigMgr->addConfiguration(CONFIG_TYPE_FSERVER, server); //"server.cfg");
mConfigMgr->addConfiguration(CONFIG_TYPE_PEERS, mConnMgr);
mConnMgr->addMonitor(ad);
mConnMgr->addMonitor(msgSrv);
/**************************************************************************/
server->setSearchInterface(pqih, mAuthMgr, mConnMgr);
mConfigMgr->addConfiguration("server.cfg", server);
mConfigMgr->addConfiguration("peers.cfg", mConnMgr);
mConfigMgr->addConfiguration("general.cfg", mGeneralConfig);
mConfigMgr->addConfiguration("msgs.cfg", msgSrv);
/**************************************************************************/
/**************************************************************************/
@ -513,6 +545,25 @@ int RsServer::StartupRetroShare(RsInit *config)
mConfigMgr->loadConfiguration();
/**************************************************************************/
/* Hack Old Configuration into new System (first load only) */
/**************************************************************************/
if (oldFormat)
{
/* transfer all authenticated peers to friend list */
std::list<std::string> authIds;
mAuthMgr->getAuthenticatedList(authIds);
std::list<std::string>::iterator it;
for(it = authIds.begin(); it != authIds.end(); it++)
{
mConnMgr->addFriend(*it);
}
/* move other configuration options */
}
/**************************************************************************/
/* trigger generalConfig loading for classes that require it */
/**************************************************************************/
@ -607,25 +658,7 @@ int RsServer::StartupRetroShare(RsInit *config)
pqih->AddSearchModule(mod);
// Set Default Save Dir. pre-load
// Load from config will overwrite...
server->setSaveDir(config->homePath.c_str());
//server->load_config();
/* create Services */
ad = new p3disc(mAuthMgr, mConnMgr);
msgSrv = new p3MsgService(mConnMgr);
chatSrv = new p3ChatService(mConnMgr);
p3GameLauncher *gameLauncher = new p3GameLauncher();
pqih -> addService(ad);
pqih -> addService(msgSrv);
pqih -> addService(chatSrv);
pqih -> addService(gameLauncher);
/* so need to Monitor too! */
mConnMgr->addMonitor(ad);
/* create Cache Services */
std::string config_dir = config->basedir;

View File

@ -29,6 +29,7 @@
#include "server/filedexserver.h"
//#include "pqi/pqissl.h"
#include "pqi/p3cfgmgr.h"
#include "pqi/p3connmgr.h"
#include "pqi/pqipersongrp.h"
@ -246,7 +247,8 @@ virtual int ConfigSetIncomingDir( std::string dir );
virtual int ConfigSetDataRates( int total, int indiv );
virtual int ConfigSetBootPrompt( bool on );
//virtual int ConfigSave( );
virtual void ConfigFinalSave( );
private:
int UpdateAllConfig();
@ -275,6 +277,10 @@ int UpdateAllConfig();
/* caches (that need ticking) */
p3Ranking *mRanking;
/* Config */
p3ConfigMgr *mConfigMgr;
p3GeneralConfig *mGeneralConfig;
// Worker Data.....
};

View File

@ -234,7 +234,11 @@ bool p3Peers::getPeerDetails(std::string id, RsPeerDetails &d)
/* get from mConnectMgr */
peerConnectState pcs;
if (!mConnMgr->getFriendNetStatus(id, pcs))
if (id == mAuthMgr->OwnId())
{
mConnMgr->getOwnNetStatus(pcs);
}
else if (!mConnMgr->getFriendNetStatus(id, pcs))
{
if (!mConnMgr->getOthersNetStatus(id, pcs))
{
@ -256,7 +260,7 @@ bool p3Peers::getPeerDetails(std::string id, RsPeerDetails &d)
d.localPort = ntohs(pcs.localaddr.sin_port);
d.extAddr = inet_ntoa(pcs.serveraddr.sin_addr);
d.extPort = ntohs(pcs.serveraddr.sin_port);
d.lastConnect = 0;
d.lastConnect = pcs.lastcontact;
d.connectPeriod = 0;
/* Translate */
@ -269,8 +273,32 @@ bool p3Peers::getPeerDetails(std::string id, RsPeerDetails &d)
if (pcs.state & RS_PEER_S_CONNECTED)
d.state |= RS_PEER_STATE_CONNECTED;
d.netMode = 0;
// TODO if (pcs.type & RS_NET_CONN_TCP_EXTERNAL)
switch(pcs.netMode)
{
case RS_NET_MODE_EXT:
d.netMode = RS_NETMODE_EXT;
break;
case RS_NET_MODE_UDP:
d.netMode = RS_NETMODE_UDP;
break;
case RS_NET_MODE_UNKNOWN:
case RS_NET_MODE_ERROR:
case RS_NET_MODE_UPNP:
default:
d.netMode = RS_NETMODE_UPNP;
break;
}
d.visState = 0;
if (!(pcs.visState & RS_VIS_STATE_NODISC))
{
d.visState |= RS_VS_DISC_ON;
}
if (!(pcs.visState & RS_VIS_STATE_NODHT))
{
d.visState |= RS_VS_DHT_ON;
}
return true;
}
@ -372,16 +400,49 @@ bool p3Peers::setExtAddress(std::string id, std::string addr_str, uint16_t port
}
bool p3Peers::setNetworkMode(std::string id, uint32_t netMode)
bool p3Peers::setNetworkMode(std::string id, uint32_t extNetMode)
{
#ifdef P3PEERS_DEBUG
std::cerr << "p3Peers::setNetworkMode() " << id;
std::cerr << std::endl;
#endif
/* translate */
uint32_t netMode = 0;
switch(extNetMode)
{
case RS_NETMODE_UDP:
netMode = RS_NET_MODE_UDP;
break;
case RS_NETMODE_EXT:
netMode = RS_NET_MODE_EXT;
break;
default:
case RS_NETMODE_UPNP:
netMode = RS_NET_MODE_UPNP;
break;
}
return mConnMgr->setNetworkMode(id, netMode);
}
bool p3Peers::setVisState(std::string id, uint32_t extVisState)
{
#ifdef P3PEERS_DEBUG
std::cerr << "p3Peers::setVisState() " << id;
std::cerr << std::endl;
#endif
uint32_t visState = 0;
if (!(extVisState & RS_VS_DHT_ON))
visState |= RS_VIS_STATE_NODHT;
if (!(extVisState & RS_VS_DISC_ON))
visState |= RS_VIS_STATE_NODISC;
return mConnMgr->setVisState(id, visState);
}
/* Auth Stuff */
std::string p3Peers::GetRetroshareInvite()
{

View File

@ -61,6 +61,7 @@ virtual bool connectAttempt(std::string id);
virtual bool setLocalAddress(std::string id, std::string addr, uint16_t port);
virtual bool setExtAddress(std::string id, std::string addr, uint16_t port);
virtual bool setNetworkMode(std::string id, uint32_t netMode);
virtual bool setVisState(std::string id, uint32_t mode);
/* Auth Stuff */
virtual std::string GetRetroshareInvite();

View File

@ -477,71 +477,146 @@ RsConfigKeyValueSet *RsGeneralConfigSerialiser::deserialiseKeyValueSet(void *dat
}
/*************************************************************************/
RsPeerConfig::~RsPeerConfig()
{
return;
}
void RsPeerConfig::clear()
{
status = 0;
lastconn_ts = 0;
lastrecv_ts = 0;
nextconn_ts = 0;
nextconn_period = 0;
}
std::ostream &RsPeerConfig::print(std::ostream &out, uint16_t indent)
{
printRsItemBase(out, "RsPeerConfig", indent);
uint16_t int_Indent = indent + 2;
printIndent(out, int_Indent);
out << "status: " << status << std::endl;
printIndent(out, int_Indent);
out << "lastconn_ts: " << lastconn_ts << std::endl;
printIndent(out, int_Indent);
out << "lastrecv_ts: " << lastrecv_ts << std::endl;
printIndent(out, int_Indent);
out << "nextconn_ts: " << nextconn_ts << std::endl;
printIndent(out, int_Indent);
out << "nextconn_period: " << nextconn_period << std::endl;
return out;
}
/*************************************************************************/
/*************************************************************************/
/*************************************************************************/
/*************************************************************************/
RsPeerConfigSerialiser::~RsPeerConfigSerialiser()
{
return;
}
uint32_t RsPeerConfigSerialiser::size(RsItem *i)
uint32_t RsPeerConfigSerialiser::size(RsItem *i)
{
RsPeerNetItem *pni;
RsPeerStunItem *psi;
if (NULL != (pni = dynamic_cast<RsPeerNetItem *>(i)))
{
return sizeNet(pni);
}
else if (NULL != (psi = dynamic_cast<RsPeerStunItem *>(i)))
{
return sizeStun(psi);
}
return 0;
}
/* serialise the data to the buffer */
bool RsPeerConfigSerialiser::serialise(RsItem *i, void *data, uint32_t *pktsize)
{
RsPeerNetItem *pni;
RsPeerStunItem *psi;
if (NULL != (pni = dynamic_cast<RsPeerNetItem *>(i)))
{
return serialiseNet(pni, data, pktsize);
}
else if (NULL != (psi = dynamic_cast<RsPeerStunItem *>(i)))
{
return serialiseStun(psi, data, pktsize);
}
return false;
}
RsItem *RsPeerConfigSerialiser::deserialise(void *data, uint32_t *pktsize)
{
/* get the type and size */
uint32_t rstype = getRsItemId(data);
if ((RS_PKT_VERSION1 != getRsItemVersion(rstype)) ||
(RS_PKT_CLASS_CONFIG != getRsItemClass(rstype)) ||
(RS_PKT_TYPE_PEER_CONFIG != getRsItemType(rstype)))
{
std::cerr << "RsPeerConfigSerialiser::deserialise() Wrong Type" << std::endl;
return NULL; /* wrong type */
}
switch(getRsItemSubType(rstype))
{
case RS_PKT_SUBTYPE_PEER_NET:
return deserialiseNet(data, pktsize);
break;
case RS_PKT_SUBTYPE_PEER_STUN:
return deserialiseStun(data, pktsize);
break;
default:
return NULL;
break;
}
return NULL;
}
/*************************************************************************/
RsPeerNetItem::~RsPeerNetItem()
{
return;
}
void RsPeerNetItem::clear()
{
pid.clear();
netMode = 0;
visState = 0;
lastContact = 0;
sockaddr_clear(&localaddr);
sockaddr_clear(&remoteaddr);
}
std::ostream &RsPeerNetItem::print(std::ostream &out, uint16_t indent)
{
printRsItemBase(out, "RsPeerNetItem", indent);
uint16_t int_Indent = indent + 2;
printIndent(out, int_Indent);
out << "PeerId: " << pid << std::endl;
printIndent(out, int_Indent);
out << "netMode: " << netMode << std::endl;
printIndent(out, int_Indent);
out << "visState: " << visState << std::endl;
printIndent(out, int_Indent);
out << "lastContact: " << lastContact << std::endl;
printIndent(out, int_Indent);
out << "localaddr: " << inet_ntoa(localaddr.sin_addr);
out << ":" << htons(localaddr.sin_port) << std::endl;
printIndent(out, int_Indent);
out << "remoteaddr: " << inet_ntoa(remoteaddr.sin_addr);
out << ":" << htons(remoteaddr.sin_port) << std::endl;
printRsItemEnd(out, "RsPeerNetItem", indent);
return out;
}
/*************************************************************************/
uint32_t RsPeerConfigSerialiser::sizeNet(RsPeerNetItem *i)
{
uint32_t s = 8; /* header */
s += 2; /* status */
s += 2; /* lastconnect_ts */
s += 2; /* lastrecv_ts */
s += 2; /* nextconn_ts */
s += 2; /* nextperiod */
s += GetTlvStringSize(i->pid); /* peerid */
s += 4; /* netMode */
s += 4; /* visState */
s += 4; /* lastContact */
s += GetTlvIpAddrPortV4Size(); /* localaddr */
s += GetTlvIpAddrPortV4Size(); /* remoteaddr */
return s;
}
bool RsPeerConfigSerialiser::serialise(RsItem *i, void *data, uint32_t *size)
bool RsPeerConfigSerialiser::serialiseNet(RsPeerNetItem *item, void *data, uint32_t *size)
{
RsPeerConfig *item = (RsPeerConfig *) i;
uint32_t tlvsize = RsPeerConfigSerialiser::size(item);
uint32_t tlvsize = RsPeerConfigSerialiser::sizeNet(item);
uint32_t offset = 0;
if(*size < tlvsize)
@ -555,24 +630,30 @@ bool RsPeerConfigSerialiser::serialise(RsItem *i, void *data, uint32_t *size)
ok &= setRsItemHeader(data, tlvsize, item->PacketId(), tlvsize);
std::cerr << "RsConfigSerialiser::serialise() Header: " << ok << std::endl;
std::cerr << "RsConfigSerialiser::serialise() Header: " << tlvsize << std::endl;
std::cerr << "RsPeerConfigSerialiser::serialiseNet() Header: " << ok << std::endl;
std::cerr << "RsPeerConfigSerialiser::serialiseNet() Header: " << tlvsize << std::endl;
/* skip the header */
offset += 8;
/* add mandatory parts first */
ok &= setRawUInt32(data, tlvsize, &offset, item->lastconn_ts); /* Mandatory */
std::cerr << "RsPeerConfigSerialiser::serialise() lastconn_ts: " << ok << std::endl; /* WRITE error check */
ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_PEERID, item->pid); /* Mandatory */
std::cerr << "RsPeerConfigSerialiser::serialiseNet() pid: " << ok << std::endl;
ok &= setRawUInt32(data, tlvsize, &offset, item->lastrecv_ts); /* Mandatory */
std::cerr << "RsPeerConfigSerialiser::serialise() lastrecv_ts: " << ok << std::endl;
ok &= setRawUInt32(data, tlvsize, &offset, item->netMode); /* Mandatory */
std::cerr << "RsPeerConfigSerialiser::serialiseNet() netMode: " << ok << std::endl;
ok &= setRawUInt32(data, tlvsize, &offset, item->nextconn_ts); /* Mandatory */
std::cerr << "RsPeerConfigSerialiser::serialise() nextconn_ts: " << ok << std::endl;
ok &= setRawUInt32(data, tlvsize, &offset, item->visState); /* Mandatory */
std::cerr << "RsPeerConfigSerialiser::serialiseNet() visState: " << ok << std::endl;
ok &= setRawUInt32(data, tlvsize, &offset, item->nextconn_period); /* Mandatory */
std::cerr << "RsPeerConfigSerialiser::serialise() nextconn_period: " << ok << std::endl;
ok &= setRawUInt32(data, tlvsize, &offset, item->lastContact); /* Mandatory */
std::cerr << "RsPeerConfigSerialiser::serialiseNet() lastContact: " << ok << std::endl;
ok &= SetTlvIpAddrPortV4(data, tlvsize, &offset, TLV_TYPE_IPV4_LOCAL, &(item->localaddr));
std::cerr << "RsPeerConfigSerialiser::serialiseNet() localaddr: " << ok << std::endl;
ok &= SetTlvIpAddrPortV4(data, tlvsize, &offset, TLV_TYPE_IPV4_REMOTE, &(item->remoteaddr));
std::cerr << "RsPeerConfigSerialiser::serialiseNet() remoteaddr: " << ok << std::endl;
if(offset != tlvsize)
{
@ -584,7 +665,7 @@ bool RsPeerConfigSerialiser::serialise(RsItem *i, void *data, uint32_t *size)
}
RsItem *RsPeerConfigSerialiser::deserialise(void *data, uint32_t *size)
RsPeerNetItem *RsPeerConfigSerialiser::deserialiseNet(void *data, uint32_t *size)
{
/* get the type and size */
uint32_t rstype = getRsItemId(data);
@ -596,7 +677,7 @@ RsItem *RsPeerConfigSerialiser::deserialise(void *data, uint32_t *size)
if ((RS_PKT_VERSION1 != getRsItemVersion(rstype)) ||
(RS_PKT_CLASS_CONFIG != getRsItemClass(rstype)) ||
(RS_PKT_TYPE_PEER_CONFIG != getRsItemType(rstype)) ||
(RS_PKT_SUBTYPE_DEFAULT != getRsItemSubType(rstype)))
(RS_PKT_SUBTYPE_PEER_NET != getRsItemSubType(rstype)))
{
return NULL; /* wrong type */
}
@ -609,25 +690,30 @@ RsItem *RsPeerConfigSerialiser::deserialise(void *data, uint32_t *size)
bool ok = true;
RsPeerConfig *item = new RsPeerConfig();
RsPeerNetItem *item = new RsPeerNetItem();
item->clear();
/* skip the header */
offset += 8;
/* get mandatory parts first */
ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_PEERID, item->pid); /* Mandatory */
std::cerr << "RsPeerConfigSerialiser::deserialiseNet() pid: " << ok << std::endl;
ok &= getRawUInt32(data, rssize, &offset, &(item->lastconn_ts));
std::cerr << "RsFileTransferSerialiser::deserilise() lastconn_ts: " << ok << std::endl;
ok &= getRawUInt32(data, rssize, &offset, &(item->netMode)); /* Mandatory */
std::cerr << "RsPeerConfigSerialiser::deserialiseNet() netMode: " << ok << std::endl;
ok &= getRawUInt32(data, rssize, &offset, &(item->lastconn_ts));
std::cerr << "RsFileTransferSerialiser::deserilise() lastrecv_ts: " << ok << std::endl;
ok &= getRawUInt32(data, rssize, &offset, &(item->visState)); /* Mandatory */
std::cerr << "RsPeerConfigSerialiser::deserialiseNet() visState: " << ok << std::endl;
ok &= getRawUInt32(data, rssize, &offset, &(item->lastconn_ts));
std::cerr << "RsFileTransferSerialiser::deserilise() nextconn_ts: " << ok << std::endl;
ok &= getRawUInt32(data, rssize, &offset, &(item->lastContact)); /* Mandatory */
std::cerr << "RsPeerConfigSerialiser::deserialiseNet() lastContact: " << ok << std::endl;
ok &= getRawUInt32(data, rssize, &offset, &(item->lastconn_ts));
std::cerr << "RsFileTransferSerialiser::deserilise() nextconn_period: " << ok << std::endl;
ok &= GetTlvIpAddrPortV4(data, rssize, &offset, TLV_TYPE_IPV4_LOCAL, &(item->localaddr));
std::cerr << "RsPeerConfigSerialiser::deserialiseNet() localaddr: " << ok << std::endl;
ok &= GetTlvIpAddrPortV4(data, rssize, &offset, TLV_TYPE_IPV4_REMOTE, &(item->remoteaddr));
std::cerr << "RsPeerConfigSerialiser::deserialiseNet() remoteaddr: " << ok << std::endl;
if (offset != rssize)
{
@ -640,6 +726,123 @@ RsItem *RsPeerConfigSerialiser::deserialise(void *data, uint32_t *size)
return item;
}
/****************************************************************************/
RsPeerStunItem::~RsPeerStunItem()
{
return;
}
void RsPeerStunItem::clear()
{
stunList.TlvClear();
}
std::ostream &RsPeerStunItem::print(std::ostream &out, uint16_t indent)
{
printRsItemBase(out, "RsPeerStunItem", indent);
uint16_t int_Indent = indent + 2;
stunList.print(out, int_Indent);
printRsItemEnd(out, "RsPeerStunItem", indent);
return out;
}
/*************************************************************************/
uint32_t RsPeerConfigSerialiser::sizeStun(RsPeerStunItem *i)
{
uint32_t s = 8; /* header */
s += i->stunList.TlvSize(); /* stunList */
return s;
}
bool RsPeerConfigSerialiser::serialiseStun(RsPeerStunItem *item, void *data, uint32_t *size)
{
uint32_t tlvsize = RsPeerConfigSerialiser::sizeStun(item);
uint32_t offset = 0;
if(*size < tlvsize)
return false; /* not enough space */
*size = tlvsize;
bool ok = true;
// serialise header
ok &= setRsItemHeader(data, tlvsize, item->PacketId(), tlvsize);
std::cerr << "RsPeerConfigSerialiser::serialiseStun() Header: " << ok << std::endl;
std::cerr << "RsPeerConfigSerialiser::serialiseStun() Header: " << tlvsize << std::endl;
/* skip the header */
offset += 8;
/* add mandatory parts first */
ok &= item->stunList.SetTlv(data, tlvsize, &offset); /* Mandatory */
std::cerr << "RsPeerConfigSerialiser::serialiseStun() stunList: " << ok << std::endl;
if(offset != tlvsize)
{
ok = false;
std::cerr << "RsPeerConfigSerialiser::serialiseStun() Size Error! " << std::endl;
}
return ok;
}
RsPeerStunItem *RsPeerConfigSerialiser::deserialiseStun(void *data, uint32_t *size)
{
/* get the type and size */
uint32_t rstype = getRsItemId(data);
uint32_t rssize = getRsItemSize(data);
uint32_t offset = 0;
if ((RS_PKT_VERSION1 != getRsItemVersion(rstype)) ||
(RS_PKT_CLASS_CONFIG != getRsItemClass(rstype)) ||
(RS_PKT_TYPE_PEER_CONFIG != getRsItemType(rstype)) ||
(RS_PKT_SUBTYPE_PEER_STUN != getRsItemSubType(rstype)))
{
return NULL; /* wrong type */
}
if (*size < rssize) /* check size */
return NULL; /* not enough data */
/* set the packet length */
*size = rssize;
bool ok = true;
RsPeerStunItem *item = new RsPeerStunItem();
item->clear();
/* skip the header */
offset += 8;
/* get mandatory parts first */
ok &= item->stunList.GetTlv(data, rssize, &offset); /* Mandatory */
std::cerr << "RsPeerConfigSerialiser::deserialiseStun() stunList: " << ok << std::endl;
if (offset != rssize)
{
/* error */
delete item;
return NULL;
}
return item;
}
/****************************************************************************/

View File

@ -40,35 +40,48 @@ const uint8_t RS_PKT_TYPE_FILE_CONFIG = 0x04;
/* GENERAL CONFIG SUBTYPES */
const uint8_t RS_PKT_SUBTYPE_KEY_VALUE = 0x01;
/* PEER CONFIG SUBTYPES */
const uint8_t RS_PKT_SUBTYPE_PEER_NET = 0x01;
const uint8_t RS_PKT_SUBTYPE_PEER_STUN = 0x02;
/**************************************************************************/
class RsPeerConfig: public RsItem
class RsPeerNetItem: public RsItem
{
public:
RsPeerConfig()
RsPeerNetItem()
:RsItem(RS_PKT_VERSION1, RS_PKT_CLASS_CONFIG,
RS_PKT_TYPE_PEER_CONFIG,
RS_PKT_SUBTYPE_DEFAULT)
RS_PKT_SUBTYPE_PEER_NET)
{ return; }
virtual ~RsPeerConfig();
virtual ~RsPeerNetItem();
virtual void clear();
std::ostream &print(std::ostream &out, uint16_t indent = 0);
//RsTlvPeerId peerid; /* Mandatory */
//RsTlvPeerFingerprint fpr; /* Mandatory */
/* networking information */
std::string pid; /* Mandatory */
uint32_t netMode; /* Mandatory */
uint32_t visState; /* Mandatory */
uint32_t lastContact; /* Mandatory */
//struct sockaddr_in lastaddr; /* Mandatory */
//struct sockaddr_in localaddr; /* Mandatory */
//struct sockaddr_in serveraddr; /* Mandatory */
uint32_t status; /* Mandatory */
uint32_t lastconn_ts; /* Mandatory */
uint32_t lastrecv_ts; /* Mandatory */
uint32_t nextconn_ts; /* Mandatory */
uint32_t nextconn_period; /* Mandatory */
struct sockaddr_in localaddr; /* Mandatory */
struct sockaddr_in remoteaddr; /* Mandatory */
};
class RsPeerStunItem: public RsItem
{
public:
RsPeerStunItem()
:RsItem(RS_PKT_VERSION1, RS_PKT_CLASS_CONFIG,
RS_PKT_TYPE_PEER_CONFIG,
RS_PKT_SUBTYPE_PEER_STUN)
{ return; }
virtual ~RsPeerStunItem();
virtual void clear();
std::ostream &print(std::ostream &out, uint16_t indent = 0);
RsTlvPeerIdSet stunList; /* Mandatory */
};
class RsPeerConfigSerialiser: public RsSerialType
{
@ -84,8 +97,21 @@ virtual uint32_t size(RsItem *);
virtual bool serialise (RsItem *item, void *data, uint32_t *size);
virtual RsItem * deserialise(void *data, uint32_t *size);
private:
virtual uint32_t sizeNet(RsPeerNetItem *);
virtual bool serialiseNet (RsPeerNetItem *item, void *data, uint32_t *size);
virtual RsPeerNetItem *deserialiseNet(void *data, uint32_t *size);
virtual uint32_t sizeStun(RsPeerStunItem *);
virtual bool serialiseStun (RsPeerStunItem *item, void *data, uint32_t *size);
virtual RsPeerStunItem * deserialiseStun(void *data, uint32_t *size);
};
/**************************************************************************/
/**************************************************************************/
/**************************************************************************/
class RsCacheConfig: public RsItem

View File

@ -179,7 +179,7 @@ bool RsDiscSerialiser::serialiseItem(RsDiscItem *item, void *data, uint32_t
TLV_TYPE_IPV4_LOCAL, &(item->laddr));
std::cerr << "RsDiscSerialiser::serialiseItem() laddress: " << ok << std::endl;
ok &= SetTlvIpAddrPortV4(data, tlvsize, &offset,
TLV_TYPE_IPV4_SERVER, &(item->saddr));
TLV_TYPE_IPV4_REMOTE, &(item->saddr));
std::cerr << "RsDiscSerialiser::serialiseItem() saddress: " << ok << std::endl;
ok &= setRawUInt16(data, tlvsize, &offset, item->contact_tf);
std::cerr << "RsDiscSerialiser::serialiseItem() contact_tf: " << ok << std::endl;
@ -235,7 +235,7 @@ RsDiscItem *RsDiscSerialiser::deserialiseItem(void *data, uint32_t *pktsize)
TLV_TYPE_IPV4_LOCAL, &(item->laddr));
std::cerr << "RsDiscSerialiser::deserialiseItem() laddress: " << ok << std::endl;
ok &= GetTlvIpAddrPortV4(data, rssize, &offset,
TLV_TYPE_IPV4_SERVER, &(item->saddr));
TLV_TYPE_IPV4_REMOTE, &(item->saddr));
std::cerr << "RsDiscSerialiser::deserialiseItem() saddress: " << ok << std::endl;
ok &= getRawUInt16(data, rssize, &offset, &(item->contact_tf));
std::cerr << "RsDiscSerialiser::deserialiseItem() contact_tf: " << ok << std::endl;
@ -347,7 +347,7 @@ bool RsDiscSerialiser::serialiseReply(RsDiscReply *item, void *data, uint32_
TLV_TYPE_IPV4_LOCAL, &(item->laddr));
std::cerr << "RsDiscSerialiser::serialiseReply() laddress: " << ok << std::endl;
ok &= SetTlvIpAddrPortV4(data, tlvsize, &offset,
TLV_TYPE_IPV4_SERVER, &(item->saddr));
TLV_TYPE_IPV4_REMOTE, &(item->saddr));
std::cerr << "RsDiscSerialiser::serialiseReply() saddress: " << ok << std::endl;
ok &= setRawUInt16(data, tlvsize, &offset, item->contact_tf);
std::cerr << "RsDiscSerialiser::serialiseReply() contact_tf: " << ok << std::endl;
@ -410,7 +410,7 @@ RsDiscReply *RsDiscSerialiser::deserialiseReply(void *data, uint32_t *pktsize)
TLV_TYPE_IPV4_LOCAL, &(item->laddr));
std::cerr << "RsDiscSerialiser::deserialiseReply() laddress: " << ok << std::endl;
ok &= GetTlvIpAddrPortV4(data, rssize, &offset,
TLV_TYPE_IPV4_SERVER, &(item->saddr));
TLV_TYPE_IPV4_REMOTE, &(item->saddr));
std::cerr << "RsDiscSerialiser::deserialiseReply() saddress: " << ok << std::endl;
ok &= getRawUInt16(data, rssize, &offset, &(item->contact_tf));
std::cerr << "RsDiscSerialiser::deserialiseReply() contact_tf: " << ok << std::endl;

View File

@ -126,7 +126,7 @@ const uint16_t TLV_TYPE_STR_HASH_SHA1 = 0x0070;
const uint16_t TLV_TYPE_STR_HASH_ED2K = 0x0071;
const uint16_t TLV_TYPE_IPV4_LOCAL = 0x0080;
const uint16_t TLV_TYPE_IPV4_SERVER = 0x0081;
const uint16_t TLV_TYPE_IPV4_REMOTE = 0x0081;
const uint16_t TLV_TYPE_IPV4_LAST = 0x0082;

View File

@ -23,21 +23,6 @@
*
*/
/* So this is a test pqi server.....
*
* the idea is that this holds some
* random data....., and responds to
* requests of a pqihandler.
*
*/
// as it is a simple test...
// don't make anything hard to do.
//
#include "server/filedexserver.h"
#include <fstream>
#include <time.h>
@ -68,11 +53,13 @@
const int fldxsrvrzone = 47659;
#define SERVER_DEBUG 1
filedexserver::filedexserver()
:p3Config(0, "server.cfg"),
:p3Config(CONFIG_TYPE_FSERVER),
pqisi(NULL), mAuthMgr(NULL), mConnMgr(NULL),
save_dir("."),
ftFiler(NULL)
mCacheStrapper(NULL), ftFiler(NULL), fiStore(NULL), fimon(NULL)
{
initialiseFileStore();
}
@ -153,7 +140,10 @@ std::string filedexserver::getSaveDir()
void filedexserver::setSaveDir(std::string d)
{
save_dir = d;
ftFiler -> setSaveBasePath(save_dir);
if (ftFiler)
ftFiler -> setSaveBasePath(save_dir);
IndicateConfigChanged(); /**** INDICATE MSG CONFIG CHANGED! *****/
}
@ -165,12 +155,16 @@ bool filedexserver::getSaveIncSearch()
void filedexserver::setSaveIncSearch(bool v)
{
save_inc = v;
IndicateConfigChanged(); /**** INDICATE MSG CONFIG CHANGED! *****/
}
int filedexserver::addSearchDirectory(std::string dir)
{
dbase_dirs.push_back(dir);
reScanDirs();
IndicateConfigChanged(); /**** INDICATE MSG CONFIG CHANGED! *****/
return 1;
}
@ -185,6 +179,8 @@ int filedexserver::removeSearchDirectory(std::string dir)
}
reScanDirs();
IndicateConfigChanged(); /**** INDICATE MSG CONFIG CHANGED! *****/
return 1;
}
@ -196,7 +192,8 @@ std::list<std::string> &filedexserver::getSearchDirectories()
int filedexserver::reScanDirs()
{
fimon->setSharedDirectories(dbase_dirs);
if (fimon)
fimon->setSharedDirectories(dbase_dirs);
return 1;
}
@ -281,6 +278,25 @@ void filedexserver::setFileCallback(std::string ownId, CacheStrapper *strappe
fimon->setSharedDirectories(dbase_dirs);
fimon->start();
std::list<RsFileTransfer *>::iterator tit;
for(tit = mResumeTransferList.begin();
tit != mResumeTransferList.end(); tit++)
{
RsFileTransfer *rsft = (*tit);
/* only add in ones which have a hash (filters old versions) */
if (rsft->file.hash != "")
{
ftFiler -> getFile(
rsft->file.name,
rsft->file.hash,
rsft->file.filesize, "");
}
delete rsft;
}
mResumeTransferList.clear();
}
int filedexserver::FileCacheSave()
@ -318,24 +334,37 @@ int filedexserver::FileCacheSave()
return 1;
}
// Transfer control.
void filedexserver::saveFileTransferStatus()
{
IndicateConfigChanged(); /**** INDICATE MSG CONFIG CHANGED! *****/
}
// Transfer control.
int filedexserver::getFile(std::string fname, std::string hash,
uint32_t size, std::string dest)
{
// send to filer.
return ftFiler -> getFile(fname, hash, size, dest);
int ret = ftFiler -> getFile(fname, hash, size, dest);
IndicateConfigChanged(); /**** INDICATE MSG CONFIG CHANGED! *****/
return ret;
}
void filedexserver::clear_old_transfers()
{
ftFiler -> clearFailedTransfers();
IndicateConfigChanged(); /**** INDICATE MSG CONFIG CHANGED! *****/
}
void filedexserver::cancelTransfer(std::string fname, std::string hash, uint32_t size)
{
ftFiler -> cancelFile(hash);
IndicateConfigChanged(); /**** INDICATE MSG CONFIG CHANGED! *****/
}
@ -719,7 +748,7 @@ std::list<RsItem *> filedexserver::saveList(bool &cleanup)
{
RsTlvKeyValue kv;
kv.key = mit->first;
kv.value = mit->first;
kv.value = mit->second;
rskv->tlvkvs.pairs.push_back(kv);
}
@ -759,6 +788,11 @@ bool filedexserver::loadList(std::list<RsItem *> load)
RsConfigKeyValueSet *rskv;
RsFileTransfer *rsft;
#ifdef SERVER_DEBUG
std::cerr << "filedexserver::loadList() Item Count: " << load.size();
std::cerr << std::endl;
#endif
for(it = load.begin(); it != load.end(); it++)
{
/* switch on type */
@ -767,27 +801,26 @@ bool filedexserver::loadList(std::list<RsItem *> load)
/* make into map */
std::map<std::string, std::string> configMap;
for(kit = rskv->tlvkvs.pairs.begin();
kit != rskv->tlvkvs.pairs.begin(); kit++)
kit != rskv->tlvkvs.pairs.end(); kit++)
{
configMap[kit->key] = kit->value;
}
loadConfigMap(configMap);
/* cleanup */
delete (*it);
}
else if (NULL != (rsft = dynamic_cast<RsFileTransfer *>(*it)))
{
/* only add in ones which have a hash (filters old versions) */
if (rsft->file.hash != "")
{
ftFiler -> getFile(
rsft->file.name,
rsft->file.hash,
rsft->file.filesize, "");
}
/* save to the preLoad list */
mResumeTransferList.push_back(rsft);
}
else
{
/* cleanup */
delete (*it);
}
/* cleanup */
delete (*it);
}
return true;
@ -827,7 +860,7 @@ bool filedexserver::loadConfigMap(std::map<std::string, std::string> &configMap
name += '0'+d2;
name += '0'+d3;
if (configMap.end() != (mit = configMap.find(save_inc_ss)))
if (configMap.end() != (mit = configMap.find(name)))
{
dir = mit->second;
dbase_dirs.push_back(mit->second);

View File

@ -71,7 +71,7 @@ int setSearchInterface(P3Interface *si, p3AuthMgr *am, p3ConnectMgr *cm);
std::list<RsFileTransfer *> getTransfers();
// get files (obsolete?)
void saveFileTransferStatus();
int getFile(std::string fname, std::string hash,
uint32_t size, std::string dest);
void clear_old_transfers();
@ -173,6 +173,9 @@ void SendFileData(ftFileData *ftd, std::string pid);
ftfiler *ftFiler;
FileIndexStore *fiStore;
FileIndexMonitor *fimon;
/* Temp Transfer List (for loading config) */
std::list<RsFileTransfer *> mResumeTransferList;
};
#endif // MRK_PQI_FILEDEX_SERVER_HEADER

View File

@ -51,8 +51,8 @@ const int msgservicezone = 54319;
p3MsgService::p3MsgService(p3ConnectMgr *cm)
:p3Service(RS_SERVICE_TYPE_MSG), mConnMgr(cm),
msgChanged(1), mMsgUniqueId(1)
:p3Service(RS_SERVICE_TYPE_MSG), pqiConfig(CONFIG_TYPE_MSGS),
mConnMgr(cm), msgChanged(1), mMsgUniqueId(1)
{
addSerialType(new RsMsgSerialiser());
}
@ -102,7 +102,7 @@ int p3MsgService::tick()
*/
incomingMsgs();
checkOutgoingMessages();
//checkOutgoingMessages();
return 0;
}
@ -146,12 +146,19 @@ int p3MsgService::incomingMsgs()
imsg[mi->msgId] = mi;
msgChanged.IndicateChanged();
IndicateConfigChanged(); /**** INDICATE MSG CONFIG CHANGED! *****/
/**** STACK UNLOCKED ***/
}
return 1;
}
void p3MsgService::statusChange(const std::list<pqipeer> &plist)
{
/* should do it properly! */
checkOutgoingMessages();
}
int p3MsgService::checkOutgoingMessages()
{
/* iterate through the outgoing queue
@ -215,11 +222,18 @@ int p3MsgService::checkOutgoingMessages()
}
}
if (toErase.size() > 0)
{
IndicateConfigChanged(); /**** INDICATE MSG CONFIG CHANGED! *****/
}
return 0;
}
int p3MsgService::save_config()
bool p3MsgService::saveConfiguration()
{
std::list<std::string>::iterator it;
std::string empty("");
@ -230,14 +244,14 @@ int p3MsgService::save_config()
/* now we create a pqiarchive, and stream all the msgs into it
*/
std::string msgfile = Filename();
RsStackMutex stack(mMsgMtx); /********** STACK LOCKED MTX ******/
std::string statelog = config_dir + "/msgs.rst";
RsSerialiser *rss = new RsSerialiser();
rss->addSerialType(new RsMsgSerialiser());
BinFileInterface *out = new BinFileInterface((char *) statelog.c_str(), BIN_FLAGS_WRITEABLE);
BinFileInterface *out = new BinFileInterface(msgfile.c_str(), BIN_FLAGS_WRITEABLE | BIN_FLAGS_HASH_DATA);
pqiarchive *pa_out = new pqiarchive(rss, out, BIN_FLAGS_WRITEABLE | BIN_FLAGS_NO_DELETE);
bool written = false;
@ -253,8 +267,6 @@ int p3MsgService::save_config()
for(mit = msgOutgoing.begin(); mit != msgOutgoing.end(); mit++)
{
//RsMsgItem *mi = (*mit)->clone();
//mi -> msgFlags |= RS_MSG_FLAGS_PENDING;
if (pa_out -> SendItem(mit->second))
{
written = true;
@ -262,30 +274,26 @@ int p3MsgService::save_config()
}
setHash(out->gethash());
delete pa_out;
return 1;
return true;
}
int p3MsgService::load_config()
bool p3MsgService::loadConfiguration(std::string &loadHash)
{
std::list<std::string>::iterator it;
std::string empty("");
std::string dir("notempty");
std::string str_true("true");
/* load msg/ft */
std::string statelog = config_dir + "/msgs.rst";
std::string msgfile = Filename();
RsSerialiser *rss = new RsSerialiser();
rss->addSerialType(new RsMsgSerialiser());
BinFileInterface *in = new BinFileInterface((char *) statelog.c_str(), BIN_FLAGS_READABLE);
BinFileInterface *in = new BinFileInterface(msgfile.c_str(), BIN_FLAGS_READABLE | BIN_FLAGS_HASH_DATA);
pqiarchive *pa_in = new pqiarchive(rss, in, BIN_FLAGS_READABLE);
RsItem *item;
RsMsgItem *mitem;
RsStackMutex stack(mMsgMtx); /********** STACK LOCKED MTX ******/
while((item = pa_in -> GetItem()))
{
@ -298,6 +306,8 @@ int p3MsgService::load_config()
mitem->msgId = getNewUniqueMsgId();
if (mitem -> msgFlags & RS_MSG_FLAGS_PENDING)
{
RsStackMutex stack(mMsgMtx); /********** STACK LOCKED MTX ******/
std::cerr << "MSG_PENDING";
std::cerr << std::endl;
mitem->print(std::cerr);
@ -305,6 +315,8 @@ int p3MsgService::load_config()
}
else
{
RsStackMutex stack(mMsgMtx); /********** STACK LOCKED MTX ******/
imsg[mitem->msgId] = mitem;
}
}
@ -314,9 +326,23 @@ int p3MsgService::load_config()
}
}
std::string hashin = in->gethash();
if (hashin != loadHash)
{
/* big error message! */
std::cerr << "p3MsgService::loadConfiguration() FAILED!" << std::endl;
std::cerr << "p3MsgService::loadConfiguration() FAILED!" << std::endl;
std::cerr << "p3MsgService::loadConfiguration() FAILED!" << std::endl;
std::cerr << "p3MsgService::loadConfiguration() FAILED!" << std::endl;
std::cerr << "p3MsgService::loadConfiguration() FAILED!" << std::endl;
}
setHash(hashin);
delete pa_in;
return 1;
return true;
}
@ -423,6 +449,8 @@ bool p3MsgService::removeMsgId(std::string mid)
delete mi;
msgChanged.IndicateChanged();
IndicateConfigChanged(); /**** INDICATE MSG CONFIG CHANGED! *****/
return true;
}
@ -434,6 +462,8 @@ bool p3MsgService::removeMsgId(std::string mid)
delete mi;
msgChanged.IndicateChanged();
IndicateConfigChanged(); /**** INDICATE MSG CONFIG CHANGED! *****/
return true;
}
@ -466,6 +496,9 @@ int p3MsgService::sendMessage(RsMsgItem *item)
pqioutput(PQL_DEBUG_BASIC, msgservicezone,
"p3MsgService::sendMessage()");
item -> msgId = getNewUniqueMsgId(); /* grabs Mtx as well */
{
RsStackMutex stack(mMsgMtx); /********** STACK LOCKED MTX ******/
/* add pending flag */
@ -473,8 +506,12 @@ int p3MsgService::sendMessage(RsMsgItem *item)
(RS_MSG_FLAGS_OUTGOING |
RS_MSG_FLAGS_PENDING);
/* STORE MsgID */
item -> msgId = getNewUniqueMsgId();
msgOutgoing[item->msgId] = item;
}
IndicateConfigChanged(); /**** INDICATE MSG CONFIG CHANGED! *****/
checkOutgoingMessages();
return 1;
}

View File

@ -41,7 +41,7 @@
class p3ConnectMgr;
class p3MsgService: public p3Service
class p3MsgService: public p3Service, public pqiConfig, public pqiMonitor
{
public:
p3MsgService(p3ConnectMgr *cm);
@ -63,18 +63,22 @@ bool MessageSend(MessageInfo &info);
void loadWelcomeMsg(); /* startup message */
int checkOutgoingMessages();
std::list<RsMsgItem *> &getMsgList();
std::list<RsMsgItem *> &getMsgOutList();
int load_config();
int save_config();
//std::list<RsMsgItem *> &getMsgList();
//std::list<RsMsgItem *> &getMsgOutList();
int tick();
int status();
/*** Overloaded from pqiConfig ****/
virtual bool loadConfiguration(std::string &loadHash);
virtual bool saveConfiguration();
/*** Overloaded from pqiConfig ****/
/*** Overloaded from pqiMonitor ***/
virtual void statusChange(const std::list<pqipeer> &plist);
int checkOutgoingMessages();
/*** Overloaded from pqiMonitor ***/
private:
uint32_t getNewUniqueMsgId();

View File

@ -49,10 +49,15 @@ p3Ranking::p3Ranking(uint16_t type, CacheTransfer *cft,
CacheStore(type, true, cft, storedir),
mStorePeriod(storePeriod)
{
{ RsStackMutex stack(mRankMtx); /********** STACK LOCKED MTX ******/
mOwnId = getAuthMgr()->OwnId();
mViewPeriod = 60 * 60 * 24 * 30; /* one Month */
mSortType = RS_RANK_ALG;
} RsStackMutex stack(mRankMtx);
// createDummyData();
return;
}
@ -100,8 +105,14 @@ void p3Ranking::loadRankFile(std::string filename, std::string src)
pqistreamer *stream = new pqistreamer(rsSerialiser, src, bio, 0);
time_t now = time(NULL);
time_t min = now - mStorePeriod;
time_t max = now + RANK_MAX_FWD_OFFSET;
time_t min, max;
{ RsStackMutex stack(mRankMtx); /********** STACK LOCKED MTX ******/
min = now - mStorePeriod;
max = now + RANK_MAX_FWD_OFFSET;
} /********** STACK LOCKED MTX ******/
#ifdef RANK_DEBUG
std::cerr << "p3Ranking::loadRankFile()";
@ -192,6 +203,8 @@ void p3Ranking::publishMsgs()
pqistreamer *stream = new pqistreamer(rsSerialiser, mOwnId, bio,
BIN_FLAGS_NO_DELETE);
{ RsStackMutex stack(mRankMtx); /********** STACK LOCKED MTX ******/
/* iterate through list */
std::map<std::string, RankGroup>::iterator it;
for(it = mData.begin(); it != mData.end(); it++)
@ -223,11 +236,18 @@ void p3Ranking::publishMsgs()
}
}
} /********** STACK LOCKED MTX ******/
stream->tick(); /* Tick for final write! */
/* flag as new info */
CacheData data;
{ RsStackMutex stack(mRankMtx); /********** STACK LOCKED MTX ******/
data.pid = mOwnId;
} /********** STACK LOCKED MTX ******/
data.cid = CacheId(CacheSource::getCacheType(), 1);
data.path = path;
@ -272,6 +292,8 @@ void p3Ranking::addRankMsg(RsRankLinkMsg *msg)
std::cerr << std::endl;
#endif
RsStackMutex stack(mRankMtx); /********** STACK LOCKED MTX ******/
std::map<std::string, RankGroup>::iterator it;
it = mData.find(rid);
if (it == mData.end())
@ -328,7 +350,7 @@ void p3Ranking::addRankMsg(RsRankLinkMsg *msg)
mRepublish = true;
}
reSortGroup(it->second);
locked_reSortGroup(it->second);
}
}
@ -337,8 +359,14 @@ void p3Ranking::addRankMsg(RsRankLinkMsg *msg)
bool p3Ranking::setSortPeriod(uint32_t period)
{
bool reSort = (mViewPeriod != period);
mViewPeriod = period;
bool reSort = false;
{
RsStackMutex stack(mRankMtx); /********** STACK LOCKED MTX ******/
reSort = (mViewPeriod != period);
mViewPeriod = period;
}
if (reSort)
{
@ -350,8 +378,13 @@ bool p3Ranking::setSortPeriod(uint32_t period)
bool p3Ranking::setSortMethod(uint32_t type)
{
bool reSort = (mSortType != type);
mSortType = type;
bool reSort = false;
{
RsStackMutex stack(mRankMtx); /********** STACK LOCKED MTX ******/
reSort = (mSortType != type);
mSortType = type;
}
if (reSort)
{
@ -363,9 +396,14 @@ bool p3Ranking::setSortMethod(uint32_t type)
bool p3Ranking::clearPeerFilter()
{
bool reSort = (mPeerFilter.size() > 0);
bool reSort = false;
{
RsStackMutex stack(mRankMtx); /********** STACK LOCKED MTX ******/
reSort = (mPeerFilter.size() > 0);
mPeerFilter.clear();
}
mPeerFilter.clear();
if (reSort)
{
@ -377,7 +415,10 @@ bool p3Ranking::clearPeerFilter()
bool p3Ranking::setPeerFilter(std::list<std::string> peers)
{
mPeerFilter = peers;
{
RsStackMutex stack(mRankMtx); /********** STACK LOCKED MTX ******/
mPeerFilter = peers;
}
sortAllMsgs();
@ -507,10 +548,9 @@ float p3Ranking::locked_calcRank(RankGroup &grp)
}
void p3Ranking::reSortGroup(RankGroup &grp)
void p3Ranking::locked_reSortGroup(RankGroup &grp)
{
std::string rid = grp.rid;
//float rank = grp.rank;
/* remove from existings rankings */
std::multimap<float, std::string>::iterator rit;
@ -532,6 +572,8 @@ void p3Ranking::reSortGroup(RankGroup &grp)
void p3Ranking::sortAllMsgs()
{
RsStackMutex stack(mRankMtx); /********** STACK LOCKED MTX ******/
/* iterate through list and re-score each one */
std::map<std::string, RankGroup>::iterator it;
@ -554,11 +596,15 @@ void p3Ranking::sortAllMsgs()
/* get Ids */
uint32_t p3Ranking::getRankingsCount()
{
RsStackMutex stack(mRankMtx); /********** STACK LOCKED MTX ******/
return mRankings.size();
}
float p3Ranking::getMaxRank()
{
RsStackMutex stack(mRankMtx); /********** STACK LOCKED MTX ******/
if (mRankings.size() == 0)
return 0;
@ -567,6 +613,8 @@ float p3Ranking::getMaxRank()
bool p3Ranking::getRankings(uint32_t first, uint32_t count, std::list<std::string> &rids)
{
RsStackMutex stack(mRankMtx); /********** STACK LOCKED MTX ******/
uint32_t i = 0;
std::multimap<float, std::string>::reverse_iterator rit;
for(rit = mRankings.rbegin(); (i < first) && (rit != mRankings.rend()); rit++);
@ -579,9 +627,13 @@ bool p3Ranking::getRankings(uint32_t first, uint32_t count, std::list<std::st
return true;
}
bool p3Ranking::getRankDetails(std::string rid, RsRankDetails &details)
{
RsStackMutex stack(mRankMtx); /********** STACK LOCKED MTX ******/
/* get the details. */
std::map<std::string, RankGroup>::iterator it;
it = mData.find(rid);
if (mData.end() == it)
@ -613,9 +665,17 @@ bool p3Ranking::getRankDetails(std::string rid, RsRankDetails &details)
void p3Ranking::tick()
{
if (mRepublish)
bool repub = false;
{
RsStackMutex stack(mRankMtx); /********** STACK LOCKED MTX ******/
repub = mRepublish;
}
if (repub)
{
publishMsgs();
RsStackMutex stack(mRankMtx); /********** STACK LOCKED MTX ******/
mRepublish = false;
}
}
@ -633,7 +693,11 @@ std::string p3Ranking::newRankMsg(std::wstring link, std::wstring title, std::ws
time_t now = time(NULL);
msg->PeerId(mOwnId);
{
RsStackMutex stack(mRankMtx); /********** STACK LOCKED MTX ******/
msg->PeerId(mOwnId);
}
msg->rid = rid;
msg->title = title;
msg->timestamp = now;
@ -654,6 +718,9 @@ bool p3Ranking::updateComment(std::string rid, std::wstring comment)
std::cerr << "p3Ranking::updateComment() rid:" << rid;
std::cerr << std::endl;
#endif
RsRankLinkMsg *msg = NULL;
{ RsStackMutex stack(mRankMtx); /********** STACK LOCKED MTX ******/
std::map<std::string, RankGroup>::iterator it;
it = mData.find(rid);
@ -668,7 +735,7 @@ bool p3Ranking::updateComment(std::string rid, std::wstring comment)
return false;
}
RsRankLinkMsg *msg = new RsRankLinkMsg();
msg = new RsRankLinkMsg();
time_t now = time(NULL);
@ -681,6 +748,8 @@ bool p3Ranking::updateComment(std::string rid, std::wstring comment)
msg->linktype = RS_LINK_TYPE_WEB;
msg->link = (it->second).link;
} /********** STACK UNLOCKED MTX ******/
#ifdef RANK_DEBUG
std::cerr << "p3Ranking::updateComment() Item:";
std::cerr << std::endl;

View File

@ -105,8 +105,10 @@ void tick();
void loadRankFile(std::string filename, std::string src);
void addRankMsg(RsRankLinkMsg *msg);
void publishMsgs();
float locked_calcRank(RankGroup &grp); /* returns 0->100 */
void reSortGroup(RankGroup &grp);
void locked_reSortGroup(RankGroup &grp);
void sortAllMsgs();
pqistreamer *createStreamer(std::string file, std::string src, bool reading);
@ -114,6 +116,10 @@ pqistreamer *createStreamer(std::string file, std::string src, bool reading);
void createDummyData();
RsMutex mRankMtx;
/***** below here is locked *****/
bool mRepublish;
uint32_t mStorePeriod;

View File

@ -24,6 +24,8 @@
*/
#include "util/rsnet.h"
#include <string.h>
uint64_t ntohll(uint64_t x)
{
@ -52,4 +54,9 @@ uint64_t htonll(uint64_t x)
return ntohll(x);
}
void sockaddr_clear(struct sockaddr_in *addr)
{
memset(addr, 0, sizeof(struct sockaddr_in));
addr->sin_family = AF_INET;
}

View File

@ -55,4 +55,7 @@ typedef uint32_t in_addr_t;
uint64_t ntohll(uint64_t x);
uint64_t htonll(uint64_t x);
/* blank a network address */
void sockaddr_clear(struct sockaddr_in *addr);
#endif /* RS_UNIVERSAL_NETWORK_HEADER */