diff --git a/libretroshare/src/distrib/p3distrib.cc b/libretroshare/src/distrib/p3distrib.cc deleted file mode 100644 index ae574c039..000000000 --- a/libretroshare/src/distrib/p3distrib.cc +++ /dev/null @@ -1,3802 +0,0 @@ -/* - * libretroshare/src/distrib: p3distrib.h - * - * - * Copyright 2004-2011 by Robert Fernie. - * 2010-2011 Christopher Evi-Parker - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License Version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 - * USA. - * - * Please report all bugs and problems to "retroshare@lunamutt.com". - * - */ - -#ifdef WINDOWS_SYS -#include "util/rswin.h" -#endif - -#include -#include - -#include -#include -#include -#include -#include -#include - -#include "retroshare/rsdistrib.h" -#include "distrib/p3distrib.h" -#include "distrib/p3distribsecurity.h" -#include "serialiser/rsdistribitems.h" -#include "serialiser/rstlvkeys.h" - -#include "util/rsdir.h" -#include "pqi/pqinotify.h" -#include "pqi/pqibin.h" -#include "pqi/sslfns.h" -#include "pqi/authssl.h" -#include "pqi/authgpg.h" - -#include "retroshare/rspeers.h" // Needed for RsPeerDetails & Online List. (Should remove dependance) - -#define FAILED_CACHE_CONT "failedcachegrp" // cache id which have failed are stored under a node of this name/grpid -#define HIST_CACHE_FNAME "grp_history.xml" - -/*** - * #define ENABLE_CACHE_OPT 1 - ***/ - -/***** - * #define DISTRIB_DEBUG 1 - * #define DISTRIB_THREAD_DEBUG 1 - * #define DISTRIB_DUMMYMSG_DEBUG 1 - ****/ - -//#define DISTRIB_DEBUG 1 -//#define DISTRIB_THREAD_DEBUG 1 -//#define DISTRIB_DUMMYMSG_DEBUG 1 - - -GroupInfo::~GroupInfo() -{ - delete distribGroup ; - - for(std::map::const_iterator it(msgs.begin());it!=msgs.end();++it) - delete it->second ; - - for(std::map::const_iterator it(decrypted_msg_cache.begin());it!=decrypted_msg_cache.end();++it) - delete it->second ; -} - -p3GroupDistrib::p3GroupDistrib(uint16_t subtype, - CacheStrapper *cs, CacheTransfer *cft, - std::string sourcedir, std::string storedir, - std::string keyBackUpDir, uint32_t configId, - uint32_t storePeriod, uint32_t pubPeriod) - - :CacheSource(subtype, true, cs, sourcedir), - CacheStore(subtype, true, cs, cft, storedir), - p3Config(configId), p3ThreadedService(subtype), - mHistoricalCaches(true), distribMtx(""), - mStorePeriod(storePeriod), - mPubPeriod(pubPeriod), - mLastPublishTime(0), - mMaxCacheSubId(1), - mKeyBackUpDir(keyBackUpDir), BACKUP_KEY_FILE("key.log"), mLastKeyPublishTime(0), mLastRecvdKeyTime(0) -{ - /* force publication of groups (cleared if local cache file found) */ - mGroupsRepublish = true; - mGroupsChanged = true; - -#ifdef RSMUTEX_DEBUG - distribMtx.setName("p3GroupDistrib - " + keyBackUpDir.substr(keyBackUpDir.find_last_of('/') + 1)); -#endif - - mOwnId = AuthSSL::getAuthSSL()->OwnId(); - - addSerialType(new RsDistribSerialiser(getRsItemService(getType()))); - - return; -} - -p3GroupDistrib::~p3GroupDistrib() -{ - for(std::map::iterator it(mRecvdPubKeys.begin());it!=mRecvdPubKeys.end();++it) - delete it->second ; - - for(std::list::iterator it(mPendingPublish.begin());it!=mPendingPublish.end();++it) - delete *it ; -} - -int p3GroupDistrib::tick() -{ - -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::tick()"; - std::cerr << std::endl; -#endif - - time_t now = time(NULL); - bool toPublish; - - { - RsStackMutex stack(distribMtx); /**** STACK LOCKED MUTEX ****/ - - toPublish = ((mPendingPublish.size() > 0) || (mPendingPubKeyRecipients.size() > 0)) && (now > (time_t) (mPubPeriod + mLastPublishTime)); - } - - if (toPublish) - { - RsStackMutex stack(distribMtx); /**** STACK LOCKED MUTEX ****/ - - locked_publishPendingMsgs(); /* flags taken care of in here */ - } - - bool toPublishGroups; - { - RsStackMutex stack(distribMtx); /**** STACK LOCKED MUTEX ****/ - toPublishGroups = mGroupsRepublish; - } - - if (toPublishGroups) - { - publishDistribGroups(); - - IndicateConfigChanged(); /**** INDICATE CONFIG CHANGED! *****/ - - RsStackMutex stack(distribMtx); /**** STACK LOCKED MUTEX ****/ - mGroupsRepublish = false; - } - - bool attemptRecv = false; - - { - RsStackMutex stack(distribMtx); - toPublish = (mPendingPubKeyRecipients.size() > 0) && (now > (time_t) (mPubPeriod + mLastKeyPublishTime)); - attemptRecv = (mRecvdPubKeys.size() > 0); // attempt to load stored keys in case user has subscribed - } - - if(toPublish){ - RsStackMutex stack(distribMtx); - locked_sharePubKey(); - } - - - if(attemptRecv) - { - attemptPublishKeysRecvd(); - } - - bool toReceive = receivedItems(); - - if(toReceive){ - - receivePubKeys(); - } - - - return 0; -} - - -/***************************************************************************************/ -/***************************************************************************************/ - /********************** overloaded functions from Cache Store ******************/ -/***************************************************************************************/ -/***************************************************************************************/ - -int p3GroupDistrib::loadCache(const CacheData &data) -{ -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::loadCache()"; - std::cerr << std::endl; -#endif - - - RsStackMutex stack(distribMtx); - -#ifdef DISTRIB_THREAD_DEBUG - std::cerr << "p3GroupDistrib::loadCache() Storing PendingRemoteCache"; - std::cerr << std::endl; -#endif - - /* store the cache file for later processing */ - mPendingCaches.push_back(CacheDataPending(data, false, mHistoricalCaches)); - - if (data.size > 0) - { - CacheStore::lockData(); /***** LOCK ****/ - locked_storeCacheEntry(data); - CacheStore::unlockData(); /***** UNLOCK ****/ - } - - return 1; -} - -bool p3GroupDistrib::loadLocalCache(const CacheData &data) -{ -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::loadLocalCache()"; - std::cerr << std::endl; -#endif - - - RsStackMutex stack(distribMtx); - -#ifdef DISTRIB_THREAD_DEBUG - std::cerr << "p3GroupDistrib::loadCache() Storing PendingLocalCache"; - std::cerr << std::endl; -#endif - - /* store the cache file for later processing */ - mPendingCaches.push_back(CacheDataPending(data, true, mHistoricalCaches)); - - - if (data.size > 0) - { - refreshCache(data); - } - - return true; -} - - -/* Handle the Cache Pending Setup */ -CacheDataPending::CacheDataPending(const CacheData &data, bool local, bool historical) - :mData(data), mLocal(local), mHistorical(historical) -{ - return; -} - -bool p3GroupDistrib::isPeerAcceptedAsCacheProvider(const std::string& ssl_id) -{ - return rsPeers->servicePermissionFlags_sslid(ssl_id) & RS_SERVICE_PERM_DISTRIB ; -} - -bool p3GroupDistrib::isPeerAcceptedAsCacheReceiver(const std::string& ssl_id) -{ - return rsPeers->servicePermissionFlags_sslid(ssl_id) & RS_SERVICE_PERM_DISTRIB ; -} - -void p3GroupDistrib::HistoricalCachesDone() -{ - RsStackMutex stack(distribMtx); - std::string id; - mHistoricalCaches = false; // called when Stored Caches have been added to Pending List. -} - - /* From RsThread */ -void p3GroupDistrib::run() /* called once the thread is started */ -{ - -#ifdef DISTRIB_THREAD_DEBUG - std::cerr << "p3GroupDistrib::run()"; - std::cerr << std::endl; -#endif - -#ifdef DISTRIB_DUMMYMSG_DEBUG - int printed = 0; -#endif - CacheData cache; - while(isRunning()) - { - /* */ - - bool validCache = false; - bool isLocal = false; - bool isHistorical = false; - { - RsStackMutex stack(distribMtx); - - if (mPendingCaches.size() > 0) - { - CacheDataPending &pendingCache = mPendingCaches.front(); - cache = pendingCache.mData; - isLocal = pendingCache.mLocal; - isHistorical = pendingCache.mHistorical; - - validCache = true; - mPendingCaches.pop_front(); - -#ifdef DISTRIB_THREAD_DEBUG - std::cerr << "p3GroupDistrib::run() found pendingCache"; - std::cerr << std::endl; -#endif - - } - - } - if (validCache) - { - loadAnyCache(cache, isLocal, isHistorical); - -#ifndef WINDOWS_SYS - usleep(1000); -#else - Sleep(1); -#endif - } - else - { -#ifndef WINDOWS_SYS - sleep(1); -#else - Sleep(1000); -#endif - -#ifdef DISTRIB_DUMMYMSG_DEBUG - /* HACK for debugging */ - if (printed < 10) - { - RsStackMutex stack(distribMtx); - locked_printAllDummyMsgs(); - - printed++; - } -#endif - - } - } -} - - - -int p3GroupDistrib::loadAnyCache(const CacheData &data, bool local, bool historical) -{ - /* if subtype = 1 -> FileGroup, else -> FileMsgs */ - - std::string file = data.path; - file += "/"; - file += data.name; - -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::loadAnyCache() file: " << file << std::endl; - std::cerr << "PeerId: " << data.pid << std::endl; - std::cerr << "Cid: " << data.cid.type << ":" << data.cid.subid << std::endl; -#endif - - if (data.cid.subid == 1) - { - loadFileGroups(file, data.pid, local, historical); - } - else - { - loadFileMsgs(file, data, local, historical); - } - - return true; -} - -/***************************************************************************************/ -/***************************************************************************************/ - /********************** load Cache Files ***************************************/ -/***************************************************************************************/ -/***************************************************************************************/ - - -/* No need for special treatment for 'own' groups. - * configuration should be loaded before cache files. - */ -void p3GroupDistrib::loadFileGroups(const std::string &filename, const std::string &src, bool local, bool historical) -{ -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::loadFileGroups()"; - std::cerr << std::endl; -#endif - - /* create the serialiser to load info */ - BinInterface *bio = new BinFileInterface(filename.c_str(), BIN_FLAGS_READABLE); - pqistore *store = createStore(bio, src, BIN_FLAGS_READABLE); - -#ifdef DISTRIB_DEBUG - std::cerr << "loading file " << filename << std::endl ; -#endif - - RsItem *item; - RsDistribGrp *newGrp; - RsDistribGrpKey *newKey; - - while(NULL != (item = store->GetItem())) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::loadFileGroups() Got Item:"; - std::cerr << std::endl; - item->print(std::cerr, 10); - std::cerr << std::endl; -#endif - - newKey = dynamic_cast(item); - if ((newGrp = dynamic_cast(item))) - { - loadGroup(newGrp, historical); - } - else if ((newKey = dynamic_cast(item))) - { - loadGroupKey(newKey, historical); - } - else - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::loadFileGroups() Unexpected Item - deleting"; - std::cerr << std::endl; -#endif - delete item; - } - } - - delete store; - - if (local) - { - /* clear publication of groups if local cache file found */ - RsStackMutex stack(distribMtx); /******* STACK LOCKED MUTEX ***********/ - mGroupsRepublish = false; - } - - return; -} - -void p3GroupDistrib::loadFileMsgs(const std::string &filename, const CacheData& data, bool local, bool historical) -{ - -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::loadFileMsgs()"; - std::cerr << std::endl; -#endif - - uint16_t cacheSubId = data.cid.subid; - const std::string& src = data.pid; - uint32_t ts = data.recvd; - - time_t now = time(NULL); - - /* create the serialiser to load msgs */ - BinInterface *bio = new BinFileInterface(filename.c_str(), BIN_FLAGS_READABLE); - pqistore *store = createStore(bio, src, BIN_FLAGS_READABLE); - -#ifdef DISTRIB_DEBUG - std::cerr << "loading file " << filename << std::endl ; -#endif - - RsItem *item; - RsDistribSignedMsg *newMsg; - std::set grpAddedTo; - - while(isRunning() && (NULL != (item = store->GetItem()))) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::loadFileMsgs() Got Item:"; - std::cerr << std::endl; - item->print(std::cerr, 10); - std::cerr << std::endl; -#endif - - if ((newMsg = dynamic_cast(item))) - { - std::string& grpId = newMsg->grpId; - - bool ok; - { - RsStackMutex stack(distribMtx); - std::set::iterator it = mSubscribedGrp.find(grpId); - ok = it != mSubscribedGrp.end(); - } - - /* - * load msg if this is a subscribed group - * if not then add the grp cache map - */ - if(ok) - { - loadMsg(newMsg, src, local, historical); - }else - { - // add grp to set so cache not added to grp again - if(grpAddedTo.find(newMsg->grpId) == grpAddedTo.end()) - { - RsStackMutex stack(distribMtx); - mGrpCacheMap[grpId].push_back(data); - grpAddedTo.insert(grpId); - } - - delete item; - } - } - else - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::loadFileMsgs() Unexpected Item - deleting"; - std::cerr << std::endl; -#endif - /* wrong message type */ - delete item; - } - } - - - if (local) - { - /* now we create a map of time -> subid - * This is used to determine the newest and the oldest items - */ -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::loadFileMsgs() Updating Local TimeStamps"; - std::cerr << std::endl; - std::cerr << "p3GroupDistrib::loadFileMsgs() CacheSubId: " << cacheSubId << " recvd: " << ts; - std::cerr << std::endl; -#endif - RsStackMutex stack(distribMtx); - - mLocalCacheTs[data.recvd] = cacheSubId; - if (cacheSubId > mMaxCacheSubId) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::loadFileMsgs() New Max CacheSubId"; - std::cerr << std::endl; -#endif - mMaxCacheSubId = cacheSubId; - } - - if (((time_t) ts < now) && ((time_t) ts > mLastPublishTime)) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::loadFileMsgs() New LastPublishTime"; - std::cerr << std::endl; -#endif - mLastPublishTime = ts; - } - } - - delete store; - return; -} - - -bool p3GroupDistrib::processCacheOptReq(const std::string &grpId) -{ - { - RsStackMutex stack(distribMtx); - if(mSubscribedGrp.find(grpId) != mSubscribedGrp.end()) - return false; - - // grp already loaded - if(mCacheOptLoaded.find(grpId) != mCacheOptLoaded.end()) - return false; - } - - bool ok; - std::list cList; - - { - RsStackMutex stack(distribMtx); - CacheOptData::iterator mit = mGrpCacheMap.find(grpId); - ok = (mit != mGrpCacheMap.end()); - if(ok) cList = mit->second; - } - - if(ok) - { - std::list::iterator sit = cList.begin(); - - for(;sit != cList.end(); sit++) - loadCacheOptMsgs(*sit, grpId); - } - else - { - return false; - } - - RsStackMutex stack(distribMtx); - mCacheOptLoaded.insert(grpId); - - return true; -} - -void p3GroupDistrib::loadCacheOptMsgs(const CacheData& data, const std::string& grpId) -{ - std::string filename = data.path; - filename += "/"; - filename += data.name; - - /* create the serialiser to load msgs */ - BinInterface *bio = new BinFileInterface(filename.c_str(), BIN_FLAGS_READABLE); - pqistore *store = createStore(bio, data.pid, BIN_FLAGS_READABLE); - -#ifdef DISTRIB_DEBUG - std::cerr << "loading file " << filename << std::endl ; -#endif - - RsItem *item; - RsDistribSignedMsg *newMsg; - - while(isRunning() && (NULL != (item = store->GetItem()))) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::loadFileMsgs() Got Item:"; - std::cerr << std::endl; - item->print(std::cerr, 10); - std::cerr << std::endl; -#endif - - if ((newMsg = dynamic_cast(item))) - { - if(newMsg->grpId == grpId) - loadMsg(newMsg, data.pid, false, true); - else - delete item; - } - else - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::loadFileMsgs() Unexpected Item - deleting"; - std::cerr << std::endl; -#endif - /* wrong message type */ - delete item; - } - } - - delete store; - return; -} - - -/***************************************************************************************/ -/***************************************************************************************/ - /********************** load Cache Msgs ***************************************/ -/***************************************************************************************/ -/***************************************************************************************/ - - -bool p3GroupDistrib::loadGroup(RsDistribGrp *newGrp, bool historical) -{ - /* load groupInfo */ - const std::string &gid = newGrp -> grpId; - const std::string &pid = newGrp -> PeerId(); - -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::loadGroup()" << std::endl; - std::cerr << "groupId: " << gid << std::endl; - std::cerr << "PeerId: " << pid << std::endl; - std::cerr << "Group:" << std::endl; - newGrp -> print(std::cerr, 10); - std::cerr << "----------------------" << std::endl; -#endif - - RsStackMutex stack(distribMtx); /******* STACK LOCKED MUTEX ***********/ - - /* look for duplicate */ - bool checked = false; - bool isNew = false; - bool ok = false; - std::map::iterator it; - it = mGroups.find(gid); - - if (it == mGroups.end()) - { - -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::loadGroup() Group Not Found"; - std::cerr << std::endl; -#endif - - if (!p3DistribSecurity::validateDistribGrp(newGrp)) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::loadGroup() Invalid Group "; - std::cerr << std::endl; -#endif - /* fails test */ - delete newGrp; - return false; - } - - checked = true; - - GroupInfo gi; - gi.grpId = gid; - mGroups[gid] = gi; - - it = mGroups.find(gid); - - isNew = true; - } - - /* at this point - always in the map */ - - /* add as source ... don't need to validate for this! */ - std::list::iterator pit; - pit = std::find(it->second.sources.begin(), it->second.sources.end(), pid); - if (pit == it->second.sources.end()) - { - it->second.sources.push_back(pid); - it->second.pop = it->second.sources.size(); - -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::loadGroup() New Source, pop = "; - std::cerr << it->second.pop; - std::cerr << std::endl; -#endif - } - - if (!checked) - { - if (!locked_checkGroupInfo(it->second, newGrp)) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::loadGroup() Fails Check"; - std::cerr << std::endl; -#endif - /* either fails check or old/same data */ - delete newGrp; - return false; - } - } - - /* useful info/update */ - if(!locked_updateGroupInfo(it->second, newGrp)) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::loadGroup() Fails Update"; - std::cerr << std::endl; -#endif - /* cleanup on false */ - delete newGrp; - } - else - { - /* Callback for any derived classes */ - - if (isNew) - locked_notifyGroupChanged(it->second, GRP_NEW_UPDATE, historical); - else - locked_notifyGroupChanged(it->second, GRP_UPDATE, historical); - - ok = true; - } - -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::loadGroup() Done"; - std::cerr << std::endl; - std::cerr << "ok: " << ok << std::endl; -#endif - return ok; - -} - - -bool p3GroupDistrib::loadGroupKey(RsDistribGrpKey *newKey, bool historical) -{ - /* load Key */ - const std::string &gid = newKey -> grpId; - -#ifdef DISTRIB_DEBUG - const std::string &pid = newKey -> PeerId(); - std::cerr << "p3GroupDistrib::loadGroupKey()" << std::endl; - std::cerr << "PeerId: " << pid << std::endl; - std::cerr << "groupId: " << gid << std::endl; - std::cerr << "Key:" << std::endl; - newKey -> print(std::cerr, 10); - std::cerr << "----------------------" << std::endl; -#endif - - RsStackMutex stack(distribMtx); /******* STACK LOCKED MUTEX ***********/ - - /* Find the Group */ - std::map::iterator it; - it = mGroups.find(gid); - - // - if (it == mGroups.end()) - { - -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::loadGroupKey() Group for key not found: discarding"; - std::cerr << std::endl; -#endif - - delete newKey; - newKey = NULL; - return false; - } - - /* have the group -> add in the key */ - bool updateOk = false; - if (newKey->key.keyFlags & RSTLV_KEY_DISTRIB_ADMIN) - { - if(!locked_updateGroupAdminKey(it->second, newKey)) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::loadGroupKey() Failed Admin Key Update"; - std::cerr << std::endl; -#endif - } - else - { - updateOk = true; - } - } - else - { - if(!locked_updateGroupPublishKey(it->second, newKey)) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::loadGroupKey() Failed Publish Key Update"; - std::cerr << std::endl; -#endif - } - else - { - updateOk = true; - } - } - - if (updateOk) - locked_notifyGroupChanged(it->second, GRP_LOAD_KEY, historical); - -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::loadGroupKey() Done - Cleaning up."; - std::cerr << std::endl; -#endif - -// if(!updateOk) - delete newKey; - - newKey = NULL; - return updateOk; -} - - -bool p3GroupDistrib::loadMsg(RsDistribSignedMsg *newMsg, const std::string &src, bool local, bool historical) -{ - /****************** check the msg ******************/ - /* Do the most likely checks to fail first.... - * - * timestamp (too old) - * group (non existant) - * msg (already have it) - * - * -> then do the expensive Hash / signature checks. - */ - -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::loadMsg()" << std::endl; - std::cerr << "Source:" << src << std::endl; - std::cerr << "Local:" << local << std::endl; - newMsg -> print(std::cerr, 10); - std::cerr << "----------------------" << std::endl; -#endif - - RsStackMutex stack(distribMtx); /******* STACK LOCKED MUTEX ***********/ - - /* Check if it exists already */ - - /* find group */ - std::map::iterator git; - if (mGroups.end() == (git = mGroups.find(newMsg->grpId))) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::loadMsg() Group Dont Exist" << std::endl; - std::cerr << std::endl; -#endif - /* if not there -> remove */ - delete newMsg; - return false; - } - - /****************** check the msg ******************/ - /* check for duplicate message, do this first to ensure minimal signature validations. - * therefore, duplicateMsg... could potentially be called on a dodgey msg (not a big problem!) - */ - - std::map::iterator mit; - mit = (git->second).msgs.find(newMsg->msgId); - if (mit != (git->second).msgs.end()) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::loadMsg() Msg already exists" << std::endl; - std::cerr << std::endl; -#endif - /* if already there -> remove */ - locked_eventDuplicateMsg(&(git->second), mit->second, src, historical); - delete newMsg; - return false; - } - - /* if unique (new) msg - do validation */ - if (!p3DistribSecurity::validateDistribSignedMsg(git->second, newMsg)) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::loadMsg() validate failed" << std::endl; - std::cerr << std::endl; -#endif - delete newMsg; - return false; - } - - void *temp_ptr = newMsg->packet.bin_data; - int temp_len = newMsg->packet.bin_len; - - /* if encrypted data then decrypt */ - if(git->second.grpFlags & RS_DISTRIB_ENCRYPTED){ - void *out_data = NULL; - int out_len = 0; - - EVP_PKEY * privateKey = NULL; - std::map::iterator kit; - - for(kit = git->second.publishKeys.begin(); kit != git->second - .publishKeys.end(); kit++ ){ - // Does not allow for possibility of different keys - - if((kit->second.type & RSTLV_KEY_TYPE_FULL) && (kit->second.key->type == EVP_PKEY_RSA)){ - privateKey = kit->second.key; - break; - } - } - - if(kit == git->second.publishKeys.end()){ - #ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::loadMsg(): Cannot find full key, grpId " << grpId - << std::endl; - #endif - delete newMsg; - return false; - } - - - if(p3DistribSecurity::decrypt(out_data, out_len, newMsg->packet.bin_data, newMsg->packet.bin_len, privateKey)){ - - newMsg->packet.TlvShallowClear(); - newMsg->packet.setBinData(out_data, out_len); - delete[] (unsigned char*) out_data; - - }else{ - if((out_data != NULL) && (out_len != 0)) - delete[] (unsigned char*) out_data; - -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::loadMsg() Failed to decrypt" << std::endl; - std::cerr << std::endl; -#endif - delete newMsg; - return false; - } - } - - /* convert Msg */ - RsDistribMsg *msg = unpackDistribSignedMsg(newMsg); - - if (!msg) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::loadMsg() unpack failed" << std::endl; - std::cerr << std::endl; -#endif - delete newMsg; - return false; - } - - if (!locked_checkDistribMsg(git->second, msg)) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::loadMsg() check failed" << std::endl; - std::cerr << std::endl; -#endif - delete newMsg; - delete msg; - return false; - } - - /* accept message */ - (git->second).msgs[msg->msgId] = msg; - - // update the time stamp of group for last post - if((git->second.lastPost < (time_t)msg->timestamp)) - git->second.lastPost = msg->timestamp; - - // Interface to handle Dummy Msgs. - locked_CheckNewMsgDummies(git->second, msg, src, historical); - - /* now update parents TS */ - locked_updateChildTS(git->second, msg); - -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::loadMsg() Msg Loaded Successfully" << std::endl; - std::cerr << std::endl; -#endif - - /* Callback for any derived classes to play with */ - locked_eventNewMsg(&(git->second), msg, src, historical); - - /* else if group = subscribed | listener -> publish */ - /* if it has come from us... then it has been published already */ - if ((!local) && (git->second.flags & (RS_DISTRIB_SUBSCRIBED))) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::loadMsg() To be Published!"; - std::cerr << std::endl; -#endif - - if(git->second.grpFlags & RS_DISTRIB_ENCRYPTED){ - newMsg->packet.TlvClear(); - newMsg->packet.setBinData(temp_ptr, temp_len); - } - - locked_toPublishMsg(newMsg); - } - else - { - /* Note it makes it very difficult to republish msg - if we have - * deleted the signed version... The load of old messages will occur - * at next startup. And publication will happen then too. - */ - -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::loadMsg() Deleted Original Msg (No Publish)"; - std::cerr << std::endl; -#endif - delete newMsg; - - } - - if(!historical) - locked_notifyGroupChanged(git->second, GRP_NEW_MSG, historical); - - return true; -} - -/***************************************************************************************/ -/***************************************************************************************/ - /****************** create/mod Cache Content **********************************/ -/***************************************************************************************/ -/***************************************************************************************/ - -void p3GroupDistrib::locked_toPublishMsg(RsDistribSignedMsg *msg) -{ -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_toPublishMsg() Adding to PendingPublish List"; - std::cerr << std::endl; -#endif - mPendingPublish.push_back(msg); - if (msg->PeerId() == mOwnId) - { - -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_toPublishMsg() Local -> ConfigSave Requested"; - std::cerr << std::endl; -#endif - /* we need to trigger Configuration save */ - IndicateConfigChanged(); /**** INDICATE CONFIG CHANGED! *****/ - } -} - - -uint16_t p3GroupDistrib::locked_determineCacheSubId() -{ - /* if oldest cache is previous to StorePeriod - use that */ - time_t now = time(NULL); - uint16_t id = 1; - - uint32_t oldest = now; - if (mLocalCacheTs.size() > 0) - { - oldest = mLocalCacheTs.begin()->first; - } - - if (oldest < now - mStorePeriod) - { - /* clear it out, return id */ - id = mLocalCacheTs.begin()->second; - mLocalCacheTs.erase(mLocalCacheTs.begin()); - -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_determineCacheSubId() Replacing Old CacheId: " << id; - std::cerr << std::endl; -#endif - return id; - } - - mMaxCacheSubId++; - -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_determineCacheSubId() Returning new Id: " << mMaxCacheSubId; - std::cerr << std::endl; -#endif - /* else return maximum */ - return mMaxCacheSubId; -} - - -void p3GroupDistrib::locked_publishPendingMsgs() -{ -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_publishPendingMsgs()"; - std::cerr << std::endl; -#endif - /* get the next message id */ - CacheData newCache; - time_t now = time(NULL); - - bool ok = true; // hass msg/cache file been written successfully - - newCache.pid = mOwnId; - newCache.cid.type = CacheSource::getCacheType(); - newCache.cid.subid = locked_determineCacheSubId(); - - /* create filename */ - std::string path = CacheSource::getCacheDir(); - - std::string tmpname; - rs_sprintf(tmpname, "grpdist-t%u-msgs-%ld.dist", CacheSource::getCacheType(), time(NULL)); - std::string filename = path + "/" + tmpname ; - std::string filenametmp = path + "/" + tmpname + ".tmp"; - - BinInterface *bio = new BinFileInterface(filenametmp.c_str(), BIN_FLAGS_WRITEABLE | BIN_FLAGS_HASH_DATA); - pqistore *store = createStore(bio, mOwnId, BIN_FLAGS_WRITEABLE); /* messages are deleted! */ - - bool resave = false; - std::list::iterator it; - for(it = mPendingPublish.begin(); it != mPendingPublish.end(); it++) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_publishPendingMsgs() Publishing:"; - std::cerr << std::endl; - (*it)->print(std::cerr, 10); - std::cerr << std::endl; -#endif - if ((*it)->PeerId() == mOwnId) - { - -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_publishPendingMsgs() Own Publish"; - std::cerr << std::endl; -#endif - resave = true; - } - - // prevent sending original source of message to peers - (*it)->PeerId(mOwnId); - - if(!store->SendItem(*it)) /* deletes it */ - { - ok &= false; - } - } - - /* Extract File Information from pqistore */ - newCache.path = path; - newCache.name = tmpname; - - newCache.hash = bio->gethash(); - newCache.size = bio->bytecount(); - newCache.recvd = now; - - /* cleanup */ - mPendingPublish.clear(); - delete store; - - if(!RsDirUtil::renameFile(filenametmp,filename)) - { - std::string errlog; - ok &= false; -#ifdef WIN32 - rs_sprintf(errlog, "Error %u", GetLastError()); -#else - rs_sprintf(errlog, "Error %d", errno); -#endif - getPqiNotify()->AddSysMessage(0, RS_SYS_WARNING, "File rename error", "Error while renaming file " + filename + ": got error " + errlog); - } - - /* indicate not to save for a while */ - mLastPublishTime = now; - - /* push file to CacheSource */ - - if(ok) - refreshCache(newCache); - - - if (ok && resave) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_publishPendingMsgs() Indicate Save Data Changed"; - std::cerr << std::endl; -#endif - /* flag to store config (saying we've published messages) */ - IndicateConfigChanged(); /**** INDICATE CONFIG CHANGED! *****/ - } -} - - -void p3GroupDistrib::publishDistribGroups() -{ -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::publishDistribGroups()"; - std::cerr << std::endl; -#endif - - /* set subid = 1 */ - CacheData newCache; - - newCache.pid = mOwnId; - newCache.cid.type = CacheSource::getCacheType(); - newCache.cid.subid = 1; - - /* create filename */ - std::string path = CacheSource::getCacheDir(); - - std::string tmpname; - rs_sprintf(tmpname, "grpdist-t%u-grps-%ld.dist", CacheSource::getCacheType(), time(NULL)); - std::string filename = path + "/" + tmpname; - std::string filenametmp = path + "/" + tmpname + ".tmp"; - std::string tempPeerId; // to store actual id temporarily - - BinInterface *bio = new BinFileInterface(filenametmp.c_str(), BIN_FLAGS_WRITEABLE | BIN_FLAGS_HASH_DATA); - pqistore *store = createStore(bio, mOwnId, BIN_FLAGS_NO_DELETE | BIN_FLAGS_WRITEABLE); - - RsStackMutex stack(distribMtx); /****** STACK MUTEX LOCKED *******/ - - - /* Iterate through all the Groups */ - std::map::iterator it; - for(it = mGroups.begin(); it != mGroups.end(); it++) - { - /* if subscribed or listener or admin -> then send it to be published by cache */ - if ((it->second.flags & RS_DISTRIB_SUBSCRIBED) || (it->second.flags & RS_DISTRIB_ADMIN)) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::publishDistribGroups() Saving Group: " << it->first; - std::cerr << std::endl; -#endif - - /* extract public info to RsDistribGrp */ - RsDistribGrp *grp = it->second.distribGroup; - - if (grp) - { - /* store in Cache File */ - tempPeerId = grp->PeerId(); - grp->PeerId(mOwnId); // prevent sending original source to users - store->SendItem(grp); /* no delete */ - grp->PeerId(tempPeerId); - - } - - /* if they have public keys, publish these too */ - std::map::iterator kit; - for(kit = it->second.publishKeys.begin(); - kit != it->second.publishKeys.end(); kit++) - { - if ((kit->second.type & RSTLV_KEY_DISTRIB_PUBLIC) && - (kit->second.type & RSTLV_KEY_TYPE_FULL)) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::publishDistribGroups() Saving Key: " << kit->first; - std::cerr << std::endl; -#endif - /* create Key for sharing */ - - RsDistribGrpKey *pubKey = new RsDistribGrpKey(); - pubKey->grpId = it->first; - - RSA *rsa_priv = EVP_PKEY_get1_RSA(kit->second.key); - p3DistribSecurity::setRSAPrivateKey(pubKey->key, rsa_priv); - RSA_free(rsa_priv); - - pubKey->key.keyFlags = RSTLV_KEY_TYPE_FULL; - pubKey->key.keyFlags |= RSTLV_KEY_DISTRIB_PUBLIC; - pubKey->key.startTS = kit->second.startTS; - pubKey->key.endTS = kit->second.endTS; - - store->SendItem(pubKey); - delete pubKey; - } - else - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::publishDistribGroups() Ignoring Key: " << kit->first; - std::cerr << std::endl; - std::cerr << "p3GroupDistrib::publishDistribGroups() Key Type: " << kit->second.type; - std::cerr << std::endl; -#endif - } - - } - } - else - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::publishDistribGroups() Ignoring Group: " << it->first; - std::cerr << std::endl; -#endif - } - - } - - /* Extract File Information from pqistore */ - newCache.path = path; - newCache.name = tmpname; - - newCache.hash = bio->gethash(); - newCache.size = bio->bytecount(); - newCache.recvd = time(NULL); - - /* cleanup */ - delete store; - - if(!RsDirUtil::renameFile(filenametmp,filename)) - { - std::string errlog; -#ifdef WIN32 - rs_sprintf(errlog, "Error %u", GetLastError()); -#else - rs_sprintf(errlog, "Error %d", errno); -#endif - getPqiNotify()->AddSysMessage(0, RS_SYS_WARNING, "File rename error", "Error while renaming file " + filename + ": got error " + errlog); - } - - /* push file to CacheSource */ - refreshCache(newCache); -} - - - /* clearing old data */ -void p3GroupDistrib::clear_local_caches(time_t now) -{ - RsStackMutex stack(distribMtx); /****** STACK MUTEX LOCKED *******/ - - time_t cutoff = now - mStorePeriod; - std::list::iterator it; - for(it = mLocalCaches.begin(); it != mLocalCaches.end();) - { - if (it->end < cutoff) - { - /* Call to CacheSource Function */ - CacheId cid(CacheSource::getCacheType(), it->cacheSubId); - clearCache(cid); - it = mLocalCaches.erase(it); - } - else - { - it++; - } - } -} - - - -/***************************************************************************************/ -/***************************************************************************************/ - /********************** Access Content ***************************************/ -/***************************************************************************************/ -/***************************************************************************************/ - - -/* get Group Lists */ -bool p3GroupDistrib::getAllGroupList(std::list &grpids) -{ - RsStackMutex stack(distribMtx); /************* STACK MUTEX ************/ - std::map::iterator git; - for(git = mGroups.begin(); git != mGroups.end(); git++) - { - grpids.push_back(git->first); - } - return true; -} - -bool p3GroupDistrib::getSubscribedGroupList(std::list &grpids) -{ - RsStackMutex stack(distribMtx); /************* STACK MUTEX ************/ - std::map::iterator git; - for(git = mGroups.begin(); git != mGroups.end(); git++) - { - if (git->second.flags & RS_DISTRIB_SUBSCRIBED) - { - grpids.push_back(git->first); - } - } - return true; -} - -bool p3GroupDistrib::getPublishGroupList(std::list &grpids) -{ - RsStackMutex stack(distribMtx); /************* STACK MUTEX ************/ - std::map::iterator git; - for(git = mGroups.begin(); git != mGroups.end(); git++) - { - if (git->second.flags & (RS_DISTRIB_ADMIN | RS_DISTRIB_PUBLISH)) - { - grpids.push_back(git->first); - } - } - return true; -} - -void p3GroupDistrib::getPopularGroupList(uint32_t popMin, uint32_t popMax, std::list &grpids) -{ - RsStackMutex stack(distribMtx); /************* STACK MUTEX ************/ - std::map::iterator git; - for(git = mGroups.begin(); git != mGroups.end(); git++) - { - if ((git->second.pop >= popMin) && - (git->second.pop <= popMax)) - { - grpids.push_back(git->first); - } - } - return; -} - - -/* get Msg Lists */ -bool p3GroupDistrib::getAllMsgList(const std::string& grpId, std::list &msgIds) -{ - - processCacheOptReq(grpId); - RsStackMutex stack(distribMtx); /************* STACK MUTEX ************/ - - - std::map::iterator git; - if (mGroups.end() == (git = mGroups.find(grpId))) - { - return false; - } - - std::map::iterator mit; - std::map msgs; - - for(mit = git->second.msgs.begin(); mit != git->second.msgs.end(); mit++) - { - msgIds.push_back(mit->first); - } - return true; -} - -bool p3GroupDistrib::getParentMsgList(const std::string& grpId, const std::string& pId, - std::list &msgIds) -{ - processCacheOptReq(grpId); - - RsStackMutex stack(distribMtx); /************* STACK MUTEX ************/ - - std::map::iterator git; - if (mGroups.end() == (git = mGroups.find(grpId))) - { - return false; - } - - std::map::iterator mit; - - for(mit = git->second.msgs.begin(); mit != git->second.msgs.end(); mit++) - { - if (mit->second->parentId == pId) - { - msgIds.push_back(mit->first); - } - } - return true; -} - -bool p3GroupDistrib::getTimePeriodMsgList(const std::string& grpId, uint32_t timeMin, - uint32_t timeMax, std::list &msgIds) -{ - RsStackMutex stack(distribMtx); /************* STACK MUTEX ************/ - std::map::iterator git; - if (mGroups.end() == (git = mGroups.find(grpId))) - { - return false; - } - - std::map::iterator mit; - - for(mit = git->second.msgs.begin(); mit != git->second.msgs.end(); mit++) - { - if ((mit->second->timestamp >= timeMin) && - (mit->second->timestamp <= timeMax)) - { - msgIds.push_back(mit->first); - } - } - return true; -} - - -GroupInfo *p3GroupDistrib::locked_getGroupInfo(const std::string& grpId) -{ - /************* ALREADY LOCKED ************/ - std::map::iterator git; - if (mGroups.end() == (git = mGroups.find(grpId))) - { - return NULL; - } - return &(git->second); -} - - -RsDistribMsg *p3GroupDistrib::locked_getGroupMsg(const std::string& grpId, const std::string& msgId) -{ - - /************* ALREADY LOCKED ************/ - - - std::map::iterator git; - if (mGroups.end() == (git = mGroups.find(grpId))) - { - return NULL; - } - - std::map::iterator mit; - if (git->second.msgs.end() == (mit = git->second.msgs.find(msgId))) - { - return NULL; - } - - return mit->second; -} - -bool p3GroupDistrib::subscribeToGroup(const std::string &grpId, bool subscribe) -{ - RsStackMutex stack(distribMtx); /************* STACK MUTEX ************/ - std::map::iterator git; - if (mGroups.end() == (git = mGroups.find(grpId))) - { - return false; - } - - if (subscribe) - { - if (!(git->second.flags & RS_DISTRIB_SUBSCRIBED)) - { - git->second.flags |= RS_DISTRIB_SUBSCRIBED; - - locked_notifyGroupChanged(git->second, GRP_SUBSCRIBED, false); - mGroupsRepublish = true; - - /* reprocess groups messages .... so actions can be taken (by inherited) - * This could be an very expensive operation! .... but they asked for it. - * - * Hopefully a LoadList call will have on existing messages! - */ - - std::map::iterator mit; - std::list::iterator pit; - - /* assume that each peer can provide all of them */ - for(mit = git->second.msgs.begin(); - mit != git->second.msgs.end(); mit++) - { - for(pit = git->second.sources.begin(); - pit != git->second.sources.end(); pit++) - { - if(*pit != mOwnId) - locked_eventDuplicateMsg(&(git->second), mit->second, *pit, false); - } - } - } - } - else - { - if (git->second.flags & RS_DISTRIB_SUBSCRIBED) - { - git->second.flags &= (~RS_DISTRIB_SUBSCRIBED); - - locked_notifyGroupChanged(git->second, GRP_UNSUBSCRIBED, false); - mGroupsRepublish = true; - } - } - - return true; -} - - -bool p3GroupDistrib::attemptPublishKeysRecvd() -{ - -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::attemptPublishKeysRecvd() " << std::endl; -#endif - - RsStackMutex stack(distribMtx); - - std::list toDelete; - std::list::iterator sit; - std::map::iterator it; - - std::map::iterator mit; - mit = mRecvdPubKeys.begin(); - - // add received keys for groups that are present - for(; mit != mRecvdPubKeys.end(); mit++){ - - it = mGroups.find(mit->first); - - // group has not arrived yet don't attempt to add - if(it == mGroups.end()){ - - continue; - - }else{ - - - - if(locked_updateGroupPublishKey(it->second, mit->second)){ - - locked_notifyGroupChanged(it->second, GRP_LOAD_KEY, false); - } - - if(it->second.flags & RS_DISTRIB_SUBSCRIBED){ - // remove key shared flag so key is not loaded back into mrecvdpubkeys - mit->second->key.keyFlags &= (~RSTLV_KEY_TYPE_SHARED); - - delete (mit->second); - toDelete.push_back(mit->first); - } - - } - } - - sit = toDelete.begin(); - - for(; sit != toDelete.end(); sit++) - mRecvdPubKeys.erase(*sit); - - if(!toDelete.empty()) IndicateConfigChanged(); - - - return true; -} - -/************************************* p3Config *************************************/ - -RsSerialiser *p3GroupDistrib::setupSerialiser() -{ - RsSerialiser *rss = new RsSerialiser(); - rss->addSerialType(new RsDistribSerialiser()); - - return rss; -} - -bool p3GroupDistrib::saveList(bool &cleanup, std::list& saveData) -{ - -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::saveList()"; - std::cerr << std::endl; -#endif - - cleanup = false; - - distribMtx.lock(); /****** MUTEX LOCKED *******/ - - /* Iterate through all the Groups */ - std::map::iterator it; - for(it = mGroups.begin(); it != mGroups.end(); it++) - { - /* if subscribed or listener -> do stuff */ - if (it->second.flags & (RS_DISTRIB_SUBSCRIBED)) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::saveList() Saving Group: " << it->first; - std::cerr << std::endl; -#endif - - /* extract public info to RsDistribGrp */ - RsDistribGrp *grp = it->second.distribGroup; - - if (grp) - { - /* store in Cache File */ - saveData.push_back(grp); /* no delete */ - } - - /* if they have public keys, publish these too */ - std::map::iterator kit; - for(kit = it->second.publishKeys.begin(); - kit != it->second.publishKeys.end(); kit++) - { - if (kit->second.type & RSTLV_KEY_TYPE_FULL) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::saveList() Saving Key: " << kit->first; - std::cerr << std::endl; -#endif - /* create Key for sharing */ - - RsDistribGrpKey *pubKey = new RsDistribGrpKey(); - pubKey->grpId = it->first; - - RSA *rsa_priv = EVP_PKEY_get1_RSA(kit->second.key); - p3DistribSecurity::setRSAPrivateKey(pubKey->key, rsa_priv); - RSA_free(rsa_priv); - - pubKey->key.keyFlags = kit->second.type; - pubKey->key.startTS = kit->second.startTS; - pubKey->key.endTS = kit->second.endTS; - - saveData.push_back(pubKey); - saveCleanupList.push_back(pubKey); - } - else - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::saveList() Ignoring Key: " << kit->first; - std::cerr << std::endl; - std::cerr << "p3GroupDistrib::saveList() Key Type: " << kit->second.type; - std::cerr << std::endl; -#endif - } - - } - - if (it->second.adminKey.type & RSTLV_KEY_TYPE_FULL) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::saveList() Saving Admin Key"; - std::cerr << std::endl; -#endif - /* create Key for sharing */ - - RsDistribGrpKey *pubKey = new RsDistribGrpKey(); - pubKey->grpId = it->first; - - RSA *rsa_priv = EVP_PKEY_get1_RSA(kit->second.key); - p3DistribSecurity::setRSAPrivateKey(pubKey->key, rsa_priv); - RSA_free(rsa_priv); - - pubKey->key.keyFlags = RSTLV_KEY_TYPE_FULL; - pubKey->key.keyFlags |= RSTLV_KEY_DISTRIB_ADMIN; - pubKey->key.startTS = kit->second.startTS; - pubKey->key.endTS = kit->second.endTS; - - saveData.push_back(pubKey); - saveCleanupList.push_back(pubKey); - } - else - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::saveList() Ignoring Admin Key: " << it->second.adminKey.keyId; - std::cerr << std::endl; - std::cerr << "p3GroupDistrib::saveList() Admin Key Type: " << it->second.adminKey.type; - std::cerr << std::endl; -#endif - } - } - else - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::saveList() Ignoring Group: " << it->first; - std::cerr << std::endl; -#endif - } - - } - - std::list::iterator mit; - for(mit = mPendingPublish.begin(); mit != mPendingPublish.end(); mit++) - { - if ((*mit)->PeerId() == mOwnId) - { - saveData.push_back(*mit); - } - } - - // also save pending private publish keys you may have - std::map::iterator pendKeyIt; - - for(pendKeyIt = mRecvdPubKeys.begin(); pendKeyIt != mRecvdPubKeys.end(); pendKeyIt++) - { - - RsDistribGrpKey *pubKey = new RsDistribGrpKey(); - pubKey->grpId = pendKeyIt->first; - const unsigned char *keyptr = (const unsigned char *) - pendKeyIt->second->key.keyData.bin_data; - long keylen = pendKeyIt->second->key.keyData.bin_len; - - RSA *rsa_priv = d2i_RSAPrivateKey(NULL, &(keyptr), keylen); - - p3DistribSecurity::setRSAPrivateKey(pubKey->key, rsa_priv); - RSA_free(rsa_priv); - - pubKey->key.keyFlags = pendKeyIt->second->key.keyFlags; - pubKey->key.startTS = pendKeyIt->second->key.startTS; - pubKey->key.endTS = pendKeyIt->second->key.endTS; - - saveData.push_back(pubKey); - saveCleanupList.push_back(pubKey); - - } - - std::list childSaveL = childSaveList(); - std::list::iterator cit = childSaveL.begin(); - RsSerialType *childSer = createSerialiser(); - uint32_t pktSize = 0; - unsigned char *data = NULL; - - for(; cit != childSaveL.end() ; cit++) - { - RsDistribConfigData* childConfig = new RsDistribConfigData(); - - pktSize = childSer->size(*cit); - data = new unsigned char[pktSize]; - childSer->serialise(*cit, data, &pktSize); - childConfig->service_data.setBinData(data, pktSize); - delete[] data; - saveData.push_back(childConfig); - saveCleanupList.push_back(childConfig); - } - - delete childSer; - - return true; -} - -void p3GroupDistrib::saveDone() -{ - /* clean up the save List */ - std::list::iterator it; - for(it = saveCleanupList.begin(); it != saveCleanupList.end(); it++) - { - delete (*it); - } - - saveCleanupList.clear(); - - /* unlock mutex */ - distribMtx.unlock(); /****** MUTEX UNLOCKED *******/ -} - -bool p3GroupDistrib::loadList(std::list& load) -{ - std::list::iterator lit; - - /* for child config data */ - std::list childLoadL; - RsSerialType* childSer = createSerialiser(); - - for(lit = load.begin(); lit != load.end(); lit++) - { - /* decide what type it is */ - - RsDistribGrp *newGrp = NULL; - RsDistribGrpKey *newKey = NULL; - RsDistribSignedMsg *newMsg = NULL; - RsDistribConfigData* newChildConfig = NULL; - - - if ((newGrp = dynamic_cast(*lit))) - { - const std::string &gid = newGrp -> grpId; - - loadGroup(newGrp, false); - subscribeToGroup(gid, true); - mSubscribedGrp.insert(gid); - } - else if ((newKey = dynamic_cast(*lit))) - { - - // for shared keys keep - if(newKey->key.keyFlags & RSTLV_KEY_TYPE_SHARED){ - - mRecvdPubKeys.insert(std::pair( - newKey->grpId, newKey)); - mPubKeyAvailableGrpId.insert(newKey->grpId); - continue; - } - - loadGroupKey(newKey, false); - - - } - else if ((newMsg = dynamic_cast(*lit))) - { - newMsg->PeerId(mOwnId); - loadMsg(newMsg, mOwnId, false, false); /* false so it'll pushed to PendingPublish list */ - } - else if ((newChildConfig = dynamic_cast(*lit))) - { - RsItem* childConfigItem = childSer->deserialise(newChildConfig->service_data.bin_data, - &newChildConfig->service_data.bin_len); - - childLoadL.push_back(childConfigItem); - - delete newChildConfig ; - } - } - - /* no need to republish until something new comes in */ - RsStackMutex stack(distribMtx); /******* STACK LOCKED MUTEX ***********/ - - childLoadList(childLoadL); // send configurations down to child - - mGroupsRepublish = false; - delete childSer; - - return true; -} - -/************************************* p3Config *************************************/ - -/* This Streamer is used for Reading and Writing Cache Files.... - * As All the child packets are Packed, we should only need RsSerialDistrib() in it. - */ - -pqistore *p3GroupDistrib::createStore(BinInterface *bio, const std::string &src, uint32_t bioflags) -{ - RsSerialiser *rsSerialiser = new RsSerialiser(); - RsSerialType *serialType = new RsDistribSerialiser(); - rsSerialiser->addSerialType(serialType); - - pqistore *store = new pqistore(rsSerialiser, src, bio, bioflags); - - return store; -} - - -/***************************************************************************************/ -/***************************************************************************************/ - /********************** Create Content ***************************************/ -/***************************************************************************************/ -/***************************************************************************************/ - -std::string p3GroupDistrib::createGroup(std::wstring name, std::wstring desc, uint32_t flags, - unsigned char* pngImageData, uint32_t imageSize) -{ -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::createGroup()" << std::endl; - std::cerr << std::endl; -#endif - /* Create a Group */ - std::string grpId; - time_t now = time(NULL); - - /* for backup */ - std::list grpKeySet; - - /* create Keys */ - RSA *rsa_admin = RSA_generate_key(2048, 65537, NULL, NULL); - RSA *rsa_admin_pub = RSAPublicKey_dup(rsa_admin); - - RSA *rsa_publish = RSA_generate_key(2048, 65537, NULL, NULL); - RSA *rsa_publish_pub = RSAPublicKey_dup(rsa_publish); - - /* Create Group Description */ - - RsDistribGrp *newGrp = new RsDistribGrp(); - - newGrp->grpName = name; - newGrp->grpDesc = desc; - newGrp->timestamp = now; - newGrp->grpFlags = flags & (RS_DISTRIB_PRIVACY_MASK | RS_DISTRIB_AUTHEN_MASK); - newGrp->grpControlFlags = 0; - - // explicit member wise copy for grp image - if((pngImageData != NULL) && (imageSize > 0)){ - newGrp->grpPixmap.binData.bin_data = new unsigned char[imageSize]; - - memcpy(newGrp->grpPixmap.binData.bin_data, pngImageData, - imageSize*sizeof(unsigned char)); - newGrp->grpPixmap.binData.bin_len = imageSize; - newGrp->grpPixmap.image_type = RSTLV_IMAGE_TYPE_PNG; - - }else{ - newGrp->grpPixmap.binData.bin_data = NULL; - newGrp->grpPixmap.binData.bin_len = 0; - newGrp->grpPixmap.image_type = 0; - } - - - - - /* set keys */ - p3DistribSecurity::setRSAPublicKey(newGrp->adminKey, rsa_admin_pub); - newGrp->adminKey.keyFlags = RSTLV_KEY_TYPE_PUBLIC_ONLY | RSTLV_KEY_DISTRIB_ADMIN; - newGrp->adminKey.startTS = now; - newGrp->adminKey.endTS = 0; /* no end */ - grpId = newGrp->adminKey.keyId; - - - RsTlvSecurityKey publish_key; - - p3DistribSecurity::setRSAPublicKey(publish_key, rsa_publish_pub); - - publish_key.keyFlags = RSTLV_KEY_TYPE_PUBLIC_ONLY; - if (flags & RS_DISTRIB_PUBLIC) - { - publish_key.keyFlags |= RSTLV_KEY_DISTRIB_PUBLIC; - } - else - { - publish_key.keyFlags |= RSTLV_KEY_DISTRIB_PRIVATE; - } - - publish_key.startTS = now; - publish_key.endTS = now + 60 * 60 * 24 * 365 * 5; /* approx 5 years */ - - newGrp->publishKeys.keys[publish_key.keyId] = publish_key; - newGrp->publishKeys.groupId = newGrp->adminKey.keyId; - - - /************* create Key Messages (to Add Later) *********************/ - RsDistribGrpKey *adKey = new RsDistribGrpKey(); - adKey->grpId = grpId; - - p3DistribSecurity::setRSAPrivateKey(adKey->key, rsa_admin); - adKey->key.keyFlags = RSTLV_KEY_TYPE_FULL | RSTLV_KEY_DISTRIB_ADMIN; - adKey->key.startTS = newGrp->adminKey.startTS; - adKey->key.endTS = newGrp->adminKey.endTS; - - - RsDistribGrpKey *pubKey = new RsDistribGrpKey(); - pubKey->grpId = grpId; - - p3DistribSecurity::setRSAPrivateKey(pubKey->key, rsa_publish); - pubKey->key.keyFlags = RSTLV_KEY_TYPE_FULL; - if (flags & RS_DISTRIB_PUBLIC) - { - pubKey->key.keyFlags |= RSTLV_KEY_DISTRIB_PUBLIC; - } - else - { - pubKey->key.keyFlags |= RSTLV_KEY_DISTRIB_PRIVATE; - } - pubKey->key.startTS = publish_key.startTS; - pubKey->key.endTS = publish_key.endTS; - /************* create Key Messages (to Add Later) *********************/ - - - /* clean up publish_key manually -> else - * the data will get deleted... - */ - - publish_key.keyData.bin_data = NULL; - publish_key.keyData.bin_len = 0; - - newGrp->grpId = grpId; - - /************* Back up Keys *********************/ - - grpKeySet.push_back(adKey); - grpKeySet.push_back(pubKey); - - backUpKeys(grpKeySet, grpId); - - /************** Serialise and sign **************************************/ - EVP_PKEY *key_admin = EVP_PKEY_new(); - EVP_PKEY_assign_RSA(key_admin, rsa_admin); - - newGrp->adminSignature.TlvClear(); - - RsSerialType *serialType = new RsDistribSerialiser(); - - uint32_t size = serialType->size(newGrp); - char* data = new char[size]; - - serialType->serialise(newGrp, data, &size); - - /* calc and check signature */ - EVP_MD_CTX *mdctx = EVP_MD_CTX_create(); - - EVP_SignInit(mdctx, EVP_sha1()); - EVP_SignUpdate(mdctx, data, size); - - unsigned int siglen = EVP_PKEY_size(key_admin); - unsigned char sigbuf[siglen]; - EVP_SignFinal(mdctx, sigbuf, &siglen, key_admin); - - /* save signature */ - newGrp->adminSignature.signData.setBinData(sigbuf, siglen); - newGrp->adminSignature.keyId = grpId; - - /* clean up */ - delete serialType; - EVP_MD_CTX_destroy(mdctx); - - - /******************* clean up all Keys *******************/ - - RSA_free(rsa_admin_pub); - RSA_free(rsa_publish_pub); - RSA_free(rsa_publish); - EVP_PKEY_free(key_admin); - - /******************* load up new Group *********************/ - loadGroup(newGrp, false); - - /* add Keys to GroupInfo */ - RsStackMutex stack(distribMtx); /************* STACK MUTEX ************/ - GroupInfo *gi = locked_getGroupInfo(grpId); - if (!gi) - { - return grpId; - } - - gi->flags |= RS_DISTRIB_SUBSCRIBED; - mGroupsRepublish = true; - - /* replace the public keys */ - locked_updateGroupAdminKey(*gi, adKey); - locked_updateGroupPublishKey(*gi, pubKey); - - delete adKey; - delete pubKey; - delete[] data; - return grpId; -} - - -bool p3GroupDistrib::backUpKeys(const std::list& keysToBackUp, std::string grpId){ - -#ifdef DISTRIB_DEBUG - std::cerr << "P3Distrib::backUpKeys() Backing up keys for grpId: " << grpId << std::endl; -#endif - - std::string filename = mKeyBackUpDir + "/" + grpId + "_" + BACKUP_KEY_FILE; - std::string filenametmp = filename + ".tmp"; - - BinInterface *bio = new BinFileInterface(filenametmp.c_str(), BIN_FLAGS_WRITEABLE); - pqistore *store = createStore(bio, mOwnId, BIN_FLAGS_NO_DELETE | BIN_FLAGS_WRITEABLE); - - std::list::const_iterator it; - bool ok = true; - - for(it=keysToBackUp.begin(); it != keysToBackUp.end(); it++){ - - ok &= store->SendItem(*it); - - } - - delete store; - - if(!RsDirUtil::renameFile(filenametmp,filename)) - { - std::string errlog; -#ifdef WIN32 - rs_sprintf(errlog, "Error %u", GetLastError()); -#else - rs_sprintf(errlog, "Error %d", errno); -#endif - getPqiNotify()->AddSysMessage(0, RS_SYS_WARNING, "File rename error", "Error while renaming file " + filename + ": got error " + errlog); - return false; - } - - return ok; -} - -bool p3GroupDistrib::restoreGrpKeys(const std::string& grpId){ - - -#ifdef DISTRIB_DEBUG - std::cerr << "p3Distrib::restoreGrpKeys() Attempting to restore private keys for grp: " - << grpId << std::endl; -#endif - - // build key directory name - std::string filename = mKeyBackUpDir + "/"+ grpId + "_" + BACKUP_KEY_FILE; - - - /* create the serialiser to load keys */ - BinInterface *bio = new BinFileInterface(filename.c_str(), BIN_FLAGS_READABLE); - pqistore *store = createStore(bio, mOwnId, BIN_FLAGS_READABLE); - - RsItem* item; - bool ok = true; - bool itemAttempted = false; - RsDistribGrpKey* key = NULL; - - RsStackMutex stack(distribMtx); - - GroupInfo* gi = locked_getGroupInfo(grpId); - - //retrieve keys from file and load to appropriate grp - while(NULL != (item = store->GetItem())){ - - itemAttempted = true; - key = dynamic_cast(item); - - if(key == NULL){ -#ifdef DISTRIB_DEBUG - std::cerr << "p3groupDistrib::restoreGrpKey() Key file / grp key item not Valid, grp: " - "\ngrpId: " << grpId << std::endl; -#endif - delete store ; - return false; - } - - if(key->key.keyFlags & RSTLV_KEY_DISTRIB_ADMIN) - ok &= locked_updateGroupAdminKey(*gi, key); - else if((key->key.keyFlags & RSTLV_KEY_DISTRIB_PRIVATE) || - (key->key.keyFlags & RSTLV_KEY_DISTRIB_PUBLIC)) - ok &= locked_updateGroupPublishKey(*gi, key); - else - ok &= false; - - } - - - - ok &= itemAttempted; - - if(ok){ - gi->flags |= RS_DISTRIB_SUBSCRIBED; - locked_notifyGroupChanged(*gi, GRP_SUBSCRIBED, false); - IndicateConfigChanged(); - mGroupsRepublish = true; - } - -#ifdef DISTRIB_DEBUG - if(!ok){ - std::cerr << "p3Distrib::restoreGrpKeys() Failed to restore private keys for grp " - << "\ngrpId: " << grpId << std::endl; - } -#endif - - delete store; - - return ok; -} - - -bool p3GroupDistrib::sharePubKey(std::string grpId, std::list& peers){ - - RsStackMutex stack(distribMtx); - - // first check that group actually exists - if(mGroups.find(grpId) == mGroups.end()){ -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::sharePubKey(): Group does not exist" << std::endl; -#endif - return false; - } - - // add to pending list to be sent - mPendingPubKeyRecipients[grpId] = peers; - - return true; -} - -void p3GroupDistrib::locked_sharePubKey(){ - - -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_sharePubKey() " << std::endl; -#endif - - std::map >::iterator mit; - std::list::iterator lit; - - // get list of peers that are online - std::list peersOnline; - rsPeers->getOnlineList(peersOnline); - std::list toDelete; - - /* send public key to peers online */ - - for(mit = mPendingPubKeyRecipients.begin(); mit != mPendingPubKeyRecipients.end(); mit++){ - - GroupInfo *gi = locked_getGroupInfo(mit->first); - - if(gi == NULL){ - toDelete.push_back(mit->first); // grp does not exist, stop attempting to share key for dead group - continue; - } - - // find full public key, and send to given peers - std::map::iterator kit; - for(kit = gi->publishKeys.begin(); - kit != gi->publishKeys.end(); kit++) - { - if (kit->second.type & RSTLV_KEY_TYPE_FULL) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_sharePubKey() Sharing Key: " << kit->first; - std::cerr << std::endl; -#endif - - // send keys to peers who are online - for(lit = mit->second.begin() ; lit != mit->second.end(); lit++){ - - if(std::find(peersOnline.begin(), peersOnline.end(), *lit) != peersOnline.end()){ - - /* create Key for sharing */ - RsDistribGrpKey* pubKey = new RsDistribGrpKey(getRsItemService(getType())); - - - pubKey->clear(); - pubKey->grpId = mit->first; - - RSA *rsa_priv = EVP_PKEY_get1_RSA(kit->second.key); - p3DistribSecurity::setRSAPrivateKey(pubKey->key, rsa_priv); - RSA_free(rsa_priv); - - pubKey->key.keyFlags = kit->second.type; - pubKey->key.startTS = kit->second.startTS; - pubKey->key.endTS = kit->second.endTS; - pubKey->PeerId(*lit); - std::cout << *lit << std::endl; - sendItem(pubKey); - - // remove peer from list - lit = mit->second.erase(lit); // no need to send to peer anymore - lit--; - } - } - } - } - - // if given peers have all received key(s) then stop sending for group - if(mit->second.empty()) - toDelete.push_back(mit->first); - } - - // delete pending peer list which are done with - for(lit = toDelete.begin(); lit != toDelete.end(); lit++) - mPendingPubKeyRecipients.erase(*lit); - - mLastKeyPublishTime = time(NULL); - - return; -} - - -void p3GroupDistrib::receivePubKeys(){ - - - RsItem* item; - std::string gid; - - std::map::iterator it; - std::list toDelete; - std::list::iterator sit; - - - // load received keys - while(NULL != (item = recvItem())){ - - RsDistribGrpKey* key_item = dynamic_cast(item); - - if(key_item != NULL){ - RsStackMutex stack(distribMtx); - - it = mGroups.find(key_item->grpId); - - // if group does not exist keep to see if it arrives later - if(it == mGroups.end()){ - - // make sure key is in date - if(((time_t)(key_item->key.startTS + mStorePeriod) > time(NULL)) && - (key_item->key.keyFlags & RSTLV_KEY_TYPE_FULL)){ - - // make sure keys does not exist in recieved list, then delete - if(mRecvdPubKeys.find(gid) == mRecvdPubKeys.end()){ - - // id key as shared so on loadlist sends back mRecvdPubKeys - key_item->key.keyFlags |= RSTLV_KEY_TYPE_SHARED; - mRecvdPubKeys.insert(std::pair(key_item->grpId, key_item)); - - mPubKeyAvailableGrpId.insert(key_item->grpId); - } - - }else{ - delete key_item; - } - - continue; - } - -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_receiveKeys()" << std::endl; - std::cerr << "PeerId : " << key_item->PeerId() << std::endl; - std::cerr << "GrpId: " << key_item->grpId << std::endl; - std::cerr << "Got key Item" << std::endl; -#endif - if(key_item->key.keyFlags & RSTLV_KEY_TYPE_FULL){ - - gid = key_item->grpId; - - // add key if user is subscribed if not store it until user subscribes - - if(locked_updateGroupPublishKey(it->second, key_item)){ - - mPubKeyAvailableGrpId.insert(key_item->grpId); - locked_notifyGroupChanged(it->second, GRP_LOAD_KEY, false); - - // keep key if user not subscribed - if(it->second.flags & RS_DISTRIB_SUBSCRIBED){ - - delete key_item; - - }else{ - - // make sure keys does not exist in recieved list - if(mRecvdPubKeys.find(gid) == mRecvdPubKeys.end()){ - - // id key as shared so on loadlist sends back to mRecvdPubKeys - key_item->key.keyFlags |= RSTLV_KEY_TYPE_SHARED; - mRecvdPubKeys.insert(std::pair(key_item->grpId, key_item)); - - } - } - - } - } - else{ - std::cerr << "p3GroupDistrib::locked_receiveKeys():" << "Not full public key" - << "Deleting item"<< std::endl; - - delete key_item; - } - } - else{ - delete item; - } - } - - - - - RsStackMutex stack(distribMtx); - - // indicate config changed and also record the groups keys received for - if(!mRecvdPubKeys.empty()) - IndicateConfigChanged(); - - return; - - - } - - -std::string p3GroupDistrib::publishMsg(RsDistribMsg *msg, bool personalSign) -{ - -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::publishMsg()" << std::endl; - msg->print(std::cerr, 10); - std::cerr << std::endl; -#endif - - /* extract grpId */ - std::string grpId = msg->grpId; - std::string msgId; - - RsDistribSignedMsg *signedMsg = NULL; - - /* ensure Group exists */ - { /* STACK MUTEX */ - - RsStackMutex stack(distribMtx); /************* STACK MUTEX ************/ - GroupInfo *gi = locked_getGroupInfo(grpId); - if (!gi) - { - #ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::publishMsg() No Group"; - std::cerr << std::endl; - #endif - return msgId; - } - - /******************* FIND KEY ******************************/ - if (!locked_choosePublishKey(*gi)) - { - #ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::publishMsg() No Publish Key(1)"; - std::cerr << std::endl; - #endif - return msgId; - } - - /* find valid publish_key */ - EVP_PKEY *publishKey = NULL; - std::map::iterator kit; - kit = gi->publishKeys.find(gi->publishKeyId); - if (kit != gi->publishKeys.end()) - { - publishKey = kit->second.key; - } - - if (!publishKey) - { - #ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::publishMsg() No Publish Key"; - std::cerr << std::endl; - #endif - /* no publish Key */ - return msgId; - } - - /******************* FIND KEY ******************************/ - - signedMsg = new RsDistribSignedMsg(); - - RsSerialType *serialType = createSerialiser(); - uint32_t size = serialType->size(msg); - char *data = new char[size]; - serialType->serialise(msg, data, &size); - - char *out_data = NULL; - uint32_t out_size = 0; - - // encrypt data if group is private - - if(gi->grpFlags & RS_DISTRIB_ENCRYPTED){ - - EVP_PKEY * privateKey = NULL; - std::map::iterator kit; - - for(kit = gi->publishKeys.begin(); kit != gi->publishKeys.end(); kit++ ){ - // Does not allow for possibility of different keys - - if((kit->second.type & RSTLV_KEY_TYPE_FULL) && (kit->second.key->type == EVP_PKEY_RSA)){ - privateKey = kit->second.key; - break; - } - } - - if(kit == gi->publishKeys.end()){ - #ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::publishMsg(): Cannot find full key for encryption, " - << "grpId " << grpId - << std::endl; - #endif - return msgId; - } - - if(p3DistribSecurity::encrypt((void*&)out_data, (int&)out_size, (void*&)data, (int)size, privateKey)){ - - delete[] data; - }else{ - delete[] data; - delete signedMsg; - delete serialType; - return msgId; - } - - }else - { - out_data = data; - out_size = size; - } - - signedMsg->packet.setBinData(out_data, out_size); - - /* sign Packet */ - - /* calc and check signature */ - EVP_MD_CTX *mdctx = EVP_MD_CTX_create(); - - EVP_SignInit(mdctx, EVP_sha1()); - EVP_SignUpdate(mdctx, out_data, out_size); - - unsigned int siglen = EVP_PKEY_size(publishKey); - unsigned char sigbuf[siglen]; - EVP_SignFinal(mdctx, sigbuf, &siglen, publishKey); - - /* save signature */ - signedMsg->publishSignature.signData.setBinData(sigbuf, siglen); - signedMsg->publishSignature.keyId = gi->publishKeyId; - - bool ok = true; - - if (personalSign) - { - unsigned int siglen = MAX_GPG_SIGNATURE_SIZE; - unsigned char sigbuf[siglen]; - if (AuthGPG::getAuthGPG()->SignDataBin(out_data, out_size, sigbuf, &siglen)) - { - signedMsg->personalSignature.signData.setBinData(sigbuf, siglen); - signedMsg->personalSignature.keyId = AuthGPG::getAuthGPG()->getGPGOwnId(); - } else { - ok = false; - } - } - - /* clean up */ - delete serialType; - EVP_MD_CTX_destroy(mdctx); - delete[] out_data; - - if (ok == false) { - delete signedMsg; - return msgId; - } - - } /* END STACK MUTEX */ - - /* extract Ids from publishSignature */ - signedMsg->msgId = p3DistribSecurity::getBinDataSign( - signedMsg->publishSignature.signData.bin_data, - signedMsg->publishSignature.signData.bin_len); - signedMsg->grpId = grpId; - signedMsg->timestamp = msg->timestamp; - - msgId = signedMsg->msgId; - - /* delete original msg */ - delete msg; - -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::publishMsg() Created SignedMsg:"; - std::cerr << std::endl; - signedMsg->print(std::cerr, 10); - std::cerr << std::endl; -#endif - - /* load proper - - * If we pretend it is coming from an alternative source - * it'll automatically get published with other msgs - */ - - signedMsg->PeerId(mOwnId); - loadMsg(signedMsg, mOwnId, false, false); - - /* done */ - return msgId; -} - - - - -/********************* Overloaded Functions **************************/ - - -bool p3GroupDistrib::locked_checkGroupInfo(GroupInfo &info, RsDistribGrp *newGrp) -{ -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_checkGroupInfo()"; - std::cerr << std::endl; -#endif - /* groupInfo */ - - /* If adminKey is the same and - * timestamp is <= timestamp, or not an update (info edit) - * then just discard it. - */ - - if (info.grpId != newGrp->grpId) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_checkGroupInfo() Failed GrpId Wrong"; - std::cerr << std::endl; -#endif - return false; - } - - if ((info.distribGroup) && (newGrp->timestamp <= info.distribGroup->timestamp)) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_checkGroupInfo() Group Data Old/Same"; - std::cerr << std::endl; -#endif - /* old or same info -> drop it */ - return false; - } - - /* otherwise validate it */ - return p3DistribSecurity::validateDistribGrp(newGrp); -} - - -/* return false - to cleanup (delete group) afterwards, - * true - we've kept the data - */ -bool p3GroupDistrib::locked_updateGroupInfo(GroupInfo &info, RsDistribGrp *newGrp) -{ - /* new group has been validated already - * update information. - */ - -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_updateGroupInfo()"; - std::cerr << std::endl; -#endif - - if (info.distribGroup) - { - delete info.distribGroup; - } - - if (info.grpIcon.pngImageData != NULL){ - delete[] info.grpIcon.pngImageData; - info.grpIcon.imageSize = 0; - } - - info.distribGroup = newGrp; - - /* copy details */ - info.grpName = newGrp->grpName; - info.grpDesc = newGrp->grpDesc; - info.grpCategory = newGrp->grpCategory; - info.grpFlags = newGrp->grpFlags; - - if((newGrp->grpPixmap.binData.bin_data != NULL) && (newGrp->grpPixmap.binData.bin_len > 0)){ - info.grpIcon.pngImageData = new unsigned char[newGrp->grpPixmap.binData.bin_len]; - - memcpy(info.grpIcon.pngImageData, newGrp->grpPixmap.binData.bin_data, - newGrp->grpPixmap.binData.bin_len*sizeof(unsigned char)); - - info.grpIcon.imageSize = newGrp->grpPixmap.binData.bin_len; - }else{ - info.grpIcon.pngImageData = NULL; - info.grpIcon.imageSize = 0; - } - - /* pop already calculated */ - /* last post handled seperately */ - - locked_checkGroupKeys(info); - - /* if we are subscribed to the group -> then we need to republish */ - if (info.flags & RS_DISTRIB_SUBSCRIBED) - { - mGroupsRepublish = true; - } - - return true; -} - - -bool p3GroupDistrib::locked_editGroup(std::string grpId, GroupInfo& gi){ - -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_editGroup() " << grpId << std::endl; -#endif - - GroupInfo* gi_curr = locked_getGroupInfo(grpId); - - if(gi_curr == NULL){ - - std::cerr << "p3GroupDistrib::locked_editGroup() Failed, group does not exist " << grpId - << std::endl; - return false; - } - - if(!(gi_curr->flags & RS_DISTRIB_ADMIN)) - return false; - - - gi_curr->grpName = gi.grpName; - gi_curr->distribGroup->grpName = gi_curr->grpName; - gi_curr->grpDesc = gi.grpDesc; - gi_curr->distribGroup->grpDesc = gi_curr->grpDesc; - - if((gi.grpIcon.imageSize != 0) && gi.grpIcon.pngImageData != NULL){ - - if((gi_curr->distribGroup->grpPixmap.binData.bin_data != NULL) && - (gi_curr->distribGroup->grpPixmap.binData.bin_len != 0)) - gi_curr->distribGroup->grpPixmap.binData.TlvClear(); - - gi_curr->distribGroup->grpPixmap.binData.bin_data = gi_curr->grpIcon.pngImageData; - gi_curr->distribGroup->grpPixmap.binData.bin_len = gi_curr->grpIcon.imageSize; - - gi_curr->grpIcon.imageSize = gi.grpIcon.imageSize; - gi_curr->grpIcon.pngImageData = gi.grpIcon.pngImageData; - - - } - - // set new timestamp for grp - gi_curr->distribGroup->timestamp = time(NULL); - - // create new signature for group - - EVP_PKEY *key_admin = gi_curr->adminKey.key; - gi_curr->distribGroup->adminSignature.TlvClear(); - RsSerialType *serialType = new RsDistribSerialiser(); - uint32_t size = serialType->size(gi_curr->distribGroup); - char* data = new char[size]; - serialType->serialise(gi_curr->distribGroup, data, &size); - - /* calc and check signature */ - EVP_MD_CTX *mdctx = EVP_MD_CTX_create(); - EVP_SignInit(mdctx, EVP_sha1()); - EVP_SignUpdate(mdctx, data, size); - - unsigned int siglen = EVP_PKEY_size(key_admin); - unsigned char sigbuf[siglen]; - EVP_SignFinal(mdctx, sigbuf, &siglen, key_admin); - - /* save signature */ - gi_curr->distribGroup->adminSignature.signData.setBinData(sigbuf, siglen); - gi_curr->distribGroup->adminSignature.keyId = grpId; - - mGroupsChanged = true; - gi_curr->grpChanged = true; - mGroupsRepublish = true; - - - - delete[] data; - delete serialType; - EVP_MD_CTX_destroy(mdctx); - - return true; -} - -bool p3GroupDistrib::locked_checkGroupKeys(GroupInfo &info) -{ -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_checkGroupKeys()"; - std::cerr << "GrpId: " << info.grpId; - std::cerr << std::endl; -#endif - - /* iterate through publish keys - check that they exist in distribGrp, or delete */ - RsDistribGrp *grp = info.distribGroup; - - std::list removeKeys; - std::map::iterator it; - -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_checkGroupKeys() Checking if Expanded Keys still Exist"; - std::cerr << std::endl; -#endif - - for(it = info.publishKeys.begin(); it != info.publishKeys.end(); it++) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_checkGroupKeys() Publish Key: " << it->first; -#endif - /* check for key in distribGrp */ - if (grp->publishKeys.keys.end() == grp->publishKeys.keys.find(it->first)) - { - /* remove publishKey */ - removeKeys.push_back(it->first); -#ifdef DISTRIB_DEBUG - std::cerr << " Old -> to Remove" << std::endl; -#endif - - } - -#ifdef DISTRIB_DEBUG - std::cerr << " Ok" << std::endl; -#endif - - } - - while(removeKeys.size() > 0) - { - std::string rkey = removeKeys.front(); - removeKeys.pop_front(); -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_checkGroupKeys() Removing Key: " << rkey; - std::cerr << std::endl; -#endif - - it = info.publishKeys.find(rkey); - EVP_PKEY_free(it->second.key); - info.publishKeys.erase(it); - } - - /* iterate through distribGrp list - expanding any missing keys */ - std::map::iterator dit; - for(dit = grp->publishKeys.keys.begin(); dit != grp->publishKeys.keys.end(); dit++) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_checkGroupKeys() Checking for New Keys: KeyId: " << dit->first; - std::cerr << std::endl; -#endif - - it = info.publishKeys.find(dit->first); - if (it == info.publishKeys.end()) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_checkGroupKeys() Key Missing - Expand"; - std::cerr << std::endl; -#endif - - /* create a new expanded public key */ - RSA *rsa_pub = p3DistribSecurity::extractPublicKey(dit->second); - if (!rsa_pub) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_checkGroupKeys() Failed to Expand Key"; - std::cerr << std::endl; -#endif - continue; - } - - GroupKey newKey; - newKey.keyId = dit->first; - newKey.type = RSTLV_KEY_TYPE_PUBLIC_ONLY | (dit->second.keyFlags & RSTLV_KEY_DISTRIB_MASK); - newKey.startTS = dit->second.startTS; - newKey.endTS = dit->second.endTS; - - newKey.key = EVP_PKEY_new(); - EVP_PKEY_assign_RSA(newKey.key, rsa_pub); - - info.publishKeys[newKey.keyId] = newKey; - -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_checkGroupKeys() Expanded Key: " << dit->first; - std::cerr << "Key Type: " << newKey.type; - std::cerr << std::endl; - std::cerr << "Start: " << newKey.startTS; - std::cerr << std::endl; - std::cerr << "End: " << newKey.endTS; - std::cerr << std::endl; -#endif - } - } - - /* now check admin key */ - if ((info.adminKey.keyId == "") || (!info.adminKey.key)) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_checkGroupKeys() Must Expand AdminKey Too"; - std::cerr << std::endl; -#endif - - /* must expand admin key too */ - RSA *rsa_pub = p3DistribSecurity::extractPublicKey(grp->adminKey); - if (rsa_pub) - { - info.adminKey.keyId = grp->adminKey.keyId; - info.adminKey.type = RSTLV_KEY_TYPE_PUBLIC_ONLY & RSTLV_KEY_DISTRIB_ADMIN; - info.adminKey.startTS = grp->adminKey.startTS; - info.adminKey.endTS = grp->adminKey.endTS; - - info.adminKey.key = EVP_PKEY_new(); - EVP_PKEY_assign_RSA(info.adminKey.key, rsa_pub); -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_checkGroupKeys() AdminKey Expanded"; - std::cerr << std::endl; -#endif - } - else - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_checkGroupKeys() ERROR Expandng AdminKey"; - std::cerr << std::endl; -#endif - } - } - - return true; -} - - - - -bool p3GroupDistrib::locked_updateGroupAdminKey(GroupInfo &info, RsDistribGrpKey *newKey) -{ - /* so firstly - check that the KeyId matches something in the group */ - const std::string &keyId = newKey->key.keyId; - -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_updateGroupAdminKey() grpId: " << keyId; - std::cerr << std::endl; -#endif - - - if (keyId != info.grpId) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_updateGroupAdminKey() Id mismatch - ERROR"; - std::cerr << std::endl; -#endif - - return false; - } - - if (!(newKey->key.keyFlags & RSTLV_KEY_TYPE_FULL)) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_updateGroupAdminKey() Key not Full - Ignore"; - std::cerr << std::endl; -#endif - - /* not a full key -> ignore */ - return false; - } - - if (info.adminKey.type & RSTLV_KEY_TYPE_FULL) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_updateGroupAdminKey() Already have Full Key - Ignore"; - std::cerr << std::endl; -#endif - - /* if we have full key already - ignore */ - return true; - } - - /* need to update key */ - RSA *rsa_priv = p3DistribSecurity::extractPrivateKey(newKey->key); - - if (!rsa_priv) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_updateGroupAdminKey() Extract Key failed - ERROR"; - std::cerr << std::endl; -#endif - - return false; - } - - /* validate they are a matching pair */ - std::string realkeyId = p3DistribSecurity::getRsaKeySign(rsa_priv); - if ((1 != RSA_check_key(rsa_priv)) || (realkeyId != keyId)) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_updateGroupAdminKey() Validate Key Failed - ERROR"; - std::cerr << std::endl; -#endif - - /* clean up */ - RSA_free(rsa_priv); - return false; - } - - /* add it in */ - EVP_PKEY *evp_pkey = EVP_PKEY_new(); - EVP_PKEY_assign_RSA(evp_pkey, rsa_priv); - - EVP_PKEY_free(info.adminKey.key); - info.adminKey.key = evp_pkey; - info.adminKey.type = RSTLV_KEY_TYPE_FULL | RSTLV_KEY_DISTRIB_ADMIN; - - info.flags |= RS_DISTRIB_ADMIN; - -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_updateGroupAdminKey() Success"; - std::cerr << std::endl; -#endif - - return true; -} - - -bool p3GroupDistrib::locked_updateGroupPublishKey(GroupInfo &info, RsDistribGrpKey *newKey) -{ - /* so firstly - check that the KeyId matches something in the group */ - const std::string &keyId = newKey->key.keyId; - -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_updateGroupPublishKey() grpId: " << info.grpId << " keyId: " << keyId; - std::cerr << std::endl; -#endif - - - std::map::iterator it; - it = info.publishKeys.find(keyId); - if (it == info.publishKeys.end()) - { - -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_updateGroupPublishKey() key not Found - Ignore"; - std::cerr << std::endl; -#endif - - /* no key -> ignore */ - return false; - } - - if (!(newKey->key.keyFlags & RSTLV_KEY_TYPE_FULL)) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_updateGroupPublishKey() not FullKey - Ignore"; - std::cerr << std::endl; -#endif - - /* not a full key -> ignore */ - return false; - } - - if (it->second.type & RSTLV_KEY_TYPE_FULL) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_updateGroupPublishKey() already have FullKey - Ignore"; - std::cerr << std::endl; -#endif - - /* if we have full key already - ignore */ - return true; - } - - /* need to update key */ - RSA *rsa_priv = p3DistribSecurity::extractPrivateKey(newKey->key); - - if (!rsa_priv) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_updateGroupPublishKey() Private Extract Failed - ERROR"; - std::cerr << std::endl; -#endif - - return false; - } - - /* validate they are a matching pair */ - std::string realkeyId = p3DistribSecurity::getRsaKeySign(rsa_priv); - if ((1 != RSA_check_key(rsa_priv)) || (realkeyId != keyId)) - { - -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_updateGroupPublishKey() Validate Private Key failed - ERROR"; - std::cerr << std::endl; -#endif - - /* clean up */ - RSA_free(rsa_priv); - return false; - } - - /* add it in */ - EVP_PKEY *evp_pkey = EVP_PKEY_new(); - EVP_PKEY_assign_RSA(evp_pkey, rsa_priv); - - EVP_PKEY_free(it->second.key); - it->second.key = evp_pkey; - it->second.type &= (~RSTLV_KEY_TYPE_PUBLIC_ONLY); - it->second.type |= RSTLV_KEY_TYPE_FULL; - -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_updateGroupPublishKey() Success"; - std::cerr << std::endl; - std::cerr << "Key ID: " << it->first; - std::cerr << std::endl; - std::cerr << "Key Type: " << it->second.type; - std::cerr << std::endl; - std::cerr << "Start: " << it->second.startTS; - std::cerr << std::endl; - std::cerr << "End: " << it->second.endTS; - std::cerr << std::endl; -#endif - - info.flags |= RS_DISTRIB_PUBLISH; - - /* if we have updated, we are subscribed, and it is a public key */ - if ((info.flags & RS_DISTRIB_SUBSCRIBED) && - (it->second.type & RSTLV_KEY_DISTRIB_PUBLIC)) - { - mGroupsRepublish = true; - } - - return true; -} - - -bool p3GroupDistrib::locked_choosePublishKey(GroupInfo &info) -{ - -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_choosePublishKey()"; - std::cerr << std::endl; -#endif - time_t now = time(NULL); - - /******************* CHECK CURRENT KEY ******************************/ - /* if current key is valid -> okay */ - - std::map::iterator kit; - kit = info.publishKeys.find(info.publishKeyId); - if (kit != info.publishKeys.end()) - { - if ((kit->second.type & RSTLV_KEY_TYPE_FULL) && - (now < kit->second.endTS) && (now > kit->second.startTS)) - { - /* key is okay */ -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_choosePublishKey() Current Key is Okay"; - std::cerr << std::endl; -#endif - return true; - } - } - - /******************* FIND KEY ******************************/ - std::string bestKey = ""; - time_t bestEndTime = 0; - - for(kit = info.publishKeys.begin(); kit != info.publishKeys.end(); kit++) - { - -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_choosePublishKey() Found Key: "; - std::cerr << kit->first << " type: " << kit->second.type; - std::cerr << std::endl; -#endif - - if (kit->second.type & RSTLV_KEY_TYPE_FULL) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_choosePublishKey() Found FULL Key: "; - std::cerr << kit->first << " startTS: " << kit->second.startTS; - std::cerr << " endTS: " << kit->second.startTS; - std::cerr << " now: " << now; - std::cerr << std::endl; -#endif - if ((now < kit->second.endTS) && (now >= kit->second.startTS)) - { - if (kit->second.endTS > bestEndTime) - { - bestKey = kit->first; - bestEndTime = kit->second.endTS; -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_choosePublishKey() Better Key: "; - std::cerr << kit->first; - std::cerr << std::endl; -#endif - } - } - } - } - - if (bestEndTime == 0) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_choosePublishKey() No Valid Key"; - std::cerr << std::endl; -#endif - return false; - } - -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_choosePublishKey() Best Key is: " << bestKey; - std::cerr << std::endl; -#endif - - info.publishKeyId = bestKey; - return true; -} - - /* deserialise RsDistribSignedMsg */ -RsDistribMsg *p3GroupDistrib::unpackDistribSignedMsg(RsDistribSignedMsg *newMsg) -{ - RsSerialType *serialType = createSerialiser(); - uint32_t size = newMsg->packet.bin_len; - RsDistribMsg *distribMsg = (RsDistribMsg *) - serialType->deserialise(newMsg->packet.bin_data, &size); - - if (distribMsg) - { - - /* transfer data that is not in the serialiser */ - distribMsg->msgId = newMsg->msgId; - - /* Full copies required ? */ - - distribMsg->publishSignature.keyId = newMsg->publishSignature.keyId; - distribMsg->publishSignature.signData.setBinData( - newMsg->publishSignature.signData.bin_data, - newMsg->publishSignature.signData.bin_len); - - distribMsg->personalSignature.keyId = newMsg->personalSignature.keyId; - distribMsg->personalSignature.signData.setBinData( - newMsg->personalSignature.signData.bin_data, - newMsg->personalSignature.signData.bin_len); - } - - delete serialType; - - return distribMsg; -} - -void p3GroupDistrib::getGrpListPubKeyAvailable(std::list& grpList) -{ - RsStackMutex stack(distribMtx); - std::set::const_iterator cit = mPubKeyAvailableGrpId.begin(); - - for(; cit != mPubKeyAvailableGrpId.end(); cit++) - grpList.push_back(*cit); - - return; -} - -bool p3GroupDistrib::locked_checkDistribMsg( - GroupInfo &/*gi*/, RsDistribMsg *msg) -{ - - /* check timestamp */ - time_t now = time(NULL); - uint32_t min = now - mStorePeriod; - uint32_t max = now + GROUP_MAX_FWD_OFFSET; - - if ((msg->timestamp < min) || (msg->timestamp > max)) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_checkDistribMsg() TS out of range"; - std::cerr << std::endl; - std::cerr << "p3GroupDistrib::locked_checkDistribMsg() msg->timestamp: " << msg->timestamp; - std::cerr << std::endl; - std::cerr << "p3GroupDistrib::locked_checkDistribMsg() = " << now - msg->timestamp << " secs ago"; - std::cerr << std::endl; - std::cerr << "p3GroupDistrib::locked_checkDistribMsg() max TS: " << max; - std::cerr << std::endl; - std::cerr << "p3GroupDistrib::locked_checkDistribMsg() min TS: " << min; - std::cerr << std::endl; -#endif - /* if outside range -> remove */ - return false; - } - - /* check filters */ - - return true; -} - - - /* now update parents TS */ -bool p3GroupDistrib::locked_updateChildTS(GroupInfo &gi, RsDistribMsg *msg) -{ - /* find all parents - update timestamp */ - time_t updateTS = msg->timestamp; - msg->childTS = updateTS; - - while("" != msg->parentId) - { - std::string parentId = msg->parentId; - - std::map::iterator mit; - if (gi.msgs.end() == (mit = gi.msgs.find(parentId))) - { - /* not found - abandon (check for dummyMsgs first) */ - return locked_updateDummyChildTS(gi, parentId, updateTS); - - } - RsDistribMsg *parent = mit->second; - if ((!parent) || (parent->childTS > updateTS)) - { - /* we're too old - give up! */ - return true; - } - - /* update timestamp */ - parent->childTS = updateTS; - msg = parent; - } - return false ; -} - - - - - - - -/***** DEBUG *****/ - -void p3GroupDistrib::printGroups(std::ostream &out) -{ - /* iterate through all the groups */ - std::map::iterator git; - for(git = mGroups.begin(); git != mGroups.end(); git++) - { - out << "GroupId: " << git->first << std::endl; - out << "Group Details: " << std::endl; - out << git->second; - out << std::endl; - - std::map::iterator mit; - for(mit = git->second.msgs.begin(); - mit != git->second.msgs.end(); mit++) - { - out << "MsgId: " << mit->first << std::endl; - out << "Message Details: " << std::endl; - mit->second->print(out, 10); - out << std::endl; - } - } -} - - -std::ostream &operator<<(std::ostream &out, const GroupInfo &info) -{ - /* print Group Info */ - out << "GroupInfo: " << info.grpId << std::endl; - out << "sources [" << info.sources.size() << "]: "; - - std::list::const_iterator sit; - for(sit = info.sources.begin(); sit != info.sources.end(); sit++) - { - out << " " << *sit; - } - out << std::endl; - - out << " Message Count: " << info.msgs.size() << std::endl; - - std::string grpName(info.grpName.begin(), info.grpName.end()); - std::string grpDesc(info.grpDesc.begin(), info.grpDesc.end()); - - out << "Group Name: " << grpName << std::endl; - out << "Group Desc: " << grpDesc << std::endl; - out << "Group Flags: " << info.flags << std::endl; - out << "Group Pop: " << info.pop << std::endl; - out << "Last Post: " << info.lastPost << std::endl; - - out << "PublishKeyId:" << info.publishKeyId << std::endl; - - out << "Published RsDistribGrp: " << std::endl; - if (info.distribGroup) - { - info.distribGroup->print(out, 10); - } - else - { - out << "No RsDistribGroup Object" << std::endl; - } - - return out; -} - -void p3GroupDistrib::locked_notifyGroupChanged(GroupInfo &info, uint32_t /*flags*/, bool /*historical*/) -{ - mGroupsChanged = true; - info.grpChanged = true; -} - - -bool p3GroupDistrib::groupsChanged(std::list &groupIds) -{ - RsStackMutex stack(distribMtx); /************* STACK MUTEX ************/ - - /* iterate through all groups and get changed list */ - if (!mGroupsChanged) - return false; - - std::map::iterator it; - for(it = mGroups.begin(); it != mGroups.end(); it++) - { - if (it->second.grpChanged) - { - groupIds.push_back(it->first); - it->second.grpChanged = false; - } - } - - mGroupsChanged = false; - return true; -} - - - -/***************************************************************************************/ -/***************************************************************************************/ - /******************* Handle Missing Messages ***********************************/ -/***************************************************************************************/ -/***************************************************************************************/ - -/* Find missing messages */ - - - -/* LOGIC: - * - * dummy(grpId, threadId, parentId, msgId); - * - * add new msg.... - * - search for threadId. - * - if missing add thread head: dummy(grpId, threadId, NULL, threadId). - * - * - search for parentId - * - if = threadId, we just added it (ok). - * - if missing add dummy(grpId, threadId, threadId, parentId). - * - * - check for matching dummy msgId. - * - if yes, delete. - * - */ - -RsDistribDummyMsg::RsDistribDummyMsg( std::string tId, std::string pId, std::string mId, uint32_t ts) -:threadId(tId), parentId(pId), msgId(mId), timestamp(ts), childTS(ts) -{ - return; -} - -std::ostream &operator<<(std::ostream &out, const RsDistribDummyMsg &msg) -{ - out << "DummyMsg(" << msg.threadId << "," << msg.parentId << "," << msg.msgId << ")"; - return out; -} - - - -bool p3GroupDistrib::locked_CheckNewMsgDummies(GroupInfo &grp, RsDistribMsg *msg, std::string /*id*/, bool /*historical*/) -{ - std::string threadId = msg->threadId; - std::string parentId = msg->parentId; - std::string msgId = msg->msgId; - -#ifdef DISTRIB_DUMMYMSG_DEBUG - std::cerr << "p3GroupDistrib::locked_CheckNewMsgDummies(grpId:" << grp.grpId << ", threadId: " << threadId; - std::cerr << ", parentId:" << parentId << ", msgId: " << msgId << ")"; - std::cerr << std::endl; -#endif - -#ifdef DISTRIB_DUMMYMSG_DEBUG - std::cerr << "p3GroupDistrib::locked_CheckNewMsgDummies() Pre Printout"; - std::cerr << std::endl; - locked_printDummyMsgs(grp); -#endif - - - /* search for threadId */ - if (threadId != "") - { - std::map::iterator tit = grp.msgs.find(threadId); - - if (tit == grp.msgs.end()) // not there! - { -#ifdef DISTRIB_DUMMYMSG_DEBUG - std::cerr << "p3GroupDistrib::locked_CheckNewMsgDummies() No ThreadId Msg, Adding DummyMsg"; - std::cerr << std::endl; -#endif - locked_addDummyMsg(grp, threadId, "", threadId, msg->timestamp); - } - else - { -#ifdef DISTRIB_DUMMYMSG_DEBUG - std::cerr << "p3GroupDistrib::locked_CheckNewMsgDummies() Found ThreadId Msg"; - std::cerr << std::endl; -#endif - } - } - - if (parentId != "") - { - /* search for parentId */ - std::map::iterator pit = grp.msgs.find(parentId); - - if (pit == grp.msgs.end()) // not there! - { -#ifdef DISTRIB_DUMMYMSG_DEBUG - std::cerr << "p3GroupDistrib::locked_CheckNewMsgDummies() No ParentId Msg, Adding DummyMsg"; - std::cerr << std::endl; -#endif - locked_addDummyMsg(grp, threadId, threadId, parentId, msg->timestamp); - } - else - { -#ifdef DISTRIB_DUMMYMSG_DEBUG - std::cerr << "p3GroupDistrib::locked_CheckNewMsgDummies() Found ParentId Msg"; - std::cerr << std::endl; -#endif - } - } - -#ifdef DISTRIB_DUMMYMSG_DEBUG - std::cerr << "p3GroupDistrib::locked_CheckNewMsgDummies() Checking for DummyMsg"; - std::cerr << std::endl; -#endif - - /* remove existing dummy */ - locked_clearDummyMsg(grp, msgId); - - -#ifdef DISTRIB_DUMMYMSG_DEBUG - std::cerr << "p3GroupDistrib::locked_CheckNewMsgDummies() Post Printout"; - std::cerr << std::endl; - locked_printDummyMsgs(grp); -#endif - - return true; -} - -bool p3GroupDistrib::locked_addDummyMsg(GroupInfo &grp, std::string threadId, std::string parentId, std::string msgId, uint32_t ts) -{ -#ifdef DISTRIB_DUMMYMSG_DEBUG - std::cerr << "p3GroupDistrib::locked_addDummyMsg(grpId:" << grp.grpId << ", threadId: " << threadId; - std::cerr << ", parentId:" << parentId << ", msgId: " << msgId << ")"; - std::cerr << std::endl; -#endif - - if (msgId == "") - { -#ifdef DISTRIB_DUMMYMSG_DEBUG - std::cerr << "p3GroupDistrib::locked_addDummyMsg() ERROR not adding empty MsgId"; - std::cerr << std::endl; -#endif - return false; - } - - /* search for the msg Id */ - std::map::iterator dit = grp.dummyMsgs.find(msgId); - - if (dit == grp.dummyMsgs.end()) // not there! - { - grp.dummyMsgs[msgId] = RsDistribDummyMsg(threadId, parentId, msgId, ts); - - -#ifdef DISTRIB_DUMMYMSG_DEBUG - std::cerr << "p3GroupDistrib::locked_addDummyMsg() Adding Dummy Msg"; - std::cerr << std::endl; -#endif - } - else - { -#ifdef DISTRIB_DUMMYMSG_DEBUG - std::cerr << "p3GroupDistrib::locked_addDummyMsg() Dummy Msg already there: " << dit->second; - std::cerr << std::endl; -#endif - } - - locked_updateDummyChildTS(grp, parentId, ts); // NOTE both ChildTS functions should be merged. - return true; -} - -bool p3GroupDistrib::locked_clearDummyMsg(GroupInfo &grp, std::string msgId) -{ -#ifdef DISTRIB_DUMMYMSG_DEBUG - std::cerr << "p3GroupDistrib::locked_clearDummyMsg(grpId:" << grp.grpId << ", msgId: " << msgId << ")"; - std::cerr << std::endl; -#endif - - /* search for the msg Id */ - std::map::iterator dit = grp.dummyMsgs.find(msgId); - if (dit != grp.dummyMsgs.end()) - { - -#ifdef DISTRIB_DUMMYMSG_DEBUG - std::cerr << "p3GroupDistrib::locked_clearDummyMsg() Erasing Dummy Msg: " << dit->second; - std::cerr << std::endl; -#endif - - grp.dummyMsgs.erase(dit); - } - else - { -#ifdef DISTRIB_DUMMYMSG_DEBUG - std::cerr << "p3GroupDistrib::locked_clearDummyMsg() Msg not found"; - std::cerr << std::endl; -#endif - } - return true; -} - - - - /* now update parents TS */ -/* NB: it is a hack to have seperate updateChildTS functions for msgs and dummyMsgs, - * this need to be combined (do when we add a parentId index.) - */ - -bool p3GroupDistrib::locked_updateDummyChildTS(GroupInfo &gi, std::string parentId, time_t updateTS) -{ - while("" != parentId) - { - std::map::iterator mit; - if (gi.dummyMsgs.end() == (mit = gi.dummyMsgs.find(parentId))) - { - /* not found - abandon */ - return true; - } - RsDistribDummyMsg *parent = &(mit->second); - if (parent->childTS > updateTS) - { - /* we're too old - give up! */ - return true; - } - - /* update timestamp */ - parent->childTS = updateTS; - parentId = parent->parentId; - } - return false ; -} - - -bool p3GroupDistrib::locked_printAllDummyMsgs() -{ -#ifdef DISTRIB_DUMMYMSG_DEBUG - std::cerr << "p3GroupDistrib::locked_printAllDummyMsg()"; - std::cerr << std::endl; -#endif - std::map::iterator it; - for(it = mGroups.begin(); it != mGroups.end(); it++) - { - locked_printDummyMsgs(it->second); - } - return true ; -} - - - -bool p3GroupDistrib::locked_printDummyMsgs(GroupInfo &grp) -{ -#ifdef DISTRIB_DUMMYMSG_DEBUG - std::cerr << "p3GroupDistrib::locked_printDummyMsg(grpId:" << grp.grpId << ")"; - std::cerr << std::endl; -#endif - - /* search for the msg Id */ - std::map::iterator dit; - for(dit = grp.dummyMsgs.begin(); dit != grp.dummyMsgs.end(); dit++) - { - std::cerr << dit->second; - std::cerr << std::endl; - } - return true; -} - - -/***** These Functions are used by the children classes to access the dummyData - ****/ - -bool p3GroupDistrib::getDummyParentMsgList(const std::string& grpId, const std::string& pId, std::list &msgIds) -{ - -#ifdef DISTRIB_DUMMYMSG_DEBUG - std::cerr << "p3GroupDistrib::getDummyParentMsgList(grpId:" << grpId << "," << pId << ")"; - std::cerr << std::endl; -#endif - - processCacheOptReq(grpId); - - RsStackMutex stack(distribMtx); /************* STACK MUTEX ************/ - - - std::map::iterator git; - if (mGroups.end() == (git = mGroups.find(grpId))) - { -#ifdef DISTRIB_DUMMYMSG_DEBUG - std::cerr << "p3GroupDistrib::getDummyParentMsgList() Group Not Found"; - std::cerr << std::endl; -#endif - return false; - } - - std::map::iterator mit; - - for(mit = git->second.dummyMsgs.begin(); mit != git->second.dummyMsgs.end(); mit++) - { - if (mit->second.parentId == pId) - { - msgIds.push_back(mit->first); - } - } - -#ifdef DISTRIB_DUMMYMSG_DEBUG - std::cerr << "p3GroupDistrib::getDummyParentMsgList() found " << msgIds.size() << " msgs"; - std::cerr << std::endl; -#endif - return true; -} - - -RsDistribDummyMsg *p3GroupDistrib::locked_getGroupDummyMsg(const std::string& grpId, const std::string& msgId) -{ - -#ifdef DISTRIB_DUMMYMSG_DEBUG - std::cerr << "p3GroupDistrib::locked_getGroupDummyMsg(grpId:" << grpId << "," << msgId << ")"; - std::cerr << std::endl; -#endif - /************* ALREADY LOCKED ************/ - std::map::iterator git; - if (mGroups.end() == (git = mGroups.find(grpId))) - { -#ifdef DISTRIB_DUMMYMSG_DEBUG - std::cerr << "p3GroupDistrib::locked_getGroupDummyMsg() Group not found"; - std::cerr << std::endl; -#endif - return NULL; - } - - std::map::iterator dit; - if (git->second.dummyMsgs.end() == (dit = git->second.dummyMsgs.find(msgId))) - { -#ifdef DISTRIB_DUMMYMSG_DEBUG - std::cerr << "p3GroupDistrib::locked_getGroupDummyMsg() Msg not found"; - std::cerr << std::endl; -#endif - return NULL; - } - - return &(dit->second); -} - diff --git a/libretroshare/src/distrib/p3distrib.h b/libretroshare/src/distrib/p3distrib.h deleted file mode 100644 index 9a8cde917..000000000 --- a/libretroshare/src/distrib/p3distrib.h +++ /dev/null @@ -1,756 +0,0 @@ -/* - * libretroshare/src/distrib: p3distrib.h - * - * - * Copyright 2004-2011 by Robert Fernie. - * 2010-2011 Christopher Evi-Parker - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License Version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 - * USA. - * - * Please report all bugs and problems to "retroshare@lunamutt.com". - * - */ - -#ifndef P3_GENERIC_DISTRIB_HEADER -#define P3_GENERIC_DISTRIB_HEADER - -#include "pqi/pqi.h" -#include "pqi/pqistore.h" -#include "pqi/p3cfgmgr.h" -#include "services/p3service.h" -#include "dbase/cachestrapper.h" -#include "serialiser/rsdistribitems.h" - -#include -#include - -#include -#include - -/* - * Group Messages.... - * - * Forums / Channels / Blogs... - * - * - * Plan. - * - * (1) First create basic structures .... algorithms. - * - * (2) integrate with Cache Source/Store for data transmission. - * (3) integrate with Serialiser for messages - * (4) bring over the final key parts from existing p3channel. - */ - -const uint32_t GROUP_MAX_FWD_OFFSET = (60 * 60 * 24 * 2); /* 2 Days */ - - -/* - * A data structure to store dummy (missing) msgs. - * They are added to the GroupInfo if there is a missing parent Msg of thread Msg - * Basic Logic is: - * - */ - -class RsDistribDummyMsg -{ - public: - RsDistribDummyMsg( std::string tId, std::string pId, std::string mId, uint32_t ts); - RsDistribDummyMsg() { return; } - std::string threadId; - std::string parentId; - std::string msgId; - - uint32_t timestamp; - time_t childTS; /* timestamp of most recent child */ -}; - - -//! for storing group keys to members of a group -/*! - * This key but be of many types, including private/public publish key, or admin prite key for group - * @see p3GroupDistrib - */ -class GroupKey -{ - public: - - GroupKey() - :type(0), startTS(0), endTS(0), key(NULL) { return; } - - uint32_t type; /// whether key is full or public - std::string keyId; - time_t startTS, endTS; - EVP_PKEY *key; /// actual group key in evp format -}; - -//! used to store group picture -/*! - * ensures use of png image format - * @see p3GroupDistrib - */ -class GroupIcon{ -public: - GroupIcon(): pngImageData(NULL), imageSize(0) { - return; - } - - ~GroupIcon(){ - - if((pngImageData != NULL) && (imageSize > 0)) - delete[] pngImageData; - - return; - } - - unsigned char* pngImageData; /// pointer to image data in png format - int imageSize; -}; - -//! used by p3groupDistrib to store mirror info found in rsDistribGroup (i.e. messages, posts, etc) -/*! - * used by p3Groudistrib to store group info, also used to communicate group information - * to p3groupdistrib inherited classes. contain - * @see rsDistribGroup - */ -class GroupInfo -{ - public: - - GroupInfo() - :distribGroup(NULL), grpFlags(0), pop(0), lastPost(0), flags(0), grpChanged(false) - { - return; - } - virtual ~GroupInfo() ; - - std::string grpId; /// the group id - RsDistribGrp *distribGroup; /// item which contains further information on group - - std::list sources; - std::map msgs; - std::map dummyMsgs; // dummyMsgs. - - /***********************************/ - - /* Copied from DistribGrp */ - std::wstring grpName; - std::wstring grpDesc; /// group description - std::wstring grpCategory; - uint32_t grpFlags; /// PRIVACY & AUTHENTICATION - - - uint32_t pop; /// popularity sources.size() - time_t lastPost; /// modded as msgs added - - /***********************************/ - - uint32_t flags; /// PUBLISH, SUBSCRIBE, ADMIN - - - std::string publishKeyId; /// current active Publish Key - std::map publishKeys; - - GroupKey adminKey; - - - GroupIcon grpIcon; - /* NOT USED YET */ - - std::map decrypted_msg_cache; /// stores a cache of messages that have been decrypted - - bool publisher, allowAnon, allowUnknown; - bool subscribed, listener; - - uint32_t type; - - /// FLAG for Client - set if changed - bool grpChanged; -}; - - - -std::ostream &operator<<(std::ostream &out, const GroupInfo &info); - -//! information on what cache stores group info -/*! - * This can refer to idividual cache message, data etc - */ -class GroupCache -{ - public: - - std::string filename; - time_t start, end; - uint16_t cacheSubId; /// used to resolve complete cache id -}; - - /* Flags for locked_notifyGroupChanged() ***/ - -const uint32_t GRP_NEW_UPDATE = 0x0001; -const uint32_t GRP_UPDATE = 0x0002; -const uint32_t GRP_LOAD_KEY = 0x0003; -const uint32_t GRP_NEW_MSG = 0x0004; -const uint32_t GRP_SUBSCRIBED = 0x0005; -const uint32_t GRP_UNSUBSCRIBED = 0x0006; - - -typedef std::map > CacheOptData; - - -//! Cache based service to implement group messaging -/*! - * - * Group Description: - * - * Master Public/Private Key: (Admin Key) used to control - * Group Name/Description/Icon. - * Filter Lists. - * Publish Keys. - * - * Publish Keys. - * TimeStore Length determined by inheriting class - * - * Everyone gets: - * Master Public Key. - * Publish Public Keys. - * blacklist, or whitelist filter. (Only useful for Non-Anonymous groups) - * Name, Desc, - * etc. - * - * Admins get Master Private Key. - * Publishers get Publish Private Key. - * - Channels only some get publish key. - * - Forums everyone gets publish private key. - * - * Group id is the public admin keys id - * - */ - -/* - * To Handle Cache Data Loading.... we want to be able to seperate Historical - * from new data (primarily for the gui's benefit). - * to do this we have a mHistoricalCaches flag, which is automatically raised at startup, - * and a function is called to cancel it (HistoricalCachesDone()). - */ - -class CacheDataPending -{ - public: - - CacheDataPending(const CacheData &data, bool local, bool historical); - CacheData mData; - bool mLocal; - bool mHistorical; -}; - -class p3GroupDistrib: public CacheSource, public CacheStore, public p3Config, public p3ThreadedService -{ - public: - - p3GroupDistrib(uint16_t subtype, - CacheStrapper *cs, CacheTransfer *cft, - std::string sourcedir, std::string storedir, std::string keyBackUpDir, - uint32_t configId, - uint32_t storePeriod, uint32_t pubPeriod); - - virtual ~p3GroupDistrib() ; - -/***************************************************************************************/ -/******************************* CACHE SOURCE / STORE Interface ************************/ -/***************************************************************************************/ -/* TO FINISH */ - - public: - - virtual bool loadLocalCache(const CacheData &data); /// overloaded from Cache Source - virtual int loadCache(const CacheData &data); /// overloaded from Cache Store - - - /* From RsThread */ - virtual void run(); /* called once the thread is started */ - - void HistoricalCachesDone(); // called when Stored Caches have been added to Pending List. - - - private: - - // derived from CacheSource - virtual bool isPeerAcceptedAsCacheReceiver(const std::string& ssl_id) ; - // derived from CacheStore - virtual bool isPeerAcceptedAsCacheProvider(const std::string& ssl_id) ; - - /* these lists are filled by the overloaded fns... then cleared by the thread */ - bool mHistoricalCaches; // initially true.... falsified by HistoricalCachesDone() - std::list mPendingCaches; - - /* top level load */ - int loadAnyCache(const CacheData &data, bool local, bool historical); - - /* load cache files */ - void loadFileGroups(const std::string &filename, const std::string &src, bool local, bool historical); - void loadFileMsgs(const std::string &filename, const CacheData& , bool local, bool historical); - bool backUpKeys(const std::list &keysToBackUp, std::string grpId); - void locked_sharePubKey(); - - /*! - * Attempt to load public key from recvd list if it exists for grpId - * @param grpId the id for the group for which private publish key is wanted - */ - bool attemptPublishKeysRecvd(); - - - - - /*! - * Simply load cache opt messages - * @param data - */ - void loadCacheOptMsgs(const CacheData& data, const std::string& grpId); - - protected: - - /* load cache msgs */ - - /*! - * processes cache opt request by loading data for group - * @param grpId the group to process request for - * @return false if group does not exist - */ - bool processCacheOptReq(const std::string &grpId); - - /*! - * msg is loaded to its group and republished, - * msg decrypted if grp is private - * @param msg msg to loaded - * @param src src of msg (peer id) - * @param local is this a local cache msg (your msg) - */ - bool loadMsg(RsDistribSignedMsg *msg, const std::string &src, bool local, bool historical); - - /*! - * msg is loaded to its group and republished, - * msg decrypted if grp is private - * @param msg msg to loaded - * @param src src of msg (peer id) - * @param local is this a local cache msg (your msg) - */ - bool locked_loadMsg(RsDistribSignedMsg *newMsg, const std::string &src, bool local, bool historical); - - /*! - * adds newgrp to grp set, GroupInfo type created and stored - * @param newGrp grp to be added - */ - bool loadGroup(RsDistribGrp *newGrp, bool historical); - - /*! - * Adds new keys dependent on whether it is an admin or publish key - * on return resource pointed to by newKey should be considered invalid - * @param newKey key to be added - * @return if key is loaded to group or stored return true - */ - bool loadGroupKey(RsDistribGrpKey *newKey, bool historical); - - - -/***************************************************************************************/ -/***************************************************************************************/ - -/***************************************************************************************/ -/**************************** Create Content *******************************************/ -/***************************************************************************************/ -/* TO FINISH */ - - public: - - /*! - * This create a distributed grp which is sent via cache system to connected peers - * @param name name of the group created - * @param desc description of the group - * @param flags privacy flag - * @param pngImageData pointer to image data, data is copied - * @param imageSize size of the image passed - * @return id of the group - */ - std::string createGroup(std::wstring name, std::wstring desc, uint32_t flags, unsigned char *pngImageData, uint32_t imageSize); - - /*! - * msg is packed into a signed message (and encrypted msg grp is private) and then sent via cache system to connnected peers - * @param msg - * @param personalSign whether to personal to sign image (this is done using gpg cert) - * @return the msg id - */ - std::string publishMsg(RsDistribMsg *msg, bool personalSign); - - /*! - * note: call back to locked_eventDuplicateMSg is made on execution - * @param grpId id of group to subscribe to - * @param subscribe true to subscribe and vice versa - * @return - */ - bool subscribeToGroup(const std::string &grpId, bool subscribe); - - - - /***************************************************************************************/ - /***************************************************************************************/ - - /***************************************************************************************/ - /****************************** Access Content ***************************************/ - /***************************************************************************************/ - - public: - - /*! - * get Group Lists - */ - bool getAllGroupList(std::list &grpids); - bool getSubscribedGroupList(std::list &grpids); - bool getPublishGroupList(std::list &grpids); - - /*! - * - * @param popMin lower limit for a grp's populairty in grpids - * @param popMax upper limit for a grp's popularity in grpids - * @param grpids grpids of grps which adhere to upper and lower limit of popularity - * @return nothing returned - */ - void getPopularGroupList(uint32_t popMin, uint32_t popMax, std::list &grpids); - - - /* get Msg Lists */ - bool getAllMsgList(const std::string& grpId, std::list &msgIds); - bool getParentMsgList(const std::string& grpId, const std::string& pId, std::list &msgIds); - bool getTimePeriodMsgList(const std::string& grpId, uint32_t timeMin, - uint32_t timeMax, std::list &msgIds); - - - GroupInfo *locked_getGroupInfo(const std::string& grpId); - RsDistribMsg *locked_getGroupMsg(const std::string& grpId, const std::string& msgId); - - /*! - * for retrieving the grpList for which public keys are available - */ - void getGrpListPubKeyAvailable(std::list& grpList); - - /* Filter Messages */ - -/***************************************************************************************/ -/***************************** Event Feedback ******************************************/ -/***************************************************************************************/ - - protected: - /*! - * root version (p3Distrib::) of this function must be called - */ - virtual void locked_notifyGroupChanged(GroupInfo &info, uint32_t flags, bool historical); - - /*! - * client (inheriting class) should use this to determing behaviour of - * their service when a duplicate msg is found - * @param group should be called when duplicate message loaded - * @param the duplicate message - * @param id - * @param historical: is this msg from an historical cache - * @return successfully executed or not - */ - virtual bool locked_eventDuplicateMsg(GroupInfo *, RsDistribMsg *, const std::string& id, bool historical) = 0; - - /*! - * Inheriting class should implement this as a response to a new msg arriving - * @param - * @param - * @param id src of msg (peer id) - * @param historical: is this msg from an historical cache - * @return - */ - virtual bool locked_eventNewMsg(GroupInfo *, RsDistribMsg *, const std::string& id, bool historical) = 0; - -/***************************************************************************************/ -/********************************* p3Config ********************************************/ -/***************************************************************************************/ -/* TO FINISH */ - - protected: - - virtual RsSerialiser *setupSerialiser(); - virtual bool saveList(bool &cleanup, std::list& saveList); - virtual void saveDone(); - virtual bool loadList(std::list& load); - - /*! - * called by top class, child can use to save configs - */ - virtual std::list childSaveList() = 0; - - /*! - * called by top class, child can use to load configs - */ - virtual bool childLoadList(std::list& configSaves) = 0; - -/***************************************************************************************/ -/***************************************************************************************/ - - public: - - virtual int tick(); /* overloaded form pqiService */ - -/***************************************************************************************/ -/**************************** Publish Content ******************************************/ -/***************************************************************************************/ -/* TO FINISH */ - protected: - - /* create/mod cache content */ - - /*! - * adds msg to pending msg map - * @param msg a signed message by peer - */ - void locked_toPublishMsg(RsDistribSignedMsg *msg); - - /*! - * adds pending msg - */ - void publishPendingMsgs(); - - /*! - * sends created groups to cache, to be passed to cache listeners - */ - void publishDistribGroups(); - - /*! - * removes old caches based on store period (anything that has been in local cache longer - * than the store period is deleted - * @param now the current time when method is called - */ - void clear_local_caches(time_t now); - - /*! - * assumes RsDistribMtx is locked when call is made - */ - void locked_publishPendingMsgs(); - - /*! - * @return cache sub id - */ - uint16_t locked_determineCacheSubId(); - - /** - * grp keys are backed up when a grp is created this allows user to retrieve lost keys in case config saving fails - * @param grpId the grpId id for which backup keys should be restored - * @return false if failed and vice versa - */ - virtual bool restoreGrpKeys(const std::string& grpId); /// restores a group keys from backup - - /** - * Allows user to send keys to a list of peers - * @param grpId the group for which to share public keys - * @param peers The peers to which public keys should be sent - */ - virtual bool sharePubKey(std::string grpId, std::list& peers); - - /** - * Attempt to receive publication keys - */ - virtual void receivePubKeys(); - - /** - * Allows group admin(s) to change group icon, description and name - *@param grpId group id - *@param gi the changes to grp name, icon, and description should be reflected here - */ - virtual bool locked_editGroup(std::string grpId, GroupInfo& gi); - - - /***************************************************************************************/ - /***************************************************************************************/ - - /***************************************************************************************/ - /*************************** Overloaded Functions **************************************/ - /***************************************************************************************/ - - /*! - * Overloaded by inherited classes to Pack/UnPack their messages - * @return inherited class's serialiser - */ - virtual RsSerialType *createSerialiser() = 0; - - /*! Used to Create/Load Cache Files only - * @param bio binary i/o - * @param src peer id from which write/read content originates - * @param bioflags read write permision for bio - * @return pointer to pqistore instance - */ - virtual pqistore *createStore(BinInterface *bio, const std::string &src, uint32_t bioflags); - - virtual bool locked_checkGroupInfo(GroupInfo &info, RsDistribGrp *newGrp); - virtual bool locked_updateGroupInfo(GroupInfo &info, RsDistribGrp *newGrp); - virtual bool locked_checkGroupKeys(GroupInfo &info); - - /*! - * @param info group for which admin key will be added to - * @param newKey admin key - * @return true if key successfully added - */ - virtual bool locked_updateGroupAdminKey(GroupInfo &info, RsDistribGrpKey *newKey); - - - /*! - * @param info group for which publish key will be added to - * @param newKey publish key - * @return true if publish key successfully added - */ - virtual bool locked_updateGroupPublishKey(GroupInfo &info, RsDistribGrpKey *newKey); - - /*! - * Use this to retrieve packed message from a signed message - * @param newMsg signed message - * @return pointer to unpacked msg - */ - virtual RsDistribMsg* unpackDistribSignedMsg(RsDistribSignedMsg *newMsg); - - - /*! - * message is checked to see if it is in a valid time range - * @param info - * @param msg message to be checked - * @return false if msg is outside correct time range - */ - virtual bool locked_checkDistribMsg(GroupInfo &info, RsDistribMsg *msg); - - /*! - * chooses the best publish key based on it being full and latest - * @param info group to choose publish key - * @return true if a publish key could be found - */ - virtual bool locked_choosePublishKey(GroupInfo &info); - - -//virtual RsDistribGrp *locked_createPublicDistribGrp(GroupInfo &info); -//virtual RsDistribGrp *locked_createPrivateDistribGrp(GroupInfo &info); - - -/***************************************************************************************/ -/***************************** Utility Functions ***************************************/ -/***************************************************************************************/ -/* TO FINISH */ - - /* utilities */ - std::string HashRsItem(const RsItem *item); - bool locked_updateChildTS(GroupInfo &gi, RsDistribMsg *msg); - -/***************************************************************************************/ -/***************************************************************************************/ - -/***************************************************************************************/ -/***************************** Utility Functions ***************************************/ -/***************************************************************************************/ - public: - - void printGroups(std::ostream &out); - - /*! - * returns list of ids for group caches that have changed - */ - bool groupsChanged(std::list &groupIds); - -/***************************************************************************************/ -/***************************************************************************************/ - - -/***************************************************************************************/ -/**************************** DummyMsgs Functions **************************************/ -/***************************************************************************************/ - public: - -bool locked_CheckNewMsgDummies(GroupInfo &info, RsDistribMsg *msg, std::string id, bool historical); -bool locked_addDummyMsg(GroupInfo &info, std::string threadId, std::string parentId, std::string msgId, uint32_t ts); -bool locked_clearDummyMsg(GroupInfo &info, std::string msgId); -bool locked_updateDummyChildTS(GroupInfo &gi, std::string parentId, time_t updateTS); // NOTE MUST BE MERGED WITH nromal version. - -bool locked_printAllDummyMsgs(); -bool locked_printDummyMsgs(GroupInfo &info); - - /* access the dummy msgs */ -bool getDummyParentMsgList(const std::string& grpId, const std::string& pId, std::list &msgIds); -RsDistribDummyMsg *locked_getGroupDummyMsg(const std::string& grpId, const std::string& msgId); - - - /* key cache functions - we use .... (not overloaded) - */ - - /* storage */ - protected: - - RsMutex distribMtx; /// Protects all class atrributes - std::string mOwnId; /// rs peer id - - private: - - std::list mLocalCaches; - std::map mGroups; - uint32_t mStorePeriod, mPubPeriod; - - /* Message Publishing */ - std::list mPendingPublish; - time_t mLastPublishTime; - std::map mLocalCacheTs; - uint16_t mMaxCacheSubId; - - bool mGroupsChanged; - bool mGroupsRepublish; - - std::list saveCleanupList; /* TEMPORARY LIST WHEN SAVING */ - std::string mKeyBackUpDir; - const std::string BACKUP_KEY_FILE; - - std::map mRecvdPubKeys; /// full publishing keys received from users - std::map > mPendingPubKeyRecipients; /// peers to receive publics key for a given grp - std::set mPubKeyAvailableGrpId; // groups id for which public keys are available - time_t mLastKeyPublishTime, mLastRecvdKeyTime; - - - /**** cache opt ****/ - - /* - * 1. when rs starts it loads only subscribed groups - * 2. and for unsubscribed groups these are store with their grp to cache mappings - * 3. when user clicks on a group this activates process cache which loads cache for only that group - * - */ - - /// stores map of grp to cache mapping - CacheOptData mGrpCacheMap; - - /// group subscribed to at start of rs - std::set mSubscribedGrp; - - /// unsubscribed groups that are already loaded - std::set mCacheOptLoaded; - - /// current exception group - std::string mCurrGrpException; - - - - -}; - - -/***************************************************************************************/ -/***************************************************************************************/ - -#endif // P3_GENERIC_DISTRIB_HEADER diff --git a/libretroshare/src/distrib/p3distribsecurity.cc b/libretroshare/src/distrib/p3distribsecurity.cc deleted file mode 100644 index 67f9e330a..000000000 --- a/libretroshare/src/distrib/p3distribsecurity.cc +++ /dev/null @@ -1,478 +0,0 @@ -/* - * libretroshare/src/distrib: p3distribverify.cc - * - * - * Copyright 2008-2010 by Robert Fernie - * 2011 Christopher Evi-Parker - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License Version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 - * USA. - * - * Please report all bugs and problems to "retroshare@lunamutt.com". - * - */ - -#include "p3distribsecurity.h" -#include "pqi/authgpg.h" -#include "retroshare/rsdistrib.h" -#include "retroshare/rspeers.h" - -p3DistribSecurity::p3DistribSecurity() -{ -} - -p3DistribSecurity::~p3DistribSecurity() -{ -} - -RSA *p3DistribSecurity::extractPublicKey(RsTlvSecurityKey& key) -{ - const unsigned char *keyptr = (const unsigned char *) key.keyData.bin_data; - long keylen = key.keyData.bin_len; - - /* extract admin key */ - RSA *rsakey = d2i_RSAPublicKey(NULL, &(keyptr), keylen); - - return rsakey; -} - - -bool p3DistribSecurity::validateDistribSignedMsg(GroupInfo & info, RsDistribSignedMsg *newMsg) -{ -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_validateDistribSignedMsg()"; - std::cerr << std::endl; - std::cerr << "GroupInfo -> distribGrp:"; - std::cerr << std::endl; - info.distribGroup->print(std::cerr, 10); - std::cerr << std::endl; - std::cerr << "RsDistribSignedMsg: "; - std::cerr << std::endl; - newMsg->print(std::cerr, 10); - std::cerr << std::endl; -#endif - -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_validateDistribSignedMsg() publish KeyId: " << newMsg->publishSignature.keyId << std::endl; - std::cerr << "p3GroupDistrib::locked_validateDistribSignedMsg() personal KeyId: " << newMsg->personalSignature.keyId << std::endl; -#endif - - /********************* check signature *******************/ - - /* find the right key */ - RsTlvSecurityKeySet &keyset = info.distribGroup->publishKeys; - - std::map::iterator kit; - kit = keyset.keys.find(newMsg->publishSignature.keyId); - - if (kit == keyset.keys.end()) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_validateDistribSignedMsg() Missing Publish Key"; - std::cerr << std::endl; -#endif - return false; - } - - /* check signature timeperiod */ - if ((newMsg->timestamp < kit->second.startTS) || - (newMsg->timestamp > kit->second.endTS)) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_validateDistribSignedMsg() TS out of range"; - std::cerr << std::endl; -#endif - return false; - } - - /* decode key */ - const unsigned char *keyptr = (const unsigned char *) kit->second.keyData.bin_data; - long keylen = kit->second.keyData.bin_len; - unsigned int siglen = newMsg->publishSignature.signData.bin_len; - unsigned char *sigbuf = (unsigned char *) newMsg->publishSignature.signData.bin_data; - -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_validateDistribSignedMsg() Decode Key"; - std::cerr << " keylen: " << keylen << " siglen: " << siglen; - std::cerr << std::endl; -#endif - - /* extract admin key */ - RSA *rsakey = d2i_RSAPublicKey(NULL, &(keyptr), keylen); - - if (!rsakey) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_validateDistribSignedMsg()"; - std::cerr << " Invalid RSA Key"; - std::cerr << std::endl; - - unsigned long err = ERR_get_error(); - std::cerr << "RSA Load Failed .... CODE(" << err << ")" << std::endl; - std::cerr << ERR_error_string(err, NULL) << std::endl; - - kit->second.print(std::cerr, 10); -#endif - } - - - EVP_PKEY *signKey = EVP_PKEY_new(); - EVP_PKEY_assign_RSA(signKey, rsakey); - - /* calc and check signature */ - EVP_MD_CTX *mdctx = EVP_MD_CTX_create(); - - EVP_VerifyInit(mdctx, EVP_sha1()); - EVP_VerifyUpdate(mdctx, newMsg->packet.bin_data, newMsg->packet.bin_len); - int signOk = EVP_VerifyFinal(mdctx, sigbuf, siglen, signKey); - - /* clean up */ - EVP_PKEY_free(signKey); - EVP_MD_CTX_destroy(mdctx); - - /* now verify Personal signature */ - if ((signOk == 1) && ((info.grpFlags & RS_DISTRIB_AUTHEN_MASK) & RS_DISTRIB_AUTHEN_REQ)) - { - unsigned int personalsiglen = - newMsg->personalSignature.signData.bin_len; - unsigned char *personalsigbuf = (unsigned char *) - newMsg->personalSignature.signData.bin_data; - - RsPeerDetails signerDetails; - std::string gpg_fpr; - if (AuthGPG::getAuthGPG()->getGPGDetails(newMsg->personalSignature.keyId, signerDetails)) - { - gpg_fpr = signerDetails.fpr; - } - - bool gpgSign = AuthGPG::getAuthGPG()->VerifySignBin( - newMsg->packet.bin_data, newMsg->packet.bin_len, - personalsigbuf, personalsiglen, gpg_fpr); - if (gpgSign) { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_validateDistribSignedMsg() Success for gpg signature." << std::endl; -#endif - signOk = 1; - } else { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_validateDistribSignedMsg() Fail for gpg signature." << std::endl; -#endif - signOk = 0; - } - } - - if (signOk == 1) - { -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_validateDistribSignedMsg() Signature OK"; - std::cerr << std::endl; -#endif - return true; - } - -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::locked_validateDistribSignedMsg() Signature invalid"; - std::cerr << std::endl; -#endif - - return false; -} - - - -std::string p3DistribSecurity::getBinDataSign(void *data, int len) -{ - unsigned char *tmp = (unsigned char *) data; - - // copy first CERTSIGNLEN bytes... - if (len > CERTSIGNLEN) - { - len = CERTSIGNLEN; - } - - std::string id; - for(uint32_t i = 0; i < CERTSIGNLEN; i++) - { - rs_sprintf_append(id, "%02x", (uint16_t) (((uint8_t *) (tmp))[i])); - } - - return id; -} - - - -bool p3DistribSecurity::encrypt(void *& out, int & outlen, const void *in, int inlen, EVP_PKEY *privateKey) -{ - - -#ifdef DISTRIB_DEBUG - std::cerr << "p3DistribSecurity::encrypt() " << std::endl; -#endif - - RSA *rsa_publish_pub = NULL; - EVP_PKEY *public_key = NULL; - - RSA* rsa_publish = EVP_PKEY_get1_RSA(privateKey); - rsa_publish_pub = RSAPublicKey_dup(rsa_publish); - - - if(rsa_publish_pub != NULL){ - public_key = EVP_PKEY_new(); - EVP_PKEY_assign_RSA(public_key, rsa_publish_pub); - }else{ -#ifdef DISTRIB_DEBUG - std::cerr << "p3DistribSecurity(): Could not generate publish key " << grpId - << std::endl; -#endif - return false; - } - - EVP_CIPHER_CTX ctx; - int eklen, net_ekl; - unsigned char *ek; - unsigned char iv[EVP_MAX_IV_LENGTH]; - EVP_CIPHER_CTX_init(&ctx); - int out_currOffset = 0; - int out_offset = 0; - - int max_evp_key_size = EVP_PKEY_size(public_key); - ek = (unsigned char*)malloc(max_evp_key_size); - const EVP_CIPHER *cipher = EVP_aes_128_cbc(); - int cipher_block_size = EVP_CIPHER_block_size(cipher); - int size_net_ekl = sizeof(net_ekl); - - int max_outlen = inlen + cipher_block_size + EVP_MAX_IV_LENGTH + max_evp_key_size + size_net_ekl; - - // intialize context and send store encrypted cipher in ek - if(!EVP_SealInit(&ctx, EVP_aes_128_cbc(), &ek, &eklen, iv, &public_key, 1)) return false; - - // now assign memory to out accounting for data, and cipher block size, key length, and key length val - out = new unsigned char[inlen + cipher_block_size + size_net_ekl + eklen + EVP_MAX_IV_LENGTH]; - - net_ekl = htonl(eklen); - memcpy((unsigned char*)out + out_offset, &net_ekl, size_net_ekl); - out_offset += size_net_ekl; - - memcpy((unsigned char*)out + out_offset, ek, eklen); - out_offset += eklen; - - memcpy((unsigned char*)out + out_offset, iv, EVP_MAX_IV_LENGTH); - out_offset += EVP_MAX_IV_LENGTH; - - // now encrypt actual data - if(!EVP_SealUpdate(&ctx, (unsigned char*) out + out_offset, &out_currOffset, (unsigned char*) in, inlen)) return false; - - // move along to partial block space - out_offset += out_currOffset; - - // add padding - if(!EVP_SealFinal(&ctx, (unsigned char*) out + out_offset, &out_currOffset)) return false; - - // move to end - out_offset += out_currOffset; - - // make sure offset has not gone passed valid memory bounds - if(out_offset > max_outlen) return false; - - // free encrypted key data - free(ek); - - outlen = out_offset; - return true; - - delete[] ek; - -#ifdef DISTRIB_DEBUG - std::cerr << "p3DistribSecurity::encrypt() finished with outlen : " << outlen << std::endl; -#endif - - return true; -} - - -bool p3DistribSecurity::decrypt(void *& out, int & outlen, const void *in, int inlen, EVP_PKEY *privateKey) -{ - -#ifdef DISTRIB_DEBUG - std::cerr << "p3DistribSecurity::decrypt() " << std::endl; -#endif - - EVP_CIPHER_CTX ctx; - int eklen = 0, net_ekl = 0; - unsigned char *ek = NULL; - unsigned char iv[EVP_MAX_IV_LENGTH]; - ek = (unsigned char*)malloc(EVP_PKEY_size(privateKey)); - EVP_CIPHER_CTX_init(&ctx); - - int in_offset = 0, out_currOffset = 0; - int size_net_ekl = sizeof(net_ekl); - - memcpy(&net_ekl, (unsigned char*)in, size_net_ekl); - eklen = ntohl(net_ekl); - in_offset += size_net_ekl; - - memcpy(ek, (unsigned char*)in + in_offset, eklen); - in_offset += eklen; - - memcpy(iv, (unsigned char*)in + in_offset, EVP_MAX_IV_LENGTH); - in_offset += EVP_MAX_IV_LENGTH; - - const EVP_CIPHER* cipher = EVP_aes_128_cbc(); - - if(!EVP_OpenInit(&ctx, cipher, ek, eklen, iv, privateKey)) return false; - - out = new unsigned char[inlen - in_offset]; - - if(!EVP_OpenUpdate(&ctx, (unsigned char*) out, &out_currOffset, (unsigned char*)in + in_offset, inlen - in_offset)) return false; - - in_offset += out_currOffset; - outlen += out_currOffset; - - if(!EVP_OpenFinal(&ctx, (unsigned char*)out + out_currOffset, &out_currOffset)) return false; - - outlen += out_currOffset; - - free(ek); - - return true; -} - -std::string p3DistribSecurity::getRsaKeySign(RSA *pubkey) -{ - int len = BN_num_bytes(pubkey -> n); - unsigned char tmp[len]; - BN_bn2bin(pubkey -> n, tmp); - - // copy first CERTSIGNLEN bytes... - if (len > CERTSIGNLEN) - { - len = CERTSIGNLEN; - } - - std::string id; - for(uint32_t i = 0; i < CERTSIGNLEN; i++) - { - rs_sprintf_append(id, "%02x", (uint16_t) (((uint8_t *) (tmp))[i])); - } - - return id; -} - - -bool p3DistribSecurity::validateDistribGrp(RsDistribGrp *newGrp) -{ -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::validateDistribGrp()"; - std::cerr << std::endl; -#endif - - /* check signature */ - RsSerialType *serialType = new RsDistribSerialiser(); - - - - /* copy out signature (shallow copy) */ - RsTlvKeySignature tmpSign = newGrp->adminSignature; - unsigned char *sigbuf = (unsigned char *) tmpSign.signData.bin_data; - unsigned int siglen = tmpSign.signData.bin_len; - - /* clear signature */ - newGrp->adminSignature.TlvClear(); - - uint32_t size = serialType->size(newGrp); - char* data = new char[size]; - - serialType->serialise(newGrp, data, &size); - - - const unsigned char *keyptr = (const unsigned char *) newGrp->adminKey.keyData.bin_data; - long keylen = newGrp->adminKey.keyData.bin_len; - - /* extract admin key */ - RSA *rsakey = d2i_RSAPublicKey(NULL, &(keyptr), keylen); - - EVP_PKEY *key = EVP_PKEY_new(); - EVP_PKEY_assign_RSA(key, rsakey); - - /* calc and check signature */ - EVP_MD_CTX *mdctx = EVP_MD_CTX_create(); - - EVP_VerifyInit(mdctx, EVP_sha1()); - EVP_VerifyUpdate(mdctx, data, size); - int ans = EVP_VerifyFinal(mdctx, sigbuf, siglen, key); - - - /* restore signature */ - newGrp->adminSignature = tmpSign; - tmpSign.TlvClear(); - - /* clean up */ - EVP_PKEY_free(key); - delete serialType; - EVP_MD_CTX_destroy(mdctx); - delete[] data; - - if (ans == 1) - return true; - -#ifdef DISTRIB_DEBUG - std::cerr << "p3GroupDistrib::validateDistribGrp() Signature invalid"; - std::cerr << std::endl; -#endif - return false; - -} - - - -void p3DistribSecurity::setRSAPublicKey(RsTlvSecurityKey & key, RSA *rsa_pub) -{ - unsigned char data[10240]; /* more than enough space */ - unsigned char *ptr = data; - int reqspace = i2d_RSAPublicKey(rsa_pub, &ptr); - - key.keyData.setBinData(data, reqspace); - - std::string keyId = getRsaKeySign(rsa_pub); - key.keyId = keyId; -} - - - -void p3DistribSecurity::setRSAPrivateKey(RsTlvSecurityKey & key, RSA *rsa_priv) -{ - unsigned char data[10240]; /* more than enough space */ - unsigned char *ptr = data; - int reqspace = i2d_RSAPrivateKey(rsa_priv, &ptr); - - key.keyData.setBinData(data, reqspace); - - std::string keyId = getRsaKeySign(rsa_priv); - key.keyId = keyId; -} - - - -RSA *p3DistribSecurity::extractPrivateKey(RsTlvSecurityKey & key) -{ - const unsigned char *keyptr = (const unsigned char *) key.keyData.bin_data; - long keylen = key.keyData.bin_len; - - /* extract admin key */ - RSA *rsakey = d2i_RSAPrivateKey(NULL, &(keyptr), keylen); - - return rsakey; -} - - diff --git a/libretroshare/src/distrib/p3distribsecurity.h b/libretroshare/src/distrib/p3distribsecurity.h deleted file mode 100644 index 44a1919d2..000000000 --- a/libretroshare/src/distrib/p3distribsecurity.h +++ /dev/null @@ -1,132 +0,0 @@ -/* - * libretroshare/src/distrib: p3distribverify.h - * - * 3P/PQI network interface for RetroShare. - * - * Copyright 2008-2010 by Robert Fernie - * 2011 Christopher Evi-Parker - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License Version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 - * USA. - * - * Please report all bugs and problems to "retroshare@lunamutt.com". - * - */ - -#ifndef P3DISTRIBVERIFY_H_ -#define P3DISTRIBVERIFY_H_ - -#include "serialiser/rstlvkeys.h" -#include "distrib/p3distrib.h" - -#include -#include - - -/*! - * This contains functionality for performing security - * operations needed to validate data received in p3GroupDistrib - * Also has functionality to receive data - */ -class p3DistribSecurity { - -public: - - p3DistribSecurity(); - ~p3DistribSecurity(); - - /*! - * extracts the public key from an RsTlvSecurityKey - * @param key RsTlvSecurityKey to extract public RSA key from - * @return pointer to the public RSA key if successful, null otherwise - */ - static RSA *extractPublicKey(RsTlvSecurityKey &key); - - /*! - * extracts the public key from an RsTlvSecurityKey - * @param key RsTlvSecurityKey to extract private RSA key from - * @return pointer to the private RSA key if successful, null otherwise - */ - static RSA *extractPrivateKey(RsTlvSecurityKey &key); - - /*! - * stores the rsa public key in a RsTlvSecurityKey - * @param key RsTlvSecurityKey to store the public rsa key in - * @param rsa_pub - */ - static void setRSAPublicKey(RsTlvSecurityKey &key, RSA *rsa_pub); - - /*! - * stores the rsa private key in a RsTlvSecurityKey - * @param key stores the rsa private key in a RsTlvSecurityKey - * @param rsa_priv the rsa private key to store - */ - static void setRSAPrivateKey(RsTlvSecurityKey &key, RSA *rsa_priv); - - /*! - * extracts signature from RSA key - * @param pubkey - * @return signature of RSA key in hex format - */ - static std::string getRsaKeySign(RSA *pubkey); - - /*! - * extracts the signature and stores it in a string - * in hex format - * @param data - * @param len - * @return - */ - static std::string getBinDataSign(void *data, int len); - - /*! - * Encrypts data using envelope encryption (taken from open ssl's evp_sealinit ) - * only full publish key holders can encrypt data for given group - *@param out - *@param outlen - *@param in - *@param inlen - */ - static bool encrypt(void *&out, int &outlen, const void *in, int inlen, EVP_PKEY *privateKey); - - - /** - * Decrypts data using evelope decryption (taken from open ssl's evp_sealinit ) - * only full publish key holders can decrypt data for a group - * @param out where decrypted data is written to - * @param outlen - * @param in - * @param inlen - * @return false if encryption failed - */ - static bool decrypt(void *&out, int &outlen, const void *in, int inlen, EVP_PKEY *privateKey); - - /*! - * uses grp signature to check if group has been - * tampered with - * @param newGrp - * @return true if group valid false otherwise - */ - static bool validateDistribGrp(RsDistribGrp *newGrp); - - /*! - * uses groupinfo public key to verify signature of signed message - * @param info groupinfo for which msg is meant for - * @param msg - * @return false if verfication of signature is not passed - */ - static bool validateDistribSignedMsg(GroupInfo &info, RsDistribSignedMsg *msg); -}; - -#endif /* P3DISTRIBVERIFY_H_ */ diff --git a/libretroshare/src/libretroshare.pro b/libretroshare/src/libretroshare.pro index 8dd5ca93a..59479a845 100644 --- a/libretroshare/src/libretroshare.pro +++ b/libretroshare/src/libretroshare.pro @@ -9,10 +9,6 @@ CONFIG += test_voip # This should be disabled for releases until further notice. #CONFIG += gxs debug -# Beware: All data of the stripped services are lost -DEFINES *= PQI_DISABLE_TUNNEL -#ENABLE_CACHE_OPT - profiling { QMAKE_CXXFLAGS -= -fomit-frame-pointer QMAKE_CXXFLAGS *= -pg -g -fno-omit-frame-pointer @@ -78,13 +74,9 @@ SOURCES += tcponudp/udppeer.cc \ -PUBLIC_HEADERS = retroshare/rsblogs.h \ - retroshare/rschannels.h \ - retroshare/rsdisc.h \ - retroshare/rsdistrib.h \ +PUBLIC_HEADERS = retroshare/rsdisc.h \ retroshare/rsexpr.h \ retroshare/rsfiles.h \ - retroshare/rsforums.h \ retroshare/rshistory.h \ retroshare/rsiface.h \ retroshare/rsinit.h \ @@ -101,15 +93,13 @@ PUBLIC_HEADERS = retroshare/rsblogs.h \ retroshare/rsdsdv.h \ retroshare/rsconfig.h + HEADERS += plugins/pluginmanager.h \ plugins/dlfcn_win32.h \ serialiser/rspluginitems.h HEADERS += $$PUBLIC_HEADERS -# public headers to be... -HEADERS += retroshare/rsgame.h \ - retroshare/rsphoto.h ################################# Linux ########################################## linux-* { @@ -309,8 +299,6 @@ HEADERS += dbase/cachestrapper.h \ dbase/findex.h \ dbase/fistore.h -#HEADERS += dht/p3bitdht.h \ - HEADERS += ft/ftchunkmap.h \ ft/ftcontroller.h \ ft/ftdata.h \ @@ -361,7 +349,6 @@ HEADERS += pqi/authssl.h \ pqi/pqissl.h \ pqi/pqissllistener.h \ pqi/pqisslpersongrp.h \ - pqi/pqissltunnel.h \ pqi/pqissludp.h \ pqi/pqisslproxy.h \ pqi/pqistore.h \ @@ -380,13 +367,8 @@ HEADERS += rsserver/p3discovery.h \ HEADERS += serialiser/rsbaseitems.h \ serialiser/rsbaseserial.h \ - serialiser/rsblogitems.h \ - serialiser/rschannelitems.h \ serialiser/rsconfigitems.h \ serialiser/rsdiscitems.h \ - serialiser/rsdistribitems.h \ - serialiser/rsforumitems.h \ - serialiser/rsgameitems.h \ serialiser/rshistoryitems.h \ serialiser/rsmsgitems.h \ serialiser/rsserial.h \ @@ -404,33 +386,22 @@ HEADERS += serialiser/rsbaseitems.h \ serialiser/rstlvbanlist.h \ serialiser/rsbanlistitems.h \ serialiser/rsbwctrlitems.h \ - serialiser/rstunnelitems.h -HEADERS += services/p3channels.h \ - services/p3chatservice.h \ +HEADERS += services/p3chatservice.h \ services/p3disc.h \ - services/p3forums.h \ - services/p3gamelauncher.h \ - services/p3gameservice.h \ services/p3msgservice.h \ services/p3service.h \ services/p3statusservice.h \ services/p3dsdv.h \ services/p3banlist.h \ - services/p3bwctrl.h \ - services/p3tunnel.h + services/p3bwctrl.h # services/p3discovery2.h \ -HEADERS += distrib/p3distrib.h \ - distrib/p3distribsecurity.h -# services/p3blogs.h \ - HEADERS += turtle/p3turtle.h \ turtle/rsturtleitem.h \ turtle/turtletypes.h - HEADERS += util/folderiterator.h \ util/rsdebug.h \ util/smallobject.h \ @@ -496,7 +467,6 @@ SOURCES += pqi/authgpg.cc \ pqi/pqissl.cc \ pqi/pqissllistener.cc \ pqi/pqisslpersongrp.cc \ - pqi/pqissltunnel.cc \ pqi/pqissludp.cc \ pqi/pqisslproxy.cc \ pqi/pqistore.cc \ @@ -524,13 +494,8 @@ SOURCES += plugins/pluginmanager.cc \ SOURCES += serialiser/rsbaseitems.cc \ serialiser/rsbaseserial.cc \ - serialiser/rsblogitems.cc \ - serialiser/rschannelitems.cc \ serialiser/rsconfigitems.cc \ serialiser/rsdiscitems.cc \ - serialiser/rsdistribitems.cc \ - serialiser/rsforumitems.cc \ - serialiser/rsgameitems.cc \ serialiser/rshistoryitems.cc \ serialiser/rsmsgitems.cc \ serialiser/rsserial.cc \ @@ -548,13 +513,9 @@ SOURCES += serialiser/rsbaseitems.cc \ serialiser/rstlvbanlist.cc \ serialiser/rsbanlistitems.cc \ serialiser/rsbwctrlitems.cc \ - serialiser/rstunnelitems.cc -SOURCES += services/p3channels.cc \ - services/p3chatservice.cc \ +SOURCES += services/p3chatservice.cc \ services/p3disc.cc \ - services/p3forums.cc \ - services/p3gamelauncher.cc \ services/p3msgservice.cc \ services/p3service.cc \ services/p3statusservice.cc \ @@ -565,11 +526,6 @@ SOURCES += services/p3channels.cc \ # services/p3discovery2.cc \ -# removed because getPeer() doesn t exist services/p3tunnel.cc - -SOURCES += distrib/p3distrib.cc \ - distrib/p3distribsecurity.cc - SOURCES += turtle/p3turtle.cc \ turtle/rsturtleitem.cc # turtle/turtlerouting.cc \ @@ -794,12 +750,3 @@ test_bitdht { - -use_blogs { - - HEADERS += services/p3blogs.h - SOURCES += services/p3blogs.cc - - DEFINES *= RS_USE_BLOGS -} - diff --git a/libretroshare/src/pqi/p3linkmgr.cc b/libretroshare/src/pqi/p3linkmgr.cc index 3c7759f8d..dbc56daf1 100644 --- a/libretroshare/src/pqi/p3linkmgr.cc +++ b/libretroshare/src/pqi/p3linkmgr.cc @@ -136,7 +136,6 @@ p3LinkMgrIMPL::p3LinkMgrIMPL(p3PeerMgrIMPL *peerMgr, p3NetMgrIMPL *netMgr) { RsStackMutex stack(mLinkMtx); /****** STACK LOCK MUTEX *******/ - mAllowTunnelConnection = false; mDNSResolver = new DNSResolver(); mRetryPeriod = MIN_RETRY_PERIOD; @@ -159,18 +158,6 @@ p3LinkMgrIMPL::p3LinkMgrIMPL(p3PeerMgrIMPL *peerMgr, p3NetMgrIMPL *netMgr) return; } -void p3LinkMgrIMPL::setTunnelConnection(bool b) -{ - RsStackMutex stack(mLinkMtx); /****** STACK LOCK MUTEX *******/ - mAllowTunnelConnection = b; -} - -bool p3LinkMgrIMPL::getTunnelConnection() -{ - RsStackMutex stack(mLinkMtx); /****** STACK LOCK MUTEX *******/ - return mAllowTunnelConnection; -} - bool p3LinkMgrIMPL::setLocalAddress(struct sockaddr_in addr) { RsStackMutex stack(mLinkMtx); /****** STACK LOCK MUTEX *******/ @@ -695,13 +682,6 @@ bool p3LinkMgrIMPL::connectAttempt(const std::string &id, struct sockaddr_in &ra it->second.linkType |= RS_NET_CONN_TRANS_UDP_UNKNOWN; } } - else if (type & RS_NET_CONN_TUNNEL) - { -#ifdef LINKMGR_DEBUG_LINKTYPE - std::cerr << "p3LinkMgrIMPL::connectAttempt() type & TUNNEL => TUNNEL" << std::endl; -#endif - it->second.linkType |= RS_NET_CONN_TRANS_TUNNEL; - } else { #ifdef LINKMGR_DEBUG_LINKTYPE @@ -1529,16 +1509,7 @@ bool p3LinkMgrIMPL::tryConnectUDP(const std::string &id, struct sockaddr_in &r #ifdef LINKMGR_DEBUG std::cerr << "p3LinkMgrIMPL::retryConnectUDP() Peer Already Connected" << std::endl; #endif - if (it->second.connecttype & RS_NET_CONN_TUNNEL) { -#ifdef LINKMGR_DEBUG - std::cerr << "p3LinkMgrIMPL::retryConnectUDP() Peer Connected through a tunnel connection, let's try a normal connection." << std::endl; -#endif - } else { -#ifdef LINKMGR_DEBUG - std::cerr << "p3LinkMgrIMPL::retryConnectUDP() Peer Connected no more connection attempts" << std::endl; -#endif - return false; - } + return false; } /* Explicit Request to start the UDP connection */ @@ -1614,19 +1585,7 @@ bool p3LinkMgrIMPL::retryConnectTCP(const std::string &id) #ifdef LINKMGR_DEBUG std::cerr << "p3LinkMgrIMPL::retryConnectTCP() Peer Already Connected" << std::endl; #endif - if (it->second.connecttype & RS_NET_CONN_TUNNEL) - { -#ifdef LINKMGR_DEBUG - std::cerr << "p3LinkMgrIMPL::retryConnectTCP() Peer Connected through a tunnel connection, let's try a normal connection." << std::endl; -#endif - } - else - { -#ifdef LINKMGR_DEBUG - std::cerr << "p3LinkMgrIMPL::retryConnectTCP() Peer Connected no more connection attempts" << std::endl; -#endif - return false; - } + return false; } } /****** END of LOCKED ******/ @@ -1683,8 +1642,6 @@ bool p3LinkMgrIMPL::retryConnectTCP(const std::string &id) locked_ConnectAttempt_HistoricalAddresses(&(it->second), histAddrs); - //locked_ConnectAttempt_AddTunnel(&(it->second)); - /* finish it off */ return locked_ConnectAttempt_Complete(&(it->second)); } @@ -2046,31 +2003,6 @@ void p3LinkMgrIMPL::locked_ConnectAttempt_ProxyAddress(peerConnectState *peer, } -void p3LinkMgrIMPL::locked_ConnectAttempt_AddTunnel(peerConnectState *peer) -{ - if (!(peer->state & RS_PEER_S_CONNECTED) && mAllowTunnelConnection) - { -#ifdef LINKMGR_DEBUG - std::cerr << "Adding TUNNEL Connection Attempt"; - std::cerr << std::endl; -#endif - peerConnectAddress pca; - pca.type = RS_NET_CONN_TUNNEL; - pca.ts = time(NULL); - pca.period = 0; - - sockaddr_clear(&pca.addr); - - sockaddr_clear(&(pca.proxyaddr)); - sockaddr_clear(&(pca.srcaddr)); - pca.bandwidth = 0; - - - addAddressIfUnique(peer->connAddrs, pca, false); - } -} - - bool p3LinkMgrIMPL::addAddressIfUnique(std::list &addrList, peerConnectAddress &pca, bool pushFront) { /* iterate through the list, and make sure it isn't already diff --git a/libretroshare/src/pqi/p3linkmgr.h b/libretroshare/src/pqi/p3linkmgr.h index f5526e1c3..c5918fa2d 100644 --- a/libretroshare/src/pqi/p3linkmgr.h +++ b/libretroshare/src/pqi/p3linkmgr.h @@ -42,7 +42,6 @@ class DNSResolver ; /* order of attempts ... */ const uint32_t RS_NET_CONN_TCP_ALL = 0x000f; const uint32_t RS_NET_CONN_UDP_ALL = 0x00f0; -const uint32_t RS_NET_CONN_TUNNEL = 0x0f00; const uint32_t RS_NET_CONN_TCP_LOCAL = 0x0001; const uint32_t RS_NET_CONN_TCP_EXTERNAL = 0x0002; @@ -182,8 +181,6 @@ virtual struct sockaddr_in getLocalAddress() = 0; virtual void getFriendList(std::list &ssl_peers) = 0; // ONLY used by p3peers.cc USE p3PeerMgr instead. virtual bool getFriendNetStatus(const std::string &id, peerConnectState &state) = 0; // ONLY used by p3peers.cc -virtual void setTunnelConnection(bool b) = 0; // ONLY used by p3peermgr.cc & p3peers.cc MOVE => p3PeerMgr -virtual bool getTunnelConnection() = 0; // ONLY used by p3peermgr.cc & p3peers.cc MOVE => p3PeerMgr /************* DEPRECIATED FUNCTIONS (TO REMOVE) ********/ virtual int addFriend(const std::string &ssl_id, bool isVisible) = 0; @@ -250,9 +247,6 @@ virtual void peerConnectRequest(std::string id, struct sockaddr_in raddr, virtual void getFriendList(std::list &ssl_peers); // ONLY used by p3peers.cc USE p3PeerMgr instead. virtual bool getFriendNetStatus(const std::string &id, peerConnectState &state); // ONLY used by p3peers.cc -virtual void setTunnelConnection(bool b); // ONLY used by p3peermgr.cc & p3peers.cc MOVE => p3PeerMgr -virtual bool getTunnelConnection(); // ONLY used by p3peermgr.cc & p3peers.cc MOVE => p3PeerMgr - /************************************************************************************************/ /* Extra IMPL Functions (used by p3PeerMgr, p3NetMgr + Setup) */ /************************************************************************************************/ diff --git a/libretroshare/src/pqi/p3peermgr.cc b/libretroshare/src/pqi/p3peermgr.cc index 65c7faa4d..8009ec7b8 100644 --- a/libretroshare/src/pqi/p3peermgr.cc +++ b/libretroshare/src/pqi/p3peermgr.cc @@ -1381,7 +1381,6 @@ bool p3PeerMgrIMPL::saveList(bool &cleanup, std::list& saveData) /* create a list of current peers */ cleanup = false; bool useExtAddrFinder = mNetMgr->getIPServersEnabled(); - bool allowTunnelConnection = mLinkMgr->getTunnelConnection(); mPeerMtx.lock(); /****** MUTEX LOCKED *******/ @@ -1486,14 +1485,6 @@ bool p3PeerMgrIMPL::saveList(bool &cleanup, std::list& saveData) RsConfigKeyValueSet *vitem2 = new RsConfigKeyValueSet ; - RsTlvKeyValue kv2; - kv2.key = "ALLOW_TUNNEL_CONNECTION" ; - kv2.value = (allowTunnelConnection)?"TRUE":"FALSE" ; - vitem2->tlvkvs.pairs.push_back(kv2) ; - -#ifdef PEER_DEBUG - std::cout << "Pushing item for allow_tunnel_connection = " << allowTunnelConnection << std::endl ; -#endif saveData.push_back(vitem2); saveCleanupList.push_back(vitem2); @@ -1527,7 +1518,6 @@ bool p3PeerMgrIMPL::loadList(std::list& load) // DEFAULTS. bool useExtAddrFinder = true; - bool allowTunnelConnection = true; if (load.size() == 0) { std::cerr << "p3PeerMgrIMPL::loadList() list is empty, it may be a configuration problem." << std::endl; @@ -1613,10 +1603,7 @@ bool p3PeerMgrIMPL::loadList(std::list& load) if(kit->key == "USE_EXTR_IP_FINDER") { useExtAddrFinder = (kit->value == "TRUE"); std::cerr << "setting use_extr_addr_finder to " << useExtAddrFinder << std::endl ; - } else if (kit->key == "ALLOW_TUNNEL_CONNECTION") { - allowTunnelConnection = (kit->value == "TRUE"); - std::cerr << "setting allow_tunnel_connection to " << allowTunnelConnection << std::endl ; - } + } } delete(*it); @@ -1714,7 +1701,6 @@ bool p3PeerMgrIMPL::loadList(std::list& load) } mNetMgr->setIPServersEnabled(useExtAddrFinder); - mLinkMgr->setTunnelConnection(allowTunnelConnection); return true; } diff --git a/libretroshare/src/pqi/pqi_base.h b/libretroshare/src/pqi/pqi_base.h index fcb2d5689..8bb563a77 100644 --- a/libretroshare/src/pqi/pqi_base.h +++ b/libretroshare/src/pqi/pqi_base.h @@ -237,7 +237,6 @@ class PQInterface: public RateInterface const uint32_t PQI_CONNECT_TCP = 0x0001; const uint32_t PQI_CONNECT_UDP = 0x0002; -const uint32_t PQI_CONNECT_TUNNEL = 0x0003; const uint32_t PQI_CONNECT_HIDDEN_TCP = 0x0004; diff --git a/libretroshare/src/pqi/pqipersongrp.cc b/libretroshare/src/pqi/pqipersongrp.cc index 5e24756a3..5738cb046 100644 --- a/libretroshare/src/pqi/pqipersongrp.cc +++ b/libretroshare/src/pqi/pqipersongrp.cc @@ -595,15 +595,6 @@ int pqipersongrp::connectPeer(std::string id #ifdef PGRP_DEBUG std::cerr << " pqipersongrp::connectPeer() connecting with UDP: Timeout :" << timeout; std::cerr << std::endl; -#endif - } - else if (type & RS_NET_CONN_TUNNEL) - { - ptype = PQI_CONNECT_TUNNEL; - timeout = period * 2; -#ifdef PGRP_DEBUG - std::cerr << " pqipersongrp::connectPeer() connecting with Tunnel: Timeout :" << timeout; - std::cerr << std::endl; #endif } else @@ -631,11 +622,6 @@ bool pqipersongrp::notifyConnect(std::string id, uint32_t ptype, bool success { type = RS_NET_CONN_UDP_ALL; } - else if (ptype == PQI_CONNECT_TUNNEL) - { - type = RS_NET_CONN_TUNNEL; - } - if (mLinkMgr) mLinkMgr->connectResult(id, success, type, raddr); diff --git a/libretroshare/src/pqi/pqisslpersongrp.cc b/libretroshare/src/pqi/pqisslpersongrp.cc index 91e37fab0..00569eaab 100644 --- a/libretroshare/src/pqi/pqisslpersongrp.cc +++ b/libretroshare/src/pqi/pqisslpersongrp.cc @@ -41,9 +41,6 @@ const int pqipersongrpzone = 354; #include "pqi/pqissllistener.h" #include "pqi/p3peermgr.h" -#ifndef PQI_DISABLE_TUNNEL -#include "pqi/pqissltunnel.h" -#endif #ifndef PQI_DISABLE_UDP #include "pqi/pqissludp.h" diff --git a/libretroshare/src/pqi/pqissltunnel.cc b/libretroshare/src/pqi/pqissltunnel.cc deleted file mode 100644 index e2f95a3fa..000000000 --- a/libretroshare/src/pqi/pqissltunnel.cc +++ /dev/null @@ -1,554 +0,0 @@ -/* - * "$Id: pqissl.cc,v 1.28 2007-03-17 19:32:59 rmf24 Exp $" - * - * 3P/PQI network interface for RetroShare. - * - * Copyright 2004-2006 by Robert Fernie. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License Version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 - * USA. - * - * Please report all bugs and problems to "retroshare@lunamutt.com". - * - */ - -#include "pqi/pqissltunnel.h" -#include "pqi/pqinetwork.h" -#include "pqi/p3linkmgr.h" - -//#include "services/p3tunnel.h" - -#include "util/rsnet.h" -#include "util/rsdebug.h" -#include "util/rsstring.h" - -#include -#include -#include - -const int pqisslzone = 37714; - -#define TUNNEL_WAITING_NOT 0 -#define TUNNEL_WAITING_DELAY 1 -#define TUNNEL_WAITING_SPAM_HANDSHAKE 2 -#define TUNNEL_WAITING_RETURN_HANDSHAKE 3 - - -#define TUNNEL_PASSIVE 0x00 -#define TUNNEL_ACTIVE 0x01 - -#define TUNNEL_START_CONNECTION_DELAY 1 -#define TUNNEL_PING_TIMEOUT 6 -#define TUNNEL_REPEAT_PING_TIME 2 -#define TUNNEL_TIMEOUT_AFTER_RESET 30 - -#define TUNNEL_TRY_OTHER_CONNECTION_INTERVAL 190 //let's try a normal tcp or udp connection every 190 sec - -//const int TUNNEL_LOCAL_FLAG = 0x01; -//const int TUNNEL_REMOTE_FLAG = 0x02; -//const int TUNNEL_UDP_FLAG = 0x02; -// -//static const int PQISSL_MAX_READ_ZERO_COUNT = 20; -//static const int PQISSL_SSL_CONNECT_TIMEOUT = 30; - -/********** PQI SSL STUFF ****************************************** - * - * A little note on the notifyEvent(FAILED).... - * - * this is called from - * (1) reset if needed! - * (2) Determine_Remote_Address (when all options have failed). - * - * reset() is only called when a TCP/SSL connection has been - * established, and there is an error. If there is a failed TCP - * connection, then an alternative address can be attempted. - * - * reset() is called from - * (1) destruction. - * (2) disconnect() - * (3) bad waiting state. - * - * // TCP/or SSL connection already established.... - * (5) pqissltunnel::SSL_Connection_Complete() <- okay -> cos we made a TCP connection already. - * (6) pqissltunnel::accept() <- okay cos something went wrong. - * (7) moretoread()/cansend() <- okay cos - * - */ - -pqissltunnel::pqissltunnel(PQInterface *parent, p3LinkMgr *cm, p3tunnel *p3t) - :NetBinInterface(parent, parent->PeerId()), mLinkMgr(cm) -{ - active = false; - waiting = TUNNEL_WAITING_NOT; - - rslog(RSL_ALERT, pqisslzone, "pqissltunnel for PeerId: " + PeerId()); - -// if (!(AuthSSL::getAuthSSL()->isAuthenticated(PeerId()))) { -// rslog(RSL_ALERT, pqisslzone, -// "pqissltunnel::Warning Certificate Not Approved!"); -// rslog(RSL_ALERT, pqisslzone, -// "\t pqissltunnel will not initialise...."); -// } - mP3tunnel = p3t; - current_data_offset = 0; - curent_data_packet.length = 0; - - return; -} - -pqissltunnel::~pqissltunnel() { - rslog(RSL_ALERT, pqisslzone, - "pqissltunnel::~pqissltunnel -> destroying pqissl"); - //stoplistening(); - reset(); - return; -} - - -/********** Implementation of NetInterface *************************/ - -int pqissltunnel::connect(struct sockaddr_in /*raddr*/) { -#ifdef DEBUG_PQISSL_TUNNEL - std::cerr << "pqissltunnel::connect() called : " << PeerId() << std::endl; -#endif - last_normal_connection_attempt_time = time(NULL); - mConnectTS = time(NULL); - resetTime = time(NULL) - TUNNEL_TIMEOUT_AFTER_RESET; - waiting = TUNNEL_WAITING_DELAY; - return 0; -} - -// tells pqilistener to listen for us. -int pqissltunnel::listen() -{ - //no use - return 0; -} - -int pqissltunnel::stoplistening() -{ - //no use - return 1; -} - -int pqissltunnel::disconnect() -{ -#ifdef DEBUG_PQISSL_TUNNEL - std::cerr << "pqissltunnel::disconnect() called : " << PeerId() << std::endl; -#endif - return reset(); -} - -/* BinInterface version of reset() for pqistreamer */ -int pqissltunnel::close() -{ - return reset(); -} - -// put back on the listening queue. -int pqissltunnel::reset() -{ -#ifdef DEBUG_PQISSL_TUNNEL - std::cerr << "pqissltunnel::reset() called : " << PeerId() << std::endl; -#endif - - if (active) - { -#ifdef DEBUG_PQISSL_TUNNEL - std::cerr << "pqissltunnel::reset() Reset Required because tunnel was activated !" << std::endl; - std::cerr << "pqissltunnel::reset() Will Attempt notifyEvent(FAILED)" << std::endl; -#endif - waiting = TUNNEL_WAITING_NOT; - active = false; - resetTime = time(NULL); - // clean up the streamer - if (parent()) { -#ifdef DEBUG_PQISSL_TUNNEL - std::cerr << "pqissltunnel::reset() notifyEvent(FAILED)" << std::endl; -#endif - parent() -> notifyEvent(this, NET_CONNECT_FAILED); - } - } else { -#ifdef DEBUG_PQISSL_TUNNEL - std::cerr << "pqissltunnel::reset() Reset not required because tunnel was not activated !" << std::endl; -#endif - } - return 1; -} - -int pqissltunnel::getConnectAddress(struct sockaddr_in &raddr) { - sockaddr_clear(&raddr); - return 0; -} - -bool pqissltunnel::connect_parameter(uint32_t type, uint32_t value) -{ - { - std::string out = "pqissltunnel::connect_parameter() (not used) Peer: " + PeerId(); - rs_sprintf_append(out, " type: %lu value: %lu", type, value); - rslog(RSL_DEBUG_ALL, pqisslzone, out); - } - - if (type == NET_PARAM_CONNECT_DELAY) - { - std::string out = "pqissltunnel::connect_parameter() (not used) Peer: " + PeerId(); - rs_sprintf_append(out, " DELAY: %lu", value); - rslog(RSL_WARNING, pqisslzone, out); - - return true; - } - else if (type == NET_PARAM_CONNECT_TIMEOUT) - { - std::string out = "pqissltunnel::connect_parameter() (not used) Peer: " + PeerId(); - rs_sprintf_append(out, " TIMEOUT: %lu", value); - rslog(RSL_WARNING, pqisslzone, out); - - return true; - } - return false; -} - - -/********** End of Implementation of NetInterface ******************/ -/********** Implementation of BinInterface ************************** - * Only status() + tick() are here ... as they are really related - * to the NetInterface, and not the BinInterface, - * - */ - -/* returns ... - * -1 if inactive. - * 0 if connecting. - * 1 if connected. - */ - -int pqissltunnel::status() -{ -#ifdef DEBUG_PQISSL_TUNNEL - std::cerr << "pqissltunnel::status() called." << std::endl; -#endif - - if (active) { - std::cerr << " active: " << std::endl; - // print out connection. - std::cerr << "dest : " << PeerId(); - std::cerr << "relay : " << relayPeerId; - std::cerr << std::endl; - } - else { - std::cerr << " Waiting for connection!" << std::endl; - } - - if (active) { - return 1; - } else if (waiting > 0) { - return 0; - } - return -1; -} - - -int pqissltunnel::tick() -{ - if (active && ((time(NULL) - last_normal_connection_attempt_time) > TUNNEL_TRY_OTHER_CONNECTION_INTERVAL)) { - #ifdef DEBUG_PQISSL_TUNNEL - std::cerr << "pqissltunnel::tick() attempt to connect through a normal tcp or udp connection." << std::endl; - #endif - last_normal_connection_attempt_time = time(NULL); - mLinkMgr->retryConnect(parent()->PeerId()); - } - - if (active && ((time(NULL) - last_ping_send_time) > TUNNEL_REPEAT_PING_TIME)) { - #ifdef DEBUG_PQISSL_TUNNEL - std::cerr << "pqissltunnel::tick() sending a ping." << std::endl; - #endif - last_ping_send_time = time(NULL);; - mP3tunnel->pingTunnelConnection(relayPeerId, parent()->PeerId()); - } - - if (active && ((time(NULL) - last_packet_time) > TUNNEL_PING_TIMEOUT)) { - #ifdef DEBUG_PQISSL_TUNNEL - std::cerr << "pqissltunnel::tick() no packet received since PING_RECEIVE_TIME_OUT. Connection is broken." << std::endl; - #endif - reset(); - } - // continue existing connection attempt. - if (!active) - { - // if we are waiting.. continue the connection (only) - if (waiting > 0) - { - #ifdef DEBUG_PQISSL_TUNNEL - //std::cerr << "pqissltunnel::tick() Continuing Connection Attempt!" << std::endl; - #endif - ConnectAttempt(); - return 1; - } - } - return 1; -} - -/********** End of Implementation of BinInterface ******************/ -/********** Internals of Tunnel Connection ****************************/ -int pqissltunnel::ConnectAttempt() -{ - #ifdef DEBUG_PQISSL_TUNNEL - //std::cerr << "pqissltunnel::ConnectAttempt() called." << std::endl; - #endif - switch(waiting) - { - case TUNNEL_WAITING_NOT: - active = true; /* we're starting this one */ - #ifdef DEBUG_PQISSL_TUNNEL - std::cerr << "pqissltunnel::ConnectAttempt() STATE = Not Waiting." << std::endl; - #endif - - case TUNNEL_WAITING_DELAY: - if ((time(NULL) - mConnectTS) > TUNNEL_START_CONNECTION_DELAY) { - waiting = TUNNEL_WAITING_SPAM_HANDSHAKE; - } - - break; - - case TUNNEL_WAITING_SPAM_HANDSHAKE: - #ifdef DEBUG_PQISSL_TUNNEL - std::cerr << "pqissltunnel::ConnectAttempt() STATE = Waiting for spamming handshake." << std::endl; - #endif - - spam_handshake(); - waiting = TUNNEL_WAITING_RETURN_HANDSHAKE; - break; - - case TUNNEL_WAITING_RETURN_HANDSHAKE: - if ((time(NULL) - mConnectTS) < TUNNEL_PING_TIMEOUT) { - #ifdef DEBUG_PQISSL_TUNNEL - //std::cerr << "pqissltunnel::ConnectAttempt() STATE = Waiting for handshake reply." << std::endl; - #endif - } else { - #ifdef DEBUG_PQISSL_TUNNEL - std::cerr << "pqissltunnel::ConnectAttempt() no handshake reply during imparing time. Connection failed." << std::endl; - #endif - waiting = TUNNEL_WAITING_NOT; - active = false; - // clean up the streamer - if (parent()) { -#ifdef DEBUG_PQISSL_TUNNEL - std::cerr << "pqissltunnel::reset() Reset not required because tunnel was not activated !" << std::endl; -#endif - parent() -> notifyEvent(this, NET_CONNECT_FAILED); - } - } - break; - - - default: - std::cerr << "pqissltunnel::ConnectAttempt() STATE = Unknown - Reset" << std::endl; - - reset(); - break; - } - return -1; -} - -void pqissltunnel::spam_handshake() -{ -#ifdef DEBUG_PQISSL_TUNNEL - std::cerr << "pqissltunnel::spam_handshake() starting to spam handshake tunnel packet." << std::endl; -#endif - std::list peers; - mLinkMgr->getOnlineList(peers); - std::list::iterator it = peers.begin(); - while (it != peers.end()) { - //send a handshake to the destination through the relay - if (*it != parent()->PeerId()) { - mP3tunnel->initiateHandshake(*it, parent()->PeerId()); - } - ++it; - } -} - -void pqissltunnel::addIncomingPacket(void* encoded_data, int encoded_data_length) { - #ifdef DEBUG_PQISSL_TUNNEL - std::cerr << "pqissltunnel::addIncomingPacket() called." << std::endl; - #endif - last_packet_time = time(NULL); - - data_with_length data_w_l; - data_w_l.data = (void*)malloc(encoded_data_length) ; - memcpy(data_w_l.data, encoded_data, encoded_data_length); - data_w_l.length = encoded_data_length; - data_packet_queue.push_front(data_w_l); -} - -void pqissltunnel::IncommingPingPacket() { - #ifdef DEBUG_PQISSL_TUNNEL - std::cerr << "pqissltunnel::IncommingPingPacket() called" << std::endl; - #endif - - last_packet_time = time(NULL); -} - -void pqissltunnel::IncommingHanshakePacket(std::string incRelayPeerId) { - #ifdef DEBUG_PQISSL_TUNNEL - std::cerr << "pqissltunnel::IncommingHanshakePacket() called with incRelayPeerId : " << incRelayPeerId << std::endl; - #endif - - if ((time(NULL) - resetTime) <= TUNNEL_TIMEOUT_AFTER_RESET) { -#ifdef DEBUG_PQISSL_TUNNEL - std::cerr << "pqissltunnel::IncommingHanshakePacket() a reset occured, don't activate the connection." << std::endl; -#endif - return; - } - last_packet_time = time(NULL); - - std::string message = "pqissltunnel::IncommingHanshakePacket() mConnMgr->isOnline(parent()->PeerId() : "; - if (mLinkMgr->isOnline(parent()->PeerId())) { - message += "true"; - } else { - message += "false"; - } - rslog(RSL_DEBUG_BASIC, pqisslzone, message); - - if (active || mLinkMgr->isOnline(parent()->PeerId())) { - //connection is already active, or peer is already online don't do nothing - return; - } - //TODO : check if cert is in order before accepting - - //activate connection - waiting = TUNNEL_WAITING_NOT; - active = true; - relayPeerId = incRelayPeerId; - - if (parent()) - { - #ifdef DEBUG_PQISSL_TUNNEL - std::cerr << "pqissltunnel::IncommingHanshakePacket() Notify the pqiperson.... (Both Connect/Receive)" << parent()->PeerId() < notifyEvent(this, NET_CONNECT_SUCCESS); - } -} -/********** Implementation of BinInterface ************************** - * All the rest of the BinInterface. - * - */ - -int pqissltunnel::senddata(void *data, int len) -{ -#ifdef DEBUG_PQISSL_TUNNEL - std::cerr << "pqissltunnel::senddata() called" << std::endl ; -#endif - if (!active) { - #ifdef DEBUG_PQISSL_TUNNEL - std::cerr << "pqissltunnel::senddata() connection is not active" << std::endl ; - #endif - return -1; - } - - int outlen = 0; - void * out; - if (!AuthSSL::getAuthSSL()->encrypt(out, outlen, data, len, parent()->PeerId())) { - std::cerr << "pqissltunnel::senddata() problem while crypting packet, ignoring it." << std::endl; - return -1; - } - - #ifdef DEBUG_PQISSL_TUNNEL - std::cerr << "pqissltunnel::senddata() sending item via p3tunnel" << std::endl ; - #endif - mP3tunnel->sendTunnelData(parent()->PeerId(), relayPeerId, out, outlen); - - return len; -} - -int pqissltunnel::readdata(void *data, int len) -{ -#ifdef DEBUG_PQISSL_TUNNEL - std::cout << "pqissltunnel::readdata() called" << std::endl ; -#endif - //let's see if we got a new packet to read - if (current_data_offset >= curent_data_packet.length) { - //current packet has finished reading, let's pop out a new packet if available - if (data_packet_queue.size() ==0) { - //no more to read - return -1; - } else { - //let's read a new packet - current_data_offset = 0; - //decrypt one packet from the queue and put it into the current data packet. - if (!AuthSSL::getAuthSSL()->decrypt(curent_data_packet.data, curent_data_packet.length, data_packet_queue.back().data, data_packet_queue.back().length)) { - std::cerr << "pqissltunnel::readdata() problem while decrypting packet, ignoring it." << std::endl; - curent_data_packet.length = 0; - return -1; - } - data_packet_queue.pop_back(); - } - } - - if (current_data_offset < curent_data_packet.length) { -#ifdef DEBUG_PQISSL_TUNNEL - std::cout << "pqissltunnel::readdata() reading..." << std::endl ; - std::cout << "pqissltunnel::readdata() len : " << len << std::endl ; - std::cout << "pqissltunnel::readdata() current_data_offset : " << current_data_offset << std::endl ; - std::cout << "pqissltunnel::readdata() curent_data_packet.length : " << curent_data_packet.length << std::endl ; - std::cerr << "pqissltunnel::readdata() getRsItemSize(curent_data_packet.data) : " << getRsItemSize(curent_data_packet.data) << std::endl; -#endif - - //read from packet - memcpy(data, (void*)((unsigned long int)curent_data_packet.data+(unsigned long int)current_data_offset), len); - current_data_offset += len; - - return len; - } - - return -1; -} - -// dummy function currently. -int pqissltunnel::netstatus() -{ - return 1; -} - -int pqissltunnel::isactive() -{ - return active; -} - -bool pqissltunnel::moretoread() -{ - //let's see if we got an old packet or a new packet to read - if (current_data_offset >= curent_data_packet.length && data_packet_queue.size() ==0) { - return false; - } else { - return true; - } -} - -bool pqissltunnel::cansend() -{ - if (!mLinkMgr->isOnline(relayPeerId)) { - reset(); - return false; - } - return true; -} - -std::string pqissltunnel::gethash() -{ - std::string dummyhash; - return dummyhash; -} - -/********** End of Implementation of BinInterface ******************/ diff --git a/libretroshare/src/pqi/pqissltunnel.h b/libretroshare/src/pqi/pqissltunnel.h deleted file mode 100644 index ed6d6f312..000000000 --- a/libretroshare/src/pqi/pqissltunnel.h +++ /dev/null @@ -1,146 +0,0 @@ -/* - * "$Id: pqissl.h,v 1.18 2007-03-11 14:54:22 rmf24 Exp $" - * - * 3P/PQI network interface for RetroShare. - * - * Copyright 2004-2006 by Robert Fernie. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License Version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 - * USA. - * - * Please report all bugs and problems to "retroshare@lunamutt.com". - * - */ - - - -#ifndef MRK_PQI_SSL_TUNNEL_HEADER -#define MRK_PQI_SSL_TUNNEL_HEADER - -#include "util/rswin.h" - -#include - -// operating system specific network header. -//#include "pqi/pqinetwork.h" - -#include "pqi/pqi_base.h" - -#include "services/p3tunnel.h" - -#include "pqi/authssl.h" - -/***************************** pqi Net SSL Interface ********************************* - * This provides the base SSL interface class, - * and handles most of the required functionality. - * - * there are a series of small fn's that can be overloaded - * to provide alternative behaviour.... - * - * Classes expected to inherit from this are: - * - * pqissllistener -> pqissllistener (tcp only) - * -> pqixpgplistener (tcp only) - * - * pqissl -> pqissltcp - * -> pqissludp - * -> pqixpgptcp - * -> pqixpgpudp - * - */ - -class pqissl; -class cert; - -class pqissltunnellistener; - -class p3LinkMgr; - -struct data_with_length { - int length; - void *data; -}; - -class pqissltunnel: public NetBinInterface -{ -public: - pqissltunnel(PQInterface *parent, p3LinkMgr *cm, p3tunnel *p3t); -virtual ~pqissltunnel(); - - // NetInterface - -//the addr is not used for the tunnel -virtual int connect(struct sockaddr_in raddr); -virtual int listen(); -virtual int stoplistening(); -virtual int reset(); -virtual int disconnect(); -virtual int getConnectAddress(struct sockaddr_in &raddr); - -virtual bool connect_parameter(uint32_t type, uint32_t value); - - // BinInterface -virtual int tick(); -virtual int status(); - -virtual int senddata(void*, int); -virtual int readdata(void*, int); -virtual int netstatus(); -virtual int isactive(); -virtual bool moretoread(); -virtual bool cansend(); - -virtual int close(); /* BinInterface version of reset() */ -virtual std::string gethash(); /* not used here */ -virtual bool bandwidthLimited() { return true ; } // replace by !sameLAN to avoid bandwidth limiting on lAN - -//called by the p3tunnel service to add incoming packets that will be read by the read data function. -void addIncomingPacket(void* encoded_data, int data_length); -void IncommingPingPacket(); -void IncommingHanshakePacket(std::string incRelayPeerId); - -private: - //if no packet (last_time_packet_time) is received since PING_RECEIVE_TIME_OUT, let's assume the connection is broken - int last_normal_connection_attempt_time; - - //if no packet (last_time_packet_time) is received since PING_RECEIVE_TIME_OUT, let's assume the connection is broken - int last_packet_time; - - //send a ping on a regular basis - int last_ping_send_time; - - int ConnectAttempt(); - void spam_handshake(); - int waiting; - bool active; - time_t resetTime; - pqissltunnellistener *pqil; - - /* Need Certificate specific functions here! */ - time_t mConnectTS; - - p3LinkMgr *mLinkMgr; - - p3tunnel *mP3tunnel; - - std::list data_packet_queue; - data_with_length curent_data_packet; - int current_data_offset; - - //tunneling details - std::string relayPeerId; - -}; - -#endif // MRK_PQI_SSL_HEADER diff --git a/libretroshare/src/retroshare/rsblogs.h b/libretroshare/src/retroshare/rsblogs.h deleted file mode 100644 index 35586c3b4..000000000 --- a/libretroshare/src/retroshare/rsblogs.h +++ /dev/null @@ -1,154 +0,0 @@ -#ifndef RS_BLOG_GUI_INTERFACE_H -#define RS_BLOG_GUI_INTERFACE_H - -/* - * libretroshare/src/rsiface: rsblogs.h - * - * RetroShare C++ Interface. - * - * Copyright 2008 by Robert Fernie. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License Version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 - * USA. - * - * Please report all bugs and problems to "retroshare@lunamutt.com". - * - */ - - -#include -#include -#include - -#include "rstypes.h" -#include "rsdistrib.h" /* For FLAGS */ - -class BlogInfo -{ - public: - BlogInfo() {} - std::string blogId; - std::wstring blogName; - std::wstring blogDesc; - - uint32_t blogFlags; - uint32_t pop; - - unsigned char* pngChanImage; - uint32_t pngImageLen; - - time_t lastPost; -}; - -class BlogMsgInfo -{ - public: - BlogMsgInfo() {} - std::string blogId; - std::string msgId; - /// this has a value if replying to another msg - std::string msgIdReply; - - unsigned int msgflags; - - std::wstring subject; - std::wstring msg; - time_t ts; - - std::list files; - uint32_t count; - uint64_t size; -}; - - -class BlogMsgSummary -{ - public: - BlogMsgSummary() {} - std::string blogId; - std::string msgId; - - uint32_t msgflags; - - std::wstring subject; - std::wstring msg; - std::string msgIdReply; - uint32_t count; /* file count */ - time_t ts; - -}; - -std::ostream &operator<<(std::ostream &out, const BlogInfo &info); -std::ostream &operator<<(std::ostream &out, const BlogMsgSummary &info); -std::ostream &operator<<(std::ostream &out, const BlogMsgInfo &info); - -class RsBlogs; -extern RsBlogs *rsBlogs; - -class RsBlogs -{ - public: - - RsBlogs() { return; } -virtual ~RsBlogs() { return; } - -/****************************************/ - -/*! - * Checks if the group a blod id belongs to has changed - */ -virtual bool blogsChanged(std::list &blogIds) = 0; - - -virtual std::string createBlog(std::wstring blogName, std::wstring blogDesc, uint32_t blogFlags, - unsigned char* pngImageData, uint32_t imageSize) = 0; - -virtual bool getBlogInfo(std::string cId, BlogInfo &ci) = 0; -virtual bool getBlogList(std::list &chanList) = 0; -virtual bool getBlogMsgList(std::string cId, std::list &msgs) = 0; - -/*! - * Retrieves a specific blog Msg based on group Id and message Id - */ -virtual bool getBlogMessage(std::string cId, std::string mId, BlogMsgInfo &msg) = 0; - -/*! - * Can send blog message to user - * @param info the message - */ -virtual bool BlogMessageSend(BlogMsgInfo &info) = 0; - -/*! - * Allows user to subscribe to a blog via group ID - * @param cId group id - * @param subscribe determine subscription based on value - */ -virtual bool blogSubscribe(std::string cId, bool subscribe) = 0; - -/*! - * Commenting on other user's blogs, ensure field info has a valid info.msgIdReply has valid msg id, this - * points to which message the blog reply is replying to - */ -virtual bool BlogMessageReply(BlogMsgInfo &info) = 0; - -/*! - * - */ -virtual bool isReply(BlogMsgInfo &info) = 0; -/****************************************/ - -}; - - -#endif diff --git a/libretroshare/src/retroshare/rschannels.h b/libretroshare/src/retroshare/rschannels.h deleted file mode 100644 index 78ff1c312..000000000 --- a/libretroshare/src/retroshare/rschannels.h +++ /dev/null @@ -1,283 +0,0 @@ -#ifndef RS_CHANNEL_GUI_INTERFACE_H -#define RS_CHANNEL_GUI_INTERFACE_H - -/* - * libretroshare/src/rsiface: rschannels.h - * - * RetroShare C++ Interface. - * - * Copyright 2008 by Robert Fernie. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License Version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 - * USA. - * - * Please report all bugs and problems to "retroshare@lunamutt.com". - * - */ - - -#include -#include -#include - -#include "rstypes.h" -#include "rsdistrib.h" /* For FLAGS */ - -#define CHANNEL_MSG_STATUS_MASK 0x000f -#define CHANNEL_MSG_STATUS_READ 0x0001 -#define CHANNEL_MSG_STATUS_UNREAD_BY_USER 0x0002 -#define CHANNEL_MSG_STATUS_DOWLOADED 0x0004 - - -//! Stores information for a give channel id -/*! - * Stores all information for a given channel id - */ -class ChannelInfo -{ - public: - ChannelInfo() : autoDownload(false), pngChanImage(NULL), pngImageLen(0) - {} - std::string channelId; - std::wstring channelName; - std::wstring channelDesc; - - uint32_t channelFlags; - uint32_t pop; /// popularity - bool autoDownload; - - unsigned char* pngChanImage; - uint32_t pngImageLen; - - time_t lastPost; - std::string destination_directory ; -}; - -//! for storing a channel msgs thumbnail picture -class ChannelMsgThumbnail -{ -public: - ChannelMsgThumbnail() : image_thumbnail(NULL), im_thumbnail_size(0) {} - - unsigned char* image_thumbnail; - int im_thumbnail_size; -}; - -//! Stores information on a message within a channel -class ChannelMsgInfo -{ - public: - ChannelMsgInfo () : count(0), size(0) {} - std::string channelId; - std::string msgId; - - unsigned int msgflags; - - std::wstring subject; - std::wstring msg; - time_t ts; /// time stamp - - std::list files; - uint32_t count; /// file count - uint64_t size; /// size of all files - - ChannelMsgThumbnail thumbnail; - -}; - - -//! gives a more brief account of a channel message than channelMsgInfo -class ChannelMsgSummary -{ - public: - ChannelMsgSummary() : count(0) {} - std::string channelId; - std::string msgId; - - uint32_t msgflags; - - std::wstring subject; - std::wstring msg; - uint32_t count; /// file count - time_t ts; /// time stamp - -}; - -std::ostream &operator<<(std::ostream &out, const ChannelInfo &info); -std::ostream &operator<<(std::ostream &out, const ChannelMsgSummary &info); -std::ostream &operator<<(std::ostream &out, const ChannelMsgInfo &info); - -class RsChannels; -extern RsChannels *rsChannels; - -/*! - * retroshare interface to the channels distributed group service - * Channels user to create feeds similar to RSS feed where you can share files - * with other users, when you subscribe to a channel you immediately begin downloading - * the file shared on that channel. Channel feeds are shared anonymously - */ -class RsChannels -{ - public: - - RsChannels() { return; } -virtual ~RsChannels() { return; } - -/****************************************/ - -/*! - * returns a list of channel id that have changed (i.e. received new message, chan descr update) - * @param chanIds this is populated with channel ids that have changed - */ -virtual bool channelsChanged(std::list &chanIds) = 0; - -/*! - * @param chanName name of the channel - * @param chanDesc a short description for the created channel - * @param chanFlags admin details on created channel group see rsdistrib.h for flags types - * @param pngImageData point at image data in PNG format - * @param imageSize size of the image data - */ -virtual std::string createChannel(std::wstring chanName, std::wstring chanDesc, uint32_t chanFlags, - unsigned char* pngImageData, uint32_t imageSize) = 0; - -/*! - * retrieve channel information - * @param cId channel id - * @param ci channel info is store here - */ -virtual bool getChannelInfo(const std::string &cId, ChannelInfo &ci) = 0; - -/*! - * @param chanList populated channelinfo for all channels - */ -virtual bool getChannelList(std::list &chanList) = 0; - -/*! - * get a message summary list for a given channel id - * @param cId channel id user wants messages for - * @param msgs summary of messages for the given cId - */ -virtual bool getChannelMsgList(const std::string &cId, std::list &msgs) = 0; - -/*! - * retrieve more comprehensive message info given channel id and message id - */ -virtual bool getChannelMessage(const std::string &cId, const std::string &mId, ChannelMsgInfo &msg) = 0; - -/*! - * set message status - * @param cId channel id - * @param mId message id - * @param status status to set - * @param statusMask bitmask to modify - */ -virtual bool setMessageStatus(const std::string& cId,const std::string& mId, const uint32_t status, const uint32_t statusMask) = 0; - -/*! - * set message status - * @param cId channel id - * @param mId message id - * @param status status - */ -virtual bool getMessageStatus(const std::string& cId, const std::string& mId, uint32_t& status) = 0; - -/*! - * count the new and unread messages - * @param cId channel id - * @param newCount count of new messages - * @param unreadCount count of unread messages - */ -virtual bool getMessageCount(const std::string &cId, unsigned int &newCount, unsigned int &unreadCount) = 0; - -/*! - * send message contain in message info to the id indicated within it (make sure you set the channel id of the message info) - * @param info message to be sent - */ -virtual bool ChannelMessageSend(ChannelMsgInfo &info) = 0; - -/*! - * @param cId the channel id - * @param subscribe set to true if you want to subscribe and to false to unsubscribe - * @param set true to allow autodownload of new content and false otherwise, ignored when second param is false - */ -virtual bool channelSubscribe(const std::string &cId, bool subscribe, bool autoDl) = 0; - -/*! - * This hashes a file which is not already shared by client or his peers, - * The file is copied into the channels directory if its not too large (> 100mb) - * @param path This is full path to file - * @param channel Id - */ -virtual bool channelExtraFileHash(const std::string &path, const std::string &chId, FileInfo& fInfo) = 0; - -/*! - * This removes hashed extra files, and also removes channels directory copy if it exists - * @param chId channel id - */ -virtual bool channelExtraFileRemove(const std::string &hash, const std::string &chId) = 0; - -/*! - * Restores channel private keys for channel in the event keys stored in configuration files are lost - * @param chId channel id to restore keys for - */ -virtual bool channelRestoreKeys(const std::string &chId) = 0; - -/*! - * shares keys with peers - *@param chId the channel for which private publish keys will be shared - *@param peers peers in this list will be sent keys - * - */ -virtual bool channelShareKeys(const std::string &chId, std::list& peers) = 0; -/****************************************/ - -/*! - * allows peers to change information for the channel: - * can only change channel image, descriptions and name - * - */ -virtual bool channelEditInfo(const std::string &chId, ChannelInfo &ci) = 0; - - -/*! - * get list of channels for which private publish key is available - * @param grpIds list of channels for which private publish key is available - */ -virtual void getPubKeysAvailableGrpIds(std::list& chanIds) = 0; - -/*! - * set the channel so that it does not auto download any more - * @param chId the channel id to set for - * @param set to true to enable auto dl and false to disable - */ -virtual bool channelSetAutoDl(const std::string& chId, bool autoDl) = 0; - -// sets the defautl destination directory for files downloaded in this channel. -// Default is "" which means Downloads/ - -virtual bool channelSetDestinationDirectory(const std::string& cid,const std::string& dir) = 0 ; - -/*! - * get what autoDl is set to for the given channel id - * @param chId id of channel to get autoDl status for - * @param autoDl - * @return false if channel cannot be found - */ -virtual bool channelGetAutoDl(const std::string& chId, bool& autoDl) = 0; - -}; - - -#endif diff --git a/libretroshare/src/retroshare/rsdistrib.h b/libretroshare/src/retroshare/rsdistrib.h deleted file mode 100644 index 9faee45ff..000000000 --- a/libretroshare/src/retroshare/rsdistrib.h +++ /dev/null @@ -1,56 +0,0 @@ -#ifndef RS_DISTRIB_GUI_INTERFACE_H -#define RS_DISTRIB_GUI_INTERFACE_H - -/* - * libretroshare/src/rsiface: rsdistrib.h - * - * RetroShare C++ Interface. - * - * Copyright 2007-2008 by Robert Fernie. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License Version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 - * USA. - * - * Please report all bugs and problems to "retroshare@lunamutt.com". - * - */ - - -#define RS_DISTRIB_PRIVACY_MASK 0x0000000f /* who can publish & view */ -#define RS_DISTRIB_AUTHEN_MASK 0x000000f0 /* how to publish */ -#define RS_DISTRIB_LISTEN_MASK 0x00000f00 /* distribution flags */ -#define RS_DISTRIB_UPDATE_MASK 0x0000f000 /* if sending a group info update */ -#define RS_DISTRIB_MISC_MASK 0x00ff0000 /* if sending a group info update */ - -#define RS_DISTRIB_PUBLIC 0x00000001 /* anyone can publish */ -#define RS_DISTRIB_PRIVATE 0x00000002 /* anyone with key can publish */ -#define RS_DISTRIB_ENCRYPTED 0x00000004 /* need publish key to view */ - -#define RS_DISTRIB_AUTHEN_REQ 0x00000010 /* you must sign messages */ -#define RS_DISTRIB_AUTHEN_ANON 0x00000020 /* you can send anonymous messages */ - -#define RS_DISTRIB_ADMIN 0x00000100 -#define RS_DISTRIB_PUBLISH 0x00000200 -#define RS_DISTRIB_SUBSCRIBED 0x00000400 - -#define RS_DISTRIB_UPDATE 0x00001000 - -/* don't know if this should go with the above flags, as it message specific, and not a group settings. - * As it is currently not stored any configuration, it can be changed. - */ - -#define RS_DISTRIB_MISSING_MSG 0x00010000 - - -#endif diff --git a/libretroshare/src/retroshare/rsforums.h b/libretroshare/src/retroshare/rsforums.h deleted file mode 100644 index 74065805e..000000000 --- a/libretroshare/src/retroshare/rsforums.h +++ /dev/null @@ -1,166 +0,0 @@ -#ifndef RS_FORUM_GUI_INTERFACE_H -#define RS_FORUM_GUI_INTERFACE_H - -/* - * libretroshare/src/rsiface: rsforums.h - * - * RetroShare C++ Interface. - * - * Copyright 2007-2008 by Robert Fernie. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License Version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 - * USA. - * - * Please report all bugs and problems to "retroshare@lunamutt.com". - * - */ - - -#include -#include -#include - -#include "rstypes.h" -#include "rsdistrib.h" /* For FLAGS */ - -#define FORUM_MSG_STATUS_MASK 0x000f -#define FORUM_MSG_STATUS_READ 0x0001 -#define FORUM_MSG_STATUS_UNREAD_BY_USER 0x0002 - -class ForumInfo -{ - public: - ForumInfo() - { - forumFlags = 0 ; - subscribeFlags = 0 ; - pop = 0 ; - lastPost = 0 ; - } - std::string forumId; - std::wstring forumName; - std::wstring forumDesc; - - uint32_t forumFlags; - uint32_t subscribeFlags; - - uint32_t pop; - - time_t lastPost; -}; - -class ForumMsgInfo -{ - public: - ForumMsgInfo() - { - msgflags = 0 ; - ts = childTS = status = 0 ; - } - std::string forumId; - std::string threadId; - std::string parentId; - std::string msgId; - - std::string srcId; /* if Authenticated -> signed here */ - - unsigned int msgflags; - - std::wstring title; - std::wstring msg; - time_t ts; - time_t childTS; - uint32_t status; -}; - - -class ThreadInfoSummary -{ - public: - ThreadInfoSummary() - { - msgflags = 0 ; - count = 0 ; - ts = childTS = 0 ; - } - std::string forumId; - std::string threadId; - std::string parentId; - std::string msgId; - - uint32_t msgflags; - - std::wstring title; - std::wstring msg; - int count; /* file count */ - time_t ts; - time_t childTS; -}; - -std::ostream &operator<<(std::ostream &out, const ForumInfo &info); -std::ostream &operator<<(std::ostream &out, const ThreadInfoSummary &info); -std::ostream &operator<<(std::ostream &out, const ForumMsgInfo &info); - -class RsForums; -extern RsForums *rsForums; - -class RsForums -{ - public: - - RsForums() { return; } -virtual ~RsForums() { return; } - -/****************************************/ - -virtual bool forumsChanged(std::list &forumIds) = 0; - - -virtual std::string createForum(const std::wstring &forumName, const std::wstring &forumDesc, uint32_t forumFlags) = 0; - -virtual bool getForumInfo(const std::string &fId, ForumInfo &fi) = 0; - -/*! - * allows peers to change information for the forum: - * can only change name and descriptions - * - */ -virtual bool setForumInfo(const std::string &fId, ForumInfo &fi) = 0; - -virtual bool getForumList(std::list &forumList) = 0; -virtual bool getForumThreadList(const std::string &fId, std::list &msgs) = 0; -virtual bool getForumThreadMsgList(const std::string &fId, const std::string &pId, std::list &msgs) = 0; -virtual bool getForumMessage(const std::string &fId, const std::string &mId, ForumMsgInfo &msg) = 0; -virtual bool setMessageStatus(const std::string& fId,const std::string& mId, const uint32_t status, const uint32_t statusMask) = 0; -virtual bool getMessageStatus(const std::string& fId, const std::string& mId, uint32_t& status) = 0; -virtual bool ForumMessageSend(ForumMsgInfo &info) = 0; -virtual bool forumRestoreKeys(const std::string& fId) = 0; -virtual bool forumSubscribe(const std::string &fId, bool subscribe) = 0; - -/*! - * shares keys with peers - *@param fId the forum for which private publish keys will be shared - *@param peers list of peers to be sent keys - * - */ -virtual bool forumShareKeys(std::string fId, std::list& peers) = 0; - -virtual bool getMessageCount(const std::string &fId, unsigned int &newCount, unsigned int &unreadCount) = 0; - -/****************************************/ - -}; - - -#endif diff --git a/libretroshare/src/retroshare/rsgame.h b/libretroshare/src/retroshare/rsgame.h deleted file mode 100644 index 553bb477b..000000000 --- a/libretroshare/src/retroshare/rsgame.h +++ /dev/null @@ -1,113 +0,0 @@ -#ifndef RS_GAME_GUI_INTERFACE_H -#define RS_GAME_GUI_INTERFACE_H - -/* - * libretroshare/src/rsiface: rsgame.h - * - * RetroShare C++ Interface. - * - * Copyright 2007-2008 by Robert Fernie. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License Version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 - * USA. - * - * Please report all bugs and problems to "retroshare@lunamutt.com". - * - */ - - -#include "rstypes.h" - - -class RsGameLauncher; - -/* declare single RsIface for everyone to use! */ - -extern RsGameLauncher *rsGameLauncher; - -#include -#include -#include - -class RsGameInfo -{ - public: - - std::string gameId; - std::string serverId; - - std::string gameType; - std::wstring gameName; - std::string serverName; - std::string status; - uint16_t numPlayers; - -}; - -class RsGamePeer -{ - public: - std::string id; - bool invite; - bool interested; - bool play; -}; - -class RsGameDetail -{ - public: - std::string gameId; - std::string gameType; - std::wstring gameName; - - bool areServer; /* are we the server? */ - std::string serverId; /* if not, who is? */ - std::string serverName; - - std::string status; - - uint16_t numPlayers; - std::map gamers; - -}; - -class RsGameLauncher -{ - public: - -/* server commands */ -virtual std::string createGame(uint32_t gameType, std::wstring name) = 0; -virtual bool deleteGame(std::string gameId) = 0; -virtual bool inviteGame(std::string gameId) = 0; -virtual bool playGame(std::string gameId) = 0; -//virtual bool quitGame(std::string gameId) = 0; - -virtual bool invitePeer(std::string gameId, std::string peerId) = 0; -virtual bool uninvitePeer(std::string gameId, std::string peerId) = 0; -virtual bool confirmPeer(std::string gameId, std::string peerId, - int16_t pos = -1) = 0; -virtual bool unconfirmPeer(std::string gameId, std::string peerId) = 0; - -/* client commands */ -virtual bool interestedPeer(std::string gameId) = 0; -virtual bool uninterestedPeer(std::string gameId) = 0; - -/* get details */ -virtual bool getGameList(std::list &gameList) = 0; -virtual bool getGameDetail(std::string gameId, RsGameDetail &detail) = 0; - -}; - - -#endif diff --git a/libretroshare/src/retroshare/rsnotify.h b/libretroshare/src/retroshare/rsnotify.h index 4ed389bdc..1de8184d2 100644 --- a/libretroshare/src/retroshare/rsnotify.h +++ b/libretroshare/src/retroshare/rsnotify.h @@ -61,9 +61,6 @@ const uint32_t RS_CHAT_TABBED_WINDOW = 0x0008; const uint32_t RS_CHAT_BLINK = 0x0010; const uint32_t RS_FEED_TYPE_PEER = 0x0010; -const uint32_t RS_FEED_TYPE_CHAN = 0x0020; -const uint32_t RS_FEED_TYPE_FORUM = 0x0040; -const uint32_t RS_FEED_TYPE_BLOG = 0x0080; const uint32_t RS_FEED_TYPE_CHAT = 0x0100; const uint32_t RS_FEED_TYPE_MSG = 0x0200; const uint32_t RS_FEED_TYPE_FILES = 0x0400; @@ -79,18 +76,6 @@ const uint32_t RS_FEED_ITEM_SEC_AUTH_DENIED = RS_FEED_TYPE_SECURITY | 0x0002; const uint32_t RS_FEED_ITEM_SEC_UNKNOWN_IN = RS_FEED_TYPE_SECURITY | 0x0003; const uint32_t RS_FEED_ITEM_SEC_UNKNOWN_OUT = RS_FEED_TYPE_SECURITY | 0x0004; -const uint32_t RS_FEED_ITEM_CHAN_NEW = RS_FEED_TYPE_CHAN | 0x0001; -const uint32_t RS_FEED_ITEM_CHAN_UPDATE = RS_FEED_TYPE_CHAN | 0x0002; -const uint32_t RS_FEED_ITEM_CHAN_MSG = RS_FEED_TYPE_CHAN | 0x0003; - -const uint32_t RS_FEED_ITEM_FORUM_NEW = RS_FEED_TYPE_FORUM | 0x0001; -const uint32_t RS_FEED_ITEM_FORUM_UPDATE = RS_FEED_TYPE_FORUM | 0x0002; -const uint32_t RS_FEED_ITEM_FORUM_MSG = RS_FEED_TYPE_FORUM | 0x0003; - -const uint32_t RS_FEED_ITEM_BLOG_NEW = RS_FEED_TYPE_BLOG | 0x0001; -const uint32_t RS_FEED_ITEM_BLOG_UPDATE = RS_FEED_TYPE_BLOG | 0x0002; -const uint32_t RS_FEED_ITEM_BLOG_MSG = RS_FEED_TYPE_BLOG | 0x0003; - const uint32_t RS_FEED_ITEM_CHAT_NEW = RS_FEED_TYPE_CHAT | 0x0001; const uint32_t RS_FEED_ITEM_MESSAGE = RS_FEED_TYPE_MSG | 0x0001; const uint32_t RS_FEED_ITEM_FILES_NEW = RS_FEED_TYPE_FILES | 0x0001; diff --git a/libretroshare/src/retroshare/rspeers.h b/libretroshare/src/retroshare/rspeers.h index ee5df57a9..fbabc7bc2 100644 --- a/libretroshare/src/retroshare/rspeers.h +++ b/libretroshare/src/retroshare/rspeers.h @@ -79,12 +79,12 @@ const ServicePermissionFlags RS_SERVICE_PERM_ALL = RS_SERVICE_PERM_TURTL /* Connect state */ const uint32_t RS_PEER_CONNECTSTATE_OFFLINE = 0; -const uint32_t RS_PEER_CONNECTSTATE_TRYING_TUNNEL = 1; + const uint32_t RS_PEER_CONNECTSTATE_TRYING_TCP = 2; const uint32_t RS_PEER_CONNECTSTATE_TRYING_UDP = 3; const uint32_t RS_PEER_CONNECTSTATE_CONNECTED_TCP = 4; const uint32_t RS_PEER_CONNECTSTATE_CONNECTED_UDP = 5; -const uint32_t RS_PEER_CONNECTSTATE_CONNECTED_TUNNEL = 6; + const uint32_t RS_PEER_CONNECTSTATE_CONNECTED_UNKNOWN = 7; /* Error codes for certificate cleaning and cert parsing. Numbers should not overlap. */ @@ -129,7 +129,6 @@ const uint32_t RS_NET_CONN_TRANS_UDP_PROXY = 0x00000040; const uint32_t RS_NET_CONN_TRANS_UDP_RELAY = 0x00000080; const uint32_t RS_NET_CONN_TRANS_OTHER_MASK = 0x00000f00; -const uint32_t RS_NET_CONN_TRANS_TUNNEL = 0x00000100; const uint32_t RS_NET_CONN_TRANS_UNKNOWN = 0x00001000; @@ -319,9 +318,7 @@ class RsPeers virtual void getIPServersList(std::list& ip_servers) = 0; virtual void allowServerIPDetermination(bool) = 0; - virtual void allowTunnelConnection(bool) = 0; virtual bool getAllowServerIPDetermination() = 0 ; - virtual bool getAllowTunnelConnection() = 0 ; /* Auth Stuff */ virtual std::string GetRetroshareInvite(const std::string& ssl_id,bool include_signatures,bool old_format = false) = 0; diff --git a/libretroshare/src/rsserver/p3face-config.cc b/libretroshare/src/rsserver/p3face-config.cc index 14c6ff172..af21674b7 100644 --- a/libretroshare/src/rsserver/p3face-config.cc +++ b/libretroshare/src/rsserver/p3face-config.cc @@ -89,15 +89,9 @@ void RsServer::rsGlobalShutDown() mPluginsManager->stopPlugins(); - // stop the p3distrib threads - - mForums->join(); - mChannels->join(); - - #ifdef RS_ENABLE_GXS - //if(mGxsCircles) mGxsCircles->join(); + if(mGxsCircles) mGxsCircles->join(); if(mGxsForums) mGxsForums->join(); if(mGxsChannels) mGxsChannels->join(); if(mGxsIdService) mGxsIdService->join(); @@ -108,11 +102,5 @@ void RsServer::rsGlobalShutDown() #endif - - -#ifdef RS_USE_BLOGS - mBlogs->join(); -#endif - AuthGPG::exit(); } diff --git a/libretroshare/src/rsserver/p3face-server.cc b/libretroshare/src/rsserver/p3face-server.cc index 7c42f6fac..406881f6e 100644 --- a/libretroshare/src/rsserver/p3face-server.cc +++ b/libretroshare/src/rsserver/p3face-server.cc @@ -69,8 +69,6 @@ RsServer::RsServer(NotifyBase &callback) msgSrv = NULL; chatSrv = NULL; mStatusSrv = NULL; - mChannels = NULL; - mForums = NULL; /* caches (that need ticking) */ /* Config */ diff --git a/libretroshare/src/rsserver/p3face.h b/libretroshare/src/rsserver/p3face.h index 5d8750273..47f4bdd3b 100644 --- a/libretroshare/src/rsserver/p3face.h +++ b/libretroshare/src/rsserver/p3face.h @@ -40,10 +40,7 @@ #include "services/p3disc.h" #include "services/p3msgservice.h" #include "services/p3chatservice.h" -#include "services/p3blogs.h" #include "services/p3statusservice.h" -#include "services/p3channels.h" -#include "services/p3forums.h" /* GXS Classes - just declare the classes. so we don't have to totally recompile to switch */ @@ -115,10 +112,6 @@ class RsServer: public RsControl, public RsThread /* General Internal Helper Functions (Must be Locked) */ -#if 0 - cert *intFindCert(RsCertId id); - RsCertId intGetCertId(cert *c); -#endif /****************************************/ /****************************************/ @@ -182,9 +175,6 @@ class RsServer: public RsControl, public RsThread p3MsgService *msgSrv; p3ChatService *chatSrv; p3StatusService *mStatusSrv; - p3Channels *mChannels; - p3Forums *mForums; - /* caches (that need ticking) */ /* GXS */ p3Wiki *mWiki; diff --git a/libretroshare/src/rsserver/p3peers.cc b/libretroshare/src/rsserver/p3peers.cc index 7c0846dae..98be1a9f1 100644 --- a/libretroshare/src/rsserver/p3peers.cc +++ b/libretroshare/src/rsserver/p3peers.cc @@ -395,9 +395,7 @@ bool p3Peers::getPeerDetails(const std::string &id, RsPeerDetails &d) if (pcs.inConnAttempt) { - if (pcs.currentConnAddrAttempt.type & RS_NET_CONN_TUNNEL) { - d.connectState = RS_PEER_CONNECTSTATE_TRYING_TUNNEL; - } else if (pcs.currentConnAddrAttempt.type & RS_NET_CONN_TCP_ALL) { + if (pcs.currentConnAddrAttempt.type & RS_NET_CONN_TCP_ALL) { d.connectState = RS_PEER_CONNECTSTATE_TRYING_TCP; rs_sprintf(d.connectStateString, "%s:%u", rs_inet_ntoa(pcs.currentConnAddrAttempt.addr.sin_addr).c_str(), ntohs(pcs.currentConnAddrAttempt.addr.sin_port)); } else if (pcs.currentConnAddrAttempt.type & RS_NET_CONN_UDP_ALL) { @@ -415,10 +413,6 @@ bool p3Peers::getPeerDetails(const std::string &id, RsPeerDetails &d) { d.connectState = RS_PEER_CONNECTSTATE_CONNECTED_UDP; } - else if (pcs.connecttype == RS_NET_CONN_TUNNEL) - { - d.connectState = RS_PEER_CONNECTSTATE_CONNECTED_TUNNEL; - } else { d.connectState = RS_PEER_CONNECTSTATE_CONNECTED_UNKNOWN; @@ -707,27 +701,11 @@ void p3Peers::allowServerIPDetermination(bool b) mNetMgr->setIPServersEnabled(b) ; } -void p3Peers::allowTunnelConnection(bool b) -{ - #ifdef P3PEERS_DEBUG - std::cerr << "p3Peers::allowTunnelConnection() set tunnel to : " << b << std::endl; - #endif - mLinkMgr->setTunnelConnection(b) ; -} - bool p3Peers::getAllowServerIPDetermination() { return mNetMgr->getIPServersEnabled() ; } -bool p3Peers::getAllowTunnelConnection() -{ - #ifdef P3PEERS_DEBUG - std::cerr << "p3Peers::getAllowTunnelConnection() tunnel is : " << mConnMgr->getTunnelConnection() << std::endl; - #endif - return mLinkMgr->getTunnelConnection() ; -} - bool p3Peers::setLocalAddress(const std::string &id, const std::string &addr_str, uint16_t port) { #ifdef P3PEERS_DEBUG diff --git a/libretroshare/src/rsserver/p3peers.h b/libretroshare/src/rsserver/p3peers.h index 482154adc..cc5f54d07 100644 --- a/libretroshare/src/rsserver/p3peers.h +++ b/libretroshare/src/rsserver/p3peers.h @@ -92,9 +92,7 @@ virtual bool setVisState(const std::string &id, uint32_t mode); virtual void getIPServersList(std::list& ip_servers) ; virtual void allowServerIPDetermination(bool) ; -virtual void allowTunnelConnection(bool) ; virtual bool getAllowServerIPDetermination() ; -virtual bool getAllowTunnelConnection() ; /* Auth Stuff */ // Get the invitation (GPG cert + local/ext address + SSL id for the given peer) diff --git a/libretroshare/src/rsserver/rsinit.cc b/libretroshare/src/rsserver/rsinit.cc index fe01152e0..67008f97c 100644 --- a/libretroshare/src/rsserver/rsinit.cc +++ b/libretroshare/src/rsserver/rsinit.cc @@ -275,7 +275,6 @@ void RsInit::InitRsConfig() //setZoneLevel(PQL_DEBUG_BASIC, 38422); // pqipacket. //setZoneLevel(PQL_DEBUG_BASIC, 96184); // pqinetwork; //setZoneLevel(PQL_DEBUG_BASIC, 82371); // pqiperson. - //setZoneLevel(PQL_DEBUG_BASIC, 60478); // pqitunnel. //setZoneLevel(PQL_DEBUG_BASIC, 34283); // pqihandler. //setZoneLevel(PQL_DEBUG_BASIC, 44863); // discItems. //setZoneLevel(PQL_DEBUG_BASIC, 2482); // p3disc @@ -1761,11 +1760,7 @@ RsTurtle *rsTurtle = NULL ; #include "services/p3disc.h" #include "services/p3msgservice.h" #include "services/p3chatservice.h" -#include "services/p3gamelauncher.h" -#include "services/p3forums.h" -#include "services/p3channels.h" #include "services/p3statusservice.h" -#include "services/p3blogs.h" #include "turtle/p3turtle.h" #ifdef RS_ENABLE_GXS @@ -1785,10 +1780,6 @@ RsTurtle *rsTurtle = NULL ; #endif // RS_ENABLE_GXS -#ifndef PQI_DISABLE_TUNNEL -#include "services/p3tunnel.h" -#endif - #include #include @@ -1805,7 +1796,6 @@ RsTurtle *rsTurtle = NULL ; #include "rsserver/p3history.h" #include "rsserver/p3serverconfig.h" -#include "retroshare/rsgame.h" #include "pqi/p3notify.h" // HACK - moved to pqi for compilation order. @@ -2134,9 +2124,6 @@ int RsServer::StartupRetroShare() std::string config_dir = RsInitConfig::configDir; std::string localcachedir = config_dir + "/cache/local"; std::string remotecachedir = config_dir + "/cache/remote"; - std::string channelsdir = config_dir + "/channels"; - std::string blogsdir = config_dir + "/blogs"; - std::string forumdir = config_dir + "/forums"; std::vector plugins_directories ; @@ -2189,12 +2176,6 @@ int RsServer::StartupRetroShare() chatSrv = new p3ChatService(mLinkMgr, mHistoryMgr); mStatusSrv = new p3StatusService(mLinkMgr); -#ifndef PQI_DISABLE_TUNNEL - p3tunnel *tn = new p3tunnel(mConnMgr, pqih); - pqih -> addService(tn); - mConnMgr->setP3tunnel(tn); -#endif - p3turtle *tr = new p3turtle(mLinkMgr) ; rsTurtle = tr ; pqih -> addService(tr); @@ -2208,22 +2189,6 @@ int RsServer::StartupRetroShare() pqih -> addService(chatSrv); pqih ->addService(mStatusSrv); - mForums = new p3Forums(RS_SERVICE_TYPE_FORUM, mCacheStrapper, mCacheTransfer, localcachedir, remotecachedir, forumdir); - - mCacheStrapper -> addCachePair( CachePair(mForums, mForums, CacheId(RS_SERVICE_TYPE_FORUM, 0))); - pqih -> addService(mForums); /* This must be also ticked as a service */ - - mChannels = new p3Channels(RS_SERVICE_TYPE_CHANNEL, mCacheStrapper, mCacheTransfer, rsFiles, localcachedir, remotecachedir, channelsdir); - - mCacheStrapper -> addCachePair(CachePair(mChannels, mChannels, CacheId(RS_SERVICE_TYPE_CHANNEL, 0))); - pqih -> addService(mChannels); /* This must be also ticked as a service */ -#ifdef RS_USE_BLOGS - p3Blogs *mBlogs = new p3Blogs(RS_SERVICE_TYPE_QBLOG, mCacheStrapper, mCacheTransfer, rsFiles, localcachedir, remotecachedir, blogsdir); - - mCacheStrapper -> addCachePair(CachePair(mBlogs, mBlogs, CacheId(RS_SERVICE_TYPE_QBLOG, 0))); - pqih -> addService(mBlogs); /* This must be also ticked as a service */ - -#endif // now add plugin objects inside the loop: // - client services provided by plugins. // - cache services provided by plugins. @@ -2419,11 +2384,6 @@ int RsServer::StartupRetroShare() #endif // RS_ENABLE_GXS. -#ifndef RS_RELEASE - p3GameLauncher *gameLauncher = new p3GameLauncher(mLinkMgr); - pqih -> addService(gameLauncher); -#endif - #ifdef RS_VOIPTEST p3VoRS *mVoipTest = new p3VoRS(mLinkMgr); pqih -> addService(mVoipTest); @@ -2476,7 +2436,7 @@ int RsServer::StartupRetroShare() /* need to Monitor too! */ mLinkMgr->addMonitor(pqih); mLinkMgr->addMonitor(mCacheStrapper); - mLinkMgr->addMonitor(ad); + //mLinkMgr->addMonitor(ad); mLinkMgr->addMonitor(msgSrv); mLinkMgr->addMonitor(mStatusSrv); mLinkMgr->addMonitor(chatSrv); @@ -2501,14 +2461,9 @@ int RsServer::StartupRetroShare() mConfigMgr->addConfiguration("msgs.cfg", msgSrv); mConfigMgr->addConfiguration("chat.cfg", chatSrv); mConfigMgr->addConfiguration("p3History.cfg", mHistoryMgr); -#ifdef RS_USE_BLOGS - mConfigMgr->addConfiguration("blogs.cfg", mBlogs); -#endif - mConfigMgr->addConfiguration("forums.cfg", mForums); - mConfigMgr->addConfiguration("channels.cfg", mChannels); mConfigMgr->addConfiguration("p3Status.cfg", mStatusSrv); mConfigMgr->addConfiguration("turtle.cfg", tr); - mConfigMgr->addConfiguration("p3disc.cfg", ad); + //mConfigMgr->addConfiguration("p3disc.cfg", ad); #ifdef RS_USE_BITDHT mConfigMgr->addConfiguration("bitdht.cfg", mBitDht); @@ -2596,31 +2551,10 @@ int RsServer::StartupRetroShare() /* Peer stuff is up to date */ - /* Channel/Forum/Blog stuff will all come from Caches */ - getPqiNotify()->ClearFeedItems(RS_FEED_ITEM_CHAN_NEW); - getPqiNotify()->ClearFeedItems(RS_FEED_ITEM_CHAN_UPDATE); - getPqiNotify()->ClearFeedItems(RS_FEED_ITEM_CHAN_MSG); - - getPqiNotify()->ClearFeedItems(RS_FEED_ITEM_FORUM_NEW); - getPqiNotify()->ClearFeedItems(RS_FEED_ITEM_FORUM_UPDATE); - getPqiNotify()->ClearFeedItems(RS_FEED_ITEM_FORUM_MSG); - - getPqiNotify()->ClearFeedItems(RS_FEED_ITEM_BLOG_NEW); - getPqiNotify()->ClearFeedItems(RS_FEED_ITEM_BLOG_UPDATE); - getPqiNotify()->ClearFeedItems(RS_FEED_ITEM_BLOG_MSG); - //getPqiNotify()->ClearFeedItems(RS_FEED_ITEM_CHAT_NEW); getPqiNotify()->ClearFeedItems(RS_FEED_ITEM_MESSAGE); //getPqiNotify()->ClearFeedItems(RS_FEED_ITEM_FILES_NEW); - /* flag that the basic Caches are now in the pending Queues */ - mForums->HistoricalCachesDone(); - mChannels->HistoricalCachesDone(); - -#ifdef RS_USE_BLOGS - mBlogs->HistoricalCachesDone(); -#endif - /**************************************************************************/ /* Add AuthGPG services */ /**************************************************************************/ @@ -2678,14 +2612,6 @@ int RsServer::StartupRetroShare() mBitDht->start(); #endif - // startup the p3distrib threads (for cache loading). - mForums->start(); - mChannels->start(); - -#ifdef RS_USE_BLOGS - mBlogs->start(); -#endif - /**************************************************************************/ // create loopback device, and add to pqisslgrp. @@ -2706,23 +2632,10 @@ int RsServer::StartupRetroShare() rsConfig = serverConfig; rsMsgs = new p3Msgs(msgSrv, chatSrv); - rsForums = mForums; - rsChannels = mChannels; - - - -#ifdef RS_USE_BLOGS - rsBlogs = mBlogs; -#endif + rsStatus = new p3Status(mStatusSrv); rsHistory = new p3History(mHistoryMgr); -#ifndef RS_RELEASE - rsGameLauncher = gameLauncher; -#else - rsGameLauncher = NULL; -#endif - /* put a welcome message in! */ if (RsInitConfig::firsttime_run) { diff --git a/libretroshare/src/serialiser/rsblogitems.cc b/libretroshare/src/serialiser/rsblogitems.cc deleted file mode 100644 index 1ad80c4c6..000000000 --- a/libretroshare/src/serialiser/rsblogitems.cc +++ /dev/null @@ -1,255 +0,0 @@ - -/* - * libretroshare/src/serialiser: rsblogitems.cc - * - * RetroShare Serialiser. - * - * Copyright 2010 by Cyril, Chris Parker . - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License Version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 - * USA. - * - * Please report all bugs and problems to "retroshare@lunamutt.com". - * - */ - -#include "serialiser/rsblogitems.h" - -#include "serialiser/rsbaseserial.h" -#include "serialiser/rstlvbase.h" - -#define RSSERIAL_DEBUG 1 -#include - -/*************************************************************************/ - -void RsBlogMsg::clear() -{ - RsDistribMsg::clear(); - - subject.clear(); - message.clear(); - - std::list::iterator it = graphic_set.begin(); - - for(; it != graphic_set.end(); it++) - { - it->TlvClear(); - } - - graphic_set.clear(); -} - -std::ostream &RsBlogMsg::print(std::ostream &out, uint16_t indent) -{ - printRsItemBase(out, "RsBlogMsg", indent); - uint16_t int_Indent = indent + 2; - - RsDistribMsg::print(out, int_Indent); - - printIndent(out, int_Indent); - - std::string cnv_subject(subject.begin(), subject.end()); - out << "subject: " << cnv_subject << std::endl; - - printIndent(out, int_Indent); - - std::string cnv_message(message.begin(), message.end()); - out << "message: " << cnv_message << std::endl; - - std::list::iterator it = graphic_set.begin(); - - for(; it != graphic_set.end(); it++) - { - it->print(out, int_Indent); - } - - - printRsItemEnd(out, "RsBlogMsg", indent); - return out; -} - - -/*************************************************************************/ -/*************************************************************************/ - -uint32_t RsBlogSerialiser::sizeMsg(RsBlogMsg *item) -{ - uint32_t s = 8; /* header */ - /* RsDistribMsg stuff */ - s += GetTlvStringSize(item->grpId); - s += GetTlvStringSize(item->parentId); - s += GetTlvStringSize(item->threadId); - s += 4; /* timestamp */ - - /* RsBlogMsg stuff */ - s += GetTlvWideStringSize(item->subject); - s += GetTlvWideStringSize(item->message); - - std::list::iterator it = item->graphic_set.begin(); - - for(; it != item->graphic_set.end(); it++) - { - s += it->TlvSize(); - } - - return s; -} - -/* serialise the data to the buffer */ -bool RsBlogSerialiser::serialiseMsg(RsBlogMsg *item, void *data, uint32_t *pktsize) -{ - uint32_t tlvsize = sizeMsg(item); - uint32_t offset = 0; - - if (*pktsize < tlvsize) - return false; /* not enough space */ - - *pktsize = tlvsize; - - bool ok = true; - - ok &= setRsItemHeader(data, tlvsize, item->PacketId(), tlvsize); - - std::cerr << "RsBlogSerialiser::serialiseMsg() Header: " << ok << std::endl; - std::cerr << "RsBlogSerialiser::serialiseMsg() Size: " << tlvsize << std::endl; - - /* skip the header */ - offset += 8; - - /* RsDistribMsg first */ - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_GROUPID, item->grpId); - std::cerr << "RsBlogSerialiser::serialiseMsg() grpId: " << ok << std::endl; - - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_PARENTID, item->parentId); - std::cerr << "RsBlogSerialiser::serialiseMsg() parentId: " << ok << std::endl; - - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_THREADID, item->threadId); - std::cerr << "RsBlogSerialiser::serialiseMsg() threadpId: " << ok << std::endl; - - ok &= setRawUInt32(data, tlvsize, &offset, item->timestamp); - std::cerr << "RsBlogSerialiser::serialiseMsg() timestamp: " << ok << std::endl; - - /* RsBlogMsg */ - ok &= SetTlvWideString(data, tlvsize, &offset, TLV_TYPE_WSTR_SUBJECT, item->subject); - std::cerr << "RsBlogSerialiser::serialiseMsg() subject: " << ok << std::endl; - ok &= SetTlvWideString(data, tlvsize, &offset, TLV_TYPE_WSTR_MSG, item->message); - std::cerr << "RsBlogSerialiser::serialiseMsg() msg: " << ok << std::endl; - - std::list::iterator it = item->graphic_set.begin(); - - for(; it != item->graphic_set.end(); it++) - { - ok &= it->SetTlv(data, tlvsize, &offset); - } - - if (offset != tlvsize) - { - ok = false; - std::cerr << "RsBlogSerialiser::serialiseMsg() Size Error! " << std::endl; - } - - return ok; -} - - - -RsBlogMsg *RsBlogSerialiser::deserialiseMsg(void *data, uint32_t *pktsize) -{ - /* get the type and size */ - uint32_t rstype = getRsItemId(data); - uint32_t rssize = getRsItemSize(data); - - uint32_t offset = 0; - - - if ((RS_PKT_VERSION_SERVICE != getRsItemVersion(rstype)) || - (RS_SERVICE_TYPE_QBLOG != getRsItemService(rstype)) || - (RS_PKT_SUBTYPE_BLOG_MSG != getRsItemSubType(rstype))) - { - return NULL; /* wrong type */ - } - - if (*pktsize < rssize) /* check size */ - return NULL; /* not enough data */ - - /* set the packet length */ - *pktsize = rssize; - - bool ok = true; - - /* ready to load */ - RsBlogMsg *item = new RsBlogMsg(); - item->clear(); - - /* skip the header */ - offset += 8; - - /* RsDistribMsg first */ - ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_GROUPID, item->grpId); - ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_PARENTID, item->parentId); - ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_THREADID, item->threadId); - ok &= getRawUInt32(data, rssize, &offset, &(item->timestamp)); - - /* RsBlogMsg */ - - ok &= GetTlvWideString(data, rssize, &offset, TLV_TYPE_WSTR_SUBJECT, item->subject); - ok &= GetTlvWideString(data, rssize, &offset, TLV_TYPE_WSTR_MSG, item->message); - - RsTlvImage image; - image.TlvClear(); - - while(offset != rssize) - { - image.GetTlv(data, rssize, &offset); - item->graphic_set.push_back(image); - image.TlvClear(); - } - - if (offset != rssize) - { - /* error */ - delete item; - return NULL; - } - - if (!ok) - { - delete item; - return NULL; - } - - return item; -} - - -uint32_t RsBlogSerialiser::size(RsItem *item) -{ - return sizeMsg((RsBlogMsg *) item); -} - -bool RsBlogSerialiser::serialise(RsItem *item, void *data, uint32_t *pktsize) -{ - return serialiseMsg((RsBlogMsg *) item, data, pktsize); -} - -RsItem *RsBlogSerialiser::deserialise(void *data, uint32_t *pktsize) -{ - return deserialiseMsg(data, pktsize); -} - - - -/*************************************************************************/ - diff --git a/libretroshare/src/serialiser/rsblogitems.h b/libretroshare/src/serialiser/rsblogitems.h deleted file mode 100644 index 14412d762..000000000 --- a/libretroshare/src/serialiser/rsblogitems.h +++ /dev/null @@ -1,91 +0,0 @@ -#ifndef RS_BLOG_ITEMS_H -#define RS_BLOG_ITEMS_H - -/* - * libretroshare/src/serialiser: rsblogitems.h - * - * RetroShare Serialiser. - * - * Copyright 2007-2008 by Cyril, Chris Parker. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License Version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 - * USA. - * - * Please report all bugs and problems to "retroshare@lunamutt.com". - * - */ - -#include - -#include "serialiser/rsserviceids.h" -#include "serialiser/rsserial.h" -#include "serialiser/rstlvtypes.h" -#include "serialiser/rstlvkeys.h" - -#include "serialiser/rsdistribitems.h" - -const uint8_t RS_PKT_SUBTYPE_BLOG_MSG = 0x01; - -/**************************************************************************/ - -class RsBlogMsg: public RsDistribMsg -{ - public: - RsBlogMsg() - :RsDistribMsg(RS_SERVICE_TYPE_QBLOG, RS_PKT_SUBTYPE_BLOG_MSG) { return; } -virtual ~RsBlogMsg() { return; } - -virtual void clear(); -virtual std::ostream& print(std::ostream &out, uint16_t indent = 0); - - /* - * RsDistribMsg has: - * grpId, timestamp. - * Not Used: parentId, threadId - */ - std::wstring subject; - std::wstring message; - - /// for adding images to graphics - std::list graphic_set; - -}; - -class RsBlogSerialiser: public RsSerialType -{ - public: - RsBlogSerialiser() - :RsSerialType(RS_PKT_VERSION_SERVICE, RS_SERVICE_TYPE_QBLOG) - { return; } -virtual ~RsBlogSerialiser() - { return; } - -virtual uint32_t size(RsItem *); -virtual bool serialise (RsItem *item, void *data, uint32_t *size); -virtual RsItem * deserialise(void *data, uint32_t *size); - - private: - - /* For RS_PKT_SUBTYPE_CHANNEL_MSG */ -virtual uint32_t sizeMsg(RsBlogMsg *); -virtual bool serialiseMsg(RsBlogMsg *item, void *data, uint32_t *size); -virtual RsBlogMsg *deserialiseMsg(void *data, uint32_t *size); - -}; - -/**************************************************************************/ - -#endif /* RS_BLOG_ITEMS_H */ - - diff --git a/libretroshare/src/serialiser/rschannelitems.cc b/libretroshare/src/serialiser/rschannelitems.cc deleted file mode 100644 index b9cd79f70..000000000 --- a/libretroshare/src/serialiser/rschannelitems.cc +++ /dev/null @@ -1,627 +0,0 @@ - -/* - * libretroshare/src/serialiser: rschannelitems.cc - * - * RetroShare Serialiser. - * - * Copyright 2008 by Robert Fernie. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License Version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 - * USA. - * - * Please report all bugs and problems to "retroshare@lunamutt.com". - * - */ - -#include "serialiser/rschannelitems.h" - -#include "serialiser/rsbaseserial.h" -#include "serialiser/rstlvbase.h" - -//#define RSSERIAL_DEBUG 0 -#include - -/*************************************************************************/ - -void RsChannelMsg::clear() -{ - RsDistribMsg::clear(); - - subject.clear(); - message.clear(); - - attachment.TlvClear(); - thumbnail.TlvClear(); -} - -std::ostream &RsChannelMsg::print(std::ostream &out, uint16_t indent) -{ - printRsItemBase(out, "RsChannelMsg", indent); - uint16_t int_Indent = indent + 2; - - RsDistribMsg::print(out, int_Indent); - - printIndent(out, int_Indent); - - std::string cnv_subject(subject.begin(), subject.end()); - out << "subject: " << cnv_subject << std::endl; - - printIndent(out, int_Indent); - - std::string cnv_message(message.begin(), message.end()); - out << "message: " << cnv_message << std::endl; - - printIndent(out, int_Indent); - out << "Attachment: " << std::endl; - attachment.print(out, int_Indent); - - printIndent(out, int_Indent); - out << "Thumbnail: " << std::endl; - thumbnail.print(out, int_Indent); - - printRsItemEnd(out, "RsChannelMsg", indent); - return out; -} - -void RsChannelReadStatus::clear() -{ - - RsDistribChildConfig::clear(); - - channelId.clear(); - msgReadStatus.clear(); - - return; - -} -std::ostream& RsChannelDestDirConfigItem::print(std::ostream &out, uint16_t indent = 0) -{ - - printRsItemBase(out, "RsChannelDestDirConfigItem", indent); - uint16_t int_Indent = indent + 2; - - RsDistribChildConfig::print(out, int_Indent); - - for(uint32_t i=0;i::iterator mit = msgReadStatus.begin(); - - for(; mit != msgReadStatus.end(); mit++) - { - - printIndent(out, int_Indent); - out << "msgId : " << mit->first << std::endl; - - printIndent(out, int_Indent); - out << " status : " << mit->second << std::endl; - - } - - printRsItemEnd(out, "RsChannelMsg", indent); - return out; -} - -/*************************************************************************/ -/*************************************************************************/ - -uint32_t RsChannelSerialiser::sizeMsg(RsChannelMsg *item) -{ - uint32_t s = 8; /* header */ - /* RsDistribMsg stuff */ - s += GetTlvStringSize(item->grpId); - s += 4; /* timestamp */ - - /* RsChannelMsg stuff */ - s += GetTlvWideStringSize(item->subject); - s += GetTlvWideStringSize(item->message); - s += item->attachment.TlvSize(); - s += item->thumbnail.TlvSize(); - - return s; -} - -/* serialise the data to the buffer */ -bool RsChannelSerialiser::serialiseMsg(RsChannelMsg *item, void *data, uint32_t *pktsize) -{ - uint32_t tlvsize = sizeMsg(item); - uint32_t offset = 0; - - if (*pktsize < tlvsize) - return false; /* not enough space */ - - *pktsize = tlvsize; - - bool ok = true; - - ok &= setRsItemHeader(data, tlvsize, item->PacketId(), tlvsize); - -#ifdef RSSERIAL_DEBUG - std::cerr << "RsChannelSerialiser::serialiseMsg() Header: " << ok << std::endl; - std::cerr << "RsChannelSerialiser::serialiseMsg() Size: " << tlvsize << std::endl; -#endif - - /* skip the header */ - offset += 8; - - /* RsDistribMsg first */ - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_GROUPID, item->grpId); -#ifdef RSSERIAL_DEBUG - std::cerr << "RsChannelSerialiser::serialiseMsg() grpId: " << ok << std::endl; -#endif - - ok &= setRawUInt32(data, tlvsize, &offset, item->timestamp); -#ifdef RSSERIAL_DEBUG - std::cerr << "RsChannelSerialiser::serialiseMsg() timestamp: " << ok << std::endl; -#endif - - /* RsChannelMsg */ - ok &= SetTlvWideString(data, tlvsize, &offset, TLV_TYPE_WSTR_SUBJECT, item->subject); -#ifdef RSSERIAL_DEBUG - std::cerr << "RsChannelSerialiser::serialiseMsg() Title: " << ok << std::endl; -#endif - ok &= SetTlvWideString(data, tlvsize, &offset, TLV_TYPE_WSTR_MSG, item->message); -#ifdef RSSERIAL_DEBUG - std::cerr << "RsChannelSerialiser::serialiseMsg() Msg: " << ok << std::endl; -#endif - - ok &= item->attachment.SetTlv(data, tlvsize, &offset); -#ifdef RSSERIAL_DEBUG - std::cerr << "RsChannelSerialiser::serialiseMsg() Attachment: " << ok << std::endl; -#endif - - ok &= item->thumbnail.SetTlv(data, tlvsize, &offset); -#ifdef RSSERIAL_DEBUG - std::cerr << "RsChannelSerialiser::serialiseMsg() thumbnail: " << ok << std::endl; -#endif - - if (offset != tlvsize) - { - ok = false; - std::cerr << "RsChannelSerialiser::serialiseMsg() Size Error! " << std::endl; - } - - return ok; -} - - - -RsChannelMsg *RsChannelSerialiser::deserialiseMsg(void *data, uint32_t *pktsize) -{ - /* get the type and size */ - uint32_t rstype = getRsItemId(data); - uint32_t rssize = getRsItemSize(data); - - uint32_t offset = 0; - - - if ((RS_PKT_VERSION_SERVICE != getRsItemVersion(rstype)) || - (RS_SERVICE_TYPE_CHANNEL != getRsItemService(rstype)) || - (RS_PKT_SUBTYPE_CHANNEL_MSG != getRsItemSubType(rstype))) - { - return NULL; /* wrong type */ - } - - if (*pktsize < rssize) /* check size */ - return NULL; /* not enough data */ - - /* set the packet length */ - *pktsize = rssize; - - bool ok = true; - - /* ready to load */ - RsChannelMsg *item = new RsChannelMsg(); - item->clear(); - - /* skip the header */ - offset += 8; - - /* RsDistribMsg first */ - ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_GROUPID, item->grpId); - ok &= getRawUInt32(data, rssize, &offset, &(item->timestamp)); - - /* RsChannelMsg */ - ok &= GetTlvWideString(data, rssize, &offset, TLV_TYPE_WSTR_SUBJECT, item->subject); - ok &= GetTlvWideString(data, rssize, &offset, TLV_TYPE_WSTR_MSG, item->message); - ok &= item->attachment.GetTlv(data, rssize, &offset); - ok &= item->thumbnail.GetTlv(data, rssize, &offset); - - - if (offset != rssize) - { - /* error */ - delete item; - return NULL; - } - - if (!ok) - { - delete item; - return NULL; - } - - return item; -} - - -uint32_t RsChannelSerialiser::sizeDestDirConfig(RsChannelDestDirConfigItem *item) -{ - uint32_t s = 8; /* header */ - /* RsDistribChildConfig stuff */ - - s += 4; /* save_type */ - - /* RsChannelReadStatus stuff */ - - s += 4; /* size */ - - for(uint32_t i=0;idest_dirs.size();++i) - { - s += GetTlvStringSize(item->dest_dirs[i].first) ; - s += GetTlvStringSize(item->dest_dirs[i].second) ; - } - - return s; -} -uint32_t RsChannelSerialiser::sizeReadStatus(RsChannelReadStatus *item) -{ - uint32_t s = 8; /* header */ - /* RsDistribChildConfig stuff */ - - s += 4; /* save_type */ - - /* RsChannelReadStatus stuff */ - - s += GetTlvStringSize(item->channelId); - - std::map::iterator mit = item->msgReadStatus.begin(); - - for(; mit != item->msgReadStatus.end(); mit++) - { - s += GetTlvStringSize(mit->first); /* key */ - s += 4; /* value */ - } - - return s; -} - -/* serialise the data to the buffer */ -bool RsChannelSerialiser::serialiseDestDirConfig(RsChannelDestDirConfigItem *item, void *data, uint32_t *pktsize) -{ - uint32_t tlvsize = sizeDestDirConfig(item); - uint32_t offset = 0; - - if (*pktsize < tlvsize) - return false; /* not enough space */ - - *pktsize = tlvsize; - - bool ok = true; - - ok &= setRsItemHeader(data, tlvsize, item->PacketId(), tlvsize); -#ifdef RSSERIAL_DEBUG - std::cerr << "RsChannelSerialiser::serialiseDestDirConfig() Header: " << ok << std::endl; - std::cerr << "RsChannelSerialiser::serialiseDestDirConfig() Size: " << tlvsize << std::endl; -#endif - - /* skip the header */ - offset += 8; - - /* RsDistribMsg first */ - - ok &= setRawUInt32(data, tlvsize, &offset, item->save_type); -#ifdef RSSERIAL_DEBUG - std::cerr << "RsChannelSerialiser::serialiseDestDirConfig() save_type: " << ok << std::endl; -#endif - ok &= setRawUInt32(data, tlvsize, &offset, item->dest_dirs.size()); /* value */ - - for(uint32_t i=0;idest_dirs.size();++i) - { - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_GROUPID, item->dest_dirs[i].first) ; - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_PATH, item->dest_dirs[i].second) ; - } - -#ifdef RSSERIAL_DEBUG - std::cerr << "RsChannelSerialiser::serialiseDestDirConfig() msgReadStatus: " << ok << std::endl; -#endif - - if (offset != tlvsize) - { - ok = false; - std::cerr << "RsChannelSerialiser::serialiseDestDirConfig() Size Error! " << std::endl; - } - - return ok; -} -/* serialise the data to the buffer */ -bool RsChannelSerialiser::serialiseReadStatus(RsChannelReadStatus *item, void *data, uint32_t *pktsize) -{ - uint32_t tlvsize = sizeReadStatus(item); - uint32_t offset = 0; - - if (*pktsize < tlvsize) - return false; /* not enough space */ - - *pktsize = tlvsize; - - bool ok = true; - - ok &= setRsItemHeader(data, tlvsize, item->PacketId(), tlvsize); -#ifdef RSSERIAL_DEBUG - std::cerr << "RsChannelSerialiser::serialiseReadStatus() Header: " << ok << std::endl; - std::cerr << "RsChannelSerialiser::serialiseReadStatus() Size: " << tlvsize << std::endl; -#endif - - /* skip the header */ - offset += 8; - - /* RsDistribMsg first */ - - ok &= setRawUInt32(data, tlvsize, &offset, item->save_type); -#ifdef RSSERIAL_DEBUG - std::cerr << "RsChannelSerialiser::serialiseReadStatus() save_type: " << ok << std::endl; -#endif - - - - /* RsChannelMsg */ - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_GROUPID, item->channelId); -#ifdef RSSERIAL_DEBUG - std::cerr << "RsChannelSerialiser::serialiseReadStatus() channelId: " << ok << std::endl; -#endif - - std::map::iterator mit = item->msgReadStatus.begin(); - - for(; mit != item->msgReadStatus.end(); mit++) - { - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_MSGID, mit->first); /* key */ - ok &= setRawUInt32(data, tlvsize, &offset, mit->second); /* value */ - } - -#ifdef RSSERIAL_DEBUG - std::cerr << "RsChannelSerialiser::serialiseReadStatus() msgReadStatus: " << ok << std::endl; -#endif - - if (offset != tlvsize) - { - ok = false; - std::cerr << "RsChannelSerialiser::serialiseReadStatus() Size Error! " << std::endl; - } - - return ok; -} - -RsChannelDestDirConfigItem *RsChannelSerialiser::deserialiseDestDirConfig(void *data, uint32_t *pktsize) -{ - /* get the type and size */ - uint32_t rstype = getRsItemId(data); - uint32_t rssize = getRsItemSize(data); - - uint32_t offset = 0; - - - if ((RS_PKT_VERSION_SERVICE != getRsItemVersion(rstype)) || (RS_SERVICE_TYPE_CHANNEL != getRsItemService(rstype)) || (RS_PKT_SUBTYPE_CHANNEL_DEST_DIR != getRsItemSubType(rstype))) - return NULL; /* wrong type */ - - if (*pktsize < rssize) /* check size */ - return NULL; /* not enough data */ - - /* set the packet length */ - *pktsize = rssize; - - bool ok = true; - - /* ready to load */ - RsChannelDestDirConfigItem *item = new RsChannelDestDirConfigItem(); - item->clear(); - - /* skip the header */ - offset += 8; - - /* RsDistribMsg first */ - ok &= getRawUInt32(data, rssize, &offset, &(item->save_type)); - - uint32_t size ; - ok &= getRawUInt32(data, rssize, &offset, &size) ; - - for(uint32_t i=0;idest_dirs.push_back(std::pair(chid,path)) ; - } - - if(offset != rssize) - { - ok = false; - std::cerr << "RsChannelSerialiser::deserialiseDestDirConfig() Size Error! " << std::endl; - } - - if (!ok) - { - delete item; - return NULL; - } - - return item; -} - -RsChannelReadStatus *RsChannelSerialiser::deserialiseReadStatus(void *data, uint32_t *pktsize) -{ - /* get the type and size */ - uint32_t rstype = getRsItemId(data); - uint32_t rssize = getRsItemSize(data); - - uint32_t offset = 0; - - - if ((RS_PKT_VERSION_SERVICE != getRsItemVersion(rstype)) || - (RS_SERVICE_TYPE_CHANNEL != getRsItemService(rstype)) || - (RS_PKT_SUBTYPE_CHANNEL_READ_STATUS != getRsItemSubType(rstype))) - { - return NULL; /* wrong type */ - } - - if (*pktsize < rssize) /* check size */ - return NULL; /* not enough data */ - - /* set the packet length */ - *pktsize = rssize; - - bool ok = true; - - /* ready to load */ - RsChannelReadStatus *item = new RsChannelReadStatus(); - item->clear(); - - /* skip the header */ - offset += 8; - - /* RsDistribMsg first */ - ok &= getRawUInt32(data, rssize, &offset, &(item->save_type)); - - /* RschannelMsg */ - ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_GROUPID, item->channelId); - - std::string key; - uint32_t value; - - while(offset != rssize) - { - key.clear(); - value = 0; - - ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_MSGID, key); /* key */ - - /* incomplete key value pair? then fail*/ - if(offset == rssize) - { - delete item; - return NULL; - } - - ok &= getRawUInt32(data, rssize, &offset, &value); /* value */ - - item->msgReadStatus.insert(std::pair(key, value)); - } - - if (!ok) - { - delete item; - return NULL; - } - - return item; -} - -/************************************************************/ - -uint32_t RsChannelSerialiser::size(RsItem *item) -{ - RsChannelMsg* dcm; - RsChannelReadStatus* drs; - RsChannelDestDirConfigItem* dd; - - if( NULL != ( dcm = dynamic_cast(item))) - { - return sizeMsg(dcm); - } - else if(NULL != (drs = dynamic_cast(item))) - { - return sizeReadStatus(drs); - } - else if(NULL != (dd = dynamic_cast(item))) - { - return sizeDestDirConfig(dd); - } - - return false; -} - -bool RsChannelSerialiser::serialise(RsItem *item, void *data, uint32_t *pktsize) -{ - RsChannelMsg* dcm; - RsChannelReadStatus* drs; - RsChannelDestDirConfigItem* dd; - - if( NULL != ( dcm = dynamic_cast(item))) - { - return serialiseMsg(dcm, data, pktsize); - } - else if(NULL != (drs = dynamic_cast(item))) - { - return serialiseReadStatus(drs, data, pktsize); - } - else if(NULL != (dd = dynamic_cast(item))) - { - return serialiseDestDirConfig(dd, data, pktsize); - } - - return false; -} - -RsItem *RsChannelSerialiser::deserialise(void *data, uint32_t *pktsize) -{ - if(data == NULL) - return NULL ; - - /* get the type and size */ - uint32_t rstype = getRsItemId(data); - - if ((RS_PKT_VERSION_SERVICE != getRsItemVersion(rstype)) || - (RS_SERVICE_TYPE_CHANNEL != getRsItemService(rstype))) - { - return NULL; /* wrong type */ - } - - switch(getRsItemSubType(rstype)) - { - case RS_PKT_SUBTYPE_CHANNEL_MSG: - return deserialiseMsg(data, pktsize); - case RS_PKT_SUBTYPE_CHANNEL_READ_STATUS: - return deserialiseReadStatus(data, pktsize); - case RS_PKT_SUBTYPE_CHANNEL_DEST_DIR: - return deserialiseDestDirConfig(data, pktsize); - default: - return NULL; - } - - return NULL; -} - - - -/*************************************************************************/ - diff --git a/libretroshare/src/serialiser/rschannelitems.h b/libretroshare/src/serialiser/rschannelitems.h deleted file mode 100644 index 3eb20d5e9..000000000 --- a/libretroshare/src/serialiser/rschannelitems.h +++ /dev/null @@ -1,141 +0,0 @@ -#ifndef RS_CHANNEL_ITEMS_H -#define RS_CHANNEL_ITEMS_H - -/* - * libretroshare/src/serialiser: rschannelitems.h - * - * RetroShare Serialiser. - * - * Copyright 2007-2008 by Robert Fernie. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License Version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 - * USA. - * - * Please report all bugs and problems to "retroshare@lunamutt.com". - * - */ - -#include - -#include "serialiser/rsserviceids.h" -#include "serialiser/rsserial.h" -#include "serialiser/rstlvtypes.h" -#include "serialiser/rstlvkeys.h" - -#include "serialiser/rsdistribitems.h" - -const uint8_t RS_PKT_SUBTYPE_CHANNEL_MSG = 0x01; -const uint8_t RS_PKT_SUBTYPE_CHANNEL_READ_STATUS = 0x02; -const uint8_t RS_PKT_SUBTYPE_CHANNEL_DEST_DIR = 0x03; - -/**************************************************************************/ - -class RsChannelMsg: public RsDistribMsg -{ - public: - RsChannelMsg() - :RsDistribMsg(RS_SERVICE_TYPE_CHANNEL, RS_PKT_SUBTYPE_CHANNEL_MSG) { return; } -virtual ~RsChannelMsg() { return; } - -virtual void clear(); -virtual std::ostream& print(std::ostream &out, uint16_t indent = 0); - - /* - * RsDistribMsg has: - * grpId, timestamp. - * Not Used: parentId, threadId - */ - - std::wstring subject; - std::wstring message; - - RsTlvFileSet attachment; - RsTlvImage thumbnail; - -}; - -/*! - * This is used to keep track of whether a message has been read - * by client - */ -class RsChannelReadStatus : public RsDistribChildConfig -{ -public: - RsChannelReadStatus() - : RsDistribChildConfig(RS_SERVICE_TYPE_CHANNEL, RS_PKT_SUBTYPE_CHANNEL_READ_STATUS) - { return; } - - virtual ~RsChannelReadStatus() {return; } - - virtual void clear(); - virtual std::ostream& print(std::ostream &out, uint16_t indent); - - std::string channelId; - - /// a map which contains the read for messages within a forum - std::map msgReadStatus; - - std::string destination_directory ; -}; -/*! - * This is used to store the destination directories of each channel - */ -class RsChannelDestDirConfigItem : public RsDistribChildConfig -{ -public: - RsChannelDestDirConfigItem() - : RsDistribChildConfig(RS_SERVICE_TYPE_CHANNEL, RS_PKT_SUBTYPE_CHANNEL_DEST_DIR) - { return; } - - virtual ~RsChannelDestDirConfigItem() {} - - virtual void clear() { dest_dirs.clear() ; } - virtual std::ostream& print(std::ostream &out, uint16_t indent); - - std::vector > dest_dirs; -}; -class RsChannelSerialiser: public RsSerialType -{ - public: - RsChannelSerialiser() - :RsSerialType(RS_PKT_VERSION_SERVICE, RS_SERVICE_TYPE_CHANNEL) - { return; } -virtual ~RsChannelSerialiser() - { return; } - -virtual uint32_t size(RsItem *); -virtual bool serialise (RsItem *item, void *data, uint32_t *size); -virtual RsItem * deserialise(void *data, uint32_t *size); - - private: - - /* For RS_PKT_SUBTYPE_CHANNEL_MSG */ -virtual uint32_t sizeMsg(RsChannelMsg *); -virtual bool serialiseMsg(RsChannelMsg *item, void *data, uint32_t *size); -virtual RsChannelMsg *deserialiseMsg(void *data, uint32_t *size); - -virtual uint32_t sizeReadStatus(RsChannelReadStatus* ); -virtual bool serialiseReadStatus(RsChannelReadStatus* item, void* data, uint32_t *size); -virtual RsChannelReadStatus *deserialiseReadStatus(void* data, uint32_t *size); - -virtual uint32_t sizeDestDirConfig(RsChannelDestDirConfigItem* ); -virtual bool serialiseDestDirConfig(RsChannelDestDirConfigItem* item, void* data, uint32_t *size); -virtual RsChannelDestDirConfigItem *deserialiseDestDirConfig(void* data, uint32_t *size); -}; - -/**************************************************************************/ - -#endif /* RS_CHANNEL_ITEMS_H */ - - diff --git a/libretroshare/src/serialiser/rsdistribitems.cc b/libretroshare/src/serialiser/rsdistribitems.cc deleted file mode 100644 index 5a4396c5d..000000000 --- a/libretroshare/src/serialiser/rsdistribitems.cc +++ /dev/null @@ -1,958 +0,0 @@ - -/* - * libretroshare/src/serialiser: rsforumitems.cc - * - * RetroShare Serialiser. - * - * Copyright 2007-2008 by Robert Fernie. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License Version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 - * USA. - * - * Please report all bugs and problems to "retroshare@lunamutt.com". - * - */ - -#include "serialiser/rsdistribitems.h" - -#include "serialiser/rsbaseserial.h" -#include "serialiser/rstlvbase.h" - -//#define RSSERIAL_DEBUG 1 -#include - -/*************************************************************************/ - -void RsDistribMsg::clear() -{ - grpId.clear(); - parentId.clear(); - threadId.clear(); - timestamp = 0; - childTS = 0; - - msgId.clear(); - publishSignature.TlvClear(); - personalSignature.TlvClear(); -} - -std::ostream &RsDistribMsg::print(std::ostream &out, uint16_t indent) -{ - printRsItemBase(out, "RsDistribMsg", indent); - uint16_t int_Indent = indent + 2; - printIndent(out, int_Indent); - out << "grpId: " << grpId << std::endl; - printIndent(out, int_Indent); - out << "parentId: " << parentId << std::endl; - printIndent(out, int_Indent); - out << "threadId: " << threadId << std::endl; - - printIndent(out, int_Indent); - out << "timestamp: " << timestamp << std::endl; - - printIndent(out, int_Indent); - out << "<<<<<<<< Not Serialised >>>>>>>>" << std::endl; - - printIndent(out, int_Indent); - out << "msgId: " << msgId << std::endl; - publishSignature.print(out, int_Indent); - personalSignature.print(out, int_Indent); - - out << "<<<<<<<< Not Serialised >>>>>>>>" << std::endl; - - printRsItemEnd(out, "RsDistribMsg", indent); - return out; -} - -void RsDistribChildConfig::clear() -{ - save_type = 0; -} - -std::ostream& RsDistribChildConfig::print(std::ostream &out, uint16_t indent) -{ - printRsItemBase(out, "RsDistribChildConfig", indent); - uint16_t int_Indent = indent + 2; - - printIndent(out, int_Indent); - out << "save_type: " << save_type << std::endl; - - printRsItemEnd(out, "RsDistribChildConfig", indent); - return out; -} - -void RsDistribConfigData::clear() -{ - service_data.TlvClear(); -} - -std::ostream& RsDistribConfigData::print(std::ostream &out, uint16_t indent) -{ - printRsItemBase(out, "RsDistribConfigData", indent); - uint16_t int_Indent = indent + 2; - - service_data.print(out, int_Indent); - - printRsItemEnd(out, "RsDistribChildConfig", indent); - return out; -} - -void RsDistribSignedMsg::clear() -{ -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDistribSignedMsg::clear()" << std::endl; -#endif - - grpId.clear(); - msgId.clear(); - flags = 0; - timestamp = 0; - packet.TlvClear(); - publishSignature.TlvClear(); - personalSignature.TlvClear(); - - return; -} - -std::ostream &RsDistribSignedMsg::print(std::ostream &out, uint16_t indent) -{ - printRsItemBase(out, "RsDistribSignedMsg", indent); - uint16_t int_Indent = indent + 2; - - printIndent(out, int_Indent); - out << "grpId: " << grpId << std::endl; - printIndent(out, int_Indent); - out << "msgId: " << msgId << std::endl; - printIndent(out, int_Indent); - out << "flags: " << flags << std::endl; - printIndent(out, int_Indent); - out << "timestamp: " << timestamp << std::endl; - packet.print(out, 10); - publishSignature.print(out, 10); - personalSignature.print(out, 10); - - printRsItemEnd(out, "RsDistribSignedMsg", indent); - return out; -} - -/*************************************************************************/ - -void RsDistribGrp::clear() -{ -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDistribGrp::clear()" << std::endl; -#endif - - grpId.clear(); - timestamp = 0; - grpFlags = 0; - grpName.clear(); - grpDesc.clear(); - grpCategory.clear(); - - grpControlFlags = 0; - grpControlList.TlvClear(); - - grpPixmap.TlvClear(); - - adminKey.TlvClear(); - publishKeys.TlvClear(); - - adminSignature.TlvClear(); -} - -std::ostream &RsDistribGrp::print(std::ostream &out, uint16_t indent) -{ - printRsItemBase(out, "RsDistribGrp", indent); - uint16_t int_Indent = indent + 2; - printIndent(out, int_Indent); - out << "grpId: " << grpId << std::endl; - printIndent(out, int_Indent); - out << "timestamp: " << timestamp << std::endl; - printIndent(out, int_Indent); - out << "grpFlags: " << grpFlags << std::endl; - - printIndent(out, int_Indent); - - std::string cnv_name(grpName.begin(), grpName.end()); - out << "grpName: " << cnv_name << std::endl; - - printIndent(out, int_Indent); - - std::string cnv_desc(grpDesc.begin(), grpDesc.end()); - out << "grpDesc: " << cnv_desc << std::endl; - - printIndent(out, int_Indent); - std::string cnv_category(grpCategory.begin(), grpCategory.end()); - out << "grpCategory: " << cnv_category << std::endl; - - printIndent(out, int_Indent); - out << "grpControlFlags: " << grpControlFlags << std::endl; - - grpControlList.print(out, int_Indent); - - grpPixmap.print(out, int_Indent); - - adminKey.print(out, int_Indent); - publishKeys.print(out, int_Indent); - adminSignature.print(out, int_Indent); - - printRsItemEnd(out, "RsDistribGrp", indent); - return out; -} - -/*************************************************************************/ - -void RsDistribGrpKey::clear() -{ -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDistribGrpKey::clear()" << std::endl; -#endif - - grpId.clear(); - key.TlvClear(); -} - -std::ostream &RsDistribGrpKey::print(std::ostream &out, uint16_t indent) -{ - printRsItemBase(out, "RsDistribGrpKey", indent); - uint16_t int_Indent = indent + 2; - printIndent(out, int_Indent); - out << "grpId: " << grpId << std::endl; - - key.print(out, int_Indent); - - printRsItemEnd(out, "RsDistribGrpKey", indent); - return out; -} - -/*************************************************************************/ -/*************************************************************************/ - -uint32_t RsDistribSerialiser::sizeGrp(RsDistribGrp *item) -{ - uint32_t s = 8; /* header */ - /* RsDistribMsg stuff */ - s += GetTlvStringSize(item->grpId); - s += 4; /* timestamp */ - s += 4; /* grpFlags */ - s += GetTlvWideStringSize(item->grpName); - s += GetTlvWideStringSize(item->grpDesc); - s += GetTlvWideStringSize(item->grpCategory); - - s += 4; /* grpControlFlags */ - s += item->grpControlList.TlvSize(); - - s += item->grpPixmap.TlvSize(); - - s += item->adminKey.TlvSize(); - s += item->publishKeys.TlvSize(); - s += item->adminSignature.TlvSize(); - - return s; -} - -/* serialise the data to the buffer */ -bool RsDistribSerialiser::serialiseGrp(RsDistribGrp *item, void *data, uint32_t *pktsize) -{ -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDistribSerialiser::serialiseGrp()" << std::endl; -#endif - - uint32_t tlvsize = sizeGrp(item); - uint32_t offset = 0; - - if (*pktsize < tlvsize) - { -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDistribSerialiser::serialiseGrp() FAIL no space" << std::endl; -#endif - - return false; /* not enough space */ - } - - *pktsize = tlvsize; - - bool ok = true; - - ok &= setRsItemHeader(data, tlvsize, item->PacketId(), tlvsize); - - /* skip the header */ - offset += 8; - - /* RsDistribGrp */ - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_GROUPID, item->grpId); - ok &= setRawUInt32(data, tlvsize, &offset, item->timestamp); - ok &= setRawUInt32(data, tlvsize, &offset, item->grpFlags); - -#ifdef RSSERIAL_DEBUG - if (!ok) - std::cerr << "RsDistribSerialiser::serialiseGrp() Id/Flags NOK" << std::endl; -#endif - ok &= SetTlvWideString(data, tlvsize, &offset, TLV_TYPE_WSTR_NAME, item->grpName); - ok &= SetTlvWideString(data, tlvsize, &offset, TLV_TYPE_WSTR_COMMENT, item->grpDesc); - ok &= SetTlvWideString(data, tlvsize, &offset, TLV_TYPE_WSTR_CATEGORY, item->grpCategory); - -#ifdef RSSERIAL_DEBUG - if (!ok) - std::cerr << "RsDistribSerialiser::serialiseGrp() Strings NOK" << std::endl; -#endif - ok &= setRawUInt32(data, tlvsize, &offset, item->grpControlFlags); - ok &= item->grpControlList.SetTlv(data, tlvsize, &offset); - - ok &= item->grpPixmap.SetTlv(data, tlvsize, &offset); -#ifdef RSSERIAL_DEBUG - if (!ok) - std::cerr << "RsDistribSerialiser::serialiseGrp() List/Pix NOK" << std::endl; -#endif - - ok &= item->adminKey.SetTlv(data, tlvsize, &offset); -#ifdef RSSERIAL_DEBUG - if (!ok) - std::cerr << "RsDistribSerialiser::serialiseGrp() AdminKey NOK" << std::endl; -#endif - ok &= item->publishKeys.SetTlv(data, tlvsize, &offset); -#ifdef RSSERIAL_DEBUG - if (!ok) - std::cerr << "RsDistribSerialiser::serialiseGrp() PubKey NOK" << std::endl; -#endif - ok &= item->adminSignature.SetTlv(data, tlvsize, &offset); -#ifdef RSSERIAL_DEBUG - if (!ok) - std::cerr << "RsDistribSerialiser::serialiseGrp() AdminSign NOK" << std::endl; -#endif - - if (offset != tlvsize) - { - ok = false; - std::cerr << "RsDistribSerialiser::serialiseGrp() Size Error! " << std::endl; - } - -#ifdef RSSERIAL_DEBUG - if (!ok) - { - std::cerr << "RsDistribSerialiser::serialiseGrp() NOK" << std::endl; - } -#endif - - return ok; -} - - -RsDistribGrp *RsDistribSerialiser::deserialiseGrp(void *data, uint32_t *pktsize) -{ -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDistribSerialiser::deserialiseGrp()" << std::endl; -#endif - /* get the type and size */ - uint32_t rstype = getRsItemId(data); - uint32_t rssize = getRsItemSize(data); - - uint32_t offset = 0; - - - if ((RS_PKT_VERSION_SERVICE != getRsItemVersion(rstype)) || - (SERVICE_TYPE != getRsItemService(rstype)) || - (RS_PKT_SUBTYPE_DISTRIB_GRP != getRsItemSubType(rstype))) - { -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDistribSerialiser::deserialiseGrp() FAIL wrong type" << std::endl; -#endif - return NULL; /* wrong type */ - } - - if (*pktsize < rssize) /* check size */ - { -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDistribSerialiser::deserialiseGrp() FAIL wrong size" << std::endl; -#endif - return NULL; /* not enough data */ - } - - /* set the packet length */ - *pktsize = rssize; - - bool ok = true; - - /* ready to load */ - RsDistribGrp *item = new RsDistribGrp(); - item->clear(); - - /* skip the header */ - offset += 8; - - /* RsDistribGrp */ - ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_GROUPID, item->grpId); - ok &= getRawUInt32(data, rssize, &offset, &(item->timestamp)); - ok &= getRawUInt32(data, rssize, &offset, &(item->grpFlags)); - - ok &= GetTlvWideString(data, rssize, &offset, TLV_TYPE_WSTR_NAME, item->grpName); - ok &= GetTlvWideString(data, rssize, &offset, TLV_TYPE_WSTR_COMMENT, item->grpDesc); - ok &= GetTlvWideString(data, rssize, &offset, TLV_TYPE_WSTR_CATEGORY, item->grpCategory); - - ok &= getRawUInt32(data, rssize, &offset, &(item->grpControlFlags)); - ok &= item->grpControlList.GetTlv(data, rssize, &offset); - - ok &= item->grpPixmap.GetTlv(data, rssize, &offset); - - ok &= item->adminKey.GetTlv(data, rssize, &offset); - ok &= item->publishKeys.GetTlv(data, rssize, &offset); - ok &= item->adminSignature.GetTlv(data, rssize, &offset); - - if (offset != rssize) - { -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDistribSerialiser::deserialiseGrp() FAIL size mismatch" << std::endl; -#endif - /* error */ - delete item; - return NULL; - } - - if (!ok) - { -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDistribSerialiser::deserialiseGrp() NOK" << std::endl; -#endif - delete item; - return NULL; - } - - return item; -} - -/*************************************************************************/ - -uint32_t RsDistribSerialiser::sizeGrpKey(RsDistribGrpKey *item) -{ - uint32_t s = 8; /* header */ - s += GetTlvStringSize(item->grpId); - s += item->key.TlvSize(); - - return s; -} - -/* serialise the data to the buffer */ -bool RsDistribSerialiser::serialiseGrpKey(RsDistribGrpKey *item, void *data, uint32_t *pktsize) -{ -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDistribSerialiser::serialiseGrpKey()" << std::endl; -#endif - /* error */ - uint32_t tlvsize = sizeGrpKey(item); - uint32_t offset = 0; - - if (*pktsize < tlvsize) - { -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDistribSerialiser::serialiseGrpKey() FAIL no space" << std::endl; -#endif - return false; /* not enough space */ - } - - *pktsize = tlvsize; - - bool ok = true; - - ok &= setRsItemHeader(data, tlvsize, item->PacketId(), tlvsize); -#ifdef RSSERIAL_DEBUG - if (!ok) - { - std::cerr << "RsDistribSerialiser::serialiseGrpKey() HEADER FAILED" << std::endl; - } -#endif - - /* skip the header */ - offset += 8; - - /* RsDistribGrp */ - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_GROUPID, item->grpId); -#ifdef RSSERIAL_DEBUG - if (!ok) - { - std::cerr << "RsDistribSerialiser::serialiseGrpKey() GROUPID FAILED" << std::endl; - } -#endif - - ok &= item->key.SetTlv(data, tlvsize, &offset); -#ifdef RSSERIAL_DEBUG - if (!ok) - { - std::cerr << "RsDistribSerialiser::serialiseGrpKey() KEY FAILED" << std::endl; - } -#endif - - if (offset != tlvsize) - { - ok = false; - std::cerr << "RsDistribSerialiser::serialiseGrpKey() Size Error! " << std::endl; - } - -#ifdef RSSERIAL_DEBUG - if (!ok) - { - std::cerr << "RsDistribSerialiser::serialiseGrpKey() NOK" << std::endl; - } -#endif - - return ok; -} - - -RsDistribGrpKey *RsDistribSerialiser::deserialiseGrpKey(void *data, uint32_t *pktsize) -{ -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDistribSerialiser::deserialiseGrpKey()" << std::endl; -#endif - /* get the type and size */ - uint32_t rstype = getRsItemId(data); - uint32_t rssize = getRsItemSize(data); - - uint32_t offset = 0; - - - if ((RS_PKT_VERSION_SERVICE != getRsItemVersion(rstype)) || - (SERVICE_TYPE != getRsItemService(rstype)) || - (RS_PKT_SUBTYPE_DISTRIB_GRP_KEY != getRsItemSubType(rstype))) - { -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDistribSerialiser::deserialiseGrpKey() FAIL wrong type" << std::endl; -#endif - return NULL; /* wrong type */ - } - - if (*pktsize < rssize) /* check size */ - { -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDistribSerialiser::deserialiseGrpKey() FAIL no space" << std::endl; -#endif - return NULL; /* not enough data */ - } - - /* set the packet length */ - *pktsize = rssize; - - bool ok = true; - - /* ready to load */ - RsDistribGrpKey *item = new RsDistribGrpKey(); - item->clear(); - - /* skip the header */ - offset += 8; - - /* RsDistribGrp */ - ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_GROUPID, item->grpId); - ok &= item->key.GetTlv(data, rssize, &offset); - - if (offset != rssize) - { -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDistribSerialiser::deserialiseGrpKey() FAIL size mismatch" << std::endl; -#endif - /* error */ - delete item; - return NULL; - } - - if (!ok) - { -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDistribSerialiser::deserialiseGrpKey() FAIL not Okay" << std::endl; -#endif - delete item; - return NULL; - } - - return item; -} - -/*************************************************************************/ - -uint32_t RsDistribSerialiser::sizeSignedMsg(RsDistribSignedMsg *item) -{ - uint32_t s = 8; /* header */ - /* RsDistribSignedMsg stuff */ - s += GetTlvStringSize(item->grpId); - s += GetTlvStringSize(item->msgId); - s += 4; /* flags */ - s += 4; /* timestamp */ - s += item->packet.TlvSize(); - s += item->publishSignature.TlvSize(); - s += item->personalSignature.TlvSize(); - - return s; -} - -/* serialise the data to the buffer */ -bool RsDistribSerialiser::serialiseSignedMsg(RsDistribSignedMsg *item, void *data, uint32_t *pktsize) -{ -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDistribSerialiser::serialiseSignedMsg()" << std::endl; -#endif - uint32_t tlvsize = sizeSignedMsg(item); - uint32_t offset = 0; - - if (*pktsize < tlvsize) - { -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDistribSerialiser::serialiseSignedMsg() FAIL no space" << std::endl; -#endif - return false; /* not enough space */ - } - - *pktsize = tlvsize; - - bool ok = true; - - ok &= setRsItemHeader(data, tlvsize, item->PacketId(), tlvsize); - - /* skip the header */ - offset += 8; - - /* RsDistribSignedMsg */ - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_GROUPID, item->grpId); - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_MSGID, item->msgId); - - ok &= setRawUInt32(data, tlvsize, &offset, item->flags); - ok &= setRawUInt32(data, tlvsize, &offset, item->timestamp); - - ok &= item->packet.SetTlv(data, tlvsize, &offset); - - ok &= item->publishSignature.SetTlv(data, tlvsize, &offset); - ok &= item->personalSignature.SetTlv(data, tlvsize, &offset); - - if (offset != tlvsize) - { -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDistribSerialiser::serialiseSignedMsg() FAIL Size Error! " << std::endl; -#endif - ok = false; - } - -#ifdef RSSERIAL_DEBUG - if (!ok) - { - std::cerr << "RsDistribSerialiser::serialiseSignedMsg() NOK" << std::endl; - } -#endif - - return ok; -} - - -RsDistribSignedMsg *RsDistribSerialiser::deserialiseSignedMsg(void *data, uint32_t *pktsize) -{ -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDistribSerialiser::deserialiseSignedMsg()" << std::endl; -#endif - /* get the type and size */ - uint32_t rstype = getRsItemId(data); - uint32_t rssize = getRsItemSize(data); - - uint32_t offset = 0; - - - if ((RS_PKT_VERSION_SERVICE != getRsItemVersion(rstype)) || - (SERVICE_TYPE != getRsItemService(rstype)) || - (RS_PKT_SUBTYPE_DISTRIB_SIGNED_MSG != getRsItemSubType(rstype))) - { -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDistribSerialiser::deserialiseSignedMsg() Wrong Type" << std::endl; -#endif - return NULL; /* wrong type */ - } - - if (*pktsize < rssize) /* check size */ - { -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDistribSerialiser::deserialiseSignedMsg() Wrong Size" << std::endl; -#endif - return NULL; /* not enough data */ - } - - /* set the packet length */ - *pktsize = rssize; - - bool ok = true; - - /* ready to load */ - RsDistribSignedMsg *item = new RsDistribSignedMsg(); - item->clear(); - - /* skip the header */ - offset += 8; - - /* RsDistribGrp */ - ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_GROUPID, item->grpId); - ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_MSGID, item->msgId); - ok &= getRawUInt32(data, rssize, &offset, &(item->flags)); - ok &= getRawUInt32(data, rssize, &offset, &(item->timestamp)); - - ok &= item->packet.GetTlv(data, rssize, &offset); - - ok &= item->publishSignature.GetTlv(data, rssize, &offset); - ok &= item->personalSignature.GetTlv(data, rssize, &offset); - - if (offset != rssize) - { -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDistribSerialiser::deserialiseSignedMsg() size mismatch" << std::endl; -#endif - /* error */ - delete item; - return NULL; - } - - if (!ok) - { -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDistribSerialiser::deserialiseSignedMsg() NOK" << std::endl; -#endif - delete item; - return NULL; - } - - return item; -} - - - -/*********************** save data *******************************/ - - -uint32_t RsDistribSerialiser::sizeConfigData(RsDistribConfigData *item) -{ - uint32_t s = 8; /* header */ - - /* RsDistribSignedMsg stuff */ - s += item->service_data.TlvSize(); - - return s; -} - -/* serialise the data to the buffer */ -bool RsDistribSerialiser::serialiseConfigData(RsDistribConfigData *item, void *data, uint32_t *pktsize) -{ -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDistribSerialiser::serialiseConfigData()" << std::endl; -#endif - uint32_t tlvsize = sizeConfigData(item); - uint32_t offset = 0; - - if (*pktsize < tlvsize) - { -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDistribSerialiser::serialiseConfigData() FAIL no space" << std::endl; -#endif - return false; /* not enough space */ - } - - *pktsize = tlvsize; - - bool ok = true; - - ok &= setRsItemHeader(data, tlvsize, item->PacketId(), tlvsize); - - /* skip the header */ - offset += 8; - - /* RsDistribSignedMsg */ - ok &= item->service_data.SetTlv(data, tlvsize, &offset); - - if (offset != tlvsize) - { -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDistribSerialiser::serialiseConfigData() FAIL Size Error! " << std::endl; -#endif - ok = false; - } - -#ifdef RSSERIAL_DEBUG - if (!ok) - { - std::cerr << "RsDistribSerialiser::serialiseConfigData() NOK" << std::endl; - } -#endif - - return ok; -} - - -RsDistribConfigData *RsDistribSerialiser::deserialiseConfigData(void *data, uint32_t *pktsize) -{ -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDistribSerialiser::deserialiseConfigData()" << std::endl; -#endif - /* get the type and size */ - uint32_t rstype = getRsItemId(data); - uint32_t rssize = getRsItemSize(data); - - uint32_t offset = 0; - - - if ((RS_PKT_VERSION_SERVICE != getRsItemVersion(rstype)) || - (SERVICE_TYPE != getRsItemService(rstype)) || - (RS_PKT_SUBTYPE_DISTRIB_CONFIG_DATA != getRsItemSubType(rstype))) - { -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDistribSerialiser::deserialiseSignedMsg() Wrong Type" << std::endl; -#endif - return NULL; /* wrong type */ - } - - if (*pktsize < rssize) /* check size */ - { -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDistribSerialiser::deserialiseSignedMsg() Wrong Size" << std::endl; -#endif - return NULL; /* not enough data */ - } - - /* set the packet length */ - *pktsize = rssize; - - bool ok = true; - - /* ready to load */ - RsDistribConfigData *item = new RsDistribConfigData(); - item->clear(); - - /* skip the header */ - offset += 8; - - /* RsDistribGrp */ - ok &= item->service_data.GetTlv(data, rssize, &offset); - - if (offset != rssize) - { -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDistribSerialiser::deserialiseSignedMsg() size mismatch" << std::endl; -#endif - /* error */ - delete item; - return NULL; - } - - if (!ok) - { -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDistribSerialiser::deserialiseSignedMsg() NOK" << std::endl; -#endif - delete item; - return NULL; - } - - return item; -} - - - - - -uint32_t RsDistribSerialiser::size(RsItem *i) -{ - RsDistribGrp *dg; - RsDistribGrpKey *dgk; - RsDistribSignedMsg *dsm; - RsDistribConfigData *dsd; - - /* in order of frequency */ - if (NULL != (dsm = dynamic_cast(i))) - { - return sizeSignedMsg(dsm); - } - else if (NULL != (dg = dynamic_cast(i))) - { - return sizeGrp(dg); - } - else if (NULL != (dgk = dynamic_cast(i))) - { - return sizeGrpKey(dgk); - } - else if(NULL != (dsd = dynamic_cast(i))) - { - return sizeConfigData(dsd); - } - - return 0; -} - -bool RsDistribSerialiser::serialise(RsItem *i, void *data, uint32_t *pktsize) -{ -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDistribSerialiser::serialise()" << std::endl; -#endif - RsDistribGrp *dg; - RsDistribGrpKey *dgk; - RsDistribSignedMsg *dsm; - RsDistribConfigData *dsd; - - if (NULL != (dsm = dynamic_cast(i))) - { - return serialiseSignedMsg(dsm, data, pktsize); - } - else if (NULL != (dg = dynamic_cast(i))) - { - return serialiseGrp(dg, data, pktsize); - } - else if (NULL != (dgk = dynamic_cast(i))) - { - return serialiseGrpKey(dgk, data, pktsize); - } - else if(NULL != (dsd = dynamic_cast(i))) - { - return serialiseConfigData(dsd, data, pktsize); - } - return false; -} - -RsItem *RsDistribSerialiser::deserialise(void *data, uint32_t *pktsize) -{ -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDistribSerialiser::deserialise()" << std::endl; -#endif - /* get the type and size */ - uint32_t rstype = getRsItemId(data); - - if ((RS_PKT_VERSION_SERVICE != getRsItemVersion(rstype)) || - (SERVICE_TYPE != getRsItemService(rstype))) - { - return NULL; /* wrong type */ - } - - switch(getRsItemSubType(rstype)) - { - case RS_PKT_SUBTYPE_DISTRIB_GRP: - return deserialiseGrp(data, pktsize); - break; - case RS_PKT_SUBTYPE_DISTRIB_GRP_KEY: - return deserialiseGrpKey(data, pktsize); - break; - case RS_PKT_SUBTYPE_DISTRIB_SIGNED_MSG: - return deserialiseSignedMsg(data, pktsize); - break; - case RS_PKT_SUBTYPE_DISTRIB_CONFIG_DATA: - return deserialiseConfigData(data, pktsize); - break; - default: - return NULL; - break; - } - return NULL; -} - -/*************************************************************************/ -/*************************************************************************/ - diff --git a/libretroshare/src/serialiser/rsdistribitems.h b/libretroshare/src/serialiser/rsdistribitems.h deleted file mode 100644 index 33681de10..000000000 --- a/libretroshare/src/serialiser/rsdistribitems.h +++ /dev/null @@ -1,260 +0,0 @@ -#ifndef RS_DISTRIB_ITEMS_H -#define RS_DISTRIB_ITEMS_H - -/* - * libretroshare/src/serialiser: rsdistribitems.h - * - * RetroShare Serialiser. - * - * Copyright 2007-2008 by Robert Fernie. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License Version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 - * USA. - * - * Please report all bugs and problems to "retroshare@lunamutt.com". - * - */ - -#include - -#include "serialiser/rsserviceids.h" -#include "serialiser/rsserial.h" -#include "serialiser/rstlvbase.h" -#include "serialiser/rstlvtypes.h" -#include "serialiser/rstlvkeys.h" - -const uint8_t RS_PKT_SUBTYPE_DISTRIB_GRP = 0x01; -const uint8_t RS_PKT_SUBTYPE_DISTRIB_GRP_KEY = 0x02; -const uint8_t RS_PKT_SUBTYPE_DISTRIB_SIGNED_MSG = 0x03; -const uint8_t RS_PKT_SUBTYPE_DISTRIB_CONFIG_DATA = 0x04; - -/**************************************************************************/ - -/*! - * This should be subclassed by p3distrib subclass's to store their data - * save data - */ -class RsDistribChildConfig: public RsItem -{ -public: - RsDistribChildConfig(uint16_t servtype, uint8_t subtype) - : RsItem(RS_PKT_VERSION_SERVICE, servtype, subtype),save_type(0) {return;} - - virtual ~RsDistribChildConfig() { return; } - - virtual void clear(); - virtual std::ostream& print(std::ostream &out, uint16_t indent = 0); - - /// use this to id the type of data you want to save - uint32_t save_type; -}; - - -/*! - * This should be used to save the service data such as settings - */ -class RsDistribConfigData: public RsItem -{ -public: - RsDistribConfigData() - : RsItem(RS_PKT_VERSION_SERVICE, RS_SERVICE_TYPE_DISTRIB, RS_PKT_SUBTYPE_DISTRIB_CONFIG_DATA), service_data(TLV_TYPE_BIN_SERIALISE) - {return;} - - virtual ~RsDistribConfigData() { return; } - - virtual void clear(); - - virtual std::ostream& print(std::ostream &out, uint16_t indent = 0); - - // this is where a derived distrib service saves its data - RsTlvBinaryData service_data; - -}; - - -/*! - * This is used by p3Distrib for storing messages - * of derived services, attributes are given for writing - * personal signatures (confirms user) and publish signatures (to - * confirm consistency source) - */ -class RsDistribMsg: public RsItem -{ - public: - RsDistribMsg(uint16_t servtype, uint8_t subtype) - :RsItem(RS_PKT_VERSION_SERVICE, servtype, subtype) { return; } - -virtual ~RsDistribMsg() { return; } - -virtual void clear(); -virtual std::ostream& print(std::ostream &out, uint16_t indent = 0); - - std::string grpId; /* Grp Id */ - - /// Parent Msg Id, msgs above a thread - std::string parentId; - - /// Thread Msg Id: useful identifyingfor responses - ///to a forum msg and replies in general - std::string threadId; - uint32_t timestamp; - - /* Not Serialised */ - - std::string msgId; /* Msg Id */ - time_t childTS; /* timestamp of most recent child */ - - /// used to confirm the message is from a group author, or someone with valid publish key - RsTlvKeySignature publishSignature; - - /// used to confirm message is from a particular peer - RsTlvKeySignature personalSignature; -}; - - -/*! - * This is used as a storage container for messages from a service - * via the binary data container (packet) - */ -class RsDistribSignedMsg: public RsItem -{ - public: - RsDistribSignedMsg() - :RsItem(RS_PKT_VERSION_SERVICE, RS_SERVICE_TYPE_DISTRIB, RS_PKT_SUBTYPE_DISTRIB_SIGNED_MSG), - packet(TLV_TYPE_BIN_SERIALISE) - { return; } - -virtual ~RsDistribSignedMsg() { return; } - -virtual void clear(); -virtual std::ostream& print(std::ostream &out, uint16_t indent = 0); - - std::string grpId; - - /// should be taken publishSignature - std::string msgId; - uint32_t flags; - uint32_t timestamp; - - /// in order to tranfer messages from service level to distrib level - RsTlvBinaryData packet; - RsTlvKeySignature publishSignature; - RsTlvKeySignature personalSignature; -}; - - -class RsDistribGrp: public RsItem -{ - public: -// RsDistribGrp(uint16_t servtype, uint8_t subtype) -// :RsItem(RS_PKT_VERSION_SERVICE, servtype, subtype) { return; } - - RsDistribGrp() - :RsItem(RS_PKT_VERSION_SERVICE, RS_SERVICE_TYPE_DISTRIB, RS_PKT_SUBTYPE_DISTRIB_GRP) - { return; } - -virtual ~RsDistribGrp() { return; } - -virtual void clear(); -virtual std::ostream& print(std::ostream &out, uint16_t indent = 0); - - std::string grpId; /* Grp Id */ - uint32_t timestamp; - uint32_t grpFlags; - std::wstring grpName; - std::wstring grpDesc; - std::wstring grpCategory; - - RsTlvImage grpPixmap; - - uint32_t grpControlFlags; - RsTlvPeerIdSet grpControlList; - - RsTlvSecurityKey adminKey; - RsTlvSecurityKeySet publishKeys; - - RsTlvKeySignature adminSignature; -}; - - -class RsDistribGrpKey: public RsItem -{ - public: - - RsDistribGrpKey(uint16_t service_type) - :RsItem(RS_PKT_VERSION_SERVICE, service_type, RS_PKT_SUBTYPE_DISTRIB_GRP_KEY) - { return; } - - RsDistribGrpKey() - :RsItem(RS_PKT_VERSION_SERVICE, RS_SERVICE_TYPE_DISTRIB, RS_PKT_SUBTYPE_DISTRIB_GRP_KEY) - { return; } - -virtual ~RsDistribGrpKey() { return; } - -virtual void clear(); -virtual std::ostream& print(std::ostream &out, uint16_t indent = 0); - - std::string grpId; /* Grp Id */ - RsTlvSecurityKey key; -}; - - -class RsDistribSerialiser: public RsSerialType -{ - public: - - // optional to allow use in p3service/sockets - RsDistribSerialiser(uint16_t service_type = RS_SERVICE_TYPE_DISTRIB) - : RsSerialType(RS_PKT_VERSION_SERVICE, service_type), SERVICE_TYPE(service_type) - { return; } - -virtual ~RsDistribSerialiser() - { return; } - -virtual uint32_t size(RsItem *); -virtual bool serialise (RsItem *item, void *data, uint32_t *size); -virtual RsItem * deserialise(void *data, uint32_t *size); - - private: - - /* For RS_PKT_SUBTYPE_DISTRIB_GRP */ -virtual uint32_t sizeGrp(RsDistribGrp *); -virtual bool serialiseGrp (RsDistribGrp *item, void *data, uint32_t *size); -virtual RsDistribGrp *deserialiseGrp(void *data, uint32_t *size); - - /* For RS_PKT_SUBTYPE_DISTRIB_GRP_KEY */ -virtual uint32_t sizeGrpKey(RsDistribGrpKey *); -virtual bool serialiseGrpKey (RsDistribGrpKey *item, void *data, uint32_t *size); -virtual RsDistribGrpKey *deserialiseGrpKey(void *data, uint32_t *size); - - /* For RS_PKT_SUBTYPE_DISTRIB_SIGNED_MSG */ -virtual uint32_t sizeSignedMsg(RsDistribSignedMsg *); -virtual bool serialiseSignedMsg (RsDistribSignedMsg *item, void *data, uint32_t *size); -virtual RsDistribSignedMsg *deserialiseSignedMsg(void *data, uint32_t *size); - - /* For RS_PKT_SUBTYPE_DISTRIB_SAVE_DATA */ -virtual uint32_t sizeConfigData(RsDistribConfigData *); -virtual bool serialiseConfigData(RsDistribConfigData *item, void *data, uint32_t *size); -virtual RsDistribConfigData *deserialiseConfigData(void* data, uint32_t *size); - - -const uint16_t SERVICE_TYPE; - -}; - -/**************************************************************************/ - -#endif /* RS_FORUM_ITEMS_H */ - - diff --git a/libretroshare/src/serialiser/rsforumitems.cc b/libretroshare/src/serialiser/rsforumitems.cc deleted file mode 100644 index 91c9ac47d..000000000 --- a/libretroshare/src/serialiser/rsforumitems.cc +++ /dev/null @@ -1,493 +0,0 @@ - -/* - * libretroshare/src/serialiser: rsforumitems.cc - * - * RetroShare Serialiser. - * - * Copyright 2007-2008 by Robert Fernie. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License Version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 - * USA. - * - * Please report all bugs and problems to "retroshare@lunamutt.com". - * - */ - -#include "serialiser/rsforumitems.h" - -#include "serialiser/rsbaseserial.h" -#include "serialiser/rstlvbase.h" - -// #define RSSERIAL_DEBUG 1 -#include - -/*************************************************************************/ - -void RsForumMsg::clear() -{ - RsDistribMsg::clear(); - - srcId.clear(); - title.clear(); - msg.clear(); -} - -std::ostream &RsForumMsg::print(std::ostream &out, uint16_t indent) -{ - printRsItemBase(out, "RsForumMsg", indent); - uint16_t int_Indent = indent + 2; - - RsDistribMsg::print(out, int_Indent); - - printIndent(out, int_Indent); - out << "srcId: " << srcId << std::endl; - - printIndent(out, int_Indent); - - std::string cnv_title(title.begin(), title.end()); - out << "title: " << cnv_title << std::endl; - - printIndent(out, int_Indent); - - std::string cnv_msg(msg.begin(), msg.end()); - out << "msg: " << cnv_msg << std::endl; - - printRsItemEnd(out, "RsForumMsg", indent); - return out; -} - -void RsForumReadStatus::clear() -{ - - RsDistribChildConfig::clear(); - - forumId.clear(); - msgReadStatus.clear(); - - return; - -} - -std::ostream& RsForumReadStatus::print(std::ostream &out, uint16_t indent = 0) -{ - - printRsItemBase(out, "RsForumMsg", indent); - uint16_t int_Indent = indent + 2; - - RsDistribChildConfig::print(out, int_Indent); - - printIndent(out, int_Indent); - out << "ForumId: " << forumId << std::endl; - - printIndent(out, int_Indent); - out << "ForumId: " << forumId << std::endl; - - std::map::iterator mit = msgReadStatus.begin(); - - for(; mit != msgReadStatus.end(); mit++) - { - - printIndent(out, int_Indent); - out << "msgId : " << mit->first << std::endl; - - printIndent(out, int_Indent); - out << " status : " << mit->second << std::endl; - - } - - printRsItemEnd(out, "RsForumMsg", indent); - return out; -} - -/*************************************************************************/ -/*************************************************************************/ - -uint32_t RsForumSerialiser::sizeMsg(RsForumMsg *item) -{ - uint32_t s = 8; /* header */ - /* RsDistribMsg stuff */ - s += GetTlvStringSize(item->grpId); - s += GetTlvStringSize(item->parentId); - s += GetTlvStringSize(item->threadId); - s += 4; /* timestamp */ - - /* RsForumMsg stuff */ - s += GetTlvStringSize(item->srcId); - s += GetTlvWideStringSize(item->title); - s += GetTlvWideStringSize(item->msg); - - return s; -} - - -/* serialise the data to the buffer */ -bool RsForumSerialiser::serialiseMsg(RsForumMsg *item, void *data, uint32_t *pktsize) -{ - uint32_t tlvsize = sizeMsg(item); - uint32_t offset = 0; - - if (*pktsize < tlvsize) - return false; /* not enough space */ - - *pktsize = tlvsize; - - bool ok = true; - - ok &= setRsItemHeader(data, tlvsize, item->PacketId(), tlvsize); -#ifdef RSSERIAL_DEBUG - std::cerr << "RsForumSerialiser::serialiseMsg() Header: " << ok << std::endl; - std::cerr << "RsForumSerialiser::serialiseMsg() Size: " << tlvsize << std::endl; -#endif - - /* skip the header */ - offset += 8; - - /* RsDistribMsg first */ - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_GROUPID, item->grpId); -#ifdef RSSERIAL_DEBUG - std::cerr << "RsForumSerialiser::serialiseMsg() grpId: " << ok << std::endl; -#endif - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_PARENTID, item->parentId); -#ifdef RSSERIAL_DEBUG - std::cerr << "RsForumSerialiser::serialiseMsg() parentId: " << ok << std::endl; -#endif - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_THREADID, item->threadId); -#ifdef RSSERIAL_DEBUG - std::cerr << "RsForumSerialiser::serialiseMsg() threadId: " << ok << std::endl; -#endif - - ok &= setRawUInt32(data, tlvsize, &offset, item->timestamp); -#ifdef RSSERIAL_DEBUG - std::cerr << "RsForumSerialiser::serialiseMsg() timestamp: " << ok << std::endl; -#endif - - /* RsForumMsg */ - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_PEERID, item->srcId); -#ifdef RSSERIAL_DEBUG - std::cerr << "RsForumSerialiser::serialiseMsg() srcId: " << ok << std::endl; -#endif - - ok &= SetTlvWideString(data, tlvsize, &offset, TLV_TYPE_WSTR_TITLE, item->title); -#ifdef RSSERIAL_DEBUG - std::cerr << "RsForumSerialiser::serialiseMsg() Title: " << ok << std::endl; -#endif - ok &= SetTlvWideString(data, tlvsize, &offset, TLV_TYPE_WSTR_MSG, item->msg); -#ifdef RSSERIAL_DEBUG - std::cerr << "RsForumSerialiser::serialiseMsg() Msg: " << ok << std::endl; -#endif - - if (offset != tlvsize) - { - ok = false; - std::cerr << "RsForumSerialiser::serialiseMsg() Size Error! " << std::endl; - } - - return ok; -} - - - -RsForumMsg *RsForumSerialiser::deserialiseMsg(void *data, uint32_t *pktsize) -{ - /* get the type and size */ - uint32_t rstype = getRsItemId(data); - uint32_t rssize = getRsItemSize(data); - - uint32_t offset = 0; - - - if ((RS_PKT_VERSION_SERVICE != getRsItemVersion(rstype)) || - (RS_SERVICE_TYPE_FORUM != getRsItemService(rstype)) || - (RS_PKT_SUBTYPE_FORUM_MSG != getRsItemSubType(rstype))) - { - return NULL; /* wrong type */ - } - - if (*pktsize < rssize) /* check size */ - return NULL; /* not enough data */ - - /* set the packet length */ - *pktsize = rssize; - - bool ok = true; - - /* ready to load */ - RsForumMsg *item = new RsForumMsg(); - item->clear(); - - /* skip the header */ - offset += 8; - - /* RsDistribMsg first */ - ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_GROUPID, item->grpId); - ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_PARENTID, item->parentId); - ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_THREADID, item->threadId); - ok &= getRawUInt32(data, rssize, &offset, &(item->timestamp)); - - /* RsForumMsg */ - ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_PEERID, item->srcId); - ok &= GetTlvWideString(data, rssize, &offset, TLV_TYPE_WSTR_TITLE, item->title); - ok &= GetTlvWideString(data, rssize, &offset, TLV_TYPE_WSTR_MSG, item->msg); - - if (offset != rssize) - { - /* error */ - delete item; - return NULL; - } - - if (!ok) - { - delete item; - return NULL; - } - - return item; -} - - -/*************************************************************************/ -/*************************************************************************/ - -uint32_t RsForumSerialiser::sizeReadStatus(RsForumReadStatus *item) -{ - uint32_t s = 8; /* header */ - /* RsDistribChildConfig stuff */ - - s += 4; /* save_type */ - - /* RsForumReadStatus stuff */ - - s += GetTlvStringSize(item->forumId); - - std::map::iterator mit = item->msgReadStatus.begin(); - - for(; mit != item->msgReadStatus.end(); mit++) - { - s += GetTlvStringSize(mit->first); /* key */ - s += 4; /* value */ - } - - return s; -} - -/* serialise the data to the buffer */ -bool RsForumSerialiser::serialiseReadStatus(RsForumReadStatus *item, void *data, uint32_t *pktsize) -{ - uint32_t tlvsize = sizeReadStatus(item); - uint32_t offset = 0; - - if (*pktsize < tlvsize) - return false; /* not enough space */ - - *pktsize = tlvsize; - - bool ok = true; - - ok &= setRsItemHeader(data, tlvsize, item->PacketId(), tlvsize); - -#ifdef RSSERIAL_DEBUG - std::cerr << "RsForumSerialiser::serialiseReadStatus() Header: " << ok << std::endl; - std::cerr << "RsForumSerialiser::serialiseReadStatus() Size: " << tlvsize << std::endl; -#endif - - /* skip the header */ - offset += 8; - - /* RsDistribMsg first */ - - ok &= setRawUInt32(data, tlvsize, &offset, item->save_type); -#ifdef RSSERIAL_DEBUG - std::cerr << "RsForumSerialiser::serialiseReadStatus() save_type: " << ok << std::endl; -#endif - - - - /* RsForumMsg */ - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_GROUPID, item->forumId); -#ifdef RSSERIAL_DEBUG - std::cerr << "RsForumSerialiser::serialiseReadStatus() forumId: " << ok << std::endl; -#endif - - std::map::iterator mit = item->msgReadStatus.begin(); - - for(; mit != item->msgReadStatus.end(); mit++) - { - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_MSGID, mit->first); /* key */ - ok &= setRawUInt32(data, tlvsize, &offset, mit->second); /* value */ - } - -#ifdef RSSERIAL_DEBUG - std::cerr << "RsForumSerialiser::serialiseReadStatus() msgReadStatus: " << ok << std::endl; -#endif - - if (offset != tlvsize) - { - ok = false; -#ifdef RSSERIAL_DEBUG - std::cerr << "RsForumSerialiser::serialiseReadStatus() Size Error! " << std::endl; -#endif - } - - return ok; -} - - - -RsForumReadStatus *RsForumSerialiser::deserialiseReadStatus(void *data, uint32_t *pktsize) -{ - /* get the type and size */ - uint32_t rstype = getRsItemId(data); - uint32_t rssize = getRsItemSize(data); - - uint32_t offset = 0; - - - if ((RS_PKT_VERSION_SERVICE != getRsItemVersion(rstype)) || - (RS_SERVICE_TYPE_FORUM != getRsItemService(rstype)) || - (RS_PKT_SUBTYPE_FORUM_READ_STATUS != getRsItemSubType(rstype))) - { - return NULL; /* wrong type */ - } - - if (*pktsize < rssize) /* check size */ - return NULL; /* not enough data */ - - /* set the packet length */ - *pktsize = rssize; - - bool ok = true; - - /* ready to load */ - RsForumReadStatus *item = new RsForumReadStatus(); - item->clear(); - - /* skip the header */ - offset += 8; - - /* RsDistribMsg first */ - ok &= getRawUInt32(data, rssize, &offset, &(item->save_type)); - - /* RsForumMsg */ - ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_GROUPID, item->forumId); - - std::string key; - uint32_t value; - - while(offset != rssize) - { - key.clear(); - value = 0; - - ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_MSGID, key); /* key */ - - /* incomplete key value pair? then fail*/ - if(offset == rssize) - { - delete item; - return NULL; - } - - ok &= getRawUInt32(data, rssize, &offset, &value); /* value */ - - item->msgReadStatus.insert(std::pair(key, value)); - } - - if (!ok) - { - delete item; - return NULL; - } - - return item; -} - -/************************************************************/ - -uint32_t RsForumSerialiser::size(RsItem *item) -{ - RsForumMsg* dfm; - RsForumReadStatus* drs; - - if( NULL != ( dfm = dynamic_cast(item))) - { - return sizeMsg(dfm); - } - else if(NULL != (drs = dynamic_cast(item))) - { - return sizeReadStatus(drs); - } - - return false; -} - - -bool RsForumSerialiser::serialise(RsItem *item, void *data, uint32_t *pktsize) -{ - -#ifdef RSSERIAL_DEBUG - std::cerr << "RsForumSerialiser::serialise()" << std::endl; -#endif - - RsForumMsg* dfm; - RsForumReadStatus* drs; - - if( NULL != ( dfm = dynamic_cast(item))) - { - return serialiseMsg(dfm, data, pktsize); - } - else if(NULL != (drs = dynamic_cast(item))) - { - return serialiseReadStatus(drs, data, pktsize); - } - - return NULL; -} - -RsItem *RsForumSerialiser::deserialise(void *data, uint32_t *pktsize) -{ - -#ifdef RSSERIAL_DEBUG - std::cerr << "RsForumSerialiser::deserialise()" << std::endl; -#endif - - /* get the type and size */ - uint32_t rstype = getRsItemId(data); - - if ((RS_PKT_VERSION_SERVICE != getRsItemVersion(rstype)) || - (RS_SERVICE_TYPE_FORUM != getRsItemService(rstype))) - { - return NULL; /* wrong type */ - } - - switch(getRsItemSubType(rstype)) - { - case RS_PKT_SUBTYPE_FORUM_MSG: - return deserialiseMsg(data, pktsize); - break; - case RS_PKT_SUBTYPE_FORUM_READ_STATUS: - return deserialiseReadStatus(data, pktsize); - break; - default: - return NULL; - break; - } - - return NULL; -} - - - -/*************************************************************************/ - diff --git a/libretroshare/src/serialiser/rsforumitems.h b/libretroshare/src/serialiser/rsforumitems.h deleted file mode 100644 index f83148f78..000000000 --- a/libretroshare/src/serialiser/rsforumitems.h +++ /dev/null @@ -1,124 +0,0 @@ -#ifndef RS_FORUM_ITEMS_H -#define RS_FORUM_ITEMS_H - -/* - * libretroshare/src/serialiser: rsforumitems.h - * - * RetroShare Serialiser. - * - * Copyright 2007-2008 by Robert Fernie. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License Version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 - * USA. - * - * Please report all bugs and problems to "retroshare@lunamutt.com". - * - */ - -#include - -#include "serialiser/rsserviceids.h" -#include "serialiser/rsserial.h" -#include "serialiser/rstlvtypes.h" -#include "serialiser/rstlvkeys.h" - -#include "serialiser/rsdistribitems.h" - -const uint8_t RS_PKT_SUBTYPE_FORUM_GRP = 0x01; -const uint8_t RS_PKT_SUBTYPE_FORUM_MSG = 0x02; -const uint8_t RS_PKT_SUBTYPE_FORUM_READ_STATUS = 0x03; - -/**************************************************************************/ - -class RsForumMsg: public RsDistribMsg -{ - public: - RsForumMsg() - :RsDistribMsg(RS_SERVICE_TYPE_FORUM, RS_PKT_SUBTYPE_FORUM_MSG) { return; } -virtual ~RsForumMsg() { return; } - -virtual void clear(); -virtual std::ostream& print(std::ostream &out, uint16_t indent = 0); - - /* - * RsDistribMsg has: - * grpId, parentId, threadId & timestamp. - */ - - std::string srcId; - - std::wstring title; - std::wstring msg; - -}; - -/*! - * This is used to keep track of whether a message has been read - * by client - */ -class RsForumReadStatus : public RsDistribChildConfig -{ -public: - RsForumReadStatus() - : RsDistribChildConfig(RS_SERVICE_TYPE_FORUM, RS_PKT_SUBTYPE_FORUM_READ_STATUS) - { return; } - - virtual ~RsForumReadStatus() {return; } - - virtual void clear(); - virtual std::ostream& print(std::ostream &out, uint16_t indent); - - std::string forumId; - - /// a map which contains the read for messages within a forum - std::map msgReadStatus; - -}; - -class RsForumSerialiser: public RsSerialType -{ - public: - RsForumSerialiser() - :RsSerialType(RS_PKT_VERSION_SERVICE, RS_SERVICE_TYPE_FORUM) - { return; } -virtual ~RsForumSerialiser() - { return; } - -virtual uint32_t size(RsItem *); -virtual bool serialise (RsItem *item, void *data, uint32_t *size); -virtual RsItem * deserialise(void *data, uint32_t *size); - - private: - - /* For RS_PKT_SUBTYPE_FORUM_GRP */ -//virtual uint32_t sizeGrp(RsForumGrp *); -//virtual bool serialiseGrp (RsForumGrp *item, void *data, uint32_t *size); -//virtual RsForumGrp *deserialiseGrp(void *data, uint32_t *size); - - /* For RS_PKT_SUBTYPE_FORUM_MSG */ -virtual uint32_t sizeMsg(RsForumMsg *); -virtual bool serialiseMsg(RsForumMsg *item, void *data, uint32_t *size); -virtual RsForumMsg *deserialiseMsg(void *data, uint32_t *size); - -virtual uint32_t sizeReadStatus(RsForumReadStatus* ); -virtual bool serialiseReadStatus(RsForumReadStatus* item, void* data, uint32_t *size); -virtual RsForumReadStatus *deserialiseReadStatus(void* data, uint32_t *size); - -}; - -/**************************************************************************/ - -#endif /* RS_FORUM_ITEMS_H */ - - diff --git a/libretroshare/src/serialiser/rsgameitems.cc b/libretroshare/src/serialiser/rsgameitems.cc deleted file mode 100644 index 87fe6d0d5..000000000 --- a/libretroshare/src/serialiser/rsgameitems.cc +++ /dev/null @@ -1,212 +0,0 @@ -/* - * libretroshare/src/serialiser: rsgameitems.cc - * - * RetroShare Serialiser. - * - * Copyright 2007-2008 by Robert Fernie. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License Version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 - * USA. - * - * Please report all bugs and problems to "retroshare@lunamutt.com". - * - */ - -#include "serialiser/rsbaseserial.h" -#include "serialiser/rsgameitems.h" -#include "serialiser/rstlvbase.h" - -/*** -#define RSSERIAL_DEBUG 1 -***/ - -#include - -/*************************************************************************/ - -RsGameItem::~RsGameItem() -{ - return; -} - -void RsGameItem::clear() -{ - serviceId = 0; - numPlayers = 0; - msg = 0; - - gameId.clear(); - gameComment.clear(); - players.TlvClear(); -} - -std::ostream &RsGameItem::print(std::ostream &out, uint16_t indent) -{ - printRsItemBase(out, "RsGameItem", indent); - uint16_t int_Indent = indent + 2; - printIndent(out, int_Indent); - out << "serviceId: " << serviceId << std::endl; - printIndent(out, int_Indent); - out << "numPlayers: " << numPlayers << std::endl; - printIndent(out, int_Indent); - out << "msg: " << msg << std::endl; - - printIndent(out, int_Indent); - out << "gameId: " << gameId << std::endl; - - printIndent(out, int_Indent); - std::string cnv_comment(gameComment.begin(), gameComment.end()); - out << "msg: " << cnv_comment << std::endl; - - printIndent(out, int_Indent); - out << "Players Ids: " << std::endl; - players.print(out, int_Indent); - - printRsItemEnd(out, "RsGameItem", indent); - return out; -} - - -uint32_t RsGameSerialiser::sizeItem(RsGameItem *item) -{ - uint32_t s = 8; /* header */ - s += 4; /* serviceId */ - s += 4; /* numPlayers */ - s += 4; /* msg */ - s += GetTlvStringSize(item->gameId); - s += GetTlvWideStringSize(item->gameComment); - s += item->players.TlvSize(); - - return s; -} - -/* serialise the data to the buffer */ -bool RsGameSerialiser::serialiseItem(RsGameItem *item, void *data, uint32_t *pktsize) -{ - uint32_t tlvsize = sizeItem(item); - uint32_t offset = 0; - - if (*pktsize < tlvsize) - return false; /* not enough space */ - - *pktsize = tlvsize; - - bool ok = true; - - ok &= setRsItemHeader(data, tlvsize, item->PacketId(), tlvsize); - -#ifdef RSSERIAL_DEBUG - std::cerr << "RsGameSerialiser::serialiseItem() Header: " << ok << std::endl; - std::cerr << "RsGameSerialiser::serialiseItem() Size: " << tlvsize << std::endl; -#endif - - /* skip the header */ - offset += 8; - - /* add mandatory parts first */ - ok &= setRawUInt32(data, tlvsize, &offset, item->serviceId); - ok &= setRawUInt32(data, tlvsize, &offset, item->numPlayers); - ok &= setRawUInt32(data, tlvsize, &offset, item->msg); - - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_GENID, item->gameId); - ok &= SetTlvWideString(data, tlvsize, &offset, TLV_TYPE_WSTR_COMMENT, item->gameComment); - ok &= item->players.SetTlv(data, tlvsize, &offset); - - if (offset != tlvsize) - { - ok = false; -#ifdef RSSERIAL_DEBUG - std::cerr << "RsGameSerialiser::serialiseItem() Size Error! " << std::endl; -#endif - } - - return ok; -} - -RsGameItem *RsGameSerialiser::deserialiseItem(void *data, uint32_t *pktsize) -{ - /* get the type and size */ - uint32_t rstype = getRsItemId(data); - uint32_t tlvsize = getRsItemSize(data); - - uint32_t offset = 0; - - - if ((RS_PKT_VERSION_SERVICE != getRsItemVersion(rstype)) || - (RS_SERVICE_TYPE_GAME_LAUNCHER != getRsItemService(rstype)) || - (RS_PKT_SUBTYPE_DEFAULT != getRsItemSubType(rstype))) - { - return NULL; /* wrong type */ - } - - if (*pktsize < tlvsize) /* check size */ - return NULL; /* not enough data */ - - /* set the packet length */ - *pktsize = tlvsize; - - bool ok = true; - - /* ready to load */ - RsGameItem *item = new RsGameItem(); - item->clear(); - - /* skip the header */ - offset += 8; - - /* add mandatory parts first */ - ok &= getRawUInt32(data, tlvsize, &offset, &(item->serviceId)); - ok &= getRawUInt32(data, tlvsize, &offset, &(item->numPlayers)); - ok &= getRawUInt32(data, tlvsize, &offset, &(item->msg)); - - ok &= GetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_GENID, item->gameId); - ok &= GetTlvWideString(data, tlvsize, &offset, TLV_TYPE_WSTR_COMMENT, item->gameComment); - ok &= item->players.GetTlv(data, tlvsize, &offset); - - if (offset != tlvsize) - { - /* error */ - delete item; - return NULL; - } - - if (!ok) - { - delete item; - return NULL; - } - - return item; -} - - -uint32_t RsGameSerialiser::size(RsItem *item) -{ - return sizeItem((RsGameItem *) item); -} - -bool RsGameSerialiser::serialise(RsItem *item, void *data, uint32_t *pktsize) -{ - return serialiseItem((RsGameItem *) item, data, pktsize); -} - -RsItem *RsGameSerialiser::deserialise(void *data, uint32_t *pktsize) -{ - return deserialiseItem(data, pktsize); -} - -/*************************************************************************/ - - - diff --git a/libretroshare/src/serialiser/rsgameitems.h b/libretroshare/src/serialiser/rsgameitems.h deleted file mode 100644 index 4b183f82d..000000000 --- a/libretroshare/src/serialiser/rsgameitems.h +++ /dev/null @@ -1,84 +0,0 @@ -#ifndef RS_GAME_ITEMS_H -#define RS_GAME_ITEMS_H - -/* - * libretroshare/src/serialiser: rsgameitems.h - * - * RetroShare Serialiser. - * - * Copyright 2007-2008 by Robert Fernie. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License Version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 - * USA. - * - * Please report all bugs and problems to "retroshare@lunamutt.com". - * - */ - -#include - -#include "serialiser/rsserviceids.h" -#include "serialiser/rsserial.h" -#include "serialiser/rstlvtypes.h" - -/**************************************************************************/ - -class RsGameItem: public RsItem -{ - public: - RsGameItem() - :RsItem(RS_PKT_VERSION_SERVICE, RS_SERVICE_TYPE_GAME_LAUNCHER, - RS_PKT_SUBTYPE_DEFAULT) - { return; } -virtual ~RsGameItem(); -virtual void clear(); -std::ostream &print(std::ostream &out, uint16_t indent = 0); - - uint32_t serviceId; - uint32_t numPlayers; - uint32_t msg; /* RS_GAME_MSG_XXX */ - - std::string gameId; - std::wstring gameComment; - - RsTlvPeerIdSet players; -}; - -class RsGameSerialiser: public RsSerialType -{ - public: - RsGameSerialiser() - :RsSerialType(RS_PKT_VERSION_SERVICE, RS_SERVICE_TYPE_GAME_LAUNCHER) - { return; } -virtual ~RsGameSerialiser() - { return; } - -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 sizeItem(RsGameItem *); -virtual bool serialiseItem (RsGameItem *item, void *data, uint32_t *size); -virtual RsGameItem *deserialiseItem(void *data, uint32_t *size); - - -}; - -/**************************************************************************/ - -#endif /* RS_GAME_ITEMS_H */ - - diff --git a/libretroshare/src/serialiser/rstunnelitems.cc b/libretroshare/src/serialiser/rstunnelitems.cc deleted file mode 100644 index 53dc3cd9e..000000000 --- a/libretroshare/src/serialiser/rstunnelitems.cc +++ /dev/null @@ -1,304 +0,0 @@ -#include -#include -#include "rstunnelitems.h" -#include "util/rsstring.h" - -// -----------------------------------------------------------------------------------// -// -------------------------------- Serialization. --------------------------------- // -// -----------------------------------------------------------------------------------// -// - -// -// ---------------------------------- Packet sizes -----------------------------------// -// - -uint32_t RsTunnelDataItem::serial_size() -{ -#ifdef P3TUNNEL_DEBUG - std::cerr << "RsTunnelDataItem::serial_size() called." << std::endl ; -#endif - uint32_t s = 0 ; - - s += 8 ; // header - s += GetTlvStringSize(sourcePeerId) ; - s += GetTlvStringSize(relayPeerId) ; - s += GetTlvStringSize(destPeerId) ; - - s += 4 ; //encoded_data_len - s += encoded_data_len; - - return s ; -} - -uint32_t RsTunnelHandshakeItem::serial_size() -{ -#ifdef P3TUNNEL_DEBUG - std::cerr << "RsTunnelHandshakeItem::serial_size() called." << std::endl ; -#endif - uint32_t s = 0 ; - - s += 8 ; // header - s += GetTlvStringSize(sourcePeerId) ; - s += GetTlvStringSize(relayPeerId) ; - s += GetTlvStringSize(destPeerId) ; - s += GetTlvStringSize(sslCertPEM) ; - s += 4 ; //connection_accept - - - return s ; -} - -// -// ---------------------------------- Serialization ----------------------------------// -// -RsItem *RsTunnelSerialiser::deserialise(void *data, uint32_t *size) -{ -#ifdef P3TUNNEL_DEBUG - std::cerr << "RsTunnelSerialiser::deserialise() called." << std::endl ; -#endif - // look what we have... - - /* get the type */ - uint32_t rstype = getRsItemId(data); -#ifdef P3TUNNEL_DEBUG - std::cerr << "p3tunnel: deserialising packet: " << std::endl ; -#endif - if ((RS_PKT_VERSION_SERVICE != getRsItemVersion(rstype)) || (RS_SERVICE_TYPE_TUNNEL != getRsItemService(rstype))) - { -#ifdef P3TUNNEL_DEBUG - std::cerr << " Wrong type !!" << std::endl ; -#endif - return NULL; /* wrong type */ - } - - switch(getRsItemSubType(rstype)) - { - case RS_TUNNEL_SUBTYPE_DATA : return RsTunnelDataItem::deserialise(data,*size) ; - case RS_TUNNEL_SUBTYPE_HANDSHAKE : return RsTunnelHandshakeItem::deserialise(data,*size) ; - - default: - std::cerr << "Unknown packet type in Rstunnel!" << std::endl ; - return NULL ; - } -} - -RsTunnelDataItem::~RsTunnelDataItem() -{ - if(encoded_data != NULL) - free(encoded_data) ; -} - -bool RsTunnelDataItem::serialize(void *data,uint32_t& pktsize) -{ -#ifdef P3TUNNEL_DEBUG - std::cerr << "RsTunnelDataItem::serialize() called." << std::endl ; -#endif - uint32_t tlvsize = serial_size(); - uint32_t offset = 0; - - if (pktsize < tlvsize) - return false; /* not enough space */ - - pktsize = tlvsize; - - bool ok = true; - -#ifdef P3TUNNEL_DEBUG - std::cerr << "RsTunnelDataItem::serialize() tlvsize : " << tlvsize << std::endl ; -#endif - - ok &= setRsItemHeader(data,tlvsize,PacketId(), tlvsize); - - /* skip the header */ - offset += 8; - - /* add mandatory parts first */ - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_VALUE, sourcePeerId); - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_VALUE, relayPeerId); - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_VALUE, destPeerId); - - ok &= setRawUInt32(data, tlvsize, &offset, encoded_data_len) ; - - if(encoded_data != NULL) - memcpy((void*)((unsigned char*)data+offset),encoded_data,encoded_data_len) ; - -#ifdef P3TUNNEL_DEBUG - std::cerr << "RsTunnelDataItem::serialise() (offset + encoded_data_len) " << (offset + encoded_data_len) << std::endl; - std::cerr << "RsTunnelDataItem::serialise() tlvsize " << tlvsize << std::endl; -#endif - - if ((offset + encoded_data_len) != tlvsize ) - { - ok = false; - std::cerr << "RsTunnelDataItem::serialiseTransfer() Size Error! " << std::endl; - } - -#ifdef P3TUNNEL_DEBUG - std::cerr << "RsTunnelDataItem::serialize() packet size inside serialised data : " << getRsItemSize(data) << std::endl ; -#endif - - return ok; -} - -bool RsTunnelHandshakeItem::serialize(void *data,uint32_t& pktsize) -{ -#ifdef P3TUNNEL_DEBUG - std::cerr << "RsTunnelHandshakeItem::serialize() called." << std::endl ; -#endif - uint32_t tlvsize = serial_size(); - uint32_t offset = 0; - - if (pktsize < tlvsize) - return false; /* not enough space */ - - pktsize = tlvsize; - - bool ok = true; - -#ifdef P3TUNNEL_DEBUG - std::cerr << "RsTunnelHandshakeItem::serialize() tlvsize : " << tlvsize << std::endl ; -#endif - - ok &= setRsItemHeader(data,tlvsize,PacketId(), tlvsize); - - /* skip the header */ - offset += 8; - - /* add mandatory parts first */ - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_VALUE, sourcePeerId); - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_VALUE, relayPeerId); - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_VALUE, destPeerId); - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_CERT_SSL, sslCertPEM); - ok &= setRawUInt32(data, tlvsize, &offset, connection_accepted); - - if (offset != tlvsize ) - { - ok = false; - std::cerr << "RsTunnelHandshakeItem::serialiseTransfer() Size Error! " << std::endl; - } - - return ok; -} - -#ifdef P3TUNNEL_DEBUG -void displayRawPacket(std::ostream &out, void *data, uint32_t size) -{ - uint32_t i; - std::string sout; - rs_sprintf(sout, "DisplayRawPacket: Size: %ld", size); - - for(i = 0; i < size; i++) - { - if (i % 16 == 0) - { - sout += "\n"; - } - rs_sprintf_append(sout, "%02x:", (int) (((unsigned char *) data)[i])); - } - - out << sout << std::endl; -} -#endif - -//deserialize in constructor -RsTunnelDataItem *RsTunnelDataItem::deserialise(void *data,uint32_t pktsize) -{ - RsTunnelDataItem *item = new RsTunnelDataItem ; -#ifdef P3TUNNEL_DEBUG - std::cerr << "RsTunnelDataItem constructor called : deserializing packet." << std::endl ; -#endif - uint32_t offset = 8; // skip the header - uint32_t rssize = getRsItemSize(data); - bool ok = true ; - -#ifdef P3TUNNEL_DEBUG - std::cerr << "RsTunnelDataItem constructor rssize : " << rssize << std::endl ; -#endif - - ok &= GetTlvString(data, pktsize, &offset, TLV_TYPE_STR_VALUE, item->sourcePeerId); - ok &= GetTlvString(data, pktsize, &offset, TLV_TYPE_STR_VALUE, item->relayPeerId); - ok &= GetTlvString(data, pktsize, &offset, TLV_TYPE_STR_VALUE, item->destPeerId); - - ok &= getRawUInt32(data, pktsize, &offset, &item->encoded_data_len) ; - - if(!ok) // return early to avoid calling malloc with invalid size - return NULL ; - - if(item->encoded_data_len > 0) - { - item->encoded_data = (void*)malloc(item->encoded_data_len) ; - memcpy(item->encoded_data, (void*)((unsigned char*)data+offset), item->encoded_data_len); - } - else - item->encoded_data = NULL ; - - if ((offset + item->encoded_data_len) != rssize) - { - std::cerr << "Size error while deserializing a RsTunnelHandshakeItem." << std::endl; -#ifdef P3TUNNEL_DEBUG - displayRawPacket(std::cerr,data,rssize) ; -#endif - return NULL ; - } - if (!ok) - { - std::cerr << "Error while deserializing a RstunnelDataItem." << std::endl ; - return NULL ; - } - return item ; -} - -//deserialize in constructor -RsTunnelHandshakeItem *RsTunnelHandshakeItem::deserialise(void *data,uint32_t pktsize) -{ - RsTunnelHandshakeItem *item = new RsTunnelHandshakeItem ; -#ifdef P3TUNNEL_DEBUG - std::cerr << "RsTunnelHandshakeItem constructor called : deserializing packet." << std::endl ; -#endif - uint32_t offset = 8; // skip the header - uint32_t rssize = getRsItemSize(data); - bool ok = true ; - -#ifdef P3TUNNEL_DEBUG - std::cerr << "RsTunnelHandshakeItem constructor rssize : " << rssize << std::endl ; -#endif - - ok &= GetTlvString(data, pktsize, &offset, TLV_TYPE_STR_VALUE, item->sourcePeerId); - ok &= GetTlvString(data, pktsize, &offset, TLV_TYPE_STR_VALUE, item->relayPeerId); - ok &= GetTlvString(data, pktsize, &offset, TLV_TYPE_STR_VALUE, item->destPeerId); - ok &= GetTlvString(data, pktsize, &offset, TLV_TYPE_STR_CERT_SSL, item->sslCertPEM); - ok &= getRawUInt32(data, pktsize, &offset, &item->connection_accepted); - - if (offset != rssize) - { - std::cerr << "Size error while deserializing a RsTunnelHandshakeItem." << std::endl; - return NULL ; - } - if (!ok) - { - std::cerr << "Unknown error while deserializing a RsTunnelHandshakeItem." << std::endl ; - return NULL ; - } - return item ; -} - -std::ostream& RsTunnelDataItem::print(std::ostream& o, uint16_t) -{ - o << "RsTunnelDataItem :" << std::endl ; - o << " sourcePeerId : " << sourcePeerId << std::endl ; - o << " relayPeerId : " << relayPeerId << std::endl ; - o << " destPeerId : " << destPeerId << std::endl ; - o << " encoded_data_len : " << encoded_data_len << std::endl ; - return o ; -} - -std::ostream& RsTunnelHandshakeItem::print(std::ostream& o, uint16_t) -{ - o << "RsTunnelHandshakeItem :" << std::endl ; - o << " sourcePeerId : " << sourcePeerId << std::endl ; - o << " relayPeerId : " << relayPeerId << std::endl ; - o << " destPeerId : " << destPeerId << std::endl ; - o << " sslCertPEM : " << sslCertPEM << std::endl ; - o << " connection_accepted : " << connection_accepted << std::endl ; - return o ; -} diff --git a/libretroshare/src/serialiser/rstunnelitems.h b/libretroshare/src/serialiser/rstunnelitems.h deleted file mode 100644 index f50a79345..000000000 --- a/libretroshare/src/serialiser/rstunnelitems.h +++ /dev/null @@ -1,132 +0,0 @@ -#ifndef RS_TUNNEL_ITEMS_H -#define RS_TUNNEL_ITEMS_H - -/* - * libretroshare/src/serialiser: rschannelitems.h - * - * RetroShare Serialiser. - * - * Copyright 2007-2008 by Robert Fernie. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License Version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 - * USA. - * - * Please report all bugs and problems to "retroshare@lunamutt.com". - * - */ - -#include - -#include "serialiser/rstlvbase.h" -#include "serialiser/rsbaseserial.h" -#include "serialiser/rsserviceids.h" -#include "serialiser/rsserial.h" -#include "serialiser/rstlvtypes.h" -#include "serialiser/rstlvkeys.h" - -const uint8_t RS_TUNNEL_SUBTYPE_DATA = 0x01 ; -const uint8_t RS_TUNNEL_SUBTYPE_HANDSHAKE = 0x02 ; - -/***********************************************************************************/ -/* Basic Tunnel Item Class */ -/***********************************************************************************/ - -class RsTunnelItem: public RsItem -{ - public: - RsTunnelItem(uint8_t tunnel_subtype) : RsItem(RS_PKT_VERSION_SERVICE,RS_SERVICE_TYPE_TUNNEL,tunnel_subtype) {} - - virtual ~RsTunnelItem() {} - - virtual bool serialize(void *data,uint32_t& size) = 0 ; // Isn't it better that items can serialize themselves ? - virtual uint32_t serial_size() { return 0;} - - virtual void clear() {} -}; - -class RsTunnelDataItem: public RsTunnelItem -{ - public: - RsTunnelDataItem() : RsTunnelItem(RS_TUNNEL_SUBTYPE_DATA) - { - encoded_data = NULL ; // To comply with the destructor below. - } - virtual ~RsTunnelDataItem() ; - - static RsTunnelDataItem *deserialise(void *data,uint32_t size) ; // deserialization - - uint32_t encoded_data_len; - void *encoded_data; - - std::string sourcePeerId ; - std::string relayPeerId ; - std::string destPeerId ; - - std::ostream& print(std::ostream& o, uint16_t) ; - - bool serialize(void *data,uint32_t& size) ; - uint32_t serial_size() ; -}; - -class RsTunnelHandshakeItem: public RsTunnelItem -{ - public: - RsTunnelHandshakeItem() : RsTunnelItem(RS_TUNNEL_SUBTYPE_HANDSHAKE) {} - virtual ~RsTunnelHandshakeItem() {} - - static RsTunnelHandshakeItem *deserialise(void *data,uint32_t size) ; // deserialization - - std::string sourcePeerId ; - std::string relayPeerId ; - std::string destPeerId ; - std::string sslCertPEM ; - uint32_t connection_accepted; - - std::ostream& print(std::ostream& o, uint16_t) ; - - bool serialize(void *data,uint32_t& size) ; - uint32_t serial_size() ; -}; - -class RsTunnelSerialiser: public RsSerialType -{ - public: - RsTunnelSerialiser() : RsSerialType(RS_PKT_VERSION_SERVICE, RS_SERVICE_TYPE_TUNNEL) {} - - virtual uint32_t size(RsItem *item) - { - RsTunnelItem * rst; - if (NULL != (rst = dynamic_cast(item))) - { - return rst->serial_size() ; - } else { - std::cerr << "RsTunnelSerialiser::size() problem, not a RsTunnelItem." << std::endl; - } - return 0; - } - virtual bool serialise(RsItem *item, void *data, uint32_t *size) - { - RsTunnelItem * rst; - if (NULL != (rst = dynamic_cast(item))) - { - return rst->serialize(data,*size) ; - } else { - std::cerr << "RsTunnelSerialiser::serialise() problem, not a RsTunnelItem." << std::endl; - } - return false; - } - virtual RsItem *deserialise (void *data, uint32_t *size) ; -}; - -#endif /* RS_TUNNEL_ITEMS_H */ diff --git a/libretroshare/src/services/p3blogs.cc b/libretroshare/src/services/p3blogs.cc deleted file mode 100644 index c865282f2..000000000 --- a/libretroshare/src/services/p3blogs.cc +++ /dev/null @@ -1,406 +0,0 @@ -/* - * libretroshare/src/services: p3Blogs.cc - * - * RetroShare C++ Interface. - * - * Copyright 2008 by Robert Fernie. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License Version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 - * USA. - * - * Please report all bugs and problems to "retroshare@lunamutt.com". - * - */ - -#include "services/p3blogs.h" -#include "util/rsdir.h" - -std::ostream &operator<<(std::ostream &out, const BlogInfo &info) -{ - std::string name(info.blogName.begin(), info.blogName.end()); - std::string desc(info.blogDesc.begin(), info.blogDesc.end()); - - out << "BlogInfo:"; - out << std::endl; - out << "BlogId: " << info.blogId << std::endl; - out << "BlogName: " << name << std::endl; - out << "BlogDesc: " << desc << std::endl; - out << "BlogFlags: " << info.blogFlags << std::endl; - out << "Pop: " << info.pop << std::endl; - out << "LastPost: " << info.lastPost << std::endl; - - return out; -} - -std::ostream &operator<<(std::ostream &out, const BlogMsgSummary &info) -{ - out << "BlogMsgSummary:"; - out << std::endl; - out << "BlogId: " << info.blogId << std::endl; - - return out; -} - -std::ostream &operator<<(std::ostream &out, const BlogMsgInfo &info) -{ - out << "BlogMsgInfo:"; - out << std::endl; - out << "BlogId: " << info.blogId << std::endl; - - return out; -} - - -RsBlogs *rsBlogs = NULL; - - -/* Blogs will be initially stored for 1 year - * remember 2^16 = 64K max units in store period. - * PUBPERIOD * 2^16 = max STORE PERIOD */ -#define BLOG_STOREPERIOD (90*24*3600) /* 30 * 24 * 3600 - secs in a year */ -#define BLOG_PUBPERIOD 600 /* 10 minutes ... (max = 455 days) */ - -p3Blogs::p3Blogs(uint16_t type, CacheStrapper *cs, - CacheTransfer *cft, - std::string srcdir, std::string storedir) - :p3GroupDistrib(type, cs, cft, srcdir, storedir, "", - CONFIG_TYPE_QBLOG, BLOG_STOREPERIOD, BLOG_PUBPERIOD) -{ - return; -} - -p3Blogs::~p3Blogs() -{ - return; -} - -/****************************************/ - -bool p3Blogs::blogsChanged(std::list &blogIds) -{ - return groupsChanged(blogIds); -} - - -bool p3Blogs::getBlogInfo(std::string cId, BlogInfo &ci) -{ - RsStackMutex stack(distribMtx); /***** STACK LOCKED MUTEX *****/ - - /* extract details */ - GroupInfo *gi = locked_getGroupInfo(cId); - - if (!gi) - return false; - - ci.blogId = gi->grpId; - ci.blogName = gi->grpName; - ci.blogDesc = gi->grpDesc; - - ci.blogFlags = gi->flags; - - ci.pop = gi->sources.size(); - ci.lastPost = gi->lastPost; - - ci.pngChanImage = gi->grpIcon.pngImageData; - - if(ci.pngChanImage != NULL) - ci.pngImageLen = gi->grpIcon.imageSize; - else - ci.pngImageLen = 0; - - return true; -} - - -bool p3Blogs::getBlogList(std::list &blogList) -{ - std::list grpIds; - std::list::iterator it; - - getAllGroupList(grpIds); - - for(it = grpIds.begin(); it != grpIds.end(); it++) - { - BlogInfo ci; - if (getBlogInfo(*it, ci)) - { - blogList.push_back(ci); - } - } - return true; -} - - -bool p3Blogs::getBlogMsgList(std::string cId, std::list &msgs) -{ - std::list msgIds; - std::list::iterator it; - - getAllMsgList(cId, msgIds); - - RsStackMutex stack(distribMtx); /***** STACK LOCKED MUTEX *****/ - for(it = msgIds.begin(); it != msgIds.end(); it++) - { - /* get details */ - RsDistribMsg *msg = locked_getGroupMsg(cId, *it); - RsBlogMsg *cmsg = dynamic_cast(msg); - if (!cmsg) - continue; - - BlogMsgSummary tis; - - tis.blogId = msg->grpId; - tis.msgId = msg->msgId; - tis.ts = msg->timestamp; - - /* the rest must be gotten from the derived Msg */ - - tis.subject = cmsg->subject; - tis.msg = cmsg->message; - - msgs.push_back(tis); - } - return true; -} - -bool p3Blogs::getBlogMessage(std::string fId, std::string mId, BlogMsgInfo &info) -{ - std::list msgIds; - std::list::iterator it; - - RsStackMutex stack(distribMtx); /***** STACK LOCKED MUTEX *****/ - - RsDistribMsg *msg = locked_getGroupMsg(fId, mId); - RsBlogMsg *cmsg = dynamic_cast(msg); - if (!cmsg) - return false; - - - info.blogId = msg->grpId; - info.msgId = msg->msgId; - info.ts = msg->timestamp; - - /* the rest must be gotten from the derived Msg */ - - info.subject = cmsg->subject; - info.msg = cmsg->message; - - return true; -} - -bool p3Blogs::BlogMessageSend(BlogMsgInfo &info) -{ - - RsBlogMsg *cmsg = new RsBlogMsg(); - cmsg->grpId = info.blogId; - - cmsg->subject = info.subject; - cmsg->message = info.msg; - cmsg->timestamp = time(NULL); - - std::string msgId = publishMsg(cmsg, true); - - return true; -} - -bool p3Blogs::BlogMessageReply(BlogMsgInfo& reply){ - - // ensure it has a value - if(isReply(reply)){ - std::cerr << "p3Blogs::BlogMessageReply()" << " This is not a reply " << std::endl; - return false; - } - - - // also check that msgId exists for group - - return BlogMessageSend(reply); -} - -bool p3Blogs::isReply(BlogMsgInfo& info){ - - // if replies list is empty then this is not a reply to a blog - return !info.msgIdReply.empty(); -} - -std::string p3Blogs::createBlog(std::wstring blogName, std::wstring blogDesc, uint32_t blogFlags, - unsigned char* pngImageData, uint32_t imageSize) -{ - - std::string id = createGroup(blogName, blogDesc, blogFlags, pngImageData, imageSize); - - return id; -} - -RsSerialType *p3Blogs::createSerialiser() -{ - return new RsBlogSerialiser(); -} - -bool p3Blogs::locked_checkDistribMsg(RsDistribMsg *msg) -{ - return true; -} - - -RsDistribGrp *p3Blogs::locked_createPublicDistribGrp(GroupInfo &info) -{ - RsDistribGrp *grp = NULL; //new RsChannelGrp(); - - return grp; -} - -RsDistribGrp *p3Blogs::locked_createPrivateDistribGrp(GroupInfo &info) -{ - RsDistribGrp *grp = NULL; //new RsChannelGrp(); - - return grp; -} - - -bool p3Blogs::blogSubscribe(std::string cId, bool subscribe) -{ - std::cerr << "p3Blogs::channelSubscribe() "; - std::cerr << cId; - std::cerr << std::endl; - - return subscribeToGroup(cId, subscribe); -} - - -/***************************************************************************************/ -/****************** Event Feedback (Overloaded form p3distrib) *************************/ -/***************************************************************************************/ -/* only download in the first week of channel - * older stuff can be manually downloaded. - */ - -const uint32_t DOWNLOAD_PERIOD = 7 * 24 * 3600; - -/* This is called when we receive a msg, and also recalled - * - */ - -bool p3Blogs::locked_eventDuplicateMsg(GroupInfo *grp, RsDistribMsg *msg, const std::string& id, bool historical) -{ - return true; -} - -#include "pqi/pqinotify.h" - -bool p3Blogs::locked_eventNewMsg(GroupInfo *grp, RsDistribMsg *msg, const std::string& id, bool historical) -{ - std::string grpId = msg->grpId; - std::string msgId = msg->msgId; - std::string nullId; - - std::cerr << "p3Blogs::locked_eventNewMsg() "; - std::cerr << " grpId: " << grpId; - std::cerr << " msgId: " << msgId; - std::cerr << " peerId: " << id; - std::cerr << std::endl; - - if (!historical) - { - getPqiNotify()->AddFeedItem(RS_FEED_ITEM_BLOG_MSG, grpId, msgId, nullId); - } - - /* request the files - * NB: This could result in duplicates. - * which must be handled by ft side. - * - * this is exactly what DuplicateMsg does. - * */ - return locked_eventDuplicateMsg(grp, msg, id, historical); -} - - - - -void p3Blogs::locked_notifyGroupChanged(GroupInfo &grp, uint32_t flags, bool historical) -{ - std::string grpId = grp.grpId; - std::string msgId; - std::string nullId; - - std::cerr << "p3Blogs::locked_notifyGroupChanged() "; - std::cerr << grpId; - std::cerr << " flags:" << flags; - std::cerr << std::endl; - - switch(flags) - { - case GRP_NEW_UPDATE: - std::cerr << "p3Blogs::locked_notifyGroupChanged() NEW UPDATE"; - std::cerr << std::endl; - if (!historical) - { - getPqiNotify()->AddFeedItem(RS_FEED_ITEM_BLOG_NEW, grpId, msgId, nullId); - } - break; - case GRP_UPDATE: - std::cerr << "p3Blogs::locked_notifyGroupChanged() UPDATE"; - std::cerr << std::endl; - if (!historical) - { - getPqiNotify()->AddFeedItem(RS_FEED_ITEM_BLOG_UPDATE, grpId, msgId, nullId); - } - break; - case GRP_LOAD_KEY: - std::cerr << "p3Blogs::locked_notifyGroupChanged() LOAD_KEY"; - std::cerr << std::endl; - break; - case GRP_NEW_MSG: - std::cerr << "p3Blogs::locked_notifyGroupChanged() NEW MSG"; - std::cerr << std::endl; - break; - case GRP_SUBSCRIBED: - std::cerr << "p3Blogs::locked_notifyGroupChanged() SUBSCRIBED"; - std::cerr << std::endl; - break; - case GRP_UNSUBSCRIBED: - std::cerr << "p3Blogs::locked_notifyGroupChanged() UNSUBSCRIBED"; - std::cerr << std::endl; - - /* won't stop downloads... */ - - break; - - default: - std::cerr << "p3Blogs::locked_notifyGroupChanged() Unknown DEFAULT"; - std::cerr << std::endl; - break; - } - - return p3GroupDistrib::locked_notifyGroupChanged(grp, flags); -} - -//TODO: if you want to enable config saving and loading implement this -bool p3Blogs::childLoadList(std::list& configSaves) -{ - return true; -} - -//TODO: -std::list p3Blogs::childSaveList() -{ - std::list saveL; - - return saveL; -} - -/****************************************/ - - - diff --git a/libretroshare/src/services/p3blogs.h b/libretroshare/src/services/p3blogs.h deleted file mode 100644 index 6c087007f..000000000 --- a/libretroshare/src/services/p3blogs.h +++ /dev/null @@ -1,137 +0,0 @@ -#ifndef RS_P3_BLOGS_INTERFACE_H -#define RS_P3_BLOGS_INTERFACE_H - -/* - * libretroshare/src/services: p3blogs.h - * - * RetroShare C++ Interface. - * - * Copyright 2008 by Robert Fernie. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License Version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 - * USA. - * - * Please report all bugs and problems to "retroshare@lunamutt.com". - * - */ - -#include "retroshare/rsblogs.h" -#include "retroshare/rsfiles.h" -#include "distrib/p3distrib.h" - -#include "serialiser/rstlvtypes.h" -#include "serialiser/rsblogitems.h" - -/*! - * implements the blog interface using the distrib service. it allows users to send blogs using - * retroshare's cache service. its use - */ -class p3Blogs: public p3GroupDistrib, public RsBlogs -{ - public: - - /*! - * @param CacheStrapper needed to push blogs onto the cache service - * @param CacheTransfer maintains distrib servi - * @param srcdir - * @param storedir - */ - p3Blogs(uint16_t type, CacheStrapper *cs, CacheTransfer *cft, - std::string srcdir, std::string storedir); -virtual ~p3Blogs(); - -/****************************************/ -/********* rsBlogs Interface ***********/ - - -/** - * check if any of the blogs has been changed - * @param blogIds list blogs by ids to be checked - * @return false if changed and vice versa - */ -virtual bool blogsChanged(std::list &blogIds); - -/** - * creates a new blog - */ -virtual std::string createBlog(std::wstring blogName, std::wstring blogDesc, uint32_t blogFlags, - unsigned char* pngImageData, uint32_t imageSize); - -/** - * @param cId the id for the blog - * @param BloogInfo blog information is stored here - */ -virtual bool getBlogInfo(std::string cId, BlogInfo &ci); - -/** - * get list of blogs from the group peer belongs to - */ -virtual bool getBlogList(std::list &blogList); - -/** - * Returns a list of all the messages sent - * @param cId group id - * @param msgs - */ -virtual bool getBlogMsgList(std::string cId, std::list &msgs); -virtual bool getBlogMessage(std::string cId, std::string mId, BlogMsgInfo &msg); - -virtual bool BlogMessageSend(BlogMsgInfo &info); - -/** - * subscribes or unsubscribes peer to a blog message - * @param cId the id of the blog message peer wants to subscribe - * @param subscribe set to true to subscribe, false otherwise - */ -virtual bool blogSubscribe(std::string cId, bool subscribe); - - -/** - * send a reply to a blog msg, ensure msgIdReply has valid id to a message - */ -virtual bool BlogMessageReply(BlogMsgInfo &info); - -/** - * check if a particular blog is a reply - * @return false if not a reply, true otherwise - */ -virtual bool isReply(BlogMsgInfo& info); - - -/***************************************************************************************/ -/****************** Event Feedback (Overloaded form p3distrib) *************************/ -/***************************************************************************************/ - - protected: -virtual void locked_notifyGroupChanged(GroupInfo &info, uint32_t flags, bool historical); -virtual bool locked_eventNewMsg(GroupInfo *, RsDistribMsg *, const std::string&, bool historical); -virtual bool locked_eventDuplicateMsg(GroupInfo *, RsDistribMsg *, const std::string&, bool historical); - - -/****************************************/ -/********* Overloaded Functions *********/ - -virtual RsSerialType *createSerialiser(); - -virtual bool locked_checkDistribMsg(RsDistribMsg *msg); -virtual RsDistribGrp *locked_createPublicDistribGrp(GroupInfo &info); -virtual RsDistribGrp *locked_createPrivateDistribGrp(GroupInfo &info); -virtual bool childLoadList(std::list& configSaves); -virtual std::list childSaveList(); -/****************************************/ - -}; - - -#endif diff --git a/libretroshare/src/services/p3channels.cc b/libretroshare/src/services/p3channels.cc deleted file mode 100644 index 1c2035fd8..000000000 --- a/libretroshare/src/services/p3channels.cc +++ /dev/null @@ -1,1092 +0,0 @@ -/* - * libretroshare/src/services: p3channels.cc - * - * RetroShare C++ Interface. - * - * Copyright 2008 by Robert Fernie. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License Version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 - * USA. - * - * Please report all bugs and problems to "retroshare@lunamutt.com". - * - */ - -#include "services/p3channels.h" -#include "util/rsdir.h" -#include "retroshare/rsiface.h" - -std::ostream &operator<<(std::ostream &out, const ChannelInfo &info) -{ - std::string name(info.channelName.begin(), info.channelName.end()); - std::string desc(info.channelDesc.begin(), info.channelDesc.end()); - - out << "ChannelInfo:"; - out << std::endl; - out << "ChannelId: " << info.channelId << std::endl; - out << "ChannelName: " << name << std::endl; - out << "ChannelDesc: " << desc << std::endl; - out << "ChannelFlags: " << info.channelFlags << std::endl; - out << "Pop: " << info.pop << std::endl; - out << "LastPost: " << info.lastPost << std::endl; - - return out; -} - -std::ostream &operator<<(std::ostream &out, const ChannelMsgSummary &info) -{ - out << "ChannelMsgSummary: ChannelId: " << info.channelId << std::endl; - - return out; -} - -std::ostream &operator<<(std::ostream &out, const ChannelMsgInfo &info) -{ - out << "ChannelMsgInfo: ChannelId: " << info.channelId << std::endl; - - return out; -} - - -RsChannels *rsChannels = NULL; - - -/* remember 2^16 = 64K max units in store period. - * PUBPERIOD * 2^16 = max STORE PERIOD */ -#define CHANNEL_STOREPERIOD (30*24*3600) /* 30 * 24 * 3600 - secs in a 30 day month */ -#define CHANNEL_PUBPERIOD 120 /* 2 minutes ... (max = 455 days) */ -#define MAX_AUTO_DL 1E9 /* auto download of attachment limit; 1 GIG */ - -p3Channels::p3Channels(uint16_t type, CacheStrapper *cs, - CacheTransfer *cft, RsFiles *files, - std::string srcdir, std::string storedir, std::string chanDir) - :p3GroupDistrib(type, cs, cft, srcdir, storedir, chanDir, - CONFIG_TYPE_CHANNELS, CHANNEL_STOREPERIOD, CHANNEL_PUBPERIOD), - mRsFiles(files), - mChannelsDir(chanDir) -{ - - /* create chanDir */ - if (!RsDirUtil::checkCreateDirectory(mChannelsDir)) { - std::cerr << "p3Channels() Failed to create Channels Directory: " << mChannelsDir << std::endl; - } - - - return; -} - -p3Channels::~p3Channels() -{ - return; -} - -/****************************************/ - -bool p3Channels::channelsChanged(std::list &chanIds) -{ - return groupsChanged(chanIds); -} - - -bool p3Channels::getChannelInfo(const std::string &cId, ChannelInfo &ci) -{ - RsStackMutex stack(distribMtx); /***** STACK LOCKED MUTEX *****/ - - /* extract details */ - GroupInfo *gi = locked_getGroupInfo(cId); - - if (!gi) - return false; - - ci.channelId = gi->grpId; - ci.channelName = gi->grpName; - ci.channelDesc = gi->grpDesc; - - ci.channelFlags = gi->flags; - - ci.pop = gi->sources.size(); - ci.lastPost = gi->lastPost; - ci.destination_directory = (mDestinationDirectories.find(cId)==mDestinationDirectories.end())?"":(mDestinationDirectories[cId]) ; - - ci.pngChanImage = gi->grpIcon.pngImageData; - - if(ci.pngChanImage != NULL) - ci.pngImageLen = gi->grpIcon.imageSize; - else - ci.pngImageLen = 0; - - return true; -} - - -bool p3Channels::getChannelList(std::list &channelList) -{ - std::list grpIds; - std::list::iterator it; - - getAllGroupList(grpIds); - - for(it = grpIds.begin(); it != grpIds.end(); it++) - { - ChannelInfo ci; - if (getChannelInfo(*it, ci)) - { - channelList.push_back(ci); - } - } - return true; -} - - -bool p3Channels::getChannelMsgList(const std::string &cId, std::list &msgs) -{ - std::list msgIds; - std::list::iterator it; - - getAllMsgList(cId, msgIds); - - RsStackMutex stack(distribMtx); /***** STACK LOCKED MUTEX *****/ - for(it = msgIds.begin(); it != msgIds.end(); it++) - { - /* get details */ - RsDistribMsg *msg = locked_getGroupMsg(cId, *it); - RsChannelMsg *cmsg = dynamic_cast(msg); - if (!cmsg) - continue; - - ChannelMsgSummary tis; - - tis.channelId = msg->grpId; - tis.msgId = msg->msgId; - tis.ts = msg->timestamp; - - /* the rest must be gotten from the derived Msg */ - - tis.subject = cmsg->subject; - tis.msg = cmsg->message; - tis.count = cmsg->attachment.items.size(); - - msgs.push_back(tis); - } - return true; -} - -bool p3Channels::getChannelMessage(const std::string &cId, const std::string &mId, ChannelMsgInfo &info) -{ - std::list msgIds; - std::list::iterator it; - - processCacheOptReq(cId); - - RsStackMutex stack(distribMtx); /***** STACK LOCKED MUTEX *****/ - - RsDistribMsg *msg = locked_getGroupMsg(cId, mId); - RsChannelMsg *cmsg = dynamic_cast(msg); - if (!cmsg) - return false; - - - info.channelId = msg->grpId; - info.msgId = msg->msgId; - info.ts = msg->timestamp; - - /* the rest must be gotten from the derived Msg */ - - info.subject = cmsg->subject; - info.msg = cmsg->message; - info.count = 0; - info.size = 0; - - std::list::iterator fit; - for(fit = cmsg->attachment.items.begin(); - fit != cmsg->attachment.items.end(); fit++) - { - FileInfo fi; - fi.fname = RsDirUtil::getTopDir(fit->name); - fi.size = fit->filesize; - fi.hash = fit->hash; - fi.path = fit->path; - - info.files.push_back(fi); - info.count++; - info.size += fi.size; - } - - if((cmsg->thumbnail.binData.bin_data != NULL) && (cmsg->thumbnail.image_type == RSTLV_IMAGE_TYPE_PNG)) - { - info.thumbnail.image_thumbnail = - (unsigned char*) cmsg->thumbnail.binData.bin_data; - - info.thumbnail.im_thumbnail_size = - cmsg->thumbnail.binData.bin_len; - } - - return true; -} - -bool p3Channels::channelRestoreKeys(const std::string &chId){ - - return p3GroupDistrib::restoreGrpKeys(chId); -} - -bool p3Channels::ChannelMessageSend(ChannelMsgInfo &info) -{ - - RsChannelMsg *cmsg = new RsChannelMsg(); - cmsg->grpId = info.channelId; - - cmsg->subject = info.subject; - cmsg->message = info.msg; - cmsg->timestamp = time(NULL); - - std::list::iterator it; - for(it = info.files.begin(); it != info.files.end(); it++) - { - - RsTlvFileItem mfi; - mfi.hash = it -> hash; - mfi.name = it -> fname; - mfi.filesize = it -> size; - cmsg -> attachment.items.push_back(mfi); - } - - // explicit member wise copy for grp image - if((info.thumbnail.image_thumbnail != NULL) && - (info.thumbnail.im_thumbnail_size > 0)){ - - cmsg->thumbnail.binData.bin_data = - new unsigned char[info.thumbnail.im_thumbnail_size]; - - memcpy(cmsg->thumbnail.binData.bin_data, info.thumbnail.image_thumbnail, - info.thumbnail.im_thumbnail_size*sizeof(unsigned char)); - cmsg->thumbnail.binData.bin_len = info.thumbnail.im_thumbnail_size; - cmsg->thumbnail.image_type = RSTLV_IMAGE_TYPE_PNG; - - }else{ - - cmsg->thumbnail.binData.bin_data = NULL; - cmsg->thumbnail.binData.bin_len = 0; - cmsg->thumbnail.image_type = 0; - } - - bool toSign = false; - // Channels are not personally signed yet... (certainly not by default!). - // This functionality can easily be added once its available in the gui + API. - // should check the GroupFlags for default. - - std::string msgId = publishMsg(cmsg, toSign); - - if (msgId.empty()) { - return false; - } - - return setMessageStatus(info.channelId, msgId, CHANNEL_MSG_STATUS_READ, CHANNEL_MSG_STATUS_MASK); -} - -bool p3Channels::setMessageStatus(const std::string& cId,const std::string& mId,const uint32_t status, const uint32_t statusMask) -{ - bool changed = false; - uint32_t newStatus = 0; - - { - RsStackMutex stack(distribMtx); /***** STACK LOCKED MUTEX *****/ - - std::list::iterator lit = mReadStatus.begin(); - - for(; lit != mReadStatus.end(); lit++) - { - - if((*lit)->channelId == cId) - { - RsChannelReadStatus* rsi = *lit; - uint32_t oldStatus = rsi->msgReadStatus[mId]; - rsi->msgReadStatus[mId] &= ~statusMask; - rsi->msgReadStatus[mId] |= (status & statusMask); - - newStatus = rsi->msgReadStatus[mId]; - if (oldStatus != newStatus) { - changed = true; - } - break; - } - - } - - // if channel id does not exist create one - if(lit == mReadStatus.end()) - { - RsChannelReadStatus* rsi = new RsChannelReadStatus(); - rsi->channelId = cId; - rsi->msgReadStatus[mId] = status & statusMask; - mReadStatus.push_back(rsi); - saveList.push_back(rsi); - - newStatus = rsi->msgReadStatus[mId]; - changed = true; - } - - if (changed) { - IndicateConfigChanged(); - } - } /******* UNLOCKED ********/ - - if (changed) { - rsicontrol->getNotify().notifyListChange(NOTIFY_LIST_CHANNELLIST_LOCKED, NOTIFY_TYPE_MOD); - rsicontrol->getNotify().notifyChannelMsgReadSatusChanged(cId, mId, newStatus); - } - - return true; -} - -bool p3Channels::getMessageStatus(const std::string& cId, const std::string& mId, uint32_t& status) -{ - - status = 0; - - RsStackMutex stack(distribMtx); - - std::list::iterator lit = mReadStatus.begin(); - - for(; lit != mReadStatus.end(); lit++) - { - - if((*lit)->channelId == cId) - { - break; - } - - } - - if(lit == mReadStatus.end()) - { - return false; - } - - std::map::iterator mit = (*lit)->msgReadStatus.find(mId); - - if(mit != (*lit)->msgReadStatus.end()) - { - status = mit->second; - return true; - } - - return false; -} - -bool p3Channels::getMessageCount(const std::string &cId, unsigned int &newCount, unsigned int &unreadCount) -{ - newCount = 0; - unreadCount = 0; - - std::list grpIds; - - if (cId.empty()) { - // count all messages of all subscribed channels - getAllGroupList(grpIds); - } else { - // count all messages of one channels - grpIds.push_back(cId); - } - - std::list::iterator git; - for (git = grpIds.begin(); git != grpIds.end(); git++) { - std::string cId = *git; - uint32_t grpFlags; - - { - // only flag is needed - RsStackMutex stack(distribMtx); /***** STACK LOCKED MUTEX *****/ - GroupInfo *gi = locked_getGroupInfo(cId); - if (gi == NULL) { - return false; - } - grpFlags = gi->flags; - } /******* UNLOCKED ********/ - - if (grpFlags & (RS_DISTRIB_ADMIN | RS_DISTRIB_SUBSCRIBED)) { - std::list msgIds; - if (getAllMsgList(cId, msgIds)) { - std::list::iterator mit; - - RsStackMutex stack(distribMtx); /***** STACK LOCKED MUTEX *****/ - - std::list::iterator lit; - for(lit = mReadStatus.begin(); lit != mReadStatus.end(); lit++) { - if ((*lit)->channelId == cId) { - break; - } - } - - if (lit == mReadStatus.end()) { - // no status available -> all messages are new - newCount += msgIds.size(); - unreadCount += msgIds.size(); - continue; - } - - for (mit = msgIds.begin(); mit != msgIds.end(); mit++) { - std::map::iterator rit = (*lit)->msgReadStatus.find(*mit); - - if (rit == (*lit)->msgReadStatus.end()) { - // no status available -> message is new - newCount++; - unreadCount++; - continue; - } - - if (rit->second & CHANNEL_MSG_STATUS_READ) { - // message is not new - if (rit->second & CHANNEL_MSG_STATUS_UNREAD_BY_USER) { - // message is unread - unreadCount++; - } - } else { - newCount++; - unreadCount++; - } - } - } /******* UNLOCKED ********/ - } - } - - return true; -} - -bool p3Channels::channelExtraFileHash(const std::string &path, const std::string & /*chId*/, FileInfo& fInfo){ - - // get file name - std::string fname, fnameBuff; - std::string::const_reverse_iterator rit; - - for(rit = path.rbegin(); *rit != '/' ; rit++){ - fnameBuff.push_back(*rit); - } - - // reverse string buff for correct file name - fname.append(fnameBuff.rbegin(), fnameBuff.rend()); - - TransferRequestFlags flags = RS_FILE_REQ_ANONYMOUS_ROUTING; - - // then hash file and get file info too - - if(!mRsFiles->ExtraFileHash(path, CHANNEL_STOREPERIOD, flags)) - return false; - - fInfo.path = path; - fInfo.fname = fname; - - return true; -} - - -bool p3Channels::channelExtraFileRemove(const std::string &hash, const std::string &chId) -{ - TransferRequestFlags tflags = RS_FILE_REQ_ANONYMOUS_ROUTING | RS_FILE_REQ_EXTRA; - FileSearchFlags sflags = RS_FILE_HINTS_NETWORK_WIDE | RS_FILE_HINTS_EXTRA; - - /* remove copy from channels directory */ - - FileInfo fInfo; - mRsFiles->FileDetails(hash, sflags, fInfo); - std::string chPath = mChannelsDir + "/" + chId + "/" + fInfo.fname; - - if(remove(chPath.c_str()) == 0){ - std::cerr << "p3Channel::channelExtraFileRemove() Removed file :" - << chPath.c_str() << std::endl; - - }else{ - std::cerr << "p3Channel::channelExtraFileRemove() Failed to remove file :" - << chPath.c_str() << std::endl; - } - - return mRsFiles->ExtraFileRemove(hash, tflags); -} - - -std::string p3Channels::createChannel(std::wstring channelName, std::wstring channelDesc, uint32_t channelFlags, - unsigned char* pngImageData, uint32_t imageSize) -{ - - std::string grpId = createGroup(channelName, channelDesc, channelFlags, pngImageData, imageSize); - - // create channel directory - std::string channelDir = mChannelsDir + "/" + grpId; - - if(RsDirUtil::checkCreateDirectory(channelDir)) - std::cerr << "p3Channels::createChannel(): Failed to create channel directory " - << channelDir << std::endl; - - return grpId; -} - -RsSerialType *p3Channels::createSerialiser() -{ - return new RsChannelSerialiser(); -} - -bool p3Channels::locked_checkDistribMsg(RsDistribMsg */*msg*/) -{ - return true; -} - - - - -bool p3Channels::channelSubscribe(const std::string &cId, bool subscribe, bool autoDl) -{ -#ifdef CHANNEL_DEBUG - std::cerr << "p3Channels::channelSubscribe() " << cId << std::endl; -#endif - - { - RsStackMutex stack(distribMtx); - - if(subscribe) - mChannelStatus[cId] |= autoDl ? - (RS_CHAN_STATUS_AUTO_DL & RS_CHAN_STATUS_MASK) : ~RS_CHAN_STATUS_MASK; - } - - bool ok = subscribeToGroup(cId, subscribe); - - - // if subscribing set channel status bit field on whether - // or not to auto download - { - RsStackMutex stack(distribMtx); - - if(!ok || !subscribe){ - mChannelStatus.erase(cId); - removeChannelReadStatusEntry(cId); - } - else{ - addChannelReadStatusEntry(cId); - } - - IndicateConfigChanged(); - } - return ok; -} - -void p3Channels::addChannelReadStatusEntry(const std::string& cId) -{ - std::list::iterator lit = mReadStatus.begin(); - RsChannelReadStatus* rds = NULL; - - // check to ensure an entry does not exist - for(; lit != mReadStatus.end(); lit++){ - - if((*lit)->channelId == cId) - { - break; - } - } - - if(lit == mReadStatus.end()){ - rds = new RsChannelReadStatus(); - rds->channelId = cId; - mReadStatus.push_back(rds); - saveList.push_back(rds); - } - - return; -} - -//TODO: delete unsubscribed channels from entry -void p3Channels::removeChannelReadStatusEntry(const std::string& cId) -{ - std::list::iterator lit = mReadStatus.begin(); - statMap::iterator mit; - // check to ensure an entry does not exist - for(; lit != mReadStatus.end(); lit++){ - - if((*lit)->channelId == cId) - { - if((mit = (*lit)->msgReadStatus.find(cId)) != - (*lit)->msgReadStatus.end()){ - (*lit)->msgReadStatus.erase(mit); - break; - } - } - } - -} -bool p3Channels::channelShareKeys(const std::string &chId, std::list& peers){ - -#ifdef CHANNEL_DEBUG - std::cerr << "p3Channels::channelShareKeys() " << chId << std::endl; -#endif - - return sharePubKey(chId, peers); - -} - -bool p3Channels::channelEditInfo(const std::string &chId, ChannelInfo& info){ - -#ifdef CHANNEL_DEBUG - std::cerr << "p3Channels::channelUdateInfo() " << chId << std::endl; -#endif - - GroupInfo gi; - - RsStackMutex stack(distribMtx); - - gi.grpName = info.channelName; - gi.grpDesc = info.channelDesc; - - - if((info.pngChanImage != NULL) && (info.pngImageLen != 0)){ - gi.grpIcon.imageSize = info.pngImageLen; - gi.grpIcon.pngImageData = info.pngChanImage; - } - else{ - gi.grpIcon.imageSize = 0; - gi.grpIcon.pngImageData = NULL; - } - - return locked_editGroup(chId, gi); - -} - - -void p3Channels::getPubKeysAvailableGrpIds(std::list& grpIds) -{ - - getGrpListPubKeyAvailable(grpIds); - return; - -} - -bool p3Channels::channelSetDestinationDirectory(const std::string& chId, const std::string& dest_dir) -{ - RsStackMutex stack(distribMtx); - - mDestinationDirectories[chId] = dest_dir ; - IndicateConfigChanged() ; - - return true ; -} - -bool p3Channels::channelSetAutoDl(const std::string& chId, bool autoDl) -{ - - RsStackMutex stack(distribMtx); - - statMap::iterator it = mChannelStatus.find(chId); - bool changed = false; - - if(it != mChannelStatus.end()){ - - if(autoDl) - it->second |= RS_CHAN_STATUS_AUTO_DL; - else - it->second &= ~(RS_CHAN_STATUS_AUTO_DL & RS_CHAN_STATUS_MASK); - - changed = true; - } - else - { -#ifdef CHANNEL_DEBUG - std::cerr << "p3Channels::channelSetAutoDl(): " << "Channel does not exist" - << std::endl; -#endif - return false; - } - - // save configuration - if(changed) - IndicateConfigChanged(); - - return true; -} - - -bool p3Channels::channelGetAutoDl(const std::string& chId, bool& autoDl) -{ - RsStackMutex stack(distribMtx); - - statMap::iterator it = mChannelStatus.find(chId); - - if(it != mChannelStatus.end()) - autoDl = it->second & RS_CHAN_STATUS_AUTO_DL; - else // create the entry. No particular risk with that. - { - mChannelStatus[chId] = 0 ; - autoDl = false ; - } - return true; -} - -/***************************************************************************************/ -/****************** Event Feedback (Overloaded form p3distrib) *************************/ -/***************************************************************************************/ -/* only download in the first week of channel - * older stuff can be manually downloaded. - */ - -const uint32_t DOWNLOAD_PERIOD = 7 * 24 * 3600; - -/* This is called when we receive a msg, and also recalled - * on a subscription to a channel.. - */ - -bool p3Channels::locked_eventDuplicateMsg(GroupInfo *grp, RsDistribMsg *msg, const std::string& id, bool /*historical*/) -{ - std::string grpId = msg->grpId; - std::string msgId = msg->msgId; - std::string nullId; - - - RsChannelMsg *chanMsg = dynamic_cast(msg); - if (!chanMsg) - { - return true; - } - - // return if msg has d download already - - statMap MsgMap; - statMap::iterator mit1, mit2; - std::list::iterator lit = mReadStatus.begin(); - - for(;lit != mReadStatus.end();lit++){ - - if((*lit)->channelId == grpId) - break; - } - - mit2 = mChannelStatus.find(grpId); - - if(mit2 != mChannelStatus.end()) - { - if(!(mit2->second & RS_CHAN_STATUS_AUTO_DL)){ - - if(lit != mReadStatus.end()){ - - if(( mit1=(*lit)->msgReadStatus.find(msgId)) != (*lit)->msgReadStatus.end()) - (*lit)->msgReadStatus[msgId] |= (CHANNEL_MSG_STATUS_MASK & CHANNEL_MSG_STATUS_DOWLOADED); - - } - return false; - } - } - - if(lit != mReadStatus.end()){ - - if(( mit1=(*lit)->msgReadStatus.find(msgId)) != (*lit)->msgReadStatus.end()){ - if(mit1->second & CHANNEL_MSG_STATUS_DOWLOADED) - return false; - }else{ - // create an entry for msg id - (*lit)->msgReadStatus[msgId] = ~CHANNEL_MSG_STATUS_MASK; - } - } - - - - /* request the files - * NB: This will result in duplicates. - * it is upto ftserver/ftcontroller/ftextralist to handle this! - * */ - - bool download = (grp->flags & RS_DISTRIB_SUBSCRIBED); - - if (id == mOwnId) - { - download = false; -#ifdef CHANNEL_DEBUG - std::cerr << "p3Channels::locked_eventDuplicateMsg() msg from self - not downloading"; - std::cerr << std::endl; -#endif - } - - /* check subscribed */ - if (!download) - { - return true; - } - - /* check age */ - time_t age = time(NULL) - msg->timestamp; - - if (age > (time_t)DOWNLOAD_PERIOD ) - { - return true; - } - - // get channel info to determine if channel is private or not - ChannelInfo cInfo; - bool chanPrivate = false; - - // tho if empty don't bother - if(!chanMsg->attachment.items.empty()){ - - - if(grp->flags & RS_DISTRIB_PRIVATE) - chanPrivate = true; - } - - /* Iterate through files */ - std::list::iterator fit; - for(fit = chanMsg->attachment.items.begin(); fit != chanMsg->attachment.items.end(); fit++) - { - std::string fname = fit->name; - std::string hash = fit->hash; - uint64_t size = fit->filesize; - std::string channelname = grpId; - - std::string localpath; - TransferRequestFlags flags; - - // send to download directory if file is private - // We also add explicit sources only if the channel is private. Otherwise we DL in network wide mode - // using anonymous tunnels. - // - std::list srcIds; - - if(chanPrivate) - { - localpath = mChannelsDir; - flags = RS_FILE_REQ_BACKGROUND | RS_FILE_REQ_EXTRA; - - srcIds.push_back(id); - } - else - { - if(mDestinationDirectories.find(grpId) != mDestinationDirectories.end()) - localpath = mDestinationDirectories[grpId] ; - else - localpath = ""; // forces dl to default directory - - flags = RS_FILE_REQ_BACKGROUND | RS_FILE_REQ_ANONYMOUS_ROUTING; - } - - /* download it ... and flag for ExtraList - * don't do pre-search check as FileRequest does it better - * - * FileRequest will ignore request if file is already indexed. - */ - -#ifdef CHANNEL_DEBUG - std::cerr << "p3Channels::locked_eventDuplicateMsg() " << " Downloading: " << fname; - std::cerr << " to: " << localpath << " from: " << id << std::endl; -#endif - - if(size < MAX_AUTO_DL) - mRsFiles->FileRequest(fname, hash, size, localpath, flags, srcIds); - } - - if(lit != mReadStatus.end()){ - - (*lit)->msgReadStatus[msgId] |= (CHANNEL_MSG_STATUS_MASK & - CHANNEL_MSG_STATUS_DOWLOADED); - - } - - IndicateConfigChanged(); - - return true; -} - -#include "pqi/pqinotify.h" - -bool p3Channels::locked_eventNewMsg(GroupInfo *grp, RsDistribMsg *msg, const std::string& id, bool historical) -{ - std::string grpId = msg->grpId; - std::string msgId = msg->msgId; - std::string nullId; - - if (!historical) - { - getPqiNotify()->AddFeedItem(RS_FEED_ITEM_CHAN_MSG, grpId, msgId, nullId); - } - - /* request the files - * NB: This could result in duplicates. - * which must be handled by ft side. - * - * this is exactly what DuplicateMsg does. - * */ - return locked_eventDuplicateMsg(grp, msg, id, historical); -} - -void p3Channels::locked_notifyGroupChanged(GroupInfo &grp, uint32_t flags, bool historical) -{ - std::string grpId = grp.grpId; - std::string msgId; - std::string nullId; - - - switch(flags) - { - case GRP_NEW_UPDATE: - #ifdef CHANNEL_DEBUG - std::cerr << "p3Channels::locked_notifyGroupChanged() NEW UPDATE" << std::endl; - #endif - if (!historical) - { - getPqiNotify()->AddFeedItem(RS_FEED_ITEM_CHAN_NEW, grpId, msgId, nullId); - } - rsicontrol->getNotify().notifyListChange(NOTIFY_LIST_CHANNELLIST_LOCKED, NOTIFY_TYPE_ADD); - break; - case GRP_UPDATE: - #ifdef CHANNEL_DEBUG - std::cerr << "p3Channels::locked_notifyGroupChanged() UPDATE" << std::endl; - #endif - if (!historical) - { - getPqiNotify()->AddFeedItem(RS_FEED_ITEM_CHAN_UPDATE, grpId, msgId, nullId); - } - rsicontrol->getNotify().notifyListChange(NOTIFY_LIST_CHANNELLIST_LOCKED, NOTIFY_TYPE_MOD); - break; - case GRP_LOAD_KEY: - #ifdef CHANNEL_DEBUG - std::cerr << "p3Channels::locked_notifyGroupChanged() LOAD_KEY" << std::endl; - #endif - break; - case GRP_NEW_MSG: - #ifdef CHANNEL_DEBUG - std::cerr << "p3Channels::locked_notifyGroupChanged() NEW MSG" << std::endl; - #endif - rsicontrol->getNotify().notifyListChange(NOTIFY_LIST_CHANNELLIST_LOCKED, NOTIFY_TYPE_ADD); - break; - case GRP_SUBSCRIBED: - #ifdef CHANNEL_DEBUG - std::cerr << "p3Channels::locked_notifyGroupChanged() SUBSCRIBED" << std::endl; - #endif - { - std::string channeldir = mChannelsDir + "/" + grpId; - #ifdef CHANNEL_DEBUG - std::cerr << "p3Channels::locked_notifyGroupChanged() creating directory: " << channeldir << std::endl; - #endif - - /* create chanDir */ - if (!RsDirUtil::checkCreateDirectory(channeldir)) { - std::cerr << "p3Channels::locked_notifyGroupChanged() Failed to create Channels Directory: " << channeldir << std::endl; - } - - /* check if downloads need to be started? */ - } - - rsicontrol->getNotify().notifyListChange(NOTIFY_LIST_CHANNELLIST_LOCKED, NOTIFY_TYPE_ADD); - break; - case GRP_UNSUBSCRIBED: - #ifdef CHANNEL_DEBUG - std::cerr << "p3Channels::locked_notifyGroupChanged() UNSUBSCRIBED" << std::endl; - #endif - rsicontrol->getNotify().notifyListChange(NOTIFY_LIST_CHANNELLIST_LOCKED, NOTIFY_TYPE_DEL); - - /* won't stop downloads... */ - - break; - - default: - std::cerr << "p3Channels::locked_notifyGroupChanged() Unknown DEFAULT" << std::endl; - break; - } - - return p3GroupDistrib::locked_notifyGroupChanged(grp, flags, historical); -} - - -//TODO: if you want to config saving and loading for channel distrib service implement this method further -bool p3Channels::childLoadList(std::list& configSaves) -{ - RsChannelReadStatus* drs = NULL; - RsChannelDestDirConfigItem *dd = NULL ; - - for(std::list::iterator it = configSaves.begin(); it != configSaves.end(); it++) - { - if(NULL != (drs = dynamic_cast(*it))) - processChanReadStatus(drs); // don't delete, since it's used later on. - else if(NULL != (dd = dynamic_cast(*it))) - { - mDestinationDirectories.clear() ; - - for(uint32_t i=0;idest_dirs.size();++i) - { - mDestinationDirectories[dd->dest_dirs[i].first] = dd->dest_dirs[i].second ; - - std::cerr << "p3Channels: setDestination directory or ChId " << dd->dest_dirs[i].first << " to " << dd->dest_dirs[i].second <channelId; - - statMap::iterator sit = drs->msgReadStatus.find(chId); - - if(sit != drs->msgReadStatus.end()){ - mChannelStatus[chId] = sit->second; - } - - // first pull out the channel id status - - mMsgReadStatus[drs->channelId] = drs->msgReadStatus; - mReadStatus.push_back(drs); - - saveList.push_back(drs); -} - -std::list p3Channels::childSaveList() -{ - std::list::iterator lit = mReadStatus.begin(); - statMap::iterator sit, mit; - - // update or add current channel id status - for(; lit != mReadStatus.end(); lit++) - { - if((sit = mChannelStatus.find((*lit)->channelId)) != mChannelStatus.end()) - { - mit = (*lit)->msgReadStatus.find((*lit)->channelId); - if(mit != (*lit)->msgReadStatus.end()) - { - mit->second = sit->second; - } - else - { - (*lit)->msgReadStatus[(*lit)->channelId] = sit->second; - } - } - } - - // Make a copy of saveList and add additional items we want to save. - // - std::list to_return = saveList ; - RsChannelDestDirConfigItem *dd = new RsChannelDestDirConfigItem ; - - for(std::map::const_iterator it(mDestinationDirectories.begin());it!=mDestinationDirectories.end();++it) - dd->dest_dirs.push_back(*it) ; - - to_return.push_back(dd) ; - - return to_return; -} - -/****************************************/ diff --git a/libretroshare/src/services/p3channels.h b/libretroshare/src/services/p3channels.h deleted file mode 100644 index 59ca4bb71..000000000 --- a/libretroshare/src/services/p3channels.h +++ /dev/null @@ -1,130 +0,0 @@ -#ifndef RS_P3_CHANNELS_INTERFACE_H -#define RS_P3_CHANNELS_INTERFACE_H - -/* - * libretroshare/src/services: p3channels.h - * - * RetroShare C++ Interface. - * - * Copyright 2008 by Robert Fernie. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License Version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 - * USA. - * - * Please report all bugs and problems to "retroshare@lunamutt.com". - * - */ - -#include "retroshare/rschannels.h" -#include "retroshare/rsfiles.h" -#include "distrib/p3distrib.h" - -#include "serialiser/rstlvtypes.h" -#include "serialiser/rschannelitems.h" - -#define RS_CHAN_STATUS_MASK 0x000f -#define RS_CHAN_STATUS_AUTO_DL 0x0002 - -typedef std::map statMap; -typedef std::map chanStatMap; - -//! Channels is a distributed 'feed' service -/*! - * Implementations of rschannels interface - * @see RsChannels for definition of implemented interface - */ -class p3Channels: public p3GroupDistrib, public RsChannels -{ - public: - - p3Channels(uint16_t type, CacheStrapper *cs, CacheTransfer *cft, RsFiles *files, - std::string srcdir, std::string storedir, std::string channelsdir); -virtual ~p3Channels(); - -/*! - * cleans up dowloaded files older than one month, - * should be called during shutdown of rs - */ -void cleanUpOldFiles(); - -/****************************************/ -/********* rsChannels Interface ***********/ - -virtual bool channelsChanged(std::list &chanIds); - -virtual std::string createChannel(std::wstring chanName, std::wstring chanDesc, uint32_t chanFlags, - unsigned char* pngImageData, uint32_t size); - -virtual bool getChannelInfo(const std::string &cId, ChannelInfo &ci); -virtual bool getChannelList(std::list &chanList); -virtual bool getChannelMsgList(const std::string &cId, std::list &msgs); -virtual bool getChannelMessage(const std::string &cId, const std::string &mId, ChannelMsgInfo &msg); - -virtual bool ChannelMessageSend(ChannelMsgInfo &info); -virtual bool setMessageStatus(const std::string& cId, const std::string& mId, const uint32_t status, const uint32_t statusMask); -virtual bool getMessageStatus(const std::string& cId, const std::string& mId, uint32_t& status); - -virtual bool getMessageCount(const std::string &cId, unsigned int &newCount, unsigned int &unreadCount); -virtual bool channelSubscribe(const std::string &cId, bool subscribe, bool autoDl); -virtual bool channelExtraFileHash(const std::string &path, const std::string &chId, FileInfo& fInfo); -virtual bool channelExtraFileRemove(const std::string &hash, const std::string &chId); -virtual bool channelRestoreKeys(const std::string &chId); -virtual bool channelShareKeys(const std::string &chId, std::list& peers); -virtual bool channelEditInfo(const std::string &chId, ChannelInfo &ci); -virtual void getPubKeysAvailableGrpIds(std::list& grpIds); -virtual bool channelSetAutoDl(const std::string& chId, bool autoDl); -virtual bool channelGetAutoDl(const std::string& chId, bool& autoDl); -virtual bool channelSetDestinationDirectory(const std::string& chId,const std::string& dest_dir) ; - -/***************************************************************************************/ -/****************** Event Feedback (Overloaded form p3distrib) *************************/ -/***************************************************************************************/ - - protected: -virtual void locked_notifyGroupChanged(GroupInfo &info, uint32_t flags, bool historical); -virtual bool locked_eventNewMsg(GroupInfo *, RsDistribMsg *, const std::string&, bool historical); -virtual bool locked_eventDuplicateMsg(GroupInfo *, RsDistribMsg *, const std::string&, bool historical); - - -/****************************************/ -/********* Overloaded Functions *********/ - -virtual RsSerialType *createSerialiser(); - -virtual bool locked_checkDistribMsg(RsDistribMsg *msg); - -virtual bool childLoadList(std::list& configSaves); -virtual std::list childSaveList(); - - -/****************************************/ - - private: - -void processChanReadStatus(RsChannelReadStatus* drs); -void addChannelReadStatusEntry(const std::string& cId); -void removeChannelReadStatusEntry(const std::string& cId); - RsFiles *mRsFiles; - std::string mChannelsDir; - std::list saveList; - - std::list mReadStatus; - - chanStatMap mMsgReadStatus; - statMap mChannelStatus; - std::map mDestinationDirectories ; -}; - - -#endif diff --git a/libretroshare/src/services/p3forums.cc b/libretroshare/src/services/p3forums.cc deleted file mode 100644 index 12dcee700..000000000 --- a/libretroshare/src/services/p3forums.cc +++ /dev/null @@ -1,818 +0,0 @@ -/* - * libretroshare/src/services: rsforums.cc - * - * RetroShare C++ Interface. - * - * Copyright 2007-2008 by Robert Fernie. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License Version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 - * USA. - * - * Please report all bugs and problems to "retroshare@lunamutt.com". - * - */ - -#include "services/p3forums.h" -#include "pqi/authssl.h" -#include "util/rsdir.h" -#include "retroshare/rsiface.h" - -uint32_t convertToInternalFlags(uint32_t extFlags); -uint32_t convertToExternalFlags(uint32_t intFlags); - -std::ostream &operator<<(std::ostream &out, const ForumInfo &info) -{ - std::string name(info.forumName.begin(), info.forumName.end()); - std::string desc(info.forumDesc.begin(), info.forumDesc.end()); - - out << "ForumInfo:"; - out << std::endl; - out << "ForumId: " << info.forumId << std::endl; - out << "ForumName: " << name << std::endl; - out << "ForumDesc: " << desc << std::endl; - out << "ForumFlags: " << info.forumFlags << std::endl; - out << "Pop: " << info.pop << std::endl; - out << "LastPost: " << info.lastPost << std::endl; - - return out; -} - -std::ostream &operator<<(std::ostream &out, const ThreadInfoSummary &/*info*/) -{ - out << "ThreadInfoSummary:"; - out << std::endl; - //out << "ForumId: " << forumId << std::endl; - //out << "ThreadId: " << threadId << std::endl; - - return out; -} - -std::ostream &operator<<(std::ostream &out, const ForumMsgInfo &/*info*/) -{ - out << "ForumMsgInfo:"; - out << std::endl; - //out << "ForumId: " << forumId << std::endl; - //out << "ThreadId: " << threadId << std::endl; - - return out; -} - - -RsForums *rsForums = NULL; - - -/* Forums will be initially stored for 1 year - * remember 2^16 = 64K max units in store period. - * PUBPERIOD * 2^16 = max STORE PERIOD */ -#define FORUM_STOREPERIOD (365*24*3600) /* 365 * 24 * 3600 - secs in a year */ -#define FORUM_PUBPERIOD 600 /* 10 minutes ... (max = 455 days) */ - -p3Forums::p3Forums(uint16_t type, CacheStrapper *cs, CacheTransfer *cft, - std::string srcdir, std::string storedir, std::string forumDir) - :p3GroupDistrib(type, cs, cft, srcdir, storedir, forumDir, - CONFIG_TYPE_FORUMS, FORUM_STOREPERIOD, FORUM_PUBPERIOD), - mForumsDir(forumDir) -{ - - /* create chanDir */ - if (!RsDirUtil::checkCreateDirectory(mForumsDir)) { - std::cerr << "p3Channels() Failed to create forums Directory: " << mForumsDir << std::endl; - } - - return; -} - -p3Forums::~p3Forums() -{ - return; -} - -/****************************************/ - -bool p3Forums::forumsChanged(std::list &forumIds) -{ - return groupsChanged(forumIds); -} - -bool p3Forums::getForumInfo(const std::string &fId, ForumInfo &fi) -{ - RsStackMutex stack(distribMtx); /***** STACK LOCKED MUTEX *****/ - - /* extract details */ - GroupInfo *gi = locked_getGroupInfo(fId); - - if (!gi) - return false; - - fi.forumId = gi->grpId; - fi.forumName = gi->grpName; - fi.forumDesc = gi->grpDesc; - fi.forumFlags = gi->grpFlags; - - fi.subscribeFlags = gi->flags; - - fi.pop = gi->sources.size(); - fi.lastPost = gi->lastPost; - - return true; -} - -/*! - * allows peers to change information for the forum: - * can only change name and descriptions - * - */ -bool p3Forums::setForumInfo(const std::string &fId, ForumInfo &fi) -{ - GroupInfo gi; - - RsStackMutex stack(distribMtx); - - gi.grpName = fi.forumName; - gi.grpDesc = fi.forumDesc; - - return locked_editGroup(fId, gi); - } - -bool p3Forums::getForumList(std::list &forumList) -{ - std::list grpIds; - std::list::iterator it; - - getAllGroupList(grpIds); - - for(it = grpIds.begin(); it != grpIds.end(); it++) - { - ForumInfo fi; - if (getForumInfo(*it, fi)) - { - forumList.push_back(fi); - } - } - return true; -} - -bool p3Forums::getForumThreadList(const std::string &fId, std::list &msgs) -{ - std::list msgIds; - std::list::iterator it; - - getParentMsgList(fId, "", msgIds); - - std::list msgDummyIds; - getDummyParentMsgList(fId, "", msgDummyIds); - - RsStackMutex stack(distribMtx); /***** STACK LOCKED MUTEX *****/ - for(it = msgIds.begin(); it != msgIds.end(); it++) - { - /* get details */ - RsDistribMsg *msg = locked_getGroupMsg(fId, *it); - RsForumMsg *fmsg = dynamic_cast(msg); - if (!fmsg) - continue; - - ThreadInfoSummary tis; - - tis.forumId = msg->grpId; - tis.msgId = msg->msgId; - tis.parentId = ""; // always NULL (see request) - tis.threadId = msg->msgId; // these are the thread heads! - - tis.ts = msg->timestamp; - tis.childTS = msg->childTS; - - /* the rest must be gotten from the derived Msg */ - - tis.title = fmsg->title; - tis.msg = fmsg->msg; - - msgs.push_back(tis); - } - - // now add dummy msgs. - for(it = msgDummyIds.begin(); it != msgDummyIds.end(); it++) - { - /* get details */ - RsDistribDummyMsg *msg = locked_getGroupDummyMsg(fId, *it); - ThreadInfoSummary tis; - - tis.forumId = fId; - tis.msgId = msg->msgId; - tis.parentId = ""; // always NULL (see request) - tis.threadId = msg->msgId; // these are the thread heads! - - tis.ts = msg->timestamp; - tis.childTS = msg->childTS; - - /* dummy msg */ - tis.title = L"[ ... Missing Message ... ]"; - tis.msg = L"Placeholder for missing Message"; - tis.msgflags |= RS_DISTRIB_MISSING_MSG; - - msgs.push_back(tis); - } - - return true; -} - -bool p3Forums::getForumThreadMsgList(const std::string &fId, const std::string &pId, std::list &msgs) -{ - std::list msgIds; - std::list::iterator it; - - getParentMsgList(fId, pId, msgIds); - - std::list msgDummyIds; - getDummyParentMsgList(fId, pId, msgDummyIds); - - RsStackMutex stack(distribMtx); /***** STACK LOCKED MUTEX *****/ - for(it = msgIds.begin(); it != msgIds.end(); it++) - { - /* get details */ - RsDistribMsg *msg = locked_getGroupMsg(fId, *it); - RsForumMsg *fmsg = dynamic_cast(msg); - if (!fmsg) - continue; - - ThreadInfoSummary tis; - - tis.forumId = msg->grpId; - tis.msgId = msg->msgId; - tis.parentId = msg->parentId; - tis.threadId = msg->threadId; - - tis.ts = msg->timestamp; - tis.childTS = msg->childTS; - - /* the rest must be gotten from the derived Msg */ - - tis.title = fmsg->title; - tis.msg = fmsg->msg; - - if (fmsg->personalSignature.keyId.empty() == false) { - tis.msgflags |= RS_DISTRIB_AUTHEN_REQ; - } - - msgs.push_back(tis); - } - - // now add dummy msgs. - for(it = msgDummyIds.begin(); it != msgDummyIds.end(); it++) - { - /* get details */ - RsDistribDummyMsg *msg = locked_getGroupDummyMsg(fId, *it); - ThreadInfoSummary tis; - - tis.forumId = fId; - tis.msgId = msg->msgId; - tis.parentId = msg->parentId; - tis.threadId = msg->threadId; - - tis.ts = msg->timestamp; - tis.childTS = msg->childTS; - - /* dummy msg */ - tis.title = L"[ ... Missing Message ... ]"; - tis.msg = L"Placeholder for missing Message"; - tis.msgflags |= RS_DISTRIB_MISSING_MSG; - - msgs.push_back(tis); - } - return true; -} - -bool p3Forums::getForumMessage(const std::string &fId, const std::string &mId, ForumMsgInfo &info) -{ - processCacheOptReq(fId); - - RsStackMutex stack(distribMtx); /***** STACK LOCKED MUTEX *****/ - - RsDistribMsg *msg = locked_getGroupMsg(fId, mId); - RsForumMsg *fmsg = dynamic_cast(msg); - if (!fmsg) - { - /* try for a dummy msg */ - RsDistribDummyMsg *dmsg = locked_getGroupDummyMsg(fId, mId); - if (!dmsg) - return false; - - /* fill in the dummy msg */ - info.forumId = fId; - info.msgId = dmsg->msgId; - info.parentId = dmsg->parentId; - info.threadId = dmsg->threadId; - - info.ts = dmsg->timestamp; - info.childTS = dmsg->childTS; - - info.title = L"[ ... Missing Message ... ]"; - info.msg = L"Placeholder for missing Message"; - info.msgflags |= RS_DISTRIB_MISSING_MSG; - - info.srcId = ""; - - return true; - } - - info.forumId = msg->grpId; - info.msgId = msg->msgId; - info.parentId = msg->parentId; - info.threadId = msg->threadId; - - info.ts = msg->timestamp; - info.childTS = msg->childTS; - - /* the rest must be gotten from the derived Msg */ - - info.title = fmsg->title; - info.msg = fmsg->msg; - // should only use actual signature .... - //info.srcId = fmsg->srcId; - info.srcId = fmsg->personalSignature.keyId; - - if (fmsg->personalSignature.keyId.empty() == false) { - info.msgflags |= RS_DISTRIB_AUTHEN_REQ; - } - - return true; -} - -bool p3Forums::ForumMessageSend(ForumMsgInfo &info) -{ - bool signIt = (info.msgflags == RS_DISTRIB_AUTHEN_REQ); - - std::string mId = createForumMsg(info.forumId, info.parentId, - info.title, info.msg, signIt); - - if (mId.empty()) { - return false; - } - - // return id - info.msgId = mId; - - return setMessageStatus(info.forumId, mId, FORUM_MSG_STATUS_READ, FORUM_MSG_STATUS_MASK); -} - -bool p3Forums::setMessageStatus(const std::string& fId,const std::string& mId,const uint32_t status, const uint32_t statusMask) -{ - bool changed = false; - uint32_t newStatus = 0; - - { - RsStackMutex stack(distribMtx); /***** STACK LOCKED MUTEX *****/ - - std::map::iterator mit = mReadStatus.find(fId); - if (mit != mReadStatus.end()) - { - RsForumReadStatus* rsi = mit->second; - uint32_t oldStatus = rsi->msgReadStatus[mId]; - rsi->msgReadStatus[mId] &= ~statusMask; - rsi->msgReadStatus[mId] |= (status & statusMask); - - newStatus = rsi->msgReadStatus[mId]; - if (oldStatus != newStatus) { - changed = true; - } - } else { - // if forum id does not exist create one - RsForumReadStatus* rsi = new RsForumReadStatus(); - rsi->forumId = fId; - rsi->msgReadStatus[mId] = status & statusMask; - mReadStatus[fId] = rsi; - mSaveList.push_back(rsi); - - newStatus = rsi->msgReadStatus[mId]; - changed = true; - } - - IndicateConfigChanged(); - } /******* UNLOCKED ********/ - - if (changed) { - rsicontrol->getNotify().notifyListChange(NOTIFY_LIST_FORUMLIST_LOCKED, NOTIFY_TYPE_MOD); - rsicontrol->getNotify().notifyForumMsgReadSatusChanged(fId, mId, newStatus); - } - - return true; -} - -bool p3Forums::getMessageStatus(const std::string& fId, const std::string& mId, uint32_t& status) -{ - status = 0; - - RsStackMutex stack(distribMtx); - - std::map::iterator fit = mReadStatus.find(fId); - - if (fit == mReadStatus.end()) - { - return false; - } - - std::map::iterator rit = fit->second->msgReadStatus.find(mId); - - if(rit != fit->second->msgReadStatus.end()) - { - status = rit->second; - return true; - } - - return false; -} - -bool p3Forums::forumRestoreKeys(const std::string& fIds) -{ - return p3GroupDistrib::restoreGrpKeys(fIds); -} - - -std::string p3Forums::createForum(const std::wstring &forumName, const std::wstring &forumDesc, uint32_t forumFlags) -{ - - std::string id = createGroup(forumName, forumDesc, - convertToInternalFlags(forumFlags), NULL, 0); - - return id; -} - -std::string p3Forums::createForumMsg(std::string fId, std::string pId, - std::wstring title, std::wstring msg, bool signIt) -{ - - RsForumMsg *fmsg = new RsForumMsg(); - fmsg->grpId = fId; - fmsg->parentId = pId; - processCacheOptReq(fId); - - { - RsStackMutex stack(distribMtx); /***** STACK LOCKED MUTEX *****/ - - RsDistribMsg *msg = locked_getGroupMsg(fId, pId); - if (!msg) - { - fmsg->parentId = ""; - fmsg->threadId = ""; - } - else - { - if (msg->parentId == "") - { - fmsg->threadId = fmsg->parentId; - } - else - { - fmsg->threadId = msg->threadId; - } - } - } - - fmsg->title = title; - fmsg->msg = msg; - if (signIt) - { - fmsg->srcId = AuthSSL::getAuthSSL()->OwnId(); - } - fmsg->timestamp = time(NULL); - - std::string msgId = publishMsg(fmsg, signIt); - - if (msgId.empty()) { - delete(fmsg); - } - - return msgId; -} - -RsSerialType *p3Forums::createSerialiser() -{ - return new RsForumSerialiser(); -} - -bool p3Forums::locked_checkDistribMsg(RsDistribMsg */*msg*/) -{ - return true; -} - - -RsDistribGrp *p3Forums::locked_createPublicDistribGrp(GroupInfo &/*info*/) -{ - RsDistribGrp *grp = NULL; //new RsForumGrp(); - - return grp; -} - -RsDistribGrp *p3Forums::locked_createPrivateDistribGrp(GroupInfo &/*info*/) -{ - RsDistribGrp *grp = NULL; //new RsForumGrp(); - - return grp; -} - - -uint32_t convertToInternalFlags(uint32_t extFlags) -{ - return extFlags; -} - -uint32_t convertToExternalFlags(uint32_t intFlags) -{ - return intFlags; -} - -bool p3Forums::forumSubscribe(const std::string &fId, bool subscribe) -{ - return subscribeToGroup(fId, subscribe); -} - -bool p3Forums::getMessageCount(const std::string &fId, unsigned int &newCount, unsigned int &unreadCount) -{ - newCount = 0; - unreadCount = 0; - - std::list grpIds; - - if (fId.empty()) { - // count all messages of all subscribed forums - getAllGroupList(grpIds); - } else { - // count all messages of one forum - grpIds.push_back(fId); - } - - std::list::iterator git; - for (git = grpIds.begin(); git != grpIds.end(); git++) { - std::string fId = *git; - uint32_t grpFlags; - - { - // only flag is needed - RsStackMutex stack(distribMtx); /***** STACK LOCKED MUTEX *****/ - GroupInfo *gi = locked_getGroupInfo(fId); - if (gi == NULL) { - return false; - } - grpFlags = gi->flags; - } /******* UNLOCKED ********/ - - if (grpFlags & (RS_DISTRIB_ADMIN | RS_DISTRIB_SUBSCRIBED)) { - std::list msgIds; - if (getAllMsgList(fId, msgIds)) { - - RsStackMutex stack(distribMtx); /***** STACK LOCKED MUTEX *****/ - - std::map::iterator fit = mReadStatus.find(fId); - if (fit == mReadStatus.end()) { - // no status available -> all messages are new - newCount += msgIds.size(); - unreadCount += msgIds.size(); - continue; - } - - std::list::iterator mit; - for (mit = msgIds.begin(); mit != msgIds.end(); mit++) { - std::map::iterator rit = fit->second->msgReadStatus.find(*mit); - - if (rit == fit->second->msgReadStatus.end()) { - // no status available -> message is new - newCount++; - unreadCount++; - continue; - } - - if (rit->second & FORUM_MSG_STATUS_READ) { - // message is not new - if (rit->second & FORUM_MSG_STATUS_UNREAD_BY_USER) { - // message is unread - unreadCount++; - } - } else { - newCount++; - unreadCount++; - } - } - } /******* UNLOCKED ********/ - } - } - - return true; -} - -/***************************************************************************************/ -/****************** Event Feedback (Overloaded form p3distrib) *************************/ -/***************************************************************************************/ - -#include "pqi/pqinotify.h" - -void p3Forums::locked_notifyGroupChanged(GroupInfo &grp, uint32_t flags, bool historical) -{ - const std::string &grpId = grp.grpId; - std::string msgId; - std::string nullId; - - switch(flags) - { - case GRP_NEW_UPDATE: - if (!historical) - { - getPqiNotify()->AddFeedItem(RS_FEED_ITEM_FORUM_NEW, grpId, msgId, nullId); - } - rsicontrol->getNotify().notifyListChange(NOTIFY_LIST_FORUMLIST_LOCKED, NOTIFY_TYPE_ADD); - break; - case GRP_UPDATE: - if (!historical) - { - getPqiNotify()->AddFeedItem(RS_FEED_ITEM_FORUM_UPDATE, grpId, msgId, nullId); - } - rsicontrol->getNotify().notifyListChange(NOTIFY_LIST_FORUMLIST_LOCKED, NOTIFY_TYPE_MOD); - break; - case GRP_LOAD_KEY: - break; - case GRP_NEW_MSG: - rsicontrol->getNotify().notifyListChange(NOTIFY_LIST_FORUMLIST_LOCKED, NOTIFY_TYPE_ADD); - break; - case GRP_SUBSCRIBED: - rsicontrol->getNotify().notifyListChange(NOTIFY_LIST_FORUMLIST_LOCKED, NOTIFY_TYPE_ADD); - break; - case GRP_UNSUBSCRIBED: - rsicontrol->getNotify().notifyListChange(NOTIFY_LIST_FORUMLIST_LOCKED, NOTIFY_TYPE_DEL); - break; - } - return p3GroupDistrib::locked_notifyGroupChanged(grp, flags, historical); -} - -bool p3Forums::locked_eventDuplicateMsg(GroupInfo */*grp*/, RsDistribMsg */*msg*/, const std::string& /*id*/, bool /*historical*/) -{ - return true; -} - -bool p3Forums::forumShareKeys(std::string fId, std::list& peers) -{ - -#ifdef FORUM_DEBUG - std::cerr << "p3Forums::forumShareKeys() " << fId << std::endl; -#endif - - return sharePubKey(fId, peers); -} - -bool p3Forums::locked_eventNewMsg(GroupInfo */*grp*/, RsDistribMsg *msg, const std::string& /*id*/, bool historical) -{ - std::string grpId = msg->grpId; - std::string msgId = msg->msgId; - std::string nullId; - - if (!historical) - { - getPqiNotify()->AddFeedItem(RS_FEED_ITEM_FORUM_MSG, grpId, msgId, nullId); - } - - return true; -} - - - -/****************************************/ - -void p3Forums::loadDummyData() -{ - ForumInfo fi; - std::string forumId; - std::string msgId; - time_t now = time(NULL); - - fi.forumId = "FID1234"; - fi.forumName = L"Forum 1"; - fi.forumDesc = L"Forum 1"; - fi.forumFlags = RS_DISTRIB_ADMIN; - fi.pop = 2; - fi.lastPost = now - 123; - - forumId = createForum(fi.forumName, fi.forumDesc, fi.forumFlags); - - fi.forumId = "FID2345"; - fi.forumName = L"Forum 2"; - fi.forumDesc = L"Forum 2"; - fi.forumFlags = RS_DISTRIB_SUBSCRIBED; - fi.pop = 3; - fi.lastPost = now - 1234; - - forumId = createForum(fi.forumName, fi.forumDesc, fi.forumFlags); - msgId = createForumMsg(forumId, "", L"WELCOME TO Forum1", L"Hello!", true); - msgId = createForumMsg(forumId, msgId, L"Love this forum", L"Hello2!", true); - - return; - - /* ignore this */ - - fi.forumId = "FID3456"; - fi.forumName = L"Forum 3"; - fi.forumDesc = L"Forum 3"; - fi.forumFlags = 0; - fi.pop = 3; - fi.lastPost = now - 1234; - - forumId = createForum(fi.forumName, fi.forumDesc, fi.forumFlags); - - fi.forumId = "FID4567"; - fi.forumName = L"Forum 4"; - fi.forumDesc = L"Forum 4"; - fi.forumFlags = 0; - fi.pop = 5; - fi.lastPost = now - 1234; - - forumId = createForum(fi.forumName, fi.forumDesc, fi.forumFlags); - - fi.forumId = "FID5678"; - fi.forumName = L"Forum 5"; - fi.forumDesc = L"Forum 5"; - fi.forumFlags = 0; - fi.pop = 1; - fi.lastPost = now - 1234; - - forumId = createForum(fi.forumName, fi.forumDesc, fi.forumFlags); - - fi.forumId = "FID6789"; - fi.forumName = L"Forum 6"; - fi.forumDesc = L"Forum 6"; - fi.forumFlags = 0; - fi.pop = 2; - fi.lastPost = now - 1234; - - forumId = createForum(fi.forumName, fi.forumDesc, fi.forumFlags); - - fi.forumId = "FID7890"; - fi.forumName = L"Forum 7"; - fi.forumDesc = L"Forum 7"; - fi.forumFlags = 0; - fi.pop = 4; - fi.lastPost = now - 1234; - - forumId = createForum(fi.forumName, fi.forumDesc, fi.forumFlags); - - fi.forumId = "FID8901"; - fi.forumName = L"Forum 8"; - fi.forumDesc = L"Forum 8"; - fi.forumFlags = 0; - fi.pop = 3; - fi.lastPost = now - 1234; - - forumId = createForum(fi.forumName, fi.forumDesc, fi.forumFlags); - - fi.forumId = "FID9012"; - fi.forumName = L"Forum 9"; - fi.forumDesc = L"Forum 9"; - fi.forumFlags = 0; - fi.pop = 2; - fi.lastPost = now - 1234; - - forumId = createForum(fi.forumName, fi.forumDesc, fi.forumFlags); - - fi.forumId = "FID9123"; - fi.forumName = L"Forum 10"; - fi.forumDesc = L"Forum 10"; - fi.forumFlags = 0; - fi.pop = 1; - fi.lastPost = now - 1234; - - forumId = createForum(fi.forumName, fi.forumDesc, fi.forumFlags); -} - -std::list p3Forums::childSaveList() -{ - return mSaveList; -} - -bool p3Forums::childLoadList(std::list& configSaves) -{ - RsForumReadStatus* drs = NULL; - std::list::iterator it; - - for(it = configSaves.begin(); it != configSaves.end(); it++) - { - if(NULL != (drs = dynamic_cast(*it))) - { - mReadStatus[drs->forumId] = drs; - mSaveList.push_back(drs); - } - else - { - std::cerr << "p3Forums::childLoadList(): Configs items loaded were incorrect!" - << std::endl; - return false; - } - } - - return true; -} diff --git a/libretroshare/src/services/p3forums.h b/libretroshare/src/services/p3forums.h deleted file mode 100644 index 9a05b22e7..000000000 --- a/libretroshare/src/services/p3forums.h +++ /dev/null @@ -1,105 +0,0 @@ -#ifndef RS_P3_FORUMS_INTERFACE_H -#define RS_P3_FORUMS_INTERFACE_H - -/* - * libretroshare/src/services: p3forums.h - * - * RetroShare C++ Interface. - * - * Copyright 2008 by Robert Fernie. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License Version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 - * USA. - * - * Please report all bugs and problems to "retroshare@lunamutt.com". - * - */ - -#include "retroshare/rsforums.h" -#include "distrib/p3distrib.h" -#include "serialiser/rsforumitems.h" - - - -class p3Forums: public p3GroupDistrib, public RsForums -{ - public: - - p3Forums(uint16_t type, CacheStrapper *cs, CacheTransfer *cft, - std::string srcdir, std::string storedir, std::string forumdir); -virtual ~p3Forums(); - -void loadDummyData(); - -/****************************************/ -/********* rsForums Interface ***********/ - -virtual bool forumsChanged(std::list &forumIds); - -virtual std::string createForum(const std::wstring &forumName, const std::wstring &forumDesc, uint32_t forumFlags); - -virtual bool getForumInfo(const std::string &fId, ForumInfo &fi); -virtual bool setForumInfo(const std::string &fId, ForumInfo &fi); -virtual bool getForumList(std::list &forumList); -virtual bool getForumThreadList(const std::string &fId, std::list &msgs); -virtual bool getForumThreadMsgList(const std::string &fId, const std::string &tId, std::list &msgs); -virtual bool getForumMessage(const std::string &fId, const std::string &mId, ForumMsgInfo &msg); -virtual bool ForumMessageSend(ForumMsgInfo &info); -virtual bool setMessageStatus(const std::string& fId, const std::string& mId, const uint32_t status, const uint32_t statusMask); -virtual bool getMessageStatus(const std::string& fId, const std::string& mId, uint32_t& status); -virtual bool forumRestoreKeys(const std::string& fId); -virtual bool forumShareKeys(std::string fId, std::list& peers); -virtual bool forumSubscribe(const std::string &fId, bool subscribe); - -virtual bool getMessageCount(const std::string &fId, unsigned int &newCount, unsigned int &unreadCount); - -/***************************************************************************************/ -/****************** Event Feedback (Overloaded form p3distrib) *************************/ -/***************************************************************************************/ - -virtual void locked_notifyGroupChanged(GroupInfo &grp, uint32_t flags, bool historical); -virtual bool locked_eventDuplicateMsg(GroupInfo *, RsDistribMsg *, const std::string&, bool historical); -virtual bool locked_eventNewMsg(GroupInfo *, RsDistribMsg *, const std::string&, bool historical); - - -/****************************************/ -/********* Overloaded Functions *********/ - -//virtual RsSerialiser *setupSerialiser(); -//virtual pqistreamer *createStreamer(BinInterface *bio, std::string src, uint32_t bioflags); -virtual RsSerialType *createSerialiser(); - -virtual bool locked_checkDistribMsg(RsDistribMsg *msg); -virtual RsDistribGrp *locked_createPublicDistribGrp(GroupInfo &info); -virtual RsDistribGrp *locked_createPrivateDistribGrp(GroupInfo &info); -virtual bool childLoadList(std::list& ); -virtual std::list childSaveList(); - - -/****************************************/ - -std::string createForumMsg(std::string fId, std::string pId, - std::wstring title, std::wstring msg, bool signIt); - - private: - -std::string mForumsDir; -std::list mSaveList; // store save data - -std::map mReadStatus; - -}; - - -#endif diff --git a/libretroshare/src/services/p3gamelauncher.cc b/libretroshare/src/services/p3gamelauncher.cc deleted file mode 100644 index f2455b5b1..000000000 --- a/libretroshare/src/services/p3gamelauncher.cc +++ /dev/null @@ -1,1313 +0,0 @@ -/* - * libretroshare/src/services: p3gamelauncher.cc - * - * Other Bits for RetroShare. - * - * Copyright 2007-2008 by Robert Fernie. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License Version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 - * USA. - * - * Please report all bugs and problems to "retroshare@lunamutt.com". - * - */ - -#include "services/p3gamelauncher.h" -#include "services/p3gameservice.h" -#include "util/rsdebug.h" -#include "pqi/p3linkmgr.h" -#include - -/* global variable for GUI */ -RsGameLauncher *rsGameLauncher = NULL; - -/***** - * #define GAME_DEBUG 1 - *****/ - -#define TEST_NO_GAMES 1 - -/* So STATEs is always the best way to do things.... - * - * CLIENT: - * ------- - * state: message result - * NULL - * <------- START ----- to INVITED state - * <------- RESUME ----- to INVITED(resume) etc... - * - * INVITED - * ------ INTERESTED -----> to READY state - * ------ REJECT -----> to NULL state - * - * READY - * <------- CONFIRMED ----- to/stay READY (update) - * <------- REJECTED ----- to NULL (abort) - * <------- PLAY ----- to ACTIVE - * - * ---- - * below here the game s setup (game / players / order / etc is defined) - * - * ACTIVE (game play happens). - * <------ PAUSE -----> to NULL - * <------ disconnect ----> to NULL - * <------ QUIT -----> to NULL - * - ******************************************************** - * - * SERVER: - * ------- - * state: message result - * NULL - * ------ START -----> to SETUP state - * - * SETUP - * <----- INTERESTED ------ to SETUP state - * <----- REJECT ------ to SETUP state - * ------ CONFIRMED -----> to SETUP state - * ------ REJECTED -----> to SETUP state - * ------ PLAY -----> to ACTIVE state - * - * ---- - * below here the game s setup (game / players / order / etc is defined) - * - * ACTIVE (game play happens). - * <------- PAUSE ----- to NULL - * ------- disconnect ----- to NULL - * <------- QUIT ----- to NULL - */ - -/* Game Setup States ****/ -const uint32_t RS_GAME_INIT_INVITED = 1; /* Client */ -const uint32_t RS_GAME_INIT_READY = 2; /* Client */ -const uint32_t RS_GAME_INIT_SETUP = 3; /* Server */ -const uint32_t RS_GAME_INIT_CONFIRM = 4; /* Server */ -const uint32_t RS_GAME_INIT_ACTIVE = 5; /* Client/Server */ - - -/* Game Setup Messages ****/ -const uint32_t RS_GAME_MSG_START = 0; /* SERVER->CLIENT */ -const uint32_t RS_GAME_MSG_RESUME = 1; /* SERVER->CLIENT * TODO later */ -const uint32_t RS_GAME_MSG_INTERESTED = 2; /* CLIENT->SERVER */ -const uint32_t RS_GAME_MSG_CONFIRM = 3; /* SERVER->CLIENT */ -const uint32_t RS_GAME_MSG_PLAY = 4; /* SERVER->CLIENT */ -const uint32_t RS_GAME_MSG_PAUSE = 5; /* ANY -> ANY */ -const uint32_t RS_GAME_MSG_QUIT = 6; /* ANY -> ANY */ -const uint32_t RS_GAME_MSG_REJECT = 6; /* ANY -> ANY */ - -const int p3gamezone = 1745; - -p3GameLauncher::p3GameLauncher(p3LinkMgr *lm) - :p3Service(RS_SERVICE_TYPE_GAME_LAUNCHER), - mLinkMgr(lm) -{ -#ifdef GAME_DEBUG - std::cerr << "p3GameLauncher::p3GameLauncher()"; - std::cerr << std::endl; -#endif - - addSerialType(new RsGameSerialiser()); - mOwnId = mLinkMgr->getOwnId(); -} - -int p3GameLauncher::tick() -{ - pqioutput(PQL_DEBUG_BASIC, p3gamezone, - "p3GameLauncher::tick()"); - checkIncoming(); - return 0; -} - -int p3GameLauncher::status() -{ - pqioutput(PQL_DEBUG_BASIC, p3gamezone, - "p3GameLauncher::status()"); - return 1; -} - - -/**** Interface to GUI Game Launcher ****/ - - -/**** GUI Interface ****/ - - -bool p3GameLauncher::resumeGame(std::string) -{ -#ifdef GAME_DEBUG - std::cerr << "p3GameLauncher::resumeGame()"; - std::cerr << std::endl; -#endif - - /* get game details from p3gameService */ - /* add to status reports */ - /* send resume invites to peers in list */ - - return ""; /* TODO */ -} - - -/******************************************************************/ -/******************************************************************/ - /***** EXTERNAL RsGameLauncher Interface *******/ -/******************************************************************/ -/******************************************************************/ - - /* Server commands */ - -std::string p3GameLauncher::createGame(uint32_t gameType, std::wstring name) -{ -#ifdef GAME_DEBUG - std::cerr << "p3GameLauncher::createGame()"; - std::cerr << std::endl; -#endif - - /* translate Id */ - uint16_t srvId = gameType; - - return newGame(srvId, name); -} - -std::string p3GameLauncher::newGame(uint16_t srvId, std::wstring name) -{ -#ifdef GAME_DEBUG - std::cerr << "p3GameLauncher::newGame()"; - std::string tmpname(name.begin(), name.end()); - std::cerr << "srvId: " << srvId << " name: " << tmpname; - std::cerr << std::endl; -#endif - - /* generate GameId (random string) */ - std::string gameId = generateRandomServiceId(); - - gameStatus newGame; - newGame.gameId = gameId; - newGame.serviceId = srvId; - newGame.numPlayers = 0; - newGame.gameName = name; - - newGame.interestedPeers.clear(); - newGame.peerIds.clear(); - newGame.state = RS_GAME_INIT_SETUP; /* Server Only */ - - newGame.areServer = true; - newGame.serverId = mOwnId; - newGame.allowedPeers.push_back(mOwnId); - newGame.interestedPeers.push_back(mOwnId); - newGame.peerIds.push_back(mOwnId); - - /* send messages to peers inviting to game */ - std::list::const_iterator it; - - /* store gameStatus in list */ - gamesCurrent[gameId] = newGame; - - /* return new game Id */ - return gameId; -} - -void p3GameLauncher::cleanupGame(std::string gameId) -{ -#ifdef GAME_DEBUG - std::cerr << "p3GameLauncher::cleanupGame()"; - std::cerr << " gameId: " << gameId; - std::cerr << std::endl; -#endif - - deleteGame(gameId); -} - -bool p3GameLauncher::deleteGame(std::string gameId) -{ -#ifdef GAME_DEBUG - std::cerr << "p3GameLauncher::deleteGame()"; - std::cerr << " gameId: " << gameId; - std::cerr << std::endl; -#endif - - std::map::iterator git; - git = gamesCurrent.find(gameId); - if (git == gamesCurrent.end()) - { - return false; - } - - if (git->second.state != RS_GAME_INIT_SETUP) - { - /* send off quit messages */ - quitGame(gameId); - } - - gamesCurrent.erase(git); - - return true; -} - -bool p3GameLauncher::inviteGame(std::string gameId) -{ -#ifdef GAME_DEBUG - std::cerr << "p3GameLauncher::inviteGame()"; - std::cerr << " gameId: " << gameId; - std::cerr << std::endl; -#endif - - std::map::iterator git; - git = gamesCurrent.find(gameId); - if (git == gamesCurrent.end()) - { - return false; - } - - if (git->second.state != RS_GAME_INIT_SETUP) - { - return false; - } - - /* send messages to peers inviting to game */ - std::list::const_iterator it; - - for(it = git->second.allowedPeers.begin(); - it != git->second.allowedPeers.end(); it++) - { - /* for an invite we need: - * serviceId, gameId, numPlayers.... - */ - if (*it == mOwnId) - { - continue; - } - - RsGameItem *rgi = new RsGameItem(); - rgi->serviceId = git->second.serviceId; - rgi->gameId = git->second.gameId; - rgi->gameComment = git->second.gameName; - rgi->numPlayers = git->second.numPlayers; - rgi->players.ids = git->second.allowedPeers; - - rgi->msg = RS_GAME_MSG_START; - /* destination */ - rgi->PeerId(*it); - - /* send Msg */ - sendItem(rgi); - } - - git->second.state = RS_GAME_INIT_CONFIRM; - - return true; -} - - -/* support Game */ -bool p3GameLauncher::confirmGame(std::string gameId) -{ -#ifdef GAME_DEBUG - std::cerr << "p3GameLauncher::confirmGame()"; - std::cerr << " gameId: " << gameId; - std::cerr << std::endl; -#endif - - - std::map::iterator git; - - git = gamesCurrent.find(gameId); - if (git == gamesCurrent.end()) - { - return false; - } - - /* send messages to peers inviting to game */ - std::list::const_iterator it; - - for(it = git->second.peerIds.begin(); - it != git->second.peerIds.end(); it++) - { - /* for an invite we need: - * serviceId, gameId, numPlayers.... - */ - - if (*it == mOwnId) - { - continue; - } - - RsGameItem *rgi = new RsGameItem(); - rgi->serviceId = git->second.serviceId; - rgi->gameId = git->second.gameId; - rgi->gameComment = git->second.gameName; - rgi->numPlayers = git->second.numPlayers; - rgi->players.ids = git->second.peerIds; - - rgi->msg = RS_GAME_MSG_CONFIRM; - - /* destination */ - rgi->PeerId(*it); - - /* send Msg */ - sendItem(rgi); - } - - return true; -} - - -bool p3GameLauncher::playGame(std::string gameId) -{ -#ifdef GAME_DEBUG - std::cerr << "p3GameLauncher::playGame()"; - std::cerr << " gameId: " << gameId; - std::cerr << std::endl; -#endif - - std::map::iterator git; - - git = gamesCurrent.find(gameId); - if (git == gamesCurrent.end()) - { - return false; - } - - if (git->second.state != RS_GAME_INIT_CONFIRM) - { - return false; - } - - /* send messages to peers inviting to game */ - std::list::const_iterator it; - - for(it = git->second.peerIds.begin(); - it != git->second.peerIds.end(); it++) - { - /* for an invite we need: - * serviceId, gameId, numPlayers.... - */ - - if (*it == mOwnId) - { - continue; - } - - RsGameItem *rgi = new RsGameItem(); - rgi->serviceId = git->second.serviceId; - rgi->gameId = git->second.gameId; - rgi->gameComment = git->second.gameName; - rgi->numPlayers = git->second.numPlayers; - rgi->players.ids = git->second.peerIds; - - rgi->msg = RS_GAME_MSG_PLAY; - - /* destination */ - rgi->PeerId(*it); - - /* send Msg */ - sendItem(rgi); - } - - /* inform all the other peers that we've started the game */ - for(it = git->second.interestedPeers.begin(); - it != git->second.interestedPeers.end(); it++) - { - if (git->second.peerIds.end() == (std::find(git->second.peerIds.begin(), - git->second.peerIds.end(), *it))) - { - /* tell the them they're not needed */ - - RsGameItem *rgi = new RsGameItem(); - rgi->serviceId = git->second.serviceId; - rgi->gameId = git->second.gameId; - rgi->gameComment= git->second.gameName; - rgi->numPlayers = 0; - rgi->players.ids.clear(); - - rgi->msg = RS_GAME_MSG_REJECT; - - /* destination */ - rgi->PeerId(*it); - - /* send Msg */ - sendItem(rgi); - } - } - - /* Finally start the actual Game */ - - /* TODO */ - - - return true; - -} - -bool p3GameLauncher::quitGame(std::string gameId) -{ - /* remove unused parameter warnings */ - (void) gameId; - -#ifdef GAME_DEBUG - std::cerr << "p3GameLauncher::checkGameProperties()"; - std::cerr << " gameId: " << gameId; - std::cerr << std::endl; -#endif - - /* TODO */ - - return false; -} - - - -bool p3GameLauncher::invitePeer(std::string gameId, std::string peerId) -{ -#ifdef GAME_DEBUG - std::cerr << "p3GameLauncher::invitePeer()"; - std::cerr << " gameId: " << gameId << " peerId: " << peerId; - std::cerr << std::endl; -#endif - - std::map::iterator git; - git = gamesCurrent.find(gameId); - if (git == gamesCurrent.end()) - { - return false; - } - - if (git->second.state != RS_GAME_INIT_SETUP) - { - return false; - } - - if (peerId == mOwnId) - { - return false; - } - - /* send messages to peers inviting to game */ - std::list::const_iterator it; - if (git->second.allowedPeers.end() != - (it = std::find(git->second.allowedPeers.begin(), - git->second.allowedPeers.end(), peerId))) - { - return true; - } - - git->second.allowedPeers.push_back(peerId); - return true; -} - - -/* Server GUI commands */ -bool p3GameLauncher::uninvitePeer(std::string gameId, std::string peerId) -{ -#ifdef GAME_DEBUG - std::cerr << "p3GameLauncher::uninvitePeer()"; - std::cerr << " gameId: " << gameId << " peerId: " << peerId; - std::cerr << std::endl; -#endif - - std::map::iterator git; - git = gamesCurrent.find(gameId); - if (git == gamesCurrent.end()) - { - return false; - } - - if (git->second.state != RS_GAME_INIT_SETUP) - { - return false; - } - - if (peerId == mOwnId) - { - return false; - } - - /* send messages to peers inviting to game */ - std::list::iterator it; - if (git->second.allowedPeers.end() == - (it = std::find(git->second.allowedPeers.begin(), - git->second.allowedPeers.end(), peerId))) - { - return true; - } - - git->second.allowedPeers.erase(it); - return true; -} - - -bool p3GameLauncher::confirmPeer(std::string gameId, std::string peerId, - int16_t pos) -{ -#ifdef GAME_DEBUG - std::cerr << "p3GameLauncher::confirmPeer()"; - std::cerr << " gameId: " << gameId << " peerId: " << peerId; - std::cerr << std::endl; -#endif - - std::map::iterator git; - - git = gamesCurrent.find(gameId); - if (git == gamesCurrent.end()) - { - return false; - } - - if (git->second.state != RS_GAME_INIT_CONFIRM) - { - return false; - } - - std::list::iterator it; - if (git->second.interestedPeers.end() == - (it = std::find(git->second.interestedPeers.begin(), - git->second.interestedPeers.end(), peerId))) - { - return false; - } - - it = std::find(git->second.peerIds.begin(), - git->second.peerIds.end(), peerId); - if (it != git->second.peerIds.end()) - { - git->second.peerIds.erase(it); - } - - int32_t i = 0; - for(it = git->second.peerIds.begin(); (i < pos) && - (it != git->second.peerIds.end()); it++, i++) ; - - if ((pos < 0) || (it == git->second.peerIds.end())) - { - /* */ - git->second.peerIds.push_back(peerId); - } - - git->second.peerIds.insert(it, peerId); - return confirmGame(gameId); -} - - -bool p3GameLauncher::unconfirmPeer(std::string gameId, std::string peerId) -{ -#ifdef GAME_DEBUG - std::cerr << "p3GameLauncher::unconfirmPeer()"; - std::cerr << " gameId: " << gameId << " peerId: " << peerId; - std::cerr << std::endl; -#endif - - std::map::iterator git; - - git = gamesCurrent.find(gameId); - if (git == gamesCurrent.end()) - { - return false; - } - - if (git->second.state != RS_GAME_INIT_CONFIRM) - { - return false; - } - - std::list::iterator it; - - it = std::find(git->second.peerIds.begin(), - git->second.peerIds.end(), peerId); - if (it != git->second.peerIds.end()) - { - git->second.peerIds.erase(it); - } - return confirmGame(gameId); -} - - -/* Client GUI Commands */ -bool p3GameLauncher::interestedPeer(std::string gameId) -{ -#ifdef GAME_DEBUG - std::cerr << "p3GameLauncher::interestedPeer()"; - std::cerr << " gameId: " << gameId; - std::cerr << std::endl; -#endif - - return inviteResponse(gameId, true); -} - -bool p3GameLauncher::uninterestedPeer(std::string gameId) -{ -#ifdef GAME_DEBUG - std::cerr << "p3GameLauncher::uninterestedPeer()"; - std::cerr << " gameId: " << gameId; - std::cerr << std::endl; -#endif - - return inviteResponse(gameId, false); -} - -bool p3GameLauncher::inviteResponse(std::string gameId, bool interested) -{ -#ifdef GAME_DEBUG - std::cerr << "p3GameLauncher::inviteResponse()"; - std::cerr << " gameId: " << gameId << "interested: " << interested; - std::cerr << std::endl; -#endif - - std::map::iterator git; - - git = gamesCurrent.find(gameId); - if (git == gamesCurrent.end()) - { - return 0; - } - - /* TODO */ - - RsGameItem *rgi = new RsGameItem(); - rgi->serviceId = git->second.serviceId; - rgi->gameId = git->second.gameId; - rgi->gameComment= git->second.gameName; - rgi->numPlayers = 0; - rgi->players.ids.clear(); - - if (interested) - { - rgi->msg = RS_GAME_MSG_INTERESTED; - git->second.state = RS_GAME_INIT_READY; - } - else - { - rgi->msg = RS_GAME_MSG_REJECT; - git->second.state = RS_GAME_INIT_INVITED; - } - - /* destination */ - rgi->PeerId(git->second.serverId); - - /* send Msg */ - sendItem(rgi); - - return 1; -} - - -/***** Details ****/ - -/* get details */ -bool p3GameLauncher::getGameList(std::list &gameList) -{ -#ifdef GAME_DEBUG - std::cerr << "p3GameLauncher::getGameList()"; - std::cerr << std::endl; -#endif - - std::map::iterator git; - for(git = gamesCurrent.begin(); git != gamesCurrent.end(); git++) - { - RsGameInfo info; - - info.gameId = git->first; - info.serverId = git->second.serverId; - - rs_sprintf(info.gameType, "GameType: %lu", git->second.serviceId); - - info.serverName = "ServerName"; - info.numPlayers = git->second.numPlayers; - info.gameName = git->second.gameName; - - if (git->second.state == RS_GAME_INIT_SETUP) - { - info.status = "Setup"; - } - else if (git->second.state == RS_GAME_INIT_INVITED) - { - info.status = "Invite"; - } - else if (git->second.state == RS_GAME_INIT_CONFIRM) - { - info.status = "Confirm"; - } - else if (git->second.state == RS_GAME_INIT_READY) - { - info.status = "Ready"; - } - else if (git->second.state == RS_GAME_INIT_ACTIVE) - { - info.status = "Playing"; - } - else - { - info.status = "Unknown"; - } - - gameList.push_back(info); - } - return true; -} - -bool p3GameLauncher::getGameDetail(std::string gameId, RsGameDetail &detail) -{ -#ifdef GAME_DEBUG - std::cerr << "p3GameLauncher::getGameDetail()"; - std::cerr << " gameId: " << gameId; - std::cerr << std::endl; -#endif - - std::map::iterator git; - std::list::iterator it; - git = gamesCurrent.find(gameId); - if (git == gamesCurrent.end()) - { - return false; - } - - /* fill in the details */ - detail.gameId = gameId; - detail.gameType = git->second.serviceId; - detail.gameName = git->second.gameName; - detail.areServer = git->second.areServer; - detail.serverId = git->second.serverId; - detail.serverName = "Server???"; - detail.numPlayers = git->second.numPlayers; - - if ((git->second.state == RS_GAME_INIT_SETUP) || - (git->second.state == RS_GAME_INIT_INVITED)) - { - if (git->second.state == RS_GAME_INIT_SETUP) - detail.status = "Setup"; - else - detail.status = "Invite"; - - /* copy from invited List */ - for(it = git->second.allowedPeers.begin(); - it != git->second.allowedPeers.end(); it++) - { - RsGamePeer rgp; - rgp.id = *it; - rgp.invite = true; - rgp.interested = false; - rgp.play = false; - - detail.gamers[*it] = rgp; - } - } - else if ((git->second.state == RS_GAME_INIT_CONFIRM) || - (git->second.state == RS_GAME_INIT_READY)) - { - if (git->second.state == RS_GAME_INIT_CONFIRM) - detail.status = "Confirm"; - else - detail.status = "Ready"; - - /* copy from invited List */ - for(it = git->second.allowedPeers.begin(); - it != git->second.allowedPeers.end(); it++) - { - RsGamePeer rgp; - rgp.id = *it; - rgp.invite = true; - - if (git->second.interestedPeers.end() != - std::find(git->second.interestedPeers.begin(), - git->second.interestedPeers.end(), - *it)) - { - rgp.interested = true; - } - else - { - rgp.interested = false; - } - /* if in peerIds */ - if (git->second.peerIds.end() != - std::find(git->second.peerIds.begin(), - git->second.peerIds.end(), - *it)) - { - rgp.play = true; - } - else - { - rgp.play = false; - } - detail.gamers[*it] = rgp; - } - - - } - else if (git->second.state == RS_GAME_INIT_ACTIVE) - { - detail.status = "Playing"; - - /* copy from invited List */ - for(it = git->second.peerIds.begin(); - it != git->second.peerIds.end(); it++) - { - RsGamePeer rgp; - rgp.id = *it; - rgp.invite = true; - rgp.interested = true; - rgp.play = true; - - detail.gamers[*it] = rgp; - } - } - else - { - return false; - } - return true; -} - - -/**** Network interface ****/ - -int p3GameLauncher::checkIncoming() -{ -#ifdef GAME_DEBUG - std::cerr << "p3GameLauncher::checkIncoming()"; - std::cerr << std::endl; -#endif - - /* check for incoming items */ - - RsGameItem *gi = NULL; - - while(NULL != (gi = (RsGameItem *) recvItem())) - { - handleIncoming(gi); - delete gi; - } - return 1; -} - - -int p3GameLauncher::handleIncoming(RsGameItem *gi) -{ -#ifdef GAME_DEBUG - std::cerr << "p3GameLauncher::handleIncoming()"; - std::cerr << std::endl; -#endif - - /* check that its a valid packet... - * and that there is a gameStatus. - */ - - /* Always check the Properties */ - if (!checkGameProperties(gi->serviceId, gi->numPlayers)) - { -#ifdef GAME_DEBUG - std::cerr << "p3GameLauncher::handleIncoming()"; - std::cerr << std::endl; -#endif - sendRejectMsg(gi); - return 0; - } - - /* check if there is an existing game? */ - std::map::iterator it; - bool haveStatus = (gamesCurrent.end() != - (it = gamesCurrent.find(gi->gameId))); - - /* handle startup first */ - if (!haveStatus) - { - if (gi->msg == RS_GAME_MSG_START) - { - /***** CLIENT HANDLING ****/ - /* we are the client -> start it up! */ - return handleClientStart(gi); - } -#ifdef GAME_DEBUG - std::cerr << "p3GameLauncher::handleIncoming()"; - std::cerr << std::endl; -#endif - sendRejectMsg(gi); - return 0; - } - - /* have a current status - if we get here - * switch on - * 1) server/client. - * 2) state, - * 3) msg. - */ - - if (it->second.areServer) - { -#ifdef GAME_DEBUG - std::cerr << "p3GameLauncher::handleIncoming() AreServer for Game"; - std::cerr << std::endl; -#endif - /***** SERVER HANDLING ****/ - switch(it->second.state) - { - case RS_GAME_INIT_CONFIRM: - /* only accept INTERESTED | REJECT */ - if ((gi->msg == RS_GAME_MSG_INTERESTED) || - (gi->msg == RS_GAME_MSG_REJECT)) - { - handleServerSetup(gi); - return 1; - } - else - { -#ifdef GAME_DEBUG - std::cerr << "p3GameLauncher::handleIncoming()"; - std::cerr << " INIT_CONFIRM & msg != INT | REJ - reject"; - std::cerr << std::endl; -#endif - sendRejectMsg(gi); - return 0; - } - break; - - case RS_GAME_INIT_ACTIVE: - if ((gi->msg == RS_GAME_MSG_PAUSE) || - (gi->msg == RS_GAME_MSG_QUIT)) - { - handleServerActive(gi); - return 1; - } - else - { -#ifdef GAME_DEBUG - std::cerr << "p3GameLauncher::handleIncoming()"; - std::cerr << " INIT_ACTIVE & msg != PAU | QUIT - reject "; - std::cerr << std::endl; -#endif - sendRejectMsg(gi); - return 0; - } - break; - - case RS_GAME_INIT_SETUP: /* invalid state */ - case RS_GAME_INIT_INVITED: /* invalid state */ - case RS_GAME_INIT_READY: /* invalid state */ - default: -#ifdef GAME_DEBUG - std::cerr << "p3GameLauncher::handleIncoming()"; - std::cerr << " INIT_SETUP | INIT_INVITED | INIT_READY | default - reject "; - std::cerr << std::endl; -#endif - sendRejectMsg(gi); - return 0; - break; - } - } - else - { -#ifdef GAME_DEBUG - std::cerr << "p3GameLauncher::handleIncoming() AreClient for Game"; - std::cerr << std::endl; -#endif - /***** CLIENT HANDLING ****/ - switch(it->second.state) - { - case RS_GAME_INIT_INVITED: - /* only accept REJECT */ - if (gi->msg == RS_GAME_MSG_REJECT) - { - handleClientInvited(gi); - return 1; - } - else - { -#ifdef GAME_DEBUG - std::cerr << "p3GameLauncher::handleIncoming()"; - std::cerr << " INIT_INVITED & msg != REJ - reject "; - std::cerr << std::endl; -#endif - sendRejectMsg(gi); - return 0; - } - break; - - case RS_GAME_INIT_READY: - - if ((gi->msg == RS_GAME_MSG_CONFIRM) || - (gi->msg == RS_GAME_MSG_REJECT) || - (gi->msg == RS_GAME_MSG_PLAY)) - { - handleClientReady(gi); - return 1; - } - else - { -#ifdef GAME_DEBUG - std::cerr << "p3GameLauncher::handleIncoming()"; - std::cerr << " INIT_READY & msg != CFM, REJ, PLY - reject "; - std::cerr << std::endl; -#endif - sendRejectMsg(gi); - return 0; - } - break; - - case RS_GAME_INIT_ACTIVE: - if ((gi->msg == RS_GAME_MSG_PAUSE) || - (gi->msg == RS_GAME_MSG_QUIT)) - { - handleClientActive(gi); - return 1; - } - else - { -#ifdef GAME_DEBUG - std::cerr << "p3GameLauncher::handleIncoming()"; - std::cerr << " INIT_ACTIVE & msg != PAU, QUIT - reject "; - std::cerr << std::endl; -#endif - sendRejectMsg(gi); - return 0; - } - break; - - - case RS_GAME_INIT_SETUP: /* invalid state */ - default: -#ifdef GAME_DEBUG - std::cerr << "p3GameLauncher::handleIncoming()"; - std::cerr << " INIT_SETUP - invalid state - reject "; - std::cerr << std::endl; -#endif - sendRejectMsg(gi); - return 0; - break; - } - } - -#ifdef GAME_DEBUG - std::cerr << "p3GameLauncher::handleIncoming() Never Get Here - reject"; - std::cerr << std::endl; -#endif - - /* should never get here */ - sendRejectMsg(gi); - return 0; -} - - - -/***** Network Msg Functions ***** - * - * - * - handleClientStart(gi) * START msg * - handleClientInvited(gi); * REJECT msg * - handleClientReady(gi); * CONFIRM / REJECT / PLAY msg * - handleClientActive(gi); * PAUSE / QUIT msg * - - handleServerSetup(gi); * INTERESTED / REJECT msg * - handleServerActive(gi); * PAUSE / QUIT msg * - sendRejectMsg(gi); - * - * - * - */ - - /* START msg */ -int p3GameLauncher::handleClientStart(RsGameItem *gi) -{ -#ifdef GAME_DEBUG - std::cerr << "p3GameLauncher::handleClientStart()"; - std::cerr << std::endl; -#endif - - /* Already checked existance / Properties */ - - /* else -> add into the list of games */ - gameStatus gs; - gs.serviceId = gi->serviceId; - gs.gameId = gi->gameId; - gs.gameName = gi->gameComment; - gs.areServer = false; - gs.serverId = gi->PeerId(); - gs.state = RS_GAME_INIT_INVITED; /* Client */ - gs.numPlayers = gi->numPlayers; - gs.allowedPeers = gi->players.ids; - //gs.interestedPeers = gi->players.ids; - //gs.peerIds = gi->players.ids; - - gamesCurrent[gi->gameId] = gs; - - return 1; -} - - /* REJECT msg */ -int p3GameLauncher::handleClientInvited(RsGameItem *gi) -{ -#ifdef GAME_DEBUG - std::cerr << "p3GameLauncher::handleClientInvited()"; - std::cerr << std::endl; -#endif - - /* cleanup game */ - cleanupGame(gi->gameId); - return 1; -} - - /* CONFIRM / REJECT / PLAY msg */ -int p3GameLauncher::handleClientReady(RsGameItem *gi) -{ -#ifdef GAME_DEBUG - std::cerr << "p3GameLauncher::handleClientReady()"; - std::cerr << std::endl; -#endif - - /* get game */ - std::map::iterator it; - if (gamesCurrent.end() == (it = gamesCurrent.find(gi->gameId))) - { - /* no game exists */ - return 0; - } - - switch(gi->msg) - { - case RS_GAME_MSG_CONFIRM: - - /* update the information - * (other info should be the same) - */ - it->second.numPlayers = gi->numPlayers; - // Which one? - it->second.interestedPeers = gi->players.ids; - //it->second.peerIds = gi->players.ids; - - return 1; - break; - - case RS_GAME_MSG_REJECT: - cleanupGame(gi->gameId); - return 1; - break; - - case RS_GAME_MSG_PLAY: - /* TODO */ - return 1; - break; - default: - break; - } - return 0; -} - - /* PAUSE / QUIT msg */ -int p3GameLauncher::handleClientActive(RsGameItem */*gi*/) -{ -#ifdef GAME_DEBUG - std::cerr << "p3GameLauncher::handleClientActive()"; - std::cerr << std::endl; -#endif - - - - return 1; -} - - - /* INTERESTED / REJECT msg */ -int p3GameLauncher::handleServerSetup(RsGameItem *gi) -{ -#ifdef GAME_DEBUG - std::cerr << "p3GameLauncher::handleServerSetup()"; - std::cerr << std::endl; -#endif - - /* check if there is an existing game? */ - std::map::iterator it; - if (gamesCurrent.end() == (it = gamesCurrent.find(gi->gameId))) - { - /* no game exists */ - return 0; - } - - /* we only care about this notice -> if we're the server */ - if (it->second.areServer) - { - std::list::iterator it2, it3; - it2 = std::find(it->second.allowedPeers.begin(), - it->second.allowedPeers.end(), gi->PeerId()); - it3 = std::find(it->second.interestedPeers.begin(), - it->second.interestedPeers.end(), gi->PeerId()); - - if ((it2 != it->second.allowedPeers.end()) && - (it3 == it->second.interestedPeers.end())) - { - it->second.interestedPeers.push_back(gi->PeerId()); - return 1; - } - } - return 0; -} - -/* This is a setup update from server - * only updates the players... - */ -int p3GameLauncher::handleServerActive(RsGameItem */*gi*/) -{ -#ifdef GAME_DEBUG - std::cerr << "p3GameLauncher::handleServerActive()"; - std::cerr << std::endl; -#endif - - - return 1; -} - -int p3GameLauncher::sendRejectMsg(RsGameItem *gi) -{ -#ifdef GAME_DEBUG - std::cerr << "p3GameLauncher::sendRejectMsg()"; - std::cerr << std::endl; -#endif - - /* all should be okay ... except msg */ - - RsGameItem *response = new RsGameItem(); - response->serviceId = gi->serviceId; - response->numPlayers = gi->numPlayers; - response->msg = RS_GAME_MSG_REJECT; - response->gameId = gi->gameId; - response->gameComment = gi->gameComment; - response->players.ids = gi->players.ids; - - sendItem(response); - return 1; -} - -bool p3GameLauncher::checkGameProperties(uint16_t serviceId, uint16_t players) -{ -#ifdef GAME_DEBUG - std::cerr << "p3GameLauncher::checkGameProperties()"; - std::cerr << std::endl; -#endif - -#ifdef TEST_NO_GAMES - return true; -#endif - - std::map::iterator it; - if (gameList.end() == (it = gameList.find(serviceId))) - { - return false; /* we don't support the game */ - } - - if ((players <= it->second->getMaxPlayers()) && - (players >= it->second->getMinPlayers())) - { - return true; - } - return false; -} - diff --git a/libretroshare/src/services/p3gamelauncher.h b/libretroshare/src/services/p3gamelauncher.h deleted file mode 100644 index 5ea10edb9..000000000 --- a/libretroshare/src/services/p3gamelauncher.h +++ /dev/null @@ -1,151 +0,0 @@ -/* - * libretroshare/src/services: p3gamelauncher.h - * - * Services for RetroShare. - * - * Copyright 2004-2008 by Robert Fernie. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License Version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 - * USA. - * - * Please report all bugs and problems to "retroshare@lunamutt.com". - * - */ - - -#ifndef SERVICE_GAME_LAUNCHER_HEADER -#define SERVICE_GAME_LAUNCHER_HEADER - -/* - * A central point to setup games between peers. - * - */ - -#include -#include - -#include "services/p3service.h" -#include "serialiser/rsgameitems.h" -#include "retroshare/rsgame.h" - -class p3LinkMgr; - - -class gameAvail -{ - uint32_t serviceId; - std::string gameName; - uint16_t minPlayers; - uint16_t maxPlayers; -}; - -class gameStatus -{ - public: - - uint32_t serviceId; - std::string gameId; - std::wstring gameName; - - bool areServer; /* are we the server? */ - std::string serverId; /* if not, who is? */ - - uint16_t numPlayers; - std::list allowedPeers; /* who can play ( controlled by server) */ - std::list interestedPeers; /* who wants to play ( controlled by server) */ - std::list peerIds; /* in order of turns */ - - uint32_t state; -}; - -class p3GameService; - -/* We're going to add the external Interface - directly on here! */ - -class p3GameLauncher: public p3Service, public RsGameLauncher -{ - public: - p3GameLauncher(p3LinkMgr *lm); - - /***** EXTERNAL RsGameLauncher Interface *******/ -/* server commands */ -virtual std::string createGame(uint32_t gameType, std::wstring name); -virtual bool deleteGame(std::string gameId); -virtual bool inviteGame(std::string gameId); -virtual bool playGame(std::string gameId); -//virtual bool quitGame(std::string gameId); - -virtual bool invitePeer(std::string gameId, std::string peerId); -virtual bool uninvitePeer(std::string gameId, std::string peerId); -virtual bool confirmPeer(std::string gameId, std::string peerId, - int16_t pos = -1); -virtual bool unconfirmPeer(std::string gameId, std::string peerId); - -/* client commands */ -virtual bool interestedPeer(std::string gameId); -virtual bool uninterestedPeer(std::string gameId); - -/* get details */ -virtual bool getGameList(std::list &gameList); -virtual bool getGameDetail(std::string gameId, RsGameDetail &detail); - /***** EXTERNAL RsGameLauncher Interface *******/ - - /* support functions */ - private: -std::string newGame(uint16_t srvId, std::wstring name); -bool confirmGame(std::string gameId); -bool quitGame(std::string gameId); -bool inviteResponse(std::string gameId, bool interested); - - - /* p3Service Overloaded */ -virtual int tick(); -virtual int status(); - - /* add in the Game */ -int addGameService(p3GameService *game); - /* notify gameService/peers */ - -//int getGameList(std::list &games); -//int getGamesCurrent(std::list &games); -//int getGameDetails(std::string gid, gameStatus &status); - - /**** GUI Interface ****/ - -bool resumeGame(std::string gameId); - - /**** Network Interface ****/ -int checkIncoming(); -int handleIncoming(RsGameItem *gi); - -int handleClientStart(RsGameItem *gi); /* START msg */ -int handleClientInvited(RsGameItem *gi); /* REJECT msg */ -int handleClientReady(RsGameItem *gi); /* CONFIRM / REJECT / PLAY msg */ -int handleClientActive(RsGameItem *gi); /* PAUSE / QUIT msg */ - -int handleServerSetup(RsGameItem *gi); /* INTERESTED / REJECT msg */ -int handleServerActive(RsGameItem *gi); /* PAUSE / QUIT msg */ - -int sendRejectMsg(RsGameItem *gi); /* --- error msg */ -void cleanupGame(std::string gameId); /* remove from list */ -bool checkGameProperties(uint16_t serviceId, uint16_t players); - -std::map gameList; -std::map gamesCurrent; - - p3LinkMgr *mLinkMgr; - std::string mOwnId; -}; - -#endif // SERVICE_GAME_LAUNCHER_HEADER diff --git a/libretroshare/src/services/p3gameservice.h b/libretroshare/src/services/p3gameservice.h deleted file mode 100644 index c2bf348a2..000000000 --- a/libretroshare/src/services/p3gameservice.h +++ /dev/null @@ -1,90 +0,0 @@ -/* - * libretroshare/src/services: p3gameservice.h - * - * Services for RetroShare. - * - * Copyright 2004-2008 by Robert Fernie. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License Version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 - * USA. - * - * Please report all bugs and problems to "retroshare@lunamutt.com". - * - */ - - -#ifndef P3_SERVICE_GAME_HEADER -#define P3_SERVICE_GAME_HEADER - -/* - * A central point to setup games between peers. - * - */ - -#include -#include - -#include "services/p3service.h" - -class StoredGame -{ - public: - std::string gameId; - time_t startTime; - std::list peerIds; /* in order of turns */ -}; - -class p3GameLauncher; -class p3Service; - -class p3GameService -{ - public: - - p3GameService(uint16_t sId, std::string name, uint16_t min, uint16_t max, p3GameLauncher *l) - :serviceId(sId), gameName(name), minPlayers(min), maxPlayers(max), - service(NULL), launcher(l) - { return; } - -virtual ~p3GameService() - { return; } - - /*************** Game Interface ******************/ - /* saved games */ -virtual void getSavedGames(std::list &gList); - - /* start a game */ -virtual void startGame(StoredGame &newGame, bool resume); -virtual void quitGame(std::string gameId); -virtual void deleteGame(std::string gameId); - /*************** Game Interface ******************/ - - /* details for the Launcher */ - uint16_t getServiceId() { return serviceId; } - std::string getGameName() { return gameName; } - uint16_t getMinPlayers() { return minPlayers; } - uint16_t getMaxPlayers() { return maxPlayers; } - p3GameLauncher *getLauncher() { return launcher; } - - private: - - uint16_t serviceId; - std::string gameName; - uint16_t minPlayers, maxPlayers; - - p3Service *service; - p3GameLauncher *launcher; -}; - -#endif // P3_SERVICE_GAME_HEADER