From 750dd526c27bc6bcf5f807de26c92176340e2806 Mon Sep 17 00:00:00 2001 From: chrisparker126 Date: Fri, 16 Aug 2013 20:50:02 +0000 Subject: [PATCH 01/83] To add last couple features for GXS before 0.6 release - group update - sharing admin and publish keys - tighten up security git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.5-gxs_finale@6580 b45a01b8-16f6-495d-af2f-9b41ad6348cc From 23acb919150bc166677195aebbf51efad0057fa9 Mon Sep 17 00:00:00 2001 From: drbob Date: Mon, 2 Sep 2013 02:23:13 +0000 Subject: [PATCH 02/83] made branch for v0.6 work. git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@6673 b45a01b8-16f6-495d-af2f-9b41ad6348cc From 212b4c44c9b80ae00fc6b06d26764da6c1e7cfe3 Mon Sep 17 00:00:00 2001 From: drbob Date: Tue, 3 Sep 2013 13:35:39 +0000 Subject: [PATCH 03/83] First of the V0.6 changes. - Adding basics for proxy connection. git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@6682 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/libretroshare.pro | 7 + libretroshare/src/pqi/p3linkmgr.cc | 63 ++- libretroshare/src/pqi/p3linkmgr.h | 13 +- libretroshare/src/pqi/p3netmgr.cc | 3 + libretroshare/src/pqi/p3peermgr.cc | 108 +++- libretroshare/src/pqi/p3peermgr.h | 36 +- libretroshare/src/pqi/pqi_base.h | 7 +- libretroshare/src/pqi/pqibin.cc | 4 + libretroshare/src/pqi/pqiperson.cc | 13 +- libretroshare/src/pqi/pqiperson.h | 8 +- libretroshare/src/pqi/pqipersongrp.cc | 17 +- libretroshare/src/pqi/pqissl.cc | 6 + libretroshare/src/pqi/pqissl.h | 1 + libretroshare/src/pqi/pqisslpersongrp.cc | 102 ++-- libretroshare/src/pqi/pqisslproxy.cc | 486 ++++++++++++++++++ libretroshare/src/pqi/pqisslproxy.h | 89 ++++ libretroshare/src/serialiser/rsconfigitems.cc | 21 + libretroshare/src/serialiser/rsconfigitems.h | 4 + libretroshare/src/serialiser/rstlvbase.h | 1 + 19 files changed, 916 insertions(+), 73 deletions(-) create mode 100755 libretroshare/src/pqi/pqisslproxy.cc create mode 100755 libretroshare/src/pqi/pqisslproxy.h diff --git a/libretroshare/src/libretroshare.pro b/libretroshare/src/libretroshare.pro index 2f1357c75..8dd5ca93a 100644 --- a/libretroshare/src/libretroshare.pro +++ b/libretroshare/src/libretroshare.pro @@ -363,6 +363,7 @@ HEADERS += pqi/authssl.h \ pqi/pqisslpersongrp.h \ pqi/pqissltunnel.h \ pqi/pqissludp.h \ + pqi/pqisslproxy.h \ pqi/pqistore.h \ pqi/pqistreamer.h \ pqi/pqiqosstreamer.h \ @@ -419,6 +420,8 @@ HEADERS += services/p3channels.h \ services/p3bwctrl.h \ services/p3tunnel.h +# services/p3discovery2.h \ + HEADERS += distrib/p3distrib.h \ distrib/p3distribsecurity.h # services/p3blogs.h \ @@ -495,6 +498,7 @@ SOURCES += pqi/authgpg.cc \ pqi/pqisslpersongrp.cc \ pqi/pqissltunnel.cc \ pqi/pqissludp.cc \ + pqi/pqisslproxy.cc \ pqi/pqistore.cc \ pqi/pqistreamer.cc \ pqi/pqiqosstreamer.cc \ @@ -558,6 +562,9 @@ SOURCES += services/p3channels.cc \ services/p3banlist.cc \ services/p3bwctrl.cc \ + +# services/p3discovery2.cc \ + # removed because getPeer() doesn t exist services/p3tunnel.cc SOURCES += distrib/p3distrib.cc \ diff --git a/libretroshare/src/pqi/p3linkmgr.cc b/libretroshare/src/pqi/p3linkmgr.cc index dd29e3ae1..3c7759f8d 100644 --- a/libretroshare/src/pqi/p3linkmgr.cc +++ b/libretroshare/src/pqi/p3linkmgr.cc @@ -85,7 +85,7 @@ const uint32_t P3CONNMGR_UDP_DEFAULT_PERIOD = 30; // this represents how long i void printConnectState(std::ostream &out, peerConnectState &peer); peerConnectAddress::peerConnectAddress() - :delay(0), period(0), type(0), flags(0), ts(0) + :delay(0), period(0), type(0), flags(0), ts(0), domain_port(0) { sockaddr_clear(&addr); } @@ -588,7 +588,8 @@ const std::string p3LinkMgrIMPL::getOwnId() bool p3LinkMgrIMPL::connectAttempt(const std::string &id, struct sockaddr_in &raddr, struct sockaddr_in &proxyaddr, struct sockaddr_in &srcaddr, - uint32_t &delay, uint32_t &period, uint32_t &type, uint32_t &flags, uint32_t &bandwidth) + uint32_t &delay, uint32_t &period, uint32_t &type, uint32_t &flags, uint32_t &bandwidth, + std::string &domain_addr, uint16_t &domain_port) { RsStackMutex stack(mLinkMtx); /****** STACK LOCK MUTEX *******/ @@ -642,6 +643,9 @@ bool p3LinkMgrIMPL::connectAttempt(const std::string &id, struct sockaddr_in &ra srcaddr = it->second.currentConnAddrAttempt.srcaddr; bandwidth = it->second.currentConnAddrAttempt.bandwidth; + domain_addr = it->second.currentConnAddrAttempt.domain_addr; + domain_port = it->second.currentConnAddrAttempt.domain_port; + /********* Setup LinkType parameters **********/ #define TRICKLE_LIMIT 2001 // 2kb @@ -1632,6 +1636,29 @@ bool p3LinkMgrIMPL::retryConnectTCP(const std::string &id) #endif /* If we reach here, must retry .... extract the required info from p3PeerMgr */ + /* first possibility - is it a hidden peer */ + if (mPeerMgr->isHiddenPeer(id)) + { + struct sockaddr_in proxy_addr; + std::string domain_addr; + uint16_t domain_port; + + /* then we just have one connect attempt via the Proxy */ + if (mPeerMgr->getProxyAddress(id, proxy_addr, domain_addr, domain_port)) + { + RsStackMutex stack(mLinkMtx); /****** STACK LOCK MUTEX *******/ + + std::map::iterator it; + if (mFriendList.end() != (it = mFriendList.find(id))) + { + locked_ConnectAttempt_ProxyAddress(&(it->second), &proxy_addr, domain_addr, domain_port); + return locked_ConnectAttempt_Complete(&(it->second)); + } + } + return false; + } + + struct sockaddr_in lAddr; struct sockaddr_in eAddr; pqiIpAddrSet histAddrs; @@ -1987,6 +2014,38 @@ void p3LinkMgrIMPL::locked_ConnectAttempt_AddDynDNS(peerConnectState *peer, std } +void p3LinkMgrIMPL::locked_ConnectAttempt_ProxyAddress(peerConnectState *peer, struct sockaddr_in *proxy_addr, const std::string &domain_addr, uint16_t domain_port) +{ +#ifdef LINKMGR_DEBUG + std::cerr << "p3LinkMgrIMPL::locked_ConnectAttempt_ProxyAddress() trying address: " << domain_addr << ":" << domain_port << std::endl; +#endif + peerConnectAddress pca; + pca.addr.sin_family = AF_INET; + pca.addr.sin_addr.s_addr = proxy_addr->sin_addr.s_addr; + pca.addr.sin_port = proxy_addr->sin_port; + + pca.type = RS_NET_CONN_TCP_HIDDEN; + + //for the delay, we add a random time and some more time when the friend list is big + pca.delay = P3CONNMGR_TCP_DEFAULT_DELAY; + pca.ts = time(NULL); + pca.period = P3CONNMGR_TCP_DEFAULT_PERIOD; + + sockaddr_clear(&(pca.proxyaddr)); + sockaddr_clear(&(pca.srcaddr)); + pca.bandwidth = 0; + + pca.domain_addr = domain_addr; + pca.domain_port = domain_port; + + /* check address validity */ + if (locked_CheckPotentialAddr(&(pca.addr), 0)) + { + addAddressIfUnique(peer->connAddrs, pca, true); + } +} + + void p3LinkMgrIMPL::locked_ConnectAttempt_AddTunnel(peerConnectState *peer) { if (!(peer->state & RS_PEER_S_CONNECTED) && mAllowTunnelConnection) diff --git a/libretroshare/src/pqi/p3linkmgr.h b/libretroshare/src/pqi/p3linkmgr.h index 10b3284bd..f5526e1c3 100644 --- a/libretroshare/src/pqi/p3linkmgr.h +++ b/libretroshare/src/pqi/p3linkmgr.h @@ -47,6 +47,8 @@ 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; const uint32_t RS_NET_CONN_TCP_UNKNOW_TOPOLOGY = 0x0004; +const uint32_t RS_NET_CONN_TCP_HIDDEN = 0x0008; + const uint32_t RS_NET_CONN_UDP_DHT_SYNC = 0x0010; const uint32_t RS_NET_CONN_UDP_PEER_SYNC = 0x0020; /* coming soon */ @@ -80,6 +82,10 @@ class peerConnectAddress struct sockaddr_in proxyaddr; struct sockaddr_in srcaddr; uint32_t bandwidth; + + // Extra Parameters for Proxy/Hidden connection. + std::string domain_addr; + uint16_t domain_port; }; class peerConnectState @@ -159,7 +165,8 @@ virtual void removeMonitor(pqiMonitor *mon) = 0; /****************** Connections *******************/ virtual bool connectAttempt(const std::string &id, struct sockaddr_in &raddr, struct sockaddr_in &proxyaddr, struct sockaddr_in &srcaddr, - uint32_t &delay, uint32_t &period, uint32_t &type, uint32_t &flags, uint32_t &bandwidth) = 0; + uint32_t &delay, uint32_t &period, uint32_t &type, uint32_t &flags, uint32_t &bandwidth, + std::string &domain_addr, uint16_t &domain_port) = 0; virtual bool connectResult(const std::string &id, bool success, uint32_t flags, struct sockaddr_in remote_peer_address) = 0; virtual bool retryConnect(const std::string &id) = 0; @@ -218,7 +225,8 @@ virtual void removeMonitor(pqiMonitor *mon); /****************** Connections *******************/ virtual bool connectAttempt(const std::string &id, struct sockaddr_in &raddr, struct sockaddr_in &proxyaddr, struct sockaddr_in &srcaddr, - uint32_t &delay, uint32_t &period, uint32_t &type, uint32_t &flags, uint32_t &bandwidth); + uint32_t &delay, uint32_t &period, uint32_t &type, uint32_t &flags, uint32_t &bandwidth, + std::string &domain_addr, uint16_t &domain_port); virtual bool connectResult(const std::string &id, bool success, uint32_t flags, struct sockaddr_in remote_peer_address); virtual bool retryConnect(const std::string &id); @@ -290,6 +298,7 @@ void locked_ConnectAttempt_CurrentAddresses(peerConnectState *peer, struct sock void locked_ConnectAttempt_HistoricalAddresses(peerConnectState *peer, const pqiIpAddrSet &ipAddrs); void locked_ConnectAttempt_AddDynDNS(peerConnectState *peer, std::string dyndns, uint16_t dynPort); void locked_ConnectAttempt_AddTunnel(peerConnectState *peer); +void locked_ConnectAttempt_ProxyAddress(peerConnectState *peer, struct sockaddr_in *proxy_addr, const std::string &domain_addr, uint16_t domain_port); bool locked_ConnectAttempt_Complete(peerConnectState *peer); diff --git a/libretroshare/src/pqi/p3netmgr.cc b/libretroshare/src/pqi/p3netmgr.cc index aa2a3361c..c3f029433 100644 --- a/libretroshare/src/pqi/p3netmgr.cc +++ b/libretroshare/src/pqi/p3netmgr.cc @@ -1124,6 +1124,9 @@ bool p3NetMgrIMPL::setNetworkMode(uint32_t netMode) case RS_NET_MODE_UPNP: mNetMode |= RS_NET_MODE_TRY_UPNP; break; + case RS_NET_MODE_HIDDEN: + mNetMode |= RS_NET_MODE_TRY_UDP; // FOR THE MOMENT HIDDEN acts like = UDP. + break; default: case RS_NET_MODE_UDP: mNetMode |= RS_NET_MODE_TRY_UDP; diff --git a/libretroshare/src/pqi/p3peermgr.cc b/libretroshare/src/pqi/p3peermgr.cc index 7f2576056..65c7faa4d 100644 --- a/libretroshare/src/pqi/p3peermgr.cc +++ b/libretroshare/src/pqi/p3peermgr.cc @@ -77,7 +77,8 @@ void printConnectState(std::ostream &out, peerState &peer); peerState::peerState() :id("unknown"), gpg_id("unknown"), - netMode(RS_NET_MODE_UNKNOWN), visState(RS_VIS_STATE_STD), lastcontact(0) + netMode(RS_NET_MODE_UNKNOWN), visState(RS_VIS_STATE_STD), lastcontact(0), + hiddenNode(false), hiddenPort(0) { sockaddr_clear(&localaddr); sockaddr_clear(&serveraddr); @@ -120,6 +121,10 @@ p3PeerMgrIMPL::p3PeerMgrIMPL( const std::string& ssl_own_id, lastGroupId = 1; + // setup default ProxyServerAddress. + sockaddr_clear(&mProxyServerAddress); + inet_aton("127.0.0.1", &(mProxyServerAddress.sin_addr)); + mProxyServerAddress.sin_port = htons(7050); } @@ -274,6 +279,77 @@ bool p3PeerMgrIMPL::getGpgId(const std::string &ssl_id, std::string &gpgId) return true; } +/**** HIDDEN STUFF ****/ + +bool p3PeerMgrIMPL::isHiddenPeer(const std::string &ssl_id) +{ + RsStackMutex stack(mPeerMtx); /****** STACK LOCK MUTEX *******/ + + /* check for existing */ + std::map::iterator it; + it = mFriendList.find(ssl_id); + if (it == mFriendList.end()) + { + return (it->second).hiddenNode; + } + + /* is it hidden ?? */ + return false; +} + +bool p3PeerMgrIMPL::setHiddenDomainPort(const std::string &ssl_id, const std::string &domain_addr, const uint16_t domain_port) +{ + RsStackMutex stack(mPeerMtx); /****** STACK LOCK MUTEX *******/ + + /* check for existing */ + std::map::iterator it; + it = mFriendList.find(ssl_id); + if (it == mFriendList.end()) + { + return false; + } + + it->second.hiddenDomain = domain_addr; + it->second.hiddenPort = domain_port; + it->second.hiddenNode = true; + return true; +} + +bool p3PeerMgrIMPL::setProxyServerAddress(const struct sockaddr_in &proxy_addr) +{ + RsStackMutex stack(mPeerMtx); /****** STACK LOCK MUTEX *******/ + + mProxyServerAddress = proxy_addr; + return true; +} + + +bool p3PeerMgrIMPL::getProxyAddress(const std::string &ssl_id, struct sockaddr_in &proxy_addr, std::string &domain_addr, uint16_t &domain_port) +{ + RsStackMutex stack(mPeerMtx); /****** STACK LOCK MUTEX *******/ + + /* check for existing */ + std::map::iterator it; + it = mFriendList.find(ssl_id); + if (it == mFriendList.end()) + { + return false; + } + + if (!it->second.hiddenNode) + { + return false; + } + + domain_addr = it->second.hiddenDomain; + domain_port = it->second.hiddenPort; + + proxy_addr = mProxyServerAddress; + return true; +} + + + // Placeholder until we implement this functionality. uint32_t p3PeerMgrIMPL::getConnectionType(const std::string &/*sslId*/) { @@ -1368,6 +1444,9 @@ bool p3PeerMgrIMPL::saveList(bool &cleanup, std::list& saveData) (it->second).ipAddrs.mLocal.loadTlv(item->localAddrList); (it->second).ipAddrs.mExt.loadTlv(item->extAddrList); + item->domain_addr = (it->second).hiddenDomain; + item->domain_port = (it->second).hiddenPort; + saveData.push_back(item); saveCleanupList.push_back(item); #ifdef PEER_DEBUG @@ -1493,17 +1572,26 @@ bool p3PeerMgrIMPL::loadList(std::list& load) addFriend(pitem->pid, pitem->gpg_id, pitem->netMode, pitem->visState, pitem->lastContact, RS_SERVICE_PERM_ALL); setLocation(pitem->pid, pitem->location); } - - setLocalAddress(pitem->pid, pitem->currentlocaladdr); - setExtAddress(pitem->pid, pitem->currentremoteaddr); - setDynDNS (pitem->pid, pitem->dyndns); - /* convert addresses */ - pqiIpAddrSet addrs; - addrs.mLocal.extractFromTlv(pitem->localAddrList); - addrs.mExt.extractFromTlv(pitem->extAddrList); + if (pitem->netMode == RS_NET_MODE_HIDDEN) + { + /* set only the hidden stuff */ + setHiddenDomainPort(pitem->pid, pitem->domain_addr, pitem->domain_port); + + } + else + { + setLocalAddress(pitem->pid, pitem->currentlocaladdr); + setExtAddress(pitem->pid, pitem->currentremoteaddr); + setDynDNS (pitem->pid, pitem->dyndns); + + /* convert addresses */ + pqiIpAddrSet addrs; + addrs.mLocal.extractFromTlv(pitem->localAddrList); + addrs.mExt.extractFromTlv(pitem->extAddrList); - updateAddressList(pitem->pid, addrs); + updateAddressList(pitem->pid, addrs); + } delete(*it); diff --git a/libretroshare/src/pqi/p3peermgr.h b/libretroshare/src/pqi/p3peermgr.h index 46a09db68..ade27a15f 100644 --- a/libretroshare/src/pqi/p3peermgr.h +++ b/libretroshare/src/pqi/p3peermgr.h @@ -55,20 +55,22 @@ const uint32_t RS_VIS_STATE_BROWN = RS_VIS_STATE_NODISC; /* Startup Modes (confirmed later) */ -const uint32_t RS_NET_MODE_TRYMODE = 0x00f0; +const uint32_t RS_NET_MODE_TRYMODE = 0xff00; -const uint32_t RS_NET_MODE_TRY_EXT = 0x0010; -const uint32_t RS_NET_MODE_TRY_UPNP = 0x0020; -const uint32_t RS_NET_MODE_TRY_UDP = 0x0040; +const uint32_t RS_NET_MODE_TRY_EXT = 0x0100; +const uint32_t RS_NET_MODE_TRY_UPNP = 0x0200; +const uint32_t RS_NET_MODE_TRY_UDP = 0x0400; +const uint32_t RS_NET_MODE_TRY_HIDDEN = 0x0800; /* Actual State */ -const uint32_t RS_NET_MODE_ACTUAL = 0x000f; +const uint32_t RS_NET_MODE_ACTUAL = 0x00ff; const uint32_t RS_NET_MODE_UNKNOWN = 0x0000; const uint32_t RS_NET_MODE_EXT = 0x0001; const uint32_t RS_NET_MODE_UPNP = 0x0002; const uint32_t RS_NET_MODE_UDP = 0x0004; -const uint32_t RS_NET_MODE_UNREACHABLE = 0x0008; +const uint32_t RS_NET_MODE_HIDDEN = 0x0008; +const uint32_t RS_NET_MODE_UNREACHABLE = 0x0010; /* flags of peerStatus */ @@ -87,9 +89,10 @@ class peerState std::string id; std::string gpg_id; - uint32_t netMode; /* EXT / UPNP / UDP / INVALID */ + uint32_t netMode; /* EXT / UPNP / UDP / HIDDEN / INVALID */ uint32_t visState; /* STD, GRAY, DARK */ + struct sockaddr_in localaddr; struct sockaddr_in serveraddr; std::string dyndns; @@ -99,6 +102,10 @@ class peerState /* list of addresses from various sources */ pqiIpAddrSet ipAddrs; + bool hiddenNode; /* all IP addresses / dyndns must be blank */ + std::string hiddenDomain; + uint16_t hiddenPort; + std::string location; std::string name; @@ -162,6 +169,7 @@ virtual bool setNetworkMode(const std::string &id, uint32_t netMode) = 0; virtual bool setVisState(const std::string &id, uint32_t visState) = 0; virtual bool setLocation(const std::string &pid, const std::string &location) = 0; +virtual bool setHiddenDomainPort(const std::string &id, const std::string &domain_addr, const uint16_t domain_port) = 0; virtual bool updateCurrentAddress(const std::string& id, const pqiIpAddress &addr) = 0; virtual bool updateLastContact(const std::string& id) = 0; @@ -188,6 +196,11 @@ virtual bool getPeerName(const std::string &ssl_id, std::string &name) = 0; virtual bool getGpgId(const std::string &sslId, std::string &gpgId) = 0; virtual uint32_t getConnectionType(const std::string &sslId) = 0; +virtual bool setProxyServerAddress(const struct sockaddr_in &proxy_addr) = 0; +virtual bool isHiddenPeer(const std::string &ssl_id) = 0; +virtual bool getProxyAddress(const std::string &ssl_id, struct sockaddr_in &proxy_addr, std::string &domain_addr, uint16_t &domain_port) = 0; + + virtual int getFriendCount(bool ssl, bool online) = 0; /************* DEPRECIATED FUNCTIONS (TO REMOVE) ********/ @@ -253,7 +266,8 @@ virtual bool setNetworkMode(const std::string &id, uint32_t netMode); virtual bool setVisState(const std::string &id, uint32_t visState); virtual bool setLocation(const std::string &pid, const std::string &location); - +virtual bool setHiddenDomainPort(const std::string &id, const std::string &domain_addr, const uint16_t domain_port); + virtual bool updateCurrentAddress(const std::string& id, const pqiIpAddress &addr); virtual bool updateLastContact(const std::string& id); virtual bool updateAddressList(const std::string& id, const pqiIpAddrSet &addrs); @@ -278,6 +292,10 @@ virtual bool getPeerName(const std::string &ssl_id, std::string &name); virtual bool getGpgId(const std::string &sslId, std::string &gpgId); virtual uint32_t getConnectionType(const std::string &sslId); +virtual bool setProxyServerAddress(const struct sockaddr_in &proxy_addr); +virtual bool isHiddenPeer(const std::string &ssl_id); +virtual bool getProxyAddress(const std::string &ssl_id, struct sockaddr_in &proxy_addr, std::string &domain_addr, uint16_t &domain_port); + virtual int getFriendCount(bool ssl, bool online); /************* DEPRECIATED FUNCTIONS (TO REMOVE) ********/ @@ -349,6 +367,8 @@ private: std::list saveCleanupList; /* TEMPORARY LIST WHEN SAVING */ std::map mFriendsPermissionFlags ; // permission flags for each gpg key + + struct sockaddr_in mProxyServerAddress; }; #endif // MRK_PQI_PEER_MANAGER_HEADER diff --git a/libretroshare/src/pqi/pqi_base.h b/libretroshare/src/pqi/pqi_base.h index 5396ee528..fcb2d5689 100644 --- a/libretroshare/src/pqi/pqi_base.h +++ b/libretroshare/src/pqi/pqi_base.h @@ -238,6 +238,7 @@ 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; #define BIN_FLAGS_NO_CLOSE 0x0001 @@ -322,6 +323,9 @@ static const uint32_t NET_PARAM_CONNECT_BANDWIDTH = 5; static const uint32_t NET_PARAM_CONNECT_PROXY = 6; static const uint32_t NET_PARAM_CONNECT_SOURCE = 7; +static const uint32_t NET_PARAM_CONNECT_DOMAIN_ADDRESS = 8; +static const uint32_t NET_PARAM_CONNECT_REMOTE_PORT = 9; + /*! * ******************** Network INTERFACE *************************** @@ -357,7 +361,8 @@ virtual std::string PeerId() { return peerId; } virtual int getConnectAddress(struct sockaddr_in &raddr) = 0; virtual bool connect_parameter(uint32_t type, uint32_t value) = 0; -virtual bool connect_additional_address(uint32_t /*type*/, struct sockaddr_in */*addr*/) { return false; } // only needed by udp. +virtual bool connect_parameter(uint32_t /* type */ , const std::string & /* value */ ) { return false; } // not generally used. +virtual bool connect_additional_address(uint32_t /*type*/, struct sockaddr_in * /*addr*/) { return false; } // only needed by udp. protected: PQInterface *parent() { return p; } diff --git a/libretroshare/src/pqi/pqibin.cc b/libretroshare/src/pqi/pqibin.cc index a3f450d93..668188693 100644 --- a/libretroshare/src/pqi/pqibin.cc +++ b/libretroshare/src/pqi/pqibin.cc @@ -500,6 +500,10 @@ void printNetBinID(std::ostream &out, std::string id, uint32_t t) { out << "TCP)"; } + else if (t == PQI_CONNECT_HIDDEN_TCP) + { + out << "HTCP"; + } else { out << "UDP)"; diff --git a/libretroshare/src/pqi/pqiperson.cc b/libretroshare/src/pqi/pqiperson.cc index c8e8e7475..6783bd46d 100644 --- a/libretroshare/src/pqi/pqiperson.cc +++ b/libretroshare/src/pqi/pqiperson.cc @@ -368,7 +368,8 @@ int pqiperson::stoplistening() int pqiperson::connect(uint32_t type, struct sockaddr_in raddr, struct sockaddr_in &proxyaddr, struct sockaddr_in &srcaddr, - uint32_t delay, uint32_t period, uint32_t timeout, uint32_t flags, uint32_t bandwidth) + uint32_t delay, uint32_t period, uint32_t timeout, uint32_t flags, uint32_t bandwidth, + const std::string &domain_addr, uint16_t domain_port) { #ifdef PERSON_DEBUG #endif @@ -417,15 +418,23 @@ int pqiperson::connect(uint32_t type, struct sockaddr_in raddr, #ifdef PERSON_DEBUG std::cerr << "pqiperson::connect() setting connect_parameters" << std::endl; #endif + + // These two are universal. (it->second)->connect_parameter(NET_PARAM_CONNECT_DELAY, delay); - (it->second)->connect_parameter(NET_PARAM_CONNECT_PERIOD, period); (it->second)->connect_parameter(NET_PARAM_CONNECT_TIMEOUT, timeout); + + // these 5 are only used by UDP connections. + (it->second)->connect_parameter(NET_PARAM_CONNECT_PERIOD, period); (it->second)->connect_parameter(NET_PARAM_CONNECT_FLAGS, flags); (it->second)->connect_parameter(NET_PARAM_CONNECT_BANDWIDTH, bandwidth); (it->second)->connect_additional_address(NET_PARAM_CONNECT_PROXY, &proxyaddr); (it->second)->connect_additional_address(NET_PARAM_CONNECT_SOURCE, &srcaddr); + // These are used by Proxy/Hidden + (it->second)->connect_parameter(NET_PARAM_CONNECT_DOMAIN_ADDRESS, domain_addr); + (it->second)->connect_parameter(NET_PARAM_CONNECT_REMOTE_PORT, domain_port); + (it->second)->connect(raddr); // flag if we started a new connectionAttempt. diff --git a/libretroshare/src/pqi/pqiperson.h b/libretroshare/src/pqi/pqiperson.h index f4ec59cfd..c2a495656 100644 --- a/libretroshare/src/pqi/pqiperson.h +++ b/libretroshare/src/pqi/pqiperson.h @@ -71,6 +71,7 @@ virtual int stoplistening() { return ni -> stoplistening(); } virtual int reset() { return ni -> reset(); } virtual int disconnect() { return ni -> reset(); } virtual bool connect_parameter(uint32_t type, uint32_t value) { return ni -> connect_parameter(type, value);} +virtual bool connect_parameter(uint32_t type, std::string value) { return ni -> connect_parameter(type, value);} virtual bool connect_additional_address(uint32_t type, struct sockaddr_in *addr) { return ni -> connect_additional_address(type, addr);} @@ -111,10 +112,11 @@ int reset(); int listen(); int stoplistening(); -int connect(uint32_t type, struct sockaddr_in raddr, +int connect(uint32_t type, struct sockaddr_in raddr, struct sockaddr_in &proxyaddr, struct sockaddr_in &srcaddr, - uint32_t delay, uint32_t period, uint32_t timeout, uint32_t flags, uint32_t bandwidth); - + uint32_t delay, uint32_t period, uint32_t timeout, uint32_t flags, uint32_t bandwidth, + const std::string &domain_addr, uint16_t domain_port); + int receiveHeartbeat(); // add in connection method. int addChildInterface(uint32_t type, pqiconnect *pqi); diff --git a/libretroshare/src/pqi/pqipersongrp.cc b/libretroshare/src/pqi/pqipersongrp.cc index c18eef166..5e24756a3 100644 --- a/libretroshare/src/pqi/pqipersongrp.cc +++ b/libretroshare/src/pqi/pqipersongrp.cc @@ -546,8 +546,10 @@ int pqipersongrp::connectPeer(std::string id struct sockaddr_in proxyaddr; struct sockaddr_in srcaddr; uint32_t bandwidth; + std::string domain_addr; + uint16_t domain_port; - if (!mLinkMgr->connectAttempt(id, addr, proxyaddr, srcaddr, delay, period, type, flags, bandwidth)) + if (!mLinkMgr->connectAttempt(id, addr, proxyaddr, srcaddr, delay, period, type, flags, bandwidth, domain_addr, domain_port)) { #ifdef PGRP_DEBUG std::cerr << " pqipersongrp::connectPeer() No Net Address"; @@ -563,6 +565,8 @@ int pqipersongrp::connectPeer(std::string id std::cerr << " period: " << period; std::cerr << " type: " << type; std::cerr << " flags: " << flags; + std::cerr << " domain_addr: " << domain_addr; + std::cerr << " domain_port: " << domain_port; std::cerr << std::endl; #endif @@ -570,7 +574,14 @@ int pqipersongrp::connectPeer(std::string id uint32_t ptype; if (type & RS_NET_CONN_TCP_ALL) { - ptype = PQI_CONNECT_TCP; + if (type == RS_NET_CONN_TCP_HIDDEN) + { + ptype = PQI_CONNECT_HIDDEN_TCP; + } + else + { + ptype = PQI_CONNECT_TCP; + } timeout = RS_TCP_STD_TIMEOUT_PERIOD; #ifdef PGRP_DEBUG std::cerr << " pqipersongrp::connectPeer() connecting with TCP: Timeout :" << timeout; @@ -604,7 +615,7 @@ int pqipersongrp::connectPeer(std::string id return 0; } - p->connect(ptype, addr, proxyaddr, srcaddr, delay, period, timeout, flags, bandwidth); + p->connect(ptype, addr, proxyaddr, srcaddr, delay, period, timeout, flags, bandwidth, domain_addr, domain_port); return 1; } diff --git a/libretroshare/src/pqi/pqissl.cc b/libretroshare/src/pqi/pqissl.cc index 2e37d7583..47f6bcc43 100644 --- a/libretroshare/src/pqi/pqissl.cc +++ b/libretroshare/src/pqi/pqissl.cc @@ -265,6 +265,12 @@ int pqissl::reset() return 1; } +bool pqissl::connect_parameter(uint32_t type, const std::string &value) +{ + return false; +} + + bool pqissl::connect_parameter(uint32_t type, uint32_t value) { #ifdef PQISSL_LOG_DEBUG diff --git a/libretroshare/src/pqi/pqissl.h b/libretroshare/src/pqi/pqissl.h index 057ce6dff..58aa84f17 100644 --- a/libretroshare/src/pqi/pqissl.h +++ b/libretroshare/src/pqi/pqissl.h @@ -100,6 +100,7 @@ virtual int reset(); virtual int disconnect(); virtual int getConnectAddress(struct sockaddr_in &raddr); +virtual bool connect_parameter(uint32_t type, const std::string &value); virtual bool connect_parameter(uint32_t type, uint32_t value); // BinInterface diff --git a/libretroshare/src/pqi/pqisslpersongrp.cc b/libretroshare/src/pqi/pqisslpersongrp.cc index 8f135a32b..91e37fab0 100644 --- a/libretroshare/src/pqi/pqisslpersongrp.cc +++ b/libretroshare/src/pqi/pqisslpersongrp.cc @@ -39,6 +39,7 @@ const int pqipersongrpzone = 354; #include "pqi/pqissl.h" #include "pqi/pqissllistener.h" +#include "pqi/p3peermgr.h" #ifndef PQI_DISABLE_TUNNEL #include "pqi/pqissltunnel.h" @@ -48,6 +49,7 @@ const int pqipersongrpzone = 354; #include "pqi/pqissludp.h" #endif +#include "pqi/pqisslproxy.h" pqilistener * pqisslpersongrp::locked_createListener(struct sockaddr_in laddr) { @@ -71,51 +73,67 @@ pqiperson * pqisslpersongrp::locked_createPerson(std::string id, pqilistener *li pqioutput(PQL_DEBUG_BASIC, pqipersongrpzone, "pqipersongrp::createPerson() PeerId: " + id); pqiperson *pqip = new pqiperson(id, this); - pqissl *pqis = new pqissl((pqissllistener *) listener, pqip, mLinkMgr); - /* construct the serialiser .... - * Needs: - * * FileItem - * * FileData - * * ServiceGeneric - */ - - ssl_tunnels[id] = pqis ; // keeps for getting crypt info per peer. - - RsSerialiser *rss = new RsSerialiser(); - rss->addSerialType(new RsFileItemSerialiser()); - rss->addSerialType(new RsCacheItemSerialiser()); - rss->addSerialType(new RsServiceSerialiser()); - - pqiconnect *pqisc = new pqiconnect(rss, pqis); - - pqip -> addChildInterface(PQI_CONNECT_TCP, pqisc); - -#ifndef PQI_DISABLE_TUNNEL - pqissltunnel *pqitun = new pqissltunnel(pqip, mLinkMgr); - - RsSerialiser *rss3 = new RsSerialiser(); - rss3->addSerialType(new RsFileItemSerialiser()); - rss3->addSerialType(new RsCacheItemSerialiser()); - rss3->addSerialType(new RsServiceSerialiser()); - pqiconnect *pqicontun = new pqiconnect(rss3, pqitun); - pqip -> addChildInterface(PQI_CONNECT_TUNNEL, pqicontun); -#endif - -#ifndef PQI_DISABLE_UDP - pqissludp *pqius = new pqissludp(pqip, mLinkMgr); - - RsSerialiser *rss2 = new RsSerialiser(); - rss2->addSerialType(new RsFileItemSerialiser()); - rss2->addSerialType(new RsCacheItemSerialiser()); - rss2->addSerialType(new RsServiceSerialiser()); + // If using proxy, then only create a proxy item, otherwise can use any. + if (mPeerMgr->isHiddenPeer(id)) + { + pqisslproxy *pqis = new pqisslproxy((pqissllistener *) listener, pqip, mLinkMgr); - pqiconnect *pqiusc = new pqiconnect(rss2, pqius); - - // add a ssl + proxy interface. - // Add Proxy First. - pqip -> addChildInterface(PQI_CONNECT_UDP, pqiusc); + /* construct the serialiser .... + * Needs: + * * FileItem + * * FileData + * * ServiceGeneric + */ + + ssl_tunnels[id] = pqis ; // keeps for getting crypt info per peer. + + RsSerialiser *rss = new RsSerialiser(); + rss->addSerialType(new RsFileItemSerialiser()); + rss->addSerialType(new RsCacheItemSerialiser()); + rss->addSerialType(new RsServiceSerialiser()); + + pqiconnect *pqisc = new pqiconnect(rss, pqis); + + pqip -> addChildInterface(PQI_CONNECT_HIDDEN_TCP, pqisc); + } + else + { + pqissl *pqis = new pqissl((pqissllistener *) listener, pqip, mLinkMgr); + + /* construct the serialiser .... + * Needs: + * * FileItem + * * FileData + * * ServiceGeneric + */ + + ssl_tunnels[id] = pqis ; // keeps for getting crypt info per peer. + + RsSerialiser *rss = new RsSerialiser(); + rss->addSerialType(new RsFileItemSerialiser()); + rss->addSerialType(new RsCacheItemSerialiser()); + rss->addSerialType(new RsServiceSerialiser()); + + pqiconnect *pqisc = new pqiconnect(rss, pqis); + + pqip -> addChildInterface(PQI_CONNECT_TCP, pqisc); + +#ifndef PQI_DISABLE_UDP + pqissludp *pqius = new pqissludp(pqip, mLinkMgr); + + RsSerialiser *rss2 = new RsSerialiser(); + rss2->addSerialType(new RsFileItemSerialiser()); + rss2->addSerialType(new RsCacheItemSerialiser()); + rss2->addSerialType(new RsServiceSerialiser()); + + pqiconnect *pqiusc = new pqiconnect(rss2, pqius); + + // add a ssl + proxy interface. + // Add Proxy First. + pqip -> addChildInterface(PQI_CONNECT_UDP, pqiusc); #endif + } return pqip; } diff --git a/libretroshare/src/pqi/pqisslproxy.cc b/libretroshare/src/pqi/pqisslproxy.cc new file mode 100755 index 000000000..cfcf2ead0 --- /dev/null +++ b/libretroshare/src/pqi/pqisslproxy.cc @@ -0,0 +1,486 @@ +/* + * pqisslproxy.cc + * + * 3P/PQI network interface for RetroShare. + * + * Copyright 2004-2013 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.1 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/pqisslproxy.h" +#include "pqi/pqinetwork.h" + +#include +#include + +#include + +#include "util/rsdebug.h" +#include "util/rsnet.h" + +#include "pqi/p3linkmgr.h" + +const int pqisslproxyzone = 3517; + +#define PROXY_STATE_FAILED 0 +#define PROXY_STATE_INIT 1 +#define PROXY_STATE_WAITING_METHOD_RESPONSE 2 +#define PROXY_STATE_WAITING_SOCKS_RESPONSE 3 +#define PROXY_STATE_CONNECTION_COMPLETE 4 + +pqisslproxy::pqisslproxy(pqissllistener *l, PQInterface *parent, p3LinkMgr *lm) + :pqissl(l, parent, lm) +{ + sockaddr_clear(&remote_addr); + return; +} + + +pqisslproxy::~pqisslproxy() +{ + rslog(RSL_ALERT, pqisslproxyzone, + "pqisslproxy::~pqisslproxy -> destroying pqisslproxy"); + return; +} + +int pqisslproxy::Initiate_Connection() +{ + +#ifdef PROXY_DEBUG + std::cerr << "pqisslproxy::Initiate_Connection()"; + std::cerr << std::endl; +#endif + + rslog(RSL_DEBUG_BASIC, pqisslproxyzone, + "pqisslproxy::Initiate_Connection() Connection to Proxy"); + /* init proxy state */ + mProxyState = PROXY_STATE_INIT; + + /* call standard Init_Conn() */ + return pqissl::Initiate_Connection(); +} + + +/********* VERY DIFFERENT **********/ +int pqisslproxy::Basic_Connection_Complete() +{ + rslog(RSL_DEBUG_BASIC, pqisslproxyzone, + "pqisslproxy::Basic_Connection_Complete()..."); + +#ifdef PROXY_DEBUG + std::cerr << "pqisslproxy::Basic_Connection_Complete() STATE: " << mProxyState; + std::cerr << std::endl; +#endif + + int ret = 0; + switch(mProxyState) + { + case PROXY_STATE_INIT: + ret = Proxy_Send_Method(); // checks basic conn, sends Method when able. + break; + + case PROXY_STATE_WAITING_METHOD_RESPONSE: + ret = Proxy_Send_Address(); // waits for Method Response, send Address when able. + break; + + case PROXY_STATE_WAITING_SOCKS_RESPONSE: + ret = Proxy_Connection_Complete(); // wait for ACK. + break; + + case PROXY_STATE_CONNECTION_COMPLETE: + +#ifdef PROXY_DEBUG + std::cerr << "pqisslproxy::Basic_Connection_Complete() COMPLETED"; + std::cerr << std::endl; +#endif + + return 1; + + case PROXY_STATE_FAILED: + +#ifdef PROXY_DEBUG + std::cerr << "pqisslproxy::Basic_Connection_Complete() FAILED"; + std::cerr << std::endl; +#endif + + return -1; + } + + if (ret < 0) + { + +#ifdef PROXY_DEBUG + std::cerr << "pqisslproxy::Basic_Connection_Complete() FAILED(2)"; + std::cerr << std::endl; +#endif + + return -1; // FAILURE. + } + + +#ifdef PROXY_DEBUG + std::cerr << "pqisslproxy::Basic_Connection_Complete() IN PROGRESS"; + std::cerr << std::endl; +#endif + + // In Progress. + return 0; +} + + +int pqisslproxy::Proxy_Send_Method() +{ + +#ifdef PROXY_DEBUG + std::cerr << "pqisslproxy::Proxy_Send_Method() Checking pqissl::Basic_Connection_Complete()"; + std::cerr << std::endl; +#endif + + int ret = pqissl::Basic_Connection_Complete(); + if (ret != 1) + { + return ret; // basic connection not complete. + } + +#ifdef PROXY_DEBUG + std::cerr << "pqisslproxy::Proxy_Send_Method() Basic complete, sending Method"; + std::cerr << std::endl; +#endif + + /* send hello to proxy server */ + uint8_t method_hello_data[3] = { 0x05, 0x01, 0x00 }; // [ Ver | nMethods (1) | No Auth Method ] + + int sent = send(sockfd, method_hello_data, 3, 0); + if (sent != 3) + { + +#ifdef PROXY_DEBUG + std::cerr << "pqisslproxy::Proxy_Send_Method() Send Failure"; + std::cerr << std::endl; +#endif + return -1; + } + +#ifdef PROXY_DEBUG + std::cerr << "pqisslproxy::Proxy_Send_Method() Send Method Okay"; + std::cerr << std::endl; +#endif + + mProxyState = PROXY_STATE_WAITING_METHOD_RESPONSE; + + return 1; +} + +int pqisslproxy::Proxy_Method_Response() +{ + +#ifdef PROXY_DEBUG + std::cerr << "pqisslproxy::Proxy_Method_Response()"; + std::cerr << std::endl; +#endif + + /* get response from proxy server */ + + uint8_t method_response[2]; + + // read from the socket. + int recvd = recv(sockfd, method_response, 2, MSG_WAITALL); + if (recvd != 2) + { + if ((recvd == -1) && (errno == EAGAIN)) + { + +#ifdef PROXY_DEBUG + std::cerr << "pqisslproxy::Proxy_Method_Response() EAGAIN"; + std::cerr << std::endl; +#endif + + return 0; + } + +#ifdef PROXY_DEBUG + std::cerr << "pqisslproxy::Proxy_Method_Response() Error recving response"; + std::cerr << std::endl; +#endif + return -1; + } + + // does it make sense? + if (method_response[0] != 0x05) + { + + // Error. +#ifdef PROXY_DEBUG + std::cerr << "pqisslproxy::Proxy_Method_Response() Error response[0] != 0x05. Is: "; + std::cerr << (uint32_t) method_response[0]; + std::cerr << std::endl; +#endif + return -1; + } + + if (method_response[1] != 0x00) + { + +#ifdef PROXY_DEBUG + std::cerr << "pqisslproxy::Proxy_Method_Response() Error response[0] != 0x00. Is: "; + std::cerr << (uint32_t) method_response[1]; + std::cerr << std::endl; +#endif + // Error. + return -1; + } + + +#ifdef PROXY_DEBUG + std::cerr << "pqisslproxy::Proxy_Method_Response() Response Okay"; + std::cerr << std::endl; +#endif + + return 1; +} + +#define MAX_SOCKS_REQUEST_LEN 262 // 4 + 1 + 255 + 2. + +int pqisslproxy::Proxy_Send_Address() +{ + +#ifdef PROXY_DEBUG + std::cerr << "pqisslproxy::Proxy_Send_Address() Checking Method Response"; + std::cerr << std::endl; +#endif + + // Check Method Response. + int ret = Proxy_Method_Response(); + if (ret != 1) + { + return ret; // Method Response not complete. + } + + uint8_t socks_request[MAX_SOCKS_REQUEST_LEN] = + { 0x05, // SOCKS VERSION. + 0x01, // CONNECT (Tor doesn't support BIND or UDP). + 0x00, // RESERVED. + 0x03, // ADDRESS TYPE (Domain Name) + 0x00, // Length of Domain name... the rest is variable so can't hard code it! + }; + + /* get the length of the domain name, pack so we can't overflow uint8_t */ + uint8_t len = mDomainAddress.length(); + socks_request[4] = len; + for(int i = 0; i < len; i++) + { + socks_request[5 + i] = mDomainAddress[i]; + } + + /* now add the port, being careful with packing */ + uint16_t net_port = htons(mRemotePort); + socks_request[5 + len] = ((uint8_t *) &net_port)[0]; + socks_request[5 + len + 1] = ((uint8_t *) &net_port)[1]; + + int pkt_len = 5 + len + 2; + +#ifdef PROXY_DEBUG + std::cerr << "pqisslproxy::Proxy_Send_Address() Sending String: "; + for(int i = 0; i < pkt_len; i++) + std::cerr << (uint32_t) socks_request[i]; + std::cerr << std::endl; +#endif + int sent = send(sockfd, socks_request, pkt_len, 0); + if (sent != pkt_len) + { + +#ifdef PROXY_DEBUG + std::cerr << "pqisslproxy::Proxy_Send_Address() Send Error"; + std::cerr << std::endl; +#endif + + return -1; + } + + +#ifdef PROXY_DEBUG + std::cerr << "pqisslproxy::Proxy_Send_Address() Sent Okay"; + std::cerr << std::endl; +#endif + + mProxyState = PROXY_STATE_WAITING_SOCKS_RESPONSE; + return 1; +} + +int pqisslproxy::Proxy_Connection_Complete() +{ + /* get response from proxy server */ + /* response is similar format to request - with variable length data */ + + uint8_t socks_response[MAX_SOCKS_REQUEST_LEN]; + + int recvd = recv(sockfd, socks_response, 5, MSG_WAITALL); + if (recvd != 5) + { + if ((recvd == -1) && (errno == EAGAIN)) + { +#ifdef PROXY_DEBUG + std::cerr << "pqisslproxy::Proxy_Connection_Complete() EAGAIN"; + std::cerr << std::endl; +#endif + return 0; + } + +#ifdef PROXY_DEBUG + std::cerr << "pqisslproxy::Proxy_Connection_Complete() recv error"; + std::cerr << std::endl; +#endif + return -1; + } + + // error checking. + if (socks_response[0] != 0x05) + { + +#ifdef PROXY_DEBUG + std::cerr << "pqisslproxy::Proxy_Connection_Complete() ERROR socks_response[0] != 0x05. is: "; + std::cerr << (uint32_t) socks_response[0]; + std::cerr << std::endl; +#endif + + // error. + return -1; + } + + if (socks_response[1] != 0x00) + { + +#ifdef PROXY_DEBUG + std::cerr << "pqisslproxy::Proxy_Connection_Complete() ERROR socks_response[1] != 0x00. is: "; + std::cerr << (uint32_t) socks_response[1]; + std::cerr << std::endl; +#endif + + // connection failed. + return -1; + } + + int address_bytes = 0; + switch(socks_response[3]) // Address Type. + { + case 0x01: + // IPv4 4 address bytes. + address_bytes = 4; +#ifdef PROXY_DEBUG + std::cerr << "pqisslproxy::Proxy_Connection_Complete() IPv4 Address Type"; + std::cerr << std::endl; +#endif + break; + case 0x04: + // IPv6 16 address bytes. + address_bytes = 16; +#ifdef PROXY_DEBUG + std::cerr << "pqisslproxy::Proxy_Connection_Complete() IPv6 Address Type"; + std::cerr << std::endl; +#endif + break; + case 0x03: + // Variable address bytes - specified in next byte. + address_bytes = 1 + socks_response[4]; +#ifdef PROXY_DEBUG + std::cerr << "pqisslproxy::Proxy_Connection_Complete() Domain Address Type. len: " << address_bytes; + std::cerr << std::endl; +#endif + break; + default: + // unknown error. +#ifdef PROXY_DEBUG + std::cerr << "pqisslproxy::Proxy_Connection_Complete() ERROR Unknown Address Type"; + std::cerr << std::endl; +#endif + return -1; + break; + } + + + // read the remaining bytes. + recvd = recv(sockfd, &(socks_response[5]), address_bytes + 1, MSG_WAITALL); // address_bytes - 1 + 2... + if (recvd != address_bytes + 1) + { + if ((recvd == -1) && (errno == EAGAIN)) + { +#ifdef PROXY_DEBUG + std::cerr << "pqisslproxy::Proxy_Connection_Complete() ERROR EAGAIN at end."; + std::cerr << std::endl; +#endif + // Waiting - shouldn't happen. + return 0; + } + +#ifdef PROXY_DEBUG + std::cerr << "pqisslproxy::Proxy_Connection_Complete() ERROR recving(2)"; + std::cerr << std::endl; +#endif + return -1; + } + +#ifdef PROXY_DEBUG + std::cerr << "pqisslproxy::Proxy_Connection_Complete() Received String: "; + for(int i = 0; i < 4 + address_bytes + 2; i++) + std::cerr << (uint32_t) socks_response[i]; + std::cerr << std::endl; +#endif + + // should print address. + // if we get here - connection is good!. + mProxyState = PROXY_STATE_CONNECTION_COMPLETE; + return 1; + +} + +bool pqisslproxy::connect_parameter(uint32_t type, const std::string &value) +{ + if (type == NET_PARAM_CONNECT_DOMAIN_ADDRESS) + { + std::string out; + rs_sprintf(out, "pqisslproxy::connect_parameter() Peer: %s DOMAIN_ADDRESS: %s", PeerId().c_str(), value.c_str()); + rslog(RSL_WARNING, pqisslproxyzone, out); + + mDomainAddress = value; + std::cerr << out << std::endl; + return true; + } + return pqissl::connect_parameter(type, value); +} + +bool pqisslproxy::connect_parameter(uint32_t type, uint32_t value) +{ + if (type == NET_PARAM_CONNECT_REMOTE_PORT) + { + std::string out; + rs_sprintf(out, "pqisslproxy::connect_parameter() Peer: %s REMOTE_PORT: %lu", PeerId().c_str(), value); + rslog(RSL_WARNING, pqisslproxyzone, out); + + mRemotePort = value; + std::cerr << out << std::endl; + return true; + } + return pqissl::connect_parameter(type, value); +} + + + + diff --git a/libretroshare/src/pqi/pqisslproxy.h b/libretroshare/src/pqi/pqisslproxy.h new file mode 100755 index 000000000..ff1db04a3 --- /dev/null +++ b/libretroshare/src/pqi/pqisslproxy.h @@ -0,0 +1,89 @@ +/* + * pqisslproxy.h + * + * 3P/PQI network interface for RetroShare. + * + * Copyright 2004-2013 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.1 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_PROXY_HEADER +#define MRK_PQI_SSL_PROXY_HEADER + +#include + +// operating system specific network header. +#include "pqi/pqinetwork.h" + +#include +#include + +#include "pqi/pqissl.h" + + /* pqisslproxy uses SOCKS5 proxy to hidden your own address and connect to peers. + * It uses the Domain Name interface of SOCKS5, as opposed to an IP address. + */ + +class pqisslproxy; +class cert; + +/* This provides a NetBinInterface, which is + * primarily inherited from pqissl. + * fns declared here are different -> all others are identical. + */ + +class pqisslproxy: public pqissl +{ +public: + pqisslproxy(pqissllistener *l, PQInterface *parent, p3LinkMgr *lm); +virtual ~pqisslproxy(); + + // NetInterface. Is the same. + // BinInterface. Is the same. + +virtual bool connect_parameter(uint32_t type, const std::string &value); +virtual bool connect_parameter(uint32_t type, uint32_t value); + +protected: + +//Initiate is the same - except it uses the Proxy Address rather than the Peer Address. +// minor tweaks to setup data state. +virtual int Initiate_Connection(); + +// The real overloading is done in Basic Connection Complete. +// Instead of just checking for an open socket, we need to communicate with the SOCKS5 proxy. +virtual int Basic_Connection_Complete(); + +// These are the internal steps in setting up the Proxy Connection. +virtual int Proxy_Send_Method(); +virtual int Proxy_Method_Response(); +virtual int Proxy_Send_Address(); +virtual int Proxy_Connection_Complete(); + +private: + + uint32_t mProxyState; + + std::string mDomainAddress; + uint16_t mRemotePort; +}; + +#endif // MRK_PQI_SSL_PROXY_HEADER diff --git a/libretroshare/src/serialiser/rsconfigitems.cc b/libretroshare/src/serialiser/rsconfigitems.cc index 5776824bd..774b7c433 100644 --- a/libretroshare/src/serialiser/rsconfigitems.cc +++ b/libretroshare/src/serialiser/rsconfigitems.cc @@ -1060,6 +1060,9 @@ void RsPeerNetItem::clear() localAddrList.TlvClear(); extAddrList.TlvClear(); + + domain_addr.clear(); + domain_port = 0; } std::ostream &RsPeerNetItem::print(std::ostream &out, uint16_t indent) @@ -1122,6 +1125,9 @@ uint32_t RsPeerConfigSerialiser::sizeNet(RsPeerNetItem *i) s += i->localAddrList.TlvSize(); s += i->extAddrList.TlvSize(); + s += GetTlvStringSize(i->domain_addr); + s += 2; /* domain_port */ + return s; } @@ -1173,6 +1179,10 @@ bool RsPeerConfigSerialiser::serialiseNet(RsPeerNetItem *item, void *data, uint3 ok &= item->localAddrList.SetTlv(data, tlvsize, &offset); ok &= item->extAddrList.SetTlv(data, tlvsize, &offset); + // New for V0.6. + ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_DOMADDR, item->domain_addr); + ok &= setRawUInt16(data, tlvsize, &offset, item->domain_port); /* Mandatory */ + if(offset != tlvsize) { ok = false; @@ -1241,6 +1251,17 @@ RsPeerNetItem *RsPeerConfigSerialiser::deserialiseNet(void *data, uint32_t *size ok &= item->localAddrList.GetTlv(data, rssize, &offset); ok &= item->extAddrList.GetTlv(data, rssize, &offset); + // Allow acceptance of old format. + if (offset == rssize) + { + std::cerr << "RsPeerConfigSerialiser::deserialiseNet() Accepting Old format PeerNetItem" << std::endl; + return item; + } + + + // New for V0.6. + ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_DOMADDR, item->domain_addr); + ok &= getRawUInt16(data, rssize, &offset, &(item->domain_port)); /* Mandatory */ if (offset != rssize) { diff --git a/libretroshare/src/serialiser/rsconfigitems.h b/libretroshare/src/serialiser/rsconfigitems.h index 772e031da..b979cf8fc 100644 --- a/libretroshare/src/serialiser/rsconfigitems.h +++ b/libretroshare/src/serialiser/rsconfigitems.h @@ -118,6 +118,10 @@ std::ostream &print(std::ostream &out, uint16_t indent = 0); RsTlvIpAddrSet localAddrList; RsTlvIpAddrSet extAddrList; + + // for proxy connection. + std::string domain_addr; + uint16_t domain_port; }; class RsPeerServicePermissionItem : public RsItem diff --git a/libretroshare/src/serialiser/rstlvbase.h b/libretroshare/src/serialiser/rstlvbase.h index 70698df64..c99973fbf 100644 --- a/libretroshare/src/serialiser/rstlvbase.h +++ b/libretroshare/src/serialiser/rstlvbase.h @@ -157,6 +157,7 @@ const uint16_t TLV_TYPE_IPV4_LOCAL = 0x0080; const uint16_t TLV_TYPE_IPV4_REMOTE = 0x0081; const uint16_t TLV_TYPE_IPV4_LAST = 0x0082; const uint16_t TLV_TYPE_STR_DYNDNS = 0x0083; +const uint16_t TLV_TYPE_STR_DOMADDR = 0x0084; /*** MORE STRING IDS ****/ const uint16_t TLV_TYPE_STR_GROUPID = 0x00a0; From a6cf7383717adc2fd0e45540d743d8deaa92caf7 Mon Sep 17 00:00:00 2001 From: drbob Date: Tue, 3 Sep 2013 14:51:23 +0000 Subject: [PATCH 04/83] Removing old services, serialisers and other references for: - forums - channels - tunnel - blog - gamelauncher. - distrib. Note this majorly breaks the GUI, for the moment. git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@6683 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/distrib/p3distrib.cc | 3802 ----------------- libretroshare/src/distrib/p3distrib.h | 756 ---- .../src/distrib/p3distribsecurity.cc | 478 --- libretroshare/src/distrib/p3distribsecurity.h | 132 - libretroshare/src/libretroshare.pro | 63 +- libretroshare/src/pqi/p3linkmgr.cc | 72 +- libretroshare/src/pqi/p3linkmgr.h | 6 - libretroshare/src/pqi/p3peermgr.cc | 16 +- libretroshare/src/pqi/pqi_base.h | 1 - libretroshare/src/pqi/pqipersongrp.cc | 14 - libretroshare/src/pqi/pqisslpersongrp.cc | 3 - libretroshare/src/pqi/pqissltunnel.cc | 554 --- libretroshare/src/pqi/pqissltunnel.h | 146 - libretroshare/src/retroshare/rsblogs.h | 154 - libretroshare/src/retroshare/rschannels.h | 283 -- libretroshare/src/retroshare/rsdistrib.h | 56 - libretroshare/src/retroshare/rsforums.h | 166 - libretroshare/src/retroshare/rsgame.h | 113 - libretroshare/src/retroshare/rsnotify.h | 15 - libretroshare/src/retroshare/rspeers.h | 7 +- libretroshare/src/rsserver/p3face-config.cc | 14 +- libretroshare/src/rsserver/p3face-server.cc | 2 - libretroshare/src/rsserver/p3face.h | 10 - libretroshare/src/rsserver/p3peers.cc | 24 +- libretroshare/src/rsserver/p3peers.h | 2 - libretroshare/src/rsserver/rsinit.cc | 93 +- libretroshare/src/serialiser/rsblogitems.cc | 255 -- libretroshare/src/serialiser/rsblogitems.h | 91 - .../src/serialiser/rschannelitems.cc | 627 --- libretroshare/src/serialiser/rschannelitems.h | 141 - .../src/serialiser/rsdistribitems.cc | 958 ----- libretroshare/src/serialiser/rsdistribitems.h | 260 -- libretroshare/src/serialiser/rsforumitems.cc | 493 --- libretroshare/src/serialiser/rsforumitems.h | 124 - libretroshare/src/serialiser/rsgameitems.cc | 212 - libretroshare/src/serialiser/rsgameitems.h | 84 - libretroshare/src/serialiser/rstunnelitems.cc | 304 -- libretroshare/src/serialiser/rstunnelitems.h | 132 - libretroshare/src/services/p3blogs.cc | 406 -- libretroshare/src/services/p3blogs.h | 137 - libretroshare/src/services/p3channels.cc | 1092 ----- libretroshare/src/services/p3channels.h | 130 - libretroshare/src/services/p3forums.cc | 818 ---- libretroshare/src/services/p3forums.h | 105 - libretroshare/src/services/p3gamelauncher.cc | 1313 ------ libretroshare/src/services/p3gamelauncher.h | 151 - libretroshare/src/services/p3gameservice.h | 90 - 47 files changed, 15 insertions(+), 14890 deletions(-) delete mode 100644 libretroshare/src/distrib/p3distrib.cc delete mode 100644 libretroshare/src/distrib/p3distrib.h delete mode 100644 libretroshare/src/distrib/p3distribsecurity.cc delete mode 100644 libretroshare/src/distrib/p3distribsecurity.h delete mode 100644 libretroshare/src/pqi/pqissltunnel.cc delete mode 100644 libretroshare/src/pqi/pqissltunnel.h delete mode 100644 libretroshare/src/retroshare/rsblogs.h delete mode 100644 libretroshare/src/retroshare/rschannels.h delete mode 100644 libretroshare/src/retroshare/rsdistrib.h delete mode 100644 libretroshare/src/retroshare/rsforums.h delete mode 100644 libretroshare/src/retroshare/rsgame.h delete mode 100644 libretroshare/src/serialiser/rsblogitems.cc delete mode 100644 libretroshare/src/serialiser/rsblogitems.h delete mode 100644 libretroshare/src/serialiser/rschannelitems.cc delete mode 100644 libretroshare/src/serialiser/rschannelitems.h delete mode 100644 libretroshare/src/serialiser/rsdistribitems.cc delete mode 100644 libretroshare/src/serialiser/rsdistribitems.h delete mode 100644 libretroshare/src/serialiser/rsforumitems.cc delete mode 100644 libretroshare/src/serialiser/rsforumitems.h delete mode 100644 libretroshare/src/serialiser/rsgameitems.cc delete mode 100644 libretroshare/src/serialiser/rsgameitems.h delete mode 100644 libretroshare/src/serialiser/rstunnelitems.cc delete mode 100644 libretroshare/src/serialiser/rstunnelitems.h delete mode 100644 libretroshare/src/services/p3blogs.cc delete mode 100644 libretroshare/src/services/p3blogs.h delete mode 100644 libretroshare/src/services/p3channels.cc delete mode 100644 libretroshare/src/services/p3channels.h delete mode 100644 libretroshare/src/services/p3forums.cc delete mode 100644 libretroshare/src/services/p3forums.h delete mode 100644 libretroshare/src/services/p3gamelauncher.cc delete mode 100644 libretroshare/src/services/p3gamelauncher.h delete mode 100644 libretroshare/src/services/p3gameservice.h 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 From 561cfcf18998903dbbfc00672c377c9f4d1f4ac2 Mon Sep 17 00:00:00 2001 From: drbob Date: Sat, 7 Sep 2013 02:55:35 +0000 Subject: [PATCH 05/83] Switching on GXS by default. switching rs data directory to ./retroshare6 for the moment. git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@6701 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/libretroshare.pro | 2 +- libretroshare/src/rsserver/rsinit.cc | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/libretroshare/src/libretroshare.pro b/libretroshare/src/libretroshare.pro index 59479a845..3fd616849 100644 --- a/libretroshare/src/libretroshare.pro +++ b/libretroshare/src/libretroshare.pro @@ -7,7 +7,7 @@ CONFIG += test_voip #GXS Stuff. # This should be disabled for releases until further notice. -#CONFIG += gxs debug +CONFIG += gxs debug profiling { QMAKE_CXXFLAGS -= -fomit-frame-pointer diff --git a/libretroshare/src/rsserver/rsinit.cc b/libretroshare/src/rsserver/rsinit.cc index 67008f97c..d917cbc2b 100644 --- a/libretroshare/src/rsserver/rsinit.cc +++ b/libretroshare/src/rsserver/rsinit.cc @@ -806,7 +806,7 @@ bool RsInit::setupBaseDir() return false ; } RsInitConfig::basedir = h; - RsInitConfig::basedir += "/.retroshare"; + RsInitConfig::basedir += "/.retroshare6"; #else if (RsInitConfig::portable) { // use directory "Data" in portable version @@ -844,7 +844,7 @@ bool RsInit::setupBaseDir() std::cerr << "Cannot Create BaseConfig Dir" << std::endl; return false ; } - RsInitConfig::basedir += "\\RetroShare"; + RsInitConfig::basedir += "\\RetroShare6"; } #endif /******************************** WINDOWS/UNIX SPECIFIC PART ******************/ From 683e75aeefd2e998606a4def80183d8a4b207b3b Mon Sep 17 00:00:00 2001 From: drbob Date: Sat, 7 Sep 2013 04:21:48 +0000 Subject: [PATCH 06/83] Removed Forums / Channels / Blogs stuff. and made GUI recompile. git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@6702 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- retroshare-gui/src/gui/ChannelFeed.cpp | 927 -------- retroshare-gui/src/gui/ChannelFeed.h | 139 -- retroshare-gui/src/gui/ChannelFeed.ui | 314 --- .../src/gui/FileTransfer/DLListDelegate.cpp | 2 +- .../src/gui/FileTransfer/TransfersDialog.cpp | 2 +- retroshare-gui/src/gui/ForumsDialog.cpp | 2113 ----------------- retroshare-gui/src/gui/ForumsDialog.h | 214 -- retroshare-gui/src/gui/ForumsDialog.ui | 591 ----- retroshare-gui/src/gui/MainWindow.cpp | 18 +- retroshare-gui/src/gui/MainWindow.h | 12 +- retroshare-gui/src/gui/NewsFeed.cpp | 18 +- retroshare-gui/src/gui/NewsFeed.h | 3 + retroshare-gui/src/gui/RetroShareLink.cpp | 14 +- .../src/gui/channels/ChannelDetails.cpp | 117 - .../src/gui/channels/ChannelDetails.h | 57 - .../src/gui/channels/ChannelDetails.ui | 148 -- .../src/gui/channels/ChannelUserNotify.cpp | 106 - .../src/gui/channels/ChannelUserNotify.h | 47 - .../src/gui/channels/CreateChannel.cpp | 151 -- .../src/gui/channels/CreateChannel.h | 51 - .../src/gui/channels/CreateChannel.ui | 371 --- .../src/gui/channels/CreateChannelMsg.cpp | 648 ----- .../src/gui/channels/CreateChannelMsg.h | 91 - .../src/gui/channels/CreateChannelMsg.ui | 365 --- .../src/gui/channels/EditChanDetails.cpp | 118 - .../src/gui/channels/EditChanDetails.h | 55 - .../src/gui/channels/EditChanDetails.ui | 143 -- retroshare-gui/src/gui/channels/ShareKey.cpp | 6 +- retroshare-gui/src/gui/common/StatusDefs.cpp | 6 - retroshare-gui/src/gui/feeds/BlogMsgItem.cpp | 189 -- retroshare-gui/src/gui/feeds/BlogMsgItem.h | 65 - retroshare-gui/src/gui/feeds/BlogMsgItem.ui | 242 -- retroshare-gui/src/gui/feeds/BlogNewItem.cpp | 219 -- retroshare-gui/src/gui/feeds/BlogNewItem.h | 62 - retroshare-gui/src/gui/feeds/BlogNewItem.ui | 260 -- retroshare-gui/src/gui/feeds/ChanMsgItem.cpp | 466 ---- retroshare-gui/src/gui/feeds/ChanMsgItem.h | 74 - retroshare-gui/src/gui/feeds/ChanMsgItem.ui | 481 ---- retroshare-gui/src/gui/feeds/ChanNewItem.cpp | 205 -- retroshare-gui/src/gui/feeds/ChanNewItem.h | 60 - retroshare-gui/src/gui/feeds/ChanNewItem.ui | 284 --- retroshare-gui/src/gui/feeds/ForumMsgItem.cpp | 436 ---- retroshare-gui/src/gui/feeds/ForumMsgItem.h | 69 - retroshare-gui/src/gui/feeds/ForumMsgItem.ui | 664 ------ retroshare-gui/src/gui/feeds/ForumNewItem.cpp | 206 -- retroshare-gui/src/gui/feeds/ForumNewItem.h | 61 - retroshare-gui/src/gui/feeds/ForumNewItem.ui | 325 --- retroshare-gui/src/gui/forums/CreateForum.cpp | 134 -- retroshare-gui/src/gui/forums/CreateForum.h | 54 - retroshare-gui/src/gui/forums/CreateForum.ui | 314 --- .../src/gui/forums/CreateForumMsg.cpp | 259 -- .../src/gui/forums/CreateForumMsg.h | 64 - .../src/gui/forums/CreateForumMsg.ui | 282 --- .../src/gui/forums/EditForumDetails.cpp | 82 - .../src/gui/forums/EditForumDetails.h | 53 - .../src/gui/forums/EditForumDetails.ui | 87 - .../src/gui/forums/ForumDetails.cpp | 112 - retroshare-gui/src/gui/forums/ForumDetails.h | 57 - retroshare-gui/src/gui/forums/ForumDetails.ui | 175 -- .../src/gui/forums/ForumUserNotify.cpp | 106 - .../src/gui/forums/ForumUserNotify.h | 47 - retroshare-gui/src/gui/settings/ForumPage.cpp | 58 - retroshare-gui/src/gui/settings/ForumPage.h | 49 - retroshare-gui/src/gui/settings/ForumPage.ui | 70 - .../src/gui/settings/NotifyPage.cpp | 4 + .../src/gui/settings/ServerPage.cpp | 2 +- .../src/gui/settings/rsettingswin.cpp | 4 +- .../src/gui/settings/rsharesettings.cpp | 4 +- .../src/gui/unfinished/blogs/BlogDetails.cpp | 147 -- .../src/gui/unfinished/blogs/BlogDetails.h | 68 - .../src/gui/unfinished/blogs/BlogDetails.ui | 151 -- .../src/gui/unfinished/blogs/BlogsDialog.cpp | 588 ----- .../src/gui/unfinished/blogs/BlogsDialog.h | 107 - .../src/gui/unfinished/blogs/BlogsDialog.ui | 568 ----- .../src/gui/unfinished/blogs/BlogsMsgItem.cpp | 192 -- .../src/gui/unfinished/blogs/BlogsMsgItem.h | 71 - .../src/gui/unfinished/blogs/BlogsMsgItem.ui | 274 --- .../src/gui/unfinished/blogs/CreateBlog.cpp | 173 -- .../src/gui/unfinished/blogs/CreateBlog.h | 60 - .../src/gui/unfinished/blogs/CreateBlog.ui | 329 --- .../gui/unfinished/blogs/CreateBlogMsg.cpp | 923 ------- .../src/gui/unfinished/blogs/CreateBlogMsg.h | 161 -- .../src/gui/unfinished/blogs/CreateBlogMsg.ui | 343 --- retroshare-gui/src/retroshare-gui.pro | 192 +- 84 files changed, 160 insertions(+), 17419 deletions(-) delete mode 100644 retroshare-gui/src/gui/ChannelFeed.cpp delete mode 100644 retroshare-gui/src/gui/ChannelFeed.h delete mode 100644 retroshare-gui/src/gui/ChannelFeed.ui delete mode 100644 retroshare-gui/src/gui/ForumsDialog.cpp delete mode 100644 retroshare-gui/src/gui/ForumsDialog.h delete mode 100644 retroshare-gui/src/gui/ForumsDialog.ui delete mode 100644 retroshare-gui/src/gui/channels/ChannelDetails.cpp delete mode 100644 retroshare-gui/src/gui/channels/ChannelDetails.h delete mode 100644 retroshare-gui/src/gui/channels/ChannelDetails.ui delete mode 100644 retroshare-gui/src/gui/channels/ChannelUserNotify.cpp delete mode 100644 retroshare-gui/src/gui/channels/ChannelUserNotify.h delete mode 100644 retroshare-gui/src/gui/channels/CreateChannel.cpp delete mode 100644 retroshare-gui/src/gui/channels/CreateChannel.h delete mode 100644 retroshare-gui/src/gui/channels/CreateChannel.ui delete mode 100644 retroshare-gui/src/gui/channels/CreateChannelMsg.cpp delete mode 100644 retroshare-gui/src/gui/channels/CreateChannelMsg.h delete mode 100644 retroshare-gui/src/gui/channels/CreateChannelMsg.ui delete mode 100644 retroshare-gui/src/gui/channels/EditChanDetails.cpp delete mode 100644 retroshare-gui/src/gui/channels/EditChanDetails.h delete mode 100644 retroshare-gui/src/gui/channels/EditChanDetails.ui delete mode 100644 retroshare-gui/src/gui/feeds/BlogMsgItem.cpp delete mode 100644 retroshare-gui/src/gui/feeds/BlogMsgItem.h delete mode 100644 retroshare-gui/src/gui/feeds/BlogMsgItem.ui delete mode 100644 retroshare-gui/src/gui/feeds/BlogNewItem.cpp delete mode 100644 retroshare-gui/src/gui/feeds/BlogNewItem.h delete mode 100644 retroshare-gui/src/gui/feeds/BlogNewItem.ui delete mode 100644 retroshare-gui/src/gui/feeds/ChanMsgItem.cpp delete mode 100644 retroshare-gui/src/gui/feeds/ChanMsgItem.h delete mode 100644 retroshare-gui/src/gui/feeds/ChanMsgItem.ui delete mode 100644 retroshare-gui/src/gui/feeds/ChanNewItem.cpp delete mode 100644 retroshare-gui/src/gui/feeds/ChanNewItem.h delete mode 100644 retroshare-gui/src/gui/feeds/ChanNewItem.ui delete mode 100644 retroshare-gui/src/gui/feeds/ForumMsgItem.cpp delete mode 100644 retroshare-gui/src/gui/feeds/ForumMsgItem.h delete mode 100644 retroshare-gui/src/gui/feeds/ForumMsgItem.ui delete mode 100644 retroshare-gui/src/gui/feeds/ForumNewItem.cpp delete mode 100644 retroshare-gui/src/gui/feeds/ForumNewItem.h delete mode 100644 retroshare-gui/src/gui/feeds/ForumNewItem.ui delete mode 100644 retroshare-gui/src/gui/forums/CreateForum.cpp delete mode 100644 retroshare-gui/src/gui/forums/CreateForum.h delete mode 100644 retroshare-gui/src/gui/forums/CreateForum.ui delete mode 100644 retroshare-gui/src/gui/forums/CreateForumMsg.cpp delete mode 100644 retroshare-gui/src/gui/forums/CreateForumMsg.h delete mode 100644 retroshare-gui/src/gui/forums/CreateForumMsg.ui delete mode 100644 retroshare-gui/src/gui/forums/EditForumDetails.cpp delete mode 100644 retroshare-gui/src/gui/forums/EditForumDetails.h delete mode 100644 retroshare-gui/src/gui/forums/EditForumDetails.ui delete mode 100644 retroshare-gui/src/gui/forums/ForumDetails.cpp delete mode 100644 retroshare-gui/src/gui/forums/ForumDetails.h delete mode 100644 retroshare-gui/src/gui/forums/ForumDetails.ui delete mode 100644 retroshare-gui/src/gui/forums/ForumUserNotify.cpp delete mode 100644 retroshare-gui/src/gui/forums/ForumUserNotify.h delete mode 100644 retroshare-gui/src/gui/settings/ForumPage.cpp delete mode 100644 retroshare-gui/src/gui/settings/ForumPage.h delete mode 100644 retroshare-gui/src/gui/settings/ForumPage.ui delete mode 100644 retroshare-gui/src/gui/unfinished/blogs/BlogDetails.cpp delete mode 100644 retroshare-gui/src/gui/unfinished/blogs/BlogDetails.h delete mode 100644 retroshare-gui/src/gui/unfinished/blogs/BlogDetails.ui delete mode 100644 retroshare-gui/src/gui/unfinished/blogs/BlogsDialog.cpp delete mode 100644 retroshare-gui/src/gui/unfinished/blogs/BlogsDialog.h delete mode 100644 retroshare-gui/src/gui/unfinished/blogs/BlogsDialog.ui delete mode 100644 retroshare-gui/src/gui/unfinished/blogs/BlogsMsgItem.cpp delete mode 100644 retroshare-gui/src/gui/unfinished/blogs/BlogsMsgItem.h delete mode 100644 retroshare-gui/src/gui/unfinished/blogs/BlogsMsgItem.ui delete mode 100644 retroshare-gui/src/gui/unfinished/blogs/CreateBlog.cpp delete mode 100644 retroshare-gui/src/gui/unfinished/blogs/CreateBlog.h delete mode 100644 retroshare-gui/src/gui/unfinished/blogs/CreateBlog.ui delete mode 100644 retroshare-gui/src/gui/unfinished/blogs/CreateBlogMsg.cpp delete mode 100644 retroshare-gui/src/gui/unfinished/blogs/CreateBlogMsg.h delete mode 100644 retroshare-gui/src/gui/unfinished/blogs/CreateBlogMsg.ui diff --git a/retroshare-gui/src/gui/ChannelFeed.cpp b/retroshare-gui/src/gui/ChannelFeed.cpp deleted file mode 100644 index 7d3ba46ea..000000000 --- a/retroshare-gui/src/gui/ChannelFeed.cpp +++ /dev/null @@ -1,927 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2008 Robert Fernie - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#include - -#include "ChannelFeed.h" - -#include "feeds/ChanMsgItem.h" -#include "common/PopularityDefs.h" -#include "settings/rsharesettings.h" - -#include "channels/CreateChannel.h" -#include "channels/ChannelDetails.h" -#include "channels/CreateChannelMsg.h" -#include "channels/EditChanDetails.h" -#include "channels/ShareKey.h" -#include "channels/ChannelUserNotify.h" -#include "notifyqt.h" -#include "RetroShareLink.h" - -#define CHAN_DEFAULT_IMAGE ":/images/channels.png" - -#define WARNING_LIMIT 3600*24*2 - -/* Images for TreeWidget */ -#define IMAGE_CHANNELBLUE ":/images/channelsblue.png" -#define IMAGE_CHANNELGREEN ":/images/channelsgreen.png" -#define IMAGE_CHANNELRED ":/images/channelsred.png" -#define IMAGE_CHANNELYELLOW ":/images/channelsyellow.png" - -/**** - * #define CHAN_DEBUG - ***/ - -#define USE_THREAD - -/** Constructor */ -ChannelFeed::ChannelFeed(QWidget *parent) -: RsAutoUpdatePage(1000,parent) -{ - /* Invoke the Qt Designer generated object setup routine */ - setupUi(this); - - connect(postButton, SIGNAL(clicked()), this, SLOT(createMsg())); - connect(NotifyQt::getInstance(), SIGNAL(channelMsgReadSatusChanged(QString,QString,int)), this, SLOT(channelMsgReadSatusChanged(QString,QString,int))); - - /*************** Setup Left Hand Side (List of Channels) ****************/ - - connect(treeWidget, SIGNAL(treeCustomContextMenuRequested(QPoint)), this, SLOT( channelListCustomPopupMenu( QPoint ) ) ); - connect(treeWidget, SIGNAL(treeCurrentItemChanged(QString)), this, SLOT(selectChannel(QString))); - - mChannelId.clear(); - - /* Set initial size the splitter */ - QList sizes; - sizes << 300 << width(); // Qt calculates the right sizes - splitter->setSizes(sizes); - - /* Initialize group tree */ - QToolButton *newChannelButton = new QToolButton(this); - newChannelButton->setIcon(QIcon(":/images/add_channel24.png")); - newChannelButton->setToolTip(tr("Create Channel")); - connect(newChannelButton, SIGNAL(clicked()), this, SLOT(createChannel())); - treeWidget->addToolButton(newChannelButton); - - ownChannels = treeWidget->addCategoryItem(tr("My Channels"), QIcon(IMAGE_CHANNELBLUE), true); - subcribedChannels = treeWidget->addCategoryItem(tr("Subscribed Channels"), QIcon(IMAGE_CHANNELRED), true); - popularChannels = treeWidget->addCategoryItem(tr("Popular Channels"), QIcon(IMAGE_CHANNELGREEN ), false); - otherChannels = treeWidget->addCategoryItem(tr("Other Channels"), QIcon(IMAGE_CHANNELYELLOW), false); - - progressLabel->hide(); - progressBar->hide(); - - fillThread = NULL; - - //added from ahead - updateChannelList(); - - nameLabel->setMinimumWidth(20); - - /* load settings */ - processSettings(true); - - updateChannelMsgs(); - - QString help_str = tr( - "

  Channels

\ -

Channels allow you to post data (e.g. movies, music) that will spread in the network \ - among people who subscribed your channel. If you activate auto-download on a channel, files attached to each post will start \ - downloading automatically when the post is received.

\ -

You see channels your friends are subscribed to, and forward subscribed channels to \ - your friends. This promotes good channels in the network. \ - When you first connect to a new friend, it's likely \ - you will receive many such cache files, and new channels will appear. \ -

\ -

Only the channel's creator can post on that channel. Other peers \ - in the network can only read from it, unless the channel is private. You can however share the posting rights or the reading rights \ - with your friends.

\ - ") ; - - - registerHelpButton(helpButton,help_str) ; -} - -ChannelFeed::~ChannelFeed() -{ - if (fillThread) { - fillThread->stop(); - delete(fillThread); - fillThread = NULL; - } - - // save settings - processSettings(false); -} - -UserNotify *ChannelFeed::getUserNotify(QObject *parent) -{ - return new ChannelUserNotify(parent); -} - -void ChannelFeed::processSettings(bool load) -{ - Settings->beginGroup(QString("ChannelFeed")); - - if (load) { - // load settings - - // state of splitter - splitter->restoreState(Settings->value("Splitter").toByteArray()); - } else { - // save settings - - // state of splitter - Settings->setValue("Splitter", splitter->saveState()); - } - - treeWidget->processSettings(Settings, load); - - Settings->endGroup(); -} - -void ChannelFeed::channelListCustomPopupMenu( QPoint /*point*/ ) -{ - ChannelInfo ci; - if (!rsChannels->getChannelInfo(mChannelId, ci)) { - return; - } - - QMenu contextMnu(this); - - QAction *postchannelAct = new QAction(QIcon(":/images/mail_reply.png"), tr( "Post to Channel" ), &contextMnu); - connect( postchannelAct , SIGNAL( triggered() ), this, SLOT( createMsg() ) ); - - QAction *subscribechannelAct = new QAction(QIcon(":/images/edit_add24.png"), tr( "Subscribe to Channel" ), &contextMnu); - connect( subscribechannelAct , SIGNAL( triggered() ), this, SLOT( subscribeChannel() ) ); - - QAction *unsubscribechannelAct = new QAction(QIcon(":/images/cancel.png"), tr( "Unsubscribe to Channel" ), &contextMnu); - connect( unsubscribechannelAct , SIGNAL( triggered() ), this, SLOT( unsubscribeChannel() ) ); - - QAction *setallasreadchannelAct = new QAction(QIcon(":/images/message-mail-read.png"), tr( "Set all as read" ), &contextMnu); - connect( setallasreadchannelAct , SIGNAL( triggered() ), this, SLOT( setAllAsReadClicked() ) ); - - bool autoDl = false; - rsChannels->channelGetAutoDl(mChannelId, autoDl); - - QAction *autochannelAct = autoDl? (new QAction(QIcon(":/images/redled.png"), tr( "Disable Auto-Download" ), &contextMnu)) - : (new QAction(QIcon(":/images/start.png"),tr( "Enable Auto-Download" ), &contextMnu)) ; - - connect( autochannelAct , SIGNAL( triggered() ), this, SLOT( toggleAutoDownload() ) ); - - QAction *channeldetailsAct = new QAction(QIcon(":/images/info16.png"), tr( "Show Channel Details" ), &contextMnu); - connect( channeldetailsAct , SIGNAL( triggered() ), this, SLOT( showChannelDetails() ) ); - - QAction *restoreKeysAct = new QAction(QIcon(":/images/settings16.png"), tr("Restore Publish Rights for Channel" ), &contextMnu); - connect( restoreKeysAct , SIGNAL( triggered() ), this, SLOT( restoreChannelKeys() ) ); - - QAction *editChannelDetailAct = new QAction(QIcon(":/images/edit_16.png"), tr("Edit Channel Details"), &contextMnu); - connect( editChannelDetailAct, SIGNAL( triggered() ), this, SLOT( editChannelDetail() ) ); - - QAction *shareKeyAct = new QAction(QIcon(":/images/gpgp_key_generate.png"), tr("Share Channel"), &contextMnu); - connect( shareKeyAct, SIGNAL( triggered() ), this, SLOT( shareKey() ) ); - - if((ci.channelFlags & RS_DISTRIB_ADMIN) && (ci.channelFlags & RS_DISTRIB_SUBSCRIBED)) - contextMnu.addAction( editChannelDetailAct); - else - contextMnu.addAction( channeldetailsAct ); - - if((ci.channelFlags & RS_DISTRIB_PUBLISH) && (ci.channelFlags & RS_DISTRIB_SUBSCRIBED)) - { - contextMnu.addAction( postchannelAct ); - contextMnu.addAction( shareKeyAct ); - } - - if(ci.channelFlags & RS_DISTRIB_SUBSCRIBED) - { - QMenu *directoryMenu = contextMnu.addMenu(QIcon(":/images/folderopen.png"),tr("Set destination directory")) ; - - QAction *specifyDestinationDirectoryAct = new QAction(QIcon(":/images/filefind.png"), tr("Other..."), &contextMnu); - directoryMenu->addAction(specifyDestinationDirectoryAct); - connect(specifyDestinationDirectoryAct,SIGNAL(triggered()),this,SLOT(chooseDestinationDirectory())) ; - - // Now get the list of existing directories. - - std::list dirs ; - rsFiles->getSharedDirectories(dirs) ; - bool found = false ; - - for(std::list::const_iterator it(dirs.begin());it!=dirs.end();++it) - { - // check for existence of directory name - QFile directory(QString::fromUtf8((*it).filename.c_str())) ; - - if(!directory.exists()) continue ; - if(!(directory.permissions() & QFile::WriteOwner)) continue ; - - QAction *act ; - - if(ci.destination_directory == (*it).filename) - { - act = new QAction(QIcon(":/images/start.png"),QString::fromUtf8((*it).virtualname.c_str()),directoryMenu) ; - found = true ; - } - else - act = new QAction(QString::fromUtf8((*it).virtualname.c_str()),directoryMenu) ; - - act->setData(QString::fromUtf8((*it).filename.c_str())) ; - connect(act,SIGNAL(triggered()),this,SLOT(setDestinationDirectory())) ; - directoryMenu->addAction(act) ; - } - QAction *defaultDestinationDirectoryAct = new QAction(tr("[Default]"), &contextMnu); - defaultDestinationDirectoryAct->setData(QString()) ; - connect(defaultDestinationDirectoryAct,SIGNAL(triggered()),this,SLOT(setDestinationDirectory())) ; - - directoryMenu->addAction(defaultDestinationDirectoryAct); - - if(ci.destination_directory.empty()) - defaultDestinationDirectoryAct->setIcon(QIcon(":/images/start.png")) ; - else if(!found) - specifyDestinationDirectoryAct->setIcon(QIcon(":/images/start.png")) ; - } - - if(ci.channelFlags & RS_DISTRIB_SUBSCRIBED) - { - contextMnu.addAction( unsubscribechannelAct ); - contextMnu.addAction( restoreKeysAct ); - contextMnu.addSeparator(); - contextMnu.addAction( autochannelAct ); - contextMnu.addAction( setallasreadchannelAct ); - } - else - contextMnu.addAction( subscribechannelAct ); - - contextMnu.addSeparator(); - QAction *action = contextMnu.addAction(QIcon(":/images/copyrslink.png"), tr("Copy RetroShare Link"), this, SLOT(copyChannelLink())); - action->setEnabled(!mChannelId.empty()); - -#ifdef CHAN_DEBUG - contextMnu.addSeparator(); - action = contextMnu.addAction("Generate mass data", this, SLOT(generateMassData())); - action->setEnabled (!mChannelId.empty() && (ci.channelFlags & RS_DISTRIB_PUBLISH)); -#endif - - contextMnu.exec(QCursor::pos()); -} -void ChannelFeed::setDestinationDirectory() -{ - ChannelInfo ci; - if (!rsChannels->getChannelInfo(mChannelId, ci)) - return; - - std::string dest_dir(qobject_cast(sender())->data().toString().toUtf8().data()) ; - - std::cerr << "Setting new directory " << dest_dir << " to channel " << mChannelId << std::endl; - rsChannels->channelSetDestinationDirectory(mChannelId,dest_dir) ; -} -void ChannelFeed::chooseDestinationDirectory() -{ - ChannelInfo ci; - if (!rsChannels->getChannelInfo(mChannelId, ci)) - return; - - QString dirname = QFileDialog::getExistingDirectory(NULL,tr("Select channel destination directory"),QString::fromStdString(ci.destination_directory),QFileDialog::ShowDirsOnly) ; - - if(dirname.isNull()) - return ; - - std::cerr << "Setting new directory " << dirname.toStdString() << " to channel " << mChannelId << std::endl; - rsChannels->channelSetDestinationDirectory(mChannelId,dirname.toStdString()) ; -} -void ChannelFeed::createChannel() -{ - CreateChannel *cf = new CreateChannel(); - cf->show(); - - /* window will destroy itself! */ -} - -/*************************************************************************************/ -/*************************************************************************************/ -/*************************************************************************************/ - -QScrollArea *ChannelFeed::getScrollArea() -{ - return scrollArea; -} - -void ChannelFeed::deleteFeedItem(QWidget */*item*/, uint32_t /*type*/) -{ -} - -void ChannelFeed::openChat(std::string /*peerId*/) -{ -} - -void ChannelFeed::openComments(uint32_t /*type*/ , const RsGxsGroupId & /*grpId */, const RsGxsMessageId & /*msgId*/, const QString & /* title */) -{ -} - -void ChannelFeed::editChannelDetail(){ - - EditChanDetails editUi(this, mChannelId); - editUi.exec(); -} - -void ChannelFeed::shareKey() -{ - ShareKey shareUi(this, mChannelId, CHANNEL_KEY_SHARE); - shareUi.exec(); -} - -void ChannelFeed::copyChannelLink() -{ - if (mChannelId.empty()) { - return; - } - - ChannelInfo ci; - if (rsChannels->getChannelInfo(mChannelId, ci)) { - RetroShareLink link; - if (link.createChannel(ci.channelId, "")) { - QList urls; - urls.push_back(link); - RSLinkClipboard::copyLinks(urls); - } - } -} - -void ChannelFeed::createMsg() -{ - if (mChannelId.empty()) { - return; - } - - CreateChannelMsg *msgDialog = new CreateChannelMsg(mChannelId); - msgDialog->show(); - - /* window will destroy itself! */ -} - -void ChannelFeed::restoreChannelKeys() -{ - if(rsChannels->channelRestoreKeys(mChannelId)) - QMessageBox::information(NULL,tr("Publish rights restored."),tr("Publish rights have been restored for this channel.")) ; - else - QMessageBox::warning(NULL,tr("Publish not restored."),tr("Publish rights can't be restored for this channel.
You're not the creator of this channel.")) ; -} - -void ChannelFeed::selectChannel(const QString &id) -{ - mChannelId = id.toStdString(); - - bool autoDl = false; - rsChannels->channelGetAutoDl(mChannelId, autoDl); - - setAutoDownloadButton(autoDl); - - updateChannelMsgs(); -} - -void ChannelFeed::updateDisplay() -{ - if (!rsChannels) { - return; - } - - std::list chanIds; - std::list::iterator it; - - if (rsChannels->channelsChanged(chanIds)) { - /* update channel list */ - updateChannelList(); - - it = std::find(chanIds.begin(), chanIds.end(), mChannelId); - if (it != chanIds.end()) { - updateChannelMsgs(); - } - } -} - -static void channelInfoToGroupItemInfo(const ChannelInfo &channelInfo, GroupItemInfo &groupItemInfo) -{ - groupItemInfo.id = QString::fromStdString(channelInfo.channelId); - groupItemInfo.name = QString::fromStdWString(channelInfo.channelName); - groupItemInfo.description = QString::fromStdWString(channelInfo.channelDesc); - groupItemInfo.popularity = channelInfo.pop; - groupItemInfo.lastpost = QDateTime::fromTime_t(channelInfo.lastPost); - - QPixmap chanImage; - if (channelInfo.pngImageLen) { - chanImage.loadFromData(channelInfo.pngChanImage, channelInfo.pngImageLen, "PNG"); - } else { - chanImage = QPixmap(CHAN_DEFAULT_IMAGE); - } - - groupItemInfo.icon = QIcon(chanImage); -} - -void ChannelFeed::updateChannelList() -{ - if (!rsChannels) { - return; - } - - std::list channelList; - std::list::iterator it; - rsChannels->getChannelList(channelList); - - std::list keysAvailable; - std::list::iterator keyIt; - rsChannels->getPubKeysAvailableGrpIds(keysAvailable); - - /* get the ids for our lists */ - QList adminList; - QList subList; - QList popList; - QList otherList; - std::multimap popMap; - - for(it = channelList.begin(); it != channelList.end(); it++) { - /* sort it into Publish (Own), Subscribed, Popular and Other */ - uint32_t flags = it->channelFlags; - - GroupItemInfo groupItemInfo; - channelInfoToGroupItemInfo(*it, groupItemInfo); - - if ((flags & RS_DISTRIB_ADMIN) && (flags & RS_DISTRIB_PUBLISH) && (flags & RS_DISTRIB_SUBSCRIBED)) { - adminList.push_back(groupItemInfo); - } else { - for (keyIt = keysAvailable.begin(); keyIt != keysAvailable.end(); keyIt++) { - if (it->channelId == *keyIt) { - /* Found Key, set title text to bold and colored blue */ - groupItemInfo.privatekey = true; - break; - } - } - - if ((flags & RS_DISTRIB_SUBSCRIBED) || ((flags & RS_DISTRIB_SUBSCRIBED) && (flags & RS_DISTRIB_PUBLISH)) ) { - subList.push_back(groupItemInfo); - } else { - /* rate the others by popularity */ - popMap.insert(std::make_pair(it->pop, groupItemInfo)); - } - } - } - - /* iterate backwards through popMap - take the top 5 or 10% of list */ - uint32_t popCount = 5; - if (popCount < popMap.size() / 10) { - popCount = popMap.size() / 10; - } - - uint32_t i = 0; - std::multimap::reverse_iterator rit; - for (rit = popMap.rbegin(); rit != popMap.rend(); rit++) { - if (i < popCount) { - popList.push_back(rit->second); - i++; - } else { - otherList.push_back(rit->second); - } - } - - /* now we have our lists ---> update entries */ - - treeWidget->fillGroupItems(ownChannels, adminList); - treeWidget->fillGroupItems(subcribedChannels, subList); - treeWidget->fillGroupItems(popularChannels, popList); - treeWidget->fillGroupItems(otherChannels, otherList); - - updateMessageSummaryList(""); -} - - -void ChannelFeed::channelMsgReadSatusChanged(const QString& channelId, const QString& /*msgId*/, int /*status*/) -{ - updateMessageSummaryList(channelId.toStdString()); -} - -void ChannelFeed::updateMessageSummaryList(const std::string &channelId) -{ - QTreeWidgetItem *items[2] = { ownChannels, subcribedChannels }; - - for (int item = 0; item < 2; item++) { - int child; - int childCount = items[item]->childCount(); - for (child = 0; child < childCount; child++) { - QTreeWidgetItem *childItem = items[item]->child(child); - std::string childId = treeWidget->itemId(childItem).toStdString(); - if (childId.empty()) { - continue; - } - - if (channelId.empty() || childId == channelId) { - /* Calculate unread messages */ - unsigned int newMessageCount = 0; - unsigned int unreadMessageCount = 0; - rsChannels->getMessageCount(childId, newMessageCount, unreadMessageCount); - - treeWidget->setUnreadCount(childItem, unreadMessageCount); - - if (channelId.empty() == false) { - /* Calculate only this channel */ - break; - } - } - } - } -} - -static bool sortChannelMsgSummary(const ChannelMsgSummary &msg1, const ChannelMsgSummary &msg2) -{ - return (msg1.ts > msg2.ts); -} - -void ChannelFeed::updateChannelMsgs() -{ - if (fillThread) { -#ifdef CHAN_DEBUG - std::cerr << "ChannelFeed::updateChannelMsgs() stop current fill thread" << std::endl; -#endif - // stop current fill thread - ChannelFillThread *thread = fillThread; - fillThread = NULL; - thread->stop(); - delete(thread); - - progressLabel->hide(); - progressBar->hide(); - } - - if (!rsChannels) { - return; - } - - /* replace all the messages with new ones */ - QList::iterator mit; - for (mit = mChanMsgItems.begin(); mit != mChanMsgItems.end(); mit++) { - delete (*mit); - } - mChanMsgItems.clear(); - - ChannelInfo ci; - if (!rsChannels->getChannelInfo(mChannelId, ci)) { - postButton->setEnabled(false); - nameLabel->setText(tr("No Channel Selected")); - logoLabel->setPixmap(QPixmap(":/images/channels.png")); - logoLabel->setEnabled(false); - return; - } - - QPixmap chanImage; - if (ci.pngImageLen != 0) { - chanImage.loadFromData(ci.pngChanImage, ci.pngImageLen, "PNG"); - } else { - chanImage = QPixmap(CHAN_DEFAULT_IMAGE); - } - logoLabel->setPixmap(chanImage); - logoLabel->setEnabled(true); - - /* set Channel name */ - nameLabel->setText(QString::fromStdWString(ci.channelName)); - - if (ci.channelFlags & RS_DISTRIB_PUBLISH) { - postButton->setEnabled(true); - } else { - postButton->setEnabled(false); - } - - if (ci.channelFlags & RS_DISTRIB_SUBSCRIBED) { - actionEnable_Auto_Download->setEnabled(true); - } else { - actionEnable_Auto_Download->setEnabled(false); - } - -#ifdef USE_THREAD - progressLabel->show(); - progressBar->reset(); - progressBar->show(); - - // create fill thread - fillThread = new ChannelFillThread(this, mChannelId); - - // connect thread - connect(fillThread, SIGNAL(finished()), this, SLOT(fillThreadFinished()), Qt::BlockingQueuedConnection); - connect(fillThread, SIGNAL(addMsg(QString,QString,int,int)), this, SLOT(fillThreadAddMsg(QString,QString,int,int)), Qt::BlockingQueuedConnection); - -#ifdef CHAN_DEBUG - std::cerr << "ChannelFeed::updateChannelMsgs() Start fill thread" << std::endl; -#endif - - // start thread - fillThread->start(); -#else - std::list msgs; - std::list::iterator it; - rsChannels->getChannelMsgList(mChannelId, msgs); - - msgs.sort(sortChannelMsgSummary); - - for (it = msgs.begin(); it != msgs.end(); it++) { - ChanMsgItem *cmi = new ChanMsgItem(this, 0, mChannelId, it->msgId, true); - mChanMsgItems.push_back(cmi); - verticalLayout_2->addWidget(cmi); - } -#endif -} - -void ChannelFeed::fillThreadFinished() -{ -#ifdef CHAN_DEBUG - std::cerr << "ChannelFeed::fillThreadFinished()" << std::endl; -#endif - - // thread has finished - ChannelFillThread *thread = dynamic_cast(sender()); - if (thread) { - if (thread == fillThread) { - // current thread has finished, hide progressbar and release thread - progressBar->hide(); - progressLabel->hide(); - fillThread = NULL; - } - -#ifdef CHAN_DEBUG - if (thread->wasStopped()) { - // thread was stopped - std::cerr << "ChannelFeed::fillThreadFinished() Thread was stopped" << std::endl; - } -#endif - -#ifdef CHAN_DEBUG - std::cerr << "ChannelFeed::fillThreadFinished() Delete thread" << std::endl; -#endif - - thread->deleteLater(); - thread = NULL; - } - -#ifdef CHAN_DEBUG - std::cerr << "ChannelFeed::fillThreadFinished done()" << std::endl; -#endif -} - -void ChannelFeed::fillThreadAddMsg(const QString &channelId, const QString &channelMsgId, int current, int count) -{ - if (sender() == fillThread) { - // show fill progress - if (count) { - progressBar->setValue(current * progressBar->maximum() / count); - } - - lockLayout(NULL, true); - - ChanMsgItem *cmi = new ChanMsgItem(this, 0, channelId.toStdString(), channelMsgId.toStdString(), true); - mChanMsgItems.push_back(cmi); - verticalLayout->addWidget(cmi); - cmi->show(); - - lockLayout(cmi, false); - } -} - -void ChannelFeed::unsubscribeChannel() -{ -#ifdef CHAN_DEBUG - std::cerr << "ChannelFeed::unsubscribeChannel()"; - std::cerr << std::endl; -#endif - - if (rsChannels) { - rsChannels->channelSubscribe(mChannelId, false, false); - } - - updateChannelMsgs(); -} - - -void ChannelFeed::subscribeChannel() -{ -#ifdef CHAN_DEBUG - std::cerr << "ChannelFeed::subscribeChannel()"; - std::cerr << std::endl; -#endif - - if (rsChannels) { - rsChannels->channelSubscribe(mChannelId, true, false); - } - - updateChannelMsgs(); -} - -void ChannelFeed::showChannelDetails() -{ - if (mChannelId.empty()) { - return; - } - - if (!rsChannels) { - return; - } - - ChannelDetails channelui (this); - - channelui.showDetails(mChannelId); - channelui.exec(); -} - -void ChannelFeed::setAllAsReadClicked() -{ - if (mChannelId.empty()) { - return; - } - - if (!rsChannels) { - return; - } - - ChannelInfo ci; - if (rsChannels->getChannelInfo(mChannelId, ci) == false) { - return; - } - - if (ci.channelFlags & RS_DISTRIB_SUBSCRIBED) { - std::list msgs; - std::list::iterator it; - - rsChannels->getChannelMsgList(mChannelId, msgs); - - for(it = msgs.begin(); it != msgs.end(); it++) { - rsChannels->setMessageStatus(mChannelId, it->msgId, CHANNEL_MSG_STATUS_READ, CHANNEL_MSG_STATUS_READ | CHANNEL_MSG_STATUS_UNREAD_BY_USER); - } - } -} - -void ChannelFeed::toggleAutoDownload(){ - - if(mChannelId.empty()) - return; - - bool autoDl = true; - - if(rsChannels->channelGetAutoDl(mChannelId, autoDl)){ - - // if auto dl is set true, then set false - if(autoDl){ - rsChannels->channelSetAutoDl(mChannelId, false); - }else{ - rsChannels->channelSetAutoDl(mChannelId, true); - } - setAutoDownloadButton(!autoDl); - } - else{ - std::cerr << "Auto Download failed to set" - << std::endl; - } -} - -bool ChannelFeed::navigate(const std::string& channelId, const std::string& msgId) -{ - if (channelId.empty()) { - return false; - } - - if (treeWidget->activateId(QString::fromStdString(channelId), msgId.empty()) == NULL) { - return false; - } - - /* Messages are filled in selectChannel */ - if (mChannelId != channelId) { - return false; - } - - if (msgId.empty()) { - return true; - } - - /* Search exisiting item */ - QList::iterator mit; - for (mit = mChanMsgItems.begin(); mit != mChanMsgItems.end(); mit++) { - ChanMsgItem *item = *mit; - if (item->msgId() == msgId) { - // the next two lines are necessary to calculate the layout of the widgets in the scroll area (maybe there is a better solution) - item->show(); - QCoreApplication::processEvents(); - - scrollArea->ensureWidgetVisible(item, 0, 0); - return true; - } - } - - return false; -} - -void ChannelFeed::setAutoDownloadButton(bool autoDl) -{ - if (autoDl) { - actionEnable_Auto_Download->setText(tr("Disable Auto-Download")); - }else{ - actionEnable_Auto_Download->setText(tr("Enable Auto-Download")); - } -} - -void ChannelFeed::generateMassData() -{ -#ifdef CHAN_DEBUG - if (mChannelId.empty ()) { - return; - } - - if (QMessageBox::question(this, "Generate mass data", "Do you really want to generate mass data ?", QMessageBox::Yes|QMessageBox::No, QMessageBox::No) == QMessageBox::No) { - return; - } - - for (int thread = 1; thread < 1000; thread++) { - ChannelMsgInfo msgInfo; - msgInfo.channelId = mChannelId; - msgInfo.subject = QString("Test %1").arg(thread, 3, 10, QChar('0')).toStdWString(); - msgInfo.msg = QString("That is only a test").toStdWString(); - - if (rsChannels->ChannelMessageSend(msgInfo) == false) { - return; - } - } -#endif -} - -// ForumsFillThread -ChannelFillThread::ChannelFillThread(ChannelFeed *parent, const std::string &channelId) - : QThread(parent) -{ - stopped = false; - this->channelId = channelId; -} - -ChannelFillThread::~ChannelFillThread() -{ -#ifdef CHAN_DEBUG - std::cerr << "ChannelFillThread::~ChannelFillThread" << std::endl; -#endif -} - -void ChannelFillThread::stop() -{ - disconnect(); - stopped = true; - QApplication::processEvents(); - wait(); -} - -void ChannelFillThread::run() -{ -#ifdef CHAN_DEBUG - std::cerr << "ChannelFillThread::run()" << std::endl; -#endif - - std::list msgs; - std::list::iterator it; - rsChannels->getChannelMsgList(channelId, msgs); - - msgs.sort(sortChannelMsgSummary); - - int count = msgs.size(); - int pos = 0; - - for (it = msgs.begin(); it != msgs.end(); it++) { - if (stopped) { - break; - } - - emit addMsg(QString::fromStdString(channelId), QString::fromStdString(it->msgId), ++pos, count); - } - -#ifdef CHAN_DEBUG - std::cerr << "ChannelFillThread::run() stopped: " << (wasStopped() ? "yes" : "no") << std::endl; -#endif -} diff --git a/retroshare-gui/src/gui/ChannelFeed.h b/retroshare-gui/src/gui/ChannelFeed.h deleted file mode 100644 index a92c4f811..000000000 --- a/retroshare-gui/src/gui/ChannelFeed.h +++ /dev/null @@ -1,139 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2008 Robert Fernie - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - -#ifndef _CHANNEL_FEED_DIALOG_H -#define _CHANNEL_FEED_DIALOG_H - -#include -#include -#include -#include - -#include "mainpage.h" -#include "RsAutoUpdatePage.h" - -#include "ui_ChannelFeed.h" - -#include "gui/feeds/FeedHolder.h" - -class ChanMsgItem; -class QTreeWidgetItem; -class ChannelFillThread; - -class ChannelFeed : public RsAutoUpdatePage, public FeedHolder, private Ui::ChannelFeed -{ - Q_OBJECT - -public: - /** Default Constructor */ - ChannelFeed(QWidget *parent = 0); - /** Default Destructor */ - ~ChannelFeed(); - - virtual UserNotify *getUserNotify(QObject *parent); - - /* FeedHolder */ - virtual QScrollArea *getScrollArea(); - virtual void deleteFeedItem(QWidget *item, uint32_t type); - virtual void openChat(std::string peerId); - virtual void openComments(uint32_t /*type*/ , const RsGxsGroupId & /*grpId */, const RsGxsMessageId & /*msgId*/, const QString & /*title */); - - bool navigate(const std::string& channelId, const std::string& msgId); - - /* overloaded from RsAuthUpdatePage */ - virtual void updateDisplay(); - -private slots: - void channelListCustomPopupMenu( QPoint point ); - void selectChannel(const QString &id); - - void createChannel(); - - void subscribeChannel(); - void unsubscribeChannel(); - void setAllAsReadClicked(); - void toggleAutoDownload(); - - void createMsg(); - - void showChannelDetails(); - void restoreChannelKeys(); - void editChannelDetail(); - void shareKey(); - void copyChannelLink(); - void setDestinationDirectory(); - void chooseDestinationDirectory(); - - void channelMsgReadSatusChanged(const QString& channelId, const QString& msgId, int status); - - void generateMassData(); - - void fillThreadFinished(); - void fillThreadAddMsg(const QString &channelId, const QString &channelMsgId, int current, int count); - -private: - void updateChannelList(); - void updateChannelMsgs(); - void updateMessageSummaryList(const std::string &channelId); - - void processSettings(bool load); - - void setAutoDownloadButton(bool autoDl); - - std::string mChannelId; /* current Channel */ - - /* Layout Pointers */ - QBoxLayout *mMsgLayout; - - QList mChanMsgItems; - std::map mChanSearchScore; //chanId, score - - QTreeWidgetItem *ownChannels; - QTreeWidgetItem *subcribedChannels; - QTreeWidgetItem *popularChannels; - QTreeWidgetItem *otherChannels; - - ChannelFillThread *fillThread; -}; - -class ChannelFillThread : public QThread -{ - Q_OBJECT - -public: - ChannelFillThread(ChannelFeed *parent, const std::string &channelId); - ~ChannelFillThread(); - - void run(); - void stop(); - bool wasStopped() { return stopped; } - -signals: - void addMsg(const QString &channelId, const QString &channelMsgId, int current, int count); - -public: - std::string channelId; - -private: - volatile bool stopped; -}; - -#endif diff --git a/retroshare-gui/src/gui/ChannelFeed.ui b/retroshare-gui/src/gui/ChannelFeed.ui deleted file mode 100644 index 2ccf8ce45..000000000 --- a/retroshare-gui/src/gui/ChannelFeed.ui +++ /dev/null @@ -1,314 +0,0 @@ - - - ChannelFeed - - - - 0 - 0 - 681 - 476 - - - - - - - - 0 - 0 - - - - QFrame::Box - - - QFrame::Sunken - - - - 2 - - - - - - 24 - 24 - - - - - - - :/images/channels32.png - - - true - - - - - - - - 10 - 75 - true - - - - Channels - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Qt::NoFocus - - - - :/images/64px_help.png:/images/64px_help.png - - - true - - - true - - - - - - - - - - Qt::Horizontal - - - - - 0 - 0 - - - - - - - - - QFrame::Box - - - QFrame::Sunken - - - - 4 - - - - - - 64 - 64 - - - - - 64 - 64 - - - - - - - :/images/channels.png - - - true - - - - - - - - - - - - - - - 21 - - - - Channel Name - - - true - - - - - - - - - - QFrame::Box - - - QFrame::Sunken - - - - 2 - - - - - Qt::NoFocus - - - Post to Channel - - - - :/images/mail_send.png:/images/mail_send.png - - - - 32 - 16 - - - - true - - - - - - - Qt::Horizontal - - - - 314 - 10 - - - - - - - - - - - - - Loading - - - - - - - 1000 - - - 24 - - - - - - - - - true - - - - - 0 - 0 - 513 - 16 - - - - - 0 - 0 - - - - - 0 - - - 0 - - - - - - - - - - - - - Set all as read - - - Set all as read - - - - - Enable Auto-Download - - - Enable Auto-Download - - - splitter - titleBarFrame - - - - GroupTreeWidget - QWidget -
gui/common/GroupTreeWidget.h
- 1 -
-
- - - - -
diff --git a/retroshare-gui/src/gui/FileTransfer/DLListDelegate.cpp b/retroshare-gui/src/gui/FileTransfer/DLListDelegate.cpp index f693df430..71b9774c8 100644 --- a/retroshare-gui/src/gui/FileTransfer/DLListDelegate.cpp +++ b/retroshare-gui/src/gui/FileTransfer/DLListDelegate.cpp @@ -222,7 +222,7 @@ void DLListDelegate::paint(QPainter * painter, const QStyleOptionViewItem & opti case COLUMN_LASTDL: qi64Value = index.data().value(); if (qi64Value < std::numeric_limits::max()){ - QDateTime qdtLastDL = QDateTime::fromTime_t(qi64Value/1000); + QDateTime qdtLastDL = QDateTime::fromTime_t(qi64Value); painter->drawText(option.rect, Qt::AlignCenter, qdtLastDL.toString("yyyy-MM-dd_hh:mm:ss")); } else { painter->drawText(option.rect, Qt::AlignCenter, tr("File Never Seen")); diff --git a/retroshare-gui/src/gui/FileTransfer/TransfersDialog.cpp b/retroshare-gui/src/gui/FileTransfer/TransfersDialog.cpp index 19d252957..869b98a8f 100644 --- a/retroshare-gui/src/gui/FileTransfer/TransfersDialog.cpp +++ b/retroshare-gui/src/gui/FileTransfer/TransfersDialog.cpp @@ -945,7 +945,7 @@ int TransfersDialog::addItem(int row, const FileInfo &fileInfo, const std::map -#include -#include -#include -#include -#include - -#include "ForumsDialog.h" -#include "forums/CreateForum.h" -#include "forums/CreateForumMsg.h" -#include "forums/ForumDetails.h" -#include "forums/EditForumDetails.h" -#include "forums/ForumUserNotify.h" -#include "msgs/MessageComposer.h" -#include "settings/rsharesettings.h" -#include "common/Emoticons.h" -#include "common/RSItemDelegate.h" -#include "common/PopularityDefs.h" -#include "common/RSTreeWidgetItem.h" -#include "RetroShareLink.h" -#include "channels/ShareKey.h" -#include "notifyqt.h" -#include "util/HandleRichText.h" -#include "util/DateTime.h" - -#include -#include -#include - -#include - -//#define DEBUG_FORUMS - -/* Images for context menu icons */ -#define IMAGE_MESSAGE ":/images/folder-draft.png" -#define IMAGE_MESSAGEREPLY ":/images/mail_reply.png" -#define IMAGE_MESSAGEREMOVE ":/images/mail_delete.png" -#define IMAGE_DOWNLOAD ":/images/start.png" -#define IMAGE_DOWNLOADALL ":/images/startall.png" - -/* Images for TreeWidget */ -#define IMAGE_FOLDER ":/images/folder16.png" -#define IMAGE_FOLDERGREEN ":/images/folder_green.png" -#define IMAGE_FOLDERRED ":/images/folder_red.png" -#define IMAGE_FOLDERYELLOW ":/images/folder_yellow.png" -#define IMAGE_FORUM ":/images/konversation.png" -#define IMAGE_SUBSCRIBE ":/images/edit_add24.png" -#define IMAGE_UNSUBSCRIBE ":/images/cancel.png" -#define IMAGE_INFO ":/images/info16.png" -#define IMAGE_NEWFORUM ":/images/new_forum16.png" -#define IMAGE_FORUMAUTHD ":/images/konv_message2.png" -#define IMAGE_COPYLINK ":/images/copyrslink.png" - -#define VIEW_LAST_POST 0 -#define VIEW_THREADED 1 -#define VIEW_FLAT 2 - -/* Thread constants */ -#define COLUMN_THREAD_COUNT 6 -#define COLUMN_THREAD_TITLE 0 -#define COLUMN_THREAD_READ 1 -#define COLUMN_THREAD_DATE 2 -#define COLUMN_THREAD_AUTHOR 3 -#define COLUMN_THREAD_SIGNED 4 -#define COLUMN_THREAD_CONTENT 5 - -#define COLUMN_THREAD_DATA 0 // column for storing the userdata like msgid and parentid - -#define ROLE_THREAD_MSGID Qt::UserRole -#define ROLE_THREAD_STATUS Qt::UserRole + 1 -#define ROLE_THREAD_MISSING Qt::UserRole + 2 -// no need to copy, don't count in ROLE_THREAD_COUNT -#define ROLE_THREAD_READCHILDREN Qt::UserRole + 3 -#define ROLE_THREAD_UNREADCHILDREN Qt::UserRole + 4 -#define ROLE_THREAD_SORT Qt::UserRole + 5 - -#define ROLE_THREAD_COUNT 3 - -#define IS_UNREAD(status) ((status & FORUM_MSG_STATUS_READ) == 0 || (status & FORUM_MSG_STATUS_UNREAD_BY_USER)) -#define IS_FORUM_ADMIN(subscribeFlags) (subscribeFlags & RS_DISTRIB_ADMIN) -#define IS_FORUM_SUBSCRIBED(subscribeFlags) (subscribeFlags & (RS_DISTRIB_ADMIN | RS_DISTRIB_SUBSCRIBED)) - -/** Constructor */ -ForumsDialog::ForumsDialog(QWidget *parent) -: RsAutoUpdatePage(1000,parent) -{ - /* Invoke the Qt Designer generated object setup routine */ - ui.setupUi(this); - - m_bProcessSettings = false; - subscribeFlags = 0; - inMsgAsReadUnread = false; - - threadCompareRole = new RSTreeWidgetItemCompareRole; - threadCompareRole->setRole(COLUMN_THREAD_DATE, ROLE_THREAD_SORT); - - connect( ui.forumTreeWidget, SIGNAL( treeCustomContextMenuRequested( QPoint ) ), this, SLOT( forumListCustomPopupMenu( QPoint ) ) ); - connect( ui.threadTreeWidget, SIGNAL( customContextMenuRequested( QPoint ) ), this, SLOT( threadListCustomPopupMenu( QPoint ) ) ); - - connect(ui.newmessageButton, SIGNAL(clicked()), this, SLOT(createmessage())); - connect(ui.newthreadButton, SIGNAL(clicked()), this, SLOT(createthread())); - - connect( ui.forumTreeWidget, SIGNAL( treeCurrentItemChanged(QString) ), this, SLOT( changedForum(QString) ) ); - - connect( ui.threadTreeWidget, SIGNAL( itemSelectionChanged() ), this, SLOT( changedThread () ) ); - connect( ui.threadTreeWidget, SIGNAL( itemClicked(QTreeWidgetItem*,int)), this, SLOT( clickedThread (QTreeWidgetItem*,int) ) ); - connect( ui.viewBox, SIGNAL( currentIndexChanged ( int ) ), this, SLOT( changedViewBox () ) ); - - connect(ui.expandButton, SIGNAL(clicked()), this, SLOT(togglethreadview())); - connect(ui.previousButton, SIGNAL(clicked()), this, SLOT(previousMessage())); - connect(ui.nextButton, SIGNAL(clicked()), this, SLOT(nextMessage())); - connect(ui.nextUnreadButton, SIGNAL(clicked()), this, SLOT(nextUnreadMessage())); - - connect(ui.downloadButton, SIGNAL(clicked()), this, SLOT(downloadAllFiles())); - - connect(ui.filterLineEdit, SIGNAL(textChanged(QString)), this, SLOT(filterItems(QString))); - connect(ui.filterLineEdit, SIGNAL(filterChanged(int)), this, SLOT(filterColumnChanged(int))); - - connect(NotifyQt::getInstance(), SIGNAL(forumMsgReadSatusChanged(QString,QString,int)), this, SLOT(forumMsgReadSatusChanged(QString,QString,int))); - - /* Set initial size the splitter */ - QList sizes; - sizes << 300 << width(); // Qt calculates the right sizes - //ui.splitter->setSizes(sizes); - - /* Set own item delegate */ - RSItemDelegate *itemDelegate = new RSItemDelegate(this); - itemDelegate->setSpacing(QSize(0, 2)); - ui.threadTreeWidget->setItemDelegate(itemDelegate); - - /* Set header resize modes and initial section sizes */ - QHeaderView * ttheader = ui.threadTreeWidget->header () ; - ttheader->setResizeMode (COLUMN_THREAD_TITLE, QHeaderView::Interactive); - ttheader->resizeSection (COLUMN_THREAD_DATE, 140); - ttheader->resizeSection (COLUMN_THREAD_TITLE, 290); - - ui.threadTreeWidget->sortItems( COLUMN_THREAD_DATE, Qt::DescendingOrder ); - - /* Set text of column "Read" to empty - without this the column has a number as header text */ - QTreeWidgetItem *headerItem = ui.threadTreeWidget->headerItem(); - headerItem->setText(COLUMN_THREAD_READ, ""); - - /* Initialize group tree */ - QToolButton *newForumButton = new QToolButton(this); - newForumButton->setIcon(QIcon(":/images/new_forum16.png")); - newForumButton->setToolTip(tr("Create Forum")); - connect(newForumButton, SIGNAL(clicked()), this, SLOT(newforum())); - ui.forumTreeWidget->addToolButton(newForumButton); - - /* create forum tree */ - yourForums = ui.forumTreeWidget->addCategoryItem(tr("My Forums"), QIcon(IMAGE_FOLDER), true); - subscribedForums = ui.forumTreeWidget->addCategoryItem(tr("Subscribed Forums"), QIcon(IMAGE_FOLDERRED), true); - popularForums = ui.forumTreeWidget->addCategoryItem(tr("Popular Forums"), QIcon(IMAGE_FOLDERGREEN), false); - otherForums = ui.forumTreeWidget->addCategoryItem(tr("Other Forums"), QIcon(IMAGE_FOLDERYELLOW), false); - - lastViewType = -1; - - /* add filter actions */ - ui.filterLineEdit->addFilter(QIcon(), tr("Title"), COLUMN_THREAD_TITLE, tr("Search Title")); - ui.filterLineEdit->addFilter(QIcon(), tr("Date"), COLUMN_THREAD_DATE, tr("Search Date")); - ui.filterLineEdit->addFilter(QIcon(), tr("Author"), COLUMN_THREAD_AUTHOR, tr("Search Author")); - ui.filterLineEdit->addFilter(QIcon(), tr("Content"), COLUMN_THREAD_CONTENT, tr("Search Content")); - ui.filterLineEdit->setCurrentFilter(COLUMN_THREAD_TITLE); - - // load settings - processSettings(true); - - /* Set header sizes for the fixed columns and resize modes, must be set after processSettings */ - ttheader->resizeSection (COLUMN_THREAD_READ, 24); - ttheader->setResizeMode (COLUMN_THREAD_READ, QHeaderView::Fixed); - ttheader->hideSection (COLUMN_THREAD_CONTENT); - - ui.progressBar->hide(); - ui.progLayOutTxt->hide(); - ui.progressBarLayOut->setEnabled(false); - - fillThread = NULL; - - insertThreads(); - - ui.threadTreeWidget->installEventFilter(this); - - /* Hide platform specific features */ -#ifdef Q_WS_WIN - -#endif - - QString help_str = tr( - "

  Forums

\ -

Retroshare Forums look like internet forums, but they work in a decentralized way: \ - You see forums your friends are subscribed to, and you forward subscribed forums to \ - your friends. This automatically promotes interesting forums in the network.

\ -

Forums are either Authenticated () in which case you need to cryptographically sign \ - your posts, or anonymous (). The former class is more resistant to spamming.

\ -

Forum posts propagate from friend to friend using small cache file exchanges. When you first connect to a new friend, it's likely \ - you will receive many such cache files, and new forums will appear. \ -

\ - ") ; - - - registerHelpButton(ui.helpButton,help_str) ; -} - -ForumsDialog::~ForumsDialog() -{ - if (fillThread) { - fillThread->stop(); - delete(fillThread); - fillThread = NULL; - } - - delete(threadCompareRole); - - // save settings - processSettings(false); -} - -UserNotify *ForumsDialog::getUserNotify(QObject *parent) -{ - return new ForumUserNotify(parent); -} - -void ForumsDialog::processSettings(bool bLoad) -{ - m_bProcessSettings = true; - - QHeaderView *pHeader = ui.threadTreeWidget->header () ; - - Settings->beginGroup(QString("ForumsDialog")); - - if (bLoad) { - // load settings - - // expandFiles - bool bValue = Settings->value("expandButton", true).toBool(); - ui.expandButton->setChecked(bValue); - togglethreadview_internal(); - - // filterColumn - ui.filterLineEdit->setCurrentFilter(Settings->value("filterColumn", COLUMN_THREAD_TITLE).toInt()); - - // index of viewBox - ui.viewBox->setCurrentIndex(Settings->value("viewBox", VIEW_THREADED).toInt()); - - // state of thread tree - pHeader->restoreState(Settings->value("ThreadTree").toByteArray()); - - // state of splitter - ui.splitter->restoreState(Settings->value("Splitter").toByteArray()); - ui.threadSplitter->restoreState(Settings->value("threadSplitter").toByteArray()); - } else { - // save settings - - // state of thread tree - Settings->setValue("ThreadTree", pHeader->saveState()); - - // state of splitter - Settings->setValue("Splitter", ui.splitter->saveState()); - Settings->setValue("threadSplitter", ui.threadSplitter->saveState()); - } - - ui.forumTreeWidget->processSettings(Settings, bLoad); - - Settings->endGroup(); - m_bProcessSettings = false; -} - -void ForumsDialog::changeEvent(QEvent *e) -{ - QWidget::changeEvent(e); - switch (e->type()) { - case QEvent::StyleChange: - CalculateIconsAndFonts(); - break; - default: - // remove compiler warnings - break; - } -} - -void ForumsDialog::forumListCustomPopupMenu( QPoint /*point*/ ) -{ - QMenu contextMnu( this ); - - QAction *action = contextMnu.addAction(QIcon(IMAGE_SUBSCRIBE), tr("Subscribe to Forum"), this, SLOT(subscribeToForum())); - action->setDisabled (mCurrForumId.empty() || IS_FORUM_SUBSCRIBED(subscribeFlags)); - - action = contextMnu.addAction(QIcon(IMAGE_UNSUBSCRIBE), tr("Unsubscribe to Forum"), this, SLOT(unsubscribeToForum())); - action->setEnabled (!mCurrForumId.empty() && IS_FORUM_SUBSCRIBED(subscribeFlags)); - - contextMnu.addSeparator(); - - contextMnu.addAction(QIcon(IMAGE_NEWFORUM), tr("New Forum"), this, SLOT(newforum())); - - action = contextMnu.addAction(QIcon(IMAGE_INFO), tr("Show Forum Details"), this, SLOT(showForumDetails())); - action->setEnabled (!mCurrForumId.empty ()); - - action = contextMnu.addAction(QIcon(":/images/settings16.png"), tr("Edit Forum Details"), this, SLOT(editForumDetails())); - action->setEnabled (!mCurrForumId.empty () && IS_FORUM_ADMIN(subscribeFlags)); - - QAction *shareKeyAct = new QAction(QIcon(":/images/gpgp_key_generate.png"), tr("Share Forum"), &contextMnu); - connect( shareKeyAct, SIGNAL( triggered() ), this, SLOT( shareKey() ) ); - shareKeyAct->setEnabled(!mCurrForumId.empty() && IS_FORUM_ADMIN(subscribeFlags)); - contextMnu.addAction( shareKeyAct); - - QAction *restoreKeysAct = new QAction(QIcon(":/images/settings16.png"), tr("Restore Publish Rights for Forum" ), &contextMnu); - connect( restoreKeysAct , SIGNAL( triggered() ), this, SLOT( restoreForumKeys() ) ); - restoreKeysAct->setEnabled(!mCurrForumId.empty() && !IS_FORUM_ADMIN(subscribeFlags)); - contextMnu.addAction( restoreKeysAct); - - action = contextMnu.addAction(QIcon(IMAGE_COPYLINK), tr("Copy RetroShare Link"), this, SLOT(copyForumLink())); - action->setEnabled(!mCurrForumId.empty()); - - contextMnu.addSeparator(); - - action = contextMnu.addAction(QIcon(":/images/message-mail-read.png"), tr("Mark all as read"), this, SLOT(markMsgAsReadAll())); - action->setEnabled (!mCurrForumId.empty () && IS_FORUM_SUBSCRIBED(subscribeFlags)); - - action = contextMnu.addAction(QIcon(":/images/message-mail.png"), tr("Mark all as unread"), this, SLOT(markMsgAsUnreadAll())); - action->setEnabled (!mCurrForumId.empty () && IS_FORUM_SUBSCRIBED(subscribeFlags)); - -#ifdef DEBUG_FORUMS - contextMnu.addSeparator(); - action = contextMnu.addAction("Generate mass data", this, SLOT(generateMassData())); - action->setEnabled (!mCurrForumId.empty() && IS_FORUM_SUBSCRIBED(subscribeFlags)); -#endif - - contextMnu.exec(QCursor::pos()); -} - -void ForumsDialog::threadListCustomPopupMenu( QPoint /*point*/ ) -{ - if (fillThread) { - return; - } - - QMenu contextMnu( this ); - - QAction *replyAct = new QAction(QIcon(IMAGE_MESSAGEREPLY), tr( "Reply" ), &contextMnu ); - connect( replyAct , SIGNAL( triggered() ), this, SLOT( createmessage() ) ); - - QAction *newthreadAct = new QAction(QIcon(IMAGE_DOWNLOADALL), tr( "Start New Thread" ), &contextMnu ); - newthreadAct->setEnabled (IS_FORUM_SUBSCRIBED(subscribeFlags)); - connect( newthreadAct , SIGNAL( triggered() ), this, SLOT( createthread() ) ); - - QAction *replyauthorAct = new QAction(QIcon(IMAGE_MESSAGEREPLY), tr( "Reply to Author" ), &contextMnu ); - connect( replyauthorAct , SIGNAL( triggered() ), this, SLOT( replytomessage() ) ); - - QAction* expandAll = new QAction(tr( "Expand all" ), &contextMnu ); - connect( expandAll , SIGNAL( triggered() ), ui.threadTreeWidget, SLOT (expandAll()) ); - - QAction* collapseAll = new QAction(tr( "Collapse all" ), &contextMnu ); - connect( collapseAll , SIGNAL( triggered() ), ui.threadTreeWidget, SLOT(collapseAll()) ); - - QAction *markMsgAsRead = new QAction(QIcon(":/images/message-mail-read.png"), tr("Mark as read"), &contextMnu); - connect(markMsgAsRead , SIGNAL(triggered()), this, SLOT(markMsgAsRead())); - - QAction *markMsgAsReadChildren = new QAction(QIcon(":/images/message-mail-read.png"), tr("Mark as read") + " (" + tr ("with children") + ")", &contextMnu); - connect(markMsgAsReadChildren, SIGNAL(triggered()), this, SLOT(markMsgAsReadChildren())); - - QAction *markMsgAsUnread = new QAction(QIcon(":/images/message-mail.png"), tr("Mark as unread"), &contextMnu); - connect(markMsgAsUnread , SIGNAL(triggered()), this, SLOT(markMsgAsUnread())); - - QAction *markMsgAsUnreadChildren = new QAction(QIcon(":/images/message-mail.png"), tr("Mark as unread") + " (" + tr ("with children") + ")", &contextMnu); - connect(markMsgAsUnreadChildren , SIGNAL(triggered()), this, SLOT(markMsgAsUnreadChildren())); - - if (IS_FORUM_SUBSCRIBED(subscribeFlags)) { - QList Rows; - QList RowsRead; - QList RowsUnread; - int nCount = getSelectedMsgCount (&Rows, &RowsRead, &RowsUnread); - - if (RowsUnread.size() == 0) { - - markMsgAsRead->setDisabled(true); - } - if (RowsRead.size() == 0) { - markMsgAsUnread->setDisabled(true); - } - - bool bHasUnreadChildren = false; - bool bHasReadChildren = false; - int nRowCount = Rows.count(); - for (int i = 0; i < nRowCount; i++) { - if (bHasUnreadChildren || Rows[i]->data(COLUMN_THREAD_DATA, ROLE_THREAD_UNREADCHILDREN).toBool()) { - bHasUnreadChildren = true; - } - if (bHasReadChildren || Rows[i]->data(COLUMN_THREAD_DATA, ROLE_THREAD_READCHILDREN).toBool()) { - bHasReadChildren = true; - } - } - markMsgAsReadChildren->setEnabled(bHasUnreadChildren); - markMsgAsUnreadChildren->setEnabled(bHasReadChildren); - - if (nCount == 1) { - replyAct->setEnabled (true); - replyauthorAct->setEnabled (true); - } else { - replyAct->setDisabled (true); - replyauthorAct->setDisabled (true); - } - } else { - markMsgAsRead->setDisabled(true); - markMsgAsReadChildren->setDisabled(true); - markMsgAsUnread->setDisabled(true); - markMsgAsUnreadChildren->setDisabled(true); - replyAct->setDisabled (true); - replyauthorAct->setDisabled (true); - } - - contextMnu.addAction( replyAct); - contextMnu.addAction( newthreadAct); - contextMnu.addAction( replyauthorAct); - QAction* action = contextMnu.addAction(QIcon(IMAGE_COPYLINK), tr( "Copy RetroShare Link"), this, SLOT(copyMessageLink())); - action->setEnabled(!mCurrForumId.empty() && !mCurrThreadId.empty()); - contextMnu.addSeparator(); - contextMnu.addAction(markMsgAsRead); - contextMnu.addAction(markMsgAsReadChildren); - contextMnu.addAction(markMsgAsUnread); - contextMnu.addAction(markMsgAsUnreadChildren); - contextMnu.addSeparator(); - contextMnu.addAction( expandAll); - contextMnu.addAction( collapseAll); - - contextMnu.exec(QCursor::pos()); -} - -bool ForumsDialog::eventFilter(QObject *obj, QEvent *event) -{ - if (obj == ui.threadTreeWidget) { - if (event->type() == QEvent::KeyPress) { - QKeyEvent *keyEvent = static_cast(event); - if (keyEvent && keyEvent->key() == Qt::Key_Space) { - // Space pressed - QTreeWidgetItem *item = ui.threadTreeWidget->currentItem (); - clickedThread (item, COLUMN_THREAD_READ); - return true; // eat event - } - } - } - // pass the event on to the parent class - return RsAutoUpdatePage::eventFilter(obj, event); -} - -void ForumsDialog::restoreForumKeys(void) -{ - rsForums->forumRestoreKeys(mCurrForumId); -} - -void ForumsDialog::togglethreadview() -{ - // save state of button - Settings->setValueToGroup("ForumsDialog", "expandButton", ui.expandButton->isChecked()); - - togglethreadview_internal(); -} - -void ForumsDialog::togglethreadview_internal() -{ - if (ui.expandButton->isChecked()) { - ui.postText->setVisible(true); - ui.expandButton->setIcon(QIcon(QString(":/images/edit_remove24.png"))); - ui.expandButton->setToolTip(tr("Hide")); - } else { - ui.postText->setVisible(false); - ui.expandButton->setIcon(QIcon(QString(":/images/edit_add24.png"))); - ui.expandButton->setToolTip(tr("Expand")); - } -} - -void ForumsDialog::updateDisplay() -{ - std::list forumIds; - std::list::iterator it; - if (!rsForums) - return; - - if (rsForums->forumsChanged(forumIds)) - { - /* update Forums List */ - insertForums(); - - it = std::find(forumIds.begin(), forumIds.end(), mCurrForumId); - if (it != forumIds.end()) - { - /* update threads as well */ - insertThreads(); - } - } -} - -static void CleanupItems (QList &items) -{ - QList::iterator item; - for (item = items.begin (); item != items.end (); item++) { - if (*item) { - delete (*item); - } - } - items.clear(); -} - -void ForumsDialog::forumInfoToGroupItemInfo(const ForumInfo &forumInfo, GroupItemInfo &groupItemInfo) -{ - groupItemInfo.id = QString::fromStdString(forumInfo.forumId); - groupItemInfo.name = QString::fromStdWString(forumInfo.forumName); - groupItemInfo.description = QString::fromStdWString(forumInfo.forumDesc); - groupItemInfo.popularity = forumInfo.pop; - groupItemInfo.lastpost = QDateTime::fromTime_t(forumInfo.lastPost); - - if (forumInfo.forumFlags & RS_DISTRIB_AUTHEN_REQ) { - groupItemInfo.name += " (" + tr("AUTHD") + ")"; - groupItemInfo.icon = QIcon(IMAGE_FORUMAUTHD); - } else { - groupItemInfo.icon = QIcon(IMAGE_FORUM); - } -} - -void ForumsDialog::insertForums() -{ - std::list forumList; - std::list::iterator it; - if (!rsForums) - { - return; - } - - rsForums->getForumList(forumList); - - QList adminList; - QList subList; - QList popList; - QList otherList; - std::multimap popMap; - - for (it = forumList.begin(); it != forumList.end(); it++) { - /* sort it into Publish (Own), Subscribed, Popular and Other */ - uint32_t flags = it->subscribeFlags; - - GroupItemInfo groupItemInfo; - forumInfoToGroupItemInfo(*it, groupItemInfo); - - if (flags & RS_DISTRIB_ADMIN) { - adminList.push_back(groupItemInfo); - } else if (flags & RS_DISTRIB_SUBSCRIBED) { - /* subscribed forum */ - subList.push_back(groupItemInfo); - } else { - /* rate the others by popularity */ - popMap.insert(std::make_pair(it->pop, groupItemInfo)); - } - } - - /* iterate backwards through popMap - take the top 5 or 10% of list */ - uint32_t popCount = 5; - if (popCount < popMap.size() / 10) - { - popCount = popMap.size() / 10; - } - - uint32_t i = 0; - uint32_t popLimit = 0; - std::multimap::reverse_iterator rit; - for(rit = popMap.rbegin(); ((rit != popMap.rend()) && (i < popCount)); rit++, i++) ; - if (rit != popMap.rend()) { - popLimit = rit->first; - } - - for (rit = popMap.rbegin(); rit != popMap.rend(); rit++) { - if (rit->second.popularity < (int) popLimit) { - otherList.append(rit->second); - } else { - popList.append(rit->second); - } - } - - /* now we can add them in as a tree! */ - ui.forumTreeWidget->fillGroupItems(yourForums, adminList); - ui.forumTreeWidget->fillGroupItems(subscribedForums, subList); - ui.forumTreeWidget->fillGroupItems(popularForums, popList); - ui.forumTreeWidget->fillGroupItems(otherForums, otherList); - - updateMessageSummaryList(""); -} - -void ForumsDialog::changedForum(const QString &id) -{ - mCurrForumId = id.toStdString(); - - insertThreads(); -} - -void ForumsDialog::changedThread () -{ - if (fillThread) { - return; - } - - /* just grab the ids of the current item */ - QTreeWidgetItem *curr = ui.threadTreeWidget->currentItem(); - - if ((!curr) || (!curr->isSelected())) { - mCurrThreadId = ""; - } else { - mCurrThreadId = curr->data(COLUMN_THREAD_DATA, ROLE_THREAD_MSGID).toString().toStdString(); - } - insertPost(); -} - -void ForumsDialog::clickedThread (QTreeWidgetItem *item, int column) -{ - if (mCurrForumId.empty() || !IS_FORUM_SUBSCRIBED(subscribeFlags)) { - return; - } - - if (item == NULL) { - return; - } - - if (column == COLUMN_THREAD_READ) { - QList Rows; - Rows.append(item); - uint32_t status = item->data(COLUMN_THREAD_DATA, ROLE_THREAD_STATUS).toUInt(); - setMsgAsReadUnread(Rows, IS_UNREAD(status)); - return; - } -} - -void ForumsDialog::forumMsgReadSatusChanged(const QString &forumId, const QString &msgId, int status) -{ - if (inMsgAsReadUnread) { - return; - } - - if (forumId.toStdString() == mCurrForumId) { - /* Search exisiting item */ - QTreeWidgetItemIterator itemIterator(ui.threadTreeWidget); - QTreeWidgetItem *item = NULL; - while ((item = *itemIterator) != NULL) { - itemIterator++; - - if (item->data(COLUMN_THREAD_DATA, ROLE_THREAD_MSGID).toString() == msgId) { - // update status - item->setData(COLUMN_THREAD_DATA, ROLE_THREAD_STATUS, status); - - QTreeWidgetItem *parentItem = item; - while (parentItem->parent()) { - parentItem = parentItem->parent(); - } - CalculateIconsAndFonts(parentItem); - break; - } - } - } - updateMessageSummaryList(forumId.toStdString()); -} - -void ForumsDialog::CalculateIconsAndFonts(QTreeWidgetItem *pItem, bool &bHasReadChilddren, bool &bHasUnreadChilddren) -{ - uint32_t status = pItem->data(COLUMN_THREAD_DATA, ROLE_THREAD_STATUS).toUInt(); - - bool bUnread = IS_UNREAD(status); - bool missing = pItem->data(COLUMN_THREAD_DATA, ROLE_THREAD_MISSING).toBool(); - - // set icon - if (missing) { - pItem->setIcon(COLUMN_THREAD_READ, QIcon()); - pItem->setIcon(COLUMN_THREAD_TITLE, QIcon()); - } else { - if (bUnread) { - pItem->setIcon(COLUMN_THREAD_READ, QIcon(":/images/message-state-unread.png")); - } else { - pItem->setIcon(COLUMN_THREAD_READ, QIcon(":/images/message-state-read.png")); - } - if (status & FORUM_MSG_STATUS_READ) { - pItem->setIcon(COLUMN_THREAD_TITLE, QIcon()); - } else { - pItem->setIcon(COLUMN_THREAD_TITLE, QIcon(":/images/message-state-new.png")); - } - } - - int nItem; - int nItemCount = pItem->childCount(); - - bool bMyReadChilddren = false; - bool bMyUnreadChilddren = false; - - for (nItem = 0; nItem < nItemCount; nItem++) { - CalculateIconsAndFonts(pItem->child(nItem), bMyReadChilddren, bMyUnreadChilddren); - } - - // set font - for (int i = 0; i < COLUMN_THREAD_COUNT; i++) { - QFont qf = pItem->font(i); - - if (!IS_FORUM_SUBSCRIBED(subscribeFlags)) { - qf.setBold(false); - pItem->setTextColor(i, textColorNotSubscribed()); - } else if (bUnread) { - qf.setBold(true); - pItem->setTextColor(i, textColorUnread()); - } else if (bMyUnreadChilddren) { - qf.setBold(true); - pItem->setTextColor(i, textColorUnreadChildren()); - } else { - qf.setBold(false); - pItem->setTextColor(i, textColorRead()); - } - if (missing) { - /* Missing message */ - pItem->setTextColor(i, textColorMissing()); - } - pItem->setFont(i, qf); - } - - pItem->setData(COLUMN_THREAD_DATA, ROLE_THREAD_READCHILDREN, bHasReadChilddren || bMyReadChilddren); - pItem->setData(COLUMN_THREAD_DATA, ROLE_THREAD_UNREADCHILDREN, bHasUnreadChilddren || bMyUnreadChilddren); - - bHasReadChilddren = bHasReadChilddren || bMyReadChilddren || !bUnread; - bHasUnreadChilddren = bHasUnreadChilddren || bMyUnreadChilddren || bUnread; -} - -void ForumsDialog::CalculateIconsAndFonts(QTreeWidgetItem *pItem /* = NULL*/) -{ - bool bDummy1 = false; - bool bDummy2 = false; - - if (pItem) { - CalculateIconsAndFonts(pItem, bDummy1, bDummy2); - return; - } - - int nItem; - int nItemCount = ui.threadTreeWidget->topLevelItemCount(); - - for (nItem = 0; nItem < nItemCount; nItem++) { - bDummy1 = false; - bDummy2 = false; - CalculateIconsAndFonts(ui.threadTreeWidget->topLevelItem(nItem), bDummy1, bDummy2); - } -} - -void ForumsDialog::fillThreadFinished() -{ -#ifdef DEBUG_FORUMS - std::cerr << "ForumsDialog::fillThreadFinished" << std::endl; -#endif - - // thread has finished - ForumsFillThread *thread = dynamic_cast(sender()); - if (thread) { - if (thread == fillThread) { - // current thread has finished, hide progressbar and release thread - ui.progressBar->hide(); - ui.progLayOutTxt->hide(); - ui.progressBarLayOut->setEnabled(false); - fillThread = NULL; - } - - if (thread->wasStopped()) { - // thread was stopped -#ifdef DEBUG_FORUMS - std::cerr << "ForumsDialog::fillThreadFinished Thread was stopped" << std::endl; -#endif - } else { -#ifdef DEBUG_FORUMS - std::cerr << "ForumsDialog::fillThreadFinished Add messages" << std::endl; -#endif - ui.threadTreeWidget->setSortingEnabled(false); - - /* add all messages in! */ - if (lastViewType != thread->viewType || lastForumID != mCurrForumId) { - ui.threadTreeWidget->clear(); - lastViewType = thread->viewType; - lastForumID = mCurrForumId; - ui.threadTreeWidget->insertTopLevelItems(0, thread->items); - - // clear list - thread->items.clear(); - } else { - FillThreads (thread->items, thread->expandNewMessages, thread->itemToExpand); - - // cleanup list - CleanupItems (thread->items); - } - - ui.threadTreeWidget->setSortingEnabled(true); - - if (thread->focusMsgId.empty() == false) { - /* Search exisiting item */ - QTreeWidgetItemIterator itemIterator(ui.threadTreeWidget); - QTreeWidgetItem *item = NULL; - while ((item = *itemIterator) != NULL) { - itemIterator++; - - if (item->data(COLUMN_THREAD_DATA, ROLE_THREAD_MSGID).toString().toStdString() == thread->focusMsgId) { - ui.threadTreeWidget->setCurrentItem(item); - ui.threadTreeWidget->setFocus(); - break; - } - } - } - - QList::iterator Item; - for (Item = thread->itemToExpand.begin(); Item != thread->itemToExpand.end(); Item++) { - if ((*Item)->isHidden() == false) { - (*Item)->setExpanded(true); - } - } - thread->itemToExpand.clear(); - - if (ui.filterLineEdit->text().isEmpty() == false) { - filterItems(ui.filterLineEdit->text()); - } - - insertPost (); - CalculateIconsAndFonts(); - - ui.newthreadButton->setEnabled (IS_FORUM_SUBSCRIBED(subscribeFlags)); - } - -#ifdef DEBUG_FORUMS - std::cerr << "ForumsDialog::fillThreadFinished Delete thread" << std::endl; -#endif - - thread->deleteLater(); - thread = NULL; - } - -#ifdef DEBUG_FORUMS - std::cerr << "ForumsDialog::fillThreadFinished done" << std::endl; -#endif -} - -void ForumsDialog::fillThreadProgress(int current, int count) -{ - // show fill progress - if (count) { - ui.progressBar->setValue(current * ui.progressBar->maximum() / count); - } -} - -void ForumsDialog::insertThreads() -{ -#ifdef DEBUG_FORUMS - /* get the current Forum */ - std::cerr << "ForumsDialog::insertThreads()" << std::endl; -#endif - - if (fillThread) { -#ifdef DEBUG_FORUMS - std::cerr << "ForumsDialog::insertThreads() stop current fill thread" << std::endl; -#endif - // stop current fill thread - ForumsFillThread *thread = fillThread; - fillThread = NULL; - thread->stop(); - delete(thread); - - ui.progressBar->hide(); - ui.progLayOutTxt->hide(); - } - - subscribeFlags = 0; - - ui.newmessageButton->setEnabled (false); - ui.newthreadButton->setEnabled (false); - - ui.postText->clear(); - ui.threadTitle->clear(); - - if (mCurrForumId.empty()) - { - /* not an actual forum - clear */ - ui.threadTreeWidget->clear(); - /* when no Thread selected - clear */ - ui.forumName->clear(); - /* clear last stored forumID */ - mCurrForumId.erase(); - lastForumID.erase(); - -#ifdef DEBUG_FORUMS - std::cerr << "ForumsDialog::insertThreads() Current Thread Invalid" << std::endl; -#endif - - return; - } - - ForumInfo fi; - if (!rsForums->getForumInfo(mCurrForumId, fi)) { - return; - } - - subscribeFlags = fi.subscribeFlags; - ui.forumName->setText(QString::fromStdWString(fi.forumName)); - - ui.progressBarLayOut->setEnabled(true); - - ui.progLayOutTxt->show(); - ui.progressBar->reset(); - ui.progressBar->show(); - - // create fill thread - fillThread = new ForumsFillThread(this); - - // set data - fillThread->compareRole = threadCompareRole; - fillThread->forumId = mCurrForumId; - fillThread->filterColumn = ui.filterLineEdit->currentFilter(); - fillThread->subscribeFlags = subscribeFlags; - fillThread->viewType = ui.viewBox->currentIndex(); - if (lastViewType != fillThread->viewType || lastForumID != mCurrForumId) { - fillThread->fillComplete = true; - } - - if (fillThread->viewType == VIEW_FLAT) { - ui.threadTreeWidget->setRootIsDecorated(false); - } else { - ui.threadTreeWidget->setRootIsDecorated(true); - } - - // connect thread - connect(fillThread, SIGNAL(finished()), this, SLOT(fillThreadFinished()), Qt::BlockingQueuedConnection); - connect(fillThread, SIGNAL(progress(int,int)), this, SLOT(fillThreadProgress(int,int))); - -#ifdef DEBUG_FORUMS - std::cerr << "ForumsDialog::insertThreads() Start fill thread" << std::endl; -#endif - - // start thread - fillThread->start(); -} - -void ForumsDialog::FillThreads(QList &ThreadList, bool expandNewMessages, QList &itemToExpand) -{ -#ifdef DEBUG_FORUMS - std::cerr << "ForumsDialog::FillThreads()" << std::endl; -#endif - - int Index = 0; - QTreeWidgetItem *Thread; - QList::iterator NewThread; - - // delete not existing - while (Index < ui.threadTreeWidget->topLevelItemCount ()) { - Thread = ui.threadTreeWidget->topLevelItem (Index); - - // search existing new thread - int Found = -1; - for (NewThread = ThreadList.begin (); NewThread != ThreadList.end (); NewThread++) { - if (Thread->data (COLUMN_THREAD_DATA, ROLE_THREAD_MSGID) == (*NewThread)->data (COLUMN_THREAD_DATA, ROLE_THREAD_MSGID)) { - // found it - Found = Index; - break; - } - } - if (Found >= 0) { - Index++; - } else { - delete (ui.threadTreeWidget->takeTopLevelItem (Index)); - } - } - - // iterate all new threads - for (NewThread = ThreadList.begin (); NewThread != ThreadList.end (); NewThread++) { - // search existing thread - int Found = -1; - int Count = ui.threadTreeWidget->topLevelItemCount (); - for (Index = 0; Index < Count; Index++) { - Thread = ui.threadTreeWidget->topLevelItem (Index); - if (Thread->data (COLUMN_THREAD_DATA, ROLE_THREAD_MSGID) == (*NewThread)->data (COLUMN_THREAD_DATA, ROLE_THREAD_MSGID)) { - // found it - Found = Index; - break; - } - } - - if (Found >= 0) { - // set child data - int i; - for (i = 0; i < COLUMN_THREAD_COUNT; i++) { - Thread->setText (i, (*NewThread)->text (i)); - } - for (i = 0; i < ROLE_THREAD_COUNT; i++) { - Thread->setData (COLUMN_THREAD_DATA, Qt::UserRole + i, (*NewThread)->data (COLUMN_THREAD_DATA, Qt::UserRole + i)); - } - - // fill recursive - FillChildren (Thread, *NewThread, expandNewMessages, itemToExpand); - } else { - // add new thread - ui.threadTreeWidget->addTopLevelItem (*NewThread); - Thread = *NewThread; - *NewThread = NULL; - } - - uint32_t status = Thread->data (COLUMN_THREAD_DATA, ROLE_THREAD_STATUS).toUInt(); - if (expandNewMessages && IS_UNREAD(status)) { - QTreeWidgetItem *pParent = Thread; - while ((pParent = pParent->parent()) != NULL) { - if (std::find(itemToExpand.begin(), itemToExpand.end(), pParent) == itemToExpand.end()) { - itemToExpand.push_back(pParent); - } - } - } - } - -#ifdef DEBUG_FORUMS - std::cerr << "ForumsDialog::FillThreads() done" << std::endl; -#endif -} - -void ForumsDialog::FillChildren(QTreeWidgetItem *Parent, QTreeWidgetItem *NewParent, bool expandNewMessages, QList &itemToExpand) -{ - int Index = 0; - int NewIndex; - int NewCount = NewParent->childCount(); - - QTreeWidgetItem *Child; - QTreeWidgetItem *NewChild; - - // delete not existing - while (Index < Parent->childCount ()) { - Child = Parent->child (Index); - - // search existing new child - int Found = -1; - int Count = NewParent->childCount(); - for (NewIndex = 0; NewIndex < Count; NewIndex++) { - NewChild = NewParent->child (NewIndex); - if (NewChild->data (COLUMN_THREAD_DATA, ROLE_THREAD_MSGID) == Child->data (COLUMN_THREAD_DATA, ROLE_THREAD_MSGID)) { - // found it - Found = Index; - break; - } - } - if (Found >= 0) { - Index++; - } else { - delete (Parent->takeChild (Index)); - } - } - - // iterate all new children - for (NewIndex = 0; NewIndex < NewCount; NewIndex++) { - NewChild = NewParent->child (NewIndex); - - // search existing child - int Found = -1; - int Count = Parent->childCount(); - for (Index = 0; Index < Count; Index++) { - Child = Parent->child (Index); - if (Child->data (COLUMN_THREAD_DATA, ROLE_THREAD_MSGID) == NewChild->data (COLUMN_THREAD_DATA, ROLE_THREAD_MSGID)) { - // found it - Found = Index; - break; - } - } - - if (Found >= 0) { - // set child data - int i; - for (i = 0; i < COLUMN_THREAD_COUNT; i++) { - Child->setText (i, NewChild->text (i)); - } - for (i = 0; i < ROLE_THREAD_COUNT; i++) { - Child->setData (COLUMN_THREAD_DATA, Qt::UserRole + i, NewChild->data (COLUMN_THREAD_DATA, Qt::UserRole + i)); - } - - // fill recursive - FillChildren (Child, NewChild, expandNewMessages, itemToExpand); - } else { - // add new child - Child = NewParent->takeChild(NewIndex); - Parent->addChild (Child); - NewIndex--; - NewCount--; - } - - uint32_t status = Child->data (COLUMN_THREAD_DATA, ROLE_THREAD_STATUS).toUInt(); - if (expandNewMessages && IS_UNREAD(status)) { - QTreeWidgetItem *pParent = Child; - while ((pParent = pParent->parent()) != NULL) { - if (std::find(itemToExpand.begin(), itemToExpand.end(), pParent) == itemToExpand.end()) { - itemToExpand.push_back(pParent); - } - } - } - } -} - -QString ForumsDialog::titleFromInfo(ForumMsgInfo &msgInfo) -{ - if (msgInfo.msgflags & RS_DISTRIB_MISSING_MSG) { - return QApplication::translate("ForumsDialog", "[ ... Missing Message ... ]"); - } - - return QString::fromStdWString(msgInfo.title); -} - -QString ForumsDialog::messageFromInfo(ForumMsgInfo &msgInfo) -{ - if (msgInfo.msgflags & RS_DISTRIB_MISSING_MSG) { - return QApplication::translate("ForumsDialog", "Placeholder for missing Message"); - } - - return QString::fromStdWString(msgInfo.msg); -} - -void ForumsDialog::insertPost() -{ - if (mCurrForumId.empty()) - { - ui.postText->setText(""); - ui.threadTitle->setText(""); - ui.previousButton->setEnabled(false); - ui.nextButton->setEnabled(false); - ui.newmessageButton->setEnabled (false); - return; - } - - if (mCurrThreadId.empty()) - { - ui.previousButton->setEnabled(false); - ui.nextButton->setEnabled(false); - ui.newmessageButton->setEnabled (false); - - ForumInfo fi; - if (!rsForums->getForumInfo(mCurrForumId, fi)) { - ui.postText->setText(""); - ui.threadTitle->setText(""); - return; - } - ui.threadTitle->setText(tr("Forum Description")); - ui.postText->setText(QString::fromStdWString(fi.forumDesc)); - return; - } - - QTreeWidgetItem *curr = ui.threadTreeWidget->currentItem(); - if (curr) { - QTreeWidgetItem *Parent = curr->parent (); - int Index = Parent ? Parent->indexOfChild (curr) : ui.threadTreeWidget->indexOfTopLevelItem (curr); - int Count = Parent ? Parent->childCount () : ui.threadTreeWidget->topLevelItemCount (); - ui.previousButton->setEnabled (Index > 0); - ui.nextButton->setEnabled (Index < Count - 1); - } else { - // there is something wrong - ui.previousButton->setEnabled(false); - ui.nextButton->setEnabled(false); - return; - } - - ui.newmessageButton->setEnabled (IS_FORUM_SUBSCRIBED(subscribeFlags) && mCurrThreadId.empty() == false); - - /* get the Post */ - ForumMsgInfo msg; - if (!rsForums->getForumMessage(mCurrForumId, mCurrThreadId, msg)) - { - ui.postText->setText(""); - return; - } - - bool bSetToReadOnActive = Settings->getForumMsgSetToReadOnActivate(); - uint32_t status = curr->data(COLUMN_THREAD_DATA, ROLE_THREAD_STATUS).toUInt(); - - QList Row; - Row.append(curr); - if (status & FORUM_MSG_STATUS_READ) { - if (bSetToReadOnActive && (status & FORUM_MSG_STATUS_UNREAD_BY_USER)) { - /* set to read */ - setMsgAsReadUnread(Row, true); - } - } else { - /* set to read */ - if (bSetToReadOnActive) { - setMsgAsReadUnread(Row, true); - } else { - /* set to unread by user */ - setMsgAsReadUnread(Row, false); - } - } - - QString extraTxt = RsHtml().formatText(ui.postText->document(), messageFromInfo(msg), RSHTML_FORMATTEXT_EMBED_SMILEYS | RSHTML_FORMATTEXT_EMBED_LINKS); - - ui.postText->setHtml(extraTxt); - ui.threadTitle->setText(titleFromInfo(msg)); -} - -void ForumsDialog::previousMessage () -{ - QTreeWidgetItem *Item = ui.threadTreeWidget->currentItem (); - if (Item == NULL) { - return; - } - - QTreeWidgetItem *Parent = Item->parent (); - int Index = Parent ? Parent->indexOfChild (Item) : ui.threadTreeWidget->indexOfTopLevelItem (Item); - if (Index > 0) { - QTreeWidgetItem *Previous = Parent ? Parent->child (Index - 1) : ui.threadTreeWidget->topLevelItem (Index - 1); - if (Previous) { - ui.threadTreeWidget->setCurrentItem (Previous); - } - } -} - -void ForumsDialog::nextMessage () -{ - QTreeWidgetItem *Item = ui.threadTreeWidget->currentItem (); - if (Item == NULL) { - return; - } - - QTreeWidgetItem *Parent = Item->parent (); - int Index = Parent ? Parent->indexOfChild (Item) : ui.threadTreeWidget->indexOfTopLevelItem (Item); - int Count = Parent ? Parent->childCount () : ui.threadTreeWidget->topLevelItemCount (); - if (Index < Count - 1) { - QTreeWidgetItem *Next = Parent ? Parent->child (Index + 1) : ui.threadTreeWidget->topLevelItem (Index + 1); - if (Next) { - ui.threadTreeWidget->setCurrentItem (Next); - } - } -} - -void ForumsDialog::downloadAllFiles() -{ - QStringList urls; - if (RsHtml::findAnchors(ui.postText->toHtml(), urls) == false) { - return; - } - - if (urls.count() == 0) { - return; - } - - RetroShareLink::process(urls, RetroShareLink::TYPE_FILE/*, true*/); -} - -void ForumsDialog::nextUnreadMessage() -{ - QTreeWidgetItem *currentItem = ui.threadTreeWidget->currentItem(); - - while (TRUE) { - QTreeWidgetItemIterator itemIterator = currentItem ? QTreeWidgetItemIterator(currentItem, QTreeWidgetItemIterator::NotHidden) : QTreeWidgetItemIterator(ui.threadTreeWidget, QTreeWidgetItemIterator::NotHidden); - - QTreeWidgetItem *item; - while ((item = *itemIterator) != NULL) { - itemIterator++; - - if (item == currentItem) { - continue; - } - - uint32_t status = item->data(COLUMN_THREAD_DATA, ROLE_THREAD_STATUS).toUInt(); - if (IS_UNREAD(status)) { - ui.threadTreeWidget->setCurrentItem(item); - ui.threadTreeWidget->scrollToItem(item, QAbstractItemView::EnsureVisible); - return; - } - } - - if (currentItem == NULL) { - break; - } - - /* start from top */ - currentItem = NULL; - } -} - -// TODO -#if 0 -void ForumsDialog::removemessage() -{ - //std::cerr << "ForumsDialog::removemessage()" << std::endl; - std::string cid, mid; - if (!getCurrentMsg(cid, mid)) - { - //std::cerr << "ForumsDialog::removemessage()"; - //std::cerr << " No Message selected" << std::endl; - return; - } - - rsMsgs -> MessageDelete(mid); -} -#endif - -/* get selected messages - the messages tree is single selected, but who knows ... */ -int ForumsDialog::getSelectedMsgCount(QList *pRows, QList *pRowsRead, QList *pRowsUnread) -{ - if (pRowsRead) pRowsRead->clear(); - if (pRowsUnread) pRowsUnread->clear(); - - QList selectedItems = ui.threadTreeWidget->selectedItems(); - for(QList::iterator it = selectedItems.begin(); it != selectedItems.end(); it++) { - if (pRows) pRows->append(*it); - if (pRowsRead || pRowsUnread) { - uint32_t status = (*it)->data(COLUMN_THREAD_DATA, ROLE_THREAD_STATUS).toUInt(); - if (IS_UNREAD(status)) { - if (pRowsUnread) pRowsUnread->append(*it); - } else { - if (pRowsRead) pRowsRead->append(*it); - } - } - } - - return selectedItems.size(); -} - -void ForumsDialog::setMsgAsReadUnread(QList &Rows, bool bRead) -{ - QList::iterator Row; - std::list changedItems; - - inMsgAsReadUnread = true; - - for (Row = Rows.begin(); Row != Rows.end(); Row++) { - if ((*Row)->data(COLUMN_THREAD_DATA, ROLE_THREAD_MISSING).toBool()) { - /* Missing message */ - continue; - } - - uint32_t status = (*Row)->data(COLUMN_THREAD_DATA, ROLE_THREAD_STATUS).toUInt(); - - /* set always as read ... */ - uint32_t statusNew = status | FORUM_MSG_STATUS_READ; - if (bRead) { - /* ... and as read by user */ - statusNew &= ~FORUM_MSG_STATUS_UNREAD_BY_USER; - } else { - /* ... and as unread by user */ - statusNew |= FORUM_MSG_STATUS_UNREAD_BY_USER; - } - if (status != statusNew) { - std::string msgId = (*Row)->data(COLUMN_THREAD_DATA, ROLE_THREAD_MSGID).toString().toStdString(); - rsForums->setMessageStatus(mCurrForumId, msgId, statusNew, FORUM_MSG_STATUS_READ | FORUM_MSG_STATUS_UNREAD_BY_USER); - - (*Row)->setData(COLUMN_THREAD_DATA, ROLE_THREAD_STATUS, statusNew); - - QTreeWidgetItem *parentItem = *Row; - while (parentItem->parent()) { - parentItem = parentItem->parent(); - } - if (std::find(changedItems.begin(), changedItems.end(), parentItem) == changedItems.end()) { - changedItems.push_back(parentItem); - } - } - } - - inMsgAsReadUnread = false; - - if (changedItems.size()) { - for (std::list::iterator it = changedItems.begin(); it != changedItems.end(); it++) { - CalculateIconsAndFonts(*it); - } - updateMessageSummaryList(mCurrForumId); - } -} - -void ForumsDialog::markMsgAsReadUnread (bool bRead, bool bChildren, bool bForum) -{ - if (mCurrForumId.empty() || !IS_FORUM_SUBSCRIBED(subscribeFlags)) { - return; - } - - /* get selected messages */ - QList Rows; - if (bForum) { - int itemCount = ui.threadTreeWidget->topLevelItemCount(); - for (int item = 0; item < itemCount; item++) { - Rows.push_back(ui.threadTreeWidget->topLevelItem(item)); - } - } else { - getSelectedMsgCount (&Rows, NULL, NULL); - } - - if (bChildren) { - /* add children */ - QList AllRows; - - while (Rows.isEmpty() == false) { - QTreeWidgetItem *pRow = Rows.takeFirst(); - - /* add only items with the right state or with not FORUM_MSG_STATUS_READ */ - uint32_t status = pRow->data(COLUMN_THREAD_DATA, ROLE_THREAD_STATUS).toUInt(); - if (IS_UNREAD(status) == bRead || (status & FORUM_MSG_STATUS_READ) == 0) { - AllRows.append(pRow); - } - - for (int i = 0; i < pRow->childCount(); i++) { - /* add child to main list and let the main loop do the work */ - Rows.append(pRow->child(i)); - } - } - - if (AllRows.isEmpty()) { - /* nothing to do */ - return; - } - - setMsgAsReadUnread (AllRows, bRead); - - return; - } - - setMsgAsReadUnread (Rows, bRead); -} - -void ForumsDialog::markMsgAsRead() -{ - markMsgAsReadUnread(true, false, false); -} - -void ForumsDialog::markMsgAsReadChildren() -{ - markMsgAsReadUnread(true, true, false); -} - -void ForumsDialog::markMsgAsReadAll() -{ - markMsgAsReadUnread(true, true, true); -} - -void ForumsDialog::markMsgAsUnread() -{ - markMsgAsReadUnread(false, false, false); -} - -void ForumsDialog::markMsgAsUnreadChildren() -{ - markMsgAsReadUnread(false, true, false); -} - -void ForumsDialog::markMsgAsUnreadAll() -{ - markMsgAsReadUnread(false, true, true); -} - -void ForumsDialog::copyForumLink() -{ - if (mCurrForumId.empty()) { - return; - } - - ForumInfo fi; - if (rsForums->getForumInfo(mCurrForumId, fi)) { - RetroShareLink link; - if (link.createForum(fi.forumId, "")) { - QList urls; - urls.push_back(link); - RSLinkClipboard::copyLinks(urls); - } - } -} - -void ForumsDialog::copyMessageLink() -{ - if (mCurrForumId.empty() || mCurrThreadId.empty()) { - return; - } - - ForumInfo fi; - if (rsForums->getForumInfo(mCurrForumId, fi)) { - RetroShareLink link; - if (link.createForum(mCurrForumId, mCurrThreadId)) { - QList urls; - urls.push_back(link); - RSLinkClipboard::copyLinks(urls); - } - } -} - -void ForumsDialog::newforum() -{ - CreateForum *cf = new CreateForum(); - cf->show(); - - /* window will destroy itself! */ -} - -void ForumsDialog::createmessage() -{ - if (mCurrForumId.empty () || !IS_FORUM_SUBSCRIBED(subscribeFlags)) { - return; - } - - CreateForumMsg *cfm = new CreateForumMsg(mCurrForumId, mCurrThreadId); - cfm->show(); - - /* window will destroy itself! */ -} - -void ForumsDialog::createthread() -{ - if (mCurrForumId.empty ()) { - QMessageBox::information(this, tr("RetroShare"), tr("No Forum Selected!")); - return; - } - - CreateForumMsg *cfm = new CreateForumMsg(mCurrForumId, ""); - cfm->show(); - - /* window will destroy itself! */ -} - -void ForumsDialog::subscribeToForum() -{ - forumSubscribe(true); -} - -void ForumsDialog::unsubscribeToForum() -{ - forumSubscribe(false); -} - -void ForumsDialog::forumSubscribe(bool subscribe) -{ - if (mCurrForumId.empty()) { - return; - } - - rsForums->forumSubscribe(mCurrForumId, subscribe); -} - -void ForumsDialog::showForumDetails() -{ - if (mCurrForumId.empty()) { - return; - } - - ForumDetails fui; - - fui.showDetails (mCurrForumId); - fui.exec (); -} - -void ForumsDialog::editForumDetails() -{ - if (mCurrForumId.empty()) { - return; - } - - EditForumDetails editUi(mCurrForumId, this); - editUi.exec(); -} - -static QString buildReplyHeader(const ForumMsgInfo &msgInfo) -{ - RetroShareLink link; - link.createMessage(msgInfo.srcId, ""); - QString from = link.toHtml(); - - QString header = QString("-----%1-----").arg(QApplication::translate("ForumsDialog", "Original Message")); - header += QString("
%1: %2
").arg(QApplication::translate("ForumsDialog", "From"), from); - - header += QString("
%1: %2
").arg(QApplication::translate("ForumsDialog", "Sent"), DateTime::formatLongDateTime(msgInfo.ts)); - header += QString("%1: %2

").arg(QApplication::translate("ForumsDialog", "Subject"), QString::fromStdWString(msgInfo.title)); - header += "
"; - - header += QApplication::translate("ForumsDialog", "On %1, %2 wrote:").arg(DateTime::formatDateTime(msgInfo.ts), from); - - return header; -} - -void ForumsDialog::replytomessage() -{ - if (mCurrForumId.empty()) { - return; - } - - std::string fId = mCurrForumId; - std::string pId = mCurrThreadId; - - ForumMsgInfo msgInfo ; - rsForums->getForumMessage(fId,pId,msgInfo) ; - - if (rsPeers->getPeerName(msgInfo.srcId) !="") - { - MessageComposer *nMsgDialog = MessageComposer::newMsg(); - - std::string hash ; - std::string mGpgId = msgInfo.srcId; - - if(rsMsgs->getDistantMessageHash(mGpgId,hash)) - { - nMsgDialog->addRecipient(MessageComposer::TO, hash, mGpgId); - - nMsgDialog->setTitleText(QString::fromStdWString(msgInfo.title), MessageComposer::REPLY); - nMsgDialog->setQuotedMsg(QString::fromStdWString(msgInfo.msg), buildReplyHeader(msgInfo)); - - //nMsgDialog->addRecipient(MessageComposer::TO, msgInfo.srcId, false); - - nMsgDialog->show(); - nMsgDialog->activateWindow(); - } - - /* window will destroy itself! */ - } - else - { - QMessageBox::information(this, tr("RetroShare"),tr("You can't reply an Anonymous Author")); - } -} - -void ForumsDialog::changedViewBox() -{ - if (m_bProcessSettings) { - return; - } - - // save index - Settings->setValueToGroup("ForumsDialog", "viewBox", ui.viewBox->currentIndex()); - - insertThreads(); -} - -void ForumsDialog::filterColumnChanged(int column) -{ - if (m_bProcessSettings) { - return; - } - - if (column == COLUMN_THREAD_CONTENT) { - // need content ... refill - insertThreads(); - } else { - filterItems(ui.filterLineEdit->text()); - } - - // save index - Settings->setValueToGroup("ForumsDialog", "filterColumn", column); -} - -void ForumsDialog::filterItems(const QString& text) -{ - int filterColumn = ui.filterLineEdit->currentFilter(); - - int nCount = ui.threadTreeWidget->topLevelItemCount (); - for (int nIndex = 0; nIndex < nCount; nIndex++) { - filterItem(ui.threadTreeWidget->topLevelItem(nIndex), text, filterColumn); - } -} - -void ForumsDialog::shareKey() -{ - ShareKey shareUi(this, mCurrForumId, FORUM_KEY_SHARE); - shareUi.exec(); -} - -bool ForumsDialog::filterItem(QTreeWidgetItem *pItem, const QString &text, int filterColumn) -{ - bool bVisible = true; - - if (text.isEmpty() == false) { - if (pItem->text(filterColumn).contains(text, Qt::CaseInsensitive) == false) { - bVisible = false; - } - } - - int nVisibleChildCount = 0; - int nCount = pItem->childCount(); - for (int nIndex = 0; nIndex < nCount; nIndex++) { - if (filterItem(pItem->child(nIndex), text, filterColumn)) { - nVisibleChildCount++; - } - } - - if (bVisible || nVisibleChildCount) { - pItem->setHidden(false); - } else { - pItem->setHidden(true); - } - - return (bVisible || nVisibleChildCount); -} - -void ForumsDialog::updateMessageSummaryList(std::string forumId) -{ - QTreeWidgetItem *items[2] = { yourForums, subscribedForums }; - - for (int item = 0; item < 2; item++) { - int child; - int childCount = items[item]->childCount(); - for (child = 0; child < childCount; child++) { - QTreeWidgetItem *childItem = items[item]->child(child); - std::string childId = ui.forumTreeWidget->itemId(childItem).toStdString(); - if (childId.empty()) { - continue; - } - - if (forumId.empty() || childId == forumId) { - /* calculate unread messages */ - unsigned int newMessageCount = 0; - unsigned int unreadMessageCount = 0; - rsForums->getMessageCount(childId, newMessageCount, unreadMessageCount); - - ui.forumTreeWidget->setUnreadCount(childItem, unreadMessageCount); - - if (forumId.empty() == false) { - /* Calculate only this forum */ - break; - } - } - } - } -} - -bool ForumsDialog::navigate(const std::string& forumId, const std::string& msgId) -{ - if (forumId.empty()) { - return false; - } - - if (ui.forumTreeWidget->activateId(QString::fromStdString(forumId), msgId.empty()) == NULL) { - return false; - } - - /* Threads are filled in changedForum */ - if (mCurrForumId != forumId) { - return false; - } - - if (msgId.empty()) { - return true; - } - - if (fillThread && fillThread->isRunning()) { - fillThread->focusMsgId = msgId; - return true; - } - - /* Search exisiting item */ - QTreeWidgetItemIterator itemIterator(ui.threadTreeWidget); - QTreeWidgetItem *item = NULL; - while ((item = *itemIterator) != NULL) { - itemIterator++; - - if (item->data(COLUMN_THREAD_DATA, ROLE_THREAD_MSGID).toString().toStdString() == msgId) { - ui.threadTreeWidget->setCurrentItem(item); - ui.threadTreeWidget->setFocus(); - return true; - } - } - - return false; -} - -void ForumsDialog::generateMassData() -{ -#ifdef DEBUG_FORUMS - if (mCurrForumId.empty ()) { - return; - } - - if (QMessageBox::question(this, "Generate mass data", "Do you really want to generate mass data ?", QMessageBox::Yes|QMessageBox::No, QMessageBox::No) == QMessageBox::No) { - return; - } - - for (int thread = 1; thread < 1000; thread++) { - ForumMsgInfo threadInfo; - threadInfo.forumId = mCurrForumId; - threadInfo.title = QString("Test %1").arg(thread, 3, 10, QChar('0')).toStdWString(); - threadInfo.msg = QString("That is only a test").toStdWString(); - - if (rsForums->ForumMessageSend(threadInfo) == false) { - return; - } - - for (int msg = 1; msg < 3; msg++) { - ForumMsgInfo msgInfo; - msgInfo.forumId = mCurrForumId; - msgInfo.threadId = threadInfo.msgId; - msgInfo.parentId = threadInfo.msgId; - msgInfo.title = threadInfo.title; - msgInfo.msg = threadInfo.msg; - - if (rsForums->ForumMessageSend(msgInfo) == false) { - return; - } - } - } -#endif -} - -// ForumsFillThread -ForumsFillThread::ForumsFillThread(ForumsDialog *parent) - : QThread(parent) -{ - stopped = false; - compareRole = NULL; - - expandNewMessages = Settings->getForumExpandNewMessages(); - fillComplete = false; - - filterColumn = 0; - subscribeFlags = 0; - viewType = 0; -} - -ForumsFillThread::~ForumsFillThread() -{ -#ifdef DEBUG_FORUMS - std::cerr << "ForumsFillThread::~ForumsFillThread" << std::endl; -#endif - // remove all items (when items are available, the thread was terminated) - CleanupItems (items); - itemToExpand.clear(); -} - -void ForumsFillThread::stop() -{ - disconnect(); - stopped = true; - QApplication::processEvents(); - wait(); -} - -void ForumsFillThread::run() -{ -#ifdef DEBUG_FORUMS - std::cerr << "ForumsFillThread::run()" << std::endl; -#endif - - uint32_t status; - - std::list threads; - std::list::iterator tit; - rsForums->getForumThreadList(forumId, threads); - - bool flatView = false; - bool useChildTS = false; - switch(viewType) - { - case VIEW_LAST_POST: - useChildTS = true; - break; - case VIEW_FLAT: - flatView = true; - break; - case VIEW_THREADED: - break; - } - - int count = threads.size(); - int pos = 0; - - for (tit = threads.begin(); tit != threads.end(); tit++) - { - if (stopped) { - break; - } - -#ifdef DEBUG_FORUMS - std::cerr << "ForumsFillThread::run() Adding TopLevel Thread: mId: " << tit->msgId << std::endl; -#endif - - ForumMsgInfo msginfo; - if (rsForums->getForumMessage(forumId, tit->msgId, msginfo) == false) { -#ifdef DEBUG_FORUMS - std::cerr << "ForumsFillThread::run() Failed to Get Msg" << std::endl; -#endif - continue; - } - - /* add Msg */ - /* setup - * - */ - - QTreeWidgetItem *item = new RSTreeWidgetItem(compareRole); - - QString text; - - { - QDateTime qtime; - QString sort; - - if (useChildTS) - qtime.setTime_t(tit->childTS); - else - qtime.setTime_t(tit->ts); - - text = DateTime::formatDateTime(qtime); - sort = qtime.toString("yyyyMMdd_hhmmss"); - - if (useChildTS) - { - qtime.setTime_t(tit->ts); - text += " / "; - text += DateTime::formatDateTime(qtime); - sort += "_" + qtime.toString("yyyyMMdd_hhmmss"); - } - item->setText(COLUMN_THREAD_DATE, text); - item->setData(COLUMN_THREAD_DATE, ROLE_THREAD_SORT, sort); - } - - item->setText(COLUMN_THREAD_TITLE, ForumsDialog::titleFromInfo(msginfo)); - - if (msginfo.msgflags & RS_DISTRIB_MISSING_MSG) - { - item->setText(COLUMN_THREAD_AUTHOR, tr("Unknown")); - } - else - { - text = QString::fromUtf8(rsPeers->getPeerName(msginfo.srcId).c_str()); - if (text.isEmpty()) - { - item->setText(COLUMN_THREAD_AUTHOR, tr("Anonymous")); - } - else - { - item->setText(COLUMN_THREAD_AUTHOR, text); - } - } - - if (msginfo.msgflags & RS_DISTRIB_AUTHEN_REQ) - { - item->setText(COLUMN_THREAD_SIGNED, tr("signed")); - item->setIcon(COLUMN_THREAD_SIGNED, QIcon(":/images/mail-signed.png")); - } - else - { - item->setText(COLUMN_THREAD_SIGNED, tr("none")); - item->setIcon(COLUMN_THREAD_SIGNED, QIcon(":/images/mail-signature-unknown.png")); - } - - if (filterColumn == COLUMN_THREAD_CONTENT) { - // need content for filter - QTextDocument doc; - doc.setHtml(QString::fromStdWString(msginfo.msg)); - item->setText(COLUMN_THREAD_CONTENT, doc.toPlainText().replace(QString("\n"), QString(" "))); - } - - item->setData(COLUMN_THREAD_DATA, ROLE_THREAD_MSGID, QString::fromStdString(tit->msgId)); - - if (IS_FORUM_SUBSCRIBED(subscribeFlags) && !(msginfo.msgflags & RS_DISTRIB_MISSING_MSG)) { - rsForums->getMessageStatus(msginfo.forumId, msginfo.msgId, status); - } else { - // show message as read - status = FORUM_MSG_STATUS_READ; - } - item->setData(COLUMN_THREAD_DATA, ROLE_THREAD_STATUS, status); - - item->setData(COLUMN_THREAD_DATA, ROLE_THREAD_MISSING, (msginfo.msgflags & RS_DISTRIB_MISSING_MSG) ? true : false); - - std::list threadlist; - threadlist.push_back(item); - - while (threadlist.size() > 0) - { - if (stopped) { - break; - } - - /* get children */ - QTreeWidgetItem *parent = threadlist.front(); - threadlist.pop_front(); - std::string pId = parent->data(COLUMN_THREAD_DATA, ROLE_THREAD_MSGID).toString().toStdString(); - - std::list msgs; - std::list::iterator mit; - -#ifdef DEBUG_FORUMS - std::cerr << "ForumsFillThread::run() Getting Children of : " << pId << std::endl; -#endif - - if (rsForums->getForumThreadMsgList(forumId, pId, msgs)) - { -#ifdef DEBUG_FORUMS - std::cerr << "ForumsFillThread::run() #Children " << msgs.size() << std::endl; -#endif - - /* iterate through child */ - for(mit = msgs.begin(); mit != msgs.end(); mit++) - { -#ifdef DEBUG_FORUMS - std::cerr << "ForumsFillThread::run() adding " << mit->msgId << std::endl; -#endif - - ForumMsgInfo msginfo; - if (rsForums->getForumMessage(forumId, mit->msgId, msginfo) == false) { -#ifdef DEBUG_FORUMS - std::cerr << "ForumsFillThread::run() Failed to Get Msg" << std::endl; -#endif - continue; - } - - QTreeWidgetItem *child = NULL; - if (flatView) - { - child = new RSTreeWidgetItem(compareRole); - } - else - { - child = new RSTreeWidgetItem(compareRole, parent); - } - - { - QDateTime qtime; - QString sort; - - if (useChildTS) - qtime.setTime_t(mit->childTS); - else - qtime.setTime_t(mit->ts); - - text = DateTime::formatDateTime(qtime); - sort = qtime.toString("yyyyMMdd_hhmmss"); - - if (useChildTS) - { - qtime.setTime_t(mit->ts); - text += " / "; - text += DateTime::formatDateTime(qtime); - sort += "_" + qtime.toString("yyyyMMdd_hhmmss"); - } - child->setText(COLUMN_THREAD_DATE, text); - child->setData(COLUMN_THREAD_DATE, ROLE_THREAD_SORT, sort); - } - - child->setText(COLUMN_THREAD_TITLE, ForumsDialog::titleFromInfo(msginfo)); - - text = QString::fromUtf8(rsPeers->getPeerName(msginfo.srcId).c_str()); - if (text.isEmpty()) - { - child->setText(COLUMN_THREAD_AUTHOR, tr("Anonymous")); - } - else - { - child->setText(COLUMN_THREAD_AUTHOR, text); - } - - if (msginfo.msgflags & RS_DISTRIB_AUTHEN_REQ) - { - child->setText(COLUMN_THREAD_SIGNED, tr("signed")); - child->setIcon(COLUMN_THREAD_SIGNED,(QIcon(":/images/mail-signed.png"))); - } - else - { - child->setText(COLUMN_THREAD_SIGNED, tr("none")); - child->setIcon(COLUMN_THREAD_SIGNED,(QIcon(":/images/mail-signature-unknown.png"))); - } - - if (filterColumn == COLUMN_THREAD_CONTENT) { - // need content for filter - QTextDocument doc; - doc.setHtml(ForumsDialog::messageFromInfo(msginfo)); - child->setText(COLUMN_THREAD_CONTENT, doc.toPlainText().replace(QString("\n"), QString(" "))); - } - - child->setData(COLUMN_THREAD_DATA, ROLE_THREAD_MSGID, QString::fromStdString(mit->msgId)); - - if (IS_FORUM_SUBSCRIBED(subscribeFlags) && !(msginfo.msgflags & RS_DISTRIB_MISSING_MSG)) { - rsForums->getMessageStatus(msginfo.forumId, msginfo.msgId, status); - } else { - // show message as read - status = FORUM_MSG_STATUS_READ; - } - child->setData(COLUMN_THREAD_DATA, ROLE_THREAD_STATUS, status); - - child->setData(COLUMN_THREAD_DATA, ROLE_THREAD_MISSING, (msginfo.msgflags & RS_DISTRIB_MISSING_MSG) ? true : false); - - if (fillComplete && expandNewMessages && IS_UNREAD(status)) { - QTreeWidgetItem *pParent = child; - while ((pParent = pParent->parent()) != NULL) { - if (std::find(itemToExpand.begin(), itemToExpand.end(), pParent) == itemToExpand.end()) { - itemToExpand.push_back(pParent); - } - } - } - - /* setup child */ - threadlist.push_back(child); - - if (flatView) - { - items.append(child); - } - } - } - } - - /* add to list */ - items.append(item); - - emit progress(++pos, count); - } - -#ifdef DEBUG_FORUMS - std::cerr << "ForumsFillThread::run() stopped: " << (wasStopped() ? "yes" : "no") << std::endl; -#endif -} diff --git a/retroshare-gui/src/gui/ForumsDialog.h b/retroshare-gui/src/gui/ForumsDialog.h deleted file mode 100644 index ed3c21f98..000000000 --- a/retroshare-gui/src/gui/ForumsDialog.h +++ /dev/null @@ -1,214 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2008 Robert Fernie - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - -#ifndef _FORUMSDIALOG_H -#define _FORUMSDIALOG_H - -#include - -#include "mainpage.h" -#include "RsAutoUpdatePage.h" -#include "ui_ForumsDialog.h" - -class ForumInfo; -class ForumsFillThread; -class ForumMsgInfo; -class RSTreeWidgetItemCompareRole; - -class ForumsDialog : public RsAutoUpdatePage -{ - Q_OBJECT - - Q_PROPERTY(QColor textColorRead READ textColorRead WRITE setTextColorRead) - Q_PROPERTY(QColor textColorUnread READ textColorUnread WRITE setTextColorUnread) - Q_PROPERTY(QColor textColorUnreadChildren READ textColorUnreadChildren WRITE setTextColorUnreadChildren) - Q_PROPERTY(QColor textColorNotSubscribed READ textColorNotSubscribed WRITE setTextColorNotSubscribed) - Q_PROPERTY(QColor textColorMissing READ textColorMissing WRITE setTextColorMissing) - -public: - ForumsDialog(QWidget *parent = 0); - ~ForumsDialog(); - - virtual UserNotify *getUserNotify(QObject *parent); - - bool navigate(const std::string& forumId, const std::string& msgId); - - /* overloaded from RsAuthUpdatePage */ - virtual void updateDisplay(); - - static QString titleFromInfo(ForumMsgInfo &msgInfo); - static QString messageFromInfo(ForumMsgInfo &msgInfo); - - QColor textColorRead() const { return mTextColorRead; } - QColor textColorUnread() const { return mTextColorUnread; } - QColor textColorUnreadChildren() const { return mTextColorUnreadChildren; } - QColor textColorNotSubscribed() const { return mTextColorNotSubscribed; } - QColor textColorMissing() const { return mTextColorMissing; } - - void setTextColorRead(QColor color) { mTextColorRead = color; } - void setTextColorUnread(QColor color) { mTextColorUnread = color; } - void setTextColorUnreadChildren(QColor color) { mTextColorUnreadChildren = color; } - void setTextColorNotSubscribed(QColor color) { mTextColorNotSubscribed = color; } - void setTextColorMissing(QColor color) { mTextColorMissing = color; } - -protected: - bool eventFilter(QObject *obj, QEvent *ev); - void changeEvent(QEvent *e); - -private slots: - /** Create the context popup menu and it's submenus */ - void forumListCustomPopupMenu( QPoint point ); - void threadListCustomPopupMenu( QPoint point ); - void restoreForumKeys(); - void newforum(); - - void changedForum(const QString &id); - void changedThread(); - void clickedThread (QTreeWidgetItem *item, int column); - void forumMsgReadSatusChanged(const QString &forumId, const QString &msgId, int status); - - void replytomessage(); - //void print(); - //void printpreview(); - - //void removemessage(); - void markMsgAsRead(); - void markMsgAsReadChildren(); - void markMsgAsReadAll(); - void markMsgAsUnread(); - void markMsgAsUnreadAll(); - void markMsgAsUnreadChildren(); - void copyForumLink(); - void copyMessageLink(); - - /* handle splitter */ - void togglethreadview(); - - void createthread(); - void createmessage(); - - void subscribeToForum(); - void unsubscribeToForum(); - - void showForumDetails(); - void editForumDetails(); - - void previousMessage (); - void nextMessage (); - void nextUnreadMessage(); - void downloadAllFiles(); - - void changedViewBox(); - - void filterColumnChanged(int column); - void filterItems(const QString &text); - - void generateMassData(); - - void fillThreadFinished(); - void fillThreadProgress(int current, int count); - - void shareKey(); - -private: - void insertForums(); - void insertThreads(); - void insertPost(); - void updateMessageSummaryList(std::string forumId); - void forumInfoToGroupItemInfo(const ForumInfo &forumInfo, GroupItemInfo &groupItemInfo); - - void forumSubscribe(bool subscribe); - void FillThreads(QList &ThreadList, bool bExpandNewMessages, QList &itemToExpand); - void FillChildren(QTreeWidgetItem *Parent, QTreeWidgetItem *NewParent, bool bExpandNewMessages, QList &itemToExpand); - - int getSelectedMsgCount(QList *pRows, QList *pRowsRead, QList *pRowsUnread); - void setMsgAsReadUnread(QList &Rows, bool bRead); - void markMsgAsReadUnread(bool bRead, bool bChildren, bool bForum); - void CalculateIconsAndFonts(QTreeWidgetItem *pItem = NULL); - void CalculateIconsAndFonts(QTreeWidgetItem *pItem, bool &bHasReadChilddren, bool &bHasUnreadChilddren); - - void processSettings(bool bLoad); - void togglethreadview_internal(); - - bool filterItem(QTreeWidgetItem *pItem, const QString &text, int filterColumn); - - bool m_bProcessSettings; - bool inMsgAsReadUnread; - - QTreeWidgetItem *yourForums; - QTreeWidgetItem *subscribedForums; - QTreeWidgetItem *popularForums; - QTreeWidgetItem *otherForums; - - RSTreeWidgetItemCompareRole *threadCompareRole; - std::string mCurrForumId; - std::string mCurrThreadId; - int subscribeFlags; - - int lastViewType; - std::string lastForumID; - - ForumsFillThread *fillThread; - - /* Color definitions (for standard see qss.default) */ - QColor mTextColorRead; - QColor mTextColorUnread; - QColor mTextColorUnreadChildren; - QColor mTextColorNotSubscribed; - QColor mTextColorMissing; - - /** Qt Designer generated object */ - Ui::ForumsDialog ui; -}; - -class ForumsFillThread : public QThread -{ - Q_OBJECT - -public: - ForumsFillThread(ForumsDialog *parent); - ~ForumsFillThread(); - - void run(); - void stop(); - bool wasStopped() { return stopped; } - -signals: - void progress(int current, int count); - -public: - std::string forumId; - int filterColumn; - int subscribeFlags; - bool fillComplete; - int viewType; - bool expandNewMessages; - std::string focusMsgId; - RSTreeWidgetItemCompareRole *compareRole; - - QList items; - QList itemToExpand; - -private: - volatile bool stopped; -}; - -#endif diff --git a/retroshare-gui/src/gui/ForumsDialog.ui b/retroshare-gui/src/gui/ForumsDialog.ui deleted file mode 100644 index 672738739..000000000 --- a/retroshare-gui/src/gui/ForumsDialog.ui +++ /dev/null @@ -1,591 +0,0 @@ - - - ForumsDialog - - - - 0 - 0 - 769 - 519 - - - - - - - - 0 - 0 - - - - QFrame::Box - - - QFrame::Sunken - - - - 2 - - - - - - 24 - 24 - - - - - - - :/images/konversation.png - - - true - - - - - - - - 10 - 75 - true - - - - Forums - - - - - - - Qt::Horizontal - - - - 123 - 13 - - - - - - - - Qt::NoFocus - - - - :/images/64px_help.png:/images/64px_help.png - - - true - - - true - - - - - - - - - - Qt::Horizontal - - - - - 0 - 0 - - - - - - Qt::Vertical - - - - - - - - - - 0 - 0 - - - - - 0 - 0 - - - - - 16777215 - 16777215 - - - - - 10 - 75 - true - - - - Forum: - - - - - - - - 0 - 0 - - - - - 10 - 75 - true - - - - true - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse - - - - - - - - Last Post - - - - - Threaded View - - - - - Flat View - - - - - - - - - - - 9 - - - - Qt::CustomContextMenu - - - true - - - true - - - - Title - - - - - - - - - :/images/message-state-header.png:/images/message-state-header.png - - - - - Date - - - - - Author - - - - - Signed - - - - - - - - - - - 0 - 0 - - - - - 10 - 75 - true - - - - Thread: - - - - - - - - 10 - 75 - true - - - - true - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse - - - - - - - false - - - - 0 - 0 - - - - - 24 - 24 - - - - - 24 - 24 - - - - Qt::NoFocus - - - Previous Thread - - - - - - - :/images/back.png:/images/back.png - - - - - - - false - - - - 0 - 0 - - - - - 24 - 24 - - - - - 24 - 24 - - - - Qt::NoFocus - - - Next Thread - - - - - - - :/images/forward.png:/images/forward.png - - - - - - - - 24 - 24 - - - - Qt::NoFocus - - - - - - - :/images/edit_remove24.png:/images/edit_remove24.png - - - true - - - true - - - - - - - - 24 - 24 - - - - Qt::NoFocus - - - Download all files - - - - :/images/down.png:/images/down.png - - - - - - - - 0 - 0 - - - - Next unread - - - - - - - - - - 0 - 0 - - - - QFrame::Box - - - QFrame::Sunken - - - - 2 - - - - - Qt::NoFocus - - - Start new Thread for Selected Forum - - - - :/images/mail_new.png:/images/mail_new.png - - - - 32 - 16 - - - - true - - - - - - - Qt::NoFocus - - - Reply Message - - - - :/images/mail_reply.png:/images/mail_reply.png - - - - 32 - 16 - - - - true - - - - - - - Qt::Horizontal - - - QSizePolicy::Expanding - - - - 40 - 20 - - - - - - - - - - - - - - - - - 75 - true - - - - Loading - - - - - - - - 16777215 - 25 - - - - 1000 - - - 0 - - - - - - - - - - - 0 - 10 - - - - - 9 - - - - - - - - - - Print - - - - - PrintPreview - - - splitter - titleBarFrame - - - - GroupTreeWidget - QWidget -
gui/common/GroupTreeWidget.h
- 1 -
- - LineEditClear - QLineEdit -
gui/common/LineEditClear.h
-
- - LinkTextBrowser - QTextBrowser -
gui/common/LinkTextBrowser.h
-
-
- - - - -
diff --git a/retroshare-gui/src/gui/MainWindow.cpp b/retroshare-gui/src/gui/MainWindow.cpp index 0fb92cee3..4d4cc1da4 100644 --- a/retroshare-gui/src/gui/MainWindow.cpp +++ b/retroshare-gui/src/gui/MainWindow.cpp @@ -48,12 +48,12 @@ #include "NewsFeed.h" #include "ShareManager.h" #include "NetworkView.h" -#include "ForumsDialog.h" +//#include "ForumsDialog.h" #include "FriendsDialog.h" #include "ChatLobbyWidget.h" #include "HelpDialog.h" #include "AboutDialog.h" -#include "ChannelFeed.h" +//#include "ChannelFeed.h" #include "bwgraph/bwgraph.h" #include "help/browser/helpbrowser.h" #include "chat/ChatDialog.h" @@ -87,8 +87,6 @@ #include #include #include -#include -#include #include #include "gui/connect/ConnectFriendWizard.h" @@ -267,17 +265,21 @@ MainWindow::MainWindow(QWidget* parent, Qt::WFlags flags) action = createPageAction(QIcon(IMAGE_MESSAGES), tr("Messages"), grp)); notify.push_back(QPair(messagesDialog, action)); +#if 0 ui->stackPages->add(channelFeed = new ChannelFeed(ui->stackPages), action = createPageAction(QIcon(IMAGE_CHANNELS), tr("Channels"), grp)); notify.push_back(QPair(channelFeed, action)); +#endif #ifdef BLOGS ui->stackPages->add(blogsFeed = new BlogsDialog(ui->stackPages), createPageAction(QIcon(IMAGE_BLOGS), tr("Blogs"), grp)); #endif - + +#if 0 ui->stackPages->add(forumsDialog = new ForumsDialog(ui->stackPages), action = createPageAction(QIcon(IMAGE_FORUMS), tr("Forums"), grp)); notify.push_back(QPair(forumsDialog, action)); +#endif std::cerr << "Looking for interfaces in existing plugins:" << std::endl; for(int i = 0;inbPlugins();++i) @@ -815,12 +817,14 @@ void SetForegroundWindowInternal(HWND hWnd) case Messages: _instance->ui->stackPages->setCurrentPage( _instance->messagesDialog ); break; +#if 0 case Channels: _instance->ui->stackPages->setCurrentPage( _instance->channelFeed ); return true ; case Forums: _instance->ui->stackPages->setCurrentPage( _instance->forumsDialog ); return true ; +#endif #ifdef BLOGS case Blogs: Page = _instance->blogsFeed; @@ -865,12 +869,14 @@ void SetForegroundWindowInternal(HWND hWnd) return Links; } #endif +#if 0 if (page == _instance->channelFeed) { return Channels; } if (page == _instance->forumsDialog) { return Forums; } +#endif #ifdef BLOGS if (page == _instance->blogsFeed) { return Blogs; @@ -907,10 +913,12 @@ void SetForegroundWindowInternal(HWND hWnd) case Links: return _instance->linksDialog; #endif +#if 0 case Channels: return _instance->channelFeed; case Forums: return _instance->forumsDialog; +#endif #ifdef BLOGS case Blogs: return _instance->blogsFeed; diff --git a/retroshare-gui/src/gui/MainWindow.h b/retroshare-gui/src/gui/MainWindow.h index ed822d78e..589f6ceae 100644 --- a/retroshare-gui/src/gui/MainWindow.h +++ b/retroshare-gui/src/gui/MainWindow.h @@ -41,7 +41,7 @@ class RatesStatus; class DiscStatus; class DHTStatus; class HashingStatus; -class ForumsDialog; +//class ForumsDialog; class FriendsDialog; class ChatLobbyWidget; class ChatDialog; @@ -52,7 +52,7 @@ class MessagesDialog; class SharedFilesDialog; class MessengerWindow; class PluginsPage; -class ChannelFeed; +//class ChannelFeed; class BandwidthGraph; class MainPage; class NewsFeed; @@ -84,8 +84,8 @@ public: Transfers = 3, /** Transfers page. */ SharedDirectories = 4, /** Shared Directories page. */ Messages = 5, /** Messages page. */ - Channels = 6, /** Channels page. */ - Forums = 7, /** Forums page. */ + // Channels = 6, /** Channels page. */ + // Forums = 7, /** Forums page. */ Search = 8, /** Search page. */ #ifdef BLOGS Blogs = 9, /** Blogs page. */ @@ -129,8 +129,8 @@ public: ChatLobbyWidget *chatLobbyDialog; MessagesDialog *messagesDialog; SharedFilesDialog *sharedfilesDialog; - ForumsDialog *forumsDialog; - ChannelFeed *channelFeed; +// ForumsDialog *forumsDialog; +// ChannelFeed *channelFeed; Idle *idle; #ifdef RS_USE_LINKS diff --git a/retroshare-gui/src/gui/NewsFeed.cpp b/retroshare-gui/src/gui/NewsFeed.cpp index aa352a83d..066b2b3b8 100644 --- a/retroshare-gui/src/gui/NewsFeed.cpp +++ b/retroshare-gui/src/gui/NewsFeed.cpp @@ -25,15 +25,17 @@ #include #include -#include -#include +//#include +//#include #include #include +#if 0 #include "feeds/ChanNewItem.h" #include "feeds/ChanMsgItem.h" #include "feeds/ForumNewItem.h" #include "feeds/ForumMsgItem.h" +#endif #include "settings/rsettingswin.h" #ifdef BLOGS @@ -53,12 +55,16 @@ #include "common/FeedNotify.h" const uint32_t NEWSFEED_PEERLIST = 0x0001; + +#if 0 const uint32_t NEWSFEED_FORUMNEWLIST = 0x0002; const uint32_t NEWSFEED_FORUMMSGLIST = 0x0003; const uint32_t NEWSFEED_CHANNEWLIST = 0x0004; const uint32_t NEWSFEED_CHANMSGLIST = 0x0005; const uint32_t NEWSFEED_BLOGNEWLIST = 0x0006; const uint32_t NEWSFEED_BLOGMSGLIST = 0x0007; +#endif + const uint32_t NEWSFEED_MESSAGELIST = 0x0008; const uint32_t NEWSFEED_CHATMSGLIST = 0x0009; const uint32_t NEWSFEED_SECLIST = 0x000a; @@ -164,6 +170,7 @@ void NewsFeed::updateDisplay() addFeedItemSecurityUnknownOut(fi); break; +#if 0 case RS_FEED_ITEM_CHAN_NEW: if (flags & RS_FEED_TYPE_CHAN) addFeedItemChanNew(fi); @@ -198,6 +205,7 @@ void NewsFeed::updateDisplay() if (flags & RS_FEED_TYPE_BLOG) addFeedItemBlogMsg(fi); break; +#endif case RS_FEED_ITEM_CHAT_NEW: if (flags & RS_FEED_TYPE_CHAT) @@ -270,6 +278,7 @@ void NewsFeed::testFeeds(uint notifyFlags) instance->addFeedItemSecurityUnknownOut(fi); break; +#if 0 case RS_FEED_TYPE_CHAN: { std::list channelList; @@ -385,6 +394,7 @@ void NewsFeed::testFeeds(uint notifyFlags) // instance->addFeedItemBlogNew(fi); // instance->addFeedItemBlogMsg(fi); break; +#endif case RS_FEED_TYPE_CHAT: fi.mId1 = rsPeers->getOwnId(); @@ -618,8 +628,10 @@ void NewsFeed::addFeedItemSecurityUnknownOut(RsFeedItem &fi) #endif } +#if 0 void NewsFeed::addFeedItemChanNew(RsFeedItem &fi) { + /* make new widget */ ChanNewItem *cni = new ChanNewItem(this, NEWSFEED_CHANNEWLIST, fi.mId1, false, true); @@ -756,6 +768,8 @@ void NewsFeed::addFeedItemBlogMsg(RsFeedItem &fi) #endif } +#endif + void NewsFeed::addFeedItemChatNew(RsFeedItem &fi, bool addWithoutCheck) { #ifdef NEWS_DEBUG diff --git a/retroshare-gui/src/gui/NewsFeed.h b/retroshare-gui/src/gui/NewsFeed.h index 698b040ec..e0dcc0378 100644 --- a/retroshare-gui/src/gui/NewsFeed.h +++ b/retroshare-gui/src/gui/NewsFeed.h @@ -80,6 +80,7 @@ private: void addFeedItemSecurityUnknownIn(RsFeedItem &fi); void addFeedItemSecurityUnknownOut(RsFeedItem &fi); +#if 0 void addFeedItemChanNew(RsFeedItem &fi); void addFeedItemChanUpdate(RsFeedItem &fi); void addFeedItemChanMsg(RsFeedItem &fi); @@ -88,6 +89,8 @@ private: void addFeedItemForumMsg(RsFeedItem &fi); void addFeedItemBlogNew(RsFeedItem &fi); void addFeedItemBlogMsg(RsFeedItem &fi); +#endif + void addFeedItemChatNew(RsFeedItem &fi, bool addWithoutCheck); void addFeedItemMessage(RsFeedItem &fi); void addFeedItemFilesNew(RsFeedItem &fi); diff --git a/retroshare-gui/src/gui/RetroShareLink.cpp b/retroshare-gui/src/gui/RetroShareLink.cpp index 308eea491..e5d6630c2 100644 --- a/retroshare-gui/src/gui/RetroShareLink.cpp +++ b/retroshare-gui/src/gui/RetroShareLink.cpp @@ -30,8 +30,8 @@ #include "RetroShareLink.h" #include "MainWindow.h" -#include "ForumsDialog.h" -#include "ChannelFeed.h" +//#include "ForumsDialog.h" +//#include "ChannelFeed.h" #include "SearchDialog.h" #include "msgs/MessageComposer.h" #include "util/misc.h" @@ -44,8 +44,8 @@ #include #include #include -#include -#include +//#include +//#include //#define DEBUG_RSLINK 1 @@ -470,6 +470,7 @@ bool RetroShareLink::createForum(const std::string& id, const std::string& msgId { clear(); +#if 0 if (!id.empty()) { _hash = QString::fromStdString(id); _msgId = QString::fromStdString(msgId); @@ -488,6 +489,7 @@ bool RetroShareLink::createForum(const std::string& id, const std::string& msgId } } } +#endif check(); @@ -498,6 +500,7 @@ bool RetroShareLink::createChannel(const std::string& id, const std::string& msg { clear(); +#if 0 if (!id.empty()) { _hash = QString::fromStdString(id); _msgId = QString::fromStdString(msgId); @@ -516,6 +519,7 @@ bool RetroShareLink::createChannel(const std::string& id, const std::string& msg } } } +#endif check(); @@ -1365,6 +1369,7 @@ static void processList(const QStringList &list, const QString &textSingular, co break; } +#if 0 case TYPE_FORUM: { #ifdef DEBUG_RSLINK @@ -1456,6 +1461,7 @@ static void processList(const QStringList &list, const QString &textSingular, co } break; } +#endif case TYPE_SEARCH: { diff --git a/retroshare-gui/src/gui/channels/ChannelDetails.cpp b/retroshare-gui/src/gui/channels/ChannelDetails.cpp deleted file mode 100644 index e45622c5d..000000000 --- a/retroshare-gui/src/gui/channels/ChannelDetails.cpp +++ /dev/null @@ -1,117 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2009 RetroShare Team - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ -#include "ChannelDetails.h" -#include "util/DateTime.h" - -#include -#include -#include -#include - -#include -#include - -#include -#include -#include - - -/** Default constructor */ -ChannelDetails::ChannelDetails(QWidget *parent) - : QDialog(parent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint) -{ - /* Invoke Qt Designer generated QObject setup routine */ - ui.setupUi(this); - - connect(ui.buttonBox, SIGNAL(rejected()), this, SLOT(close())); - - ui.nameline ->setReadOnly(true); - ui.popline ->setReadOnly(true); - ui.postline ->setReadOnly(true); - ui.IDline ->setReadOnly(true); - ui.DescriptiontextEdit ->setReadOnly(true); - - ui.typeEncrypted->setEnabled(false); - ui.typePrivate->setEnabled(false); -} - - -/** - Overloads the default show() slot so we can set opacity*/ - -void -ChannelDetails::show() -{ - //loadSettings(); - if(!this->isVisible()) { - QDialog::show(); - - } -} - -void ChannelDetails::showDetails(std::string mChannelId) -{ - cId = mChannelId; - loadChannel(); -} - -void ChannelDetails::loadChannel() -{ - if (!rsChannels) - { - return; - } - uint32_t flags = 0; - - ChannelInfo ci; - rsChannels->getChannelInfo(cId, ci); - flags = ci.channelFlags; - - // Set Channel Name - ui.nameline->setText(QString::fromStdWString(ci.channelName)); - - // Set Channel Popularity - { - ui.popline -> setText(QString::number(ci.pop)); - } - - // Set Last Channel Post Date - if (ci.lastPost) { - ui.postline->setText(DateTime::formatLongDateTime(ci.lastPost)); - } - - // Set Channel ID - ui.IDline->setText(QString::fromStdString(ci.channelId)); - - // Set Channel Description - ui.DescriptiontextEdit->setText(QString::fromStdWString(ci.channelDesc)); - - if (flags |= RS_DISTRIB_PRIVATE) - { - ui.typeEncrypted->setChecked(false); - ui.typePrivate->setChecked(true); - } - else if (flags |= RS_DISTRIB_ENCRYPTED) - { - ui.typeEncrypted->setChecked(true); - ui.typePrivate->setChecked(false); - } -} diff --git a/retroshare-gui/src/gui/channels/ChannelDetails.h b/retroshare-gui/src/gui/channels/ChannelDetails.h deleted file mode 100644 index 4fd31dcac..000000000 --- a/retroshare-gui/src/gui/channels/ChannelDetails.h +++ /dev/null @@ -1,57 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2009 RetroShare Team - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - -#ifndef _CHANNELDETAILS_H -#define _CHANNELDETAILS_H - -#include - -#include "ui_ChannelDetails.h" - -class ChannelDetails : public QDialog -{ - Q_OBJECT - - public: - - /** Default constructor */ - ChannelDetails(QWidget *parent = 0); - - void showDetails(std::string mChannelId); - -signals: - void configChanged() ; - -public slots: - /** Overloaded QWidget.show */ - void show(); - -private: - void loadChannel(); - - std::string cId; - /** Qt Designer generated object */ - Ui::ChannelDetails ui; - -}; - -#endif - diff --git a/retroshare-gui/src/gui/channels/ChannelDetails.ui b/retroshare-gui/src/gui/channels/ChannelDetails.ui deleted file mode 100644 index f7c15c02e..000000000 --- a/retroshare-gui/src/gui/channels/ChannelDetails.ui +++ /dev/null @@ -1,148 +0,0 @@ - - - ChannelDetails - - - - 0 - 0 - 455 - 408 - - - - Channel Details - - - - :/images/rstray3.png:/images/rstray3.png - - - - - - 0 - - - - - :/images/info16.png:/images/info16.png - - - Channel Details - - - - - - Channel Info - - - - - - Channel Name - - - - - - - - - - Popularity - - - - - - - true - - - - - - - Last Post - - - - - - - true - - - - - - - Channel ID - - - - - - - - - - Channel Description - - - - - - - - - Type - - - - - - Restricted - Anyone can read, limited publishing (Private Publish Key) - - - - - - - Private - (Private Publish Key required to view Messages) - - - - - - - - - - - - - - - - - - - - - - QDialogButtonBox::Close - - - - - - - - - - - - diff --git a/retroshare-gui/src/gui/channels/ChannelUserNotify.cpp b/retroshare-gui/src/gui/channels/ChannelUserNotify.cpp deleted file mode 100644 index ac88fca68..000000000 --- a/retroshare-gui/src/gui/channels/ChannelUserNotify.cpp +++ /dev/null @@ -1,106 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2012 RetroShare Team - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - -#include "ChannelUserNotify.h" -#include "gui/settings/rsharesettings.h" -#include "gui/notifyqt.h" -#include "gui/MainWindow.h" - -#include - -ChannelUserNotify::ChannelUserNotify(QObject *parent) : - UserNotify(parent) -{ - connect(NotifyQt::getInstance(), SIGNAL(channelsChanged(int)), this, SLOT(updateIcon()), Qt::QueuedConnection); -} - -bool ChannelUserNotify::hasSetting(QString &name) -{ - name = tr("Channel Post"); - - return true; -} - -bool ChannelUserNotify::notifyEnabled() -{ - return (Settings->getTrayNotifyFlags() & TRAYNOTIFY_CHANNELS); -} - -bool ChannelUserNotify::notifyCombined() -{ - return (Settings->getTrayNotifyFlags() & TRAYNOTIFY_CHANNELS_COMBINED); -} - -bool ChannelUserNotify::notifyBlink() -{ - return (Settings->getTrayNotifyBlinkFlags() & TRAYNOTIFY_BLINK_CHANNELS); -} - -void ChannelUserNotify::setNotifyEnabled(bool enabled, bool combined, bool blink) -{ - uint notifyFlags = Settings->getTrayNotifyFlags(); - uint blinkFlags = Settings->getTrayNotifyBlinkFlags(); - - if (enabled) { - notifyFlags |= TRAYNOTIFY_CHANNELS; - } else { - notifyFlags &= ~TRAYNOTIFY_CHANNELS; - } - - if (combined) { - notifyFlags |= TRAYNOTIFY_CHANNELS_COMBINED; - } else { - notifyFlags &= ~TRAYNOTIFY_CHANNELS_COMBINED; - } - - if (blink) { - blinkFlags |= TRAYNOTIFY_BLINK_CHANNELS; - } else { - blinkFlags &= ~TRAYNOTIFY_BLINK_CHANNELS; - } - - Settings->setTrayNotifyFlags(notifyFlags); - Settings->setTrayNotifyBlinkFlags(blinkFlags); -} - -QIcon ChannelUserNotify::getIcon() -{ - return QIcon(":/images/channels16.png"); -} - -QIcon ChannelUserNotify::getMainIcon(bool hasNew) -{ - return hasNew ? QIcon(":/images/channels_new.png") : QIcon(":/images/channels.png"); -} - -unsigned int ChannelUserNotify::getNewCount() -{ - unsigned int newMessageCount = 0; - unsigned int unreadMessageCount = 0; - rsChannels->getMessageCount("", newMessageCount, unreadMessageCount); - - return newMessageCount; -} - -void ChannelUserNotify::iconClicked() -{ - MainWindow::showWindow(MainWindow::Channels); -} diff --git a/retroshare-gui/src/gui/channels/ChannelUserNotify.h b/retroshare-gui/src/gui/channels/ChannelUserNotify.h deleted file mode 100644 index ef1608001..000000000 --- a/retroshare-gui/src/gui/channels/ChannelUserNotify.h +++ /dev/null @@ -1,47 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2012 RetroShare Team - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - -#ifndef CHANNELUSERNOTIFY_H -#define CHANNELUSERNOTIFY_H - -#include "gui/common/UserNotify.h" - -class ChannelUserNotify : public UserNotify -{ - Q_OBJECT - -public: - ChannelUserNotify(QObject *parent = 0); - - virtual bool hasSetting(QString &name); - virtual bool notifyEnabled(); - virtual bool notifyCombined(); - virtual bool notifyBlink(); - virtual void setNotifyEnabled(bool enabled, bool combined, bool blink); - -private: - virtual QIcon getIcon(); - virtual QIcon getMainIcon(bool hasNew); - virtual unsigned int getNewCount(); - virtual void iconClicked(); -}; - -#endif // CHANNELUSERNOTIFY_H diff --git a/retroshare-gui/src/gui/channels/CreateChannel.cpp b/retroshare-gui/src/gui/channels/CreateChannel.cpp deleted file mode 100644 index 4342204b0..000000000 --- a/retroshare-gui/src/gui/channels/CreateChannel.cpp +++ /dev/null @@ -1,151 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2008 Robert Fernie - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - -#include -#include - -#include - -#include "CreateChannel.h" -#include "gui/common/PeerDefs.h" -#include "util/misc.h" - -#include -#include - -/** Constructor */ -CreateChannel::CreateChannel() -: QDialog(NULL, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint) -{ - /* Invoke the Qt Designer generated object setup routine */ - ui.setupUi(this); - - setAttribute(Qt::WA_DeleteOnClose, true); - - ui.headerFrame->setHeaderImage(QPixmap(":/images/add_channel64.png")); - ui.headerFrame->setHeaderText(tr("New Channel")); - - picture = NULL; - - // connect up the buttons. - connect( ui.buttonBox, SIGNAL(accepted()), this, SLOT(createChannel())); - connect( ui.buttonBox, SIGNAL(rejected()), this, SLOT(close())); - - connect( ui.logoButton, SIGNAL(clicked() ), this , SLOT(addChannelLogo())); - connect( ui.pubKeyShare_cb, SIGNAL( clicked() ), this, SLOT( setShareList( ) )); - - if (!ui.pubKeyShare_cb->isChecked()) { - ui.contactsdockWidget->hide(); - this->resize(this->size().width() - ui.contactsdockWidget->size().width(), this->size().height()); - } - - /* initialize key share list */ - ui.keyShareList->setHeaderText(tr("Contacts:")); - ui.keyShareList->setModus(FriendSelectionWidget::MODUS_CHECK); - ui.keyShareList->setShowType(FriendSelectionWidget::SHOW_GROUP | FriendSelectionWidget::SHOW_SSL); - ui.keyShareList->start(); - - newChannel(); -} - -void CreateChannel::setShareList(){ - - if (ui.pubKeyShare_cb->isChecked()){ - this->resize(this->size().width() + ui.contactsdockWidget->size().width(), this->size().height()); - ui.contactsdockWidget->show(); - } else { - ui.contactsdockWidget->hide(); - this->resize(this->size().width() - ui.contactsdockWidget->size().width(), this->size().height()); - } -} - -void CreateChannel::newChannel() -{ - /* enforce Private for the moment */ - ui.typePrivate->setChecked(true); - - ui.typeEncrypted->setEnabled(true); - - ui.msgAnon->setChecked(true); - ui.msgAuth->setEnabled(false); - ui.msgGroupBox->hide(); - - ui.channelName->setFocus(); -} - -void CreateChannel::createChannel() -{ - QString name = misc::removeNewLine(ui.channelName->text()); - QString desc = ui.channelDesc->toPlainText(); - uint32_t flags = 0; - - if (name.isEmpty()) { - /* error message */ - QMessageBox::warning(this, "RetroShare", tr("Please add a Name"), QMessageBox::Ok, QMessageBox::Ok); - return; //Don't add a empty name!! - } - - if (ui.typePrivate->isChecked()) { - flags |= RS_DISTRIB_PRIVATE; - } else if (ui.typeEncrypted->isChecked()) { - flags |= RS_DISTRIB_ENCRYPTED; - } - - if (ui.msgAuth->isChecked()) { - flags |= RS_DISTRIB_AUTHEN_REQ; - } else if (ui.msgAnon->isChecked()) { - flags |= RS_DISTRIB_AUTHEN_ANON; - } - QByteArray ba; - QBuffer buffer(&ba); - - if (!picture.isNull()) { - // send chan image - - buffer.open(QIODevice::WriteOnly); - picture.save(&buffer, "PNG"); // writes image into ba in PNG format - } - - if (rsChannels) { - std::string chId = rsChannels->createChannel(name.toStdWString(), desc.toStdWString(), flags, (unsigned char*)ba.data(), ba.size()); - - if (ui.pubKeyShare_cb->isChecked()) { - std::list shareList; - ui.keyShareList->selectedSslIds(shareList, false); - rsChannels->channelShareKeys(chId, shareList); - } - } - - close(); -} - -void CreateChannel::addChannelLogo() // the same function as in EditChanDetails -{ - QPixmap img = misc::getOpenThumbnailedPicture(this, tr("Load channel logo"), 64, 64); - - if (img.isNull()) - return; - - picture = img; - - // to show the selected - ui.logoLabel->setPixmap(picture); -} diff --git a/retroshare-gui/src/gui/channels/CreateChannel.h b/retroshare-gui/src/gui/channels/CreateChannel.h deleted file mode 100644 index f82e3536c..000000000 --- a/retroshare-gui/src/gui/channels/CreateChannel.h +++ /dev/null @@ -1,51 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2008 Robert Fernie - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - -#ifndef _CREATE_CHANNEL_DIALOG_H -#define _CREATE_CHANNEL_DIALOG_H - -#include "ui_CreateChannel.h" - -class CreateChannel : public QDialog -{ - Q_OBJECT - -public: - CreateChannel(); - - void newChannel(); /* cleanup */ - -private slots: - /* actions to take.... */ - void createChannel(); - - void addChannelLogo(); - void setShareList(); - -private: - QPixmap picture; - - /** Qt Designer generated object */ - Ui::CreateChannel ui; -}; - -#endif - diff --git a/retroshare-gui/src/gui/channels/CreateChannel.ui b/retroshare-gui/src/gui/channels/CreateChannel.ui deleted file mode 100644 index d93df8009..000000000 --- a/retroshare-gui/src/gui/channels/CreateChannel.ui +++ /dev/null @@ -1,371 +0,0 @@ - - - CreateChannel - - - - 0 - 0 - 703 - 611 - - - - Create a new Channel - - - - :/images/rstray3.png:/images/rstray3.png - - - - 0 - - - 0 - - - - - - - - - - - - - Name - - - - - - - - - - - - true - - - - 0 - 0 - - - - - 300 - 524287 - - - - - 220 - 0 - - - - - 0 - 0 - - - - check peers you would like to share private publish key with - - - false - - - QDockWidget::NoDockWidgetFeatures - - - Share Key With - - - - - 0 - - - 0 - - - - - - 0 - 4 - - - - - 20 - 0 - - - - - 300 - 16777215 - - - - - 220 - 0 - - - - - 200 - 0 - - - - - - - - - - - - - - Description - - - - - - - - - - - - Type: - - - - 0 - - - 6 - - - - - Restricted - Anyone can read, limited publishing (Private Publish Key) - - - - - - - Private - (Private Publish Key required to view Messages) - - - - - - - - - - Allowed Messages - - - - 0 - - - 6 - - - - - Anonymous Messages - - - - - - - Authenticated Messages - - - - - - - - - - Key Sharing - - - - 0 - - - 6 - - - - - Key recipients can publish to restricted-type channels, and can view and publish for private-type channels - - - Share Private Publish Key - - - - - - - - - - Channel Logo - - - - 6 - - - 6 - - - 6 - - - 2 - - - 6 - - - - - - - - 64 - 64 - - - - - 64 - 64 - - - - QFrame::StyledPanel - - - QFrame::Raised - - - :/images/channels.png - - - true - - - - - - - Add Channel Logo - - - - :/images/add_image24.png:/images/add_image24.png - - - - - - - Qt::Horizontal - - - - 118 - 20 - - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - - - - - - - - HeaderFrame - QFrame -
gui/common/HeaderFrame.h
- 1 -
- - FriendSelectionWidget - QWidget -
gui/common/FriendSelectionWidget.h
- 1 -
-
- - - - -
diff --git a/retroshare-gui/src/gui/channels/CreateChannelMsg.cpp b/retroshare-gui/src/gui/channels/CreateChannelMsg.cpp deleted file mode 100644 index a1caaecbc..000000000 --- a/retroshare-gui/src/gui/channels/CreateChannelMsg.cpp +++ /dev/null @@ -1,648 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2008 Robert Fernie - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - -#include -#include -#include -#include -#include -#include -#include - -#include -#include "CreateChannelMsg.h" -#include "gui/feeds/SubFileItem.h" -#include "util/misc.h" - -#include -#include - -#include - -/** Constructor */ -CreateChannelMsg::CreateChannelMsg(std::string cId) -: QDialog (NULL, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint), mChannelId(cId) ,mCheckAttachment(true), mAutoMediaThumbNail(false) -{ - /* Invoke the Qt Designer generated object setup routine */ - setupUi(this); - - headerFrame->setHeaderImage(QPixmap(":/images/channels.png")); - headerFrame->setHeaderText(tr("New Channel Post")); - - setAttribute ( Qt::WA_DeleteOnClose, true ); - - connect(buttonBox, SIGNAL(accepted()), this, SLOT(sendMsg())); - connect(buttonBox, SIGNAL(rejected()), this, SLOT(cancelMsg())); - - connect(addFileButton, SIGNAL(clicked() ), this , SLOT(addExtraFile())); - connect(addfilepushButton, SIGNAL(clicked() ), this , SLOT(addExtraFile())); - connect(addThumbnailButton, SIGNAL(clicked() ), this , SLOT(addThumbnail())); - connect(thumbNailCb, SIGNAL(toggled(bool)), this, SLOT(allowAutoMediaThumbNail(bool))); - connect(tabWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextMenu(QPoint))); - - thumbNailCb->setVisible(false); - thumbNailCb->setEnabled(false); -#ifdef CHANNELS_FRAME_CATCHER - fCatcher = new framecatcher(); - thumbNailCb->setVisible(true); - thumbNailCb->setEnabled(true); -#endif - //buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); - - setAcceptDrops(true); - - newChannelMsg(); -} - -void CreateChannelMsg::contextMenu(QPoint /*point*/) -{ - QList links ; - RSLinkClipboard::pasteLinks(links) ; - - int n_file = 0 ; - - for(QList::const_iterator it(links.begin());it!=links.end();++it) - if((*it).type() == RetroShareLink::TYPE_FILE) - n_file++ ; - - QMenu contextMnu(this) ; - - QAction *action ; - - if(n_file > 1) - action = contextMnu.addAction(QIcon(":/images/pasterslink.png"), tr("Paste RetroShare Links"), this, SLOT(pasteLink())); - else - action = contextMnu.addAction(QIcon(":/images/pasterslink.png"), tr("Paste RetroShare Link"), this, SLOT(pasteLink())); - - action->setDisabled(n_file < 1) ; - contextMnu.exec(QCursor::pos()); -} - -void CreateChannelMsg::pasteLink() -{ - std::cerr << "Pasting links: " << std::endl; - - QList links,not_have ; - RSLinkClipboard::pasteLinks(links) ; - - for(QList::const_iterator it(links.begin());it!=links.end();++it) - if((*it).type() == RetroShareLink::TYPE_FILE) - { - // 0 - check that we actually have the file! - // - - std::cerr << "Pasting " << (*it).toString().toStdString() << std::endl; - - FileInfo info ; - if(rsFiles->alreadyHaveFile( (*it).hash().toStdString(),info ) ) - addAttachment((*it).hash().toStdString(), (*it).name().toUtf8().constData(), (*it).size(), true, "") ; - else - not_have.push_back( *it ) ; - } - - if(!not_have.empty()) - { - QString msg = tr("You are about to add files you're not actually sharing. Do you still want this to happen?")+"

" ; - - for(QList::const_iterator it(not_have.begin());it!=not_have.end();++it) - msg += (*it).toString() + "
" ; - - if(QMessageBox::YesToAll == QMessageBox::question(NULL,tr("About to post un-owned files to a channel."),msg,QMessageBox::YesToAll | QMessageBox::No)) - for(QList::const_iterator it(not_have.begin());it!=not_have.end();++it) - addAttachment((*it).hash().toStdString(), (*it).name().toUtf8().constData(), (*it).size(), false, "") ; - } -} - -CreateChannelMsg::~CreateChannelMsg(){ - -#ifdef CHANNELS_FRAME_CATCHER - delete fCatcher; -#endif - -} - -/* Dropping */ - -void CreateChannelMsg::dragEnterEvent(QDragEnterEvent *event) -{ - /* print out mimeType */ - std::cerr << "CreateChannelMsg::dragEnterEvent() Formats"; - std::cerr << std::endl; - QStringList formats = event->mimeData()->formats(); - QStringList::iterator it; - for(it = formats.begin(); it != formats.end(); it++) - { - std::cerr << "Format: " << (*it).toStdString(); - std::cerr << std::endl; - } - - if (event->mimeData()->hasFormat("text/plain")) - { - std::cerr << "CreateChannelMsg::dragEnterEvent() Accepting PlainText"; - std::cerr << std::endl; - event->acceptProposedAction(); - } - else if (event->mimeData()->hasUrls()) - { - std::cerr << "CreateChannelMsg::dragEnterEvent() Accepting Urls"; - std::cerr << std::endl; - event->acceptProposedAction(); - } - else if (event->mimeData()->hasFormat("application/x-rsfilelist")) - { - std::cerr << "CreateChannelMsg::dragEnterEvent() accepting Application/x-qabs..."; - std::cerr << std::endl; - event->acceptProposedAction(); - } - else - { - std::cerr << "CreateChannelMsg::dragEnterEvent() No PlainText/Urls"; - std::cerr << std::endl; - } -} - -void CreateChannelMsg::dropEvent(QDropEvent *event) -{ - if (!(Qt::CopyAction & event->possibleActions())) - { - std::cerr << "CreateChannelMsg::dropEvent() Rejecting uncopyable DropAction"; - std::cerr << std::endl; - - /* can't do it */ - return; - } - - std::cerr << "CreateChannelMsg::dropEvent() Formats" << std::endl; - QStringList formats = event->mimeData()->formats(); - QStringList::iterator it; - for(it = formats.begin(); it != formats.end(); it++) - { - std::cerr << "Format: " << (*it).toStdString(); - std::cerr << std::endl; - } - - if (event->mimeData()->hasText()) - { - std::cerr << "CreateChannelMsg::dropEvent() Plain Text:"; - std::cerr << std::endl; - std::cerr << event->mimeData()->text().toStdString(); - std::cerr << std::endl; - } - - if (event->mimeData()->hasUrls()) - { - std::cerr << "CreateChannelMsg::dropEvent() Urls:" << std::endl; - - QList urls = event->mimeData()->urls(); - QList::iterator uit; - for(uit = urls.begin(); uit != urls.end(); uit++) - { - QString localpath = uit->toLocalFile(); - std::cerr << "Whole URL: " << uit->toString().toStdString() << std::endl; - std::cerr << "or As Local File: " << localpath.toStdString() << std::endl; - - if (localpath.isEmpty() == false) - { - // Check that the file does exist and is not a directory - QDir dir(localpath); - if (dir.exists()) { - std::cerr << "CreateChannelMsg::dropEvent() directory not accepted."<< std::endl; - QMessageBox mb(tr("Drop file error."), tr("Directory can't be dropped, only files are accepted."),QMessageBox::Information,QMessageBox::Ok,0,0,this); - mb.exec(); - } else if (QFile::exists(localpath)) { - addAttachment(localpath.toUtf8().constData()); - } else { - std::cerr << "CreateChannelMsg::dropEvent() file does not exists."<< std::endl; - QMessageBox mb(tr("Drop file error."), tr("File not found or file name not accepted."),QMessageBox::Information,QMessageBox::Ok,0,0,this); - mb.exec(); - } - } - } - } - else if (event->mimeData()->hasFormat("application/x-rsfilelist")) - { - std::cerr << "CreateChannelMsg::dropEvent() Application/x-rsfilelist"; - std::cerr << std::endl; - - QByteArray data = event->mimeData()->data("application/x-rsfilelist"); - std::cerr << "Data Len:" << data.length(); - std::cerr << std::endl; - std::cerr << "Data is:" << data.data(); - std::cerr << std::endl; - - std::string newattachments(data.data()); - parseRsFileListAttachments(newattachments); - } - - event->setDropAction(Qt::CopyAction); - event->accept(); -} - -void CreateChannelMsg::parseRsFileListAttachments(const std::string &attachList) -{ - /* split into lines */ - QString input = QString::fromStdString(attachList); - - QStringList attachItems = input.split("\n"); - QStringList::iterator it; - QStringList::iterator it2; - - for(it = attachItems.begin(); it != attachItems.end(); it++) - { - std::cerr << "CreateChannelMsg::parseRsFileListAttachments() Entry: "; - - QStringList parts = (*it).split("/"); - - bool ok = false; - quint64 qsize = 0; - - std::string fname; - std::string hash; - uint64_t size = 0; - std::string source; - - int i = 0; - for(it2 = parts.begin(); it2 != parts.end(); it2++, i++) - { - std::cerr << "\"" << it2->toStdString() << "\" "; - switch(i) - { - case 0: - fname = it2->toStdString(); - break; - case 1: - hash = it2->toStdString(); - break; - case 2: - qsize = it2->toULongLong(&ok, 10); - size = qsize; - break; - case 3: - source = it2->toStdString(); - break; - } - } - - std::cerr << std::endl; - - std::cerr << "\tfname: " << fname << std::endl; - std::cerr << "\thash: " << hash << std::endl; - std::cerr << "\tsize: " << size << std::endl; - std::cerr << "\tsource: " << source << std::endl; - - /* basic error checking */ - if ((ok) && (hash.size() == 40)) - { - std::cerr << "Item Ok" << std::endl; - if (source == "Local") - { - addAttachment(hash, fname, size, true, ""); - } - else - { - // TEMP NOT ALLOWED UNTIL FT WORKING. - addAttachment(hash, fname, size, false, source); - } - - } - else - { - std::cerr << "Error Decode: Hash size: " << hash.size() << std::endl; - } - - } -} - - -void CreateChannelMsg::addAttachment(const std::string &hash, const std::string &fname, uint64_t size, bool local, const std::string &srcId) -{ - /* add a SubFileItem to the attachment section */ - std::cerr << "CreateChannelMsg::addAttachment()"; - std::cerr << std::endl; - - /* add widget in for new destination */ - - uint32_t flags = SFI_TYPE_CHANNEL; - if (local) - { - flags |= SFI_STATE_LOCAL; - } - else - { - flags |= SFI_STATE_REMOTE; - } - - SubFileItem *file = new SubFileItem(hash, fname, "", size, flags, srcId); // destroyed when fileFrame (this subfileitem) is destroyed - - mAttachments.push_back(file); - QLayout *layout = fileFrame->layout(); - layout->addWidget(file); - - if (mCheckAttachment) - { - checkAttachmentReady(); - } - - return; -} - - -void CreateChannelMsg::addExtraFile() -{ - /* add a SubFileItem to the attachment section */ - std::cerr << "CreateChannelMsg::addExtraFile() opening file dialog"; - std::cerr << std::endl; - - QStringList files; - if (misc::getOpenFileNames(this, RshareSettings::LASTDIR_EXTRAFILE, tr("Add Extra File"), "", files)) { - for (QStringList::iterator fileIt = files.begin(); fileIt != files.end(); fileIt++) { - addAttachment((*fileIt).toUtf8().constData()); - } - } -} - - -void CreateChannelMsg::addAttachment(const std::string &path) -{ - /* add a SubFileItem to the attachment section */ - std::cerr << "CreateChannelMsg::addAttachment()"; - std::cerr << std::endl; - - if(mAutoMediaThumbNail) - setThumbNail(path, 2000); - - /* add widget in for new destination */ - uint32_t flags = SFI_TYPE_CHANNEL | SFI_STATE_EXTRA | SFI_FLAG_CREATE; - - // check attachment if hash exists already - std::list::iterator it; - - for(it= mAttachments.begin(); it != mAttachments.end(); it++){ - - if((*it)->FilePath() == path){ - QMessageBox::warning(this, tr("RetroShare"), - tr("File already Added and Hashed"), - QMessageBox::Ok, QMessageBox::Ok); - - return; - } - - } - - // channels creates copy of file into channels directory and shares this - - FileInfo fInfo; - rsChannels->channelExtraFileHash(path, mChannelId, fInfo); - - // file is not innitial - SubFileItem *file = new SubFileItem(fInfo.hash, fInfo.fname, fInfo.path, fInfo.size, - flags, mChannelId); // destroyed when fileFrame (this subfileitem) is destroyed - - mAttachments.push_back(file); - QLayout *layout = fileFrame->layout(); - layout->addWidget(file); - - if (mCheckAttachment) - { - checkAttachmentReady(); - } - - return; -} - -bool CreateChannelMsg::setThumbNail(const std::string& path, int frame){ - -#ifdef CHANNELS_FRAME_CATCHER - unsigned char* imageBuffer = NULL; - int width = 0, height = 0, errCode = 0; - int length; - std::string errString; - - if(1 != (errCode = fCatcher->open(path))){ - fCatcher->getError(errCode, errString); - std::cerr << errString << std::endl; - return false; - } - - length = fCatcher->getLength(); - - // make sure frame chosen is at lease a quarter length of video length if not choose quarter length - if(frame < (int) (0.25 * length)) - frame = 0.25 * length; - - if(1 != (errCode = fCatcher->getRGBImage(frame, imageBuffer, width, height))){ - fCatcher->getError(errCode, errString); - std::cerr << errString << std::endl; - return false; - } - - if(imageBuffer == NULL) - return false; - - QImage tNail(imageBuffer, width, height, QImage::Format_RGB32); - QByteArray ba; - QBuffer buffer(&ba); - buffer.open(QIODevice::WriteOnly); - tNail.save(&buffer, "PNG"); - QPixmap img; - img.loadFromData(ba, "PNG"); - img = img.scaled(thumbnail_label->width(), thumbnail_label->height(), Qt::KeepAspectRatio); - thumbnail_label->setPixmap(img); - - delete[] imageBuffer; -#else - Q_UNUSED(path); - Q_UNUSED(frame); -#endif - - return true; -} - -void CreateChannelMsg::allowAutoMediaThumbNail(bool allowThumbNail){ - - mAutoMediaThumbNail = allowThumbNail; -} - -void CreateChannelMsg::checkAttachmentReady() -{ - std::list::iterator fit; - - mCheckAttachment = false; - - for(fit = mAttachments.begin(); fit != mAttachments.end(); fit++) - { - if (!(*fit)->isHidden()) - { - if (!(*fit)->ready()) - { - /* ensure file is hashed or file will be hashed, thus - * recognized by librs but not correctly by gui (can't - * formally remove it) - */ - buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); - buttonBox->button(QDialogButtonBox::Cancel)->setEnabled(false); - break; - } - } - } - - if (fit == mAttachments.end()) - { - buttonBox->button(QDialogButtonBox::Ok)->setEnabled(true); - buttonBox->button(QDialogButtonBox::Cancel)->setEnabled(true); - } - - /* repeat... */ - int msec_rate = 1000; - QTimer::singleShot( msec_rate, this, SLOT(checkAttachmentReady(void))); -} - - -void CreateChannelMsg::cancelMsg() -{ - std::cerr << "CreateChannelMsg::cancelMsg() :" - << "Deleting EXTRA attachments" << std::endl; - - std::cerr << std::endl; - - std::list::const_iterator it; - - for(it = mAttachments.begin(); it != mAttachments.end(); it++) - rsChannels->channelExtraFileRemove((*it)->FileHash(), mChannelId); - - close(); - return; -} - -void CreateChannelMsg::newChannelMsg() -{ - if (!rsChannels) - return; - - ChannelInfo ci; - if (!rsChannels->getChannelInfo(mChannelId, ci)) - { - - return; - } - - channelName->setText(QString::fromStdWString(ci.channelName)); - subjectEdit->setFocus(); -} - -void CreateChannelMsg::sendMsg() -{ - std::cerr << "CreateChannelMsg::sendMsg()"; - std::cerr << std::endl; - - /* construct message bits */ - std::wstring subject = misc::removeNewLine(subjectEdit->text()).toStdWString(); - std::wstring msg = msgEdit->toPlainText().toStdWString(); - - std::list files; - - std::list::iterator fit; - - for(fit = mAttachments.begin(); fit != mAttachments.end(); fit++) - { - if (!(*fit)->isHidden()) - { - FileInfo fi; - fi.hash = (*fit)->FileHash(); - fi.fname = (*fit)->FileName(); - fi.size = (*fit)->FileSize(); - - files.push_back(fi); - - /* commence downloads - if we don't have the file */ - - if (!(*fit)->done()) - { - if ((*fit)->ready()) - { - (*fit)->download(); - } - // Skips unhashed files. - } - } - } - - sendMessage(subject, msg, files); - -} - -void CreateChannelMsg::sendMessage(std::wstring subject, std::wstring msg, std::list &files) -{ - QString name = misc::removeNewLine(subjectEdit->text()); - - if(name.isEmpty()) - { /* error message */ - QMessageBox::warning(this, tr("RetroShare"), - tr("Please add a Subject"), - QMessageBox::Ok, QMessageBox::Ok); - - return; //Don't add an empty Subject!! - } - else - /* rsChannels */ - if (rsChannels) - { - ChannelMsgInfo msgInfo; - - msgInfo.channelId = mChannelId; - msgInfo.msgId = ""; - - msgInfo.subject = subject; - msgInfo.msg = msg; - msgInfo.files = files; - - QByteArray ba; - QBuffer buffer(&ba); - - if(!picture.isNull()){ - // send chan image - - buffer.open(QIODevice::WriteOnly); - picture.save(&buffer, "PNG"); // writes image into ba in PNG format - msgInfo.thumbnail.image_thumbnail = (unsigned char*) ba.data(); - msgInfo.thumbnail.im_thumbnail_size = ba.size(); - } - - rsChannels->ChannelMessageSend(msgInfo); - } - - close(); - return; - -} - -void CreateChannelMsg::addThumbnail() -{ - QPixmap img = misc::getOpenThumbnailedPicture(this, tr("Load thumbnail picture"), 156, 107); - - if (img.isNull()) - return; - - picture = img; - - // to show the selected - thumbnail_label->setPixmap(picture); -} diff --git a/retroshare-gui/src/gui/channels/CreateChannelMsg.h b/retroshare-gui/src/gui/channels/CreateChannelMsg.h deleted file mode 100644 index 848aa5b03..000000000 --- a/retroshare-gui/src/gui/channels/CreateChannelMsg.h +++ /dev/null @@ -1,91 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2008 Robert Fernie - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - -#ifndef _CREATECHANNELMSG_H -#define _CREATECHANNELMSG_H - -#include "ui_CreateChannelMsg.h" -#include - -#ifdef CHANNELS_FRAME_CATCHER -#include "util/framecatcher.h" -#endif - -class SubFileItem; -class FileInfo; - -class CreateChannelMsg : public QDialog, private Ui::CreateChannelMsg -{ - Q_OBJECT - -public: - /** Default Constructor */ - CreateChannelMsg(std::string cId); - - - /** Default Destructor */ - ~CreateChannelMsg(); - - void addAttachment(const std::string &path); - void addAttachment(const std::string &hash, const std::string &fname, uint64_t size, bool local, const std::string &srcId); - - void newChannelMsg(); - - QPixmap picture; - -protected: -virtual void dragEnterEvent(QDragEnterEvent *event); -virtual void dropEvent(QDropEvent *event); - -private slots: - void addExtraFile(); - void checkAttachmentReady(); - - void cancelMsg(); - void sendMsg(); - void pasteLink() ; - void contextMenu(QPoint) ; - - void addThumbnail(); - void allowAutoMediaThumbNail(bool); - -private: - - void parseRsFileListAttachments(const std::string &attachList); - void sendMessage(std::wstring subject, std::wstring msg, std::list &files); - bool setThumbNail(const std::string& path, int frame); - - - std::string mChannelId; - - std::list mAttachments; - - bool mCheckAttachment; - bool mAutoMediaThumbNail; - -#ifdef CHANNELS_FRAME_CATCHER - framecatcher* fCatcher; -#endif - -}; - -#endif - diff --git a/retroshare-gui/src/gui/channels/CreateChannelMsg.ui b/retroshare-gui/src/gui/channels/CreateChannelMsg.ui deleted file mode 100644 index 6e9ebb4bd..000000000 --- a/retroshare-gui/src/gui/channels/CreateChannelMsg.ui +++ /dev/null @@ -1,365 +0,0 @@ - - - CreateChannelMsg - - - - 0 - 0 - 581 - 479 - - - - true - - - New Channel Post - - - - :/images/rstray3.png:/images/rstray3.png - - - - 0 - - - 0 - - - - - - - - QFrame::StyledPanel - - - QFrame::Raised - - - - - - true - - - Qt::CustomContextMenu - - - false - - - 0 - - - - Channel Post - - - - - - - - - 75 - true - - - - Channel Post to: - - - - - - - true - - - true - - - - - - - - - - - <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> -<html><head><meta name="qrichtext" content="1" /><style type="text/css"> -p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'Ubuntu'; font-size:11pt; font-weight:400; font-style:normal;"> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:10pt; font-weight:600;">Attachments:</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><img src=":/images/feedback_arrow.png" /><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;"> Use Drag and Drop / Add Files button, to Hash new files.</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><img src=":/images/feedback_arrow.png" /><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;"> Copy/Paste RetroShare links from your shares</span></p></body></html> - - - - - - - Add File to Attach - - - - :/images/add-share24.png:/images/add-share24.png - - - - - - - Add Channel Thumbnail - - - - :/images/add_image24.png:/images/add_image24.png - - - - - - - - - - 156 - 107 - - - - - 0 - 0 - - - - :/images/thumb-default-video.png - - - - - - - Qt::Horizontal - - - - 12 - 98 - - - - - - - - Message - - - - - - - - - 75 - true - - - - Subject : - - - - - - - - - - - - - - - - - - - - :/images/attachment.png:/images/attachment.png - - - Attachments - - - - - - - - - :/images/attachment.png - - - - - - - - 16777215 - 26 - - - - - 75 - true - - - - Attachments - - - - - - - Qt::Horizontal - - - - 334 - 26 - - - - - - - - - 0 - 0 - - - - - 34 - 34 - - - - - - - - :/images/add-share24.png:/images/add-share24.png - - - - 24 - 24 - - - - - - - - Allow channels to get frame for message thumbnail from movie media attachments or not - - - Auto Thumbnail - - - - - - - Qt::ScrollBarAlwaysOn - - - true - - - - - 0 - 0 - 98 - 24 - - - - - 0 - 0 - - - - - 3 - - - 3 - - - - - - 0 - 0 - - - - true - - - Drag and Drop Files from Search Results - - - - - - - - - - - - - - - - Qt::Horizontal - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - - - - - - HeaderFrame - QFrame -
gui/common/HeaderFrame.h
- 1 -
-
- - - - -
diff --git a/retroshare-gui/src/gui/channels/EditChanDetails.cpp b/retroshare-gui/src/gui/channels/EditChanDetails.cpp deleted file mode 100644 index f0cc39d78..000000000 --- a/retroshare-gui/src/gui/channels/EditChanDetails.cpp +++ /dev/null @@ -1,118 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2010 Christopher Evi-Parker - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ -#include "EditChanDetails.h" - -#include - -#include - -#include "util/misc.h" - -#include -#include -#include - -#define CHAN_DEFAULT_IMAGE ":/images/channels.png" - - -/** Default constructor */ -EditChanDetails::EditChanDetails(QWidget *parent, std::string cId) - : QDialog(parent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint), mChannelId(cId) -{ - /* Invoke Qt Designer generated QObject setup routine */ - ui.setupUi(this); - - connect(ui.buttonBox, SIGNAL(accepted()), this, SLOT(applyDialog())); - connect(ui.buttonBox, SIGNAL(rejected()), this, SLOT(close())); - - connect( ui.logoButton, SIGNAL(clicked() ), this , SLOT(addChannelLogo())); - - ui.logoButton->setDisabled(true); - ui.logoLabel->setDisabled(true); - - loadChannel(); -} - -void EditChanDetails::loadChannel() -{ - if (!rsChannels) - { - return; - } - - ChannelInfo ci; - rsChannels->getChannelInfo(mChannelId, ci); - - // Set Channel Name - ui.nameline->setText(QString::fromStdWString(ci.channelName)); - - // Set Channel Description - ui.DescriptiontextEdit->setText(QString::fromStdWString(ci.channelDesc)); - - // Set Channel Logo - QPixmap chanImage; - if(ci.pngImageLen != 0) - { - chanImage.loadFromData(ci.pngChanImage, ci.pngImageLen, "PNG"); - } - else - { - chanImage = QPixmap(CHAN_DEFAULT_IMAGE); - } - ui.logoLabel->setPixmap(chanImage); - -} - -void EditChanDetails::applyDialog() -{ - if(!rsChannels) - return; - - // if text boxes have not been edited leave alone - if(!ui.nameline->isModified() && !ui.DescriptiontextEdit->document()->isModified()) - return; - - ChannelInfo ci; - - ci.channelName = misc::removeNewLine(ui.nameline->text()).toStdWString(); - ci.channelDesc = ui.DescriptiontextEdit->document()->toPlainText().toStdWString(); - - /* reload now */ - rsChannels->channelEditInfo(mChannelId, ci); - - /* close the Dialog after the Changes applied */ - close(); - - return; -} - -void EditChanDetails::addChannelLogo() // the same function as in CreateChannel -{ - QPixmap img = misc::getOpenThumbnailedPicture(this, tr("Load channel logo"), 64, 64); - - if (img.isNull()) - return; - - picture = img; - - // to show the selected - ui.logoLabel->setPixmap(picture); -} diff --git a/retroshare-gui/src/gui/channels/EditChanDetails.h b/retroshare-gui/src/gui/channels/EditChanDetails.h deleted file mode 100644 index dc9cd0c4e..000000000 --- a/retroshare-gui/src/gui/channels/EditChanDetails.h +++ /dev/null @@ -1,55 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2010 Christopher Evi-Parker - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - -#ifndef _EDITCHANDETAILS_H -#define _EDITCHANDETAILS_H - -#include - -#include "ui_EditChanDetails.h" - -class EditChanDetails : public QDialog -{ - Q_OBJECT - -public: - /** Default constructor */ - EditChanDetails(QWidget *parent = 0, std::string cId = 0); - -signals: - void configChanged(); - -private slots: - void applyDialog(); - void addChannelLogo(); - -private: - void loadChannel(); - - std::string mChannelId; - QPixmap picture; - - /** Qt Designer generated object */ - Ui::EditChanDetails ui; -}; - -#endif - diff --git a/retroshare-gui/src/gui/channels/EditChanDetails.ui b/retroshare-gui/src/gui/channels/EditChanDetails.ui deleted file mode 100644 index 4035d284f..000000000 --- a/retroshare-gui/src/gui/channels/EditChanDetails.ui +++ /dev/null @@ -1,143 +0,0 @@ - - - EditChanDetails - - - - 0 - 0 - 436 - 355 - - - - Channel Details - - - - :/images/rstray3.png:/images/rstray3.png - - - - - - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - - - - 0 - - - - - :/images/info16.png:/images/info16.png - - - Edit Channel Details - - - - - - Channel Info - - - - - - Channel Name - - - - - - - - - - Channel Description - - - - - - - - - - - - - - - - - Qt::Horizontal - - - - 118 - 20 - - - - - - - - Add Channel Logo - - - - :/images/add_image24.png:/images/add_image24.png - - - - - - - - 64 - 64 - - - - - 64 - 64 - - - - QFrame::StyledPanel - - - QFrame::Raised - - - :/images/channels.png - - - true - - - - - - - - - - - - - - - - diff --git a/retroshare-gui/src/gui/channels/ShareKey.cpp b/retroshare-gui/src/gui/channels/ShareKey.cpp index 52adf91e5..390f4f193 100644 --- a/retroshare-gui/src/gui/channels/ShareKey.cpp +++ b/retroshare-gui/src/gui/channels/ShareKey.cpp @@ -24,8 +24,8 @@ #include #include -#include -#include +//#include +//#include #include #include "gui/common/PeerDefs.h" @@ -77,6 +77,7 @@ void ShareKey::shareKey() return; } +#if 0 if (mGrpType & CHANNEL_KEY_SHARE) { if (!rsChannels) return; @@ -97,6 +98,7 @@ void ShareKey::shareKey() // incorrect type return; } +#endif close(); } diff --git a/retroshare-gui/src/gui/common/StatusDefs.cpp b/retroshare-gui/src/gui/common/StatusDefs.cpp index 6050ad470..6cc4f771f 100644 --- a/retroshare-gui/src/gui/common/StatusDefs.cpp +++ b/retroshare-gui/src/gui/common/StatusDefs.cpp @@ -144,9 +144,6 @@ QString StatusDefs::connectStateString(RsPeerDetails &details) case 0: stateString = peerStateString(details.state); break; - case RS_PEER_CONNECTSTATE_TRYING_TUNNEL: - stateString = qApp->translate("StatusDefs", "Trying tunnel connection"); - break; case RS_PEER_CONNECTSTATE_TRYING_TCP: stateString = qApp->translate("StatusDefs", "Trying TCP"); break; @@ -159,9 +156,6 @@ QString StatusDefs::connectStateString(RsPeerDetails &details) case RS_PEER_CONNECTSTATE_CONNECTED_UDP: stateString = qApp->translate("StatusDefs", "Connected: UDP"); break; - case RS_PEER_CONNECTSTATE_CONNECTED_TUNNEL: - stateString = qApp->translate("StatusDefs", "Connected: Tunnel"); - break; case RS_PEER_CONNECTSTATE_CONNECTED_UNKNOWN: stateString = qApp->translate("StatusDefs", "Connected: Unknown"); break; diff --git a/retroshare-gui/src/gui/feeds/BlogMsgItem.cpp b/retroshare-gui/src/gui/feeds/BlogMsgItem.cpp deleted file mode 100644 index 24348735b..000000000 --- a/retroshare-gui/src/gui/feeds/BlogMsgItem.cpp +++ /dev/null @@ -1,189 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2008 Robert Fernie - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - -#include - -#include "BlogMsgItem.h" - -#include "FeedHolder.h" -#include "SubFileItem.h" - -/**** - * #define DEBUG_ITEM 1 - ****/ - -/** Constructor */ -BlogMsgItem::BlogMsgItem(FeedHolder *parent, uint32_t feedId, std::string peerId, std::string msgId, bool isHome) -:QWidget(NULL), mParent(parent), mFeedId(feedId), - mPeerId(peerId), mMsgId(msgId), mIsHome(isHome) -{ - /* Invoke the Qt Designer generated object setup routine */ - setupUi(this); - - setAttribute ( Qt::WA_DeleteOnClose, true ); - - /* general ones */ - connect( expandButton, SIGNAL( clicked( void ) ), this, SLOT( toggle ( void ) ) ); - connect( clearButton, SIGNAL( clicked( void ) ), this, SLOT( removeItem ( void ) ) ); - //connect( gotoButton, SIGNAL( clicked( void ) ), this, SLOT( gotoHome ( void ) ) ); - - /* specific ones */ - connect( playButton, SIGNAL( clicked( void ) ), this, SLOT( playMedia ( void ) ) ); - - small(); - updateItemStatic(); - updateItem(); -} - - -void BlogMsgItem::updateItemStatic() -{ - /* fill in */ -#ifdef DEBUG_ITEM - std::cerr << "BlogMsgItem::updateItemStatic()"; - std::cerr << std::endl; -#endif - - msgLabel->setText("What did you expect? \nThe Blogs will be up and running shortly!"); - titleLabel->setText("Blog Feed: Jacki @ Friday"); - subjectLabel->setText("Brand new exciting Blog stuff"); - - /* add Files */ - int total = (int) (10.0 * (rand() / (RAND_MAX + 1.0))); - int i; - - total = 0; - - for(i = 0; i < total; i++) - { - /* add file */ - SubFileItem *fi = new SubFileItem("dummyHash", "dummy_File", "", 1283918, SFI_STATE_REMOTE, mPeerId); - mFileItems.push_back(fi); - - QLayout *layout = expandFrame->layout(); - layout->addWidget(fi); - } - - playButton->setEnabled(false); - - if (mIsHome) - { - /* disable buttons */ - clearButton->setEnabled(false); - //gotoButton->setEnabled(false); - - clearButton->hide(); - } -} - - -void BlogMsgItem::updateItem() -{ - /* fill in */ -#ifdef DEBUG_ITEM - std::cerr << "BlogMsgItem::updateItem()"; - std::cerr << std::endl; -#endif - int msec_rate = 10000; - - /* Very slow Tick to check when all files are downloaded */ - std::list::iterator it; - for(it = mFileItems.begin(); it != mFileItems.end(); it++) - { - if (!(*it)->done()) - { - /* loop again */ - QTimer::singleShot( msec_rate, this, SLOT(updateItem( void ) )); - return; - } - } - if (mFileItems.size() > 0) - { - playButton->setEnabled(true); - } -} - - -void BlogMsgItem::small() -{ - expandFrame->hide(); -} - -void BlogMsgItem::toggle() -{ - mParent->lockLayout(this, true); - - if (expandFrame->isHidden()) - { - expandFrame->show(); - expandButton->setIcon(QIcon(QString(":/images/edit_remove24.png"))); - expandButton->setToolTip(tr("Hide")); - } - else - { - expandFrame->hide(); - expandButton->setIcon(QIcon(QString(":/images/edit_add24.png"))); - expandButton->setToolTip(tr("Expand")); - } - - mParent->lockLayout(this, false); -} - - -void BlogMsgItem::removeItem() -{ -#ifdef DEBUG_ITEM - std::cerr << "BlogMsgItem::removeItem()"; - std::cerr << std::endl; -#endif - - mParent->lockLayout(this, true); - hide(); - mParent->lockLayout(this, false); - - if (mParent) - { - mParent->deleteFeedItem(this, mFeedId); - } -} - - -void BlogMsgItem::gotoHome() -{ -#ifdef DEBUG_ITEM - std::cerr << "BlogMsgItem::gotoHome()"; - std::cerr << std::endl; -#endif -} - -/*********** SPECIFIC FUNCTIOSN ***********************/ - - -void BlogMsgItem::playMedia() -{ -#ifdef DEBUG_ITEM - std::cerr << "BlogMsgItem::playMedia()"; - std::cerr << std::endl; -#endif -} - - - diff --git a/retroshare-gui/src/gui/feeds/BlogMsgItem.h b/retroshare-gui/src/gui/feeds/BlogMsgItem.h deleted file mode 100644 index b89e21a59..000000000 --- a/retroshare-gui/src/gui/feeds/BlogMsgItem.h +++ /dev/null @@ -1,65 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2008 Robert Fernie - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - -#ifndef _BLOG_MSG_ITEM_DIALOG_H -#define _BLOG_MSG_ITEM_DIALOG_H - -#include "ui_BlogMsgItem.h" -#include - -class FeedHolder; -class SubFileItem; - -class BlogMsgItem : public QWidget, private Ui::BlogMsgItem -{ - Q_OBJECT - -public: - /** Default Constructor */ - BlogMsgItem(FeedHolder *parent, uint32_t feedId, const std::string &peerId, const std::string &msgId, bool isHome); - - void updateItemStatic(); - void small(); - -private slots: - /* default stuff */ - void gotoHome(); - void removeItem(); - void toggle(); - - void playMedia(); - - void updateItem(); - -private: - FeedHolder *mParent; - uint32_t mFeedId; - - std::string mPeerId; - std::string mMsgId; - - bool mIsHome; - - std::list mFileItems; -}; - -#endif - diff --git a/retroshare-gui/src/gui/feeds/BlogMsgItem.ui b/retroshare-gui/src/gui/feeds/BlogMsgItem.ui deleted file mode 100644 index 94c82ec8f..000000000 --- a/retroshare-gui/src/gui/feeds/BlogMsgItem.ui +++ /dev/null @@ -1,242 +0,0 @@ - - - BlogMsgItem - - - - 0 - 0 - 552 - 238 - - - - - - - - 0 - - - - - - 0 - 0 - - - - QFrame#frame{ -border: 2px solid #6ACEFF; -border-radius: 10px; -background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, -stop:0 #0076B1, stop:1 #12A3EB);} - - - QFrame::StyledPanel - - - QFrame::Raised - - - - 0 - - - 0 - - - - - 6 - - - - - - 0 - 0 - - - - Qt::NoFocus - - - Remove Item - - - - :/images/close_normal.png:/images/close_normal.png - - - - - - - Qt::Horizontal - - - QSizePolicy::Preferred - - - - 16 - 26 - - - - - - - - - 0 - 0 - - - - - 75 - true - true - - - - Blog - - - - - - - Qt::Horizontal - - - QSizePolicy::Preferred - - - - 1000 - 20 - - - - - - - - - 0 - 0 - - - - Qt::NoFocus - - - Expand - - - - :/images/edit_add24.png:/images/edit_add24.png - - - - - - - - - - - Subject - - - - - - - - 0 - 0 - - - - subjectLabel - - - - - - - Qt::Horizontal - - - QSizePolicy::Preferred - - - - 500 - 20 - - - - - - - - - 0 - 0 - - - - Qt::NoFocus - - - Play Media - - - - :/images/startall.png:/images/startall.png - - - - - - - - - QFrame::StyledPanel - - - QFrame::Raised - - - - - - - 0 - 0 - - - - Long - message here - - - - - - - - - - - - - - - - diff --git a/retroshare-gui/src/gui/feeds/BlogNewItem.cpp b/retroshare-gui/src/gui/feeds/BlogNewItem.cpp deleted file mode 100644 index 8a3f7674b..000000000 --- a/retroshare-gui/src/gui/feeds/BlogNewItem.cpp +++ /dev/null @@ -1,219 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2008 Robert Fernie - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - -#include "BlogNewItem.h" -#include "FeedHolder.h" - -#include - -#define BLOG_DEFAULT_IMAGE ":/images/hi64-app-kblogger.png" - - -/**** - * #define DEBUG_ITEM 1 - ****/ - -/** Constructor */ -BlogNewItem::BlogNewItem(FeedHolder *parent, uint32_t feedId, std::string blogId, bool isHome, bool isNew) -:QWidget(NULL), mParent(parent), mFeedId(feedId), - mBlogId(blogId), mIsHome(isHome), mIsNew(isNew) -{ - /* Invoke the Qt Designer generated object setup routine */ - setupUi(this); - - setAttribute ( Qt::WA_DeleteOnClose, true ); - - /* general ones */ - connect( expandButton, SIGNAL( clicked( void ) ), this, SLOT( toggle ( void ) ) ); - connect( clearButton, SIGNAL( clicked( void ) ), this, SLOT( removeItem ( void ) ) ); - - /* specific ones */ - connect( subscribeButton, SIGNAL( clicked( void ) ), this, SLOT( subscribeBlog ( void ) ) ); - - small(); - updateItemStatic(); - updateItem(); -} - - -void BlogNewItem::updateItemStatic() -{ - if (!rsBlogs) - return; - - - /* fill in */ -#ifdef DEBUG_ITEM - std::cerr << "BlogNewItem::updateItemStatic()"; - std::cerr << std::endl; -#endif - - BlogInfo bi; - if (rsBlogs->getBlogInfo(mBlogId, bi)) - { - nameLabel->setText(QString::fromStdWString(bi.blogName)); - - descLabel->setText(QString::fromStdWString(bi.blogDesc)); - - if(bi.pngImageLen != 0){ - - QPixmap blogImage; - blogImage.loadFromData(bi.pngChanImage, bi.pngImageLen, "PNG"); - logo_label->setPixmap(QPixmap(blogImage)); - }else{ - QPixmap defaulImage(BLOG_DEFAULT_IMAGE); - logo_label->setPixmap(QPixmap(defaulImage)); - } - - if (bi.blogFlags & RS_DISTRIB_SUBSCRIBED) - { - subscribeButton->setEnabled(false); - //postButton->setEnabled(true); - } - else - { - subscribeButton->setEnabled(true); - //postButton->setEnabled(false); - } - - - /* should also check the other flags */ - } - else - { - nameLabel->setText(tr("Unknown Blog")); - titleLabel->setText("Blog ???"); - descLabel->setText(""); - } - - if (mIsNew) - { - titleLabel->setText(tr("New Blog")); - } - else - { - titleLabel->setText(tr("Updated Blog")); - } - - if (mIsHome) - { - /* disable buttons */ - clearButton->setEnabled(false); - //gotoButton->setEnabled(false); - } -} - - -void BlogNewItem::updateItem() -{ - /* fill in */ -#ifdef DEBUG_ITEM - std::cerr << "BlogNewItem::updateItem()"; - std::cerr << std::endl; -#endif - -} - - -void BlogNewItem::small() -{ - expandFrame->hide(); -} - -void BlogNewItem::toggle() -{ - mParent->lockLayout(this, true); - - if (expandFrame->isHidden()) - { - expandFrame->show(); - expandButton->setIcon(QIcon(QString(":/images/edit_remove24.png"))); - expandButton->setToolTip(tr("Hide")); - } - else - { - expandFrame->hide(); - expandButton->setIcon(QIcon(QString(":/images/edit_add24.png"))); - expandButton->setToolTip(tr("Expand")); - } - - mParent->lockLayout(this, false); -} - - -void BlogNewItem::removeItem() -{ -#ifdef DEBUG_ITEM - std::cerr << "BlogNewItem::removeItem()"; - std::cerr << std::endl; -#endif - - mParent->lockLayout(this, true); - hide(); - mParent->lockLayout(this, false); - - if (mParent) - { - mParent->deleteFeedItem(this, mFeedId); - } -} - - -void BlogNewItem::gotoHome() -{ -#ifdef DEBUG_ITEM - std::cerr << "BlogNewItem::gotoHome()"; - std::cerr << std::endl; -#endif -} - -/*********** SPECIFIC FUNCTIOSN ***********************/ - - -void BlogNewItem::unsubscribeBlog() -{ -#ifdef DEBUG_ITEM - std::cerr << "BlogNewItem::unsubscribeBlog()"; - std::cerr << std::endl; -#endif - if (rsBlogs) - { - rsBlogs->blogSubscribe(mBlogId, false); - } - updateItemStatic(); -} - - -void BlogNewItem::subscribeBlog() -{ -#ifdef DEBUG_ITEM - std::cerr << "BlogNewItem::subscribeBlog()"; - std::cerr << std::endl; -#endif - if (rsBlogs) - { - rsBlogs->blogSubscribe(mBlogId, true); - } - updateItemStatic(); -} - - - diff --git a/retroshare-gui/src/gui/feeds/BlogNewItem.h b/retroshare-gui/src/gui/feeds/BlogNewItem.h deleted file mode 100644 index 93f7781da..000000000 --- a/retroshare-gui/src/gui/feeds/BlogNewItem.h +++ /dev/null @@ -1,62 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2008 Robert Fernie - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - -#ifndef _BLOG_NEW_ITEM_DIALOG_H -#define _BLOG_NEW_ITEM_DIALOG_H - -#include "ui_BlogNewItem.h" -#include - -class FeedHolder; - -class BlogNewItem : public QWidget, private Ui::BlogNewItem -{ - Q_OBJECT - -public: - /** Default Constructor */ - BlogNewItem(FeedHolder *parent, uint32_t feedId, const std::string &blogId, bool isHome, bool isNew); - - void updateItemStatic(); - void small(); - -private slots: - /* default stuff */ - void gotoHome(); - void removeItem(); - void toggle(); - - void unsubscribeBlog(); - void subscribeBlog(); - - void updateItem(); - -private: - FeedHolder *mParent; - uint32_t mFeedId; - - std::string mBlogId; - bool mIsHome; - bool mIsNew; -}; - -#endif - diff --git a/retroshare-gui/src/gui/feeds/BlogNewItem.ui b/retroshare-gui/src/gui/feeds/BlogNewItem.ui deleted file mode 100644 index 39c531f69..000000000 --- a/retroshare-gui/src/gui/feeds/BlogNewItem.ui +++ /dev/null @@ -1,260 +0,0 @@ - - - BlogNewItem - - - - 0 - 0 - 643 - 109 - - - - - 0 - - - - - - 0 - 0 - - - - QFrame#frame{ -border: 2px solid #6ACEFF; -border-radius: 10px; -background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, -stop:0 #0076B1, stop:1 #12A3EB);} - - - QFrame::StyledPanel - - - QFrame::Raised - - - - 6 - - - 6 - - - - - - - - 0 - 0 - - - - Qt::NoFocus - - - Remove Item - - - - :/images/close_normal.png:/images/close_normal.png - - - - - - - - 0 - 0 - - - - - 75 - true - true - - - - New Blog - - - - - - - Qt::Horizontal - - - QSizePolicy::Fixed - - - - 20 - 20 - - - - - - - - - 32 - 32 - - - - Logo - - - true - - - - - - - name - - - - - - - Qt::Horizontal - - - QSizePolicy::Expanding - - - - 500 - 20 - - - - - - - - - 0 - 0 - - - - Qt::NoFocus - - - Subscribe to Blog - - - - :/images/directoryadd_24x24_shadow.png:/images/directoryadd_24x24_shadow.png - - - - - - - Qt::Horizontal - - - QSizePolicy::Fixed - - - - 20 - 20 - - - - - - - - - 0 - 0 - - - - Qt::NoFocus - - - Expand - - - - :/images/edit_add24.png:/images/edit_add24.png - - - - - - - - - QFrame::StyledPanel - - - QFrame::Raised - - - - 0 - - - 0 - - - - - Blog Description - - - - - - - - - :/images/contacts24.png - - - - - - - - 0 - 0 - - - - Description - of Blog - - - - - - - - - - - - - - - - - - - diff --git a/retroshare-gui/src/gui/feeds/ChanMsgItem.cpp b/retroshare-gui/src/gui/feeds/ChanMsgItem.cpp deleted file mode 100644 index 51244a8d1..000000000 --- a/retroshare-gui/src/gui/feeds/ChanMsgItem.cpp +++ /dev/null @@ -1,466 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2008 Robert Fernie - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - -#include -#include -#include - -#include "rshare.h" -#include "ChanMsgItem.h" - -#include "FeedHolder.h" -#include "SubFileItem.h" -#include "gui/notifyqt.h" -#include "util/misc.h" -#include "gui/RetroShareLink.h" -#include "util/HandleRichText.h" -#include "util/DateTime.h" - -#include - -/**** - * #define DEBUG_ITEM 1 - ****/ - -#define COLOR_NORMAL QColor(248, 248, 248) -#define COLOR_NEW QColor(220, 236, 253) - -/** Constructor */ -ChanMsgItem::ChanMsgItem(FeedHolder *parent, uint32_t feedId, const std::string &chanId, const std::string &msgId, bool isHome) -:QWidget(NULL), mParent(parent), mFeedId(feedId), - mChanId(chanId), mMsgId(msgId), mIsHome(isHome) -{ - /* Invoke the Qt Designer generated object setup routine */ - setupUi(this); - - setAttribute ( Qt::WA_DeleteOnClose, true ); - - m_inUpdateItemStatic = false; - - /* general ones */ - connect( expandButton, SIGNAL( clicked( void ) ), this, SLOT( toggle ( void ) ) ); - connect( clearButton, SIGNAL( clicked( void ) ), this, SLOT( removeItem ( void ) ) ); - - /* specific */ - connect(readAndClearButton, SIGNAL(clicked()), this, SLOT(readAndClearItem())); - connect( unsubscribeButton, SIGNAL( clicked( void ) ), this, SLOT( unsubscribeChannel ( void ) ) ); - connect( downloadButton, SIGNAL( clicked( void ) ), this, SLOT( download ( void ) ) ); - connect( playButton, SIGNAL( clicked( void ) ), this, SLOT( play ( void ) ) ); - connect( copyLinkButton, SIGNAL( clicked( void ) ), this, SLOT( copyLink ( void ) ) ); - - connect( readButton, SIGNAL( toggled(bool) ), this, SLOT( readToggled(bool) ) ); - connect( NotifyQt::getInstance(), SIGNAL(channelMsgReadSatusChanged(QString,QString,int)), this, SLOT(channelMsgReadSatusChanged(QString,QString,int)), Qt::QueuedConnection); - - downloadButton->hide(); - playButton->hide(); - warn_image_label->hide(); - warning_label->hide(); - - titleLabel->setMinimumWidth(100); - subjectLabel->setMinimumWidth(100); - warning_label->setMinimumWidth(100); - - frame->setProperty("state", ""); - QPalette palette = frame->palette(); - palette.setColor(frame->backgroundRole(), COLOR_NORMAL); - frame->setPalette(palette); - - expandFrame->hide(); - updateItemStatic(); - updateItem(); -} - -void ChanMsgItem::updateItemStatic() -{ - /* fill in */ -#ifdef DEBUG_ITEM - std::cerr << "ChanMsgItem::updateItemStatic()"; - std::cerr << std::endl; -#endif - - ChannelMsgInfo cmi; - - if (!rsChannels) - return; - - if (!rsChannels->getChannelMessage(mChanId, mMsgId, cmi)) - return; - - m_inUpdateItemStatic = true; - - QString title; - - ChannelInfo ci; - rsChannels->getChannelInfo(mChanId, ci); - - if (!mIsHome) - { - title = tr("Channel Feed") + ": "; - RetroShareLink link; - link.createChannel(ci.channelId, ""); - title += link.toHtml(); - titleLabel->setText(title); - RetroShareLink msgLink; - msgLink.createChannel(cmi.channelId, cmi.msgId); - subjectLabel->setText(msgLink.toHtml()); - - if ((ci.channelFlags & RS_DISTRIB_SUBSCRIBED) || (ci.channelFlags & RS_DISTRIB_ADMIN)) { - unsubscribeButton->setEnabled(true); - } else { - unsubscribeButton->setEnabled(false); - } - readButton->hide(); - newLabel->hide(); - copyLinkButton->hide(); - } - else - { - /* subject */ - titleLabel->setText(QString::fromStdWString(cmi.subject)); - subjectLabel->setText(RsHtml().formatText(NULL, QString::fromStdWString(cmi.msg), RSHTML_FORMATTEXT_EMBED_SMILEYS | RSHTML_FORMATTEXT_EMBED_LINKS)); - - /* disable buttons: deletion facility not enabled with cache services yet */ - clearButton->setEnabled(false); - unsubscribeButton->setEnabled(false); - clearButton->hide(); - readAndClearButton->hide(); - unsubscribeButton->hide(); - copyLinkButton->show(); - - if ((ci.channelFlags & RS_DISTRIB_SUBSCRIBED) || (ci.channelFlags & RS_DISTRIB_ADMIN)) { - readButton->setVisible(true); - - uint32_t status = 0; - rsChannels->getMessageStatus(mChanId, mMsgId, status); - - if ((status & CHANNEL_MSG_STATUS_READ) == 0 || (status & CHANNEL_MSG_STATUS_UNREAD_BY_USER)) { - readButton->setChecked(true); - readButton->setIcon(QIcon(":/images/message-state-unread.png")); - } else { - readButton->setChecked(false); - readButton->setIcon(QIcon(":/images/message-state-read.png")); - } - - bool newState; - QColor color; - if (status & CHANNEL_MSG_STATUS_READ) { - newLabel->setVisible(false); - newState = false; - color = COLOR_NORMAL; - } else { - newLabel->setVisible(true); - newState = true; - color = COLOR_NEW; - } - - /* unpolish widget to clear the stylesheet's palette cache */ - frame->style()->unpolish(frame); - - QPalette palette = frame->palette(); - palette.setColor(frame->backgroundRole(), color); - frame->setPalette(palette); - - frame->setProperty("new", newState); - Rshare::refreshStyleSheet(frame, false); - } else { - readButton->setVisible(false); - newLabel->setVisible(false); - } - } - - msgLabel->setText(RsHtml().formatText(NULL, QString::fromStdWString(cmi.msg), RSHTML_FORMATTEXT_EMBED_SMILEYS | RSHTML_FORMATTEXT_EMBED_LINKS)); - msgFrame->setVisible(!cmi.msg.empty()); - - datetimelabel->setText(DateTime::formatLongDateTime(cmi.ts)); - - filelabel->setText(QString("(%1 %2) %3").arg(cmi.count).arg(tr("Files")).arg(misc::friendlyUnit(cmi.size))); - - if (mFileItems.empty() == false) { - std::list::iterator it; - for(it = mFileItems.begin(); it != mFileItems.end(); it++) - { - delete(*it); - } - mFileItems.clear(); - } - - std::list::iterator it; - for(it = cmi.files.begin(); it != cmi.files.end(); it++) - { - /* add file */ - SubFileItem *fi = new SubFileItem(it->hash, it->fname, it->path, it->size, - SFI_STATE_REMOTE | SFI_TYPE_CHANNEL, ""); - mFileItems.push_back(fi); - - /* check if the file is a media file */ - if (!misc::isPreviewable(QFileInfo(QString::fromUtf8(it->fname.c_str())).suffix())) - fi->mediatype(); - - - QLayout *layout = expandFrame->layout(); - layout->addWidget(fi); - } - - if(cmi.thumbnail.image_thumbnail != NULL) - { - QPixmap thumbnail; - thumbnail.loadFromData(cmi.thumbnail.image_thumbnail, cmi.thumbnail.im_thumbnail_size, "PNG"); - - logoLabel->setPixmap(thumbnail); - } - - m_inUpdateItemStatic = false; -} - -void ChanMsgItem::setFileCleanUpWarning(uint32_t time_left) -{ - int hours = (int)time_left/3600; - int minutes = (time_left - hours*3600)%60; - - warning_label->setText(tr("Warning! You have less than %1 hours and %2 minute before this file is deleted Consider saving it.").arg( - QString::number(hours)).arg(QString::number(minutes))); - - QFont warnFont = warning_label->font(); - warnFont.setBold(true); - warning_label->setFont(warnFont); - - warn_image_label->setVisible(true); - warning_label->setVisible(true); - return; - -} - -void ChanMsgItem::updateItem() -{ - /* fill in */ -#ifdef DEBUG_ITEM - std::cerr << "ChanMsgItem::updateItem()"; - std::cerr << std::endl; -#endif - int msec_rate = 10000; - - int downloadCount = 0; - int downloadStartable = 0; - int playCount = 0; - int playStartable = 0; - bool startable; - bool loopAgain = false; - - /* Very slow Tick to check when all files are downloaded */ - std::list::iterator it; - for(it = mFileItems.begin(); it != mFileItems.end(); it++) - { - SubFileItem *item = *it; - - if (item->isDownloadable(startable)) { - downloadCount++; - if (startable) { - downloadStartable++; - } - } - if (item->isPlayable(startable)) { - playCount++; - if (startable) { - playStartable++; - } - } - - if (!item->done()) - { - /* loop again */ - loopAgain = true; - } - } - - if (downloadCount) { - downloadButton->show(); - - if (downloadStartable) { - downloadButton->setEnabled(true); - } else { - downloadButton->setEnabled(false); - } - } else { - downloadButton->hide(); - } - if (playCount) { - /* one file is playable */ - playButton->show(); - - if (playStartable == 1) { - playButton->setEnabled(true); - } else { - playButton->setEnabled(false); - } - } else { - playButton->hide(); - } - - if (loopAgain) { - QTimer::singleShot( msec_rate, this, SLOT(updateItem( void ) )); - } -} - -void ChanMsgItem::toggle() -{ - mParent->lockLayout(this, true); - - if (expandFrame->isHidden()) - { - expandFrame->show(); - expandButton->setIcon(QIcon(QString(":/images/edit_remove24.png"))); - expandButton->setToolTip(tr("Hide")); - - readToggled(false); - } - else - { - expandFrame->hide(); - expandButton->setIcon(QIcon(QString(":/images/edit_add24.png"))); - expandButton->setToolTip(tr("Expand")); - } - - mParent->lockLayout(this, false); -} - -void ChanMsgItem::removeItem() -{ -#ifdef DEBUG_ITEM - std::cerr << "ChanMsgItem::removeItem()"; - std::cerr << std::endl; -#endif - - mParent->lockLayout(this, true); - hide(); - mParent->lockLayout(this, false); - - if (mParent) - { - mParent->deleteFeedItem(this, mFeedId); - } -} - -/*********** SPECIFIC FUNCTIONS ***********************/ - -void ChanMsgItem::readAndClearItem() -{ -#ifdef DEBUG_ITEM - std::cerr << "ChanMsgItem::readAndClearItem()"; - std::cerr << std::endl; -#endif - - readToggled(false); - removeItem(); -} - -void ChanMsgItem::unsubscribeChannel() -{ -#ifdef DEBUG_ITEM - std::cerr << "ChanMsgItem::unsubscribeChannel()"; - std::cerr << std::endl; -#endif - - if (rsChannels) - { - rsChannels->channelSubscribe(mChanId, false, false); - } - updateItemStatic(); -} - -void ChanMsgItem::download() -{ - readToggled(false); - - std::list::iterator it; - for(it = mFileItems.begin(); it != mFileItems.end(); it++) - { - (*it)->download(); - } - - updateItem(); -} - -void ChanMsgItem::play() -{ - std::list::iterator it; - for(it = mFileItems.begin(); it != mFileItems.end(); it++) - { - bool startable; - if ((*it)->isPlayable(startable) && startable) { - (*it)->play(); - } - } -} - -void ChanMsgItem::readToggled(bool checked) -{ - if (m_inUpdateItemStatic) { - return; - } - - /* set always as read ... */ - uint32_t statusNew = CHANNEL_MSG_STATUS_READ; - if (checked) { - /* ... and as unread by user */ - statusNew |= CHANNEL_MSG_STATUS_UNREAD_BY_USER; - } else { - /* ... and as read by user */ - statusNew &= ~CHANNEL_MSG_STATUS_UNREAD_BY_USER; - } - - if (!mIsHome) { - disconnect( NotifyQt::getInstance(), SIGNAL(channelMsgReadSatusChanged(QString,QString,int)), this, SLOT(channelMsgReadSatusChanged(QString,QString,int))); - } - rsChannels->setMessageStatus(mChanId, mMsgId, statusNew, CHANNEL_MSG_STATUS_READ | CHANNEL_MSG_STATUS_UNREAD_BY_USER); - if (!mIsHome) { - connect( NotifyQt::getInstance(), SIGNAL(channelMsgReadSatusChanged(QString,QString,int)), this, SLOT(channelMsgReadSatusChanged(QString,QString,int)), Qt::QueuedConnection); - } -} - -void ChanMsgItem::channelMsgReadSatusChanged(const QString& channelId, const QString& msgId, int status) -{ - if (channelId.toStdString() == mChanId && msgId.toStdString() == mMsgId) { - if (!mIsHome) { - if (status & CHANNEL_MSG_STATUS_READ) { - close(); - return; - } - } - updateItemStatic(); - } -} - -void ChanMsgItem::copyLink() -{ - if (mChanId.empty() || mMsgId.empty()) { - return; - } - - ChannelMsgInfo cmi; - if (rsChannels->getChannelMessage(mChanId, mMsgId, cmi)) { - RetroShareLink link; - if (link.createChannel(cmi.channelId, cmi.msgId)) { - QList urls; - urls.push_back(link); - RSLinkClipboard::copyLinks(urls); - } - } -} diff --git a/retroshare-gui/src/gui/feeds/ChanMsgItem.h b/retroshare-gui/src/gui/feeds/ChanMsgItem.h deleted file mode 100644 index aad77f49a..000000000 --- a/retroshare-gui/src/gui/feeds/ChanMsgItem.h +++ /dev/null @@ -1,74 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2008 Robert Fernie - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - -#ifndef _CHAN_MSG_ITEM_DIALOG_H -#define _CHAN_MSG_ITEM_DIALOG_H - -#include "ui_ChanMsgItem.h" -#include - -class FeedHolder; -class SubFileItem; - -class ChanMsgItem : public QWidget, private Ui::ChanMsgItem -{ - Q_OBJECT - -public: - /** Default Constructor */ - ChanMsgItem(FeedHolder *parent, uint32_t feedId, const std::string &chanId, const std::string &msgId, bool isHome); - - void updateItemStatic(); - void setFileCleanUpWarning(uint32_t time_left); - - const std::string &msgId() { return mMsgId; } - -private slots: - /* default stuff */ - void removeItem(); - void toggle(); - - void readAndClearItem(); - void unsubscribeChannel(); - void download(); - void play(); - void copyLink(); - - void readToggled(bool checked); - void channelMsgReadSatusChanged(const QString& channelId, const QString& msgId, int status); - - void updateItem(); - -private: - FeedHolder *mParent; - uint32_t mFeedId; - - std::string mChanId; - std::string mMsgId; - - bool mIsHome; - bool m_inUpdateItemStatic; - - std::list mFileItems; -}; - -#endif - diff --git a/retroshare-gui/src/gui/feeds/ChanMsgItem.ui b/retroshare-gui/src/gui/feeds/ChanMsgItem.ui deleted file mode 100644 index 795c5fa0a..000000000 --- a/retroshare-gui/src/gui/feeds/ChanMsgItem.ui +++ /dev/null @@ -1,481 +0,0 @@ - - - ChanMsgItem - - - - 0 - 0 - 629 - 172 - - - - - 6 - - - 1 - - - 1 - - - - - - 0 - 0 - - - - true - - - QFrame::Box - - - QFrame::Sunken - - - - - - - - - 156 - 107 - - - - - - - :/images/thumb-default-video.png - - - true - - - - - - - - - - - - 0 - 0 - - - - - 11 - 75 - true - true - PreferAntialias - - - - <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> -<html><head><meta name="qrichtext" content="1" /><style type="text/css"> -p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:11pt; font-weight:600; font-style:italic;"> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-style:normal; color:#656565;">Channel Subject</span></p></body></html> - - - false - - - true - - - - - - - - 75 - true - PreferAntialias - - - - <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> -<html><head><meta name="qrichtext" content="1" /><style type="text/css"> -p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:600; font-style:normal;"> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt; color:#666666;">DateTime</span></p></body></html> - - - - - - - - - - - - 0 - 0 - - - - - 16777215 - 60 - - - - <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> -<html><head><meta name="qrichtext" content="1" /><style type="text/css"> -p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt; color:#666666;">Short Description</span></p></body></html> - - - true - - - true - - - - - - - - PreferAntialias - - - - fileLabel - - - Qt::AlignRight|Qt::AlignTop|Qt::AlignTrailing - - - - - - - - - - - - 24 - 16777215 - - - - - - - :/images/status_unknown.png - - - - - - - TextLabel - - - - - - - - - 8 - - - - - - 24 - 16777215 - - - - Qt::NoFocus - - - Toggle Message Read Status - - - - :/images/message-state-unread.png:/images/message-state-unread.png - - - true - - - false - - - false - - - - - - - - 16777215 - 21 - - - - New - - - - - - - - - - Qt::NoFocus - - - Download - - - - :/images/download16.png:/images/download16.png - - - - - - - - - - Qt::NoFocus - - - Play - - - - :/images/player_play.png:/images/player_play.png - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 0 - 0 - - - - - 24 - 16777215 - - - - Qt::NoFocus - - - Copy RetroShare Link - - - - :/images/copyrslink.png:/images/copyrslink.png - - - - - - - - 0 - 0 - - - - - 24 - 16777215 - - - - Qt::NoFocus - - - Unsubscribe From Channel - - - - :/images/mail_delete.png:/images/mail_delete.png - - - - - - - - 0 - 0 - - - - - 24 - 16777215 - - - - Qt::NoFocus - - - Expand - - - - :/images/edit_add24.png:/images/edit_add24.png - - - - - - - - 0 - 0 - - - - - 24 - 16777215 - - - - Qt::NoFocus - - - Set as read and remove item - - - - :/images/cancel.png:/images/cancel.png - - - - - - - - 0 - 0 - - - - - 24 - 16777215 - - - - Qt::NoFocus - - - Remove Item - - - - :/images/close_normal.png:/images/close_normal.png - - - - - - - - - - - - - - 0 - - - - - QFrame::Box - - - QFrame::Sunken - - - - 5 - - - - - - 0 - 0 - - - - true - - - 6 - - - -1 - - - true - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse - - - - - - - - - - - - - - - - - - - diff --git a/retroshare-gui/src/gui/feeds/ChanNewItem.cpp b/retroshare-gui/src/gui/feeds/ChanNewItem.cpp deleted file mode 100644 index bc5dad292..000000000 --- a/retroshare-gui/src/gui/feeds/ChanNewItem.cpp +++ /dev/null @@ -1,205 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2008 Robert Fernie - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - -#include "ChanNewItem.h" -#include "FeedHolder.h" -#include "gui/RetroShareLink.h" - -#include - -#define CHAN_DEFAULT_IMAGE ":/images/channels.png" - -/**** - * #define DEBUG_ITEM 1 - ****/ - -/** Constructor */ -ChanNewItem::ChanNewItem(FeedHolder *parent, uint32_t feedId, const std::string &chanId, bool isHome, bool isNew) -:QWidget(NULL), mParent(parent), mFeedId(feedId), - mChanId(chanId), mIsHome(isHome), mIsNew(isNew) -{ - /* Invoke the Qt Designer generated object setup routine */ - setupUi(this); - - setAttribute ( Qt::WA_DeleteOnClose, true ); - - /* general ones */ - connect( expandButton, SIGNAL( clicked( void ) ), this, SLOT( toggle ( void ) ) ); - connect( clearButton, SIGNAL( clicked( void ) ), this, SLOT( removeItem ( void ) ) ); - - /* specific ones */ - connect( subscribeButton, SIGNAL( clicked( void ) ), this, SLOT( subscribeChannel ( void ) ) ); - - expandFrame->hide(); - updateItemStatic(); - updateItem(); -} - - -void ChanNewItem::updateItemStatic() -{ - if (!rsChannels) - return; - - - /* fill in */ -#ifdef DEBUG_ITEM - std::cerr << "ChanNewItem::updateItemStatic()"; - std::cerr << std::endl; -#endif - - ChannelInfo ci; - if (rsChannels->getChannelInfo(mChanId, ci)) - { - RetroShareLink link; - link.createChannel(ci.channelId, ""); - nameLabel->setText(link.toHtml()); - - descLabel->setText(QString::fromStdWString(ci.channelDesc)); - - if(ci.pngImageLen != 0){ - QPixmap chanImage; - chanImage.loadFromData(ci.pngChanImage, ci.pngImageLen, "PNG"); - logoLabel->setPixmap(QPixmap(chanImage)); - } else { - QPixmap defaulImage(CHAN_DEFAULT_IMAGE); - logoLabel->setPixmap(QPixmap(defaulImage)); - } - - if (ci.channelFlags & RS_DISTRIB_SUBSCRIBED) - { - subscribeButton->setEnabled(false); - //postButton->setEnabled(true); - } - else - { - subscribeButton->setEnabled(true); - //postButton->setEnabled(false); - } - - - /* should also check the other flags */ - } - else - { - nameLabel->setText(tr("Unknown Channel")); - titleLabel->setText("Channel ???"); - descLabel->setText(""); - } - - if (mIsNew) - { - titleLabel->setText(tr("New Channel")); - } - else - { - titleLabel->setText(tr("Updated Channel")); - } - - if (mIsHome) - { - /* disable buttons */ - clearButton->setEnabled(false); - } -} - - -void ChanNewItem::updateItem() -{ - /* fill in */ -#ifdef DEBUG_ITEM - std::cerr << "ChanNewItem::updateItem()"; - std::cerr << std::endl; -#endif - -} - -void ChanNewItem::toggle() -{ - mParent->lockLayout(this, true); - - if (expandFrame->isHidden()) - { - expandFrame->show(); - expandButton->setIcon(QIcon(QString(":/images/edit_remove24.png"))); - expandButton->setToolTip(tr("Hide")); - } - else - { - expandFrame->hide(); - expandButton->setIcon(QIcon(QString(":/images/edit_add24.png"))); - expandButton->setToolTip(tr("Expand")); - } - - mParent->lockLayout(this, false); -} - - -void ChanNewItem::removeItem() -{ -#ifdef DEBUG_ITEM - std::cerr << "ChanNewItem::removeItem()"; - std::cerr << std::endl; -#endif - - mParent->lockLayout(this, true); - hide(); - mParent->lockLayout(this, false); - - if (mParent) - { - mParent->deleteFeedItem(this, mFeedId); - } -} - - -/*********** SPECIFIC FUNCTIOSN ***********************/ - - -void ChanNewItem::unsubscribeChannel() -{ -#ifdef DEBUG_ITEM - std::cerr << "ChanNewItem::unsubscribeChannel()"; - std::cerr << std::endl; -#endif - if (rsChannels) - { - rsChannels->channelSubscribe(mChanId, false, false); - } - updateItemStatic(); -} - - -void ChanNewItem::subscribeChannel() -{ -#ifdef DEBUG_ITEM - std::cerr << "ChanNewItem::subscribeChannel()"; - std::cerr << std::endl; -#endif - if (rsChannels) - { - rsChannels->channelSubscribe(mChanId, true, true); - } - updateItemStatic(); -} - - - diff --git a/retroshare-gui/src/gui/feeds/ChanNewItem.h b/retroshare-gui/src/gui/feeds/ChanNewItem.h deleted file mode 100644 index cda5b1088..000000000 --- a/retroshare-gui/src/gui/feeds/ChanNewItem.h +++ /dev/null @@ -1,60 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2008 Robert Fernie - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - -#ifndef _CHANNEL_NEW_ITEM_DIALOG_H -#define _CHANNEL_NEW_ITEM_DIALOG_H - -#include "ui_ChanNewItem.h" -#include - -class FeedHolder; - -class ChanNewItem : public QWidget, private Ui::ChanNewItem -{ - Q_OBJECT - -public: - /** Default Constructor */ - ChanNewItem(FeedHolder *parent, uint32_t feedId, const std::string &chanId, bool isHome, bool isNew); - - void updateItemStatic(); - -private slots: - /* default stuff */ - void removeItem(); - void toggle(); - - void unsubscribeChannel(); - void subscribeChannel(); - - void updateItem(); - -private: - FeedHolder *mParent; - uint32_t mFeedId; - - std::string mChanId; - bool mIsHome; - bool mIsNew; -}; - -#endif - diff --git a/retroshare-gui/src/gui/feeds/ChanNewItem.ui b/retroshare-gui/src/gui/feeds/ChanNewItem.ui deleted file mode 100644 index 4f8379de9..000000000 --- a/retroshare-gui/src/gui/feeds/ChanNewItem.ui +++ /dev/null @@ -1,284 +0,0 @@ - - - ChanNewItem - - - - 0 - 0 - 643 - 155 - - - - - 0 - - - - - - 0 - 0 - - - - - - - - - 248 - 248 - 248 - - - - - - - - - 248 - 248 - 248 - - - - - - - - - 248 - 248 - 248 - - - - - - - - true - - - QFrame::Box - - - QFrame::Sunken - - - - - - - - - 64 - 64 - - - - - 64 - 64 - - - - true - - - - - - - name - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop - - - true - - - - - - - - 0 - 0 - - - - - 75 - true - true - - - - New Channel - - - - - - - - - - - Qt::Horizontal - - - QSizePolicy::Expanding - - - - 338 - 28 - - - - - - - - - 0 - 0 - - - - Qt::NoFocus - - - Subscribe to Channel - - - - :/images/directoryadd_24x24_shadow.png:/images/directoryadd_24x24_shadow.png - - - - - - - - 0 - 0 - - - - Qt::NoFocus - - - Expand - - - - :/images/edit_add24.png:/images/edit_add24.png - - - - - - - - 0 - 0 - - - - Qt::NoFocus - - - Remove Item - - - - :/images/close_normal.png:/images/close_normal.png - - - - - - - - - Qt::Horizontal - - - - 455 - 20 - - - - - - - - - 0 - - - 0 - - - - - Channel Description - - - - - - - - - :/images/contacts24.png - - - - - - - - 0 - 0 - - - - Description - of Channel - - - true - - - true - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse - - - - - - - - - - - - - - - - - - - diff --git a/retroshare-gui/src/gui/feeds/ForumMsgItem.cpp b/retroshare-gui/src/gui/feeds/ForumMsgItem.cpp deleted file mode 100644 index 2a4fadde6..000000000 --- a/retroshare-gui/src/gui/feeds/ForumMsgItem.cpp +++ /dev/null @@ -1,436 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2008 Robert Fernie - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - -#include -#include - -#include "ForumMsgItem.h" -#include "FeedHolder.h" -#include "gui/RetroShareLink.h" - -#include -#include -#include - -#include "gui/forums/CreateForumMsg.h" -#include "util/HandleRichText.h" -#include "util/DateTime.h" -#include "gui/common/AvatarDefs.h" -#include "gui/notifyqt.h" -#include "gui/ForumsDialog.h" -//#include "gui/settings/rsharesettings.h" - -/**** - * #define DEBUG_ITEM 1 - ****/ - -/** Constructor */ -ForumMsgItem::ForumMsgItem(FeedHolder *parent, uint32_t feedId, const std::string &forumId, const std::string &postId, bool isHome) -:QWidget(NULL), mParent(parent), mFeedId(feedId), mForumId(forumId), mPostId(postId), mIsHome(isHome), mIsTop(false) -{ - /* Invoke the Qt Designer generated object setup routine */ - setupUi(this); - - setAttribute ( Qt::WA_DeleteOnClose, true ); - - /* general ones */ - connect( expandButton, SIGNAL( clicked( void ) ), this, SLOT( toggle ( void ) ) ); - connect( clearButton, SIGNAL( clicked( void ) ), this, SLOT( removeItem ( void ) ) ); - - /* specific ones */ - connect(readAndClearButton, SIGNAL(clicked()), this, SLOT(readAndClearItem())); - connect( unsubscribeButton, SIGNAL( clicked( void ) ), this, SLOT( unsubscribeForum ( void ) ) ); - connect( replyButton, SIGNAL( clicked( void ) ), this, SLOT( replyToPost ( void ) ) ); - connect( sendButton, SIGNAL( clicked( ) ), this, SLOT( sendMsg() ) ); - - connect(NotifyQt::getInstance(), SIGNAL(forumMsgReadSatusChanged(QString,QString,int)), this, SLOT(forumMsgReadSatusChanged(QString,QString,int)), Qt::QueuedConnection); - - subjectLabel->setMinimumWidth(20); - - nextFrame->hide(); - prevFrame->hide(); - - updateItemStatic(); - updateItem(); - textEdit->hide(); - sendButton->hide(); - signedcheckBox->hide(); -} - -void ForumMsgItem::updateItemStatic() -{ - if (!rsForums) - return; - - /* fill in */ -#ifdef DEBUG_ITEM - std::cerr << "ForumMsgItem::updateItemStatic()"; - std::cerr << std::endl; -#endif - - canReply = false; - - ForumInfo fi; - if (rsForums->getForumInfo(mForumId, fi)) - { - RetroShareLink link; - link.createForum(fi.forumId, ""); - QString title = tr("Forum Post") + ": "; - title += link.toHtml(); - - titleLabel->setText(title); - if (fi.subscribeFlags & (RS_DISTRIB_ADMIN | RS_DISTRIB_SUBSCRIBED)) - { - unsubscribeButton->setEnabled(true); - replyButton->setEnabled(true); - - if (fi.forumFlags & RS_DISTRIB_AUTHEN_REQ) - { - signedcheckBox->setChecked(true); - signedcheckBox->setEnabled(false); - } - - canReply = true; - } - else - { - unsubscribeButton->setEnabled(false); - replyButton->setEnabled(false); - } - } - else - { - titleLabel->setText(tr("Unknown Forum Post")); - } - - /* get actual Message */ - ForumMsgInfo msg; - if (rsForums->getForumMessage(mForumId, mPostId, msg)) - { -#ifdef DEBUG_ITEM - std::cerr << "Ids: MsgId: " << msg.msgId; - std::cerr << std::endl; - std::cerr << "Ids: ParentId: " << msg.parentId; - std::cerr << std::endl; - std::cerr << "Ids: ThreadId: " << msg.threadId; - std::cerr << std::endl; -#endif - - /* decide if top or not */ - if ((msg.msgId == msg.threadId) || (msg.threadId == "")) - { - mIsTop = true; - } - - RetroShareLink link; - link.createForum(msg.forumId, msg.msgId); - - if (mIsTop) - { - avatar->setId(msg.srcId, true); - - if (rsPeers->getPeerName(msg.srcId) !="") - { - RetroShareLink linkMessage; - linkMessage.createMessage(msg.srcId, ""); - nameLabel->setText(linkMessage.toHtml()); - } - else - { - nameLabel->setText(tr("Anonymous")); - } - - prevSubLabel->setText(link.toHtml()); - prevMsgLabel->setText(RsHtml().formatText(NULL, ForumsDialog::messageFromInfo(msg), RSHTML_FORMATTEXT_EMBED_SMILEYS | RSHTML_FORMATTEXT_EMBED_LINKS)); - - timestamplabel->setText(DateTime::formatLongDateTime(msg.ts)); - - nextFrame->hide(); - } - else - { - nextAvatar->setId(msg.srcId, true); - - if (rsPeers->getPeerName(msg.srcId) !="") - { - RetroShareLink linkMessage; - linkMessage.createMessage(msg.srcId, ""); - nextNameLabel->setText(linkMessage.toHtml()); - } - else - { - nextNameLabel->setText(tr("Anonymous")); - } - - nextSubLabel->setText(link.toHtml()); - nextMsgLabel->setText(RsHtml().formatText(NULL, ForumsDialog::messageFromInfo(msg), RSHTML_FORMATTEXT_EMBED_SMILEYS | RSHTML_FORMATTEXT_EMBED_LINKS)); - - timestamplabel->setText(DateTime::formatLongDateTime(msg.ts)); - - prevSHLabel->setText(tr("In Reply to") + ": "); - - ForumMsgInfo msgParent; - if (rsForums->getForumMessage(mForumId, msg.parentId, msgParent)) - { - avatar->setId(msgParent.srcId, true); - - RetroShareLink linkParent; - linkParent.createForum(msgParent.forumId, msgParent.msgId); - prevSubLabel->setText(linkParent.toHtml()); - prevMsgLabel->setText(RsHtml().formatText(NULL, ForumsDialog::messageFromInfo(msgParent), RSHTML_FORMATTEXT_EMBED_SMILEYS | RSHTML_FORMATTEXT_EMBED_LINKS)); - - if (rsPeers->getPeerName(msgParent.srcId) !="") - { - RetroShareLink linkMessage; - linkMessage.createMessage(msgParent.srcId, ""); - nameLabel->setText(linkMessage.toHtml()); - } - else - { - nameLabel->setText(tr("Anonymous")); - } - } - else - { - prevSubLabel->setText("???"); - prevMsgLabel->setText("???"); - } - } - - /* header stuff */ - subjectLabel->setText(link.toHtml()); - //srcLabel->setText(QString::fromStdString(msg.srcId)); - } - - if (mIsHome) - { - /* disable buttons */ - clearButton->setEnabled(false); - //gotoButton->setEnabled(false); - - clearButton->hide(); - } - - unsubscribeButton->hide(); -} - -void ForumMsgItem::updateItem() -{ - /* fill in */ -#ifdef DEBUG_ITEM - std::cerr << "ForumMsgItem::updateItem()"; - std::cerr << std::endl; -#endif -} - -void ForumMsgItem::toggle() -{ - mParent->lockLayout(this, true); - - if (prevFrame->isHidden()) - { - prevFrame->show(); - textEdit->setVisible(canReply); - sendButton->setVisible(canReply); - signedcheckBox->setVisible(canReply); - expandButton->setIcon(QIcon(QString(":/images/edit_remove24.png"))); - expandButton->setToolTip(tr("Hide")); - if (!mIsTop) - { - nextFrame->show(); - } - - setAsRead(); - } - else - { - prevFrame->hide(); - nextFrame->hide(); - textEdit->hide(); - sendButton->hide(); - signedcheckBox->hide(); - expandButton->setIcon(QIcon(QString(":/images/edit_add24.png"))); - expandButton->setToolTip(tr("Expand")); - } - - mParent->lockLayout(this, false); -} - -void ForumMsgItem::removeItem() -{ -#ifdef DEBUG_ITEM - std::cerr << "ForumMsgItem::removeItem()"; - std::cerr << std::endl; -#endif - - mParent->lockLayout(this, true); - hide(); - mParent->lockLayout(this, false); - - if (mParent) - { - mParent->deleteFeedItem(this, mFeedId); - } -} - -/*********** SPECIFIC FUNCTIOSN ***********************/ - -void ForumMsgItem::readAndClearItem() -{ -#ifdef DEBUG_ITEM - std::cerr << "ForumMsgItem::readAndClearItem()"; - std::cerr << std::endl; -#endif - - setAsRead(); - removeItem(); -} - -void ForumMsgItem::unsubscribeForum() -{ -#ifdef DEBUG_ITEM - std::cerr << "ForumMsgItem::unsubscribeForum()"; - std::cerr << std::endl; -#endif - if (rsForums) - { - rsForums->forumSubscribe(mForumId, false); - } - updateItemStatic(); -} - -void ForumMsgItem::subscribeForum() -{ -#ifdef DEBUG_ITEM - std::cerr << "ForumMsgItem::subscribeForum()"; - std::cerr << std::endl; -#endif - if (rsForums) - { - rsForums->forumSubscribe(mForumId, true); - } - updateItemStatic(); -} - -void ForumMsgItem::replyToPost() -{ - if (canReply == false) { - return; - } - -#ifdef DEBUG_ITEM - std::cerr << "ForumMsgItem::replyToPost()"; - std::cerr << std::endl; -#endif - if (mParent) - { - CreateForumMsg *cfm = new CreateForumMsg(mForumId, mPostId); - cfm->show(); - } -} - -void ForumMsgItem::sendMsg() -{ - if (canReply == false) { - return; - } - - if(textEdit->toPlainText().isEmpty()) - { /* error message */ - QMessageBox::warning(this, "RetroShare",tr("Please give a Text Message"), - QMessageBox::Ok, QMessageBox::Ok); - - return; //Don't add a empty Message!! - } - - ForumMsgInfo msg; - - /* get message */ - if (rsForums->getForumMessage(mForumId, mPostId, msg)) { - ForumMsgInfo msgInfo; - - msgInfo.forumId = mForumId; - msgInfo.threadId = ""; - msgInfo.parentId = mPostId; - msgInfo.msgId = ""; - - /* modify title */ - QString text = QString::fromStdWString(msg.title); - if (text.startsWith("Re:", Qt::CaseInsensitive)) { - msgInfo.title = msg.title; - } else { - msgInfo.title = L"Re: " + msg.title; - } - - QString desc; - RsHtml::optimizeHtml(textEdit, desc); - - msgInfo.msg = desc.toStdWString(); - msgInfo.msgflags = 0; - - if (signedcheckBox->isChecked()) - { - msgInfo.msgflags = RS_DISTRIB_AUTHEN_REQ; - } - - if ((msgInfo.msg == L"") && (msgInfo.title == L"")) - return; /* do nothing */ - - if (rsForums->ForumMessageSend(msgInfo) == true) { - textEdit->clear(); - } - } -} - -void ForumMsgItem::forumMsgReadSatusChanged(const QString &forumId, const QString &msgId, int status) -{ - if (mForumId == forumId.toStdString() && mPostId == msgId.toStdString()) { - if (status & FORUM_MSG_STATUS_READ) { - close(); - } - } -} - -void ForumMsgItem::setAsRead() -{ - if (canReply) { - uint32_t status; - rsForums->getMessageStatus(mForumId, mPostId, status); - - /* set always to read ... */ - uint32_t statusNew = status | FORUM_MSG_STATUS_READ; - -// bool setToReadOnActive = Settings->getForumMsgSetToReadOnActivate(); -// if (setToReadOnActive) { - /* ... and to read by user */ - statusNew &= ~FORUM_MSG_STATUS_UNREAD_BY_USER; -// } else { -// /* ... and to unread by user */ -// statusNew |= FORUM_MSG_STATUS_UNREAD_BY_USER; -// } - - if (status != statusNew) { - disconnect(NotifyQt::getInstance(), SIGNAL(forumMsgReadSatusChanged(QString,QString,int)), this, SLOT(forumMsgReadSatusChanged(QString,QString,int))); - rsForums->setMessageStatus(mForumId, mPostId, statusNew, FORUM_MSG_STATUS_READ | FORUM_MSG_STATUS_UNREAD_BY_USER); - connect(NotifyQt::getInstance(), SIGNAL(forumMsgReadSatusChanged(QString,QString,int)), this, SLOT(forumMsgReadSatusChanged(QString,QString,int)), Qt::QueuedConnection); - } - } -} diff --git a/retroshare-gui/src/gui/feeds/ForumMsgItem.h b/retroshare-gui/src/gui/feeds/ForumMsgItem.h deleted file mode 100644 index 74acfa5d9..000000000 --- a/retroshare-gui/src/gui/feeds/ForumMsgItem.h +++ /dev/null @@ -1,69 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2008 Robert Fernie - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - -#ifndef _FORUM_MSG_ITEM_DIALOG_H -#define _FORUM_MSG_ITEM_DIALOG_H - -#include "ui_ForumMsgItem.h" - -class FeedHolder; - -#include -class ForumMsgItem : public QWidget, private Ui::ForumMsgItem -{ - Q_OBJECT - -public: - /** Default Constructor */ - ForumMsgItem(FeedHolder *parent, uint32_t feedId, const std::string &forumId, const std::string &postId, bool isHome); - - void updateItemStatic(); - -private slots: - /* default stuff */ - void removeItem(); - void toggle(); - - void readAndClearItem(); - void unsubscribeForum(); - void subscribeForum(); - void replyToPost(); - void sendMsg(); - - void forumMsgReadSatusChanged(const QString &forumId, const QString &msgId, int status); - - void updateItem(); - -private: - void setAsRead(); - - FeedHolder *mParent; - uint32_t mFeedId; - bool canReply; - - std::string mForumId; - std::string mPostId; - bool mIsHome; - bool mIsTop; -}; - -#endif - diff --git a/retroshare-gui/src/gui/feeds/ForumMsgItem.ui b/retroshare-gui/src/gui/feeds/ForumMsgItem.ui deleted file mode 100644 index 46494cae1..000000000 --- a/retroshare-gui/src/gui/feeds/ForumMsgItem.ui +++ /dev/null @@ -1,664 +0,0 @@ - - - ForumMsgItem - - - - 0 - 0 - 577 - 387 - - - - - 0 - - - - - - 0 - 0 - - - - - - - - - 215 - 215 - 215 - - - - - - - - - 215 - 215 - 215 - - - - - - - - - 215 - 215 - 215 - - - - - - - - true - - - QFrame::Box - - - QFrame::Sunken - - - - - - - - - 48 - 48 - - - - - 48 - 48 - - - - :/images/konversation.png - - - Qt::AlignCenter - - - - - - - - 0 - 0 - - - - - 9 - 75 - false - true - - - - Forum Name - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop - - - true - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse - - - - - - - - - - - Qt::Horizontal - - - - 358 - 20 - - - - - - - - - 9 - 75 - true - - - - Timestamp - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop - - - - - - - Qt::Horizontal - - - - 518 - 20 - - - - - - - - - - - - - 75 - true - - - - Subject: - - - - - - - Subject... - - - false - - - true - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse - - - - - - - Qt::Horizontal - - - QSizePolicy::Expanding - - - - 10 - 20 - - - - - - - - - 0 - 0 - - - - Qt::NoFocus - - - Unsubscribe To Forum - - - - :/images/mail_delete.png:/images/mail_delete.png - - - - - - - - 0 - 0 - - - - Qt::NoFocus - - - Reply - - - - :/images/replymail24.png:/images/replymail24.png - - - - - - - - 0 - 0 - - - - Qt::NoFocus - - - Expand - - - - :/images/edit_add24.png:/images/edit_add24.png - - - - - - - - 0 - 0 - - - - Qt::NoFocus - - - Set as read and remove item - - - - :/images/cancel.png:/images/cancel.png - - - - - - - - 0 - 0 - - - - Qt::NoFocus - - - Remove Item - - - - :/images/close_normal.png:/images/close_normal.png - - - - - - - - - QFrame::Box - - - QFrame::Sunken - - - - - - - 32 - 32 - - - - - 32 - 32 - - - - - - - - - 75 - true - - - - Friend Name - - - true - - - - - - - - - - 0 - 0 - - - - - 75 - true - - - - Subject: - - - - - - - - 0 - 0 - - - - Message is about ??? - - - true - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse - - - - - - - Qt::Horizontal - - - QSizePolicy::Preferred - - - - 40 - 20 - - - - - - - - - - Qt::Vertical - - - - 20 - 9 - - - - - - - - - - - 0 - 0 - - - - Previous Message... - - - true - - - true - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse - - - - - - - Qt::Horizontal - - - QSizePolicy::Preferred - - - - 40 - 20 - - - - - - - - - - - - - QFrame::Box - - - QFrame::Sunken - - - - - - - 32 - 32 - - - - - 32 - 32 - - - - - - - - - 75 - true - - - - Next Name - - - true - - - - - - - - - - 0 - 0 - - - - - 75 - true - - - - Subject: - - - - - - - - 0 - 0 - - - - Message is about ??? - - - true - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse - - - - - - - - - Qt::Vertical - - - - 20 - 27 - - - - - - - - - - - 0 - 0 - - - - Current Message.. - - - true - - - true - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse - - - - - - - - - - - - - 16777215 - 40 - - - - - - - - - - Qt::Horizontal - - - - 40 - 2 - - - - - - - - Send - - - - - - - Signed - - - - - - - - - - - - - AvatarWidget - QLabel -
gui/common/AvatarWidget.h
- 1 -
-
- - - - -
diff --git a/retroshare-gui/src/gui/feeds/ForumNewItem.cpp b/retroshare-gui/src/gui/feeds/ForumNewItem.cpp deleted file mode 100644 index 87534b34a..000000000 --- a/retroshare-gui/src/gui/feeds/ForumNewItem.cpp +++ /dev/null @@ -1,206 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2008 Robert Fernie - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - -#include "ForumNewItem.h" -#include "FeedHolder.h" - -#include -#include "gui/forums/CreateForumMsg.h" -#include "gui/RetroShareLink.h" - -/**** - * #define DEBUG_ITEM 1 - ****/ - -/** Constructor */ -ForumNewItem::ForumNewItem(FeedHolder *parent, uint32_t feedId, const std::string &forumId, bool isHome, bool isNew) -:QWidget(NULL), mParent(parent), mFeedId(feedId), - mForumId(forumId), mIsHome(isHome), mIsNew(isNew) -{ - /* Invoke the Qt Designer generated object setup routine */ - setupUi(this); - - setAttribute ( Qt::WA_DeleteOnClose, true ); - - /* general ones */ - connect( expandButton, SIGNAL( clicked( void ) ), this, SLOT( toggle ( void ) ) ); - connect( clearButton, SIGNAL( clicked( void ) ), this, SLOT( removeItem ( void ) ) ); - - /* specific ones */ - connect( subscribeButton, SIGNAL( clicked( void ) ), this, SLOT( subscribeForum ( void ) ) ); - // To Cheeky to post on a brand new forum.... - connect( postButton, SIGNAL( clicked( void ) ), this, SLOT( postToForum ( void ) ) ); - - expandFrame->hide(); - updateItemStatic(); - updateItem(); -} - - -void ForumNewItem::updateItemStatic() -{ - if (!rsForums) - return; - - - /* fill in */ -#ifdef DEBUG_ITEM - std::cerr << "ForumNewItem::updateItemStatic()"; - std::cerr << std::endl; -#endif - - ForumInfo fi; - if (rsForums->getForumInfo(mForumId, fi)) - { - RetroShareLink link; - link.createForum(fi.forumId, ""); - nameLabel->setText(link.toHtml()); - - descLabel->setText(QString::fromStdWString(fi.forumDesc)); - - if (fi.subscribeFlags & RS_DISTRIB_SUBSCRIBED) - { - subscribeButton->setEnabled(false); - postButton->setEnabled(true); - } - else - { - subscribeButton->setEnabled(true); - postButton->setEnabled(false); - } - - /* should also check the other flags */ - } - else - { - nameLabel->setText(tr("Unknown Forum")); - titleLabel->setText(tr("New Forum")); - descLabel->setText(""); - } - - if (mIsNew) - { - titleLabel->setText(tr("New Forum")); - } - else - { - titleLabel->setText(tr("Updated Forum")); - } - - if (mIsHome) - { - /* disable buttons */ - clearButton->setEnabled(false); - } -} - - -void ForumNewItem::updateItem() -{ - /* fill in */ -#ifdef DEBUG_ITEM - std::cerr << "ForumNewItem::updateItem()"; - std::cerr << std::endl; -#endif - -} - -void ForumNewItem::toggle() -{ - mParent->lockLayout(this, true); - - if (expandFrame->isHidden()) - { - expandFrame->show(); - expandButton->setIcon(QIcon(QString(":/images/edit_remove24.png"))); - expandButton->setToolTip(tr("Hide")); - } - else - { - expandFrame->hide(); - expandButton->setIcon(QIcon(QString(":/images/edit_add24.png"))); - expandButton->setToolTip(tr("Expand")); - } - - mParent->lockLayout(this, false); -} - -void ForumNewItem::removeItem() -{ -#ifdef DEBUG_ITEM - std::cerr << "ForumNewItem::removeItem()"; - std::cerr << std::endl; -#endif - - mParent->lockLayout(this, true); - hide(); - mParent->lockLayout(this, false); - - if (mParent) - { - mParent->deleteFeedItem(this, mFeedId); - } -} - - -/*********** SPECIFIC FUNCTIOSN ***********************/ - - -void ForumNewItem::unsubscribeForum() -{ -#ifdef DEBUG_ITEM - std::cerr << "ForumNewItem::unsubscribeForum()"; - std::cerr << std::endl; -#endif - if (rsForums) - { - rsForums->forumSubscribe(mForumId, false); - } - updateItemStatic(); -} - - -void ForumNewItem::subscribeForum() -{ -#ifdef DEBUG_ITEM - std::cerr << "ForumNewItem::subscribeForum()"; - std::cerr << std::endl; -#endif - if (rsForums) - { - rsForums->forumSubscribe(mForumId, true); - } - updateItemStatic(); -} - -void ForumNewItem::postToForum() -{ -#ifdef DEBUG_ITEM - std::cerr << "ForumNewItem::subscribeForum()"; - std::cerr << std::endl; -#endif - if (mParent) - { - //mParent->openMsg(FEEDHOLDER_MSG_FORUM, mForumId, ""); - CreateForumMsg *cfm = new CreateForumMsg(mForumId, ""); - cfm->show(); - } -} diff --git a/retroshare-gui/src/gui/feeds/ForumNewItem.h b/retroshare-gui/src/gui/feeds/ForumNewItem.h deleted file mode 100644 index 88e64c20e..000000000 --- a/retroshare-gui/src/gui/feeds/ForumNewItem.h +++ /dev/null @@ -1,61 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2008 Robert Fernie - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - -#ifndef _FORUM_NEW_ITEM_DIALOG_H -#define _FORUM_NEW_ITEM_DIALOG_H - -#include "ui_ForumNewItem.h" -#include - -class FeedHolder; - -class ForumNewItem : public QWidget, private Ui::ForumNewItem -{ - Q_OBJECT - -public: - /** Default Constructor */ - ForumNewItem(FeedHolder *parent, uint32_t feedId, const std::string &forumId, bool isHome, bool isNew); - - void updateItemStatic(); - -private slots: - /* default stuff */ - void removeItem(); - void toggle(); - - void unsubscribeForum(); - void subscribeForum(); - void postToForum(); - - void updateItem(); - -private: - FeedHolder *mParent; - uint32_t mFeedId; - - std::string mForumId; - bool mIsHome; - bool mIsNew; -}; - -#endif - diff --git a/retroshare-gui/src/gui/feeds/ForumNewItem.ui b/retroshare-gui/src/gui/feeds/ForumNewItem.ui deleted file mode 100644 index 87983df57..000000000 --- a/retroshare-gui/src/gui/feeds/ForumNewItem.ui +++ /dev/null @@ -1,325 +0,0 @@ - - - ForumNewItem - - - - 0 - 0 - 618 - 117 - - - - - 0 - - - - - - 0 - 0 - - - - - - - - - 255 - 255 - 255 - - - - - - - 215 - 215 - 215 - - - - - - - - - 255 - 255 - 255 - - - - - - - 215 - 215 - 215 - - - - - - - - - 215 - 215 - 215 - - - - - - - 215 - 215 - 215 - - - - - - - - true - - - QFrame::Box - - - QFrame::Sunken - - - - 9 - - - 6 - - - 6 - - - - - - - - - - :/images/konversation.png - - - - - - - - 0 - 0 - - - - - 75 - true - true - - - - Forum - - - - - - - Qt::Horizontal - - - QSizePolicy::Fixed - - - - 20 - 20 - - - - - - - - name - - - true - - - - - - - Qt::Horizontal - - - QSizePolicy::Expanding - - - - 500 - 20 - - - - - - - - - 0 - 0 - - - - Qt::NoFocus - - - Subscribe to Forum - - - - :/images/directoryadd_24x24_shadow.png:/images/directoryadd_24x24_shadow.png - - - - - - - Qt::NoFocus - - - - :/images/mail_new.png:/images/mail_new.png - - - - - - - Qt::Horizontal - - - QSizePolicy::Fixed - - - - 20 - 20 - - - - - - - - - 0 - 0 - - - - Qt::NoFocus - - - Expand - - - - :/images/edit_add24.png:/images/edit_add24.png - - - - - - - - 0 - 0 - - - - Qt::NoFocus - - - Remove Item - - - - :/images/close_normal.png:/images/close_normal.png - - - - - - - - - - 0 - - - 0 - - - - - Forum Description - - - - - - - - - :/images/contacts24.png - - - - - - - - 0 - 0 - - - - Description - of Forum - - - - - - - - - - - - - - - - - - - diff --git a/retroshare-gui/src/gui/forums/CreateForum.cpp b/retroshare-gui/src/gui/forums/CreateForum.cpp deleted file mode 100644 index 08a128fb1..000000000 --- a/retroshare-gui/src/gui/forums/CreateForum.cpp +++ /dev/null @@ -1,134 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2008 Robert Fernie - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - -#include - -#include "util/misc.h" -#include "CreateForum.h" -#include "gui/common/PeerDefs.h" - -#include - -#include -#include - -/** Constructor */ -CreateForum::CreateForum() -: QDialog(NULL, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint) -{ - /* Invoke the Qt Designer generated object setup routine */ - ui.setupUi(this); - - setAttribute(Qt::WA_DeleteOnClose, true); - - ui.headerFrame->setHeaderImage(QPixmap(":/images/konversation64.png")); - ui.headerFrame->setHeaderText(tr("New Forum")); - - // connect up the buttons. - connect( ui.buttonBox, SIGNAL(accepted()), this, SLOT(createForum())); - connect( ui.buttonBox, SIGNAL(rejected()), this, SLOT(close())); - connect( ui.pubKeyShare_cb, SIGNAL( clicked() ), this, SLOT( setShareList( ) )); - - if (!ui.pubKeyShare_cb->isChecked()) { - ui.contactsdockWidget->hide(); - this->resize(this->size().width() - ui.contactsdockWidget->size().width(), this->size().height()); - } - - /* initialize key share list */ - ui.keyShareList->setHeaderText(tr("Contacts:")); - ui.keyShareList->setModus(FriendSelectionWidget::MODUS_CHECK); - ui.keyShareList->setShowType(FriendSelectionWidget::SHOW_GROUP | FriendSelectionWidget::SHOW_SSL); - ui.keyShareList->start(); - - newForum(); -} - -void CreateForum::newForum() -{ - /* enforce Public for the moment */ - ui.typePublic->setChecked(true); - - ui.typePrivate->setEnabled(false); - ui.typeEncrypted->setEnabled(true); - -#ifdef RS_RELEASE_VERSION - ui.typePrivate->setVisible(false); - ui.typeEncrypted->setVisible(true); -#endif - - ui.msgAnon->setChecked(true); - //ui.msgAuth->setEnabled(false); - - ui.forumName->clear(); - ui.forumDesc->clear(); - - ui.forumName->setFocus(); -} - -void CreateForum::createForum() -{ - QString name = misc::removeNewLine(ui.forumName->text()); - QString desc = ui.forumDesc->toPlainText(); //toHtml(); - uint32_t flags = 0; - - if(name.isEmpty()) { - /* error message */ - QMessageBox::warning(this, "RetroShare", tr("Please add a Name"), QMessageBox::Ok, QMessageBox::Ok); - return; //Don't add a empty name!! - } - - if (ui.typePublic->isChecked()) { - flags |= RS_DISTRIB_PUBLIC; - } else if (ui.typePrivate->isChecked()) { - flags |= RS_DISTRIB_PRIVATE; - } else if (ui.typeEncrypted->isChecked()) { - flags |= RS_DISTRIB_ENCRYPTED; - } - - if (ui.msgAuth->isChecked()) { - flags |= RS_DISTRIB_AUTHEN_REQ; - } else if (ui.msgAnon->isChecked()) { - flags |= RS_DISTRIB_AUTHEN_ANON; - } - - if (rsForums) { - std::string forumId = rsForums->createForum(name.toStdWString(), desc.toStdWString(), flags); - - if (ui.pubKeyShare_cb->isChecked()) { - std::list shareList; - ui.keyShareList->selectedSslIds(shareList, false); - rsForums->forumShareKeys(forumId, shareList); - } - } - - close(); -} - -void CreateForum::setShareList() -{ - if (ui.pubKeyShare_cb->isChecked()){ - this->resize(this->size().width() + ui.contactsdockWidget->size().width(), this->size().height()); - ui.contactsdockWidget->show(); - } else { // hide share widget - ui.contactsdockWidget->hide(); - this->resize(this->size().width() - ui.contactsdockWidget->size().width(), this->size().height()); - } -} diff --git a/retroshare-gui/src/gui/forums/CreateForum.h b/retroshare-gui/src/gui/forums/CreateForum.h deleted file mode 100644 index c8725e0c7..000000000 --- a/retroshare-gui/src/gui/forums/CreateForum.h +++ /dev/null @@ -1,54 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2008 Robert Fernie - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - - -#ifndef _CREATE_FORUM_DIALOG_H -#define _CREATE_FORUM_DIALOG_H - -#include "ui_CreateForum.h" - -class CreateForum : public QDialog -{ - Q_OBJECT - -public: - CreateForum(); - - void newForum(); /* cleanup */ - -private slots: - /* actions to take.... */ - void createForum(); - - // set private forum key share list - void setShareList(); - -private: - std::list mShareList; - - QPixmap picture; - - /** Qt Designer generated object */ - Ui::CreateForum ui; -}; - -#endif - diff --git a/retroshare-gui/src/gui/forums/CreateForum.ui b/retroshare-gui/src/gui/forums/CreateForum.ui deleted file mode 100644 index edc23fa0d..000000000 --- a/retroshare-gui/src/gui/forums/CreateForum.ui +++ /dev/null @@ -1,314 +0,0 @@ - - - CreateForum - - - - 0 - 0 - 672 - 495 - - - - Create new Forum - - - - :/images/rstray3.png:/images/rstray3.png - - - - 0 - - - 0 - - - - - - - - - - - - - Name - - - - - - - - - - - - true - - - - 0 - 0 - - - - - 300 - 524287 - - - - - 220 - 0 - - - - - 0 - 0 - - - - check peers you would like to share private publish key with - - - false - - - QDockWidget::NoDockWidgetFeatures - - - Share Key With - - - - - 0 - - - 0 - - - - - - 0 - 4 - - - - - 20 - 0 - - - - - 300 - 16777215 - - - - - 220 - 0 - - - - - 200 - 0 - - - - - - - - - - - - - - Description - - - - - - - - - - - - - 0 - 0 - - - - Type: - - - - 6 - - - - - Public - Anyone can read and publish (Shared Publish Key) - - - - - - - Restricted - Anyone can read, limited publishing (Private Publish Key) - - - - - - - Private - (Private Publish Key required to view Messages) - - - - - - - - - - Key Sharing - - - - 0 - - - 6 - - - - - Key recipients can publish to restricted-type channels, and can view and publish for private-type channels - - - Share Private Publish Key - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - Allowed Messages - - - - 0 - - - 6 - - - - - Authenticated Messages - - - - - - - Anonymous Messages - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - - - - - - - - HeaderFrame - QFrame -
gui/common/HeaderFrame.h
- 1 -
- - FriendSelectionWidget - QWidget -
gui/common/FriendSelectionWidget.h
- 1 -
-
- - - - -
diff --git a/retroshare-gui/src/gui/forums/CreateForumMsg.cpp b/retroshare-gui/src/gui/forums/CreateForumMsg.cpp deleted file mode 100644 index d4cda839c..000000000 --- a/retroshare-gui/src/gui/forums/CreateForumMsg.cpp +++ /dev/null @@ -1,259 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2008 Robert Fernie - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - -#include "CreateForumMsg.h" - -#include -#include -#include -#include -#include -#include - -#include -#include - -#include "gui/settings/rsharesettings.h" -#include "gui/RetroShareLink.h" -#include "gui/common/Emoticons.h" - -#include "util/HandleRichText.h" -#include "util/misc.h" - -#include - - -/** Constructor */ -CreateForumMsg::CreateForumMsg(const std::string &fId, const std::string &pId) -: QDialog(NULL, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint), mForumId(fId), mParentId(pId) -{ - /* Invoke the Qt Designer generated object setup routine */ - ui.setupUi(this); - setAttribute(Qt::WA_DeleteOnClose, true); - - QString text = pId.empty() ? tr("Start New Thread") : tr("Post Forum Message"); - setWindowTitle(text); - - ui.headerFrame->setHeaderImage(QPixmap(":/images/konversation64.png")); - ui.headerFrame->setHeaderText(text); - - Settings->loadWidgetInformation(this); - - connect( ui.forumMessage, SIGNAL( customContextMenuRequested( QPoint ) ), this, SLOT( forumMessageCostumPopupMenu( QPoint ) ) ); - - connect(ui.hashBox, SIGNAL(fileHashingFinished(QList)), this, SLOT(fileHashingFinished(QList))); - - // connect up the buttons. - connect( ui.buttonBox, SIGNAL(accepted()), this, SLOT(createMsg())); - connect( ui.buttonBox, SIGNAL(rejected()), this, SLOT(close())); - connect( ui.emoticonButton, SIGNAL(clicked()), this, SLOT(smileyWidgetForums())); - connect( ui.attachFileButton, SIGNAL(clicked() ), this , SLOT(addFile())); - connect( ui.pastersButton, SIGNAL(clicked() ), this , SLOT(pasteLink())); - - setAcceptDrops(true); - ui.hashBox->setDropWidget(this); - ui.hashBox->setAutoHide(false); - - newMsg(); -} - -/** context menu searchTablewidget2 **/ -void CreateForumMsg::forumMessageCostumPopupMenu(QPoint point) -{ - QMenu *contextMnu = ui.forumMessage->createStandardContextMenu(point); - - contextMnu->addSeparator(); - QAction *pasteLinkAct = contextMnu->addAction(QIcon(":/images/pasterslink.png"), tr("Paste RetroShare Link"), this, SLOT(pasteLink())); - QAction *pasteLinkFullAct = contextMnu->addAction(QIcon(":/images/pasterslink.png"), tr("Paste full RetroShare Link"), this, SLOT(pasteLinkFull())); - contextMnu->addAction(QIcon(":/images/pasterslink.png"), tr("Paste my certificate link"), this, SLOT(pasteOwnCertificateLink())); - - if (RSLinkClipboard::empty()) { - pasteLinkAct->setDisabled (true); - pasteLinkFullAct->setDisabled (true); - } - - contextMnu->exec(QCursor::pos()); - delete(contextMnu); -} - -void CreateForumMsg::newMsg() -{ - /* clear all */ - ForumInfo fi; - if (rsForums->getForumInfo(mForumId, fi)) - { - ForumMsgInfo msg; - - QString name = QString::fromStdWString(fi.forumName); - QString subj; - if ((mParentId != "") && (rsForums->getForumMessage(mForumId, mParentId, msg))) - { - QString title = QString::fromStdWString(msg.title); - name += " " + tr("In Reply to") + ": "; - name += title; - - QString text = title; - - if (text.startsWith("Re:", Qt::CaseInsensitive)) - { - subj = title; - } - else - { - subj = "Re: " + title; - } - - } - - ui.forumName->setText(misc::removeNewLine(name)); - ui.forumSubject->setText(misc::removeNewLine(subj)); - - if (!ui.forumSubject->text().isEmpty()) - { - ui.forumMessage->setFocus(); - } - else - { - ui.forumSubject->setFocus(); - } - - if (fi.forumFlags & RS_DISTRIB_AUTHEN_REQ) - { - ui.signBox->setChecked(true); - ui.signBox->setEnabled(false); - } - else - { - /* Uncheck sign box by default for anonymous forums */ - ui.signBox->setChecked(false); - ui.signBox->setEnabled(true); - } - } - - ui.forumMessage->setText(""); -} - -void CreateForumMsg::createMsg() -{ - QString name = misc::removeNewLine(ui.forumSubject->text()); - QString desc; - - RsHtml::optimizeHtml(ui.forumMessage, desc); - - if(name.isEmpty()) - { /* error message */ - QMessageBox::warning(this, tr("RetroShare"),tr("Please set a Forum Subject and Forum Message"), - QMessageBox::Ok, QMessageBox::Ok); - - return; //Don't add a empty Subject!! - } - - ForumMsgInfo msgInfo; - - msgInfo.forumId = mForumId; - msgInfo.threadId = ""; - msgInfo.parentId = mParentId; - msgInfo.msgId = ""; - - msgInfo.title = name.toStdWString(); - msgInfo.msg = desc.toStdWString(); - msgInfo.msgflags = 0; - - if (ui.signBox->isChecked()) - { - msgInfo.msgflags = RS_DISTRIB_AUTHEN_REQ; - } - - if ((msgInfo.msg == L"") && (msgInfo.title == L"")) - return; /* do nothing */ - - if (rsForums->ForumMessageSend(msgInfo) == true) { - close(); - } -} - -void CreateForumMsg::closeEvent (QCloseEvent * /*event*/) -{ - Settings->saveWidgetInformation(this); -} - -void CreateForumMsg::smileyWidgetForums() -{ - Emoticons::showSmileyWidget(this, ui.emoticonButton, SLOT(addSmileys()), false); -} - -void CreateForumMsg::addSmileys() -{ - ui.forumMessage->textCursor().insertText(qobject_cast(sender())->toolTip().split("|").first()); -} - -void CreateForumMsg::addFile() -{ - QStringList files; - if (misc::getOpenFileNames(this, RshareSettings::LASTDIR_EXTRAFILE, tr("Add Extra File"), "", files)) { - ui.hashBox->addAttachments(files,RS_FILE_REQ_ANONYMOUS_ROUTING); - } -} - -void CreateForumMsg::fileHashingFinished(QList hashedFiles) -{ - std::cerr << "CreateForumMsg::fileHashingFinished() started." << std::endl; - - QString mesgString; - - QList::iterator it; - for (it = hashedFiles.begin(); it != hashedFiles.end(); ++it) { - HashedFile& hashedFile = *it; - RetroShareLink link; - if (link.createFile(hashedFile.filename, hashedFile.size, QString::fromStdString(hashedFile.hash))) { - mesgString += link.toHtmlSize() + "
"; - } - } - -#ifdef CHAT_DEBUG - std::cerr << "CreateForumMsg::anchorClicked mesgString : " << mesgString.toStdString() << std::endl; -#endif - - if (!mesgString.isEmpty()) { - ui.forumMessage->textCursor().insertHtml(mesgString); - } - - ui.forumMessage->setFocus( Qt::OtherFocusReason ); -} - -void CreateForumMsg::pasteLink() -{ - ui.forumMessage->insertHtml(RSLinkClipboard::toHtml()) ; -} - -void CreateForumMsg::pasteLinkFull() -{ - ui.forumMessage->insertHtml(RSLinkClipboard::toHtmlFull()) ; -} - -void CreateForumMsg::pasteOwnCertificateLink() -{ - RetroShareLink link ; - std::string ownId = rsPeers->getOwnId() ; - if( link.createCertificate(ownId) ) { - ui.forumMessage->insertHtml(link.toHtml() + " "); - } -} diff --git a/retroshare-gui/src/gui/forums/CreateForumMsg.h b/retroshare-gui/src/gui/forums/CreateForumMsg.h deleted file mode 100644 index 1ff855b5a..000000000 --- a/retroshare-gui/src/gui/forums/CreateForumMsg.h +++ /dev/null @@ -1,64 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2008 Robert Fernie - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - - -#ifndef _CREATE_FORUM_MSG_DIALOG_H -#define _CREATE_FORUM_MSG_DIALOG_H - -#include "ui_CreateForumMsg.h" - -class CreateForumMsg : public QDialog -{ - Q_OBJECT - -public: - CreateForumMsg(const std::string &fId, const std::string &pId); - - void newMsg(); /* cleanup */ - -private slots: - /** Create the context popup menu and it's submenus */ - void forumMessageCostumPopupMenu( QPoint point ); - - void fileHashingFinished(QList hashedFiles); - /* actions to take.... */ - void createMsg(); - void pasteLink(); - void pasteLinkFull(); - void pasteOwnCertificateLink(); - - void smileyWidgetForums(); - void addSmileys(); - void addFile(); - -protected: - void closeEvent (QCloseEvent * event); - -private: - std::string mForumId; - std::string mParentId; - - /** Qt Designer generated object */ - Ui::CreateForumMsg ui; -}; - -#endif - diff --git a/retroshare-gui/src/gui/forums/CreateForumMsg.ui b/retroshare-gui/src/gui/forums/CreateForumMsg.ui deleted file mode 100644 index 80206caad..000000000 --- a/retroshare-gui/src/gui/forums/CreateForumMsg.ui +++ /dev/null @@ -1,282 +0,0 @@ - - - CreateForumMsg - - - - 0 - 0 - 482 - 448 - - - - Post Forum Message - - - - :/images/rstray3.png:/images/rstray3.png - - - - 0 - - - 0 - - - - - - - - QFrame::StyledPanel - - - QFrame::Raised - - - - - - QFrame::NoFrame - - - QFrame::Raised - - - - 0 - - - - - Forum - - - - - - - false - - - - - - - Subject - - - - - - - - - - - - - - 16777215 - 38 - - - - QFrame::Box - - - QFrame::Sunken - - - - 6 - - - - - Qt::NoFocus - - - Attach File - - - - - - - :/images/add-share24.png:/images/add-share24.png - - - - 24 - 24 - - - - true - - - - - - - Qt::NoFocus - - - - - - - :/images/emoticons/kopete/kopete020.png:/images/emoticons/kopete/kopete020.png - - - - 24 - 24 - - - - true - - - - - - - Qt::NoFocus - - - Sign Message - - - - :/images/pgp.png:/images/pgp.png - - - - 24 - 24 - - - - true - - - - - - - Qt::Horizontal - - - - 40 - 15 - - - - - - - - Qt::NoFocus - - - Paste RetroShare Link - - - - - - - :/images/pasterslink.png:/images/pasterslink.png - - - true - - - - - - - - - - Forum Post - - - - - - Qt::CustomContextMenu - - - <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> -<html><head><meta name="qrichtext" content="1" /><style type="text/css"> -p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> -<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:8pt;"></p></body></html> - - - - - - - - - - Attach files via drag and drop - - - - - - - 0 - 0 - - - - You can attach files via drag and drop here in this window - - - true - - - - - - - - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - - - - - - HeaderFrame - QFrame -
gui/common/HeaderFrame.h
- 1 -
- - HashBox - QScrollArea -
gui/common/HashBox.h
- 1 -
-
- - - - -
diff --git a/retroshare-gui/src/gui/forums/EditForumDetails.cpp b/retroshare-gui/src/gui/forums/EditForumDetails.cpp deleted file mode 100644 index 048db0ffa..000000000 --- a/retroshare-gui/src/gui/forums/EditForumDetails.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2010 RetroShare Team - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - -#include "EditForumDetails.h" - -#include - -#include "util/misc.h" - -#include -#include -#include - - -/** Default constructor */ -EditForumDetails::EditForumDetails(std::string forumId, QWidget *parent) - : QDialog(parent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint), m_forumId(forumId) -{ - /* Invoke Qt Designer generated QObject setup routine */ - ui.setupUi(this); - - connect(ui.buttonBox, SIGNAL(accepted()), this, SLOT(applyDialog())); - connect(ui.buttonBox, SIGNAL(rejected()), this, SLOT(close())); - - loadForum(); -} - -void EditForumDetails::loadForum() -{ - if (!rsForums) { - return; - } - - ForumInfo info; - rsForums->getForumInfo(m_forumId, info); - - // set name - ui.nameline->setText(QString::fromStdWString(info.forumName)); - - // set description - ui.DescriptiontextEdit->setText(QString::fromStdWString(info.forumDesc)); -} - -void EditForumDetails::applyDialog() -{ - if (!rsForums) { - return; - } - - // if text boxes have not been edited leave alone - if (!ui.nameline->isModified() && !ui.DescriptiontextEdit->document()->isModified()) { - return; - } - - ForumInfo info; - - info.forumName = misc::removeNewLine(ui.nameline->text()).toStdWString(); - info.forumDesc = ui.DescriptiontextEdit->document()->toPlainText().toStdWString(); - - rsForums->setForumInfo(m_forumId, info); - - /* close the Dialog after the Changes applied */ - close(); -} diff --git a/retroshare-gui/src/gui/forums/EditForumDetails.h b/retroshare-gui/src/gui/forums/EditForumDetails.h deleted file mode 100644 index 28ae8d69b..000000000 --- a/retroshare-gui/src/gui/forums/EditForumDetails.h +++ /dev/null @@ -1,53 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2010 RetroShare Team - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - -#ifndef _EDITFORUMDETAILS_H -#define _EDITFORUMDETAILS_H - -#include - -#include "ui_EditForumDetails.h" - -class EditForumDetails : public QDialog -{ - Q_OBJECT - -public: - /** Default constructor */ - EditForumDetails(std::string forumId = "", QWidget *parent = 0); - -signals: - void configChanged(); - -private slots: - void applyDialog(); - -private: - void loadForum(); - - std::string m_forumId; - - /** Qt Designer generated object */ - Ui::EditForumDetails ui; -}; - -#endif - diff --git a/retroshare-gui/src/gui/forums/EditForumDetails.ui b/retroshare-gui/src/gui/forums/EditForumDetails.ui deleted file mode 100644 index e7a1f0c79..000000000 --- a/retroshare-gui/src/gui/forums/EditForumDetails.ui +++ /dev/null @@ -1,87 +0,0 @@ - - - EditForumDetails - - - - 0 - 0 - 436 - 355 - - - - Forum Details - - - - :/images/rstray3.png:/images/rstray3.png - - - - - - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - - - - 0 - - - - - :/images/info16.png:/images/info16.png - - - Edit Forum Details - - - - - - Forum Info - - - - - - Forum Name - - - - - - - - - - Forum Description - - - - - - - - - - - - - - - - - - - - - - diff --git a/retroshare-gui/src/gui/forums/ForumDetails.cpp b/retroshare-gui/src/gui/forums/ForumDetails.cpp deleted file mode 100644 index 9846b073d..000000000 --- a/retroshare-gui/src/gui/forums/ForumDetails.cpp +++ /dev/null @@ -1,112 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2009 RetroShare Team - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ -#include "ForumDetails.h" -#include "util/DateTime.h" - -#include -#include -#include -#include - -#include -#include - -#include -#include -#include - -/** Default constructor */ -ForumDetails::ForumDetails(QWidget *parent) - : QDialog(parent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint) -{ - /* Invoke Qt Designer generated QObject setup routine */ - ui.setupUi(this); - - connect(ui.buttonBox, SIGNAL(rejected()), this, SLOT(close())); - - ui.nameline ->setReadOnly(true); - ui.popline ->setReadOnly(true); - ui.postline ->setReadOnly(true); - ui.IDline ->setReadOnly(true); - ui.DescriptiontextEdit ->setReadOnly(true); - - ui.radioButton_authd->setEnabled(false); - ui.radioButton_anonymous->setEnabled(false); -} - - -/** - Overloads the default show() slot so we can set opacity*/ - -void -ForumDetails::show() -{ - //loadSettings(); - if(!this->isVisible()) { - QDialog::show(); - - } -} - -void ForumDetails::showDetails(std::string mCurrForumId) -{ - fId = mCurrForumId; - loadDialog(); -} - -void ForumDetails::loadDialog() -{ - if (!rsForums) - { - return; - } - - ForumInfo fi; - rsForums->getForumInfo(fId, fi); - - // Set Forum Name - ui.nameline->setText(QString::fromStdWString(fi.forumName)); - - // Set Popularity - ui.popline->setText(QString::number(fi.pop)); - - // Set Last Post Date - if (fi.lastPost) { - ui.postline->setText(DateTime::formatLongDateTime(fi.lastPost)); - } - - // Set Forum ID - ui.IDline->setText(QString::fromStdString(fi.forumId)); - - // Set Forum Description - ui.DescriptiontextEdit->setText(QString::fromStdWString(fi.forumDesc)); - - if (fi.forumFlags & RS_DISTRIB_AUTHEN_REQ) - { - ui.radioButton_authd->setChecked(true); - ui.radioButton_anonymous->setChecked(false); - } - if (fi.forumFlags & RS_DISTRIB_AUTHEN_ANON) - { - ui.radioButton_authd->setChecked(false); - ui.radioButton_anonymous->setChecked(true); - } -} diff --git a/retroshare-gui/src/gui/forums/ForumDetails.h b/retroshare-gui/src/gui/forums/ForumDetails.h deleted file mode 100644 index 659bda8a8..000000000 --- a/retroshare-gui/src/gui/forums/ForumDetails.h +++ /dev/null @@ -1,57 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2009 RetroShare Team - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - -#ifndef _FORUMDETAILS_H -#define _FORUMDETAILS_H - -#include - -#include "ui_ForumDetails.h" - -class ForumDetails : public QDialog -{ - Q_OBJECT - - public: - - /** Default constructor */ - ForumDetails(QWidget *parent = 0); - - void showDetails(std::string mCurrForumId); - -signals: - void configChanged() ; - -public slots: - /** Overloaded QWidget.show */ - void show(); - -private: - void loadDialog(); - - std::string fId; - /** Qt Designer generated object */ - Ui::ForumDetails ui; - -}; - -#endif - diff --git a/retroshare-gui/src/gui/forums/ForumDetails.ui b/retroshare-gui/src/gui/forums/ForumDetails.ui deleted file mode 100644 index 295f16028..000000000 --- a/retroshare-gui/src/gui/forums/ForumDetails.ui +++ /dev/null @@ -1,175 +0,0 @@ - - - ForumDetails - - - - 0 - 0 - 436 - 355 - - - - Forum Details - - - - :/images/rstray3.png:/images/rstray3.png - - - - - - 0 - - - - - :/images/info16.png:/images/info16.png - - - Forum Details - - - - - - Forum Info - - - - - - Forum Name - - - - - - - - - - Popularity - - - - - - - true - - - - - - - Last Post - - - - - - - true - - - - - - - Forum ID - - - - - - - - - - Forum Description - - - - - - - - - - - - - - - - - :/images/encrypted22.png:/images/encrypted22.png - - - Security - - - - - - Allowed Messages - - - - - - Authenticated Messages - - - - - - - Anonymous Messages - - - true - - - - - - - - - - Qt::Vertical - - - - 358 - 172 - - - - - - - - - - - - - - QDialogButtonBox::Close - - - - - - - - - - - - diff --git a/retroshare-gui/src/gui/forums/ForumUserNotify.cpp b/retroshare-gui/src/gui/forums/ForumUserNotify.cpp deleted file mode 100644 index fa1da8831..000000000 --- a/retroshare-gui/src/gui/forums/ForumUserNotify.cpp +++ /dev/null @@ -1,106 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2012 RetroShare Team - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - -#include "ForumUserNotify.h" -#include "gui/settings/rsharesettings.h" -#include "gui/notifyqt.h" -#include "gui/MainWindow.h" - -#include - -ForumUserNotify::ForumUserNotify(QObject *parent) : - UserNotify(parent) -{ - connect(NotifyQt::getInstance(), SIGNAL(forumsChanged()), this, SLOT(updateIcon()), Qt::QueuedConnection); -} - -bool ForumUserNotify::hasSetting(QString &name) -{ - name = tr("Forum Post"); - - return true; -} - -bool ForumUserNotify::notifyEnabled() -{ - return (Settings->getTrayNotifyFlags() & TRAYNOTIFY_FORUMS); -} - -bool ForumUserNotify::notifyCombined() -{ - return (Settings->getTrayNotifyFlags() & TRAYNOTIFY_FORUMS_COMBINED); -} - -bool ForumUserNotify::notifyBlink() -{ - return (Settings->getTrayNotifyBlinkFlags() & TRAYNOTIFY_BLINK_FORUMS); -} - -void ForumUserNotify::setNotifyEnabled(bool enabled, bool combined, bool blink) -{ - uint notifyFlags = Settings->getTrayNotifyFlags(); - uint blinkFlags = Settings->getTrayNotifyBlinkFlags(); - - if (enabled) { - notifyFlags |= TRAYNOTIFY_FORUMS; - } else { - notifyFlags &= ~TRAYNOTIFY_FORUMS; - } - - if (combined) { - notifyFlags |= TRAYNOTIFY_FORUMS_COMBINED; - } else { - notifyFlags &= ~TRAYNOTIFY_FORUMS_COMBINED; - } - - if (blink) { - blinkFlags |= TRAYNOTIFY_BLINK_FORUMS; - } else { - blinkFlags &= ~TRAYNOTIFY_BLINK_FORUMS; - } - - Settings->setTrayNotifyFlags(notifyFlags); - Settings->setTrayNotifyBlinkFlags(blinkFlags); -} - -QIcon ForumUserNotify::getIcon() -{ - return QIcon(":/images/konversation16.png"); -} - -QIcon ForumUserNotify::getMainIcon(bool hasNew) -{ - return hasNew ? QIcon(":/images/forums_new.png") : QIcon(":/images/konversation.png"); -} - -unsigned int ForumUserNotify::getNewCount() -{ - unsigned int newMessageCount = 0; - unsigned int unreadMessageCount = 0; - rsForums->getMessageCount("", newMessageCount, unreadMessageCount); - - return newMessageCount; -} - -void ForumUserNotify::iconClicked() -{ - MainWindow::showWindow(MainWindow::Forums); -} diff --git a/retroshare-gui/src/gui/forums/ForumUserNotify.h b/retroshare-gui/src/gui/forums/ForumUserNotify.h deleted file mode 100644 index 8451bd0b0..000000000 --- a/retroshare-gui/src/gui/forums/ForumUserNotify.h +++ /dev/null @@ -1,47 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2012 RetroShare Team - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - -#ifndef FORUMUSERNOTIFY_H -#define FORUMUSERNOTIFY_H - -#include "gui/common/UserNotify.h" - -class ForumUserNotify : public UserNotify -{ - Q_OBJECT - -public: - ForumUserNotify(QObject *parent = 0); - - virtual bool hasSetting(QString &name); - virtual bool notifyEnabled(); - virtual bool notifyCombined(); - virtual bool notifyBlink(); - virtual void setNotifyEnabled(bool enabled, bool combined, bool blink); - -private: - virtual QIcon getIcon(); - virtual QIcon getMainIcon(bool hasNew); - virtual unsigned int getNewCount(); - virtual void iconClicked(); -}; - -#endif // FORUMUSERNOTIFY_H diff --git a/retroshare-gui/src/gui/settings/ForumPage.cpp b/retroshare-gui/src/gui/settings/ForumPage.cpp deleted file mode 100644 index c877178d0..000000000 --- a/retroshare-gui/src/gui/settings/ForumPage.cpp +++ /dev/null @@ -1,58 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2006, crypton - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - -#include "ForumPage.h" -#include "rshare.h" -#include "rsharesettings.h" - -#include "../MainWindow.h" -#include "../ForumsDialog.h" - -ForumPage::ForumPage(QWidget * parent, Qt::WFlags flags) - : ConfigPage(parent, flags) -{ - ui.setupUi(this); - setAttribute(Qt::WA_QuitOnClose, false); -} - -ForumPage::~ForumPage() -{ -} - -/** Saves the changes on this page */ -bool -ForumPage::save(QString &/*errmsg*/) -{ - Settings->setForumMsgSetToReadOnActivate(ui.setMsgToReadOnActivate->isChecked()); - Settings->setForumExpandNewMessages(ui.expandNewMessages->isChecked()); - Settings->setForumOpenAllInNewTab(ui.openAllInNewTabCheckBox->isChecked()); - - return true; -} - -/** Loads the settings for this page */ -void -ForumPage::load() -{ - ui.setMsgToReadOnActivate->setChecked(Settings->getForumMsgSetToReadOnActivate()); - ui.expandNewMessages->setChecked(Settings->getForumExpandNewMessages()); - ui.openAllInNewTabCheckBox->setChecked(Settings->getForumOpenAllInNewTab()); -} diff --git a/retroshare-gui/src/gui/settings/ForumPage.h b/retroshare-gui/src/gui/settings/ForumPage.h deleted file mode 100644 index 50b4d7102..000000000 --- a/retroshare-gui/src/gui/settings/ForumPage.h +++ /dev/null @@ -1,49 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2006, crypton - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - -#ifndef FORUMPAGE_H -#define FORUMPAGE_H - -#include -#include "ui_ForumPage.h" - -class ForumPage : public ConfigPage -{ - Q_OBJECT - -public: - ForumPage(QWidget * parent = 0, Qt::WFlags flags = 0); - ~ForumPage(); - - /** Saves the changes on this page */ - virtual bool save(QString &errmsg); - /** Loads the settings for this page */ - virtual void load(); - - virtual QPixmap iconPixmap() const { return QPixmap(":/images/konversation.png") ; } - virtual QString pageName() const { return tr("Forum") ; } - -private: - Ui::ForumPage ui; -}; - -#endif // !FORUMPAGE_H - diff --git a/retroshare-gui/src/gui/settings/ForumPage.ui b/retroshare-gui/src/gui/settings/ForumPage.ui deleted file mode 100644 index 30ed15f11..000000000 --- a/retroshare-gui/src/gui/settings/ForumPage.ui +++ /dev/null @@ -1,70 +0,0 @@ - - - ForumPage - - - - 0 - 0 - 423 - 340 - - - - - - - Misc - - - - - - Set message to read on activate - - - - - - - Expand new messages - - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - New forum - - - - - - Open all forums in new tab - - - - - - - - - - - diff --git a/retroshare-gui/src/gui/settings/NotifyPage.cpp b/retroshare-gui/src/gui/settings/NotifyPage.cpp index bafa327a8..bbfeb00c1 100755 --- a/retroshare-gui/src/gui/settings/NotifyPage.cpp +++ b/retroshare-gui/src/gui/settings/NotifyPage.cpp @@ -110,12 +110,14 @@ uint NotifyPage::getNewsFlags() if (ui.notify_Peers->isChecked()) newsFlags |= RS_FEED_TYPE_PEER; +#if 0 if (ui.notify_Channels->isChecked()) newsFlags |= RS_FEED_TYPE_CHAN; if (ui.notify_Forums->isChecked()) newsFlags |= RS_FEED_TYPE_FORUM; if (ui.notify_Blogs->isChecked()) newsFlags |= RS_FEED_TYPE_BLOG; +#endif if (ui.notify_Messages->isChecked()) newsFlags |= RS_FEED_TYPE_MSG; if (ui.notify_Chat->isChecked()) @@ -210,9 +212,11 @@ void NotifyPage::load() ui.popup_ConnectAttempt->setChecked(notifyflags & RS_POPUP_CONNECT_ATTEMPT); ui.notify_Peers->setChecked(newsflags & RS_FEED_TYPE_PEER); +#if 0 ui.notify_Channels->setChecked(newsflags & RS_FEED_TYPE_CHAN); ui.notify_Forums->setChecked(newsflags & RS_FEED_TYPE_FORUM); ui.notify_Blogs->setChecked(newsflags & RS_FEED_TYPE_BLOG); +#endif ui.notify_Chat->setChecked(newsflags & RS_FEED_TYPE_CHAT); ui.notify_Messages->setChecked(newsflags & RS_FEED_TYPE_MSG); ui.notify_Chat->setChecked(newsflags & RS_FEED_TYPE_CHAT); diff --git a/retroshare-gui/src/gui/settings/ServerPage.cpp b/retroshare-gui/src/gui/settings/ServerPage.cpp index 73bb152c3..005e4137b 100755 --- a/retroshare-gui/src/gui/settings/ServerPage.cpp +++ b/retroshare-gui/src/gui/settings/ServerPage.cpp @@ -112,7 +112,7 @@ void ServerPage::toggleIpDetermination(bool b) void ServerPage::toggleTunnelConnection(bool b) { std::cerr << "ServerPage::toggleTunnelConnection() set tunnel to : " << b << std::endl; - rsPeers->allowTunnelConnection(b) ; + //rsPeers->allowTunnelConnection(b) ; } /** Saves the changes on this page */ diff --git a/retroshare-gui/src/gui/settings/rsettingswin.cpp b/retroshare-gui/src/gui/settings/rsettingswin.cpp index c1daa9027..47ff19a33 100644 --- a/retroshare-gui/src/gui/settings/rsettingswin.cpp +++ b/retroshare-gui/src/gui/settings/rsettingswin.cpp @@ -36,7 +36,7 @@ #include "RelayPage.h" #include "ChatPage.h" #include "MessagePage.h" -#include "ForumPage.h" +//#include "ForumPage.h" #include "PluginsPage.h" #include "rsharesettings.h" #include "gui/notifyqt.h" @@ -127,7 +127,7 @@ RSettingsWin::initStackedWidget() addPage(new NotifyPage()); addPage(new CryptoPage()); addPage(new MessagePage()); - addPage(new ForumPage()); + //addPage(new ForumPage()); addPage(new ChatPage()); addPage(new AppearancePage()); addPage(new SoundPage() ); diff --git a/retroshare-gui/src/gui/settings/rsharesettings.cpp b/retroshare-gui/src/gui/settings/rsharesettings.cpp index c596ec2af..d6d71c4f0 100644 --- a/retroshare-gui/src/gui/settings/rsharesettings.cpp +++ b/retroshare-gui/src/gui/settings/rsharesettings.cpp @@ -123,8 +123,8 @@ void RshareSettings::initSettings() uint defNotify = (RS_POPUP_CONNECT | RS_POPUP_MSG); - uint defNewsFeed = (RS_FEED_TYPE_PEER | RS_FEED_TYPE_CHAN | - RS_FEED_TYPE_FORUM | RS_FEED_TYPE_BLOG | + uint defNewsFeed = (RS_FEED_TYPE_PEER | +// RS_FEED_TYPE_CHAN | RS_FEED_TYPE_FORUM | RS_FEED_TYPE_BLOG | RS_FEED_TYPE_CHAT | RS_FEED_TYPE_MSG | RS_FEED_TYPE_FILES | RS_FEED_TYPE_SECURITY); diff --git a/retroshare-gui/src/gui/unfinished/blogs/BlogDetails.cpp b/retroshare-gui/src/gui/unfinished/blogs/BlogDetails.cpp deleted file mode 100644 index e698596e2..000000000 --- a/retroshare-gui/src/gui/unfinished/blogs/BlogDetails.cpp +++ /dev/null @@ -1,147 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2009 RetroShare Team - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ -#include "BlogDetails.h" - -#include -#include -#include -#include - -#include -#include - -#include -#include -#include - - -/** Default constructor */ -BlogDetails::BlogDetails(QWidget *parent, Qt::WFlags flags) - : QDialog(parent, flags) -{ - /* Invoke Qt Designer generated QObject setup routine */ - ui.setupUi(this); - - setAttribute ( Qt::WA_DeleteOnClose, true ); - - connect(ui.applyButton, SIGNAL(clicked()), this, SLOT(applyDialog())); - connect(ui.cancelButton, SIGNAL(clicked()), this, SLOT(closeinfodlg())); - - ui.applyButton->setToolTip(tr("Close")); - - ui.nameline ->setReadOnly(true); - ui.popline ->setReadOnly(true); - ui.postline ->setReadOnly(true); - ui.IDline ->setReadOnly(true); - ui.DescriptiontextEdit ->setReadOnly(true); - - -} - -/** Overloads the default show() */ -void -BlogDetails::show() -{ - if(!this->isVisible()) { - QDialog::show(); - - } -} - -void BlogDetails::closeEvent (QCloseEvent * event) -{ - QWidget::closeEvent(event); -} - -void BlogDetails::closeinfodlg() -{ - close(); -} - -void BlogDetails::showDetails(std::string mBlogId) -{ - bId = mBlogId; - loadBlog(); -} - -void BlogDetails::loadBlog() -{ - - if (!rsBlogs) - { - return; - } - - std::list channelList; - std::list::iterator it; - - BlogInfo bi; - rsBlogs->getBlogInfo(bId, bi); - - rsBlogs->getBlogList(channelList); - - - for(it = channelList.begin(); it != channelList.end(); it++) - { - - // Set Blog Name - ui.nameline->setText(QString::fromStdWString(bi.blogName)); - - // Set Blog Popularity - { - std::ostringstream out; - out << it->pop; - ui.popline -> setText(QString::fromStdString(out.str())); - } - - // Set Last Blog Post Date - { - QDateTime qtime; - qtime.setTime_t(it->lastPost); - QString timestamp = qtime.toString(Qt::DefaultLocaleShortDate); - ui.postline -> setText(timestamp); - } - - // Set Blog ID - ui.IDline->setText(QString::fromStdString(bi.blogId)); - - // Set Blog Description - ui.DescriptiontextEdit->setText(QString::fromStdWString(bi.blogDesc)); - - - - } - -} - -void BlogDetails::applyDialog() -{ - - /* reload now */ - loadBlog(); - - /* close the Dialog after the Changes applied */ - closeinfodlg(); - -} - - - diff --git a/retroshare-gui/src/gui/unfinished/blogs/BlogDetails.h b/retroshare-gui/src/gui/unfinished/blogs/BlogDetails.h deleted file mode 100644 index f0e654d8c..000000000 --- a/retroshare-gui/src/gui/unfinished/blogs/BlogDetails.h +++ /dev/null @@ -1,68 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2009 RetroShare Team - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - -#ifndef _BLOGDETAILS_H -#define _BLOGDETAILS_H - -#include - -#include "ui_BlogDetails.h" - -class BlogDetails : public QDialog -{ - Q_OBJECT - - public: - - /** Default constructor */ - BlogDetails(QWidget *parent = 0, Qt::WFlags flags = 0); - /** Default destructor */ - - void showDetails(std::string mChannelId); - -signals: - void configChanged() ; - -public slots: - /** Overloaded QWidget.show */ - void show(); - -protected: - void closeEvent (QCloseEvent * event); - -private slots: - - void closeinfodlg(); - void applyDialog(); - - -private: - - void loadBlog(); - - std::string bId; - /** Qt Designer generated object */ - Ui::BlogDetails ui; - -}; - -#endif - diff --git a/retroshare-gui/src/gui/unfinished/blogs/BlogDetails.ui b/retroshare-gui/src/gui/unfinished/blogs/BlogDetails.ui deleted file mode 100644 index 2315161fe..000000000 --- a/retroshare-gui/src/gui/unfinished/blogs/BlogDetails.ui +++ /dev/null @@ -1,151 +0,0 @@ - - - BlogDetails - - - - 0 - 0 - 436 - 355 - - - - Blog Details - - - - :/images/rstray3.png:/images/rstray3.png - - - - - - 0 - - - - - :/images/info16.png:/images/info16.png - - - Blog Details - - - - - - Blog Info - - - - - - Blog Name - - - - - - - - - - Popularity - - - - - - - true - - - - - - - Last Post - - - - - - - true - - - - - - - Blog ID - - - - - - - - - - Blog Description - - - - - - - - - - - - - - - - - - - - - Qt::Horizontal - - - - 311 - 20 - - - - - - - - Cancel - - - - - - - OK - - - false - - - true - - - - - - - - - - - - diff --git a/retroshare-gui/src/gui/unfinished/blogs/BlogsDialog.cpp b/retroshare-gui/src/gui/unfinished/blogs/BlogsDialog.cpp deleted file mode 100644 index cc7eeb77a..000000000 --- a/retroshare-gui/src/gui/unfinished/blogs/BlogsDialog.cpp +++ /dev/null @@ -1,588 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2008 Robert Fernie - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - -#include -#include -#include - -#include - -#include -#include //to retrieve peer/usrId info - -#include "BlogsDialog.h" - -#include "BlogsMsgItem.h" -#include "CreateBlog.h" -#include "CreateBlogMsg.h" -#include "BlogDetails.h" - -#include "gui/ChanGroupDelegate.h" - -#define BLOG_DEFAULT_IMAGE ":/images/hi64-app-kblogger.png" - -/** Constructor */ -BlogsDialog::BlogsDialog(QWidget *parent) -: MainPage (parent) -{ - /* Invoke the Qt Designer generated object setup routine */ - setupUi(this); - - connect(actionCreate_Blog, SIGNAL(triggered()), this, SLOT(createBlog())); - connect(postButton, SIGNAL(clicked()), this, SLOT(createMsg())); - connect(subscribeButton, SIGNAL( clicked( void ) ), this, SLOT( subscribeBlog ( void ) ) ); - connect(unsubscribeButton, SIGNAL( clicked( void ) ), this, SLOT( unsubscribeBlog ( void ) ) ); - - connect(treeView, SIGNAL(clicked(const QModelIndex &)), this, SLOT(selectBlog(const QModelIndex &))); - connect(treeView, SIGNAL(activated(const QModelIndex &)), this, SLOT(toggleSelection(const QModelIndex &))); - connect(treeView, SIGNAL(customContextMenuRequested( QPoint ) ), this, SLOT( blogListCustomPopupMenu( QPoint ) ) ); - - mBlogId = ""; - mPeerId = rsPeers->getOwnId(); // add your id - - model = new QStandardItemModel(0, 2, this); - model->setHeaderData(0, Qt::Horizontal, tr("Name"), Qt::DisplayRole); - model->setHeaderData(1, Qt::Horizontal, tr("ID"), Qt::DisplayRole); - - treeView->setModel(model); - treeView->setEditTriggers(QAbstractItemView::NoEditTriggers); - - treeView->setItemDelegate(new ChanGroupDelegate()); - - // hide header and id column - treeView->setHeaderHidden(true); - treeView->hideColumn(1); - - itemFont = QFont("ARIAL", 10); - itemFont.setBold(true); - - QStandardItem *OwnBlogs = new QStandardItem(tr("My Blogs")); - OwnBlogs->setForeground(QBrush(QColor(79, 79, 79))); - OwnBlogs->setFont(itemFont); - - QStandardItem *SubscribedBlogs = new QStandardItem(tr("Subscribed Blogs")); - SubscribedBlogs->setForeground(QBrush(QColor(79, 79, 79))); - SubscribedBlogs->setFont(itemFont); - - QStandardItem *PopularBlogs = new QStandardItem(tr("Popular Blogs")); - PopularBlogs->setForeground(QBrush(QColor(79, 79, 79))); - PopularBlogs->setFont(itemFont); - - QStandardItem *OtherBlogs = new QStandardItem(tr("Other Blogs")); - OtherBlogs->setForeground(QBrush(QColor(79, 79, 79))); - OtherBlogs->setFont(itemFont); - - model->appendRow(OwnBlogs); - model->appendRow(SubscribedBlogs); - model->appendRow(PopularBlogs); - model->appendRow(OtherBlogs); - - //added from ahead - updateBlogList(); - - mBlogFont = QFont("MS SANS SERIF", 22); - nameLabel->setFont(mBlogFont); - nameLabel->setMinimumWidth(20); - - QMenu *blogmenu = new QMenu(); - blogmenu->addAction(actionCreate_Blog); - blogmenu->addSeparator(); - blogpushButton->setMenu(blogmenu); - - QTimer *timer = new QTimer(this); - timer->connect(timer, SIGNAL(timeout()), this, SLOT(checkUpdate())); - timer->start(1000); -} - -void BlogsDialog::blogListCustomPopupMenu( QPoint point ) -{ - BlogInfo bi; - if (!rsBlogs->getBlogInfo(mBlogId, bi)) - { - return; - } - - QMenu contextMnu( this ); - - QAction *createblogpostAct = new QAction(QIcon(":/images/mail_reply.png"), tr( "Post to Blog" ), this ); - connect( createblogpostAct , SIGNAL( triggered() ), this, SLOT( createMsg() ) ); - - QAction *subscribeblogAct = new QAction(QIcon(":/images/edit_add24.png"), tr( "Subscribe to Blog" ), this ); - connect( subscribeblogAct , SIGNAL( triggered() ), this, SLOT( subscribeBlog() ) ); - - QAction *unsubscribeblogAct = new QAction(QIcon(":/images/cancel.png"), tr( "Unsubscribe to Blog" ), this ); - connect( unsubscribeblogAct , SIGNAL( triggered() ), this, SLOT( unsubscribeBlog() ) ); - - QAction *blogdetailsAct = new QAction(QIcon(":/images/info16.png"), tr( "Show Blog Details" ), this ); - connect( blogdetailsAct , SIGNAL( triggered() ), this, SLOT( showBlogDetails() ) ); - - contextMnu.clear(); - - if (bi.blogFlags & RS_DISTRIB_PUBLISH) - { - contextMnu.addAction( createblogpostAct ); - contextMnu.addSeparator(); - contextMnu.addAction( blogdetailsAct ); - } - else if (bi.blogFlags & RS_DISTRIB_SUBSCRIBED) - { - contextMnu.addAction( unsubscribeblogAct ); - contextMnu.addSeparator(); - contextMnu.addAction( blogdetailsAct );; - } - else - { - contextMnu.addAction( subscribeblogAct ); - contextMnu.addSeparator(); - contextMnu.addAction( blogdetailsAct ); - } - - contextMnu.exec(QCursor::pos()); -} - -void BlogsDialog::createBlog() -{ - CreateBlog cf (this, false); - - cf.setWindowTitle(tr("Create a new Blog")); - cf.exec(); -} - -void BlogsDialog::blogSelection() -{ - /* which item was selected? */ - - - /* update mBlogId */ - - updateBlogMsgs(); -} - - -/*************************************************************************************/ -/*************************************************************************************/ -/*************************************************************************************/ - -void BlogsDialog::deleteFeedItem(QWidget *item, uint32_t type) -{ - return; -} - -void BlogsDialog::openChat(std::string peerId) -{ - return; -} - -void BlogsDialog::createMsg() -{ - if (mBlogId == "") - { - return; - } - - CreateBlogMsg *msgDialog = new CreateBlogMsg(mBlogId); - - msgDialog->show(); - - /* window will destroy itself! */ -} - -void BlogsDialog::selectBlog( std::string bId) -{ - mBlogId = bId; - - updateBlogMsgs(); -} - -void BlogsDialog::selectBlog(const QModelIndex &index) -{ - int row = index.row(); - int col = index.column(); - if (col != 1) { - QModelIndex sibling = index.sibling(row, 1); - if (sibling.isValid()) - mBlogId = sibling.data().toString().toStdString(); - } else - mBlogId = index.data().toString().toStdString(); - updateBlogMsgs(); -} - -void BlogsDialog::checkUpdate() -{ - std::list blogIds; - std::list::iterator it; - if (!rsBlogs) - return; - - if (rsBlogs->blogsChanged(blogIds)) - { - /* update Blogs List */ - updateBlogList(); - - it = std::find(blogIds.begin(), blogIds.end(), mBlogId); - if (it != blogIds.end()) - { - updateBlogMsgs(); - } - } -} - -void BlogsDialog::updateBlogList() -{ - - std::list channelList; - std::list::iterator it; - if (!rsBlogs) - { - return; - } - - rsBlogs->getBlogList(channelList); - - /* get the ids for our lists */ - std::list adminIds; - std::list subIds; - std::list popIds; - std::list otherIds; - std::multimap popMap; - - for(it = channelList.begin(); it != channelList.end(); it++) - { - /* sort it into Publish (Own), Subscribed, Popular and Other */ - uint32_t flags = it->blogFlags; - - if (flags & RS_DISTRIB_ADMIN) - { - adminIds.push_back(it->blogId); - } - else if (flags & RS_DISTRIB_SUBSCRIBED) - { - subIds.push_back(it->blogId); - } - else - { - /* rate the others by popularity */ - popMap.insert(std::make_pair(it->pop, it->blogId)); - } - } - - /* iterate backwards through popMap - take the top 5 or 10% of list */ - uint32_t popCount = 5; - if (popCount < popMap.size() / 10) - { - popCount = popMap.size() / 10; - } - - uint32_t i = 0; - std::multimap::reverse_iterator rit; - for(rit = popMap.rbegin(); rit != popMap.rend(); rit++) - { - if(i < popCount){ - popIds.push_back(rit->second); - i++; - }else{ - otherIds.push_back(rit->second); - } - } - - /* now we have our lists ---> update entries */ - - updateBlogListOwn(adminIds); - updateBlogListSub(subIds); - updateBlogListPop(popIds); - updateBlogListOther(otherIds); -} - -void BlogsDialog::updateBlogListOwn(std::list &ids) -{ - std::list::iterator iit; - - /* remove rows with groups before adding new ones */ - model->item(OWN)->removeRows(0, model->item(OWN)->rowCount()); - - for (iit = ids.begin(); iit != ids.end(); iit ++) { -#ifdef BLOG_DEBUG - std::cerr << "BlogsDialog::updateBlogListOwn(): " << *iit << std::endl; -#endif - QStandardItem *ownGroup = model->item(OWN); - QList blog; - QStandardItem *blogNameitem = new QStandardItem(); - QStandardItem *blogIditem = new QStandardItem(); - - BlogInfo bi; - if (rsBlogs && rsBlogs->getBlogInfo(*iit, bi)) { - blogNameitem->setData(QVariant(QString::fromStdWString(bi.blogName)), Qt::DisplayRole); - blogIditem->setData(QVariant(QString::fromStdString(bi.blogId)), Qt::DisplayRole); - blogNameitem->setToolTip(tr("Popularity: %1\nFetches: %2\nAvailable: %3" - ).arg(QString::number(bi.pop)).arg(9999).arg(9999)); - } else { - blogNameitem->setData(QVariant(QString("Unknown Blog")), Qt::DisplayRole); - blogIditem->setData(QVariant(QString::fromStdString(*iit)), Qt::DisplayRole); - blogNameitem->setToolTip("Unknown Blog\nNo Description"); - } - - blog.append(blogNameitem); - blog.append(blogIditem); - ownGroup->appendRow(blog); - } -} - -void BlogsDialog::updateBlogListSub(std::list &ids) -{ - std::list::iterator iit; - - /* remove rows with groups before adding new ones */ - model->item(SUBSCRIBED)->removeRows(0, model->item(SUBSCRIBED)->rowCount()); - - for (iit = ids.begin(); iit != ids.end(); iit ++) { -#ifdef BLOG_DEBUG - std::cerr << "BlogsDialog::updateBlogListSub(): " << *iit << std::endl; -#endif - QStandardItem *ownGroup = model->item(SUBSCRIBED); - QList blog; - QStandardItem *blogNameitem = new QStandardItem(); - QStandardItem *blogIditem = new QStandardItem(); - - BlogInfo bi; - if (rsBlogs && rsBlogs->getBlogInfo(*iit, bi)) { - blogNameitem->setData(QVariant(QString::fromStdWString(bi.blogName)), Qt::DisplayRole); - blogIditem->setData(QVariant(QString::fromStdString(bi.blogId)), Qt::DisplayRole); - blogNameitem->setToolTip(tr("Popularity: %1\nFetches: %2\nAvailable: %3" - ).arg(QString::number(bi.pop)).arg(9999).arg(9999)); - } else { - blogNameitem->setData(QVariant(QString("Unknown Blog")), Qt::DisplayRole); - blogIditem->setData(QVariant(QString::fromStdString(*iit)), Qt::DisplayRole); - blogNameitem->setToolTip("Unknown Blog\nNo Description"); - } - - blog.append(blogNameitem); - blog.append(blogIditem); - ownGroup->appendRow(blog); - } - -} - -void BlogsDialog::updateBlogListPop(std::list &ids) -{ - std::list::iterator iit; - - /* remove rows with groups before adding new ones */ - model->item(POPULAR)->removeRows(0, model->item(POPULAR)->rowCount()); - - for (iit = ids.begin(); iit != ids.end(); iit ++) { -#ifdef BLOG_DEBUG - std::cerr << "BlogsDialog::updateBlogListPop(): " << *iit << std::endl; -#endif - QStandardItem *ownGroup = model->item(POPULAR); - QList blog; - QStandardItem *blogNameitem = new QStandardItem(); - QStandardItem *blogIditem = new QStandardItem(); - - BlogInfo bi; - if (rsBlogs && rsBlogs->getBlogInfo(*iit, bi)) { - blogNameitem->setData(QVariant(QString::fromStdWString(bi.blogName)), Qt::DisplayRole); - blogIditem->setData(QVariant(QString::fromStdString(bi.blogId)), Qt::DisplayRole); - blogNameitem->setToolTip(tr("Popularity: %1\nFetches: %2\nAvailable: %3" - ).arg(QString::number(bi.pop)).arg(9999).arg(9999)); - } else { - blogNameitem->setData(QVariant(QString("Unknown Blog")), Qt::DisplayRole); - blogIditem->setData(QVariant(QString::fromStdString(*iit)), Qt::DisplayRole); - blogNameitem->setToolTip("Unknown Blog\nNo Description"); - } - - blog.append(blogNameitem); - blog.append(blogIditem); - ownGroup->appendRow(blog); - } -} - -void BlogsDialog::updateBlogListOther(std::list &ids) -{ - std::list::iterator iit; - - /* remove rows with groups before adding new ones */ - model->item(OTHER)->removeRows(0, model->item(OTHER)->rowCount()); - - for (iit = ids.begin(); iit != ids.end(); iit ++) { -#ifdef BLOG_DEBUG - std::cerr << "BlogsDialog::updateBlogListOther(): " << *iit << std::endl; -#endif - QStandardItem *ownGroup = model->item(OTHER); - QList blog; - QStandardItem *blogNameitem = new QStandardItem(); - QStandardItem *blogIditem = new QStandardItem(); - - BlogInfo bi; - if (rsBlogs && rsBlogs->getBlogInfo(*iit, bi)) { - blogNameitem->setData(QVariant(QString::fromStdWString(bi.blogName)), Qt::DisplayRole); - blogIditem->setData(QVariant(QString::fromStdString(bi.blogId)), Qt::DisplayRole); - blogNameitem->setToolTip(tr("Popularity: %1\nFetches: %2\nAvailable: %3" - ).arg(QString::number(bi.pop)).arg(9999).arg(9999)); - } else { - blogNameitem->setData(QVariant(QString("Unknown Blog")), Qt::DisplayRole); - blogIditem->setData(QVariant(QString::fromStdString(*iit)), Qt::DisplayRole); - blogNameitem->setToolTip("Unknown Blog\nNo Description"); - } - - blog.append(blogNameitem); - blog.append(blogIditem); - ownGroup->appendRow(blog); - } -} - -void BlogsDialog::updateBlogMsgs() -{ - if (!rsBlogs) - return; - - BlogInfo bi; - if (!rsBlogs->getBlogInfo(mBlogId, bi)) - { - postButton->setEnabled(false); - subscribeButton->setEnabled(false); - unsubscribeButton->setEnabled(false); - nameLabel->setText("No Blog Selected"); - iconLabel->setPixmap(QPixmap(":/images/hi64-app-kblogger.png")); - iconLabel->setEnabled(false); - frame->setStyleSheet("QFrame#frame{ border: 2px solid #808080;border-radius: 10px;background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1,stop:0 #C0C0C0, stop:1 #A0A0A0); }"); - return; - } - - if(bi.pngImageLen != 0){ - - QPixmap blogImage; - blogImage.loadFromData(bi.pngChanImage, bi.pngImageLen, "PNG"); - iconLabel->setPixmap(blogImage); - iconLabel->setStyleSheet("QLabel{border: 2px solid white;}"); - }else{ - QPixmap defaultImage(BLOG_DEFAULT_IMAGE); - iconLabel->setPixmap(defaultImage); - iconLabel->setStyleSheet("QLabel{border: 2px solid white;border-radius: 10px;}"); - } - - iconLabel->setEnabled(true); - - - /* set textcolor for Blog name */ - QString blogStr("%1"); - - /* set Blog name */ - QString bname = QString::fromStdWString(bi.blogName); - nameLabel->setText(blogStr.arg(bname)); - - /* do buttons */ - if (bi.blogFlags & RS_DISTRIB_SUBSCRIBED) - { - subscribeButton->setEnabled(false); - unsubscribeButton->setEnabled(true); - frame->setStyleSheet("QFrame#frame{ border: 2px solid #FF0000;border-radius: 10px;background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1,stop:0 #B61407, stop:1 #A91106); }"); - - } - else - { - subscribeButton->setEnabled(true); - unsubscribeButton->setEnabled(false); - frame->setStyleSheet("QFrame#frame{ border: 2px solid #267F00;border-radius: 10px;background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1,stop:0 #89D51D, stop:1 #579E10); }"); - } - - if (bi.blogFlags & RS_DISTRIB_PUBLISH) - { - postButton->setEnabled(true); - frame->setStyleSheet("QFrame#frame{ border: 2px solid #6ACEFF;border-radius: 10px;background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1,stop:0 #0076B1, stop:1 #12A3EB); }"); - } - else - { - postButton->setEnabled(false); - } - - /* replace all the messages with new ones */ - std::list::iterator mit; - for(mit = mBlogMsgItems.begin(); mit != mBlogMsgItems.end(); mit++) - { - delete (*mit); - } - mBlogMsgItems.clear(); - - std::list msgs; - std::list::iterator it; - - rsBlogs->getBlogMsgList(mBlogId, msgs); - - for(it = msgs.begin(); it != msgs.end(); it++) - { - BlogsMsgItem *cmi = new BlogsMsgItem(this, 0, mPeerId, mBlogId, it->msgId, true); - - mBlogMsgItems.push_back(cmi); - verticalLayout_2->addWidget(cmi); - } -} - -void BlogsDialog::unsubscribeBlog() -{ -#ifdef BLOG_DEBUG - std::cerr << "BlogsDialog::unsubscribeBlog()"; - std::cerr << std::endl; -#endif - if (rsBlogs) - { - rsBlogs->blogSubscribe(mBlogId, false); - } - updateBlogMsgs(); -} - -void BlogsDialog::subscribeBlog() -{ -#ifdef BLOG_DEBUG - std::cerr << "BlogsDialog::subscribeBlog()"; - std::cerr << std::endl; -#endif - if (rsBlogs) - { - rsBlogs->blogSubscribe(mBlogId, true); - } - updateBlogMsgs(); -} - -void BlogsDialog::toggleSelection(const QModelIndex &index) -{ - QItemSelectionModel *selectionModel = treeView->selectionModel(); - if (index.child(0, 0).isValid()) - selectionModel->select(index, QItemSelectionModel::Toggle); -} - -void BlogsDialog::showBlogDetails() -{ - if (mBlogId == "") - { - return; - } - - if (!rsBlogs) - return; - - BlogDetails *blogui = new BlogDetails(); - - blogui->showDetails(mBlogId); - blogui->show(); - - /* window will destroy itself! */ -} diff --git a/retroshare-gui/src/gui/unfinished/blogs/BlogsDialog.h b/retroshare-gui/src/gui/unfinished/blogs/BlogsDialog.h deleted file mode 100644 index 2366d317b..000000000 --- a/retroshare-gui/src/gui/unfinished/blogs/BlogsDialog.h +++ /dev/null @@ -1,107 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2008 Robert Fernie - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - -#ifndef _BLOGSDIALOG_H -#define _BLOGSDIALOG_H - -#include "gui/mainpage.h" -#include "ui_BlogsDialog.h" - -#include "gui/feeds/FeedHolder.h" - -class QStandardItemModel; - -#define OWN 0 -#define SUBSCRIBED 1 -#define POPULAR 2 -#define OTHER 3 - -class BlogsMsgItem; - - -class BlogsDialog : public MainPage, public FeedHolder, private Ui::BlogsDialog -{ - Q_OBJECT - -public: - /** Default Constructor */ - BlogsDialog(QWidget *parent = 0); - /** Default Destructor */ - - -virtual void deleteFeedItem(QWidget *item, uint32_t type); -virtual void openChat(std::string peerId); - -public slots: - - void selectBlog( std::string ); - void selectBlog(const QModelIndex &); - void toggleSelection(const QModelIndex &); - -private slots: - - void blogListCustomPopupMenu( QPoint point ); - - void checkUpdate(); - - void createBlog(); - //void sendMsg(); - - void blogSelection(); - - void subscribeBlog(); - void unsubscribeBlog(); - - void createMsg(); - - void showBlogDetails(); - -private: - - void updateBlogList(); - void updateBlogListOwn(std::list &ids); - void updateBlogListSub(std::list &ids); - void updateBlogListPop(std::list &ids); - void updateBlogListOther(std::list &ids); - - void updateBlogMsgs(); - - QStandardItemModel *model; - - std::string mBlogId; /* current Blog */ - std::string mPeerId; - - /* Layout Pointers */ - QBoxLayout *mMsgLayout; - - - - std::list mBlogMsgItems; - - QFont mBlogFont; - QFont itemFont; - -}; - - - -#endif - diff --git a/retroshare-gui/src/gui/unfinished/blogs/BlogsDialog.ui b/retroshare-gui/src/gui/unfinished/blogs/BlogsDialog.ui deleted file mode 100644 index 6d1cc316f..000000000 --- a/retroshare-gui/src/gui/unfinished/blogs/BlogsDialog.ui +++ /dev/null @@ -1,568 +0,0 @@ - - - BlogsDialog - - - - 0 - 0 - 681 - 476 - - - - - 0 - 0 - - - - - 0 - 0 - - - - Form - - - - - - - 0 - 0 - - - - - 222 - 0 - - - - - 222 - 16777215 - - - - - 0 - 0 - - - - - 221 - 0 - - - - QFrame::StyledPanel - - - QFrame::Raised - - - - 0 - - - 0 - - - - - - 220 - 0 - - - - - 220 - 38 - - - - - 220 - 0 - - - - QFrame#chheaderframe{ -background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, - stop:0 #FEFEFE, stop:1 #E8E8E8); - -border: 1px solid #CCCCCC;} - - - - - QFrame::StyledPanel - - - QFrame::Raised - - - - 2 - - - - - 0 - - - - - - 24 - 24 - - - - - - - :/images/kblogger.png - - - true - - - - - - - <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> -<html><head><meta name="qrichtext" content="1" /><style type="text/css"> -p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Arial'; font-size:10pt; font-weight:600;">Blogs</span></p></body></html> - - - - - - - - - Qt::Horizontal - - - - 123 - 13 - - - - - - - - Add - - - QPushButton::menu-indicator { - subcontrol-origin: padding; - subcontrol-position: bottom right; - } - - QPushButton::menu-indicator:pressed, QPushButton::menu-indicator:open { - position: relative; - top: 2px; left: 2px; /* shift the arrow by 2 px */ - } - - QPushButton:hover { - border: 1px solid #CCCCCC; - } - - - - - - - :/images/edit_add24.png:/images/edit_add24.png - - - - 16 - 16 - - - - false - - - true - - - - - - - - 0 - 0 - - - - - 0 - 25 - - - - <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> -<html><head><meta name="qrichtext" content="1" /><style type="text/css"> -p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Post To Blog</span></p></body></html> - - - - - - - - - - :/images/mail_send.png:/images/mail_send.png - - - true - - - - - - - - - - Qt::CustomContextMenu - - - - - - - - - - - - QFrame#frame{ -border: 2px solid #6ACEFF; -border-radius: 10px; -background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, - stop:0 #0076B1, stop:1 #12A3EB);} - - - QFrame::StyledPanel - - - QFrame::Raised - - - - 0 - - - 0 - - - - - 16 - - - 9 - - - - - - 64 - 64 - - - - - 64 - 64 - - - - QLabel{ -border: 2px solid white; -border-radius: 10px; -} - - - - - - :/images/hi64-app-kblogger.png - - - false - - - Qt::AlignCenter - - - - - - - - 75 - true - - - - - - - <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> -<html><head><meta name="qrichtext" content="1" /><style type="text/css"> -p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:600; font-style:normal;"> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'DejaVu Sans'; font-size:14pt; color:#ffffff;">Blog Name</span></p></body></html> - - - true - - - - - - - - - 9 - - - 9 - - - - - - 0 - 0 - - - - - 26 - 26 - - - - <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> -<html><head><meta name="qrichtext" content="1" /><style type="text/css"> -p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'MS Shell Dlg 2'; font-weight:400; font-style:normal;"> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:9pt;">Unsubscribe To Blog</span></p></body></html> - - - QToolButton, QPushButton, QComboBox { -border-image: url(:/images/btn_26.png) 4; -border-width: 4; -padding: 0px 6px; -font-size: 12px; -} - -QToolButton:hover, QPushButton:hover, QComboBox:hover { -border-image: url(:/images/btn_26_hover.png) 4; -} - -QToolButton:disabled, QPushButton:disabled, QComboBox::disabled { -color:gray; -} - -QToolButton:pressed, QPushButton:pressed{ -border-image: url(:/images/btn_26_pressed.png) 4; -} - - - Unsubscribe - - - - - - - - 0 - 0 - - - - - 26 - 26 - - - - - 16777215 - 26 - - - - <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> -<html><head><meta name="qrichtext" content="1" /><style type="text/css"> -p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'MS Shell Dlg 2'; font-weight:400; font-style:normal;"> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:9pt;">Subscribe To Blog</span></p></body></html> - - - QToolButton, QPushButton, QComboBox { -border-image: url(:/images/btn_26.png) 4; -border-width: 4; -padding: 0px 6px; -font-size: 12px; -} - -QToolButton:hover, QPushButton:hover, QComboBox:hover { -border-image: url(:/images/btn_26_hover.png) 4; -} - -QToolButton:disabled, QPushButton:disabled, QComboBox::disabled { -color:gray; -} - -QToolButton:pressed, QPushButton:pressed{ -border-image: url(:/images/btn_26_pressed.png) 4; -} - - - Subscribe - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - - - - 1 - 0 - - - - - 0 - 0 - - - - - - - QFrame::StyledPanel - - - QFrame::Raised - - - - 0 - - - 0 - - - - - true - - - Qt::AlignBottom|Qt::AlignLeading|Qt::AlignLeft - - - - - 0 - 0 - 429 - 332 - - - - QWidget#scrollAreaWidgetContents{border: none;} - - - - 0 - - - 0 - - - - - - - - Qt::Vertical - - - - 391 - 266 - - - - - - - - - - - - - - - - - - :/images/kblogger.png:/images/kblogger.png - - - Create New Blog - - - Create New Blog - - - - - - - - diff --git a/retroshare-gui/src/gui/unfinished/blogs/BlogsMsgItem.cpp b/retroshare-gui/src/gui/unfinished/blogs/BlogsMsgItem.cpp deleted file mode 100644 index beba2bb87..000000000 --- a/retroshare-gui/src/gui/unfinished/blogs/BlogsMsgItem.cpp +++ /dev/null @@ -1,192 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2008 Robert Fernie - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - -#include - -#include "BlogsMsgItem.h" -#include "gui/feeds/FeedHolder.h" - -#include -#include "rshare.h" - -/**** - * #define DEBUG_ITEM 1 - ****/ - -/** Constructor */ -BlogsMsgItem::BlogsMsgItem(FeedHolder *parent, uint32_t feedId, std::string peerId, std::string blogId, std::string msgId, bool isHome) -:QWidget(NULL), mParent(parent), mFeedId(feedId), - mPeerId(peerId), mBlogId(blogId), mMsgId(msgId), mIsHome(isHome) -{ - /* Invoke the Qt Designer generated object setup routine */ - setupUi(this); - - /* general ones */ - connect( expandButton, SIGNAL( clicked( void ) ), this, SLOT( toggle ( void ) ) ); - connect( clearButton, SIGNAL( clicked( void ) ), this, SLOT( removeItem ( void ) ) ); - //connect( gotoButton, SIGNAL( clicked( void ) ), this, SLOT( gotoHome ( void ) ) ); - - /* specific ones */ - //connect( playButton, SIGNAL( clicked( void ) ), this, SLOT( playMedia ( void ) ) ); - connect( unsubscribeButton, SIGNAL( clicked( void ) ), this, SLOT( unsubscribeChannel ( void ) ) ); - - small(); - updateItemStatic(); - updateItem(); - -} - - -void BlogsMsgItem::updateItemStatic() -{ - /* fill in */ -#ifdef DEBUG_ITEM - std::cerr << "ChanMsgItem::updateItemStatic()"; - std::cerr << std::endl; -#endif - - BlogMsgInfo cmi; - - if (!rsBlogs) - return; - - if (!rsBlogs->getBlogMessage(mBlogId, mMsgId, cmi)) - return; - - QString title; - - if (!mIsHome) - { - BlogInfo ci; - rsBlogs->getBlogInfo(mBlogId, ci); - title = "Channel Feed: "; - title += QString::fromStdWString(ci.blogName); - titleLabel->setText(title); - //subjectLabel->setText(QString::fromStdWString(cmi.subject)); - } - else - { - /* subject */ - titleLabel->setText(QString::fromStdWString(cmi.subject)); - /* Blog Message */ - textBrowser->setHtml( QString::fromStdWString(cmi.msg)); - } - - //msgLabel->setText(QString::fromStdWString(cmi.msg)); - //msgcommentstextEdit->setHtml(QString::fromStdWString(cmi.msg)); - - datetimelabel->setText(Rshare::customDate(cmi.ts)); - - //playButton->setEnabled(false); - - if (mIsHome) - { - /* disable buttons */ - clearButton->setEnabled(false); - //gotoButton->setEnabled(false); - unsubscribeButton->setEnabled(false); - - clearButton->hide(); - } - - /* don't really want this at all! */ - unsubscribeButton->hide(); - //playButton->hide(); -} - - -void BlogsMsgItem::updateItem() -{ - /* fill in */ -#ifdef DEBUG_ITEM - std::cerr << "BlogMsgItem::updateItem()"; - std::cerr << std::endl; -#endif - - -} - - -void BlogsMsgItem::small() -{ - expandFrame->hide(); -} - -void BlogsMsgItem::toggle() -{ - if (expandFrame->isHidden()) - { - expandFrame->show(); - expandButton->setIcon(QIcon(QString(":/images/edit_remove24.png"))); - expandButton->setToolTip(tr("Hide")); - } - else - { - expandFrame->hide(); - expandButton->setIcon(QIcon(QString(":/images/edit_add24.png"))); - expandButton->setToolTip(tr("Expand")); - } -} - - -void BlogsMsgItem::removeItem() -{ -#ifdef DEBUG_ITEM - std::cerr << "ChanMsgItem::removeItem()"; - std::cerr << std::endl; -#endif - hide(); - if (mParent) - { - mParent->deleteFeedItem(this, mFeedId); - } -} - - -void BlogsMsgItem::gotoHome() -{ -#ifdef DEBUG_ITEM - std::cerr << "ChanMsgItem::gotoHome()"; - std::cerr << std::endl; -#endif -} - -/*********** SPECIFIC FUNCTIOSN ***********************/ - - -void BlogsMsgItem::unsubscribeChannel() -{ -#ifdef DEBUG_ITEM - std::cerr << "ChanMsgItem::unsubscribeChannel()"; - std::cerr << std::endl; -#endif -} - - -void BlogsMsgItem::playMedia() -{ -#ifdef DEBUG_ITEM - std::cerr << "ChanMsgItem::playMedia()"; - std::cerr << std::endl; -#endif -} - - diff --git a/retroshare-gui/src/gui/unfinished/blogs/BlogsMsgItem.h b/retroshare-gui/src/gui/unfinished/blogs/BlogsMsgItem.h deleted file mode 100644 index ee307daae..000000000 --- a/retroshare-gui/src/gui/unfinished/blogs/BlogsMsgItem.h +++ /dev/null @@ -1,71 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2008 Robert Fernie - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - -#ifndef _BLOGS_MSG_ITEM_DIALOG_H -#define _BLOGS_MSG_ITEM_DIALOG_H - -#include "ui_BlogsMsgItem.h" -#include - - -class FeedHolder; -class SubFileItem; - -class BlogsMsgItem : public QWidget, private Ui::BlogsMsgItem -{ - Q_OBJECT - -public: - /** Default Constructor */ - BlogsMsgItem(FeedHolder *parent, uint32_t feedId, std::string peerId, std::string blogId, std::string msgId, bool isHome); - - /** Default Destructor */ - - void updateItemStatic(); - void small(); - -private slots: - /* default stuff */ - void gotoHome(); - void removeItem(); - void toggle(); - - void playMedia(); - void unsubscribeChannel(); - - void updateItem(); - -private: - FeedHolder *mParent; - uint32_t mFeedId; - - std::string mBlogId; - std::string mMsgId; - std::string mPeerId; - - bool mIsHome; - -}; - - - -#endif - diff --git a/retroshare-gui/src/gui/unfinished/blogs/BlogsMsgItem.ui b/retroshare-gui/src/gui/unfinished/blogs/BlogsMsgItem.ui deleted file mode 100644 index 4972df312..000000000 --- a/retroshare-gui/src/gui/unfinished/blogs/BlogsMsgItem.ui +++ /dev/null @@ -1,274 +0,0 @@ - - - BlogsMsgItem - - - - 0 - 0 - 516 - 294 - - - - Form - - - QToolButton, QPushButton, QComboBox { -border-image: url(:/images/btn_26.png) 4; -border-width: 4; -padding: 0px 6px; -font-size: 12px; -} - -QToolButton:hover, QPushButton:hover, QComboBox:hover { -border-image: url(:/images/btn_26_hover.png) 4; -} - -QToolButton:disabled, QPushButton:disabled, QComboBox::disabled { -color:gray; -} - -QToolButton:pressed, QPushButton:pressed{ -border-image: url(:/images/btn_26_pressed.png) 4; -} - - - - 0 - - - 6 - - - - - - 0 - 0 - - - - QFrame#frame{border: 3px solid #407AC1; -background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, -stop:0 #FFFFFF, stop:1 #F2F2F2);; -border-radius: 10px;} - - - QFrame::StyledPanel - - - QFrame::Raised - - - - - - - - - 0 - 0 - - - - - 11 - 75 - true - true - - - - <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> -<html><head><meta name="qrichtext" content="1" /><style type="text/css"> -p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:11pt; font-weight:600; font-style:italic;"> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" color:#656565;">Blog Subject</span></p></body></html> - - - - - - - - 75 - true - - - - <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> -<html><head><meta name="qrichtext" content="1" /><style type="text/css"> -p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:600; font-style:normal;"> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt; color:#666666;">DateTime</span></p></body></html> - - - - - - - Qt::Horizontal - - - QSizePolicy::Expanding - - - - 288 - 21 - - - - - - - - - 0 - 0 - - - - Expand - - - - - - - - - - :/images/edit_add24.png:/images/edit_add24.png - - - - - - - - 0 - 0 - - - - Remove Item - - - - - - - :/images/close_normal.png:/images/close_normal.png - - - - - - - - 0 - 0 - - - - Unsubscribe From Channel - - - - - - - :/images/mail_delete.png:/images/mail_delete.png - - - - - - - - 0 - 0 - - - - QTextBrowser#textBrowser{border: 2px solid #D3D3D3; -background-color: transparent; -border-radius: 10px;} - - - - - - - - - QFrame#expandFrame{border: 2px solid #D3D3D3; -background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, -stop:0 #FFFFFF, stop:1 #F2F2F2);; -border-radius: 10px;} - - - QFrame::StyledPanel - - - QFrame::Raised - - - - - - - 0 - 0 - - - - Comments here - - - - - - - - - - - 16777215 - 60 - - - - - - - - Qt::Horizontal - - - - 398 - 20 - - - - - - - - Comment - - - - - - - - - - - - - diff --git a/retroshare-gui/src/gui/unfinished/blogs/CreateBlog.cpp b/retroshare-gui/src/gui/unfinished/blogs/CreateBlog.cpp deleted file mode 100644 index 3798041af..000000000 --- a/retroshare-gui/src/gui/unfinished/blogs/CreateBlog.cpp +++ /dev/null @@ -1,173 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2008 Robert Fernie - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - -#include -#include - -#include "CreateBlog.h" -#include "util/misc.h" - -#include - -/** Constructor */ -CreateBlog::CreateBlog(QWidget *parent, bool isForum) -: QDialog(parent), mIsForum(isForum) -{ - /* Invoke the Qt Designer generated object setup routine */ - ui.setupUi(this); - - // connect up the buttons. - connect( ui.cancelButton, SIGNAL( clicked ( bool ) ), this, SLOT( cancelBlog( ) ) ); - connect( ui.createButton, SIGNAL( clicked ( bool ) ), this, SLOT( createBlog( ) ) ); - connect( ui.LogoButton, SIGNAL(clicked() ), this , SLOT(addBlogLogo())); - connect( ui.blogLogoButton, SIGNAL(clicked() ), this , SLOT(addBlogLogo())); - - newBlog(); - -} - -void CreateBlog::show() -{ - //loadSettings(); - if(!this->isVisible()) { - QWidget::show(); - - } -} - - -void CreateBlog::newBlog() -{ - - if (mIsForum) - { - /* enforce Public for the moment */ - ui.typePublic->setChecked(true); - - ui.typePrivate->setEnabled(false); - ui.typeEncrypted->setEnabled(false); - - ui.msgAnon->setChecked(true); - //ui.msgAuth->setEnabled(false); - } - else - { - /* enforce Private for the moment */ - ui.typePrivate->setChecked(true); - - ui.typePublic->setEnabled(false); - ui.typeEncrypted->setEnabled(false); - - ui.msgAnon->setChecked(true); - ui.msgAuth->setEnabled(false); - ui.msgGroupBox->hide(); - } -} - -void CreateBlog::createBlog() -{ - QString name = ui.forumName->text(); - QString desc = ui.forumDesc->toPlainText(); //toHtml(); - uint32_t flags = 0; - - if(name.isEmpty()) - { /* error message */ - QMessageBox::warning(this, tr("RetroShare"), - tr("Please add a Name"), - QMessageBox::Ok, QMessageBox::Ok); - - return; //Don't add a empty name!! - } - else - - if (ui.typePublic->isChecked()) - { - flags |= RS_DISTRIB_PUBLIC; - } - else if (ui.typePrivate->isChecked()) - { - flags |= RS_DISTRIB_PRIVATE; - } - else if (ui.typeEncrypted->isChecked()) - { - flags |= RS_DISTRIB_ENCRYPTED; - } - - if (ui.msgAuth->isChecked()) - { - flags |= RS_DISTRIB_AUTHEN_REQ; - } - else if (ui.msgAnon->isChecked()) - { - flags |= RS_DISTRIB_AUTHEN_ANON; - } - - QByteArray ba; - QBuffer buffer(&ba); - - if(!picture.isNull()){ - // send chan image - - buffer.open(QIODevice::WriteOnly); - picture.save(&buffer, "PNG"); // writes image into ba in PNG format - } - - if (rsBlogs) - { - rsBlogs->createBlog(name.toStdWString(), desc.toStdWString(), flags, - (unsigned char*) ba.data(), ba.size()); - } - - - close(); - return; -} - -void CreateBlog::addBlogLogo(){ - - QString fileName; - if (misc::getOpenFileName(this, RshareSettings::LASTDIR_IMAGES, tr("Load File"), tr("Pictures (*.png *.xpm *.jpg)"), fileName)) - { - picture = QPixmap(fileName).scaled(64,64, Qt::IgnoreAspectRatio,Qt::SmoothTransformation); - - // to show the selected - ui.blogLogoButton->setIcon(picture); - - std::cerr << "Sending avatar image down the pipe" << std::endl ; - - // send avatar down the pipe for other peers to get it. - QByteArray ba; - QBuffer buffer(&ba); - buffer.open(QIODevice::WriteOnly); - picture.save(&buffer, "PNG"); // writes image into ba in PNG format - - std::cerr << "Image size = " << ba.size() << std::endl ; - } - -} - -void CreateBlog::cancelBlog() -{ - close(); - return; -} - - diff --git a/retroshare-gui/src/gui/unfinished/blogs/CreateBlog.h b/retroshare-gui/src/gui/unfinished/blogs/CreateBlog.h deleted file mode 100644 index 842987053..000000000 --- a/retroshare-gui/src/gui/unfinished/blogs/CreateBlog.h +++ /dev/null @@ -1,60 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2008 Robert Fernie - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - -#ifndef _CREATE_BLOG_DIALOG_H -#define _CREATE_BLOG_DIALOG_H - -#include "ui_CreateBlog.h" - -class CreateBlog : public QDialog -{ - Q_OBJECT - -public: - CreateBlog(QWidget *parent = 0, bool isForum = true); - -void newBlog(); /* cleanup */ - - /** Qt Designer generated object */ - Ui::CreateBlog ui; - - QPixmap picture; - -public slots: - /** Overloaded QWidget.show */ - void show(); - -private slots: - - /* actions to take.... */ -void createBlog(); -void cancelBlog(); -void addBlogLogo(); - - -private: - - - bool mIsForum; -}; - -#endif - diff --git a/retroshare-gui/src/gui/unfinished/blogs/CreateBlog.ui b/retroshare-gui/src/gui/unfinished/blogs/CreateBlog.ui deleted file mode 100644 index 06e3c3f03..000000000 --- a/retroshare-gui/src/gui/unfinished/blogs/CreateBlog.ui +++ /dev/null @@ -1,329 +0,0 @@ - - - CreateBlog - - - - 0 - 0 - 534 - 545 - - - - Create new Blog - - - - :/images/rstray3.png:/images/rstray3.png - - - - 0 - - - 0 - - - - - - 16777215 - 64 - - - - QFrame#frame_2{background-image: url(:/images/connect/connectFriendBanner.png);} - - - QFrame::NoFrame - - - QFrame::Raised - - - - 6 - - - 6 - - - - - - 48 - 48 - - - - - - - - - - :/images/hi48-app-kblogger.png - - - true - - - - - - - color: rgb(255, 255, 255); - - - <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> -<html><head><meta name="qrichtext" content="1" /><style type="text/css"> -p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Arial'; font-size:24pt; font-weight:600; color:#ffffff;">New Blog</span></p></body></html> - - - - - - - - - - QFrame::NoFrame - - - QFrame::Raised - - - - - - - - Name - - - - - - - - - - - - Description - - - - - - - - - - Type: - - - - 0 - - - 6 - - - - - Public - Anyone can read and publish (Shared Publish Key) - - - - - - - Restricted - Anyone can read, limited publishing (Private Publish Key) - - - - - - - Private - (Private Publish Key required to view Messages) - - - - - - - - - - Allowed Messages - - - - 0 - - - 6 - - - - - Authenticated Messages - - - - - - - Anonymous Messages - - - - - - - - - - Blog Logo - - - - 6 - - - 6 - - - 6 - - - 2 - - - 6 - - - - - - - - 64 - 64 - - - - - 64 - 64 - - - - -border: 2px solid white; -border-radius: 10px; - - - - - - - - :/images/hi64-app-kblogger.png:/images/hi64-app-kblogger.png - - - - 64 - 64 - - - - - - - - Add Blog Logo - - - - :/images/add_image24.png:/images/add_image24.png - - - - - - - Qt::Horizontal - - - - 118 - 20 - - - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - Qt::Horizontal - - - - 238 - 20 - - - - - - - - Cancel - - - - - - - Create - - - true - - - - - - - - - - - - - - - diff --git a/retroshare-gui/src/gui/unfinished/blogs/CreateBlogMsg.cpp b/retroshare-gui/src/gui/unfinished/blogs/CreateBlogMsg.cpp deleted file mode 100644 index 201c0c971..000000000 --- a/retroshare-gui/src/gui/unfinished/blogs/CreateBlogMsg.cpp +++ /dev/null @@ -1,923 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2008 Robert Fernie - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "CreateBlogMsg.h" -#include "gui/msgs/textformat.h" -#include "util/misc.h" - -#include - -/** Constructor */ -CreateBlogMsg::CreateBlogMsg(std::string cId ,QWidget* parent, Qt::WFlags flags) -: mBlogId(cId), QMainWindow (parent, flags) -{ - /* Invoke the Qt Designer generated object setup routine */ - ui.setupUi(this); - - setAttribute ( Qt::WA_DeleteOnClose, true ); - - setupFileActions(); - setupEditActions(); - setupViewActions(); - setupInsertActions(); - setupParagraphActions(); - - setAcceptDrops(true); - setStartupText(); - - newBlogMsg(); - - ui.toolBar_2->addAction(ui.actionIncreasefontsize); - ui.toolBar_2->addAction(ui.actionDecreasefontsize); - ui.toolBar_2->addAction(ui.actionBlockquoute); - ui.toolBar_2->addAction(ui.actionOrderedlist); - ui.toolBar_2->addAction(ui.actionUnorderedlist); - ui.toolBar_2->addAction(ui.actionBlockquoute); - ui.toolBar_2->addAction(ui.actionCode); - ui.toolBar_2->addAction(ui.actionsplitPost); - - setupTextActions(); - - connect(ui.actionPublish, SIGNAL(triggered()), this, SLOT(sendMsg())); - connect(ui.actionNew, SIGNAL(triggered()), this, SLOT (fileNew())); - - connect(ui.actionIncreasefontsize, SIGNAL (triggered()), this, SLOT (fontSizeIncrease())); - connect(ui.actionDecreasefontsize, SIGNAL (triggered()), this, SLOT (fontSizeDecrease())); - connect(ui.actionBlockquoute, SIGNAL (triggered()), this, SLOT (blockQuote())); - connect(ui.actionCode, SIGNAL (triggered()), this, SLOT (toggleCode())); - connect(ui.actionsplitPost, SIGNAL (triggered()), this, SLOT (addPostSplitter())); - connect(ui.actionOrderedlist, SIGNAL (triggered()), this, SLOT (addOrderedList())); - connect(ui.actionUnorderedlist, SIGNAL (triggered()), this, SLOT (addUnorderedList())); - - //connect(webView, SIGNAL(loadFinished(bool)),this, SLOT(updateTextEdit())); - connect( ui.msgEdit, SIGNAL( textChanged(const QString &)), this, SLOT(updateTextEdit())); - - connect( ui.msgEdit, SIGNAL(currentCharFormatChanged(QTextCharFormat)), - this, SLOT(currentCharFormatChanged(QTextCharFormat))); - connect( ui.msgEdit, SIGNAL(cursorPositionChanged()), - this, SLOT(cursorPositionChanged())); - - QPalette palette = QApplication::palette(); - codeBackground = palette.color( QPalette::Active, QPalette::Midlight ); - - fontChanged(ui.msgEdit->font()); - colorChanged(ui.msgEdit->textColor()); - alignmentChanged(ui.msgEdit->alignment()); - - connect( ui.msgEdit->document(), SIGNAL(modificationChanged(bool)), - actionSave, SLOT(setEnabled(bool))); - connect( ui.msgEdit->document(), SIGNAL(modificationChanged(bool)), - this, SLOT(setWindowModified(bool))); - connect( ui.msgEdit->document(), SIGNAL(undoAvailable(bool)), - actionUndo, SLOT(setEnabled(bool))); - connect( ui.msgEdit->document(), SIGNAL(undoAvailable(bool)), - ui.actionUndo, SLOT(setEnabled(bool))); - connect( ui.msgEdit->document(), SIGNAL(redoAvailable(bool)), - actionRedo, SLOT(setEnabled(bool))); - - setWindowModified( ui.msgEdit->document()->isModified()); - actionSave->setEnabled( ui.msgEdit->document()->isModified()); - actionUndo->setEnabled( ui.msgEdit->document()->isUndoAvailable()); - ui.actionUndo->setEnabled( ui.msgEdit->document()->isUndoAvailable()); - actionRedo->setEnabled( ui.msgEdit->document()->isRedoAvailable()); - - connect(actionUndo, SIGNAL(triggered()), ui.msgEdit, SLOT(undo())); - connect(ui.actionUndo, SIGNAL(triggered()), ui.msgEdit, SLOT(undo())); - connect(actionRedo, SIGNAL(triggered()), ui.msgEdit, SLOT(redo())); - - actionCut->setEnabled(false); - actionCopy->setEnabled(false); - - connect(actionCut, SIGNAL(triggered()), ui.msgEdit, SLOT(cut())); - connect(actionCopy, SIGNAL(triggered()), ui.msgEdit, SLOT(copy())); - connect(actionPaste, SIGNAL(triggered()), ui.msgEdit, SLOT(paste())); - - connect(ui.msgEdit, SIGNAL(copyAvailable(bool)), actionCut, SLOT(setEnabled(bool))); - connect(ui.msgEdit, SIGNAL(copyAvailable(bool)), actionCopy, SLOT(setEnabled(bool))); - -#ifndef QT_NO_CLIPBOARD - connect(QApplication::clipboard(), SIGNAL(dataChanged()), this, SLOT(clipboardDataChanged())); -#endif - - //defaultCharFormat - defaultCharFormat = ui.msgEdit->currentCharFormat(); - - const QFont defaultFont = ui.msgEdit->document()->defaultFont(); - defaultCharFormat.setFont( defaultFont ); - defaultCharFormat.setForeground( ui.msgEdit->currentCharFormat().foreground() ); - defaultCharFormat.setProperty( QTextFormat::FontSizeAdjustment, QVariant( 0 ) ); - defaultCharFormat.setBackground( palette.color( QPalette::Active, - QPalette::Base ) ); - defaultCharFormat.setProperty( TextFormat::HasCodeStyle, QVariant( false ) ); - - //defaultBlockFormat - defaultBlockFormat = ui.msgEdit->textCursor().blockFormat(); - -} - - -void CreateBlogMsg::cancelMsg() -{ - std::cerr << "CreateBlogMsg::cancelMsg()"; - std::cerr << std::endl; - close(); - return; -} - -void CreateBlogMsg::newBlogMsg() -{ - - if (!rsBlogs) - return; - - BlogInfo ci; - if (!rsBlogs->getBlogInfo(mBlogId, ci)) - { - - return; - } - - ui.channelName->setText(QString::fromStdWString(ci.blogName)); - -} - - -void CreateBlogMsg::sendMsg() -{ - std::cerr << "CreateBlogMsg::sendMsg()"; - std::cerr << std::endl; - - /* construct message bits */ - std::wstring subject = ui.subjectEdit->text().toStdWString(); - std::wstring msg = ui.msgEdit->toHtml().toStdWString(); - - sendMessage(subject, msg); - -} - -void CreateBlogMsg::sendMessage(std::wstring subject, std::wstring msg) -{ - std::cerr << "CreateBlogMsg::sendMessage()" << std::endl; - - QString name = ui.subjectEdit->text(); - - if(name.isEmpty()) - { /* error message */ - QMessageBox::warning(this, tr("RetroShare"), - tr("Please add a Subject"), - QMessageBox::Ok, QMessageBox::Ok); - - return; //Don't add a empty Subject!! - } - else - - /* rsChannels */ - if (rsBlogs) - { - BlogMsgInfo msgInfo; - - msgInfo.blogId = mBlogId; - msgInfo.msgId = ""; - - msgInfo.subject = subject; - msgInfo.msg = msg; - msgInfo.msgIdReply = "nothing"; - rsBlogs->BlogMessageSend(msgInfo); - } - - close(); - return; - -} - -void CreateBlogMsg::fontSizeIncrease() -{ - if ( !( ui.msgEdit->textCursor().blockFormat().hasProperty( TextFormat::HtmlHeading ) && - ui.msgEdit->textCursor().blockFormat().intProperty( TextFormat::HtmlHeading ) ) ) { - QTextCharFormat format; - int idx = ui.msgEdit->currentCharFormat().intProperty( QTextFormat::FontSizeAdjustment ); - if ( idx < 3 ) { - format.setProperty( QTextFormat::FontSizeAdjustment, QVariant( ++idx ) ); - ui.msgEdit->textCursor().mergeCharFormat( format ); - } - } - ui.msgEdit->setFocus( Qt::OtherFocusReason ); -} - -void CreateBlogMsg::fontSizeDecrease() -{ - if ( !( ui.msgEdit->textCursor().blockFormat().hasProperty( TextFormat::HtmlHeading ) && - ui.msgEdit->textCursor().blockFormat().intProperty( TextFormat::HtmlHeading ) ) ) { - QTextCharFormat format; - int idx = ui.msgEdit->currentCharFormat().intProperty( QTextFormat::FontSizeAdjustment ); - if ( idx > -1 ) { - format.setProperty( QTextFormat::FontSizeAdjustment, QVariant( --idx ) ); - ui.msgEdit->textCursor().mergeCharFormat( format ); - } - } - ui.msgEdit->setFocus( Qt::OtherFocusReason ); -} - -void CreateBlogMsg::blockQuote() -{ - QTextBlockFormat blockFormat = ui.msgEdit->textCursor().blockFormat(); - QTextBlockFormat f; - - if ( blockFormat.hasProperty( TextFormat::IsBlockQuote ) && - blockFormat.boolProperty( TextFormat::IsBlockQuote ) ) { - f.setProperty( TextFormat::IsBlockQuote, QVariant( false ) ); - f.setLeftMargin( 0 ); - f.setRightMargin( 0 ); - } else { - f.setProperty( TextFormat::IsBlockQuote, QVariant( true ) ); - f.setLeftMargin( 40 ); - f.setRightMargin( 40 ); - } - ui.msgEdit->textCursor().mergeBlockFormat( f ); -} - -void CreateBlogMsg::toggleCode() -{ - static QString preFontFamily; - - QTextCharFormat charFormat = ui.msgEdit->currentCharFormat(); - QTextCharFormat f; - - if ( charFormat.hasProperty( TextFormat::HasCodeStyle ) && - charFormat.boolProperty( TextFormat::HasCodeStyle ) ) { - f.setProperty( TextFormat::HasCodeStyle, QVariant( false ) ); - f.setBackground( defaultCharFormat.background() ); - f.setFontFamily( preFontFamily ); - ui.msgEdit->textCursor().mergeCharFormat( f ); - - } else { - preFontFamily = ui.msgEdit->fontFamily(); - f.setProperty( TextFormat::HasCodeStyle, QVariant( true ) ); - f.setBackground( codeBackground ); - f.setFontFamily( "Dejavu Sans Mono" ); - ui.msgEdit->textCursor().mergeCharFormat( f ); - } - ui.msgEdit->setFocus( Qt::OtherFocusReason ); -} - -void CreateBlogMsg::addPostSplitter() -{ - QTextBlockFormat f = ui.msgEdit->textCursor().blockFormat(); - QTextBlockFormat f1 = f; - - f.setProperty( TextFormat::IsHtmlTagSign, true ); - f.setProperty( QTextFormat::BlockTrailingHorizontalRulerWidth, - QTextLength( QTextLength::PercentageLength, 80 ) ); - if ( ui.msgEdit->textCursor().block().text().isEmpty() ) { - ui.msgEdit->textCursor().mergeBlockFormat( f ); - } else { - ui.msgEdit->textCursor().insertBlock( f ); - } - ui.msgEdit->textCursor().insertBlock( f1 ); -} - -void CreateBlogMsg::setStartupText() -{ - QString string = "

HTML Previewer

" - "

This example shows you how to use QWebView to" - " preview HTML data written in a QPlainTextEdit.

" - " "; - //webView->setHtml(string); -} - -void CreateBlogMsg::updateTextEdit() -{ - //QWebFrame *mainFrame = webView->page()->mainFrame(); - QString frameText = ui.msgEdit->toHtml(); - ui.plainTextEdit->setPlainText(frameText); - //QString text = plainTextEdit->toPlainText(); -} - -void CreateBlogMsg::textBold() -{ - QTextCharFormat fmt; - fmt.setFontWeight(actionTextBold->isChecked() ? QFont::Bold : QFont::Normal); - mergeFormatOnWordOrSelection(fmt); -} - -void CreateBlogMsg::textUnderline() -{ - QTextCharFormat fmt; - fmt.setFontUnderline(actionTextUnderline->isChecked()); - mergeFormatOnWordOrSelection(fmt); -} - -void CreateBlogMsg::textItalic() -{ - QTextCharFormat fmt; - fmt.setFontItalic(actionTextItalic->isChecked()); - mergeFormatOnWordOrSelection(fmt); -} - - -void CreateBlogMsg::textAlign(QAction *a) -{ - if (a == actionAlignLeft) - ui.msgEdit->setAlignment(Qt::AlignLeft | Qt::AlignAbsolute); - else if (a == actionAlignCenter) - ui.msgEdit->setAlignment(Qt::AlignHCenter | Qt::AlignAbsolute); - else if (a == actionAlignRight) - ui.msgEdit->setAlignment(Qt::AlignRight | Qt::AlignAbsolute); - else if (a == actionAlignJustify) - ui.msgEdit->setAlignment(Qt::AlignJustify | Qt::AlignAbsolute); - -} - -void CreateBlogMsg::alignmentChanged(Qt::Alignment a) -{ - if (a & Qt::AlignLeft) { - actionAlignLeft->setChecked(true); - } else if (a & Qt::AlignHCenter) { - actionAlignCenter->setChecked(true); - } else if (a & Qt::AlignRight) { - actionAlignRight->setChecked(true); - } else if (a & Qt::AlignJustify) { - actionAlignJustify->setChecked(true); - } -} - -void CreateBlogMsg::textFamily(const QString &f) -{ - QTextCharFormat fmt; - fmt.setFontFamily(f); - mergeFormatOnWordOrSelection(fmt); -} - -void CreateBlogMsg::textSize(const QString &p) -{ - qreal pointSize = p.toFloat(); - if (p.toFloat() > 0) { - QTextCharFormat fmt; - fmt.setFontPointSize(pointSize); - mergeFormatOnWordOrSelection(fmt); - } -} - -void CreateBlogMsg::changeFormatType(int styleIndex ) -{ - ui.msgEdit->setFocus( Qt::OtherFocusReason ); - - QTextCursor cursor = ui.msgEdit->textCursor(); - //QTextBlockFormat bformat = cursor.blockFormat(); - QTextBlockFormat bformat; - QTextCharFormat cformat; - - switch (styleIndex) { - default: - case 0: - bformat.setProperty( TextFormat::HtmlHeading, QVariant( 0 ) ); - cformat.setFontWeight( QFont::Normal ); - cformat.setProperty( QTextFormat::FontSizeAdjustment, QVariant( 0 ) ); - break; - case 1: - bformat.setProperty( TextFormat::HtmlHeading, QVariant( 1 ) ); - cformat.setFontWeight( QFont::Bold ); - cformat.setProperty( QTextFormat::FontSizeAdjustment, QVariant( 3 ) ); - break; - case 2: - bformat.setProperty( TextFormat::HtmlHeading, QVariant( 2 ) ); - cformat.setFontWeight( QFont::Bold ); - cformat.setProperty( QTextFormat::FontSizeAdjustment, QVariant( 2 ) ); - break; - case 3: - bformat.setProperty( TextFormat::HtmlHeading, QVariant( 3 ) ); - cformat.setFontWeight( QFont::Bold ); - cformat.setProperty( QTextFormat::FontSizeAdjustment, QVariant( 1 ) ); - break; - case 4: - bformat.setProperty( TextFormat::HtmlHeading, QVariant( 4 ) ); - cformat.setFontWeight( QFont::Bold ); - cformat.setProperty( QTextFormat::FontSizeAdjustment, QVariant( 0 ) ); - break; - case 5: - bformat.setProperty( TextFormat::HtmlHeading, QVariant( 5 ) ); - cformat.setFontWeight( QFont::Bold ); - cformat.setProperty( QTextFormat::FontSizeAdjustment, QVariant( -1 ) ); - break; - case 6: - bformat.setProperty( TextFormat::HtmlHeading, QVariant( 6 ) ); - cformat.setFontWeight( QFont::Bold ); - cformat.setProperty( QTextFormat::FontSizeAdjustment, QVariant( -2 ) ); - break; - } - //cformat.clearProperty( TextFormat::HasCodeStyle ); - - cursor.beginEditBlock(); - cursor.mergeBlockFormat( bformat ); - cursor.select( QTextCursor::BlockUnderCursor ); - cursor.mergeCharFormat( cformat ); - cursor.endEditBlock(); -} - - -void CreateBlogMsg::textColor() -{ - QColor col = QColorDialog::getColor(ui.msgEdit->textColor(), this); - if (!col.isValid()) - return; - QTextCharFormat fmt; - fmt.setForeground(col); - mergeFormatOnWordOrSelection(fmt); - colorChanged(col); -} - -void CreateBlogMsg::fontChanged(const QFont &f) -{ - comboFont->setCurrentIndex(comboFont->findText(QFontInfo(f).family())); - comboSize->setCurrentIndex(comboSize->findText(QString::number(f.pointSize()))); - actionTextBold->setChecked(f.bold()); - actionTextItalic->setChecked(f.italic()); - actionTextUnderline->setChecked(f.underline()); -} - -void CreateBlogMsg::colorChanged(const QColor &c) -{ - QPixmap pix(16, 16); - pix.fill(c); - //ui.colorbtn->setIcon(pix); - actionTextColor->setIcon(pix); -} - -void CreateBlogMsg::mergeFormatOnWordOrSelection(const QTextCharFormat &format) -{ - QTextCursor cursor = ui.msgEdit->textCursor(); - if (!cursor.hasSelection()) - cursor.select(QTextCursor::WordUnderCursor); - cursor.mergeCharFormat(format); - ui.msgEdit->mergeCurrentCharFormat(format); -} - -void CreateBlogMsg::currentCharFormatChanged(const QTextCharFormat &format) -{ - fontChanged(format.font()); - colorChanged(format.foreground().color()); -} - -void CreateBlogMsg::cursorPositionChanged() -{ - alignmentChanged(ui.msgEdit->alignment()); -} - -void CreateBlogMsg::clipboardDataChanged() -{ -#ifndef QT_NO_CLIPBOARD - actionPaste->setEnabled(!QApplication::clipboard()->text().isEmpty()); -#endif -} - - -void CreateBlogMsg::addOrderedList() -{ - ui.msgEdit->textCursor().createList( QTextListFormat::ListDecimal ); - -} - -void CreateBlogMsg::addUnorderedList() -{ - ui.msgEdit->textCursor().createList( QTextListFormat::ListDisc ); -} - -void CreateBlogMsg::setupFileActions() -{ - QMenu *menu = new QMenu(tr("&File"), this); - menuBar()->addMenu(menu); - - QAction *a; - - a = new QAction(QIcon(":/images/textedit/filenew.png"), tr("&New"), this); - a->setShortcut(QKeySequence::New); - connect(a, SIGNAL(triggered()), this, SLOT(fileNew())); - menu->addAction(a); - - a = new QAction(QIcon(":/images/textedit/fileopen.png"), tr("&Open..."), this); - a->setShortcut(QKeySequence::Open); - connect(a, SIGNAL(triggered()), this, SLOT(fileOpen())); - menu->addAction(a); - - menu->addSeparator(); - - actionSave = a = new QAction(QIcon(":/images/textedit/filesave.png"), tr("&Save"), this); - a->setShortcut(QKeySequence::Save); - connect(a, SIGNAL(triggered()), this, SLOT(fileSave())); - a->setEnabled(false); - menu->addAction(a); - - a = new QAction(tr("Save &As..."), this); - connect(a, SIGNAL(triggered()), this, SLOT(fileSaveAs())); - menu->addAction(a); - menu->addSeparator(); - - a = new QAction(QIcon(":/images/textedit/fileprint.png"), tr("&Print..."), this); - a->setShortcut(QKeySequence::Print); - connect(a, SIGNAL(triggered()), this, SLOT(filePrint())); - menu->addAction(a); - - a = new QAction(QIcon(":/images/textedit/fileprint.png"), tr("Print Preview..."), this); - connect(a, SIGNAL(triggered()), this, SLOT(filePrintPreview())); - menu->addAction(a); - - a = new QAction(QIcon(":/images/textedit/exportpdf.png"), tr("&Export PDF..."), this); - a->setShortcut(Qt::CTRL + Qt::Key_D); - connect(a, SIGNAL(triggered()), this, SLOT(filePrintPdf())); - menu->addAction(a); - - menu->addSeparator(); - - a = new QAction(tr("&Quit"), this); - a->setShortcut(Qt::CTRL + Qt::Key_Q); - connect(a, SIGNAL(triggered()), this, SLOT(cancelMsg())); - menu->addAction(a); -} - -void CreateBlogMsg::setupEditActions() -{ - QMenu *menu = new QMenu(tr("&Edit"), this); - menuBar()->addMenu(menu); - - QAction *a; - a = actionUndo = new QAction(QIcon(":/images/textedit/editundo.png"), tr("&Undo"), this); - a->setShortcut(QKeySequence::Undo); - menu->addAction(a); - a = actionRedo = new QAction(QIcon(":/images/textedit/editredo.png"), tr("&Redo"), this); - a->setShortcut(QKeySequence::Redo); - menu->addAction(a); - menu->addSeparator(); - a = actionCut = new QAction(QIcon(":/images/textedit/editcut.png"), tr("Cu&t"), this); - a->setShortcut(QKeySequence::Cut); - menu->addAction(a); - a = actionCopy = new QAction(QIcon(":/images/textedit/editcopy.png"), tr("&Copy"), this); - a->setShortcut(QKeySequence::Copy); - menu->addAction(a); - a = actionPaste = new QAction(QIcon(":/images/textedit/editpaste.png"), tr("&Paste"), this); - a->setShortcut(QKeySequence::Paste); - menu->addAction(a); - actionPaste->setEnabled(!QApplication::clipboard()->text().isEmpty()); -} - -void CreateBlogMsg::setupViewActions() -{ - QMenu *menu = new QMenu(tr("&View"), this); - menuBar()->addMenu(menu); - - QAction *a; - - -} - -void CreateBlogMsg::setupInsertActions() -{ - QMenu *menu = new QMenu(tr("&Insert"), this); - menuBar()->addMenu(menu); - - QAction *a; - - a = new QAction(QIcon(""), tr("&Image"), this); - connect(a, SIGNAL(triggered()), this, SLOT(addImage())); - menu->addAction(a); - -} - -void CreateBlogMsg::setupParagraphActions() -{ - comboStyle = new QComboBox(ui.toolBar_2); - ui.toolBar_2->addWidget(comboStyle); - comboStyle->addItem("Paragraph"); - comboStyle->addItem("Heading 1"); - comboStyle->addItem("Heading 2"); - comboStyle->addItem("Heading 3"); - comboStyle->addItem("Heading 4"); - comboStyle->addItem("Heading 5"); - comboStyle->addItem("Heading 6"); - - connect(comboStyle, SIGNAL(activated(int)), - this, SLOT(changeFormatType(int))); -} - -void CreateBlogMsg::setupTextActions() -{ - - QMenu *menu = new QMenu(tr("F&ormat"), this); - menuBar()->addMenu(menu); - - actionTextBold = new QAction(QIcon(":/images/textedit/textbold.png"),tr("&Bold"), this); - actionTextBold->setShortcut(Qt::CTRL + Qt::Key_B); - //actionTextBold->setPriority(QAction::LowPriority); - QFont bold; - bold.setBold(true); - actionTextBold->setFont(bold); - connect(actionTextBold, SIGNAL(triggered()), this, SLOT(textBold())); - - ui.toolBar_2->addAction(actionTextBold); - menu->addAction(actionTextBold); - actionTextBold->setCheckable(true); - - actionTextItalic = new QAction(QIcon(":/images/textedit/textitalic.png"),tr("&Italic"), this); - //actionTextItalic->setPriority(QAction::LowPriority); - actionTextItalic->setShortcut(Qt::CTRL + Qt::Key_I); - QFont italic; - italic.setItalic(true); - actionTextItalic->setFont(italic); - connect(actionTextItalic, SIGNAL(triggered()), this, SLOT(textItalic())); - - ui.toolBar_2->addAction(actionTextItalic); - menu->addAction(actionTextItalic); - actionTextItalic->setCheckable(true); - - actionTextUnderline = new QAction(QIcon(":/images/textedit/textunder.png"),tr("&Underline"), this); - actionTextUnderline->setShortcut(Qt::CTRL + Qt::Key_U); - //actionTextUnderline->setPriority(QAction::LowPriority); - QFont underline; - underline.setUnderline(true); - actionTextUnderline->setFont(underline); - connect(actionTextUnderline, SIGNAL(triggered()), this, SLOT(textUnderline())); - - ui.toolBar_2->addAction(actionTextUnderline); - menu->addAction(actionTextUnderline); - actionTextUnderline->setCheckable(true); - - menu->addSeparator(); - - QActionGroup *grp = new QActionGroup(this); - connect(grp, SIGNAL(triggered(QAction*)), this, SLOT(textAlign(QAction*))); - - // Make sure the alignLeft is always left of the alignRight - if (QApplication::isLeftToRight()) { - actionAlignLeft = new QAction(QIcon(":/images/textedit/textleft.png"),tr("&Left"), grp); - actionAlignCenter = new QAction(QIcon(":/images/textedit/textcenter.png"), tr("C&enter"), grp); - actionAlignRight = new QAction(QIcon(":/images/textedit/textright.png"), tr("&Right"), grp); - } else { - actionAlignRight = new QAction(QIcon(":/images/textedit/textright.png"), tr("&Right"), grp); - actionAlignCenter = new QAction(QIcon(":/images/textedit/textcenter.png"), tr("C&enter"), grp); - actionAlignLeft = new QAction(QIcon(":/images/textedit/textleft.png"), tr("&Left"), grp); - } - actionAlignJustify = new QAction(QIcon(":/images/textedit/textjustify.png"), tr("&Justify"), grp); - - actionAlignLeft->setShortcut(Qt::CTRL + Qt::Key_L); - actionAlignLeft->setCheckable(true); - //actionAlignLeft->setPriority(QAction::LowPriority); - actionAlignCenter->setShortcut(Qt::CTRL + Qt::Key_E); - actionAlignCenter->setCheckable(true); - //actionAlignCenter->setPriority(QAction::LowPriority); - actionAlignRight->setShortcut(Qt::CTRL + Qt::Key_R); - actionAlignRight->setCheckable(true); - //actionAlignRight->setPriority(QAction::LowPriority); - actionAlignJustify->setShortcut(Qt::CTRL + Qt::Key_J); - actionAlignJustify->setCheckable(true); - //actionAlignJustify->setPriority(QAction::LowPriority); - - ui.toolBar_2->addActions(grp->actions()); - menu->addActions(grp->actions()); - - menu->addSeparator(); - - QPixmap pix(16, 16); - pix.fill(Qt::black); - actionTextColor = new QAction(pix, tr("&Text Color..."), this); - connect(actionTextColor, SIGNAL(triggered()), this, SLOT(textColor())); - - ui.toolBar_2->addAction(actionTextColor); - menu->addAction(actionTextColor); - - menu->addAction(ui.actionOrderedlist); - menu->addAction(ui.actionUnorderedlist); - menu->addAction(ui.actionBlockquoute); - - - /*comboStyle = new QComboBox(ui.toolBar_2); - ui.toolBar_2->addWidget(comboStyle); - comboStyle->addItem("Paragraph"); - comboStyle->addItem("Heading 1"); - comboStyle->addItem("Heading 2"); - comboStyle->addItem("Heading 3"); - comboStyle->addItem("Heading 4"); - comboStyle->addItem("Heading 5"); - comboStyle->addItem("Heading 6"); - - connect(comboStyle, SIGNAL(activated(int)), - this, SLOT(changeFormatType(int)));*/ - - comboFont = new QFontComboBox(ui.toolBar_2); - ui.toolBar_2->addWidget(comboFont); - connect(comboFont, SIGNAL(activated(QString)), - this, SLOT(textFamily(QString))); - - comboSize = new QComboBox(ui.toolBar_2); - comboSize->setObjectName("comboSize"); - ui.toolBar_2->addWidget(comboSize); - comboSize->setEditable(true); - - QFontDatabase db; - foreach(int size, db.standardSizes()) - comboSize->addItem(QString::number(size)); - - connect(comboSize, SIGNAL(activated(QString)), - this, SLOT(textSize(QString))); - comboSize->setCurrentIndex(comboSize->findText(QString::number(QApplication::font() - .pointSize()))); -} - -bool CreateBlogMsg::load(const QString &f) -{ - if (!QFile::exists(f)) - return false; - QFile file(f); - if (!file.open(QFile::ReadOnly)) - return false; - - QByteArray data = file.readAll(); - QTextCodec *codec = Qt::codecForHtml(data); - QString str = codec->toUnicode(data); - if (Qt::mightBeRichText(str)) { - ui.msgEdit->setHtml(str); - } else { - str = QString::fromLocal8Bit(data); - ui.msgEdit->setPlainText(str); - } - - setCurrentFileName(f); - return true; -} - -bool CreateBlogMsg::maybeSave() -{ - if (!ui.msgEdit->document()->isModified()) - return true; - if (fileName.startsWith(QLatin1String(":/"))) - return true; - QMessageBox::StandardButton ret; - ret = QMessageBox::warning(this, tr("Application"), - tr("The document has been modified.\n" - "Do you want to save your changes?"), - QMessageBox::Save | QMessageBox::Discard - | QMessageBox::Cancel); - if (ret == QMessageBox::Save) - return fileSave(); - else if (ret == QMessageBox::Cancel) - return false; - return true; -} - -void CreateBlogMsg::fileNew() -{ - if (maybeSave()) { - ui.msgEdit->clear(); - setCurrentFileName(QString()); - } -} - -void CreateBlogMsg::fileOpen() -{ - QString fn; - if (misc::getOpenFileName(this, RshareSettings::LASTDIR_BLOGS, tr("Open File..."), tr("HTML-Files (*.htm *.html);;All Files (*)"), fn)) - load(fn); -} - -bool CreateBlogMsg::fileSave() -{ - if (fileName.isEmpty()) - return fileSaveAs(); - - QTextDocumentWriter writer(fileName); - bool success = writer.write(ui.msgEdit->document()); - if (success) - ui.msgEdit->document()->setModified(false); - return success; -} - -bool CreateBlogMsg::fileSaveAs() -{ - QString fn; - if (misc::getSaveFileName(this, RshareSettings::LASTDIR_BLOGS, tr("Save as..."), tr("ODF files (*.odt);;HTML-Files (*.htm *.html);;All Files (*)"), fn)) { - if (! (fn.endsWith(".odt", Qt::CaseInsensitive) || fn.endsWith(".htm", Qt::CaseInsensitive) || fn.endsWith(".html", Qt::CaseInsensitive)) ) - fn += ".odt"; // default - setCurrentFileName(fn); - return fileSave(); - } - - return false; -} - -void CreateBlogMsg::filePrint() -{ -#ifndef QT_NO_PRINTER - QPrinter printer(QPrinter::HighResolution); - QPrintDialog *dlg = new QPrintDialog(&printer, this); - if (ui.msgEdit->textCursor().hasSelection()) - dlg->addEnabledOption(QAbstractPrintDialog::PrintSelection); - dlg->setWindowTitle(tr("Print Document")); - if (dlg->exec() == QDialog::Accepted) { - ui.msgEdit->print(&printer); - } - delete dlg; -#endif -} - -void CreateBlogMsg::filePrintPreview() -{ -#ifndef QT_NO_PRINTER - QPrinter printer(QPrinter::HighResolution); - QPrintPreviewDialog preview(&printer, this); - connect(&preview, SIGNAL(paintRequested(QPrinter*)), SLOT(printPreview(QPrinter*))); - preview.exec(); -#endif -} - -void CreateBlogMsg::printPreview(QPrinter *printer) -{ -#ifdef QT_NO_PRINTER - Q_UNUSED(printer); -#else - ui.msgEdit->print(printer); -#endif -} - - -void CreateBlogMsg::filePrintPdf() -{ -#ifndef QT_NO_PRINTER -//! [0] - QString fileName; - if (misc::getSaveFileName(this, RshareSettings::LASTDIR_MESSAGES, tr("Export PDF"), "*.pdf", fileName)) { - if (QFileInfo(fileName).suffix().isEmpty()) - fileName.append(".pdf"); - QPrinter printer(QPrinter::HighResolution); - printer.setOutputFormat(QPrinter::PdfFormat); - printer.setOutputFileName(fileName); - ui.msgEdit->document()->print(&printer); - } -//! [0] -#endif -} - -void CreateBlogMsg::setCurrentFileName(const QString &fileName) -{ - this->fileName = fileName; - ui.msgEdit->document()->setModified(false); - - QString shownName; - if (fileName.isEmpty()) - shownName = "untitled.txt"; - else - shownName = QFileInfo(fileName).fileName(); - - //setWindowTitle(tr("%1[*] - %2").arg(shownName).arg(tr("Rich Text"))); - setWindowModified(false); -} - -void CreateBlogMsg::addImage() -{ - QString fileimg; - if (misc::getOpenFileName(this, RshareSettings::LASTDIR_MESSAGES, tr("Choose Image"), tr("Image Files supported (*.png *.jpeg *.jpg *.gif)"), fileimg)) { - QImage base(fileimg); - - Create_New_Image_Tag(fileimg); - } -} - -void CreateBlogMsg::Create_New_Image_Tag( const QString urlremoteorlocal ) -{ - /*if (image_extension(urlremoteorlocal)) {*/ - QString subtext = QString("

").arg(urlremoteorlocal); - ///////////subtext.append("

Description on image.

"); - QTextDocumentFragment fragment = QTextDocumentFragment::fromHtml(subtext); - ui.msgEdit->textCursor().insertFragment(fragment); - //emit statusMessage(QString("Image new :").arg(urlremoteorlocal)); - //} -} diff --git a/retroshare-gui/src/gui/unfinished/blogs/CreateBlogMsg.h b/retroshare-gui/src/gui/unfinished/blogs/CreateBlogMsg.h deleted file mode 100644 index 91a3c9610..000000000 --- a/retroshare-gui/src/gui/unfinished/blogs/CreateBlogMsg.h +++ /dev/null @@ -1,161 +0,0 @@ -/**************************************************************** - * RetroShare is distributed under the following license: - * - * Copyright (C) 2008 Robert Fernie - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program 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 General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - ****************************************************************/ - -#ifndef _CREATEBLOGMSG_H -#define _CREATEBLOGMSG_H - -#include - -#include "ui_CreateBlogMsg.h" -#include - -class SubFileItem; -class FileInfo; - -QT_FORWARD_DECLARE_CLASS(QAction) -QT_FORWARD_DECLARE_CLASS(QComboBox) -QT_FORWARD_DECLARE_CLASS(QFontComboBox) -QT_FORWARD_DECLARE_CLASS(QTextEdit) -QT_FORWARD_DECLARE_CLASS(QTextCharFormat) -QT_FORWARD_DECLARE_CLASS(QMenu) - -class CreateBlogMsg : public QMainWindow -{ - Q_OBJECT - -public: - /** Default Constructor */ - CreateBlogMsg(std::string cId, QWidget *parent = 0, Qt::WFlags flags = 0); - /** Default Destructor */ - - void addAttachment(std::string path); - void addAttachment(std::string hash, std::string fname, uint64_t size, - bool local, std::string srcId); - - void newBlogMsg(); - - QPixmap picture; - QSettings setter; - - void Create_New_Image_Tag( const QString urlremoteorlocal ); - -private slots: - - void cancelMsg(); - void sendMsg(); - void addImage(); - - void fontSizeIncrease(); - void fontSizeDecrease(); - void blockQuote(); - void toggleCode(); - void addPostSplitter(); - - void setStartupText(); - void updateTextEdit(); - - void fileNew(); - void fileOpen(); - bool fileSave(); - bool fileSaveAs(); - void filePrint(); - void filePrintPreview(); - void filePrintPdf(); - void printPreview(QPrinter *); - - void textBold(); - void textUnderline(); - void textItalic(); - void textFamily(const QString &f); - void textSize(const QString &p); - void changeFormatType(int styleIndex ); - - - void textColor(); - void textAlign(QAction *a); - - void addOrderedList(); - void addUnorderedList(); - - void currentCharFormatChanged(const QTextCharFormat &format); - void cursorPositionChanged(); - - void clipboardDataChanged(); - - -private: - void setupFileActions(); - void setupEditActions(); - void setupViewActions(); - void setupInsertActions(); - void setupParagraphActions(); - void setupTextActions(); - - void setCurrentFileName(const QString &fileName); - bool load(const QString &f); - bool maybeSave(); - - void mergeFormatOnWordOrSelection(const QTextCharFormat &format); - - void fontChanged(const QFont &f); - void colorChanged(const QColor &c); - void alignmentChanged(Qt::Alignment a); - - - void sendMessage(std::wstring subject, std::wstring msg); - - std::string mBlogId; - - QAction *actionSave, - *actionTextBold, - *actionTextUnderline, - *actionTextItalic, - *actionTextColor, - *actionAlignLeft, - *actionAlignCenter, - *actionAlignRight, - *actionAlignJustify, - *actionUndo, - *actionRedo, - *actionCut, - *actionCopy, - *actionPaste; - - QComboBox *comboStyle; - QFontComboBox *comboFont; - QComboBox *comboSize; - - QString fileName; - - QColor codeBackground; - QTextCharFormat defaultCharFormat; - QTextBlockFormat defaultBlockFormat; - QTextCharFormat lastCharFormat; - QTextBlockFormat lastBlockFormat; - - /** Qt Designer generated object */ - Ui::CreateBlogMsg ui; -}; - - - -#endif - diff --git a/retroshare-gui/src/gui/unfinished/blogs/CreateBlogMsg.ui b/retroshare-gui/src/gui/unfinished/blogs/CreateBlogMsg.ui deleted file mode 100644 index bd169b710..000000000 --- a/retroshare-gui/src/gui/unfinished/blogs/CreateBlogMsg.ui +++ /dev/null @@ -1,343 +0,0 @@ - - - CreateBlogMsg - - - - 0 - 0 - 666 - 515 - - - - New Blog Post - - - - :/images/rstray3.png:/images/rstray3.png - - - QToolBar#toolBar{background-image: url(:/images/connect/connectFriendBanner.png); -} - -QToolButton { - color: white; -} - -QToolBar#toolBar_2{ -background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, -stop:0 #FEFEFE, stop:1 #E8E8E8); - -border: 1px solid #CCCCCC;} - - - - - 0 - - - - - QFrame::StyledPanel - - - QFrame::Raised - - - - 0 - - - 0 - - - - - QTabWidget::South - - - 0 - - - - Blog Post - - - - - - - - - 75 - true - - - - Blog Post to: - - - - - - - true - - - true - - - - - - - - - 1 - - - - Visual Editor - - - - - - Blog Message - - - - - - - - - 75 - true - - - - Subject : - - - - - - - - - - - - - - - - - - - Html Editor - - - - - - - - - - - - - - - - - - - - - - 0 - 0 - 666 - 25 - - - - - - - - 0 - 32 - - - - - 9 - - - - toolBar - - - TopToolBarArea - - - false - - - - - - - - toolBar_2 - - - TopToolBarArea - - - true - - - - - - true - - - - :/images/textedit/hi22-action-format-text-blockquote.png:/images/textedit/hi22-action-format-text-blockquote.png - - - blockquote - - - - - - :/images/textedit/format_font_size_more.png:/images/textedit/format_font_size_more.png - - - Increase font Size - - - - - - :/images/textedit/format_font_size_less.png:/images/textedit/format_font_size_less.png - - - Decrease font size - - - - - - :/images/textedit/textbold.png:/images/textedit/textbold.png - - - Bold - - - - - - :/images/textedit/textunder.png:/images/textedit/textunder.png - - - Underline - - - - - - :/images/textedit/textitalic.png:/images/textedit/textitalic.png - - - Italic - - - - - Publish - - - - - New - - - - - - :/images/textedit/hi22-action-format-text-code.png:/images/textedit/hi22-action-format-text-code.png - - - Code - - - - - - :/images/textedit/hi22-action-insert-more-mark.png:/images/textedit/hi22-action-insert-more-mark.png - - - splitPost - - - - - - :/images/textedit/format-list-ordered.png:/images/textedit/format-list-ordered.png - - - Ordered List - - - - - - :/images/textedit/format-list-unordered.png:/images/textedit/format-list-unordered.png - - - Unordered List - - - - - true - - - - :/images/textedit/editcut.png:/images/textedit/editcut.png - - - Clipboard - - - - - - :/images/textedit/editundo.png:/images/textedit/editundo.png - - - Undo - - - - - - - - - - - - - - - diff --git a/retroshare-gui/src/retroshare-gui.pro b/retroshare-gui/src/retroshare-gui.pro index d7c47a182..7e0a3fbd7 100644 --- a/retroshare-gui/src/retroshare-gui.pro +++ b/retroshare-gui/src/retroshare-gui.pro @@ -2,7 +2,7 @@ CONFIG += qt gui uic qrc resources uitools idle bitdht # Below is for GXS services. # Should be disabled for releases. -#CONFIG += gxs debug +CONFIG += gxs debug gxs { @@ -300,13 +300,7 @@ HEADERS += rshare.h \ gui/MainWindow.h \ gui/RSHumanReadableDelegate.h \ gui/AboutDialog.h \ - gui/ForumsDialog.h \ gui/CreateMsgLinkDialog.h \ - gui/forums/ForumDetails.h \ - gui/forums/EditForumDetails.h \ - gui/forums/CreateForum.h \ - gui/forums/CreateForumMsg.h \ - gui/forums/ForumUserNotify.h \ gui/NetworkView.h \ gui/TrustView.h \ gui/MessengerWindow.h \ @@ -377,12 +371,6 @@ HEADERS += rshare.h \ gui/chat/CreateLobbyDialog.h \ gui/chat/ChatStyle.h \ gui/chat/ChatUserNotify.h \ - gui/channels/CreateChannel.h \ - gui/channels/ChannelDetails.h \ - gui/channels/CreateChannelMsg.h \ - gui/channels/EditChanDetails.h \ - gui/channels/ShareKey.h \ - gui/channels/ChannelUserNotify.h \ gui/connect/ConfCertDialog.h \ gui/msgs/MessageComposer.h \ gui/msgs/MessageWindow.h \ @@ -403,7 +391,6 @@ HEADERS += rshare.h \ gui/settings/CryptoPage.h \ gui/settings/MessagePage.h \ gui/settings/NewTag.h \ - gui/settings/ForumPage.h \ gui/settings/PluginsPage.h \ gui/settings/PluginItem.h \ gui/settings/AppearancePage.h \ @@ -478,15 +465,10 @@ HEADERS += rshare.h \ gui/elastic/arrow.h \ gui/elastic/node.h \ gui/NewsFeed.h \ - gui/ChannelFeed.h \ gui/feeds/FeedHolder.h \ - gui/feeds/ForumNewItem.h \ - gui/feeds/ForumMsgItem.h \ gui/feeds/PeerItem.h \ gui/feeds/MsgItem.h \ gui/feeds/ChatMsgItem.h \ - gui/feeds/ChanNewItem.h \ - gui/feeds/ChanMsgItem.h \ gui/feeds/SubFileItem.h \ gui/feeds/AttachFileItem.h \ gui/feeds/SecurityItem.h \ @@ -496,8 +478,26 @@ HEADERS += rshare.h \ gui/groups/CreateGroup.h \ gui/dht/DhtWindow.h \ gui/bwctrl/BwCtrlWindow.h \ + gui/channels/ShareKey.h \ gui/GetStartedDialog.h +# gui/ForumsDialog.h \ +# gui/forums/ForumDetails.h \ +# gui/forums/EditForumDetails.h \ +# gui/forums/CreateForum.h \ +# gui/forums/CreateForumMsg.h \ +# gui/forums/ForumUserNotify.h \ +# gui/feeds/ForumNewItem.h \ +# gui/feeds/ForumMsgItem.h \ +# gui/ChannelFeed.h \ +# gui/feeds/ChanNewItem.h \ +# gui/feeds/ChanMsgItem.h \ +# gui/channels/CreateChannel.h \ +# gui/channels/ChannelDetails.h \ +# gui/channels/CreateChannelMsg.h \ +# gui/channels/EditChanDetails.h \ +# gui/channels/ChannelUserNotify.h \ +# gui/settings/ForumPage.h \ FORMS += gui/StartDialog.ui \ gui/GenCertDialog.ui \ @@ -508,13 +508,8 @@ FORMS += gui/StartDialog.ui \ gui/FileTransfer/TurtleRouterDialog.ui \ gui/FileTransfer/TurtleRouterStatistics.ui \ gui/FileTransfer/DetailsDialog.ui \ - gui/ForumsDialog.ui \ gui/MainWindow.ui \ gui/CreateMsgLinkDialog.ui \ - gui/forums/CreateForum.ui \ - gui/forums/CreateForumMsg.ui \ - gui/forums/ForumDetails.ui \ - gui/forums/EditForumDetails.ui \ gui/NetworkView.ui \ gui/TrustView.ui \ gui/MessengerWindow.ui \ @@ -532,11 +527,6 @@ FORMS += gui/StartDialog.ui \ gui/profile/ProfileWidget.ui \ gui/profile/StatusMessage.ui \ gui/profile/ProfileManager.ui \ - gui/channels/CreateChannel.ui \ - gui/channels/CreateChannelMsg.ui \ - gui/channels/ChannelDetails.ui \ - gui/channels/EditChanDetails.ui \ - gui/channels/ShareKey.ui \ gui/chat/PopupChatWindow.ui \ gui/chat/PopupChatDialog.ui \ gui/chat/ChatTabWidget.ui \ @@ -559,7 +549,6 @@ FORMS += gui/StartDialog.ui \ gui/settings/CryptoPage.ui \ gui/settings/MessagePage.ui \ gui/settings/NewTag.ui \ - gui/settings/ForumPage.ui \ gui/settings/PluginsPage.ui \ gui/settings/AppearancePage.ui \ gui/settings/TransferPage.ui \ @@ -577,14 +566,9 @@ FORMS += gui/StartDialog.ui \ gui/advsearch/AdvancedSearchDialog.ui \ gui/advsearch/expressionwidget.ui \ gui/NewsFeed.ui \ - gui/ChannelFeed.ui \ - gui/feeds/ForumNewItem.ui \ - gui/feeds/ForumMsgItem.ui \ gui/feeds/PeerItem.ui \ gui/feeds/MsgItem.ui \ gui/feeds/ChatMsgItem.ui \ - gui/feeds/ChanNewItem.ui \ - gui/feeds/ChanMsgItem.ui \ gui/feeds/SubFileItem.ui \ gui/feeds/AttachFileItem.ui \ gui/feeds/SecurityItem.ui \ @@ -600,8 +584,25 @@ FORMS += gui/StartDialog.ui \ gui/style/StyleDialog.ui \ gui/dht/DhtWindow.ui \ gui/bwctrl/BwCtrlWindow.ui \ + gui/channels/ShareKey.ui \ gui/GetStartedDialog.ui +# gui/ForumsDialog.ui \ +# gui/forums/CreateForum.ui \ +# gui/forums/CreateForumMsg.ui \ +# gui/forums/ForumDetails.ui \ +# gui/forums/EditForumDetails.ui \ +# gui/feeds/ForumNewItem.ui \ +# gui/feeds/ForumMsgItem.ui \ +# gui/ChannelFeed.ui \ +# gui/channels/CreateChannel.ui \ +# gui/channels/CreateChannelMsg.ui \ +# gui/channels/ChannelDetails.ui \ +# gui/channels/EditChanDetails.ui \ +# gui/feeds/ChanNewItem.ui \ +# gui/feeds/ChanMsgItem.ui \ +# gui/settings/ForumPage.ui \ + SOURCES += main.cpp \ rshare.cpp \ gui/notifyqt.cpp \ @@ -613,13 +614,7 @@ SOURCES += main.cpp \ gui/graphframe.cpp \ gui/mainpagestack.cpp \ gui/MainWindow.cpp \ - gui/ForumsDialog.cpp \ gui/CreateMsgLinkDialog.cpp \ - gui/forums/ForumDetails.cpp \ - gui/forums/EditForumDetails.cpp \ - gui/forums/CreateForum.cpp \ - gui/forums/CreateForumMsg.cpp \ - gui/forums/ForumUserNotify.cpp \ gui/NetworkView.cpp \ gui/TrustView.cpp \ gui/MessengerWindow.cpp \ @@ -678,12 +673,6 @@ SOURCES += main.cpp \ gui/profile/ProfileWidget.cpp \ gui/profile/StatusMessage.cpp \ gui/profile/ProfileManager.cpp \ - gui/channels/CreateChannel.cpp \ - gui/channels/CreateChannelMsg.cpp \ - gui/channels/ChannelDetails.cpp \ - gui/channels/EditChanDetails.cpp \ - gui/channels/ShareKey.cpp \ - gui/channels/ChannelUserNotify.cpp \ gui/chat/PopupChatWindow.cpp \ gui/chat/PopupChatDialog.cpp \ gui/chat/PopupDistantChatDialog.cpp \ @@ -752,7 +741,6 @@ SOURCES += main.cpp \ gui/settings/CryptoPage.cpp \ gui/settings/MessagePage.cpp \ gui/settings/NewTag.cpp \ - gui/settings/ForumPage.cpp \ gui/settings/PluginsPage.cpp \ gui/settings/PluginItem.cpp \ gui/settings/AppearancePage.cpp \ @@ -785,15 +773,10 @@ SOURCES += main.cpp \ gui/elastic/arrow.cpp \ gui/elastic/node.cpp \ gui/NewsFeed.cpp \ - gui/ChannelFeed.cpp \ gui/feeds/FeedHolder.cpp \ - gui/feeds/ForumNewItem.cpp \ - gui/feeds/ForumMsgItem.cpp \ gui/feeds/PeerItem.cpp \ gui/feeds/MsgItem.cpp \ gui/feeds/ChatMsgItem.cpp \ - gui/feeds/ChanNewItem.cpp \ - gui/feeds/ChanMsgItem.cpp \ gui/feeds/SubFileItem.cpp \ gui/feeds/AttachFileItem.cpp \ gui/feeds/SecurityItem.cpp \ @@ -803,8 +786,27 @@ SOURCES += main.cpp \ gui/groups/CreateGroup.cpp \ gui/dht/DhtWindow.cpp \ gui/bwctrl/BwCtrlWindow.cpp \ + gui/channels/ShareKey.cpp \ gui/GetStartedDialog.cpp +# gui/ForumsDialog.cpp \ +# gui/forums/ForumDetails.cpp \ +# gui/forums/EditForumDetails.cpp \ +# gui/forums/CreateForum.cpp \ +# gui/forums/CreateForumMsg.cpp \ +# gui/forums/ForumUserNotify.cpp \ +# gui/feeds/ForumNewItem.cpp \ +# gui/feeds/ForumMsgItem.cpp \ +# gui/ChannelFeed.cpp \ +# gui/channels/CreateChannel.cpp \ +# gui/channels/CreateChannelMsg.cpp \ +# gui/channels/ChannelDetails.cpp \ +# gui/channels/EditChanDetails.cpp \ +# gui/channels/ChannelUserNotify.cpp \ +# gui/feeds/ChanNewItem.cpp \ +# gui/feeds/ChanMsgItem.cpp \ +# gui/settings/ForumPage.cpp \ + RESOURCES += gui/images.qrc lang/lang.qrc gui/help/content/content.qrc TRANSLATIONS += \ @@ -856,36 +858,36 @@ pluginmgr { } -blogs { - -DEPENDPATH += gui/unfinished \ - -HEADERS += gui/unfinished/blogs/BlogsDialog.h \ - gui/unfinished/blogs/CreateBlog.h \ - gui/unfinished/blogs/CreateBlogMsg.h \ - gui/unfinished/blogs/BlogsMsgItem.h \ - gui/unfinished/blogs/BlogDetails.h \ - gui/feeds/BlogNewItem.h \ - gui/feeds/BlogMsgItem.h \ - -FORMS += gui/unfinished/blogs/BlogsDialog.ui \ - gui/unfinished/blogs/CreateBlog.ui \ - gui/unfinished/blogs/CreateBlogMsg.ui \ - gui/unfinished/blogs/BlogsMsgItem.ui \ - gui/unfinished/blogs/BlogDetails.ui \ - gui/feeds/BlogNewItem.ui \ - gui/feeds/BlogMsgItem.ui \ - -SOURCES += gui/unfinished/blogs/BlogsDialog.cpp \ - gui/unfinished/blogs/CreateBlog.cpp \ - gui/unfinished/blogs/CreateBlogMsg.cpp \ - gui/unfinished/blogs/BlogsMsgItem.cpp \ - gui/unfinished/blogs/BlogDetails.cpp \ - gui/feeds/BlogNewItem.cpp \ - gui/feeds/BlogMsgItem.cpp \ - -DEFINES += BLOGS -} +#blogs { +# +#DEPENDPATH += gui/unfinished \ +# +#HEADERS += gui/unfinished/blogs/BlogsDialog.h \ +# gui/unfinished/blogs/CreateBlog.h \ +# gui/unfinished/blogs/CreateBlogMsg.h \ +# gui/unfinished/blogs/BlogsMsgItem.h \ +# gui/unfinished/blogs/BlogDetails.h \ +# gui/feeds/BlogNewItem.h \ +# gui/feeds/BlogMsgItem.h \ +# +#FORMS += gui/unfinished/blogs/BlogsDialog.ui \ +# gui/unfinished/blogs/CreateBlog.ui \ +# gui/unfinished/blogs/CreateBlogMsg.ui \ +# gui/unfinished/blogs/BlogsMsgItem.ui \ +# gui/unfinished/blogs/BlogDetails.ui \ +# gui/feeds/BlogNewItem.ui \ +# gui/feeds/BlogMsgItem.ui \ +# +#SOURCES += gui/unfinished/blogs/BlogsDialog.cpp \ +# gui/unfinished/blogs/CreateBlog.cpp \ +# gui/unfinished/blogs/CreateBlogMsg.cpp \ +# gui/unfinished/blogs/BlogsMsgItem.cpp \ +# gui/unfinished/blogs/BlogDetails.cpp \ +# gui/feeds/BlogNewItem.cpp \ +# gui/feeds/BlogMsgItem.cpp \ +# +#DEFINES += BLOGS +#} # use_links { # HEADERS += gui/AddLinksDialog.h \ @@ -930,10 +932,10 @@ unfinished { DEPENDPATH += gui/unfinished \ HEADERS += gui/unfinished/ApplicationWindow.h \ - gui/unfinished/CalDialog.h \ - gui/unfinished/ExampleDialog.h \ - gui/unfinished/GamesDialog.h \ - + +# gui/unfinished/CalDialog.h \ +# gui/unfinished/ExampleDialog.h \ +# gui/unfinished/GamesDialog.h \ # gui/unfinished/profile/ProfileView.h \ # gui/unfinished/profile/ProfileEdit.h # gui/unfinished/StatisticDialog.h \ @@ -941,10 +943,10 @@ unfinished { # gui/unfinished/PhotoShow.h \ FORMS += gui/unfinished/ApplicationWindow.ui \ - gui/unfinished/CalDialog.ui \ - gui/unfinished/ExampleDialog.ui \ - gui/unfinished/GamesDialog.ui \ - + +# gui/unfinished/CalDialog.ui \ +# gui/unfinished/ExampleDialog.ui \ +# gui/unfinished/GamesDialog.ui \ # gui/unfinished/profile/ProfileView.ui \ # gui/unfinished/profile/ProfileEdit.ui # gui/unfinished/StatisticDialog.ui \ @@ -952,10 +954,10 @@ unfinished { # gui/unfinished/PhotoShow.ui \ SOURCES += gui/unfinished/ApplicationWindow.cpp \ - gui/unfinished/CalDialog.cpp \ - gui/unfinished/ExampleDialog.cpp \ - gui/unfinished/GamesDialog.cpp \ - + +# gui/unfinished/CalDialog.cpp \ +# gui/unfinished/ExampleDialog.cpp \ +# gui/unfinished/GamesDialog.cpp \ # gui/unfinished/profile/ProfileView.cpp \ # gui/unfinished/profile/ProfileEdit.cpp # gui/unfinished/StatisticDialog.cpp \ From bfd915864bfd2f49ee368603f39f2ea80527f23e Mon Sep 17 00:00:00 2001 From: drbob Date: Mon, 9 Sep 2013 02:10:49 +0000 Subject: [PATCH 07/83] mods to support hidden node: setup & cert sharing. Also removed old configuration mode from p3cfgmgr git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@6720 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/pgp/rscertificate.cc | 96 ++- libretroshare/src/pgp/rscertificate.h | 4 + libretroshare/src/pqi/p3cfgmgr.cc | 780 +---------------------- libretroshare/src/pqi/p3cfgmgr.h | 72 +-- libretroshare/src/pqi/p3netmgr.cc | 27 +- libretroshare/src/pqi/p3peermgr.cc | 63 +- libretroshare/src/pqi/p3peermgr.h | 4 +- libretroshare/src/pqi/pqisslpersongrp.cc | 9 + libretroshare/src/retroshare/rsinit.h | 7 + libretroshare/src/retroshare/rspeers.h | 9 +- libretroshare/src/rsserver/p3peers.cc | 136 +++- libretroshare/src/rsserver/p3peers.h | 2 + libretroshare/src/rsserver/rsinit.cc | 97 ++- 13 files changed, 387 insertions(+), 919 deletions(-) diff --git a/libretroshare/src/pgp/rscertificate.cc b/libretroshare/src/pgp/rscertificate.cc index 19710fae5..7af451bd5 100644 --- a/libretroshare/src/pgp/rscertificate.cc +++ b/libretroshare/src/pgp/rscertificate.cc @@ -18,6 +18,7 @@ static const std::string EXTERNAL_IP_BEGIN_SECTION ( "--EXT--" ); static const std::string LOCAL_IP_BEGIN_SECTION ( "--LOCAL--" ); static const std::string SSLID_BEGIN_SECTION ( "--SSLID--" ); static const std::string LOCATION_BEGIN_SECTION ( "--LOCATION--" ); +static const std::string HIDDEN_NODE_BEGIN_SECTION ( "--HIDDEN--" ); static const uint8_t CERTIFICATE_PTAG_PGP_SECTION = 0x01 ; static const uint8_t CERTIFICATE_PTAG_EXTIPANDPORT_SECTION = 0x02 ; @@ -26,6 +27,7 @@ static const uint8_t CERTIFICATE_PTAG_DNS_SECTION = 0x04 ; static const uint8_t CERTIFICATE_PTAG_SSLID_SECTION = 0x05 ; static const uint8_t CERTIFICATE_PTAG_NAME_SECTION = 0x06 ; static const uint8_t CERTIFICATE_PTAG_CHECKSUM_SECTION = 0x07 ; +static const uint8_t CERTIFICATE_PTAG_HIDDENNODE_SECTION = 0x08 ; static bool is_acceptable_radix64Char(char c) { @@ -77,9 +79,17 @@ std::string RsCertificate::toStdString() const if(!only_pgp) { - addPacket( CERTIFICATE_PTAG_EXTIPANDPORT_SECTION, ipv4_external_ip_and_port , 6 , buf, p, BS ) ; - addPacket( CERTIFICATE_PTAG_LOCIPANDPORT_SECTION, ipv4_internal_ip_and_port , 6 , buf, p, BS ) ; - addPacket( CERTIFICATE_PTAG_DNS_SECTION , (unsigned char *)dns_name.c_str() , dns_name.length() , buf, p, BS ) ; + if (hidden_node) + { + addPacket( CERTIFICATE_PTAG_HIDDENNODE_SECTION, (unsigned char *)hidden_node_address.c_str(), hidden_node_address.length() , buf, p, BS ) ; + } + else + { + addPacket( CERTIFICATE_PTAG_EXTIPANDPORT_SECTION, ipv4_external_ip_and_port , 6 , buf, p, BS ) ; + addPacket( CERTIFICATE_PTAG_LOCIPANDPORT_SECTION, ipv4_internal_ip_and_port , 6 , buf, p, BS ) ; + addPacket( CERTIFICATE_PTAG_DNS_SECTION , (unsigned char *)dns_name.c_str() , dns_name.length() , buf, p, BS ) ; + } + addPacket( CERTIFICATE_PTAG_NAME_SECTION , (unsigned char *)location_name.c_str() ,location_name.length() , buf, p, BS ) ; addPacket( CERTIFICATE_PTAG_SSLID_SECTION , location_id.toByteArray() ,location_id.SIZE_IN_BYTES, buf, p, BS ) ; } @@ -143,14 +153,31 @@ RsCertificate::RsCertificate(const RsPeerDetails& Detail, const unsigned char *b location_id = SSLIdType( Detail.id ) ; location_name = Detail.location ; - scan_ip(Detail.localAddr,Detail.localPort,ipv4_internal_ip_and_port) ; - scan_ip(Detail.extAddr,Detail.extPort,ipv4_external_ip_and_port) ; + if (Detail.isHiddenNode) + { + hidden_node = true; + hidden_node_address = Detail.hiddenNodeAddress; - dns_name = Detail.dyndns ; + memset(ipv4_internal_ip_and_port,0,6) ; + memset(ipv4_external_ip_and_port,0,6) ; + dns_name = "" ; + } + else + { + hidden_node = false; + hidden_node_address = ""; + + scan_ip(Detail.localAddr,Detail.localPort,ipv4_internal_ip_and_port) ; + scan_ip(Detail.extAddr,Detail.extPort,ipv4_external_ip_and_port) ; + + dns_name = Detail.dyndns ; + } } else { only_pgp = true ; + hidden_node = false; + hidden_node_address = ""; location_id = SSLIdType() ; location_name = "" ; memset(ipv4_internal_ip_and_port,0,6) ; @@ -253,6 +280,13 @@ bool RsCertificate::initFromString(const std::string& instr,uint32_t& err_code) buf = &buf[s] ; break ; + case CERTIFICATE_PTAG_HIDDENNODE_SECTION: + hidden_node_address = std::string((char *)buf,s); + hidden_node = true; + buf = &buf[s]; + + break ; + case CERTIFICATE_PTAG_LOCIPANDPORT_SECTION: if(s != 6) { @@ -314,6 +348,17 @@ bool RsCertificate::initFromString(const std::string& instr,uint32_t& err_code) return true ; } +std::string RsCertificate::hidden_node_string() const +{ + if ((!only_pgp) && (hidden_node)) + { + return hidden_node_address; + } + + std::string empty; + return empty; +} + std::string RsCertificate::sslid_string() const { if (only_pgp) @@ -793,21 +838,34 @@ std::string RsCertificate::toStdString_oldFormat() const res += location_name ; res += ";\n" ; - std::ostringstream os ; - os << LOCAL_IP_BEGIN_SECTION ; - os << (int)ipv4_internal_ip_and_port[0] << "." << (int)ipv4_internal_ip_and_port[1] << "." << (int)ipv4_internal_ip_and_port[2] << "." << (int)ipv4_internal_ip_and_port[3] ; - os << ":" ; - os << ipv4_internal_ip_and_port[4]*256+ipv4_internal_ip_and_port[5] ; - os << ";" ; + if (hidden_node) + { + std::ostringstream os ; + os << HIDDEN_NODE_BEGIN_SECTION; + os << hidden_node_address << ";"; - os << EXTERNAL_IP_BEGIN_SECTION ; - os << (int)ipv4_external_ip_and_port[0] << "." << (int)ipv4_external_ip_and_port[1] << "." << (int)ipv4_external_ip_and_port[2] << "." << (int)ipv4_external_ip_and_port[3] ; - os << ":" ; - os << ipv4_external_ip_and_port[4]*256+ipv4_external_ip_and_port[5] ; - os << ";" ; + res += os.str() ; + res += "\n" ; + } + else + { + std::ostringstream os ; + os << LOCAL_IP_BEGIN_SECTION ; + os << (int)ipv4_internal_ip_and_port[0] << "." << (int)ipv4_internal_ip_and_port[1] << "." << (int)ipv4_internal_ip_and_port[2] << "." << (int)ipv4_internal_ip_and_port[3] ; + os << ":" ; + os << ipv4_internal_ip_and_port[4]*256+ipv4_internal_ip_and_port[5] ; + os << ";" ; + + os << EXTERNAL_IP_BEGIN_SECTION ; + os << (int)ipv4_external_ip_and_port[0] << "." << (int)ipv4_external_ip_and_port[1] << "." << (int)ipv4_external_ip_and_port[2] << "." << (int)ipv4_external_ip_and_port[3] ; + os << ":" ; + os << ipv4_external_ip_and_port[4]*256+ipv4_external_ip_and_port[5] ; + os << ";" ; + + res += os.str() ; + res += "\n" ; + } - res += os.str() ; - res += "\n" ; return res ; } diff --git a/libretroshare/src/pgp/rscertificate.h b/libretroshare/src/pgp/rscertificate.h index 7eefe8551..48143184d 100644 --- a/libretroshare/src/pgp/rscertificate.h +++ b/libretroshare/src/pgp/rscertificate.h @@ -37,6 +37,8 @@ class RsCertificate std::string location_name_string() const { return location_name; } std::string dns_string() const { return dns_name ; } std::string sslid_string() const; + std::string hidden_node_string() const; + std::string armouredPGPKey() const ; unsigned short ext_port_us() const ; @@ -70,7 +72,9 @@ class RsCertificate SSLIdType location_id ; std::string pgp_version ; std::string dns_name ; + std::string hidden_node_address; bool only_pgp ; // does the cert contain only pgp info? + bool hidden_node; // IP or hidden Node Address. }; diff --git a/libretroshare/src/pqi/p3cfgmgr.cc b/libretroshare/src/pqi/p3cfgmgr.cc index 597971994..3d15b6920 100644 --- a/libretroshare/src/pqi/p3cfgmgr.cc +++ b/libretroshare/src/pqi/p3cfgmgr.cc @@ -43,15 +43,10 @@ #define BACKEDUP_SAVE -p3ConfigMgr::p3ConfigMgr(std::string dir, std::string fname, std::string signame) - :basedir(dir), metafname(fname), metasigfname(signame), cfgMtx("p3ConfigMgr"), +p3ConfigMgr::p3ConfigMgr(std::string dir) + :basedir(dir), cfgMtx("p3ConfigMgr"), mConfigSaveActive(true) { - oldConfigType = checkForGlobalSigConfig(); - - // configuration to load correct global types - pqiConfig::globalConfigType = oldConfigType; - } void p3ConfigMgr::tick() @@ -123,242 +118,13 @@ void p3ConfigMgr::saveConfig() } /* save metaconfig */ } - - if(ok && oldConfigType) - removeOldConfigType(); return; } -void p3ConfigMgr::removeOldConfigType() -{ - std::string fName = basedir + "/" + metafname; - std::string sigfName = basedir + "/" + metasigfname; - - remove(fName.c_str()); - remove(sigfName.c_str()); - - //now set globalconfig type to false so mgr saves - oldConfigType = false; - pqiConfig::globalConfigType = oldConfigType; - -} -void p3ConfigMgr::globalSaveConfig() -{ - - RsStackMutex stack(cfgMtx); /***** LOCK STACK MUTEX ****/ - -#ifdef CONFIG_DEBUG - std::cerr << "p3ConfigMgr::globalSaveConfig()"; - std::cerr << std::endl; -#endif - - RsConfigKeyValueSet *item = new RsConfigKeyValueSet(); - - std::map::iterator it; - for(it = configs.begin(); it != configs.end(); it++) - { - if (it->second->HasConfigChanged(1)) - { -#ifdef CONFIG_DEBUG - std::cerr << "p3ConfigMgr::globalSaveConfig() Saving Element: "; - std::cerr << it->first; - std::cerr << std::endl; -#endif - it->second->saveConfiguration(); - } - /* save metaconfig */ - -#ifdef CONFIG_DEBUG - std::cerr << "p3ConfigMgr::globalSaveConfig() Element: "; - std::cerr << it->first << " Hash: " << it->second->Hash(); - std::cerr << std::endl; -#endif - if (it->second->Hash() == "") - { - /* skip if no hash */ - continue; - } - - RsTlvKeyValue kv; - rs_sprintf(kv.key, "%lu", it->first); - kv.value = it->second->Hash(); - item->tlvkvs.pairs.push_back(kv); - } - -#ifdef CONFIG_DEBUG - std::cerr << "p3ConfigMgr::globalSaveConfig() Complete MetaConfigItem: "; - std::cerr << std::endl; - item->print(std::cerr, 20); - -#endif - /* construct filename */ - std::string fname = basedir; - std::string sign_fname = basedir; - std::string fname_backup, sign_fname_backup; // back up files - - if (basedir != "") - { - fname += "/"; - sign_fname += "/"; - } - - fname += metafname; - sign_fname += metasigfname; - fname_backup = fname + ".tmp"; - sign_fname_backup = sign_fname + ".tmp"; - - /* Write the data to a stream */ - uint32_t bioflags = BIN_FLAGS_WRITEABLE; - BinMemInterface *configbio = new BinMemInterface(1000, bioflags); - RsSerialiser *rss = new RsSerialiser(); - rss->addSerialType(new RsGeneralConfigSerialiser()); - pqistore store(rss, "CONFIG", configbio, BIN_FLAGS_WRITEABLE); - - store.SendItem(item); - - /* sign data */ - std::string signature; - AuthSSL::getAuthSSL()->SignData(configbio->memptr(), configbio->memsize(), signature); - - /* write signature to configuration */ - BinMemInterface *signbio = new BinMemInterface(signature.c_str(), - signature.length(), BIN_FLAGS_READABLE); - -#ifdef CONFIG_DEBUG - std::cerr << "p3ConfigMgr::globalSaveConfig() MetaFile Signature:"; - std::cerr << std::endl; - std::cerr << signature; - std::cerr << std::endl; -#endif - - // begin two pass save - backedUpFileSave(fname, fname_backup, sign_fname, sign_fname_backup, configbio, signbio); - - delete signbio; - -} - -bool p3ConfigMgr::backedUpFileSave(const std::string& fname, const std::string& fname_backup, const std::string& sign_fname, - const std::string& sign_fname_backup, BinMemInterface* configbio, BinMemInterface* signbio){ - - FILE *file = NULL, *sign = NULL; - char *config_buff=NULL, *sign_buff=NULL; - int size_file=0, size_sign=0; - - // begin two pass saving by writing to back up file instead - if (!configbio->writetofile(fname_backup.c_str()) || !signbio->writetofile(sign_fname_backup.c_str())) - { -#ifdef CONFIG_DEBUG - std::cerr << "p3ConfigMgr::backedupFileSave() Failed write to Backup MetaFiles " << fname_backup - << " and " << sign_fname_backup; - std::cerr << std::endl; -#endif - return false; - } - -#ifdef CONFIG_DEBUG - std::cerr << "p3Config::backedUpFileSave() Save file and keeps a back up " << std::endl; -#endif - - // open file from which to collect buffer - file = RsDirUtil::rs_fopen(fname.c_str(), "rb"); - sign = RsDirUtil::rs_fopen(sign_fname.c_str(), "rb"); - - // if failed then create files - if((file == NULL) || (sign == NULL)){ -#ifdef CONFIG_DEBUG - std::cerr << "p3Config::backedUpFileSave() failed to open meta files " << fname << std::endl; -#endif - - file = RsDirUtil::rs_fopen(fname.c_str(), "wb"); - sign = RsDirUtil::rs_fopen(sign_fname.c_str(), "wb"); - - if((file == NULL) || (sign == NULL)){ - std::cerr << "p3Config::backedUpFileSave() failed to open backup meta files" << fname_backup << std::endl; - return false; - } - } - - - //determine file size - fseek(file, 0L, SEEK_END); - size_file = ftell(file); - fseek(file, 0L, SEEK_SET); - - fseek(sign, 0L, SEEK_END); - size_sign = ftell(sign); - fseek(sign, 0L, SEEK_SET); - - if((size_file) > 0 && (size_sign > 0)){ - //read this into a buffer - config_buff = new char[size_file]; - fread(config_buff, 1, size_file, file); - - //read this into a buffer - sign_buff = new char[size_sign]; - fread(sign_buff, 1, size_sign, sign); - } - - fclose(file); - fclose(sign); - - // rename back-up to current file - if(!RsDirUtil::renameFile(fname_backup, fname) || !RsDirUtil::renameFile(sign_fname_backup, sign_fname)){ -#ifdef CONFIG_DEBUG - std::cerr << "p3Config::backedUpFileSave() Failed to rename backup meta files: " << std::endl - << fname_backup << " to " << fname << std::endl - << sign_fname_backup << " to " << sign_fname << std::endl; -#endif - if (config_buff) - delete[] config_buff; - if (sign_buff) - delete[] sign_buff; - - return true; - } - - if((size_file) > 0 && (size_sign > 0)){ - - // now write actual back-up file - file = RsDirUtil::rs_fopen(fname_backup.c_str(), "wb"); - sign = RsDirUtil::rs_fopen(sign_fname_backup.c_str(), "wb"); - - if((file == NULL) || (sign == NULL)){ -#ifdef CONFIG_DEBUG - std::cerr << "p3Config::backedUpFileSave() fopen failed for file: " << fname_backup << std::endl; -#endif - delete[] config_buff; - delete[] sign_buff; - - return true; - } - - if(size_file != (int) fwrite(config_buff,1, size_file, file)) - getPqiNotify()->AddSysMessage(0, RS_SYS_WARNING, "Write error", "Error while writing backup configuration file " + fname_backup + "\nIs your disc full or out of quota ?"); - - if(size_sign != (int) fwrite(sign_buff, 1, size_sign, sign)) - getPqiNotify()->AddSysMessage(0, RS_SYS_WARNING, "Write error", "Error while writing main signature file " + sign_fname_backup + "\nIs your disc full or out of quota ?"); - - fclose(file); - fclose(sign); - -#ifdef CONFIG_DEBUG - std::cerr << "p3Config::backedUpFileSave() finished backed up save. " << std::endl; -#endif - - delete[] config_buff; - delete[] sign_buff; - } - return true; -} - void p3ConfigMgr::loadConfiguration() { - if(oldConfigType) - globalLoadConfig(); - else - loadConfig(); + loadConfig(); return; } @@ -385,222 +151,6 @@ void p3ConfigMgr::loadConfig() return; } -void p3ConfigMgr::globalLoadConfig() -{ - RsStackMutex stack(cfgMtx); /***** LOCK STACK MUTEX ****/ - -#ifdef CONFIG_DEBUG - std::cerr << "p3ConfigMgr::loadConfiguration()"; - std::cerr << std::endl; -#endif - - /* construct filename */ - std::string fname = basedir; - std::string sign_fname = basedir; - std::string fname_backup, sign_fname_backup; - - if (basedir != "") - { - fname += "/"; - sign_fname += "/"; - } - - fname += metafname; - sign_fname += metasigfname; - - // temporary files - fname_backup = fname + ".tmp"; - sign_fname_backup = sign_fname + ".tmp"; - - BinMemInterface* membio = new BinMemInterface(1000, BIN_FLAGS_READABLE); - - // Will attempt to get signature first from meta file then if that fails try temporary meta files, these will correspond to temp configs - bool pass = getSignAttempt(fname, sign_fname, membio); - - // if first attempt fails then try and temporary files - if(!pass){ - - #ifdef CONFIG_DEBUG - std::cerr << "\np3ConfigMgr::loadConfiguration(): Trying to load METACONFIG item and METASIGN with temporary files"; - std::cerr << std::endl; - #endif - - pass = getSignAttempt(fname_backup, sign_fname_backup , membio); - - if(!pass){ - #ifdef CONFIG_DEBUG - std::cerr << "\np3ConfigMgr::loadConfiguration(): failed to load METACONFIG item and METASIGN"; - std::cerr << std::endl; - #endif - - return; - } - } - - membio->fseek(0); /* go back to start of file */ - - RsSerialiser *rss = new RsSerialiser(); - rss->addSerialType(new RsGeneralConfigSerialiser()); - pqistore stream(rss, "CONFIG", membio, BIN_FLAGS_READABLE); - - RsItem *rsitem = stream.GetItem(); - - RsConfigKeyValueSet *item = dynamic_cast(rsitem); - if (!item) - { - delete rsitem; - return; - } - -#ifdef CONFIG_DEBUG - std::cerr << "p3ConfigMgr::loadConfiguration() Loaded MetaConfigItem: "; - std::cerr << std::endl; - item->print(std::cerr, 20); - -#endif - - /* extract info from KeyValueSet */ - std::list::iterator it; - for(it = item->tlvkvs.pairs.begin(); it != item->tlvkvs.pairs.end(); it++) - { - /* find the configuration */ - uint32_t confId = atoi(it->key.c_str()); - std::string hashin = it->value; - - /*********************** HACK TO CHANGE CACHE CONFIG ID ********* - * REMOVE IN A MONTH OR TWO - */ - - if (confId == CONFIG_TYPE_CACHE_OLDID) - { - confId = CONFIG_TYPE_CACHE; - } - - /*********************** HACK TO CHANGE CACHE CONFIG ID *********/ - - std::map::iterator cit; - cit = configs.find(confId); - if (cit != configs.end()) - { -#ifdef CONFIG_DEBUG - std::cerr << "p3ConfigMgr::loadConfiguration() Element: "; - std::cerr << confId << " Hash: " << hashin; - std::cerr << std::endl; -#endif - (cit->second)->loadConfiguration(hashin); - - /* force config to CHANGED to force saving into new non-global sig format */ - cit->second->IndicateConfigChanged(); - // cit->second->HasConfigChanged(0); - // cit->second->HasConfigChanged(1); - } - } - - delete item; - -#ifdef CONFIG_DEBUG - std::cerr << "p3ConfigMgr::loadConfiguration() Done!"; - std::cerr << std::endl; -#endif - -} - - -bool p3ConfigMgr::getSignAttempt(std::string& metaConfigFname, std::string& metaSignFname, BinMemInterface* membio){ - - - #ifdef CONFIG_DEBUG - std::cerr << "p3ConfigMgr::getSignAttempt() metaConfigFname : " << metaConfigFname; - std::cerr << std::endl; - std::cerr << "p3ConfigMgr::getSignAttempt() metaSignFname : " << metaSignFname; - std::cerr << std::endl; - #endif - - /* read signature */ - BinMemInterface *signbio = new BinMemInterface(1000, BIN_FLAGS_READABLE); - - if (!signbio->readfromfile(metaSignFname.c_str())) - { - #ifdef CONFIG_DEBUG - std::cerr << "p3ConfigMgr::getSignAttempt() Failed to Load MetaSignFile"; - std::cerr << std::endl; - #endif - - /* HACK to load the old one (with the wrong directory) - * THIS SHOULD BE REMOVED IN A COUPLE OF VERSIONS.... - * ONLY HERE TO CORRECT BAD MISTAKE IN EARLIER VERSIONS. - */ - - metaSignFname = metasigfname; - metaConfigFname = metafname; - - if (!signbio->readfromfile(metaSignFname.c_str())) - { - #ifdef CONFIG_DEBUG - std::cerr << "p3ConfigMgr::getSignAttempt() HACK: Failed to Load ALT MetaSignFile"; - std::cerr << std::endl; - #endif - } - else - { - #ifdef CONFIG_DEBUG - std::cerr << "p3ConfigMgr::getSignAttempt() HACK: Loaded ALT MetaSignFile"; - std::cerr << std::endl; - #endif - } - } - - std::string oldsignature((char *) signbio->memptr(), signbio->memsize()); - delete signbio; - - - - if (!membio->readfromfile(metaConfigFname.c_str())) - { - #ifdef CONFIG_DEBUG - std::cerr << "p3ConfigMgr::getSignAttempt() Failed to Load MetaFile"; - std::cerr << std::endl; - #endif - // delete membio; - // return ; - } - - /* get signature */ - std::string signature; - AuthSSL::getAuthSSL()->SignData(membio->memptr(), membio->memsize(), signature); - - #ifdef CONFIG_DEBUG - std::cerr << "p3ConfigMgr::getSignAttempt() New MetaFile Signature:"; - std::cerr << std::endl; - std::cerr << signature; - std::cerr << std::endl; - #endif - - #ifdef CONFIG_DEBUG - std::cerr << "p3ConfigMgr::getSignAttempt() Orig MetaFile Signature:"; - std::cerr << std::endl; - std::cerr << oldsignature; - std::cerr << std::endl; - #endif - - if (signature != oldsignature) - { - /* Failed */ - #ifdef CONFIG_DEBUG - std::cerr << "p3ConfigMgr::getSignAttempt() Signature Check Failed"; - std::cerr << std::endl; - #endif - return false; - } - -#ifdef CONFIG_DEBUG -std::cerr << "p3ConfigMgr::getSignAttempt() Signature Check Passed!"; -std::cerr << std::endl; -#endif - - return true; - -} void p3ConfigMgr::addConfiguration(std::string file, pqiConfig *conf) { @@ -635,32 +185,7 @@ void p3ConfigMgr::completeConfiguration() mConfigSaveActive = false; } -bool p3ConfigMgr::checkForGlobalSigConfig() -{ - bool oldTypeExists; - FILE *metaFile = NULL, *metaSig = NULL; - std::string fName = basedir + "/" + metafname; - std::string sigName = basedir + "/" + metasigfname; - metaFile = RsDirUtil::rs_fopen(fName.c_str(), "r"); - metaSig = RsDirUtil::rs_fopen(sigName.c_str(), "r"); - - // check if files exist - if((metaFile != NULL) && (metaSig != NULL)) - { - oldTypeExists = true; - fclose(metaFile); - fclose(metaSig); - } - else - oldTypeExists = false; - - - - return oldTypeExists; - - -} p3Config::p3Config(uint32_t t) :pqiConfig(t) @@ -671,10 +196,7 @@ p3Config::p3Config(uint32_t t) bool p3Config::loadConfiguration(std::string &loadHash) { - if(globalConfigType) - return loadGlobalConfig(loadHash); - else - return loadConfig(); + return loadConfig(); } bool p3Config::loadConfig() @@ -790,128 +312,6 @@ bool p3Config::loadAttempt(const std::string& cfgFname,const std::string& signFn return true; } -bool p3Config::loadGlobalConfig(std::string &loadHash) -{ - bool pass = false; - std::string cfg_fname = Filename(); - std::string cfg_fname_backup = cfg_fname + ".tmp"; - std::string hashstr; - std::list load; - -#ifdef CONFIG_DEBUG - std::string success_fname = cfg_fname; - std::cerr << "p3Config::loadConfiguration(): Attempting to load configuration file" << cfg_fname << std::endl; -#endif - - pass = getHashAttempt(loadHash, hashstr, cfg_fname, load); - - if(!pass){ - load.clear(); - pass = getHashAttempt(loadHash, hashstr, cfg_fname_backup, load); -#ifdef CONFIG_DEBUG - std::cerr << "p3Config::loadConfiguration() ERROR: Failed to get Hash from " << success_fname << std::endl; - success_fname = cfg_fname_backup; -#endif - - if(!pass){ -#ifdef CONFIG_DEBUG - std::cerr << "p3Config::loadConfiguration() ERROR: Failed to get Hash from " << success_fname << std::endl; -#endif - return false; - } - } - -#ifdef CONFIG_DEBUG - std::cerr << "p3Config::loadConfiguration(): SUCCESS: configuration file loaded" << success_fname << std::endl; -#endif - - setHash(hashstr); - return loadList(load); -} - - - - -bool p3Config::getHashAttempt(const std::string& loadHash, std::string& hashstr,const std::string& cfg_fname, - std::list& load){ - - std::list::iterator it; - - uint32_t bioflags = BIN_FLAGS_HASH_DATA | BIN_FLAGS_READABLE; - - BinInterface *bio = new BinFileInterface(cfg_fname.c_str(), bioflags); - PQInterface *stream = NULL; - - std::string tempString, msgConfigFileName; - std::string filename = Filename() ; - std::string::reverse_iterator rit = filename.rbegin(); - - - // get the msgconfig file name - for(int i =0; (i <= 7) && (rit != filename.rend()); i++) - { - tempString.push_back(*rit); - rit++; - } - - rit = tempString.rbegin(); - - for(; rit !=tempString.rend(); rit++) - msgConfigFileName.push_back(*rit); - - if(msgConfigFileName == "msgs.cfg") - stream = new pqiarchive(setupSerialiser(), bio, bioflags); - else - stream = new pqistore(setupSerialiser(), "CONFIG", bio, bioflags); - - RsItem *item = NULL; - - while(NULL != (item = stream->GetItem())) - { -#ifdef CONFIG_DEBUG - std::cerr << "p3Config::loadConfiguration() loaded item:"; - std::cerr << std::endl; - item->print(std::cerr, 0); - std::cerr << std::endl; -#endif - load.push_back(item); - } - -#ifdef CONFIG_DEBUG - std::cerr << "p3Config::loadConfiguration() loaded " << load.size(); - std::cerr << " Elements from File: " << cfg_fname; - std::cerr << std::endl; -#endif - - /* check hash */ - hashstr = bio->gethash(); - - // if hash then atmpt load with temporary file - if (hashstr != loadHash) - { - -#ifdef CONFIG_DEBUG - std::cerr << "p3Config::loadConfiguration() ERROR: Hash != MATCHloaded"; - std::cerr << std::endl; -#endif - - /* bad load */ - for(it = load.begin(); it != load.end(); it++) - { - delete (*it); - } - - setHash(""); - - delete stream; - return false; - } - - delete stream; - return true; -} - - bool p3Config::saveConfiguration() { return saveConfig(); @@ -1003,176 +403,6 @@ bool p3Config::saveConfig() } -bool p3Config::saveGlobalConfig() -{ - - bool cleanup = true; - std::list toSave; - saveList(cleanup, toSave); - - - std::string cfg_fname = Filename(); // get configuration file name - std::string cfg_fname_backup = Filename()+".tmp"; // backup file for two pass save - -#ifdef CONFIG_DEBUG - std::cerr << "Writting p3config file " << cfg_fname << std::endl ; - std::cerr << "p3Config::saveConfiguration() toSave " << toSave.size(); - std::cerr << " Elements to File: " << cfg_fname; - std::cerr << std::endl; -#endif - - // saves current config and keeps back-up (old configuration) - if(!backedUpFileSave(cfg_fname, cfg_fname_backup, toSave, cleanup)){ -#ifdef CONFIG_DEBUG - std::cerr << "p3Config::saveConfiguration(): Failed to save file" << std::endl; -#endif - return false; - } - - saveDone(); // callback to inherited class to unlock any Mutexes protecting saveList() data - - return true; -} - - -bool p3Config::backedUpFileSave(const std::string& cfg_fname, const std::string& cfg_fname_backup, std::list& itemList, - bool cleanup){ - - uint32_t bioflags = BIN_FLAGS_HASH_DATA | BIN_FLAGS_WRITEABLE; - uint32_t stream_flags = BIN_FLAGS_WRITEABLE; - bool written = true; - FILE* cfg_file = NULL; - char* buff=NULL; - int size_file = 0; - - if (!cleanup) - stream_flags |= BIN_FLAGS_NO_DELETE; - - BinInterface *bio = new BinFileInterface(cfg_fname_backup.c_str(), bioflags); - pqistore *stream = new pqistore(setupSerialiser(), "CONFIG", bio, stream_flags); - - std::list::iterator it; - - for(it = itemList.begin(); it != itemList.end(); it++) - { -#ifdef CONFIG_DEBUG - std::cerr << "p3Config::backedUpFileSave() save item:"; - std::cerr << std::endl; - (*it)->print(std::cerr, 0); - std::cerr << std::endl; -#endif - written = written && stream->SendItem(*it); - -#ifdef CONFIG_DEBUG - std::cerr << "p3Config::backedUpFileSave() saved "; -#endif - - } - - /* store the hash */ - setHash(bio->gethash()); - - // bio is taken care of in stream's destructor - delete stream; - -#ifdef CONFIG_DEBUG - std::cerr << "p3Config::backedUpFileSave() Save file and keeps a back up " << std::endl; -#endif - - // open file from which to collect buffer - cfg_file = RsDirUtil::rs_fopen(cfg_fname.c_str(), "rb"); - - // if it fails to open, create file,but back-up file will now be empty - if(cfg_file == NULL){ - #ifdef CONFIG_DEBUG - std::cerr << "p3Config::backedUpFileSave() fopen failed for file: " << cfg_fname << std::endl; - #endif - - cfg_file = RsDirUtil::rs_fopen(cfg_fname.c_str(), "wb"); - - if(cfg_file == NULL) - { - std::cerr << "p3Config::backedUpFileSave() fopen failed for file:" << cfg_fname << std::endl; - return false ; - } - } - - //determine file size - fseek(cfg_file, 0L, SEEK_END); - size_file = ftell(cfg_file); - - if(size_file < 0) // ftell returns -1 when fails - { - fclose(cfg_file); - size_file = 0 ; - } - - fseek(cfg_file, 0L, SEEK_SET); - -#ifdef CONFIG_DEBUG - std::cerr << "p3Config::backedUpFileSave(): Size of file: " << size_file << std::endl; -#endif - - // no point continuing, empty files all have same hash - if(size_file > 0){ - - //read this into a data buffer - buff = new char[size_file]; - fread(buff, 1, size_file, cfg_file); - } - - fclose(cfg_file); - - // rename back-up to current file, if this fails should return false hash's will not match at startup - if(!RsDirUtil::renameFile(cfg_fname_backup, cfg_fname)){ -#ifdef CONFIG_DEBUG - std::cerr << "p3Config::backedUpFileSave() Failed to rename file" << cfg_fname_backup << " to " - << cfg_fname << std::endl; -#endif - written &= false; // at least one file save should be successful - } - - if(size_file > 0) - { - - // now write actual back-up file - cfg_file = RsDirUtil::rs_fopen(cfg_fname_backup.c_str(), "wb"); - - if(cfg_file == NULL){ -#ifdef CONFIG_DEBUG - std::cerr << "p3Config::backedUpFileSave() fopen failed for file: " << cfg_fname_backup << std::endl; -#endif - } - - if(size_file != (int) fwrite(buff, 1, size_file, cfg_file)) - { - getPqiNotify()->AddSysMessage(0, RS_SYS_WARNING, "Write error", "Error while writing backup configuration file " + cfg_fname_backup + "\nIs your disc full or out of quota ?"); - fclose(cfg_file); - delete[] buff; - return false ; - } - - - fclose(cfg_file); - -#ifdef CONFIG_DEBUG - std::cerr << "p3Config::backedUpFileSave() finished backed up save. " << std::endl; -#endif - - - delete[] buff; - written |= true; // either backup or current file should have been saved - } - - -#ifdef CONFIG_DEBUG - std::cerr << "p3Config::backedUpFileSave() finished backed up save. " << std::endl; -#endif - - return written; -} - - /**************************** CONFIGURATION CLASSES ********************/ p3GeneralConfig::p3GeneralConfig() @@ -1313,8 +543,6 @@ bool p3GeneralConfig::loadList(std::list& load) * only the Indication and hash really need it */ -bool pqiConfig::globalConfigType = false; - pqiConfig::pqiConfig(uint32_t t) : cfgMtx("pqiConfig"), ConfInd(2), type(t) { diff --git a/libretroshare/src/pqi/p3cfgmgr.h b/libretroshare/src/pqi/p3cfgmgr.h index 355cc2d43..fa3f83246 100644 --- a/libretroshare/src/pqi/p3cfgmgr.h +++ b/libretroshare/src/pqi/p3cfgmgr.h @@ -63,7 +63,6 @@ const uint32_t CONFIG_TYPE_GENERAL = 0x0001; const uint32_t CONFIG_TYPE_PEERS = 0x0002; const uint32_t CONFIG_TYPE_FSERVER = 0x0003; const uint32_t CONFIG_TYPE_MSGS = 0x0004; -const uint32_t CONFIG_TYPE_CACHE_OLDID = 0x0005; const uint32_t CONFIG_TYPE_AUTHGPG = 0x0006; /* new FileTransfer */ @@ -155,8 +154,6 @@ void setHash(const std::string& h); RsMutex cfgMtx; - static bool globalConfigType; - private: /** @@ -200,10 +197,8 @@ class p3ConfigMgr /** * @param bdir base directory: where config files will be saved - * @param fname file name for global configuration - * @param signame file name for global signature */ - p3ConfigMgr(std::string bdir, std::string fname, std::string signame); + p3ConfigMgr(std::string bdir); /** * checks and update all added configurations @@ -237,31 +232,6 @@ class p3ConfigMgr private: - /** - * this checks for the global config file and signature and determines class's mode of operation - * @return global file rs-v0.#.cfg and rs-v0.#.sgn are present - * @deprecated - */ - bool checkForGlobalSigConfig(); - - /** - * removes theoldconfiguration type - * @deprecated - */ - void removeOldConfigType(); - - /** - * to save old style global-signature configuration files - * @deprecated - */ - void globalSaveConfig(); - - /** - * to load up old style global-signature config files - * @deprecated - */ - void globalLoadConfig(); - /** * saves configuration of pqiconfigs in object configs */ @@ -272,33 +242,10 @@ class p3ConfigMgr */ void loadConfig(); - /** - * checks if signature and configuration file's signature matches - * @return false if signature file does not match configuration file's signature - */ - bool getSignAttempt(std::string& metaConfigFname, std::string& metaSignFname, BinMemInterface* membio); - - /** - * takes current configuration which is stored in back-up file, and moves it to actual config file - * then stores data that was in actual config file into back-up, Corresponding signatures and handled - * simlarly in parallel - *@param fname the name of the first configuration file checked - *@param fname_backup the seconf file, backup, checked if first file does not exist or is corrupted - *@param sign file name in which signature is kept - *@param sign_backup file name in which signature which correspond to backup config is kept - *@param configbio to write config to file - *@param signbio to write signature config to file - */ - bool backedUpFileSave(const std::string& fname, const std::string& fname_backup,const std::string& sign, - const std::string& sign_backup, BinMemInterface* configbio, BinMemInterface* signbio); - const std::string basedir; -const std::string metafname; -const std::string metasigfname; RsMutex cfgMtx; /* below is protected */ -bool oldConfigType; bool mConfigSaveActive; std::map configs; }; @@ -351,26 +298,9 @@ virtual void saveDone() { return; } private: -/** - * takes current configuration which is stored in back-up file, and moves it to actual config file - * then stores data that was in actual config file into back-up, This is an rs specific solution - * @param fname the name of the first configuration file checked - * @param fname_backup the seconf file, backup, checked if first file does not exist or is corrupted - */ -bool backedUpFileSave(const std::string& fname, const std::string& fname_backup, std::list& toSave, - bool cleanup); - -/* - * for retrieving hash files - */ -bool getHashAttempt(const std::string& loadHash, std::string& hashstr, const std::string& fname, std::list& load); - bool loadConfig(); bool saveConfig(); -bool loadGlobalConfig(std::string& hash); -bool saveGlobalConfig(); - bool loadAttempt(const std::string&,const std::string&, std::list& load); }; /* end of p3Config */ diff --git a/libretroshare/src/pqi/p3netmgr.cc b/libretroshare/src/pqi/p3netmgr.cc index c3f029433..554c535a5 100644 --- a/libretroshare/src/pqi/p3netmgr.cc +++ b/libretroshare/src/pqi/p3netmgr.cc @@ -380,6 +380,13 @@ void p3NetMgrIMPL::netStartup() mNetStatus = RS_NET_EXT_SETUP; break; + case RS_NET_MODE_TRY_LOOPBACK: + std::cerr << "p3NetMgrIMPL::netStartup() TRY_LOOPBACK mode"; + std::cerr << std::endl; + mNetMode |= RS_NET_MODE_HIDDEN; + mNetStatus = RS_NET_LOOPBACK; + break; + default: // Fall through. #ifdef NETMGR_DEBUG_RESET @@ -535,6 +542,7 @@ void p3NetMgrIMPL::netTick() case RS_NET_LOOPBACK: //don't do a shutdown because a client in a computer without local network might be usefull for debug. //shutdown(); + std::cerr << "p3NetMgrIMPL::netTick() STATUS: RS_NET_LOOPBACK" << std::endl; #if defined(NETMGR_DEBUG_TICK) || defined(NETMGR_DEBUG_RESET) std::cerr << "p3NetMgrIMPL::netTick() STATUS: RS_NET_LOOPBACK" << std::endl; #endif @@ -905,7 +913,18 @@ bool p3NetMgrIMPL::checkNetAddress() struct in_addr prefAddr; struct sockaddr_in oldAddr; - validAddr = getPreferredInterface(mLocalAddr.sin_addr, prefAddr); + if (mNetMode & RS_NET_MODE_TRY_LOOPBACK) + { + std::cerr << "p3NetMgrIMPL::checkNetAddress() LOOPBACK ... forcing to 127.0.0.1"; + std::cerr << std::endl; + inet_aton("127.0.0.1", &prefAddr); + validAddr = true; + } + else + { + validAddr = getPreferredInterface(mLocalAddr.sin_addr, prefAddr); + } + /* if we don't have a valid address - reset */ if (!validAddr) @@ -1108,12 +1127,12 @@ bool p3NetMgrIMPL::setNetworkMode(uint32_t netMode) oldNetMode = mNetMode; -#ifdef NETMGR_DEBUG +//#ifdef NETMGR_DEBUG std::cerr << "p3NetMgrIMPL::setNetworkMode()"; std::cerr << " Existing netMode: " << mNetMode; std::cerr << " Input netMode: " << netMode; std::cerr << std::endl; -#endif +//#endif mNetMode &= ~(RS_NET_MODE_TRYMODE); switch(netMode & RS_NET_MODE_ACTUAL) @@ -1125,7 +1144,7 @@ bool p3NetMgrIMPL::setNetworkMode(uint32_t netMode) mNetMode |= RS_NET_MODE_TRY_UPNP; break; case RS_NET_MODE_HIDDEN: - mNetMode |= RS_NET_MODE_TRY_UDP; // FOR THE MOMENT HIDDEN acts like = UDP. + mNetMode |= RS_NET_MODE_TRY_LOOPBACK; break; default: case RS_NET_MODE_UDP: diff --git a/libretroshare/src/pqi/p3peermgr.cc b/libretroshare/src/pqi/p3peermgr.cc index 8009ec7b8..cef80f5cf 100644 --- a/libretroshare/src/pqi/p3peermgr.cc +++ b/libretroshare/src/pqi/p3peermgr.cc @@ -124,7 +124,7 @@ p3PeerMgrIMPL::p3PeerMgrIMPL( const std::string& ssl_own_id, // setup default ProxyServerAddress. sockaddr_clear(&mProxyServerAddress); inet_aton("127.0.0.1", &(mProxyServerAddress.sin_addr)); - mProxyServerAddress.sin_port = htons(7050); + mProxyServerAddress.sin_port = htons(9100); } @@ -142,18 +142,45 @@ void p3PeerMgrIMPL::setManagers(p3LinkMgrIMPL *linkMgr, p3NetMgrIMPL *netMgr) mNetMgr = netMgr; } +bool p3PeerMgrIMPL::setupHiddenNode(const std::string &hiddenAddress, const uint16_t hiddenPort) +{ + std::cerr << "p3PeerMgrIMPL::setupHiddenNode()"; + std::cerr << " Address: " << hiddenAddress; + std::cerr << " Port: " << hiddenPort; + std::cerr << std::endl; + + setOwnNetworkMode(RS_NET_MODE_HIDDEN); + mOwnState.hiddenNode = true; + mOwnState.hiddenPort = hiddenPort; + mOwnState.hiddenDomain = hiddenAddress; + + // switch off DHT too. + setOwnVisState(RS_VIS_STATE_GRAY); + + // Force the Port. + struct sockaddr_in loopback; + sockaddr_clear(&loopback); + inet_aton("127.0.0.1", &(loopback.sin_addr)); + loopback.sin_port = htons(hiddenPort); + + setLocalAddress(AuthSSL::getAuthSSL()->OwnId(), loopback); + + return true; +} + + bool p3PeerMgrIMPL::setOwnNetworkMode(uint32_t netMode) { bool changed = false; { RsStackMutex stack(mPeerMtx); /****** STACK LOCK MUTEX *******/ -#ifdef PEER_DEBUG +//#ifdef PEER_DEBUG std::cerr << "p3PeerMgrIMPL::setOwnNetworkMode() :"; std::cerr << " Existing netMode: " << mOwnState.netMode; std::cerr << " Input netMode: " << netMode; std::cerr << std::endl; -#endif +//#endif if (mOwnState.netMode != (netMode & RS_NET_MODE_ACTUAL)) { @@ -290,28 +317,50 @@ bool p3PeerMgrIMPL::isHiddenPeer(const std::string &ssl_id) it = mFriendList.find(ssl_id); if (it == mFriendList.end()) { - return (it->second).hiddenNode; + std::cerr << "p3PeerMgrIMPL::isHiddenPeer(" << ssl_id << ") Missing Peer => false"; + std::cerr << std::endl; + + return false; } - /* is it hidden ?? */ - return false; + std::cerr << "p3PeerMgrIMPL::isHiddenPeer(" << ssl_id << ") = " << (it->second).hiddenNode; + std::cerr << std::endl; + return (it->second).hiddenNode; } bool p3PeerMgrIMPL::setHiddenDomainPort(const std::string &ssl_id, const std::string &domain_addr, const uint16_t domain_port) { RsStackMutex stack(mPeerMtx); /****** STACK LOCK MUTEX *******/ + std::cerr << "p3PeerMgrIMPL::setHiddenDomainPort()"; + std::cerr << std::endl; + + if (ssl_id == AuthSSL::getAuthSSL()->OwnId()) + { + mOwnState.hiddenNode = true; + mOwnState.hiddenDomain = domain_addr; + mOwnState.hiddenPort = domain_port; + std::cerr << "p3PeerMgrIMPL::setHiddenDomainPort() Set own State"; + std::cerr << std::endl; + return true; + } + /* check for existing */ std::map::iterator it; it = mFriendList.find(ssl_id); if (it == mFriendList.end()) { + std::cerr << "p3PeerMgrIMPL::setHiddenDomainPort() Peer Not Found"; + std::cerr << std::endl; return false; } it->second.hiddenDomain = domain_addr; it->second.hiddenPort = domain_port; it->second.hiddenNode = true; + std::cerr << "p3PeerMgrIMPL::setHiddenDomainPort() Set Peers State"; + std::cerr << std::endl; + return true; } @@ -1414,6 +1463,8 @@ bool p3PeerMgrIMPL::saveList(bool &cleanup, std::list& saveData) item->dyndns = mOwnState.dyndns; mOwnState.ipAddrs.mLocal.loadTlv(item->localAddrList); mOwnState.ipAddrs.mExt.loadTlv(item->extAddrList); + item->domain_addr = mOwnState.hiddenDomain; + item->domain_port = mOwnState.hiddenPort; #ifdef PEER_DEBUG std::cerr << "p3PeerMgrIMPL::saveList() Own Config Item:" << std::endl; diff --git a/libretroshare/src/pqi/p3peermgr.h b/libretroshare/src/pqi/p3peermgr.h index ade27a15f..bede98560 100644 --- a/libretroshare/src/pqi/p3peermgr.h +++ b/libretroshare/src/pqi/p3peermgr.h @@ -60,7 +60,7 @@ const uint32_t RS_NET_MODE_TRYMODE = 0xff00; const uint32_t RS_NET_MODE_TRY_EXT = 0x0100; const uint32_t RS_NET_MODE_TRY_UPNP = 0x0200; const uint32_t RS_NET_MODE_TRY_UDP = 0x0400; -const uint32_t RS_NET_MODE_TRY_HIDDEN = 0x0800; +const uint32_t RS_NET_MODE_TRY_LOOPBACK = 0x0800; /* Actual State */ const uint32_t RS_NET_MODE_ACTUAL = 0x00ff; @@ -315,6 +315,8 @@ virtual bool haveOnceConnected(); void setManagers(p3LinkMgrIMPL *linkMgr, p3NetMgrIMPL *netMgr); +bool setupHiddenNode(const std::string &hiddenAddress, const uint16_t hiddenPort); + void tick(); const std::string getOwnId(); diff --git a/libretroshare/src/pqi/pqisslpersongrp.cc b/libretroshare/src/pqi/pqisslpersongrp.cc index 00569eaab..4b771b7b2 100644 --- a/libretroshare/src/pqi/pqisslpersongrp.cc +++ b/libretroshare/src/pqi/pqisslpersongrp.cc @@ -67,6 +67,9 @@ bool pqisslpersongrp::locked_getCryptoParams(const std::string& id,RsPeerCryptoP pqiperson * pqisslpersongrp::locked_createPerson(std::string id, pqilistener *listener) { + std::cerr << "pqisslpersongrp::locked_createPerson() PeerId: " << id; + std::cerr << std::endl; + pqioutput(PQL_DEBUG_BASIC, pqipersongrpzone, "pqipersongrp::createPerson() PeerId: " + id); pqiperson *pqip = new pqiperson(id, this); @@ -74,6 +77,9 @@ pqiperson * pqisslpersongrp::locked_createPerson(std::string id, pqilistener *li // If using proxy, then only create a proxy item, otherwise can use any. if (mPeerMgr->isHiddenPeer(id)) { + std::cerr << "pqisslpersongrp::locked_createPerson() Is Hidden Peer!"; + std::cerr << std::endl; + pqisslproxy *pqis = new pqisslproxy((pqissllistener *) listener, pqip, mLinkMgr); /* construct the serialiser .... @@ -96,6 +102,9 @@ pqiperson * pqisslpersongrp::locked_createPerson(std::string id, pqilistener *li } else { + std::cerr << "pqisslpersongrp::locked_createPerson() Is Normal Peer!"; + std::cerr << std::endl; + pqissl *pqis = new pqissl((pqissllistener *) listener, pqip, mLinkMgr); /* construct the serialiser .... diff --git a/libretroshare/src/retroshare/rsinit.h b/libretroshare/src/retroshare/rsinit.h index 9e7001e4f..bfde25f8f 100644 --- a/libretroshare/src/retroshare/rsinit.h +++ b/libretroshare/src/retroshare/rsinit.h @@ -44,6 +44,7 @@ #include #include #include +#include /*! * Initialisation Class (not publicly disclosed to RsIFace) @@ -95,6 +96,12 @@ class RsInit // copies existing gnupg keyrings to the new place of the OpenPGP-SDK version. Returns true on success. static bool copyGnuPGKeyrings() ; + + /*! + * Setup Hidden Location; + */ + static bool SetHiddenLocation(const std::string& hiddenaddress, uint16_t port); + /*! * Login GGP */ diff --git a/libretroshare/src/retroshare/rspeers.h b/libretroshare/src/retroshare/rspeers.h index fbabc7bc2..fb04c649d 100644 --- a/libretroshare/src/retroshare/rspeers.h +++ b/libretroshare/src/retroshare/rspeers.h @@ -54,7 +54,8 @@ const uint32_t RS_TRUST_LVL_ULTIMATE = 5; const uint32_t RS_NETMODE_UDP = 0x0001; const uint32_t RS_NETMODE_UPNP = 0x0002; const uint32_t RS_NETMODE_EXT = 0x0003; -const uint32_t RS_NETMODE_UNREACHABLE = 0x0004; +const uint32_t RS_NETMODE_HIDDEN = 0x0004; +const uint32_t RS_NETMODE_UNREACHABLE = 0x0005; /* Visibility */ const uint32_t RS_VS_DHT_ON = 0x0001; @@ -206,6 +207,10 @@ class RsPeerDetails /* Network details (only valid if friend) */ uint32_t state; + bool isHiddenNode; + std::string hiddenNodeAddress; + + // Filled in for Standard Node. std::string localAddr; uint16_t localPort; std::string extAddr; @@ -310,6 +315,8 @@ class RsPeers /* Network Stuff */ virtual bool connectAttempt(const std::string &ssl_id) = 0; virtual bool setLocation(const std::string &ssl_id, const std::string &location) = 0;//location is shown in the gui to differentiate ssl certs + virtual bool setHiddenNode(const std::string &id, const std::string &hidden_node_address) = 0; + virtual bool setLocalAddress(const std::string &ssl_id, const std::string &addr, uint16_t port) = 0; virtual bool setExtAddress( const std::string &ssl_id, const std::string &addr, uint16_t port) = 0; virtual bool setDynDNS(const std::string &id, const std::string &addr) = 0; diff --git a/libretroshare/src/rsserver/p3peers.cc b/libretroshare/src/rsserver/p3peers.cc index 98be1a9f1..e0385fd35 100644 --- a/libretroshare/src/rsserver/p3peers.cc +++ b/libretroshare/src/rsserver/p3peers.cc @@ -107,6 +107,10 @@ std::string RsPeerNetModeString(uint32_t netModel) { str = "UDP Mode"; } + else if (netModel == RS_NETMODE_HIDDEN) + { + str = "Hidden"; + } else if (netModel == RS_NETMODE_UNREACHABLE) { str = "UDP Mode (Unreachable)"; @@ -302,31 +306,47 @@ bool p3Peers::getPeerDetails(const std::string &id, RsPeerDetails &d) d.authcode = "AUTHCODE"; /* fill from pcs */ - - d.localAddr = rs_inet_ntoa(ps.localaddr.sin_addr); - d.localPort = ntohs(ps.localaddr.sin_port); - d.extAddr = rs_inet_ntoa(ps.serveraddr.sin_addr); - d.extPort = ntohs(ps.serveraddr.sin_port); - d.dyndns = ps.dyndns; d.lastConnect = ps.lastcontact; d.connectPeriod = 0; - std::list::iterator it; - for(it = ps.ipAddrs.mLocal.mAddrs.begin(); - it != ps.ipAddrs.mLocal.mAddrs.end(); it++) + if (ps.hiddenNode) { - std::string toto; - rs_sprintf(toto, "%u %ld sec", ntohs(it->mAddr.sin_port), time(NULL) - it->mSeenTime); - d.ipAddressList.push_back("L:" + rs_inet_ntoa(it->mAddr.sin_addr) + ":" + toto); + d.isHiddenNode = true; + rs_sprintf(d.hiddenNodeAddress, "%s:%u", ps.hiddenDomain.c_str(), ps.hiddenPort); + d.localAddr = "hidden"; + d.localPort = 0; + d.extAddr = "hidden"; + d.extPort = 0; + d.dyndns = ""; } - for(it = ps.ipAddrs.mExt.mAddrs.begin(); - it != ps.ipAddrs.mExt.mAddrs.end(); it++) + else { - std::string toto; - rs_sprintf(toto, "%u %ld sec", ntohs(it->mAddr.sin_port), time(NULL) - it->mSeenTime); - d.ipAddressList.push_back("E:" + rs_inet_ntoa(it->mAddr.sin_addr) + ":" + toto); - } + d.isHiddenNode = false; + d.hiddenNodeAddress = ""; + d.localAddr = rs_inet_ntoa(ps.localaddr.sin_addr); + d.localPort = ntohs(ps.localaddr.sin_port); + d.extAddr = rs_inet_ntoa(ps.serveraddr.sin_addr); + d.extPort = ntohs(ps.serveraddr.sin_port); + d.dyndns = ps.dyndns; + + std::list::iterator it; + for(it = ps.ipAddrs.mLocal.mAddrs.begin(); + it != ps.ipAddrs.mLocal.mAddrs.end(); it++) + { + std::string toto; + rs_sprintf(toto, "%u %ld sec", ntohs(it->mAddr.sin_port), time(NULL) - it->mSeenTime); + d.ipAddressList.push_back("L:" + rs_inet_ntoa(it->mAddr.sin_addr) + ":" + toto); + } + for(it = ps.ipAddrs.mExt.mAddrs.begin(); + it != ps.ipAddrs.mExt.mAddrs.end(); it++) + { + std::string toto; + rs_sprintf(toto, "%u %ld sec", ntohs(it->mAddr.sin_port), time(NULL) - it->mSeenTime); + d.ipAddressList.push_back("E:" + rs_inet_ntoa(it->mAddr.sin_addr) + ":" + toto); + } + } + switch(ps.netMode & RS_NET_MODE_ACTUAL) { @@ -339,6 +359,9 @@ bool p3Peers::getPeerDetails(const std::string &id, RsPeerDetails &d) case RS_NET_MODE_UDP: d.netMode = RS_NETMODE_UDP; break; + case RS_NET_MODE_HIDDEN: + d.netMode = RS_NETMODE_HIDDEN; + break; case RS_NET_MODE_UNREACHABLE: case RS_NET_MODE_UNKNOWN: default: @@ -706,6 +729,53 @@ bool p3Peers::getAllowServerIPDetermination() return mNetMgr->getIPServersEnabled() ; } +bool p3Peers::setLocation(const std::string &ssl_id, const std::string &location) +{ +#ifdef P3PEERS_DEBUG + std::cerr << "p3Peers::setLocation() " << ssl_id << std::endl; +#endif + + return mPeerMgr->setLocation(ssl_id, location); +} + +bool p3Peers::setHiddenNode(const std::string &id, const std::string &hidden_node_address) +{ +#ifdef P3PEERS_DEBUG + std::cerr << "p3Peers::setHiddenNode() " << id << std::endl; +#endif + + size_t cpos = hidden_node_address.rfind(':'); + if (cpos == std::string::npos) + { + std::cerr << "p3Peers::setHiddenNode() Failed to parse (:) " << hidden_node_address << std::endl; + return false; + } + + int lenport = hidden_node_address.length() - (cpos + 1); // +1 to skip over : char. + if (lenport <= 0) + { + std::cerr << "p3Peers::setHiddenNode() Missing Port: " << hidden_node_address << std::endl; + return false; + } + + std::string domain = hidden_node_address.substr(0, cpos); + std::string port = hidden_node_address.substr(cpos + 1, std::string::npos); + int portint = atoi(port.c_str()); + + if ((portint < 0) || (portint > 65535)) + { + std::cerr << "p3Peers::setHiddenNode() Invalid Port: " << hidden_node_address << std::endl; + return false; + } + + std::cerr << "p3Peers::setHiddenNode() Domain: " << domain << " Port: " << portint; + std::cerr << std::endl; + + mPeerMgr->setNetworkMode(id, RS_NET_MODE_HIDDEN); + mPeerMgr->setHiddenDomainPort(id, domain, (uint16_t) portint); + return true; +} + bool p3Peers::setLocalAddress(const std::string &id, const std::string &addr_str, uint16_t port) { #ifdef P3PEERS_DEBUG @@ -731,14 +801,6 @@ bool p3Peers::setLocalAddress(const std::string &id, const std::string &addr_st return false; } -bool p3Peers::setLocation(const std::string &ssl_id, const std::string &location) -{ -#ifdef P3PEERS_DEBUG - std::cerr << "p3Peers::setLocation() " << ssl_id << std::endl; -#endif - - return mPeerMgr->setLocation(ssl_id, location); -} bool p3Peers::setExtAddress(const std::string &id, const std::string &addr_str, uint16_t port) { #ifdef P3PEERS_DEBUG @@ -791,6 +853,9 @@ bool p3Peers::setNetworkMode(const std::string &id, uint32_t extNetMode) case RS_NETMODE_UDP: netMode = RS_NET_MODE_UDP; break; + case RS_NETMODE_HIDDEN: + netMode = RS_NET_MODE_HIDDEN; + break; case RS_NETMODE_UNREACHABLE: netMode = RS_NET_MODE_UNREACHABLE; break; @@ -923,13 +988,22 @@ bool p3Peers::loadDetailsFromStringCert(const std::string &certstr, RsPeerDetai pd.id = cert.sslid_string() ; pd.location = cert.location_name_string(); - pd.localAddr = cert.loc_ip_string(); - pd.localPort = cert.loc_port_us(); - pd.extAddr = cert.ext_ip_string(); - pd.extPort = cert.ext_port_us(); - pd.dyndns = cert.dns_string() ; + pd.isOnlyGPGdetail = pd.id.empty(); pd.service_perm_flags = RS_SERVICE_PERM_ALL ; + + if (pd.isHiddenNode) + { + pd.hiddenNodeAddress = cert.hidden_node_string(); + } + else + { + pd.localAddr = cert.loc_ip_string(); + pd.localPort = cert.loc_port_us(); + pd.extAddr = cert.ext_ip_string(); + pd.extPort = cert.ext_port_us(); + pd.dyndns = cert.dns_string() ; + } } catch(uint32_t e) { diff --git a/libretroshare/src/rsserver/p3peers.h b/libretroshare/src/rsserver/p3peers.h index cc5f54d07..6305dc1d7 100644 --- a/libretroshare/src/rsserver/p3peers.h +++ b/libretroshare/src/rsserver/p3peers.h @@ -84,6 +84,8 @@ virtual bool removeFriendLocation(const std::string &sslId); /* Network Stuff */ virtual bool connectAttempt(const std::string &id); virtual bool setLocation(const std::string &ssl_id, const std::string &location);//location is shown in the gui to differentiate ssl certs +virtual bool setHiddenNode(const std::string &id, const std::string &hidden_node_address); + virtual bool setLocalAddress(const std::string &id, const std::string &addr, uint16_t port); virtual bool setExtAddress(const std::string &id, const std::string &addr, uint16_t port); virtual bool setDynDNS(const std::string &id, const std::string &dyndns); diff --git a/libretroshare/src/rsserver/rsinit.cc b/libretroshare/src/rsserver/rsinit.cc index d917cbc2b..b1e4b146d 100644 --- a/libretroshare/src/rsserver/rsinit.cc +++ b/libretroshare/src/rsserver/rsinit.cc @@ -125,6 +125,11 @@ class RsInitConfig static unsigned short port; static std::string inet ; + /* v0.6 features */ + static bool forceApiUpgrade; + static std::string hiddenNodeAddress; + static uint16_t hiddenNodePort; + /* Logging */ static bool haveLogFile; static bool outStderr; @@ -185,6 +190,11 @@ bool RsInitConfig::forceLocalAddr; unsigned short RsInitConfig::port; std::string RsInitConfig::inet; +/* v0.6 features */ +bool RsInitConfig::forceApiUpgrade = false; +std::string RsInitConfig::hiddenNodeAddress; +uint16_t RsInitConfig::hiddenNodePort; + /* Logging */ bool RsInitConfig::haveLogFile; bool RsInitConfig::outStderr; @@ -1437,6 +1447,8 @@ bool RsInit::setupAccount(const std::string& accountdir) /***************************** FINAL LOADING OF SETUP *************************/ + + /* Login SSL */ bool RsInit::LoadPassword(const std::string& id, const std::string& inPwd) { @@ -1708,6 +1720,16 @@ void RsInit::setAutoLogin(bool autoLogin){ RsInitConfig::autoLogin = autoLogin; } +/* Setup Hidden Location; */ +bool RsInit::SetHiddenLocation(const std::string& hiddenaddress, uint16_t port) +{ + /* parse the bugger (todo) */ + RsInitConfig::hiddenNodeAddress = hiddenaddress; + RsInitConfig::hiddenNodePort = port; + return true; +} + + /* * * Init Part of RsServer... needs the private @@ -1891,19 +1913,71 @@ int RsServer::StartupRetroShare() emergencySaveDir += "Downloads"; emergencyPartialsDir += "Partials"; + /**************************************************************************/ + /* setup Configuration */ + /**************************************************************************/ + std::cerr << "Load Configuration" << std::endl; + + mConfigMgr = new p3ConfigMgr(RsInitConfig::configDir); + mGeneralConfig = new p3GeneralConfig(); + + // Add General.cfg, and load - this allows key early options. + mConfigMgr->addConfiguration("general.cfg", mGeneralConfig); + std::string dummy2("dummy"); + mGeneralConfig->loadConfiguration(dummy2); + + // NOTE: if we lose GeneralConfiguration - then RS will fail to start. + // as API_VERSION won't exist. Furthermore HIDDEN node status will be lost. + // We can potentially detect HIDDEN node cofig from "peers.cfg", + // If this is lost too - in real trouble. + +#define RS_API_VERSION_OPT "RS_API" +#define RS_API_VERSION_STRING "0.6.0" + +#define RS_HIDDEN_NODE_OPT "HIDDEN_NODE" +#define RS_HIDDEN_NODE_YES "YES" + + bool forceApiUpgrade = false; + if ((RsInitConfig::firsttime_run) || (forceApiUpgrade)) + { + mGeneralConfig->setSetting(RS_API_VERSION_OPT, RS_API_VERSION_STRING); + } + + bool setupHiddenNode = false; + if (!RsInitConfig::hiddenNodeAddress.empty()) + { + setupHiddenNode = true; + mGeneralConfig->setSetting(RS_HIDDEN_NODE_OPT, RS_HIDDEN_NODE_YES); + } + + // BASIC COMPARISION FOR NOW... can be extended later if needed. + std::string version = mGeneralConfig->getSetting(RS_API_VERSION_OPT); + if (version != RS_API_VERSION_STRING) + { + std::cerr << "Aborting: Old Retroshare Configuration"; + std::cerr << std::endl; + abort(); + } + bool isHiddenNode = false; + if (RS_HIDDEN_NODE_YES == mGeneralConfig->getSetting(RS_HIDDEN_NODE_OPT)) + { + isHiddenNode = true; + std::cerr << "Retroshare: Hidden Node"; + std::cerr << std::endl; + } + /**************************************************************************/ /* setup classes / structures */ /**************************************************************************/ std::cerr << "setup classes / structures" << std::endl; - /* History Manager */ mHistoryMgr = new p3HistoryMgr(); mPeerMgr = new p3PeerMgrIMPL( AuthSSL::getAuthSSL()->OwnId(), - AuthGPG::getAuthGPG()->getGPGOwnId(), - AuthGPG::getAuthGPG()->getGPGOwnName(), - AuthSSL::getAuthSSL()->getOwnLocation()); + AuthGPG::getAuthGPG()->getGPGOwnId(), + AuthGPG::getAuthGPG()->getGPGOwnName(), + AuthSSL::getAuthSSL()->getOwnLocation()); mNetMgr = new p3NetMgrIMPL(); mLinkMgr = new p3LinkMgrIMPL(mPeerMgr, mNetMgr); @@ -1913,7 +1987,8 @@ int RsServer::StartupRetroShare() mPeerMgr->setManagers(mLinkMgr, mNetMgr); mNetMgr->setManagers(mPeerMgr, mLinkMgr); - + + //load all the SSL certs as friends // std::list sslIds; // AuthSSL::getAuthSSL()->getAuthenticatedList(sslIds); @@ -2117,9 +2192,6 @@ int RsServer::StartupRetroShare() rsFiles = ftserver; - mConfigMgr = new p3ConfigMgr(RsInitConfig::configDir, "rs-v0.5.cfg", "rs-v0.5.sgn"); - mGeneralConfig = new p3GeneralConfig(); - /* create Cache Services */ std::string config_dir = RsInitConfig::configDir; std::string localcachedir = config_dir + "/cache/local"; @@ -2139,7 +2211,6 @@ int RsServer::StartupRetroShare() mPluginsManager = new RsPluginManager(RsInitConfig::main_executable_hash) ; rsPlugins = mPluginsManager ; mConfigMgr->addConfiguration("plugins.cfg", mPluginsManager); - mPluginsManager->loadConfiguration() ; // These are needed to load plugins: plugin devs might want to know the place of @@ -2456,7 +2527,6 @@ int RsServer::StartupRetroShare() mConfigMgr->loadConfiguration(); mConfigMgr->addConfiguration("peers.cfg", mPeerMgr); - mConfigMgr->addConfiguration("general.cfg", mGeneralConfig); mConfigMgr->addConfiguration("cache.cfg", mCacheStrapper); mConfigMgr->addConfiguration("msgs.cfg", msgSrv); mConfigMgr->addConfiguration("chat.cfg", chatSrv); @@ -2519,6 +2589,12 @@ int RsServer::StartupRetroShare() } + if (setupHiddenNode) + { + mPeerMgr->setupHiddenNode(RsInitConfig::hiddenNodeAddress, RsInitConfig::hiddenNodePort); + } + + #if 0 /* must load the trusted_peer before setting up the pqipersongrp */ if (firsttime_run) @@ -2641,6 +2717,7 @@ int RsServer::StartupRetroShare() { msgSrv->loadWelcomeMsg(); ftserver->shareDownloadDirectory(true); + mGeneralConfig->saveConfiguration(); } // load up the help page From 1d6f99de0d60654406f537ce68338dd9f91824f1 Mon Sep 17 00:00:00 2001 From: drbob Date: Mon, 9 Sep 2013 02:11:43 +0000 Subject: [PATCH 08/83] mods to support hidden nodes, and hidden certificate sharing. git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@6721 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- retroshare-gui/src/gui/GenCertDialog.cpp | 39 ++ retroshare-gui/src/gui/GenCertDialog.h | 1 + retroshare-gui/src/gui/GenCertDialog.ui | 349 +++++++++++------- .../src/gui/connect/ConfCertDialog.cpp | 30 +- .../src/gui/connect/ConnectFriendWizard.cpp | 36 +- .../src/gui/settings/ServerPage.cpp | 4 + retroshare-gui/src/gui/settings/ServerPage.ui | 7 +- 7 files changed, 311 insertions(+), 155 deletions(-) diff --git a/retroshare-gui/src/gui/GenCertDialog.cpp b/retroshare-gui/src/gui/GenCertDialog.cpp index a5de6755f..70f3fb6be 100644 --- a/retroshare-gui/src/gui/GenCertDialog.cpp +++ b/retroshare-gui/src/gui/GenCertDialog.cpp @@ -37,6 +37,7 @@ GenCertDialog::GenCertDialog(bool onlyGenerateIdentity, QWidget *parent) ui.setupUi(this); connect(ui.new_gpg_key_checkbox, SIGNAL(clicked()), this, SLOT(newGPGKeyGenUiSetup())); + connect(ui.hidden_checkbox, SIGNAL(clicked()), this, SLOT(hiddenUiSetup())); connect(ui.genButton, SIGNAL(clicked()), this, SLOT(genPerson())); connect(ui.importIdentity_PB, SIGNAL(clicked()), this, SLOT(importIdentity())); @@ -115,6 +116,7 @@ void GenCertDialog::init() ui.headerLabel2->setText(text); newGPGKeyGenUiSetup(); + hiddenUiSetup(); } void GenCertDialog::newGPGKeyGenUiSetup() { @@ -153,6 +155,28 @@ void GenCertDialog::newGPGKeyGenUiSetup() { } } + +void GenCertDialog::hiddenUiSetup() +{ + + if (ui.hidden_checkbox->isChecked()) + { + ui.hiddenaddr_input->show(); + ui.hiddenaddr_label->show(); + ui.label_hiddenaddr2->show(); + ui.hiddenport_label->show(); + ui.hiddenport_spinBox->show(); + } + else + { + ui.hiddenaddr_input->hide(); + ui.hiddenaddr_label->hide(); + ui.label_hiddenaddr2->hide(); + ui.hiddenport_label->hide(); + ui.hiddenport_spinBox->hide(); + } +} + void GenCertDialog::exportIdentity() { QString fname = QFileDialog::getSaveFileName(this,tr("Export Identity"), "",tr("RetroShare Identity files (*.asc)")) ; @@ -203,6 +227,21 @@ void GenCertDialog::genPerson() std::string genLoc = ui.location_input->text().toUtf8().constData(); std::string PGPId; + if (ui.hidden_checkbox->isChecked()) + { + std::string hl = ui.hiddenaddr_input->text().toStdString(); + uint16_t port = ui.hiddenport_spinBox->value(); + if (!RsInit::SetHiddenLocation(hl, port)) /* parses it */ + { + /* Message Dialog */ + QMessageBox::warning(this, + tr("Invalid Hidden Location"), + tr("Please put in a valid address of the form: 31769173498.onion:7800"), + QMessageBox::Ok); + return; + } + } + if (!genNewGPGKey) { if (genLoc.length() < 3) { /* Message Dialog */ diff --git a/retroshare-gui/src/gui/GenCertDialog.h b/retroshare-gui/src/gui/GenCertDialog.h index 0cb3e2194..7650d9c9a 100644 --- a/retroshare-gui/src/gui/GenCertDialog.h +++ b/retroshare-gui/src/gui/GenCertDialog.h @@ -37,6 +37,7 @@ private slots: void importIdentity(); void exportIdentity(); void newGPGKeyGenUiSetup(); + void hiddenUiSetup(); private: void init(); diff --git a/retroshare-gui/src/gui/GenCertDialog.ui b/retroshare-gui/src/gui/GenCertDialog.ui index 2ed55871f..0500f2b99 100644 --- a/retroshare-gui/src/gui/GenCertDialog.ui +++ b/retroshare-gui/src/gui/GenCertDialog.ui @@ -6,8 +6,8 @@ 0 0 - 664 - 474 + 618 + 641 @@ -32,8 +32,8 @@ 30 - - + + @@ -48,23 +48,10 @@ - + - - - - - Qt::Vertical - - - - 1 - 1 - - - - - + + It looks like you don't own any profile (PGP keys). Please fill in the form below to create one, or import an existing profile. @@ -74,117 +61,7 @@ - - - - Your profile is associated with a PGP key. RetroShare currently ignores DSA keys. - - - - - - - Name - - - - - - - Enter your nickname here - - - 64 - - - - - - - This Password is for PGP - - - Password - - - - - - - Put a strong password here. This password protects your PGP key. - - - - - - 1024 - - - QLineEdit::Password - - - - - - - Location - - - - - - - 64 - - - - - - - - 0 - 30 - - - - 1 - - - Put a meaningful location. ex : home, laptop, etc. This field will be used to differentiate different installations with the same identity (PGP key). - - - false - - - true - - - - - - - - 16777215 - 26 - - - - Create new identity - - - - :/images/contact_new.png:/images/contact_new.png - - - - - - - Use identity - - - - + 6 @@ -253,6 +130,37 @@ + + + + Use identity + + + + + + + Your profile is associated with a PGP key. RetroShare currently ignores DSA keys. + + + + + + + Name + + + + + + + Enter your nickname here + + + 64 + + + @@ -260,7 +168,7 @@ - + Be careful: this email will be visible to your friends and friends @@ -272,6 +180,183 @@ anonymous, you can use a fake email. + + + + This Password is for PGP + + + Password + + + + + + + Put a strong password here. This password protects your PGP key. + + + + + + 1024 + + + QLineEdit::Password + + + + + + + Location + + + + + + + 64 + + + + + + + + 0 + 30 + + + + 1 + + + Put a meaningful location. ex : home, laptop, etc. This field will be used to differentiate different installations with the same identity (PGP key). + + + false + + + true + + + + + + + + 16777215 + 32 + + + + Your profile is associated with a PGP key + + + Create a Hidden Location. + + + + :/images/contact_new128.png:/images/contact_new128.png + + + + 32 + 32 + + + + false + + + + + + + Tor Address + + + + + + + 64 + + + + + + + Port + + + + + + + 1 + + + 65535 + + + 7812 + + + + + + + + 0 + 30 + + + + 1 + + + This is a TOR Onion address of the form: xa76giaf6ifda7ri63i263.onion and your selected port, you must first launch TOR and create a new hidden service to generate this address. + + + false + + + true + + + + + + + + 16777215 + 26 + + + + Create new identity + + + + :/images/contact_new.png:/images/contact_new.png + + + + + + + Qt::Vertical + + + + 1 + 1 + + + + diff --git a/retroshare-gui/src/gui/connect/ConfCertDialog.cpp b/retroshare-gui/src/gui/connect/ConfCertDialog.cpp index 593a609d6..aa5b41c2b 100644 --- a/retroshare-gui/src/gui/connect/ConfCertDialog.cpp +++ b/retroshare-gui/src/gui/connect/ConfCertDialog.cpp @@ -213,15 +213,29 @@ void ConfCertDialog::load() else ui.crypto_info->setText(tr("Not connected")) ; - /* set local address */ - ui.localAddress->setText(QString::fromStdString(detail.localAddr)); - ui.localPort -> setValue(detail.localPort); - /* set the server address */ - ui.extAddress->setText(QString::fromStdString(detail.extAddr)); - ui.extPort -> setValue(detail.extPort); - - ui.dynDNS->setText(QString::fromStdString(detail.dyndns)); + if (detail.isHiddenNode) + { + /* set local address */ + ui.localAddress->setText("hidden"); + ui.localPort -> setValue(0); + /* set the server address */ + ui.extAddress->setText("hidden"); + ui.extPort -> setValue(0); + ui.dynDNS->setText(QString::fromStdString(detail.hiddenNodeAddress)); + } + else + { + /* set local address */ + ui.localAddress->setText(QString::fromStdString(detail.localAddr)); + ui.localPort -> setValue(detail.localPort); + /* set the server address */ + ui.extAddress->setText(QString::fromStdString(detail.extAddr)); + ui.extPort -> setValue(detail.extPort); + + ui.dynDNS->setText(QString::fromStdString(detail.dyndns)); + } + ui.statusline->setText(StatusDefs::connectStateString(detail)); ui.ipAddressList->clear(); diff --git a/retroshare-gui/src/gui/connect/ConnectFriendWizard.cpp b/retroshare-gui/src/gui/connect/ConnectFriendWizard.cpp index 35cd794b7..211be996f 100755 --- a/retroshare-gui/src/gui/connect/ConnectFriendWizard.cpp +++ b/retroshare-gui/src/gui/connect/ConnectFriendWizard.cpp @@ -621,23 +621,33 @@ void ConnectFriendWizard::accept() rsPeers->addFriend(peerDetails.id, peerDetails.gpg_id,serviceFlags()) ; runProgressDialog = true; - //let's check if there is ip adresses in the wizard. - if (!peerDetails.extAddr.empty() && peerDetails.extPort) { - std::cerr << "ConnectFriendWizard::accept() : setting ip ext address." << std::endl; - rsPeers->setExtAddress(peerDetails.id, peerDetails.extAddr, peerDetails.extPort); - } - if (!peerDetails.localAddr.empty() && peerDetails.localPort) { - std::cerr << "ConnectFriendWizard::accept() : setting ip local address." << std::endl; - rsPeers->setLocalAddress(peerDetails.id, peerDetails.localAddr, peerDetails.localPort); - } - if (!peerDetails.dyndns.empty()) { - std::cerr << "ConnectFriendWizard::accept() : setting DynDNS." << std::endl; - rsPeers->setDynDNS(peerDetails.id, peerDetails.dyndns); - } if (!peerDetails.location.empty()) { std::cerr << "ConnectFriendWizard::accept() : setting peerLocation." << std::endl; rsPeers->setLocation(peerDetails.id, peerDetails.location); } + + if (peerDetails.isHiddenNode) + { + std::cerr << "ConnectFriendWizard::accept() : setting hidden node." << std::endl; + rsPeers->setHiddenNode(peerDetails.id, peerDetails.hiddenNodeAddress); + } + else + { + //let's check if there is ip adresses in the wizard. + if (!peerDetails.extAddr.empty() && peerDetails.extPort) { + std::cerr << "ConnectFriendWizard::accept() : setting ip ext address." << std::endl; + rsPeers->setExtAddress(peerDetails.id, peerDetails.extAddr, peerDetails.extPort); + } + if (!peerDetails.localAddr.empty() && peerDetails.localPort) { + std::cerr << "ConnectFriendWizard::accept() : setting ip local address." << std::endl; + rsPeers->setLocalAddress(peerDetails.id, peerDetails.localAddr, peerDetails.localPort); + } + if (!peerDetails.dyndns.empty()) { + std::cerr << "ConnectFriendWizard::accept() : setting DynDNS." << std::endl; + rsPeers->setDynDNS(peerDetails.id, peerDetails.dyndns); + } + } + } if (runProgressDialog) diff --git a/retroshare-gui/src/gui/settings/ServerPage.cpp b/retroshare-gui/src/gui/settings/ServerPage.cpp index 005e4137b..b26fcf176 100755 --- a/retroshare-gui/src/gui/settings/ServerPage.cpp +++ b/retroshare-gui/src/gui/settings/ServerPage.cpp @@ -147,6 +147,10 @@ void ServerPage::load() int netIndex = 0; switch(detail.netMode) { + case RS_NETMODE_HIDDEN: + netIndex = 3; + ui.netModeComboBox->setEnabled(false); + break; case RS_NETMODE_EXT: netIndex = 2; break; diff --git a/retroshare-gui/src/gui/settings/ServerPage.ui b/retroshare-gui/src/gui/settings/ServerPage.ui index 96d13bc59..c3ddbdd4a 100755 --- a/retroshare-gui/src/gui/settings/ServerPage.ui +++ b/retroshare-gui/src/gui/settings/ServerPage.ui @@ -43,6 +43,11 @@ Manually Forwarded Port + + + Hidden Node + + @@ -369,8 +374,6 @@ behind a firewall or a VPN.
showDiscStatusBar allowIpDeterminationCB IPServersLV - textlabel_ext - textlabel_netLimited ipAddressList label_7 From 5322040d29c9b1ffa4a91e229543f0024588d78c Mon Sep 17 00:00:00 2001 From: drbob Date: Wed, 11 Sep 2013 07:00:33 +0000 Subject: [PATCH 09/83] disabled outgoing normal connections - if hidden node. git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@6730 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/pqi/p3linkmgr.cc | 13 +++++++++++++ libretroshare/src/pqi/p3peermgr.cc | 7 +++++++ libretroshare/src/pqi/p3peermgr.h | 2 ++ libretroshare/src/pqi/pqisslproxy.cc | 2 ++ 4 files changed, 24 insertions(+) diff --git a/libretroshare/src/pqi/p3linkmgr.cc b/libretroshare/src/pqi/p3linkmgr.cc index dbc56daf1..0f95d11e0 100644 --- a/libretroshare/src/pqi/p3linkmgr.cc +++ b/libretroshare/src/pqi/p3linkmgr.cc @@ -1478,6 +1478,13 @@ bool p3LinkMgrIMPL::tryConnectUDP(const std::string &id, struct sockaddr_in &r return false; #endif + if (mPeerMgr->isHidden()) + { + std::cerr << "p3LinkMgrIMPL::tryConnectUDP() isHidden(): no connection attempts for : " << id; + std::cerr << std::endl; + return false; + } + RsStackMutex stack(mLinkMtx); /****** STACK LOCK MUTEX *******/ @@ -1617,6 +1624,12 @@ bool p3LinkMgrIMPL::retryConnectTCP(const std::string &id) return false; } + if (mPeerMgr->isHidden()) + { + std::cerr << "p3LinkMgrIMPL::retryConnectTCP() isHidden(): no connection attempts for : " << id; + std::cerr << std::endl; + return false; + } struct sockaddr_in lAddr; struct sockaddr_in eAddr; diff --git a/libretroshare/src/pqi/p3peermgr.cc b/libretroshare/src/pqi/p3peermgr.cc index cef80f5cf..272bef347 100644 --- a/libretroshare/src/pqi/p3peermgr.cc +++ b/libretroshare/src/pqi/p3peermgr.cc @@ -308,6 +308,13 @@ bool p3PeerMgrIMPL::getGpgId(const std::string &ssl_id, std::string &gpgId) /**** HIDDEN STUFF ****/ +bool p3PeerMgrIMPL::isHidden() +{ + RsStackMutex stack(mPeerMtx); /****** STACK LOCK MUTEX *******/ + return mOwnState.hiddenNode; +} + + bool p3PeerMgrIMPL::isHiddenPeer(const std::string &ssl_id) { RsStackMutex stack(mPeerMtx); /****** STACK LOCK MUTEX *******/ diff --git a/libretroshare/src/pqi/p3peermgr.h b/libretroshare/src/pqi/p3peermgr.h index bede98560..dc20830ca 100644 --- a/libretroshare/src/pqi/p3peermgr.h +++ b/libretroshare/src/pqi/p3peermgr.h @@ -197,6 +197,7 @@ virtual bool getGpgId(const std::string &sslId, std::string &gpgId) = 0; virtual uint32_t getConnectionType(const std::string &sslId) = 0; virtual bool setProxyServerAddress(const struct sockaddr_in &proxy_addr) = 0; +virtual bool isHidden() = 0; virtual bool isHiddenPeer(const std::string &ssl_id) = 0; virtual bool getProxyAddress(const std::string &ssl_id, struct sockaddr_in &proxy_addr, std::string &domain_addr, uint16_t &domain_port) = 0; @@ -293,6 +294,7 @@ virtual bool getGpgId(const std::string &sslId, std::string &gpgId); virtual uint32_t getConnectionType(const std::string &sslId); virtual bool setProxyServerAddress(const struct sockaddr_in &proxy_addr); +virtual bool isHidden(); virtual bool isHiddenPeer(const std::string &ssl_id); virtual bool getProxyAddress(const std::string &ssl_id, struct sockaddr_in &proxy_addr, std::string &domain_addr, uint16_t &domain_port); diff --git a/libretroshare/src/pqi/pqisslproxy.cc b/libretroshare/src/pqi/pqisslproxy.cc index cfcf2ead0..5cfd391cd 100755 --- a/libretroshare/src/pqi/pqisslproxy.cc +++ b/libretroshare/src/pqi/pqisslproxy.cc @@ -40,6 +40,8 @@ const int pqisslproxyzone = 3517; +#define PROXY_DEBUG 1 + #define PROXY_STATE_FAILED 0 #define PROXY_STATE_INIT 1 #define PROXY_STATE_WAITING_METHOD_RESPONSE 2 From 14f99418ae32dd7433a23ff8fe2f57b979b08eb7 Mon Sep 17 00:00:00 2001 From: drbob Date: Wed, 11 Sep 2013 07:06:47 +0000 Subject: [PATCH 10/83] Added PgpIdSet git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@6731 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/serialiser/rstlvtypes.cc | 1 + libretroshare/src/serialiser/rstlvtypes.h | 6 ++++++ 2 files changed, 7 insertions(+) diff --git a/libretroshare/src/serialiser/rstlvtypes.cc b/libretroshare/src/serialiser/rstlvtypes.cc index 6a2fc0579..f10dda66a 100644 --- a/libretroshare/src/serialiser/rstlvtypes.cc +++ b/libretroshare/src/serialiser/rstlvtypes.cc @@ -247,6 +247,7 @@ std::ostream &RsTlvBinaryData::print(std::ostream &out, uint16_t indent) RsTlvPeerIdSet::RsTlvPeerIdSet(): RsTlvStringSet(TLV_TYPE_PEERSET) {} RsTlvHashSet::RsTlvHashSet(): RsTlvStringSet(TLV_TYPE_HASHSET) {} +RsTlvPgpIdSet::RsTlvPgpIdSet(): RsTlvStringSet(TLV_TYPE_PGPIDSET) {} RsTlvStringSet::RsTlvStringSet(uint16_t type) :mType(type) diff --git a/libretroshare/src/serialiser/rstlvtypes.h b/libretroshare/src/serialiser/rstlvtypes.h index 4148faa62..45e6e1e68 100644 --- a/libretroshare/src/serialiser/rstlvtypes.h +++ b/libretroshare/src/serialiser/rstlvtypes.h @@ -122,6 +122,12 @@ class RsTlvHashSet: public RsTlvStringSet RsTlvHashSet(); }; +class RsTlvPgpIdSet: public RsTlvStringSet +{ + public: + RsTlvPgpIdSet(); +}; + class RsTlvServiceIdSet: public RsTlvItem { public: From fd071161bf863e49571bfb8f41d42598abde0f2b Mon Sep 17 00:00:00 2001 From: drbob Date: Wed, 11 Sep 2013 07:09:30 +0000 Subject: [PATCH 11/83] Added IPv6 encoding. Switched IPv4 encoding to be always in Network Order. git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@6732 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/serialiser/rstlvbase.cc | 109 ++++++++++++++++++++-- libretroshare/src/serialiser/rstlvbase.h | 4 + 2 files changed, 107 insertions(+), 6 deletions(-) diff --git a/libretroshare/src/serialiser/rstlvbase.cc b/libretroshare/src/serialiser/rstlvbase.cc index 4bf8adabe..801a2e5ed 100644 --- a/libretroshare/src/serialiser/rstlvbase.cc +++ b/libretroshare/src/serialiser/rstlvbase.cc @@ -593,12 +593,12 @@ bool SetTlvIpAddrPortV4(void *data, uint32_t size, uint32_t *offset, sockaddr_in addr = *out; - /* now add the data .... (its already in network order) - so flip */ + /* now add the data .... (keep in network order) */ uint32_t ipaddr = addr.sin_addr.s_addr; - ok &= setRawUInt32(data, tlvend, offset, ntohl(ipaddr)); + ok &= setRawUInt32(data, tlvend, offset, ipaddr); uint16_t port = addr.sin_port; - ok &= setRawUInt16(data, tlvend, offset, ntohs(port)); + ok &= setRawUInt16(data, tlvend, offset, port); return ok; } @@ -650,16 +650,16 @@ bool GetTlvIpAddrPortV4(void *data, uint32_t size, uint32_t *offset, bool ok = true; - /* now get the data .... (its already in network order) - so flip */ + /* now get the data .... (keep in network order) */ uint32_t ipaddr; ok &= getRawUInt32(data, tlvend, offset, &ipaddr); in->sin_family = AF_INET; /* set FAMILY */ - in->sin_addr.s_addr = htonl(ipaddr); + in->sin_addr.s_addr = ipaddr; uint16_t port; ok &= getRawUInt16(data, tlvend, offset, &port); - in->sin_port = htons(port); + in->sin_port = port; return ok; } @@ -668,3 +668,100 @@ uint32_t GetTlvIpAddrPortV4Size() { return TLV_HEADER_SIZE + 4 + 2; /* header + 4 (IP) + 2 (Port) */ } + +bool SetTlvIpAddrPortV6(void *data, uint32_t size, uint32_t *offset, + uint16_t type, struct sockaddr_in6 *out) { + if (!data) + return false; + + uint32_t tlvsize = GetTlvIpAddrPortV4Size(); + uint32_t tlvend = *offset + tlvsize; /* where the data will extend to */ + + if (size < tlvend) + { +#ifdef TLV_BASE_DEBUG + std::cerr << "SetTlvIpAddrPortV6() FAILED - not enough space" << std::endl; + std::cerr << "SetTlvIpAddrPortV6() size: " << size << std::endl; + std::cerr << "SetTlvIpAddrPortV6() tlvsize: " << tlvsize << std::endl; + std::cerr << "SetTlvIpAddrPortV6() tlvend: " << tlvend << std::endl; +#endif + return false; + } + + bool ok = true; + ok &= SetTlvBase(data, tlvend, offset, type, tlvsize); + + /* now add the data (keep in network order) */ + uint32_t *ip6addr = (uint32_t *) out->sin6_addr.s6_addr; + for(int i = 0; i < 4; i++) + { + ok &= setRawUInt32(data, tlvend, offset, ip6addr[i]); + } + ok &= setRawUInt16(data, tlvend, offset, out->sin_port6); + return ok; +} + +bool GetTlvIpAddrPortV6(void *data, uint32_t size, uint32_t *offset, + uint16_t type, struct sockaddr_in6 *in) { + if (!data) + return false; + + if (size < *offset + TLV_HEADER_SIZE) + { +#ifdef TLV_BASE_DEBUG + std::cerr << "GetIpAddrPortV6() FAILED - not enough space" << std::endl; + std::cerr << "GetIpAddrPortV6() size: " << size << std::endl; + std::cerr << "GetIpAddrPortV6() *offset: " << *offset << std::endl; +#endif + return false; + } + + /* extract the type and size */ + void *tlvstart = right_shift_void_pointer(data, *offset); + uint16_t tlvtype = GetTlvType(tlvstart); + uint32_t tlvsize = GetTlvSize(tlvstart); + + /* check that there is size */ + uint32_t tlvend = *offset + tlvsize; + if (size < tlvend) + { +#ifdef TLV_BASE_DEBUG + std::cerr << "GetIpAddrPortV6() FAILED - not enough space" << std::endl; + std::cerr << "GetIpAddrPortV6() size: " << size << std::endl; + std::cerr << "GetIpAddrPortV6() tlvsize: " << tlvsize << std::endl; + std::cerr << "GetIpAddrPortV6() tlvend: " << tlvend << std::endl; +#endif + return false; + } + + if (type != tlvtype) + { +#ifdef TLV_BASE_DEBUG + std::cerr << "GetIpAddrPortV6() FAILED - invalid type" << std::endl; + std::cerr << "GetIpAddrPortV6() type: " << type << std::endl; + std::cerr << "GetIpAddrPortV6() tlvtype: " << tlvtype << std::endl; +#endif + return false; + } + + *offset += TLV_HEADER_SIZE; /* skip header */ + + bool ok = true; + + /* now get the data (keep in network order) */ + uint32_t *ip6addr = (uint32_t *) in->sin6_addr.s6_addr; + for(int i = 0; i < 4; i++) + { + ok &= getRawUInt32(data, tlvend, offset, ip6addr[i]); + } + + in->sin6_family = AF_INET6; /* set FAMILY */ + ok &= getRawUInt16(data, tlvend, offset, &(in->sin6_port)); + + return ok; +} + +uint32_t GetTlvIpAddrPortV6Size() { + return TLV_HEADER_SIZE + 16 + 2; /* header + 16 (IP) + 2 (Port) */ +} + diff --git a/libretroshare/src/serialiser/rstlvbase.h b/libretroshare/src/serialiser/rstlvbase.h index c99973fbf..efe7c3aac 100644 --- a/libretroshare/src/serialiser/rstlvbase.h +++ b/libretroshare/src/serialiser/rstlvbase.h @@ -273,6 +273,10 @@ bool SetTlvIpAddrPortV4(void *data, uint32_t size, uint32_t *offset, uint16_ bool GetTlvIpAddrPortV4(void *data, uint32_t size, uint32_t *offset, uint16_t type, struct sockaddr_in *in); uint32_t GetTlvIpAddrPortV4Size(); +bool SetTlvIpAddrPortV6(void *data, uint32_t size, uint32_t *offset, uint16_t type, struct sockaddr_in6 *out); +bool GetTlvIpAddrPortV6(void *data, uint32_t size, uint32_t *offset, uint16_t type, struct sockaddr_in6 *in); +uint32_t GetTlvIpAddrPortV6Size(); + /* additional function to be added bool SetTlvBinData(void* data, uint32_t size, uint32_t* offset, uint16_t type, void* data_bin, uint32_t len_tlv) From 33eb99d812634e0ea0d6b99872652c8ffe41e365 Mon Sep 17 00:00:00 2001 From: chrisparker126 Date: Wed, 11 Sep 2013 20:42:56 +0000 Subject: [PATCH 12/83] added group update feature git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.5-gxs_finale@6733 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/gxs/rsdataservice.cc | 120 +++++++++++++++++++++++++ libretroshare/src/gxs/rsdataservice.h | 15 ++++ libretroshare/src/gxs/rsgds.h | 23 ++++- libretroshare/src/gxs/rsgenexchange.cc | 95 +++++++++++++++++++- libretroshare/src/gxs/rsgenexchange.h | 18 ++++ libretroshare/src/gxs/rsgxsutil.h | 10 +++ 6 files changed, 277 insertions(+), 4 deletions(-) diff --git a/libretroshare/src/gxs/rsdataservice.cc b/libretroshare/src/gxs/rsdataservice.cc index 6836fa028..f27633af2 100644 --- a/libretroshare/src/gxs/rsdataservice.cc +++ b/libretroshare/src/gxs/rsdataservice.cc @@ -177,6 +177,8 @@ RsDataService::RsDataService(const std::string &serviceDir, const std::string &d // for retrieving msg offsets mMsgOffSetColumns.push_back(KEY_MSG_ID); mMsgOffSetColumns.push_back(KEY_NXS_FILE_OFFSET); mMsgOffSetColumns.push_back(KEY_NXS_FILE_LEN); + + grpIdColumn.push_back(KEY_GRP_ID); } RsDataService::~RsDataService(){ @@ -641,6 +643,99 @@ int RsDataService::storeGroup(std::map &grp) return ret; } +int RsDataService::updateGroup(std::map &grp) +{ + + RsStackMutex stack(mDbMutex); + + std::map::iterator sit = grp.begin(); + + // begin transaction + mDb->execSQL("BEGIN;"); + + for(; sit != grp.end(); sit++) + { + + RsNxsGrp* grpPtr = sit->first; + RsGxsGrpMetaData* grpMetaPtr = sit->second; + + // if data is larger than max item size do not add + if(!validSize(grpPtr)) continue; + + std::string grpFile = mServiceDir + "/" + grpPtr->grpId; + std::fstream ostrm(grpFile.c_str(), std::ios::binary | std::ios::app | std::ios::out); + ostrm.seekg(0, std::ios::end); // go to end to append + uint32_t offset = ostrm.tellg(); // get fill offset + + /*! + * STORE file offset, file length, file name, + * grpId, flags, publish time stamp, identity, + * id signature, admin signatue, key set, last posting ts + * and meta data + **/ + ContentValue cv; + cv.put(KEY_NXS_FILE_OFFSET, (int32_t)offset); + cv.put(KEY_NXS_FILE_LEN, (int32_t)grpPtr->grp.TlvSize()); + cv.put(KEY_NXS_FILE, grpFile); + cv.put(KEY_GRP_ID, grpPtr->grpId); + cv.put(KEY_GRP_NAME, grpMetaPtr->mGroupName); + cv.put(KEY_ORIG_GRP_ID, grpMetaPtr->mOrigGrpId); + cv.put(KEY_NXS_SERV_STRING, grpMetaPtr->mServiceString); + cv.put(KEY_NXS_FLAGS, (int32_t)grpMetaPtr->mGroupFlags); + cv.put(KEY_TIME_STAMP, (int32_t)grpMetaPtr->mPublishTs); + cv.put(KEY_GRP_SIGN_FLAGS, (int32_t)grpMetaPtr->mSignFlags); + cv.put(KEY_GRP_CIRCLE_ID, grpMetaPtr->mCircleId); + cv.put(KEY_GRP_CIRCLE_TYPE, (int32_t)grpMetaPtr->mCircleType); + cv.put(KEY_GRP_INTERNAL_CIRCLE, grpMetaPtr->mInternalCircle); + cv.put(KEY_GRP_ORIGINATOR, grpMetaPtr->mOriginator); + cv.put(KEY_GRP_AUTHEN_FLAGS, (int32_t)grpMetaPtr->mAuthenFlags); + cv.put(KEY_NXS_HASH, grpMetaPtr->mHash); + + if(! (grpMetaPtr->mAuthorId.empty()) ){ + cv.put(KEY_NXS_IDENTITY, grpMetaPtr->mAuthorId); + } + + offset = 0; + char keySetData[grpMetaPtr->keys.TlvSize()]; + grpMetaPtr->keys.SetTlv(keySetData, grpMetaPtr->keys.TlvSize(), &offset); + cv.put(KEY_KEY_SET, grpMetaPtr->keys.TlvSize(), keySetData); + + offset = 0; + char metaData[grpPtr->meta.TlvSize()]; + grpPtr->meta.SetTlv(metaData, grpPtr->meta.TlvSize(), &offset); + cv.put(KEY_NXS_META, grpPtr->meta.TlvSize(), metaData); + + // local meta data + cv.put(KEY_GRP_SUBCR_FLAG, (int32_t)grpMetaPtr->mSubscribeFlags); + cv.put(KEY_GRP_POP, (int32_t)grpMetaPtr->mPop); + cv.put(KEY_MSG_COUNT, (int32_t)grpMetaPtr->mMsgCount); + cv.put(KEY_GRP_STATUS, (int32_t)grpMetaPtr->mGroupStatus); + cv.put(KEY_GRP_LAST_POST, (int32_t)grpMetaPtr->mLastPost); + + offset = 0; + char grpData[grpPtr->grp.TlvSize()]; + grpPtr->grp.SetTlv(grpData, grpPtr->grp.TlvSize(), &offset); + ostrm.write(grpData, grpPtr->grp.TlvSize()); + ostrm.close(); + + mDb->sqlUpdate(GRP_TABLE_NAME, "grpId='" + grpPtr->grpId + "'", cv); + } + // finish transaction + bool ret = mDb->execSQL("COMMIT;"); + + for(sit = grp.begin(); sit != grp.end(); sit++) + { + //TODO: API encourages aliasing, remove this abomination + if(sit->second != sit->first->metaData) + delete sit->second; + delete sit->first; + + } + + return ret; +} + + bool RsDataService::validSize(RsNxsGrp* grp) const { if((grp->grp.TlvSize() + grp->meta.TlvSize()) <= GXS_MAX_ITEM_SIZE) return true; @@ -1177,6 +1272,31 @@ int RsDataService::removeGroups(const std::vector &grpIds) return 1; } +int RsDataService::retrieveGroupIds(std::vector &grpIds) +{ + RsStackMutex stack(mDbMutex); + + RetroCursor* c = mDb->sqlQuery(GRP_TABLE_NAME, grpIdColumn, "", ""); + + if(c) + { + bool valid = c->moveToFirst(); + + while(valid) + { + std::string grpId; + c->getString(0, grpId); + grpIds.push_back(grpId); + valid = c->moveToNext(); + } + delete c; + }else + { + return 0; + } + + return 1; +} bool RsDataService::locked_updateMessageEntries(const MsgUpdates& updates) { diff --git a/libretroshare/src/gxs/rsdataservice.h b/libretroshare/src/gxs/rsdataservice.h index 3b8d0bf2a..666aa8e98 100644 --- a/libretroshare/src/gxs/rsdataservice.h +++ b/libretroshare/src/gxs/rsdataservice.h @@ -106,6 +106,13 @@ public: */ int removeGroups(const std::vector& grpIds); + /*! + * Retrieves all group ids in store + * @param grpIds all grpids in store is inserted into this vector + * @return error code + */ + int RsDataService::retrieveGroupIds(std::vector &grpIds); + /*! * @return the cache size set for this RsGeneralDataService in bytes */ @@ -130,6 +137,13 @@ public: */ int storeGroup(std::map& grp); + /*! + * Updates group entries in Db + * @param grp map of group and decoded meta data + * @return error code + */ + int updateGroup(std::map& grsp); + /*! * @param metaData The meta data item to update * @return error code @@ -238,6 +252,7 @@ private: std::list grpColumns; std::list grpMetaColumns; + std::list grpIdColumn; std::string mServiceDir, mDbName; uint16_t mServType; diff --git a/libretroshare/src/gxs/rsgds.h b/libretroshare/src/gxs/rsgds.h index c7a5cf387..9a82d3687 100644 --- a/libretroshare/src/gxs/rsgds.h +++ b/libretroshare/src/gxs/rsgds.h @@ -167,7 +167,14 @@ public: * @param grpIds ids of groups to be removed * @return error code */ - virtual int removeGroups(const std::vector& grpIds) = 0; + virtual int removeGroups(std::vector& grpIds) = 0; + + /*! + * Retrieves all group ids in store + * @param grpIds all grpids in store is inserted into this vector + * @return error code + */ + virtual int retrieveGroupIds(const std::vector& grpIds) = 0; /*! * @return the cache size set for this RsGeneralDataService in bytes @@ -186,6 +193,13 @@ public: */ virtual int storeMessage(std::map& msgs) = 0; + /*! + * Stores a list of signed messages into data store + * @param msg map of message and decoded meta data information + * @return error code + */ + virtual int storeMessage(std::map& msgs) = 0; + /*! * Stores a list of groups in data store * @param grp map of group and decoded meta data @@ -194,6 +208,13 @@ public: virtual int storeGroup(std::map& grsp) = 0; + /*! + * Updates group entries in Db + * @param grp map of group and decoded meta data + * @return error code + */ + virtual int updateGroup(std::map& grsp) = 0; + /*! * @param metaData */ diff --git a/libretroshare/src/gxs/rsgenexchange.cc b/libretroshare/src/gxs/rsgenexchange.cc index 5133d79ca..eac88e3b0 100644 --- a/libretroshare/src/gxs/rsgenexchange.cc +++ b/libretroshare/src/gxs/rsgenexchange.cc @@ -2038,6 +2038,8 @@ void RsGenExchange::processRecvdData() processRecvdGroups(); processRecvdMessages(); + + performUpdateValidation(); } @@ -2193,9 +2195,11 @@ void RsGenExchange::processRecvdGroups() RsStackMutex stack(mGenMtx); NxsGrpPendValidVect::iterator vit = mReceivedGrps.begin(); + std::vector existingGrpIds, grpIds; + std::map grps; - std::list grpIds; + mDataStore->retrieveGroupIds(existingGrpIds); while( vit != mReceivedGrps.end()) { @@ -2224,9 +2228,19 @@ void RsGenExchange::processRecvdGroups() meta->mOriginator = grp->PeerId(); computeHash(grp->grp, meta->mHash); - grps.insert(std::make_pair(grp, meta)); - grpIds.push_back(grp->grpId); + // now check if group already existss + if(std::find(existingGrpIds.begin(), existingGrpIds.end(), grp->grpId) == existingGrpIds.end()) + { + grps.insert(std::make_pair(grp, meta)); + grpIds.push_back(grp->grpId); + } + else + { + GroupUpdate update; + update.newGrp = grp; + mGroupUpdates.push_back(update); + } erase = true; } else if(ret == VALIDATE_FAIL) @@ -2278,3 +2292,78 @@ void RsGenExchange::processRecvdGroups() mDataStore->storeGroup(grps); } } + +void RsGenExchange::performUpdateValidation() +{ +#ifdef GXS_GENX_DEBUG + std::cerr << "RsGenExchange::performUpdateValidation() " << std::endl; +#endif + + std::map grpMetas; + + std::vector::iterator vit = mGroupUpdates.begin(); + for(; vit != mGroupUpdates.end(); vit++) + grpMetas.insert(std::make_pair(vit->newGrp->grpId, (RsGxsGrpMetaData*)NULL)); + + mDataStore->retrieveGxsGrpMetaData(grpMetas); + + vit = mGroupUpdates.begin(); + for(; vit != mGroupUpdates.end(); vit++) + { + GroupUpdate& gu = *vit; + std::map::iterator mit = + grpMetas.find(gu.newGrp->grpId); + gu.oldGrpMeta = mit->second; + gu.validUpdate = updateValid(*(gu.oldGrpMeta), *(gu.newGrp)); + } + +#ifdef GXS_GENX_DEBUG + std::cerr << "RsGenExchange::performUpdateValidation() " << std::endl; +#endif + + vit = mGroupUpdates.begin(); + std::map grps; + for(; vit != mGroupUpdates.end(); vit++) + { + GroupUpdate& gu = *vit; + grps.insert(std::make_pair(gu.newGrp, gu.newGrp->metaData)); + delete gu.oldGrpMeta; + } + + mDataStore->updateGroup(grps); + mGroupUpdates.clear(); +} + +bool RsGenExchange::updateValid(RsGxsGrpMetaData& oldGrpMeta, RsNxsGrp& newGrp) const +{ + std::map& signSet = newGrp.metaData->signSet.keySignSet; + std::map::iterator mit = signSet.find(GXS_SERV::FLAG_AUTHEN_ADMIN); + + if(mit == signSet.end()) + { +#ifdef GXS_GENX_DEBUG + std::cerr << "RsGenExchange::updateValid() new admin sign not found! " << std::endl; + std::cerr << "RsGenExchange::updateValid() grpId: " << oldGrp.grpId << std::endl; +#endif + + return false; + } + + RsTlvKeySignature& adminSign = mit->second; + + std::map& keys = oldGrpMeta.keys.keys; + std::map::iterator keyMit = keys.find(oldGrpMeta.mGroupId); + + if(keyMit == keys.end()) + { +#ifdef GXS_GENX_DEBUG + std::cerr << "RsGenExchange::updateValid() admin key not found! " << std::endl; +#endif + return false; + } + + // also check this is the latest published group + bool latest = newGrp.metaData->mPublishTs > oldGrpMeta.mPublishTs; + + return GxsSecurity::validateNxsGrp(newGrp, adminSign, keyMit->second) && latest; +} diff --git a/libretroshare/src/gxs/rsgenexchange.h b/libretroshare/src/gxs/rsgenexchange.h index a9d3d7b4a..dc6a5026c 100644 --- a/libretroshare/src/gxs/rsgenexchange.h +++ b/libretroshare/src/gxs/rsgenexchange.h @@ -736,6 +736,20 @@ private: static void computeHash(const RsTlvBinaryData& data, std::string& hash); + /*! + * Checks validation of recently received groups to be + * updated + */ + void performUpdateValidation(); + + /*! + * Checks if the update is valid (i.e. the new admin signature is by the old admin key) + * @param oldGrp the old group to be updated (must have meta data member initialised) + * @param newGrp the new group that updates the old group (must have meta data member initialised) + * @return + */ + bool updateValid(RsGxsGrpMetaData& oldGrp, RsNxsGrp& newGrp) const; + private: RsMutex mGenMtx; @@ -798,6 +812,10 @@ private: const uint8_t CREATE_FAIL, CREATE_SUCCESS, CREATE_FAIL_TRY_LATER, SIGN_MAX_ATTEMPTS; const uint8_t SIGN_FAIL, SIGN_SUCCESS, SIGN_FAIL_TRY_LATER; const uint8_t VALIDATE_FAIL, VALIDATE_SUCCESS, VALIDATE_FAIL_TRY_LATER, VALIDATE_MAX_ATTEMPTS; + +private: + + std::vector mGroupUpdates; }; #endif // RSGENEXCHANGE_H diff --git a/libretroshare/src/gxs/rsgxsutil.h b/libretroshare/src/gxs/rsgxsutil.h index b15e3479f..f6b367f4a 100644 --- a/libretroshare/src/gxs/rsgxsutil.h +++ b/libretroshare/src/gxs/rsgxsutil.h @@ -129,4 +129,14 @@ private: }; +class GroupUpdate +{ +public: + GroupUpdate() : oldGrpMeta(NULL), newGrp(NULL), validUpdate(false) + {} + RsGxsGrpMetaData* oldGrpMeta; + RsNxsGrp* newGrp; + bool validUpdate; +}; + #endif /* GXSUTIL_H_ */ From 6290d8fed96f308aede6acdf4be4fa66a72389a3 Mon Sep 17 00:00:00 2001 From: drbob Date: Fri, 13 Sep 2013 14:35:19 +0000 Subject: [PATCH 13/83] Massive commit - changing from sockaddr_in => sockaddr_storage. In preparation for making RS support IPv6. NB: This breaks the build of retroshare-gui, as the sockaddr_storage_xxx fns are only defined as prototypes for now. All the aux libraries like udp / stun / tcponudp / dht have still to be converted. These changes will probably break various things and need to be tested thoroughly. git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@6735 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/dht/p3bitdht.cc | 4 +- libretroshare/src/dht/p3bitdht.h | 8 +- libretroshare/src/dht/p3bitdht_peernet.cc | 82 ++++- libretroshare/src/dht/p3bitdht_peers.cc | 47 ++- libretroshare/src/dht/stunaddrassist.h | 16 +- libretroshare/src/libretroshare.pro | 6 +- libretroshare/src/pqi/authssl.cc | 5 +- libretroshare/src/pqi/authssl.h | 4 +- libretroshare/src/pqi/p3linkmgr.cc | 201 ++++++----- libretroshare/src/pqi/p3linkmgr.h | 54 +-- libretroshare/src/pqi/p3netmgr.cc | 160 ++++----- libretroshare/src/pqi/p3netmgr.h | 26 +- libretroshare/src/pqi/p3peermgr.cc | 107 +++--- libretroshare/src/pqi/p3peermgr.h | 28 +- libretroshare/src/pqi/p3upnpmgr.h | 4 +- libretroshare/src/pqi/pqi_base.h | 6 +- libretroshare/src/pqi/pqiassist.h | 14 +- libretroshare/src/pqi/pqibin.cc | 5 +- libretroshare/src/pqi/pqibin.h | 4 +- libretroshare/src/pqi/pqiipset.cc | 14 +- libretroshare/src/pqi/pqiipset.h | 2 +- libretroshare/src/pqi/pqilistener.h | 2 +- libretroshare/src/pqi/pqimonitor.cc | 10 +- libretroshare/src/pqi/pqimonitor.h | 12 +- libretroshare/src/pqi/pqinetstatebox.cc | 61 ++-- libretroshare/src/pqi/pqinetstatebox.h | 20 +- libretroshare/src/pqi/pqinetwork.cc | 81 ++++- libretroshare/src/pqi/pqinetwork.h | 4 +- libretroshare/src/pqi/pqiperson.cc | 27 +- libretroshare/src/pqi/pqiperson.h | 10 +- libretroshare/src/pqi/pqipersongrp.cc | 19 +- libretroshare/src/pqi/pqipersongrp.h | 8 +- libretroshare/src/pqi/pqissl.cc | 29 +- libretroshare/src/pqi/pqissl.h | 10 +- libretroshare/src/pqi/pqissllistener.cc | 59 ++-- libretroshare/src/pqi/pqissllistener.h | 16 +- libretroshare/src/pqi/pqisslpersongrp.cc | 2 +- libretroshare/src/pqi/pqisslpersongrp.h | 2 +- libretroshare/src/pqi/pqisslproxy.cc | 2 +- libretroshare/src/pqi/pqissludp.cc | 68 +++- libretroshare/src/pqi/pqissludp.h | 6 +- libretroshare/src/rsserver/p3peers.cc | 47 +-- libretroshare/src/rsserver/p3serverconfig.cc | 8 +- libretroshare/src/rsserver/rsinit.cc | 12 +- libretroshare/src/serialiser/rsconfigitems.cc | 329 ++---------------- libretroshare/src/serialiser/rsconfigitems.h | 44 +-- libretroshare/src/serialiser/rstlvaddrs.cc | 157 ++++++++- libretroshare/src/serialiser/rstlvaddrs.h | 16 +- libretroshare/src/serialiser/rstlvbanlist.cc | 12 +- libretroshare/src/serialiser/rstlvbanlist.h | 3 +- libretroshare/src/serialiser/rstlvbase.cc | 4 +- libretroshare/src/serialiser/rstlvbase.h | 8 + libretroshare/src/services/p3banlist.cc | 57 +-- libretroshare/src/services/p3banlist.h | 10 +- libretroshare/src/services/p3disc.cc | 18 +- libretroshare/src/services/p3disc.h | 6 +- libretroshare/src/tcponudp/rsudpstack.h | 21 +- libretroshare/src/util/dnsresolver.cc | 18 +- libretroshare/src/util/dnsresolver.h | 4 +- libretroshare/src/util/extaddrfinder.cc | 95 ++--- libretroshare/src/util/extaddrfinder.h | 13 +- libretroshare/src/util/rsnet.h | 42 +++ libretroshare/src/zeroconf/p3zcnatassist.cc | 20 +- libretroshare/src/zeroconf/p3zcnatassist.h | 6 +- libretroshare/src/zeroconf/p3zeroconf.cc | 23 +- libretroshare/src/zeroconf/p3zeroconf.h | 10 +- 66 files changed, 1182 insertions(+), 1046 deletions(-) diff --git a/libretroshare/src/dht/p3bitdht.cc b/libretroshare/src/dht/p3bitdht.cc index 1bced9726..e366fbad3 100644 --- a/libretroshare/src/dht/p3bitdht.cc +++ b/libretroshare/src/dht/p3bitdht.cc @@ -349,7 +349,7 @@ bool p3BitDht::dropPeer(std::string pid) /* extract current peer status */ bool p3BitDht::getPeerStatus(std::string id, - struct sockaddr_in &/*laddr*/, struct sockaddr_in &/*raddr*/, + struct sockaddr_storage &/*laddr*/, struct sockaddr_storage &/*raddr*/, uint32_t &/*type*/, uint32_t &/*mode*/) { /* remove unused parameter warnings */ @@ -363,7 +363,7 @@ bool p3BitDht::getPeerStatus(std::string id, return false; } -bool p3BitDht::getExternalInterface(struct sockaddr_in &/*raddr*/, +bool p3BitDht::getExternalInterface(struct sockaddr_storage &/*raddr*/, uint32_t &/*mode*/) { diff --git a/libretroshare/src/dht/p3bitdht.h b/libretroshare/src/dht/p3bitdht.h index 608478c45..d53c9c745 100644 --- a/libretroshare/src/dht/p3bitdht.h +++ b/libretroshare/src/dht/p3bitdht.h @@ -197,8 +197,8 @@ virtual bool getNetworkStats(uint32_t &netsize, uint32_t &localnetsize); virtual bool findPeer(std::string id); virtual bool dropPeer(std::string id); -virtual int addBadPeer(const struct sockaddr_in &addr, uint32_t reason, uint32_t flags, uint32_t age); -virtual int addKnownPeer(const std::string &pid, const struct sockaddr_in &addr, uint32_t flags); +virtual int addBadPeer(const struct sockaddr_storage &addr, uint32_t reason, uint32_t flags, uint32_t age); +virtual int addKnownPeer(const std::string &pid, const struct sockaddr_storage &addr, uint32_t flags); //virtual int addFriend(const std::string pid); //virtual int addFriendOfFriend(const std::string pid); //virtual int addOther(const std::string pid); @@ -208,10 +208,10 @@ virtual void ConnectionFeedback(std::string pid, int state); /* extract current peer status */ virtual bool getPeerStatus(std::string id, - struct sockaddr_in &laddr, struct sockaddr_in &raddr, + struct sockaddr_storage &laddr, struct sockaddr_storage &raddr, uint32_t &type, uint32_t &mode); -virtual bool getExternalInterface(struct sockaddr_in &raddr, +virtual bool getExternalInterface(struct sockaddr_storage &raddr, uint32_t &mode); diff --git a/libretroshare/src/dht/p3bitdht_peernet.cc b/libretroshare/src/dht/p3bitdht_peernet.cc index 5420726f8..2a1915ddd 100644 --- a/libretroshare/src/dht/p3bitdht_peernet.cc +++ b/libretroshare/src/dht/p3bitdht_peernet.cc @@ -72,7 +72,13 @@ int p3BitDht::InfoCallback(const bdId *id, uint32_t /*type*/, uint32_t /*flags*/ if (mPeerSharer) { - mPeerSharer->updatePeer(rsid, addr, outtype, outreason, outage); + struct sockaddr_storage tmpaddr; + struct sockaddr_in *ap = (struct sockaddr_in *) &tmpaddr; + ap->sin_family = AF_INET; + ap->sin_addr = addr.sin_addr; + ap->sin_port = addr.sin_port; + + mPeerSharer->updatePeer(rsid, tmpaddr, outtype, outreason, outage); } /* call to the Stunners to drop the address as well */ @@ -1768,14 +1774,25 @@ int p3BitDht::checkConnectionAllowed(const bdId *peerId, int mode) */ -void p3BitDht::ConnectCalloutTCPAttempt(const std::string &peerId, struct sockaddr_in raddr) +void p3BitDht::ConnectCalloutTCPAttempt(const std::string &peerId, struct sockaddr_in raddrv4) { - struct sockaddr_in proxyaddr; - struct sockaddr_in srcaddr; - - sockaddr_clear(&proxyaddr); - sockaddr_clear(&srcaddr); + struct sockaddr_storage raddr; + struct sockaddr_storage proxyaddr; + struct sockaddr_storage srcaddr; + + sockaddr_storage_clear(proxyaddr); + sockaddr_storage_clear(proxyaddr); + sockaddr_storage_clear(srcaddr); + struct sockaddr_in *rap = (struct sockaddr_in *) &raddr; + struct sockaddr_in *pap = (struct sockaddr_in *) &proxyaddr; + struct sockaddr_in *sap = (struct sockaddr_in *) &srcaddr; + + // only one to translate + rap->sin_family = AF_INET; + rap->sin_addr = raddrv4.sin_addr; + rap->sin_port = raddrv4.sin_port; + uint32_t source = RS_CB_DHT; uint32_t connectFlags = RS_CB_FLAG_ORDER_UNSPEC | RS_CB_FLAG_MODE_TCP; uint32_t delay = 0; @@ -1785,14 +1802,25 @@ void p3BitDht::ConnectCalloutTCPAttempt(const std::string &peerId, struct sockad } -void p3BitDht::ConnectCalloutDirectOrProxy(const std::string &peerId, struct sockaddr_in raddr, uint32_t connectFlags, uint32_t delay) +void p3BitDht::ConnectCalloutDirectOrProxy(const std::string &peerId, struct sockaddr_in raddrv4, uint32_t connectFlags, uint32_t delay) { - struct sockaddr_in proxyaddr; - struct sockaddr_in srcaddr; - - sockaddr_clear(&proxyaddr); - sockaddr_clear(&srcaddr); - + struct sockaddr_storage raddr; + struct sockaddr_storage proxyaddr; + struct sockaddr_storage srcaddr; + + sockaddr_storage_clear(proxyaddr); + sockaddr_storage_clear(proxyaddr); + sockaddr_storage_clear(srcaddr); + + struct sockaddr_in *rap = (struct sockaddr_in *) &raddr; + struct sockaddr_in *pap = (struct sockaddr_in *) &proxyaddr; + struct sockaddr_in *sap = (struct sockaddr_in *) &srcaddr; + + // only one to translate + rap->sin_family = AF_INET; + rap->sin_addr = raddrv4.sin_addr; + rap->sin_port = raddrv4.sin_port; + uint32_t source = RS_CB_DHT; uint32_t bandwidth = 0; @@ -1800,9 +1828,33 @@ void p3BitDht::ConnectCalloutDirectOrProxy(const std::string &peerId, struct soc } void p3BitDht::ConnectCalloutRelay(const std::string &peerId, - struct sockaddr_in srcaddr, struct sockaddr_in proxyaddr, struct sockaddr_in destaddr, + struct sockaddr_in srcaddrv4, struct sockaddr_in proxyaddrv4, struct sockaddr_in destaddrv4, uint32_t connectFlags, uint32_t bandwidth) { + struct sockaddr_storage destaddr; + struct sockaddr_storage proxyaddr; + struct sockaddr_storage srcaddr; + + sockaddr_storage_clear(proxyaddr); + sockaddr_storage_clear(proxyaddr); + sockaddr_storage_clear(srcaddr); + + struct sockaddr_in *dap = (struct sockaddr_in *) &destaddr; + struct sockaddr_in *pap = (struct sockaddr_in *) &proxyaddr; + struct sockaddr_in *sap = (struct sockaddr_in *) &srcaddr; + + dap->sin_family = AF_INET; + dap->sin_addr = destaddrv4.sin_addr; + dap->sin_port = destaddrv4.sin_port; + + pap->sin_family = AF_INET; + pap->sin_addr = proxyaddrv4.sin_addr; + pap->sin_port = proxyaddrv4.sin_port; + + sap->sin_family = AF_INET; + sap->sin_addr = srcaddrv4.sin_addr; + sap->sin_port = srcaddrv4.sin_port; + uint32_t source = RS_CB_DHT; uint32_t delay = 0; diff --git a/libretroshare/src/dht/p3bitdht_peers.cc b/libretroshare/src/dht/p3bitdht_peers.cc index c16a742a9..f488af671 100644 --- a/libretroshare/src/dht/p3bitdht_peers.cc +++ b/libretroshare/src/dht/p3bitdht_peers.cc @@ -184,26 +184,59 @@ bool p3BitDht::dropPeer(std::string pid) ********************************* Basic Peer Details ************************************* ******************************************************************************************/ -int p3BitDht::addBadPeer(const struct sockaddr_in &addr, uint32_t /*reason*/, uint32_t /*flags*/, uint32_t /*age*/) +int p3BitDht::addBadPeer(const struct sockaddr_storage &addr, uint32_t /*reason*/, uint32_t /*flags*/, uint32_t /*age*/) { //mUdpBitDht->updateKnownPeer(&id, 0, bdflags); + struct sockaddr_in addrv4; + if (addr.ss_family != AF_INET) + { + std::cerr << "p3BitDht::addBadPeer() cannot handle IPV6 Yet, aborting"; + std::cerr << std::endl; + abort(); + } + struct sockaddr_in *ap = (struct sockaddr_in *) &addr; + + // convert. + addrv4.sin_family = ap->sin_family; + addrv4.sin_addr = ap->sin_addr; + addrv4.sin_port = ap->sin_port; + + if (mDhtStunner) { - mDhtStunner->dropStunPeer(addr); + mDhtStunner->dropStunPeer(addrv4); } if (mProxyStunner) { - mProxyStunner->dropStunPeer(addr); + mProxyStunner->dropStunPeer(addrv4); } return 1; } -int p3BitDht::addKnownPeer(const std::string &pid, const struct sockaddr_in &addr, uint32_t flags) +int p3BitDht::addKnownPeer(const std::string &pid, const struct sockaddr_storage &addr, uint32_t flags) { - + struct sockaddr_in addrv4; + if (addr.ss_family != AF_INET) + { + std::cerr << "p3BitDht::addKnownPeer() cannot handle IPV6 Yet, aborting"; + std::cerr << std::endl; + abort(); + } + struct sockaddr_in *ap = (struct sockaddr_in *) &addr; + + // convert. + addrv4.sin_family = ap->sin_family; + addrv4.sin_addr = ap->sin_addr; + addrv4.sin_port = ap->sin_port; + + + + + + int p3type = 0; int bdflags = 0; bdId id; @@ -262,13 +295,13 @@ int p3BitDht::addKnownPeer(const std::string &pid, const struct sockaddr_in &add id.id = dpd->mDhtId.id; - id.addr = addr; + id.addr = addrv4; } else { // shouldn't use own id without mutex - but it is static! id.id = mOwnDhtId; - id.addr = addr; + id.addr = addrv4; } mUdpBitDht->updateKnownPeer(&id, 0, bdflags); diff --git a/libretroshare/src/dht/stunaddrassist.h b/libretroshare/src/dht/stunaddrassist.h index 780267427..1df0bfabc 100644 --- a/libretroshare/src/dht/stunaddrassist.h +++ b/libretroshare/src/dht/stunaddrassist.h @@ -39,9 +39,21 @@ class stunAddrAssist: public pqiAddrAssist mStunner = stunner; } -virtual bool getExternalAddr(struct sockaddr_in &remote, uint8_t &stable) +virtual bool getExternalAddr(struct sockaddr_storage &remote, uint8_t &stable) { - return mStunner->externalAddr(remote, stable); + // IPV4 ONLY. + struct sockaddr_in remotev4; + if (mStunner->externalAddr(remotev4, stable)) + { + sockaddr_storage_clear(remote); + struct sockaddr_in *addr = (struct sockaddr_in *) &remote; + addr->sin_family = AF_INET; + addr->sin_addr = remotev4.sin_addr; + addr->sin_port = remotev4.sin_port; + + return true; + } + return false; } virtual int tick() diff --git a/libretroshare/src/libretroshare.pro b/libretroshare/src/libretroshare.pro index 3fd616849..643f0964f 100644 --- a/libretroshare/src/libretroshare.pro +++ b/libretroshare/src/libretroshare.pro @@ -323,7 +323,6 @@ HEADERS += pqi/authssl.h \ pqi/p3peermgr.h \ pqi/p3linkmgr.h \ pqi/p3netmgr.h \ - pqi/p3dhtmgr.h \ pqi/p3notify.h \ pqi/p3upnpmgr.h \ pqi/pqiqos.h \ @@ -357,6 +356,8 @@ HEADERS += pqi/authssl.h \ pqi/sslfns.h \ pqi/pqinetstatebox.h +# pqi/p3dhtmgr.h \ + HEADERS += rsserver/p3discovery.h \ rsserver/p3face.h \ rsserver/p3history.h \ @@ -449,7 +450,6 @@ SOURCES += pqi/authgpg.cc \ pqi/p3peermgr.cc \ pqi/p3linkmgr.cc \ pqi/p3netmgr.cc \ - pqi/p3dhtmgr.cc \ pqi/p3notify.cc \ pqi/pqiqos.cc \ pqi/pqiarchive.cc \ @@ -475,6 +475,8 @@ SOURCES += pqi/authgpg.cc \ pqi/sslfns.cc \ pqi/pqinetstatebox.cc +# pqi/p3dhtmgr.cc \ + SOURCES += rsserver/p3discovery.cc \ rsserver/p3face-config.cc \ rsserver/p3face-msgs.cc \ diff --git a/libretroshare/src/pqi/authssl.cc b/libretroshare/src/pqi/authssl.cc index b7c87ba25..7cf8734e0 100644 --- a/libretroshare/src/pqi/authssl.cc +++ b/libretroshare/src/pqi/authssl.cc @@ -1329,11 +1329,10 @@ void AuthSSLimpl::getCurrentConnectionAttemptInfo(std::string& gpg_id,std::strin bool AuthSSLimpl::FailedCertificate(X509 *x509, const std::string& gpgid, const std::string& sslid, const std::string& sslcn, - const struct sockaddr_in& addr, + const struct sockaddr_storage& addr, bool incoming) { - std::string ip_address ; - rs_sprintf_append(ip_address, "%s:%u", rs_inet_ntoa(addr.sin_addr).c_str(), ntohs(addr.sin_port)); + std::string ip_address = sockaddr_storage_tostring(addr); bool authed = (x509 != NULL && AuthX509WithGPG(x509)) ; diff --git a/libretroshare/src/pqi/authssl.h b/libretroshare/src/pqi/authssl.h index 99c9d0488..bf05b1793 100644 --- a/libretroshare/src/pqi/authssl.h +++ b/libretroshare/src/pqi/authssl.h @@ -153,7 +153,7 @@ virtual SSL_CTX *getCTX() = 0; virtual void setCurrentConnectionAttemptInfo(const std::string& gpg_id,const std::string& ssl_id,const std::string& ssl_cn) = 0 ; virtual void getCurrentConnectionAttemptInfo( std::string& gpg_id, std::string& ssl_id, std::string& ssl_cn) = 0 ; -virtual bool FailedCertificate(X509 *x509, const std::string& gpgid,const std::string& sslid,const std::string& sslcn,const struct sockaddr_in &addr, bool incoming) = 0; /* store for discovery */ +virtual bool FailedCertificate(X509 *x509, const std::string& gpgid,const std::string& sslid,const std::string& sslcn,const struct sockaddr_storage &addr, bool incoming) = 0; /* store for discovery */ virtual bool CheckCertificate(std::string peerId, X509 *x509) = 0; /* check that they are exact match */ static void setAuthSSL_debug(AuthSSL*) ; // used for debug only. The real function is InitSSL() @@ -232,7 +232,7 @@ virtual SSL_CTX *getCTX(); /* Restored these functions: */ virtual void setCurrentConnectionAttemptInfo(const std::string& gpg_id,const std::string& ssl_id,const std::string& ssl_cn) ; virtual void getCurrentConnectionAttemptInfo( std::string& gpg_id, std::string& ssl_id, std::string& ssl_cn) ; -virtual bool FailedCertificate(X509 *x509, const std::string& gpgid,const std::string& sslid,const std::string& sslcn,const struct sockaddr_in &addr, bool incoming); /* store for discovery */ +virtual bool FailedCertificate(X509 *x509, const std::string& gpgid,const std::string& sslid,const std::string& sslcn,const struct sockaddr_storage &addr, bool incoming); /* store for discovery */ virtual bool CheckCertificate(std::string peerId, X509 *x509); /* check that they are exact match */ diff --git a/libretroshare/src/pqi/p3linkmgr.cc b/libretroshare/src/pqi/p3linkmgr.cc index 0f95d11e0..8e268c207 100644 --- a/libretroshare/src/pqi/p3linkmgr.cc +++ b/libretroshare/src/pqi/p3linkmgr.cc @@ -58,6 +58,11 @@ const int p3connectzone = 3431; * #define LINKMGR_DEBUG_LINKTYPE 1 ***/ +#define LINKMGR_DEBUG 1 +#define LINKMGR_DEBUG_CONNFAIL 1 +#define LINKMGR_DEBUG_ACTIONS 1 +#define LINKMGR_DEBUG_LINKTYPE 1 + /**** * #define DISABLE_UDP_CONNECTIONS 1 ***/ @@ -87,7 +92,7 @@ void printConnectState(std::ostream &out, peerConnectState &peer); peerConnectAddress::peerConnectAddress() :delay(0), period(0), type(0), flags(0), ts(0), domain_port(0) { - sockaddr_clear(&addr); + sockaddr_storage_clear(addr); } @@ -144,10 +149,13 @@ p3LinkMgrIMPL::p3LinkMgrIMPL(p3PeerMgrIMPL *peerMgr, p3NetMgrIMPL *netMgr) /* setup Banned Ip Address - static for now */ - struct in_addr bip; - memset(&bip, 0, sizeof(bip)); - bip.s_addr = 1; - + struct sockaddr_storage bip; + sockaddr_storage_clear(bip); + struct sockaddr_in *addr = (struct sockaddr_in *) &bip; + addr->sin_family = AF_INET; + addr->sin_addr.s_addr = 1; + addr->sin_port = htons(0); + mBannedIpList.push_back(bip); } @@ -158,7 +166,7 @@ p3LinkMgrIMPL::p3LinkMgrIMPL(p3PeerMgrIMPL *peerMgr, p3NetMgrIMPL *netMgr) return; } -bool p3LinkMgrIMPL::setLocalAddress(struct sockaddr_in addr) +bool p3LinkMgrIMPL::setLocalAddress(const struct sockaddr_storage &addr) { RsStackMutex stack(mLinkMtx); /****** STACK LOCK MUTEX *******/ mLocalAddress = addr; @@ -166,10 +174,11 @@ bool p3LinkMgrIMPL::setLocalAddress(struct sockaddr_in addr) return true ; } -struct sockaddr_in p3LinkMgrIMPL::getLocalAddress() +bool p3LinkMgrIMPL::getLocalAddress(struct sockaddr_storage &addr) { RsStackMutex stack(mLinkMtx); /****** STACK LOCK MUTEX *******/ - return mLocalAddress; + addr = mLocalAddress; + return true; } @@ -572,9 +581,9 @@ const std::string p3LinkMgrIMPL::getOwnId() } -bool p3LinkMgrIMPL::connectAttempt(const std::string &id, struct sockaddr_in &raddr, - struct sockaddr_in &proxyaddr, - struct sockaddr_in &srcaddr, +bool p3LinkMgrIMPL::connectAttempt(const std::string &id, struct sockaddr_storage &raddr, + struct sockaddr_storage &proxyaddr, + struct sockaddr_storage &srcaddr, uint32_t &delay, uint32_t &period, uint32_t &type, uint32_t &flags, uint32_t &bandwidth, std::string &domain_addr, uint16_t &domain_port) @@ -731,7 +740,7 @@ bool p3LinkMgrIMPL::connectAttempt(const std::string &id, struct sockaddr_in &ra std::cerr << "p3LinkMgrIMPL::connectAttempt() found an address: id: " << id << std::endl; - std::cerr << " laddr: " << rs_inet_ntoa(raddr.sin_addr) << " lport: " << ntohs(raddr.sin_port) << " delay: " << delay << " period: " << period; + std::cerr << " laddr: " << sockaddr_storage_tostring(raddr) << " delay: " << delay << " period: " << period; std::cerr << " type: " << type << std::endl; std::cerr << "p3LinkMgrIMPL::connectAttempt() set LinkType to: " << it->second.linkType << std::endl; #endif @@ -741,11 +750,11 @@ bool p3LinkMgrIMPL::connectAttempt(const std::string &id, struct sockaddr_in &ra #ifdef LINKMGR_DEBUG std::cerr << "p3LinkMgrIMPL::connectAttempt() found an address: id: " << id << std::endl; - std::cerr << " laddr: " << rs_inet_ntoa(addr.sin_addr) << " lport: " << ntohs(addr.sin_port) << " delay: " << delay << " period: " << period; + std::cerr << " laddr: " << sockaddr_storage_tostring(raddr) << " delay: " << delay << " period: " << period; std::cerr << " type: " << type << std::endl; std::cerr << "p3LinkMgrIMPL::connectAttempt() set LinkType to: " << it->second.linkType << std::endl; #endif - if (raddr.sin_addr.s_addr == 0 || raddr.sin_port == 0) { + if (sockaddr_storage_isnull(raddr)) { #ifdef LINKMGR_DEBUG std::cerr << "p3LinkMgrIMPL::connectAttempt() WARNING: address or port is null" << std::endl; std::cerr << " type: " << type << std::endl; @@ -764,7 +773,7 @@ bool p3LinkMgrIMPL::connectAttempt(const std::string &id, struct sockaddr_in &ra * */ -bool p3LinkMgrIMPL::connectResult(const std::string &id, bool success, uint32_t flags, struct sockaddr_in remote_peer_address) +bool p3LinkMgrIMPL::connectResult(const std::string &id, bool success, uint32_t flags, const struct sockaddr_storage &remote_peer_address) { bool doDhtAssist = false ; bool updatePeerAddr = false; @@ -857,10 +866,7 @@ bool p3LinkMgrIMPL::connectResult(const std::string &id, bool success, uint32_t // This means we only update connections that we've made.. so maybe not too bad? if ((it->second.inConnAttempt) && - (it->second.currentConnAddrAttempt.addr.sin_addr.s_addr - == remote_peer_address.sin_addr.s_addr) && - (it->second.currentConnAddrAttempt.addr.sin_port - == remote_peer_address.sin_port)) + (sockaddr_storage_same(it->second.currentConnAddrAttempt.addr, remote_peer_address))) { updatePeerAddr = true; #ifdef LINKMGR_DEBUG @@ -986,7 +992,7 @@ bool p3LinkMgrIMPL::connectResult(const std::string &id, bool success, uint32_t mNetMgr->netAssistFriend(id,false); /* inform NetMgr that we know this peers address: but only if external address */ - if (isExternalNet(&(remote_peer_address.sin_addr))) + if (sockaddr_storage_isExternalNet(remote_peer_address)) { mNetMgr->netAssistKnownPeer(id,remote_peer_address, NETASSIST_KNOWN_PEER_FRIEND | NETASSIST_KNOWN_PEER_ONLINE); @@ -1022,7 +1028,7 @@ bool p3LinkMgrIMPL::connectResult(const std::string &id, bool success, uint32_t */ // from pqissl, when a connection failed due to security -void p3LinkMgrIMPL::notifyDeniedConnection(const std::string& gpgid,const std::string& sslid,const std::string& sslcn,const struct sockaddr_in &addr, bool incoming) +void p3LinkMgrIMPL::notifyDeniedConnection(const std::string& gpgid,const std::string& sslid,const std::string& sslcn,const struct sockaddr_storage &addr, bool incoming) { std::cerr << "p3LinkMgrIMPL::notifyDeniedConnection()"; std::cerr << " pgpid: " << gpgid; @@ -1335,14 +1341,14 @@ void p3LinkMgrIMPL::peerStatus(std::string id, const pqiIpAddrSet &addrs, } /* This has become very unwieldy - as extra arguments are required for UDP connections */ -void p3LinkMgrIMPL::peerConnectRequest(std::string id, struct sockaddr_in raddr, struct sockaddr_in proxyaddr, struct sockaddr_in srcaddr, +void p3LinkMgrIMPL::peerConnectRequest(std::string id, const struct sockaddr_storage &raddr, const struct sockaddr_storage &proxyaddr, const struct sockaddr_storage &srcaddr, uint32_t source, uint32_t flags, uint32_t delay, uint32_t bandwidth) { #ifdef LINKMGR_DEBUG std::cerr << "p3LinkMgrIMPL::peerConnectRequest() id: " << id; - std::cerr << " raddr: " << rs_inet_ntoa(raddr.sin_addr) << ":" << ntohs(raddr.sin_port); - std::cerr << " proxyaddr: " << rs_inet_ntoa(proxyaddr.sin_addr) << ":" << ntohs(proxyaddr.sin_port); - std::cerr << " srcaddr: " << rs_inet_ntoa(srcaddr.sin_addr) << ":" << ntohs(srcaddr.sin_port); + std::cerr << " raddr: " << sockaddr_storage_tostring(raddr); + std::cerr << " proxyaddr: " << sockaddr_storage_tostring(proxyaddr); + std::cerr << " srcaddr: " << sockaddr_storage_tostring(srcaddr); std::cerr << " source: " << source; std::cerr << " flags: " << flags; std::cerr << " delay: " << delay; @@ -1352,9 +1358,13 @@ void p3LinkMgrIMPL::peerConnectRequest(std::string id, struct sockaddr_in rad { /* Log */ std::string out = "p3LinkMgrIMPL::peerConnectRequest() id: " + id; - rs_sprintf_append(out, " raddr: %s:%u", rs_inet_ntoa(raddr.sin_addr).c_str(), ntohs(raddr.sin_port)); - rs_sprintf_append(out, " proxyaddr: %s:%u", rs_inet_ntoa(proxyaddr.sin_addr).c_str(), ntohs(proxyaddr.sin_port)); - rs_sprintf_append(out, " srcaddr: %s:%u", rs_inet_ntoa(srcaddr.sin_addr).c_str(), ntohs(srcaddr.sin_port)); + out += " raddr: "; + out += sockaddr_storage_tostring(raddr); + out += " proxyaddr: "; + out += sockaddr_storage_tostring(proxyaddr); + out += " srcaddr: "; + out += sockaddr_storage_tostring(srcaddr); + rs_sprintf_append(out, " source: %lu", source); rs_sprintf_append(out, " flags: %lu", flags); rs_sprintf_append(out, " delay: %lu", delay); @@ -1402,7 +1412,7 @@ void p3LinkMgrIMPL::peerConnectRequest(std::string id, struct sockaddr_in rad return; } /* setup specific attempt for DHT found address. */ - locked_ConnectAttempt_SpecificAddress(&(it->second), &raddr); + locked_ConnectAttempt_SpecificAddress(&(it->second), raddr); } retryConnect(id); @@ -1454,8 +1464,8 @@ bool p3LinkMgrIMPL::retryConnect(const std::string &id) -bool p3LinkMgrIMPL::tryConnectUDP(const std::string &id, struct sockaddr_in &rUdpAddr, - struct sockaddr_in &proxyaddr, struct sockaddr_in &srcaddr, +bool p3LinkMgrIMPL::tryConnectUDP(const std::string &id, const struct sockaddr_storage &rUdpAddr, + const struct sockaddr_storage &proxyaddr, const struct sockaddr_storage &srcaddr, uint32_t flags, uint32_t delay, uint32_t bandwidth) { @@ -1520,12 +1530,11 @@ bool p3LinkMgrIMPL::tryConnectUDP(const std::string &id, struct sockaddr_in &r } /* Explicit Request to start the UDP connection */ - if (isValidNet(&(rUdpAddr.sin_addr))) + if (sockaddr_storage_isValidNet(rUdpAddr)) { #ifdef LINKMGR_DEBUG std::cerr << "Adding udp connection attempt: "; - std::cerr << "Addr: " << rs_inet_ntoa(rUdpAddr.sin_addr); - std::cerr << ":" << ntohs(rUdpAddr.sin_port); + std::cerr << "Addr: " << sockaddr_storage_tostring(rUdpAddr); std::cerr << std::endl; #endif peerConnectAddress pca; @@ -1605,7 +1614,7 @@ bool p3LinkMgrIMPL::retryConnectTCP(const std::string &id) /* first possibility - is it a hidden peer */ if (mPeerMgr->isHiddenPeer(id)) { - struct sockaddr_in proxy_addr; + struct sockaddr_storage proxy_addr; std::string domain_addr; uint16_t domain_port; @@ -1617,7 +1626,7 @@ bool p3LinkMgrIMPL::retryConnectTCP(const std::string &id) std::map::iterator it; if (mFriendList.end() != (it = mFriendList.find(id))) { - locked_ConnectAttempt_ProxyAddress(&(it->second), &proxy_addr, domain_addr, domain_port); + locked_ConnectAttempt_ProxyAddress(&(it->second), proxy_addr, domain_addr, domain_port); return locked_ConnectAttempt_Complete(&(it->second)); } } @@ -1631,8 +1640,8 @@ bool p3LinkMgrIMPL::retryConnectTCP(const std::string &id) return false; } - struct sockaddr_in lAddr; - struct sockaddr_in eAddr; + struct sockaddr_storage lAddr; + struct sockaddr_storage eAddr; pqiIpAddrSet histAddrs; std::string dyndns; @@ -1643,11 +1652,11 @@ bool p3LinkMgrIMPL::retryConnectTCP(const std::string &id) std::map::iterator it; if (mFriendList.end() != (it = mFriendList.find(id))) { - locked_ConnectAttempt_CurrentAddresses(&(it->second), &lAddr, &eAddr); + locked_ConnectAttempt_CurrentAddresses(&(it->second), lAddr, eAddr); - uint16_t dynPort = ntohs(eAddr.sin_port); + uint16_t dynPort = sockaddr_storage_port(eAddr); if (!dynPort) - dynPort = ntohs(lAddr.sin_port); + dynPort = sockaddr_storage_port(lAddr); if (dynPort) { locked_ConnectAttempt_AddDynDNS(&(it->second), dyndns, dynPort); @@ -1677,12 +1686,11 @@ bool p3LinkMgrIMPL::retryConnectTCP(const std::string &id) #define MAX_TCP_ADDR_AGE (3600 * 24 * 14) // two weeks in seconds. -bool p3LinkMgrIMPL::locked_CheckPotentialAddr(const struct sockaddr_in *addr, time_t age) +bool p3LinkMgrIMPL::locked_CheckPotentialAddr(const struct sockaddr_storage &addr, time_t age) { #ifdef LINKMGR_DEBUG std::cerr << "p3LinkMgrIMPL::locked_CheckPotentialAddr("; - std::cerr << rs_inet_ntoa(addr->sin_addr); - std::cerr << ":" << ntohs(addr->sin_port); + std::cerr << sockaddr_storage_tostring(addr); std::cerr << ", " << age << ")"; std::cerr << std::endl; #endif @@ -1699,10 +1707,10 @@ bool p3LinkMgrIMPL::locked_CheckPotentialAddr(const struct sockaddr_in *addr, t return false; } - bool isValid = isValidNet(&(addr->sin_addr)); - // bool isLoopback = isLoopbackNet(&(addr->sin_addr)); - // bool isPrivate = isPrivateNet(&(addr->sin_addr)); - bool isExternal = isExternalNet(&(addr->sin_addr)); + bool isValid = sockaddr_storage_isValidNet(addr); + // bool isLoopback = sockaddr_storage_isLoopbackNet(addr); + // bool isPrivate = sockaddr_storage_isPrivateNet(addr); + bool isExternal = sockaddr_storage_isExternalNet(addr); /* if invalid - quick rejection */ if (!isValid) @@ -1717,10 +1725,10 @@ bool p3LinkMgrIMPL::locked_CheckPotentialAddr(const struct sockaddr_in *addr, t /* if it is on the ban list - ignore */ /* checks - is it the dreaded 1.0.0.0 */ - std::list::const_iterator it; + std::list::const_iterator it; for(it = mBannedIpList.begin(); it != mBannedIpList.end(); it++) { - if (it->s_addr == addr->sin_addr.s_addr) + if (sockaddr_storage_sameip(*it, addr)) { #ifdef LINKMGR_DEBUG std::cerr << "p3LinkMgrIMPL::locked_CheckPotentialAddr() REJECTING - ON BANNED IPLIST"; @@ -1751,12 +1759,12 @@ bool p3LinkMgrIMPL::locked_CheckPotentialAddr(const struct sockaddr_in *addr, t #ifdef LINKMGR_DEBUG std::cerr << "p3LinkMgrIMPL::locked_CheckPotentialAddr() Checking sameNet against: "; - std::cerr << rs_inet_ntoa(mLocalAddress.sin_addr); + std::cerr << sockaddr_storage_iptostring(mLocalAddress); std::cerr << ")"; std::cerr << std::endl; #endif - if (sameNet(&(mLocalAddress.sin_addr), &(addr->sin_addr))) + if (sockaddr_storage_samenet(mLocalAddress, addr)) { #ifdef LINKMGR_DEBUG std::cerr << "p3LinkMgrIMPL::locked_CheckPotentialAddr() ACCEPTING - PRIVATE & sameNET"; @@ -1776,29 +1784,28 @@ bool p3LinkMgrIMPL::locked_CheckPotentialAddr(const struct sockaddr_in *addr, t } -void p3LinkMgrIMPL::locked_ConnectAttempt_SpecificAddress(peerConnectState *peer, struct sockaddr_in *remoteAddr) +void p3LinkMgrIMPL::locked_ConnectAttempt_SpecificAddress(peerConnectState *peer, const struct sockaddr_storage &remoteAddr) { #ifdef LINKMGR_DEBUG std::cerr << "p3LinkMgrIMPL::locked_ConnectAttempt_SpecificAddresses()"; std::cerr << std::endl; #endif - if ((remoteAddr) && (locked_CheckPotentialAddr(remoteAddr, 0))) + if (locked_CheckPotentialAddr(remoteAddr, 0)) { #ifdef LINKMGR_DEBUG std::cerr << "p3LinkMgrIMPL::locked_ConnectAttempt_SpecificAddresses() "; std::cerr << "Adding tcp connection attempt: "; - std::cerr << "Addr: " << rs_inet_ntoa(remoteAddr->sin_addr); - std::cerr << ":" << ntohs(remoteAddr->sin_port); + std::cerr << "Addr: " << sockaddr_storage_tostring(remoteAddr); std::cerr << std::endl; #endif peerConnectAddress pca; - pca.addr = *remoteAddr; + pca.addr = remoteAddr; pca.type = RS_NET_CONN_TCP_EXTERNAL; pca.delay = P3CONNMGR_TCP_DEFAULT_DELAY; pca.ts = time(NULL); pca.period = P3CONNMGR_TCP_DEFAULT_PERIOD; - sockaddr_clear(&(pca.proxyaddr)); - sockaddr_clear(&(pca.srcaddr)); + sockaddr_storage_clear(pca.proxyaddr); + sockaddr_storage_clear(pca.srcaddr); pca.bandwidth = 0; addAddressIfUnique(peer->connAddrs, pca, false); @@ -1806,7 +1813,7 @@ void p3LinkMgrIMPL::locked_ConnectAttempt_SpecificAddress(peerConnectState *pee } -void p3LinkMgrIMPL::locked_ConnectAttempt_CurrentAddresses(peerConnectState *peer, struct sockaddr_in *localAddr, struct sockaddr_in *serverAddr) +void p3LinkMgrIMPL::locked_ConnectAttempt_CurrentAddresses(peerConnectState *peer, const struct sockaddr_storage &localAddr, const struct sockaddr_storage &serverAddr) { #ifdef LINKMGR_DEBUG std::cerr << "p3LinkMgrIMPL::locked_ConnectAttempt_CurrentAddresses()"; @@ -1814,45 +1821,43 @@ void p3LinkMgrIMPL::locked_ConnectAttempt_CurrentAddresses(peerConnectState *pe #endif // Just push all the addresses onto the stack. /* try "current addresses" first */ - if ((localAddr) && (locked_CheckPotentialAddr(localAddr, 0))) + if (locked_CheckPotentialAddr(localAddr, 0)) { #ifdef LINKMGR_DEBUG std::cerr << "p3LinkMgrIMPL::locked_ConnectAttempt_CurrentAddresses() "; std::cerr << "Adding tcp connection attempt: "; - std::cerr << "Current Local Addr: " << rs_inet_ntoa(localAddr->sin_addr); - std::cerr << ":" << ntohs(localAddr->sin_port); + std::cerr << "Current Local Addr: " << sockaddr_storage_tostring(localAddr); std::cerr << std::endl; #endif peerConnectAddress pca; - pca.addr = *localAddr; + pca.addr = localAddr; pca.type = RS_NET_CONN_TCP_LOCAL; pca.delay = P3CONNMGR_TCP_DEFAULT_DELAY; pca.ts = time(NULL); pca.period = P3CONNMGR_TCP_DEFAULT_PERIOD; - sockaddr_clear(&(pca.proxyaddr)); - sockaddr_clear(&(pca.srcaddr)); + sockaddr_storage_clear(pca.proxyaddr); + sockaddr_storage_clear(pca.srcaddr); pca.bandwidth = 0; addAddressIfUnique(peer->connAddrs, pca, false); } - if ((serverAddr) && (locked_CheckPotentialAddr(serverAddr, 0))) + if (locked_CheckPotentialAddr(serverAddr, 0)) { #ifdef LINKMGR_DEBUG std::cerr << "p3LinkMgrIMPL::locked_ConnectAttempt_CurrentAddresses() "; std::cerr << "Adding tcp connection attempt: "; - std::cerr << "Current Ext Addr: " << rs_inet_ntoa(serverAddr->sin_addr); - std::cerr << ":" << ntohs(serverAddr->sin_port); + std::cerr << "Current Ext Addr: " << sockaddr_storage_tostring(serverAddr); std::cerr << std::endl; #endif peerConnectAddress pca; - pca.addr = *serverAddr; + pca.addr = serverAddr; pca.type = RS_NET_CONN_TCP_EXTERNAL; pca.delay = P3CONNMGR_TCP_DEFAULT_DELAY; pca.ts = time(NULL); pca.period = P3CONNMGR_TCP_DEFAULT_PERIOD; - sockaddr_clear(&(pca.proxyaddr)); - sockaddr_clear(&(pca.srcaddr)); + sockaddr_storage_clear(pca.proxyaddr); + sockaddr_storage_clear(pca.srcaddr); pca.bandwidth = 0; addAddressIfUnique(peer->connAddrs, pca, false); @@ -1874,14 +1879,13 @@ void p3LinkMgrIMPL::locked_ConnectAttempt_HistoricalAddresses(peerConnectState for(ait = ipAddrs.mLocal.mAddrs.begin(); ait != ipAddrs.mLocal.mAddrs.end(); ait++) { - if (locked_CheckPotentialAddr(&(ait->mAddr), now - ait->mSeenTime)) + if (locked_CheckPotentialAddr(ait->mAddr, now - ait->mSeenTime)) { #ifdef LINKMGR_DEBUG std::cerr << "p3LinkMgrIMPL::locked_ConnectAttempt_HistoricalAddresses() "; std::cerr << "Adding tcp connection attempt: "; - std::cerr << "Local Addr: " << rs_inet_ntoa(ait->mAddr.sin_addr); - std::cerr << ":" << ntohs(ait->mAddr.sin_port); + std::cerr << "Local Addr: " << sockaddr_storage_tostring(ait->mAddr); std::cerr << std::endl; #endif @@ -1891,8 +1895,8 @@ void p3LinkMgrIMPL::locked_ConnectAttempt_HistoricalAddresses(peerConnectState pca.delay = P3CONNMGR_TCP_DEFAULT_DELAY; pca.ts = time(NULL); pca.period = P3CONNMGR_TCP_DEFAULT_PERIOD; - sockaddr_clear(&(pca.proxyaddr)); - sockaddr_clear(&(pca.srcaddr)); + sockaddr_storage_clear(pca.proxyaddr); + sockaddr_storage_clear(pca.srcaddr); pca.bandwidth = 0; addAddressIfUnique(peer->connAddrs, pca, false); @@ -1902,14 +1906,13 @@ void p3LinkMgrIMPL::locked_ConnectAttempt_HistoricalAddresses(peerConnectState for(ait = ipAddrs.mExt.mAddrs.begin(); ait != ipAddrs.mExt.mAddrs.end(); ait++) { - if (locked_CheckPotentialAddr(&(ait->mAddr), now - ait->mSeenTime)) + if (locked_CheckPotentialAddr(ait->mAddr, now - ait->mSeenTime)) { #ifdef LINKMGR_DEBUG std::cerr << "p3LinkMgrIMPL::locked_ConnectAttempt_HistoricalAddresses() "; std::cerr << "Adding tcp connection attempt: "; - std::cerr << "Ext Addr: " << rs_inet_ntoa(ait->mAddr.sin_addr); - std::cerr << ":" << ntohs(ait->mAddr.sin_port); + std::cerr << "Ext Addr: " << sockaddr_storage_tostring(ait->mAddr); std::cerr << std::endl; #endif peerConnectAddress pca; @@ -1918,8 +1921,8 @@ void p3LinkMgrIMPL::locked_ConnectAttempt_HistoricalAddresses(peerConnectState pca.delay = P3CONNMGR_TCP_DEFAULT_DELAY; pca.ts = time(NULL); pca.period = P3CONNMGR_TCP_DEFAULT_PERIOD; - sockaddr_clear(&(pca.proxyaddr)); - sockaddr_clear(&(pca.srcaddr)); + sockaddr_storage_clear(pca.proxyaddr); + sockaddr_storage_clear(pca.srcaddr); pca.bandwidth = 0; addAddressIfUnique(peer->connAddrs, pca, false); @@ -1931,7 +1934,7 @@ void p3LinkMgrIMPL::locked_ConnectAttempt_HistoricalAddresses(peerConnectState void p3LinkMgrIMPL::locked_ConnectAttempt_AddDynDNS(peerConnectState *peer, std::string dyndns, uint16_t port) { /* try dyndns address too */ - struct in_addr addr; + struct sockaddr_storage addr; if (!dyndns.empty() && port) { #ifdef LINKMGR_DEBUG @@ -1942,26 +1945,25 @@ void p3LinkMgrIMPL::locked_ConnectAttempt_AddDynDNS(peerConnectState *peer, std #ifdef LINKMGR_DEBUG std::cerr << "p3LinkMgrIMPL::locked_ConnectAttempt_AddDynDNS() "; std::cerr << "Adding tcp connection attempt: "; - std::cerr << "DynDNS Addr: " << rs_inet_ntoa(addr); - std::cerr << ":" << ntohs(port); + std::cerr << "DynDNS Addr: " << sockaddr_storage_iptostring(addr); + std::cerr << ":" << port; std::cerr << std::endl; #endif peerConnectAddress pca; - pca.addr.sin_family = AF_INET; - pca.addr.sin_addr.s_addr = addr.s_addr; - pca.addr.sin_port = htons(port); + sockaddr_storage_copyip(pca.addr, addr); + sockaddr_storage_setport(pca.addr, port); pca.type = RS_NET_CONN_TCP_EXTERNAL; //for the delay, we add a random time and some more time when the friend list is big pca.delay = P3CONNMGR_TCP_DEFAULT_DELAY; pca.ts = time(NULL); pca.period = P3CONNMGR_TCP_DEFAULT_PERIOD; - sockaddr_clear(&(pca.proxyaddr)); - sockaddr_clear(&(pca.srcaddr)); + sockaddr_storage_clear(pca.proxyaddr); + sockaddr_storage_clear(pca.srcaddr); pca.bandwidth = 0; /* check address validity */ - if (locked_CheckPotentialAddr(&(pca.addr), 0)) + if (locked_CheckPotentialAddr(pca.addr, 0)) { addAddressIfUnique(peer->connAddrs, pca, true); } @@ -1984,15 +1986,13 @@ void p3LinkMgrIMPL::locked_ConnectAttempt_AddDynDNS(peerConnectState *peer, std } -void p3LinkMgrIMPL::locked_ConnectAttempt_ProxyAddress(peerConnectState *peer, struct sockaddr_in *proxy_addr, const std::string &domain_addr, uint16_t domain_port) +void p3LinkMgrIMPL::locked_ConnectAttempt_ProxyAddress(peerConnectState *peer, const struct sockaddr_storage &proxy_addr, const std::string &domain_addr, uint16_t domain_port) { #ifdef LINKMGR_DEBUG std::cerr << "p3LinkMgrIMPL::locked_ConnectAttempt_ProxyAddress() trying address: " << domain_addr << ":" << domain_port << std::endl; #endif peerConnectAddress pca; - pca.addr.sin_family = AF_INET; - pca.addr.sin_addr.s_addr = proxy_addr->sin_addr.s_addr; - pca.addr.sin_port = proxy_addr->sin_port; + pca.addr = proxy_addr; pca.type = RS_NET_CONN_TCP_HIDDEN; @@ -2001,15 +2001,15 @@ void p3LinkMgrIMPL::locked_ConnectAttempt_ProxyAddress(peerConnectState *peer, pca.ts = time(NULL); pca.period = P3CONNMGR_TCP_DEFAULT_PERIOD; - sockaddr_clear(&(pca.proxyaddr)); - sockaddr_clear(&(pca.srcaddr)); + sockaddr_storage_clear(pca.proxyaddr); + sockaddr_storage_clear(pca.srcaddr); pca.bandwidth = 0; pca.domain_addr = domain_addr; pca.domain_port = domain_port; /* check address validity */ - if (locked_CheckPotentialAddr(&(pca.addr), 0)) + if (locked_CheckPotentialAddr(pca.addr, 0)) { addAddressIfUnique(peer->connAddrs, pca, true); } @@ -2022,15 +2022,14 @@ bool p3LinkMgrIMPL::addAddressIfUnique(std::list &addrList, * in the list */ #ifdef LINKMGR_DEBUG - std::cerr << "p3LinkMgrIMPL::addAddressIfUnique() Checking Address: " << rs_inet_ntoa(pca.addr.sin_addr); + std::cerr << "p3LinkMgrIMPL::addAddressIfUnique() Checking Address: " << sockaddr_storage_iptostring(pca.addr); std::cerr << std::endl; #endif std::list::iterator it; for(it = addrList.begin(); it != addrList.end(); it++) { - if ((pca.addr.sin_addr.s_addr == it->addr.sin_addr.s_addr) && - (pca.addr.sin_port == it->addr.sin_port) && + if (sockaddr_storage_same(pca.addr, it->addr) && (pca.type == it->type)) { #ifdef LINKMGR_DEBUG diff --git a/libretroshare/src/pqi/p3linkmgr.h b/libretroshare/src/pqi/p3linkmgr.h index c5918fa2d..a4513ea83 100644 --- a/libretroshare/src/pqi/p3linkmgr.h +++ b/libretroshare/src/pqi/p3linkmgr.h @@ -70,7 +70,7 @@ class peerConnectAddress public: peerConnectAddress(); /* init */ - struct sockaddr_in addr; + struct sockaddr_storage addr; uint32_t delay; /* to stop simultaneous connects */ uint32_t period; /* UDP only */ uint32_t type; @@ -78,8 +78,8 @@ class peerConnectAddress time_t ts; // Extra Parameters for Relay connections. - struct sockaddr_in proxyaddr; - struct sockaddr_in srcaddr; + struct sockaddr_storage proxyaddr; + struct sockaddr_storage srcaddr; uint32_t bandwidth; // Extra Parameters for Proxy/Hidden connection. @@ -162,19 +162,19 @@ virtual void addMonitor(pqiMonitor *mon) = 0; virtual void removeMonitor(pqiMonitor *mon) = 0; /****************** Connections *******************/ -virtual bool connectAttempt(const std::string &id, struct sockaddr_in &raddr, - struct sockaddr_in &proxyaddr, struct sockaddr_in &srcaddr, +virtual bool connectAttempt(const std::string &id, struct sockaddr_storage &raddr, + struct sockaddr_storage &proxyaddr, struct sockaddr_storage &srcaddr, uint32_t &delay, uint32_t &period, uint32_t &type, uint32_t &flags, uint32_t &bandwidth, std::string &domain_addr, uint16_t &domain_port) = 0; -virtual bool connectResult(const std::string &id, bool success, uint32_t flags, struct sockaddr_in remote_peer_address) = 0; +virtual bool connectResult(const std::string &id, bool success, uint32_t flags, const struct sockaddr_storage &remote_peer_address) = 0; virtual bool retryConnect(const std::string &id) = 0; -virtual void notifyDeniedConnection(const std::string& gpgid,const std::string& sslid,const std::string& sslcn,const struct sockaddr_in &addr, bool incoming) = 0; +virtual void notifyDeniedConnection(const std::string& gpgid,const std::string& sslid,const std::string& sslcn,const struct sockaddr_storage &addr, bool incoming) = 0; /* Network Addresses */ -virtual bool setLocalAddress(struct sockaddr_in addr) = 0; -virtual struct sockaddr_in getLocalAddress() = 0; +virtual bool setLocalAddress(const struct sockaddr_storage &addr) = 0; +virtual bool getLocalAddress(struct sockaddr_storage &addr) = 0; /************* DEPRECIATED FUNCTIONS (TO REMOVE) ********/ @@ -188,8 +188,8 @@ virtual int addFriend(const std::string &ssl_id, bool isVisible) = 0; // THESE MUSTn't BE specfied HERE - as overloaded from pqiConnectCb. //virtual void peerStatus(std::string id, const pqiIpAddrSet &addrs, // uint32_t type, uint32_t flags, uint32_t source) = 0; -//virtual void peerConnectRequest(std::string id, struct sockaddr_in raddr, -// struct sockaddr_in proxyaddr, struct sockaddr_in srcaddr, +//virtual void peerConnectRequest(std::string id, const struct sockaddr_storage &raddr, +// const struct sockaddr_storage &proxyaddr, const struct sockaddr_storage &srcaddr, // uint32_t source, uint32_t flags, uint32_t delay, uint32_t bandwidth) = 0; /****************************************************************************/ @@ -220,25 +220,25 @@ virtual void addMonitor(pqiMonitor *mon); virtual void removeMonitor(pqiMonitor *mon); /****************** Connections *******************/ -virtual bool connectAttempt(const std::string &id, struct sockaddr_in &raddr, - struct sockaddr_in &proxyaddr, struct sockaddr_in &srcaddr, +virtual bool connectAttempt(const std::string &id, struct sockaddr_storage &raddr, + struct sockaddr_storage &proxyaddr, struct sockaddr_storage &srcaddr, uint32_t &delay, uint32_t &period, uint32_t &type, uint32_t &flags, uint32_t &bandwidth, std::string &domain_addr, uint16_t &domain_port); -virtual bool connectResult(const std::string &id, bool success, uint32_t flags, struct sockaddr_in remote_peer_address); +virtual bool connectResult(const std::string &id, bool success, uint32_t flags, const struct sockaddr_storage &remote_peer_address); virtual bool retryConnect(const std::string &id); -virtual void notifyDeniedConnection(const std::string& gpgid,const std::string& sslid,const std::string& sslcn,const struct sockaddr_in &addr, bool incoming); +virtual void notifyDeniedConnection(const std::string& gpgid,const std::string& sslid,const std::string& sslcn,const struct sockaddr_storage &addr, bool incoming); /* Network Addresses */ -virtual bool setLocalAddress(struct sockaddr_in addr); -virtual struct sockaddr_in getLocalAddress(); +virtual bool setLocalAddress(const struct sockaddr_storage &addr); +virtual bool getLocalAddress(struct sockaddr_storage &addr); /******* overloaded from pqiConnectCb *************/ virtual void peerStatus(std::string id, const pqiIpAddrSet &addrs, uint32_t type, uint32_t flags, uint32_t source); -virtual void peerConnectRequest(std::string id, struct sockaddr_in raddr, - struct sockaddr_in proxyaddr, struct sockaddr_in srcaddr, +virtual void peerConnectRequest(std::string id, const struct sockaddr_storage &raddr, + const struct sockaddr_storage &proxyaddr, const struct sockaddr_storage &srcaddr, uint32_t source, uint32_t flags, uint32_t delay, uint32_t bandwidth); @@ -280,23 +280,23 @@ void statusTick(); void tickMonitors(); /* connect attempts UDP */ -bool tryConnectUDP(const std::string &id, struct sockaddr_in &rUdpAddr, - struct sockaddr_in &proxyaddr, struct sockaddr_in &srcaddr, +bool tryConnectUDP(const std::string &id, const struct sockaddr_storage &rUdpAddr, + const struct sockaddr_storage &proxyaddr, const struct sockaddr_storage &srcaddr, uint32_t flags, uint32_t delay, uint32_t bandwidth); /* connect attempts TCP */ bool retryConnectTCP(const std::string &id); -void locked_ConnectAttempt_SpecificAddress(peerConnectState *peer, struct sockaddr_in *remoteAddr); -void locked_ConnectAttempt_CurrentAddresses(peerConnectState *peer, struct sockaddr_in *localAddr, struct sockaddr_in *serverAddr); +void locked_ConnectAttempt_SpecificAddress(peerConnectState *peer, const struct sockaddr_storage &remoteAddr); +void locked_ConnectAttempt_CurrentAddresses(peerConnectState *peer, const struct sockaddr_storage &localAddr, const struct sockaddr_storage &serverAddr); void locked_ConnectAttempt_HistoricalAddresses(peerConnectState *peer, const pqiIpAddrSet &ipAddrs); void locked_ConnectAttempt_AddDynDNS(peerConnectState *peer, std::string dyndns, uint16_t dynPort); void locked_ConnectAttempt_AddTunnel(peerConnectState *peer); -void locked_ConnectAttempt_ProxyAddress(peerConnectState *peer, struct sockaddr_in *proxy_addr, const std::string &domain_addr, uint16_t domain_port); +void locked_ConnectAttempt_ProxyAddress(peerConnectState *peer, const struct sockaddr_storage &proxy_addr, const std::string &domain_addr, uint16_t domain_port); bool locked_ConnectAttempt_Complete(peerConnectState *peer); -bool locked_CheckPotentialAddr(const struct sockaddr_in *addr, time_t age); +bool locked_CheckPotentialAddr(const struct sockaddr_storage &addr, time_t age); bool addAddressIfUnique(std::list &addrList, peerConnectAddress &pca, bool pushFront); @@ -314,7 +314,7 @@ private: bool mStatusChanged; - struct sockaddr_in mLocalAddress; + struct sockaddr_storage mLocalAddress; std::list clients; @@ -333,7 +333,7 @@ private: uint32_t lastGroupId; /* relatively static list of banned ip addresses */ - std::list mBannedIpList; + std::list mBannedIpList; }; #endif // MRK_PQI_LINK_MANAGER_HEADER diff --git a/libretroshare/src/pqi/p3netmgr.cc b/libretroshare/src/pqi/p3netmgr.cc index 554c535a5..382c0f417 100644 --- a/libretroshare/src/pqi/p3netmgr.cc +++ b/libretroshare/src/pqi/p3netmgr.cc @@ -74,6 +74,11 @@ const uint32_t MIN_TIME_BETWEEN_NET_RESET = 5; * #define NETMGR_DEBUG_STATEBOX 1 ***/ +#define NETMGR_DEBUG 1 +#define NETMGR_DEBUG_RESET 1 +#define NETMGR_DEBUG_TICK 1 +#define NETMGR_DEBUG_STATEBOX 1 + pqiNetStatus::pqiNetStatus() :mLocalAddrOk(false), mExtAddrOk(false), mExtAddrStableOk(false), mUpnpOk(false), mDhtOk(false), mResetReq(false) @@ -81,8 +86,8 @@ pqiNetStatus::pqiNetStatus() mDhtNetworkSize = 0; mDhtRsNetworkSize = 0; - sockaddr_clear(&mLocalAddr); - sockaddr_clear(&mExtAddr); + sockaddr_storage_clear(mLocalAddr); + sockaddr_storage_clear(mExtAddr); return; } @@ -101,8 +106,8 @@ void pqiNetStatus::print(std::ostream &out) out << std::endl; out << "mDhtNetworkSize: " << mDhtNetworkSize << " mDhtRsNetworkSize: " << mDhtRsNetworkSize; out << std::endl; - out << "mLocalAddr: " << rs_inet_ntoa(mLocalAddr.sin_addr) << ":" << ntohs(mLocalAddr.sin_port) << " "; - out << "mExtAddr: " << rs_inet_ntoa(mExtAddr.sin_addr) << ":" << ntohs(mExtAddr.sin_port) << " "; + out << "mLocalAddr: " << sockaddr_storage_tostring(mLocalAddr) << " "; + out << "mExtAddr: " << sockaddr_storage_tostring(mExtAddr) << " "; out << " NetOk: " << NetOk(); out << std::endl; } @@ -128,12 +133,8 @@ p3NetMgrIMPL::p3NetMgrIMPL() mLastSlowTickTime = 0; mOldNatType = RSNET_NATTYPE_UNKNOWN; mOldNatHole = RSNET_NATHOLE_UNKNOWN; - mLocalAddr.sin_port = 0; - mLocalAddr.sin_addr.s_addr = 0; - mLocalAddr.sin_family = AF_INET ; - mExtAddr.sin_port = 0; - mExtAddr.sin_addr.s_addr = 0; - mExtAddr.sin_family = AF_INET ; + sockaddr_storage_clear(mLocalAddr); + sockaddr_storage_clear(mExtAddr); mVisState = 0 ; } @@ -269,7 +270,7 @@ void p3NetMgrIMPL::netReset() RsStackMutex stack(mNetMtx); /****** STACK LOCK MUTEX *******/ - struct sockaddr_in iaddr = mLocalAddr; + struct sockaddr_storage iaddr = mLocalAddr; #ifdef NETMGR_DEBUG_RESET std::cerr << "p3NetMgrIMPL::netReset() resetting listeners" << std::endl; @@ -582,8 +583,8 @@ void p3NetMgrIMPL::netUpnpInit() /* get the ports from the configuration */ mNetStatus = RS_NET_UPNP_SETUP; - iport = ntohs(mLocalAddr.sin_port); - eport = ntohs(mExtAddr.sin_port); + iport = sockaddr_storage_port(mLocalAddr); + eport = sockaddr_storage_port(mExtAddr); if ((eport < 1000) || (eport > 30000)) { eport = iport; @@ -608,7 +609,7 @@ void p3NetMgrIMPL::netUpnpCheck() mNetMtx.unlock(); /* UNLOCK MUTEX */ - struct sockaddr_in extAddr; + struct sockaddr_storage extAddr; int upnpState = netAssistFirewallActive(); if (((upnpState == 0) && (delta > (time_t)MAX_UPNP_INIT)) || @@ -640,12 +641,11 @@ void p3NetMgrIMPL::netUpnpCheck() * we now have external upnp address. Golden! * don't set netOk flag until have seen some traffic. */ - if (isValidNet(&(extAddr.sin_addr))) + if (sockaddr_storage_isValidNet(extAddr)) { #if defined(NETMGR_DEBUG_TICK) || defined(NETMGR_DEBUG_RESET) std::cerr << "p3NetMgrIMPL::netUpnpCheck() "; - std::cerr << "UpnpAddr: " << rs_inet_ntoa(extAddr.sin_addr); - std::cerr << ":" << ntohs(extAddr.sin_port); + std::cerr << "UpnpAddr: " << sockaddr_storage_tostring(extAddr); std::cerr << std::endl; #endif mNetFlags.mUpnpOk = true; @@ -680,7 +680,7 @@ void p3NetMgrIMPL::netExtCheck() { RsStackMutex stack(mNetMtx); /****** STACK LOCK MUTEX *******/ bool isStable = false; - struct sockaddr_in tmpip ; + struct sockaddr_storage tmpip ; /* check for External Address */ /* in order of importance */ @@ -697,7 +697,7 @@ void p3NetMgrIMPL::netExtCheck() #if defined(NETMGR_DEBUG_TICK) || defined(NETMGR_DEBUG_RESET) std::cerr << "p3NetMgrIMPL::netExtCheck() Ext supplied from netAssistExternalAddress()" << std::endl; #endif - if (isValidNet(&(tmpip.sin_addr))) + if (sockaddr_storage_isValidNet(tmpip)) { // must be stable??? isStable = true; @@ -722,8 +722,8 @@ void p3NetMgrIMPL::netExtCheck() std::cerr << "p3NetMgrIMPL::netExtCheck() Ext Not Ok, Checking DhtStunner" << std::endl; #endif uint8_t isstable = 0; - struct sockaddr_in tmpaddr; - sockaddr_clear(&tmpaddr); + struct sockaddr_storage tmpaddr; + sockaddr_storage_clear(tmpaddr); if (mDhtStunner) { @@ -738,7 +738,7 @@ void p3NetMgrIMPL::netExtCheck() #ifdef NETMGR_DEBUG_STATEBOX std::cerr << "p3NetMgrIMPL::netExtCheck() From DhtStunner: "; - std::cerr << rs_inet_ntoa(tmpaddr.sin_addr) << ":" << htons(tmpaddr.sin_port); + std::cerr << sockaddr_storage_tostring(tmpaddr); std::cerr << " Stable: " << (uint32_t) isstable; std::cerr << std::endl; #endif @@ -755,18 +755,18 @@ void p3NetMgrIMPL::netExtCheck() #if defined(NETMGR_DEBUG_TICK) || defined(NETMGR_DEBUG_RESET) std::cerr << "p3NetMgrIMPL::netExtCheck() checking ExtAddrFinder" << std::endl; #endif - bool extFinderOk = mExtAddrFinder->hasValidIP(&(tmpip.sin_addr)); + bool extFinderOk = mExtAddrFinder->hasValidIP(tmpip); if (extFinderOk) { #if defined(NETMGR_DEBUG_TICK) || defined(NETMGR_DEBUG_RESET) std::cerr << "p3NetMgrIMPL::netExtCheck() Ext supplied by ExtAddrFinder" << std::endl; #endif /* best guess at port */ - tmpip.sin_port = mNetFlags.mLocalAddr.sin_port; + sockaddr_storage_setport(tmpip, sockaddr_storage_port(mLocalAddr)); + #if defined(NETMGR_DEBUG_TICK) || defined(NETMGR_DEBUG_RESET) std::cerr << "p3NetMgrIMPL::netExtCheck() "; - std::cerr << "ExtAddr: " << rs_inet_ntoa(tmpip.sin_addr); - std::cerr << ":" << ntohs(tmpip.sin_port); + std::cerr << "ExtAddr: " << sockaddr_storage_tostring(tmpip); std::cerr << std::endl; #endif @@ -790,8 +790,7 @@ void p3NetMgrIMPL::netExtCheck() #if defined(NETMGR_DEBUG_TICK) || defined(NETMGR_DEBUG_RESET) std::cerr << "p3NetMgrIMPL::netExtCheck() "; - std::cerr << "ExtAddr: " << rs_inet_ntoa(mNetFlags.mExtAddr.sin_addr); - std::cerr << ":" << ntohs(mNetFlags.mExtAddr.sin_port); + std::cerr << "ExtAddr: " << sockaddr_storage_tostring(mNetFlags.mExtAddr); std::cerr << std::endl; #endif //update ip address list @@ -910,19 +909,19 @@ bool p3NetMgrIMPL::checkNetAddress() bool addrChanged = false; bool validAddr = false; - struct in_addr prefAddr; - struct sockaddr_in oldAddr; + struct sockaddr_storage prefAddr; + struct sockaddr_storage oldAddr; if (mNetMode & RS_NET_MODE_TRY_LOOPBACK) { std::cerr << "p3NetMgrIMPL::checkNetAddress() LOOPBACK ... forcing to 127.0.0.1"; std::cerr << std::endl; - inet_aton("127.0.0.1", &prefAddr); + sockaddr_storage_ipv4_aton(prefAddr, "127.0.0.1"); validAddr = true; } else { - validAddr = getPreferredInterface(mLocalAddr.sin_addr, prefAddr); + validAddr = getPreferredInterface(mLocalAddr, prefAddr); } @@ -945,15 +944,14 @@ bool p3NetMgrIMPL::checkNetAddress() RsStackMutex stack(mNetMtx); /****** STACK LOCK MUTEX *******/ oldAddr = mLocalAddr; - addrChanged = (prefAddr.s_addr != mLocalAddr.sin_addr.s_addr); + addrChanged = !sockaddr_storage_sameip(prefAddr, mLocalAddr); #ifdef NETMGR_DEBUG_TICK std::cerr << "p3NetMgrIMPL::checkNetAddress()"; std::cerr << std::endl; - std::cerr << "Current Local: " << rs_inet_ntoa(mLocalAddr.sin_addr); - std::cerr << ":" << ntohs(mLocalAddr.sin_port); + std::cerr << "Current Local: " << sockaddr_storage_tostring(mLocalAddr); std::cerr << std::endl; - std::cerr << "Current Preferred: " << rs_inet_ntoa(prefAddr); + std::cerr << "Current Preferred: " << sockaddr_storage_iptostring(prefAddr); std::cerr << std::endl; #endif @@ -962,19 +960,18 @@ bool p3NetMgrIMPL::checkNetAddress() { std::cerr << "p3NetMgrIMPL::checkNetAddress() Address Changed!"; std::cerr << std::endl; - std::cerr << "Current Local: " << rs_inet_ntoa(mLocalAddr.sin_addr); - std::cerr << ":" << ntohs(mLocalAddr.sin_port); + std::cerr << "Current Local: " << sockaddr_storage_tostring(mLocalAddr); std::cerr << std::endl; - std::cerr << "Current Preferred: " << rs_inet_ntoa(prefAddr); + std::cerr << "Current Preferred: " << sockaddr_storage_iptostring(prefAddr); std::cerr << std::endl; } #endif // update address. - mLocalAddr.sin_addr = prefAddr; + sockaddr_storage_copyip(mLocalAddr, prefAddr); mNetFlags.mLocalAddr = mLocalAddr; - if(isLoopbackNet(&(mLocalAddr.sin_addr))) + if(sockaddr_storage_isLoopbackNet(mLocalAddr)) { #ifdef NETMGR_DEBUG std::cerr << "p3NetMgrIMPL::checkNetAddress() laddr: Loopback" << std::endl; @@ -982,7 +979,7 @@ bool p3NetMgrIMPL::checkNetAddress() mNetFlags.mLocalAddrOk = false; mNetStatus = RS_NET_LOOPBACK; } - else if (!isValidNet(&mLocalAddr.sin_addr)) + else if (!sockaddr_storage_isValidNet(mLocalAddr)) { #ifdef NETMGR_DEBUG std::cerr << "p3NetMgrIMPL::checkNetAddress() laddr: invalid" << std::endl; @@ -998,7 +995,7 @@ bool p3NetMgrIMPL::checkNetAddress() } - int port = ntohs(mLocalAddr.sin_port); + int port = sockaddr_storage_port(mLocalAddr); if ((port < PQI_MIN_PORT) || (port > PQI_MAX_PORT)) { #ifdef NETMGR_DEBUG @@ -1008,8 +1005,9 @@ bool p3NetMgrIMPL::checkNetAddress() // same, but appear random from peer to peer. // Random port avoids clashes, improves anonymity. // - - mLocalAddr.sin_port = htons(PQI_MIN_PORT + (RSRandom::random_u32() % (PQI_MAX_PORT - PQI_MIN_PORT))); + + int new_port = htons(PQI_MIN_PORT + (RSRandom::random_u32() % (PQI_MAX_PORT - PQI_MIN_PORT))); + sockaddr_storage_setport(mLocalAddr, new_port); addrChanged = true; } @@ -1018,18 +1016,17 @@ bool p3NetMgrIMPL::checkNetAddress() * are the same (modify server)... this mismatch can * occur when the local port is changed.... */ - if (mLocalAddr.sin_addr.s_addr == mExtAddr.sin_addr.s_addr) + if (sockaddr_storage_sameip(mLocalAddr, mExtAddr)) { - mExtAddr.sin_port = mLocalAddr.sin_port; + sockaddr_storage_setport(mExtAddr, sockaddr_storage_port(mLocalAddr)); } // ensure that address family is set, otherwise windows Barfs. - mLocalAddr.sin_family = AF_INET; - mExtAddr.sin_family = AF_INET; + //mLocalAddr.sin_family = AF_INET; + //mExtAddr.sin_family = AF_INET; #ifdef NETMGR_DEBUG_TICK - std::cerr << "p3NetMgrIMPL::checkNetAddress() Final Local Address: " << rs_inet_ntoa(mLocalAddr.sin_addr); - std::cerr << ":" << ntohs(mLocalAddr.sin_port) << std::endl; + std::cerr << "p3NetMgrIMPL::checkNetAddress() Final Local Address: " << sockaddr_storage_tostring(mLocalAddr); std::cerr << std::endl; #endif @@ -1068,13 +1065,12 @@ void p3NetMgrIMPL::addNetListener(pqiNetListener *listener) -bool p3NetMgrIMPL::setLocalAddress(struct sockaddr_in addr) +bool p3NetMgrIMPL::setLocalAddress(const struct sockaddr_storage &addr) { bool changed = false; { RsStackMutex stack(mNetMtx); /****** STACK LOCK MUTEX *******/ - if ((mLocalAddr.sin_addr.s_addr != addr.sin_addr.s_addr) || - (mLocalAddr.sin_port != addr.sin_port)) + if (sockaddr_storage_same(mLocalAddr, addr)) { changed = true; } @@ -1093,13 +1089,12 @@ bool p3NetMgrIMPL::setLocalAddress(struct sockaddr_in addr) return true; } -bool p3NetMgrIMPL::setExtAddress(struct sockaddr_in addr) +bool p3NetMgrIMPL::setExtAddress(const struct sockaddr_storage &addr) { bool changed = false; { RsStackMutex stack(mNetMtx); /****** STACK LOCK MUTEX *******/ - if ((mExtAddr.sin_addr.s_addr != addr.sin_addr.s_addr) || - (mExtAddr.sin_port != addr.sin_port)) + if (sockaddr_storage_same(mExtAddr, addr)) { changed = true; } @@ -1250,7 +1245,7 @@ bool p3NetMgrIMPL::netAssistFirewallPorts(uint16_t iport, uint16_t eport) } -bool p3NetMgrIMPL::netAssistExtAddress(struct sockaddr_in &extAddr) +bool p3NetMgrIMPL::netAssistExtAddress(struct sockaddr_storage &extAddr) { std::map::iterator it; for(it = mFwAgents.begin(); it != mFwAgents.end(); it++) @@ -1398,7 +1393,7 @@ bool p3NetMgrIMPL::netAssistFriend(const std::string &id, bool on) } -bool p3NetMgrIMPL::netAssistKnownPeer(const std::string &id, const struct sockaddr_in &addr, uint32_t flags) +bool p3NetMgrIMPL::netAssistKnownPeer(const std::string &id, const struct sockaddr_storage &addr, uint32_t flags) { std::map::iterator it; @@ -1414,12 +1409,12 @@ bool p3NetMgrIMPL::netAssistKnownPeer(const std::string &id, const struct sockad return true; } -bool p3NetMgrIMPL::netAssistBadPeer(const struct sockaddr_in &addr, uint32_t reason, uint32_t flags, uint32_t age) +bool p3NetMgrIMPL::netAssistBadPeer(const struct sockaddr_storage &addr, uint32_t reason, uint32_t flags, uint32_t age) { std::map::iterator it; #ifdef NETMGR_DEBUG - std::cerr << "p3NetMgrIMPL::netAssistBadPeer(" << rs_inet_ntoa(addr.sin_addr) << ")"; + std::cerr << "p3NetMgrIMPL::netAssistBadPeer(" << sockaddr_storage_iptostring(addr) << ")"; std::cerr << std::endl; #endif @@ -1454,7 +1449,7 @@ bool p3NetMgrIMPL::netAssistStatusUpdate(const std::string &id, int state) std::map::iterator it; #ifdef NETMGR_DEBUG - std::cerr << "p3NetMgrIMPL::netAssistFriend(" << id << ", " << on << ")"; + std::cerr << "p3NetMgrIMPL::netAssistStatusUpdate(" << id << ", " << state << ")"; std::cerr << std::endl; #endif @@ -1466,8 +1461,8 @@ bool p3NetMgrIMPL::netAssistStatusUpdate(const std::string &id, int state) } -bool p3NetMgrIMPL::netAssistSetAddress( struct sockaddr_in &/*laddr*/, - struct sockaddr_in &/*eaddr*/, +bool p3NetMgrIMPL::netAssistSetAddress( const struct sockaddr_storage & /*laddr*/, + const struct sockaddr_storage & /*eaddr*/, uint32_t /*mode*/) { #if 0 @@ -1621,8 +1616,8 @@ void p3NetMgrIMPL::updateNetStateBox_temporal() #endif uint8_t isstable = 0; - struct sockaddr_in tmpaddr; - sockaddr_clear(&tmpaddr); + struct sockaddr_storage tmpaddr; + sockaddr_storage_clear(tmpaddr); if (mDhtStunner) { @@ -1631,11 +1626,11 @@ void p3NetMgrIMPL::updateNetStateBox_temporal() if (mDhtStunner->getExternalAddr(tmpaddr, isstable)) { RsStackMutex stack(mNetMtx); /****** STACK LOCK MUTEX *******/ - mNetStateBox.setAddressStunDht(&tmpaddr, isstable); + mNetStateBox.setAddressStunDht(tmpaddr, isstable); #ifdef NETMGR_DEBUG_STATEBOX std::cerr << "p3NetMgrIMPL::updateNetStateBox_temporal() DhtStunner: "; - std::cerr << rs_inet_ntoa(tmpaddr.sin_addr) << ":" << htons(tmpaddr.sin_port); + std::cerr << sockaddr_storage_tostring(tmpaddr); std::cerr << " Stable: " << (uint32_t) isstable; std::cerr << std::endl; #endif @@ -1650,11 +1645,11 @@ void p3NetMgrIMPL::updateNetStateBox_temporal() if (mProxyStunner->getExternalAddr(tmpaddr, isstable)) { RsStackMutex stack(mNetMtx); /****** STACK LOCK MUTEX *******/ - mNetStateBox.setAddressStunProxy(&tmpaddr, isstable); + mNetStateBox.setAddressStunProxy(tmpaddr, isstable); #ifdef NETMGR_DEBUG_STATEBOX std::cerr << "p3NetMgrIMPL::updateNetStateBox_temporal() ProxyStunner: "; - std::cerr << rs_inet_ntoa(tmpaddr.sin_addr) << ":" << htons(tmpaddr.sin_port); + std::cerr << sockaddr_storage_tostring(tmpaddr); std::cerr << " Stable: " << (uint32_t) isstable; std::cerr << std::endl; #endif @@ -1826,7 +1821,7 @@ void p3NetMgrIMPL::updateNetStateBox_startup() RsStackMutex stack(mNetMtx); /****** STACK LOCK MUTEX *******/ /* fill in the data */ - struct sockaddr_in tmpip; + struct sockaddr_storage tmpip; /* net Assist */ if (netAssistExtAddress(tmpip)) @@ -1838,19 +1833,18 @@ void p3NetMgrIMPL::updateNetStateBox_startup() std::cerr << std::endl; #endif - if (isValidNet(&(tmpip.sin_addr))) + if (sockaddr_storage_isValidNet(tmpip)) { #ifdef NETMGR_DEBUG_STATEBOX std::cerr << "p3NetMgrIMPL::updateNetStateBox_startup() "; - std::cerr << "netAssist Returned: " << rs_inet_ntoa(tmpip.sin_addr); - std::cerr << ":" << ntohs(tmpip.sin_port); + std::cerr << "netAssist Returned: " << sockaddr_storage_tostring(tmpip); std::cerr << std::endl; #endif - mNetStateBox.setAddressUPnP(true, &tmpip); + mNetStateBox.setAddressUPnP(true, tmpip); } else { - mNetStateBox.setAddressUPnP(false, &tmpip); + mNetStateBox.setAddressUPnP(false, tmpip); #ifdef NETMGR_DEBUG_STATEBOX std::cerr << "p3NetMgrIMPL::updateNetStateBox_startup() "; std::cerr << "ERROR Bad Address supplied from netAssistExternalAddress()"; @@ -1865,30 +1859,30 @@ void p3NetMgrIMPL::updateNetStateBox_startup() std::cerr << " netAssistExtAddress() is not active"; std::cerr << std::endl; #endif - mNetStateBox.setAddressUPnP(false, &tmpip); + mNetStateBox.setAddressUPnP(false, tmpip); } /* ExtAddrFinder */ if (mUseExtAddrFinder) { - bool extFinderOk = mExtAddrFinder->hasValidIP(&(tmpip.sin_addr)); + bool extFinderOk = mExtAddrFinder->hasValidIP(tmpip); if (extFinderOk) { /* best guess at port */ - tmpip.sin_port = mNetFlags.mLocalAddr.sin_port; + sockaddr_storage_setport(tmpip, sockaddr_storage_port(mNetFlags.mLocalAddr)); #ifdef NETMGR_DEBUG_STATEBOX std::cerr << "p3NetMgrIMPL::updateNetStateBox_startup() "; - std::cerr << "ExtAddrFinder Returned: " << rs_inet_ntoa(tmpip.sin_addr); + std::cerr << "ExtAddrFinder Returned: " << sockaddr_storage_iptostring(tmpip); std::cerr << std::endl; #endif - mNetStateBox.setAddressWebIP(true, &tmpip); + mNetStateBox.setAddressWebIP(true, tmpip); } else { - mNetStateBox.setAddressWebIP(false, &tmpip); + mNetStateBox.setAddressWebIP(false, tmpip); #ifdef NETMGR_DEBUG_STATEBOX std::cerr << "p3NetMgrIMPL::updateNetStateBox_startup() "; std::cerr << " ExtAddrFinder hasn't found an address yet"; @@ -1903,7 +1897,7 @@ void p3NetMgrIMPL::updateNetStateBox_startup() std::cerr << " ExtAddrFinder is not active"; std::cerr << std::endl; #endif - mNetStateBox.setAddressWebIP(false, &tmpip); + mNetStateBox.setAddressWebIP(false, tmpip); } diff --git a/libretroshare/src/pqi/p3netmgr.h b/libretroshare/src/pqi/p3netmgr.h index 823bd64b7..b8ca67907 100644 --- a/libretroshare/src/pqi/p3netmgr.h +++ b/libretroshare/src/pqi/p3netmgr.h @@ -68,8 +68,8 @@ class pqiNetStatus uint32_t mDhtNetworkSize; uint32_t mDhtRsNetworkSize; - struct sockaddr_in mLocalAddr; // percieved ext addr. - struct sockaddr_in mExtAddr; // percieved ext addr. + struct sockaddr_storage mLocalAddr; // percieved ext addr. + struct sockaddr_storage mExtAddr; // percieved ext addr. bool mResetReq; // Not Used yet!. @@ -119,8 +119,8 @@ virtual bool setVisState(uint32_t visState) = 0; // Switch DHT On/Off. virtual bool netAssistFriend(const std::string &id, bool on) = 0; -virtual bool netAssistKnownPeer(const std::string &id, const struct sockaddr_in &addr, uint32_t flags) = 0; -virtual bool netAssistBadPeer(const struct sockaddr_in &addr, uint32_t reason, uint32_t flags, uint32_t age) = 0; +virtual bool netAssistKnownPeer(const std::string &id, const struct sockaddr_storage &addr, uint32_t flags) = 0; +virtual bool netAssistBadPeer(const struct sockaddr_storage &addr, uint32_t reason, uint32_t flags, uint32_t age) = 0; virtual bool netAssistStatusUpdate(const std::string &id, int mode) = 0; /* Get Network State */ @@ -175,8 +175,8 @@ virtual bool setVisState(uint32_t visState); // Switch DHT On/Off. virtual bool netAssistFriend(const std::string &id, bool on); -virtual bool netAssistKnownPeer(const std::string &id, const struct sockaddr_in &addr, uint32_t flags); -virtual bool netAssistBadPeer(const struct sockaddr_in &addr, uint32_t reason, uint32_t flags, uint32_t age); +virtual bool netAssistKnownPeer(const std::string &id, const struct sockaddr_storage &addr, uint32_t flags); +virtual bool netAssistBadPeer(const struct sockaddr_storage &addr, uint32_t reason, uint32_t flags, uint32_t age); virtual bool netAssistStatusUpdate(const std::string &id, int mode); /* Get Network State */ @@ -214,8 +214,8 @@ void setAddrAssist(pqiAddrAssist *dhtStun, pqiAddrAssist *proxyStun); void tick(); // THESE MIGHT BE ADDED TO INTERFACE. -bool setLocalAddress(struct sockaddr_in addr); -bool setExtAddress(struct sockaddr_in addr); +bool setLocalAddress(const struct sockaddr_storage &addr); +bool setExtAddress(const struct sockaddr_storage &addr); /*************** Setup ***************************/ void addNetAssistConnect(uint32_t type, pqiNetAssistConnect *); @@ -262,13 +262,13 @@ bool netAssistConnectStats(uint32_t &netsize, uint32_t &localnetsize); void netAssistTick(); /* Assist Firewall */ -bool netAssistExtAddress(struct sockaddr_in &extAddr); +bool netAssistExtAddress(struct sockaddr_storage &extAddr); bool netAssistFirewallPorts(uint16_t iport, uint16_t eport); /* Assist Connect */ //virtual bool netAssistFriend(std::string id, bool on); (PUBLIC) -bool netAssistSetAddress( struct sockaddr_in &laddr, - struct sockaddr_in &eaddr, +bool netAssistSetAddress(const struct sockaddr_storage &laddr, + const struct sockaddr_storage &eaddr, uint32_t mode); bool netAssistAttach(bool on); @@ -326,8 +326,8 @@ private: void netStatusReset_locked(); - struct sockaddr_in mLocalAddr; - struct sockaddr_in mExtAddr; + struct sockaddr_storage mLocalAddr; + struct sockaddr_storage mExtAddr; uint32_t mNetMode; uint32_t mVisState; diff --git a/libretroshare/src/pqi/p3peermgr.cc b/libretroshare/src/pqi/p3peermgr.cc index 272bef347..fb5d2c425 100644 --- a/libretroshare/src/pqi/p3peermgr.cc +++ b/libretroshare/src/pqi/p3peermgr.cc @@ -68,6 +68,7 @@ const uint32_t PEER_IP_CONNECT_STATE_MAX_LIST_SIZE = 4; /**** * #define PEER_DEBUG 1 ***/ +#define PEER_DEBUG 1 #define MAX_AVAIL_PERIOD 230 //times a peer stay in available state when not connected #define MIN_RETRY_PERIOD 140 @@ -80,8 +81,8 @@ peerState::peerState() netMode(RS_NET_MODE_UNKNOWN), visState(RS_VIS_STATE_STD), lastcontact(0), hiddenNode(false), hiddenPort(0) { - sockaddr_clear(&localaddr); - sockaddr_clear(&serveraddr); + sockaddr_storage_clear(localaddr); + sockaddr_storage_clear(serveraddr); return; } @@ -91,9 +92,13 @@ std::string textPeerConnectState(peerState &state) std::string out = "Id: " + state.id + "\n"; rs_sprintf_append(out, "NetMode: %lu\n", state.netMode); rs_sprintf_append(out, "VisState: %lu\n", state.visState); - rs_sprintf_append(out, "laddr: %s:%u\n", rs_inet_ntoa(state.localaddr.sin_addr).c_str(), ntohs(state.localaddr.sin_port)); - rs_sprintf_append(out, "eaddr: %s:%u\n", rs_inet_ntoa(state.serveraddr.sin_addr).c_str(), ntohs(state.serveraddr.sin_port)); - + + out += "laddr: "; + out += sockaddr_storage_tostring(state.localaddr); + out += "\neaddr: "; + out += sockaddr_storage_tostring(state.serveraddr); + out += "\n"; + return out; } @@ -122,9 +127,12 @@ p3PeerMgrIMPL::p3PeerMgrIMPL( const std::string& ssl_own_id, lastGroupId = 1; // setup default ProxyServerAddress. - sockaddr_clear(&mProxyServerAddress); - inet_aton("127.0.0.1", &(mProxyServerAddress.sin_addr)); - mProxyServerAddress.sin_port = htons(9100); + sockaddr_storage_clear(mProxyServerAddress); + sockaddr_storage_ipv4_aton(mProxyServerAddress, "127.0.0.1"); + sockaddr_storage_ipv4_setport(mProxyServerAddress, 9100); + + //inet_aton("127.0.0.1", &(mProxyServerAddress.sin_addr)); + //mProxyServerAddress.sin_port = htons(9100); } @@ -158,10 +166,13 @@ bool p3PeerMgrIMPL::setupHiddenNode(const std::string &hiddenAddress, const uint setOwnVisState(RS_VIS_STATE_GRAY); // Force the Port. - struct sockaddr_in loopback; - sockaddr_clear(&loopback); - inet_aton("127.0.0.1", &(loopback.sin_addr)); - loopback.sin_port = htons(hiddenPort); + struct sockaddr_storage loopback; + sockaddr_storage_clear(loopback); + sockaddr_storage_ipv4_aton(loopback, "127.0.0.1"); + sockaddr_storage_ipv4_setport(loopback, hiddenPort); + + //inet_aton("127.0.0.1", &(loopback.sin_addr)); + //loopback.sin_port = htons(hiddenPort); setLocalAddress(AuthSSL::getAuthSSL()->OwnId(), loopback); @@ -206,7 +217,7 @@ bool p3PeerMgrIMPL::setOwnVisState(uint32_t visState) rslog(RSL_WARNING, p3peermgrzone, out); #ifdef PEER_DEBUG - std::cerr << out.str() << std::endl; + std::cerr << out.c_str() << std::endl; #endif if (mOwnState.visState != visState) { @@ -371,7 +382,7 @@ bool p3PeerMgrIMPL::setHiddenDomainPort(const std::string &ssl_id, const std::st return true; } -bool p3PeerMgrIMPL::setProxyServerAddress(const struct sockaddr_in &proxy_addr) +bool p3PeerMgrIMPL::setProxyServerAddress(const struct sockaddr_storage &proxy_addr) { RsStackMutex stack(mPeerMtx); /****** STACK LOCK MUTEX *******/ @@ -379,8 +390,7 @@ bool p3PeerMgrIMPL::setProxyServerAddress(const struct sockaddr_in &proxy_addr) return true; } - -bool p3PeerMgrIMPL::getProxyAddress(const std::string &ssl_id, struct sockaddr_in &proxy_addr, std::string &domain_addr, uint16_t &domain_port) +bool p3PeerMgrIMPL::getProxyAddress(const std::string &ssl_id, struct sockaddr_storage &proxy_addr, std::string &domain_addr, uint16_t &domain_port) { RsStackMutex stack(mPeerMtx); /****** STACK LOCK MUTEX *******/ @@ -403,8 +413,6 @@ bool p3PeerMgrIMPL::getProxyAddress(const std::string &ssl_id, struct sockaddr_i proxy_addr = mProxyServerAddress; return true; } - - // Placeholder until we implement this functionality. uint32_t p3PeerMgrIMPL::getConnectionType(const std::string &/*sslId*/) @@ -526,7 +534,7 @@ void p3PeerMgrIMPL::getOthersList(std::list &peers) int p3PeerMgrIMPL::getConnectAddresses(const std::string &id, - struct sockaddr_in &lAddr, struct sockaddr_in &eAddr, + struct sockaddr_storage &lAddr, struct sockaddr_storage &eAddr, pqiIpAddrSet &histAddrs, std::string &dyndns) { @@ -906,12 +914,12 @@ bool p3PeerMgrIMPL::addNeighbour(std::string id) * as it doesn't call back to there. */ -bool p3PeerMgrIMPL::UpdateOwnAddress(const struct sockaddr_in &localAddr, const struct sockaddr_in &extAddr) +bool p3PeerMgrIMPL::UpdateOwnAddress(const struct sockaddr_storage &localAddr, const struct sockaddr_storage &extAddr) { std::cerr << "p3PeerMgrIMPL::UpdateOwnAddress("; - std::cerr << rs_inet_ntoa(localAddr.sin_addr) << ":" << htons(localAddr.sin_port); + std::cerr << sockaddr_storage_tostring(localAddr); std::cerr << ", "; - std::cerr << rs_inet_ntoa(extAddr.sin_addr) << ":" << htons(extAddr.sin_port); + std::cerr << sockaddr_storage_tostring(extAddr); std::cerr << ")" << std::endl; { @@ -952,19 +960,18 @@ bool p3PeerMgrIMPL::UpdateOwnAddress(const struct sockaddr_in &localAddr, const std::cerr << " as MANUAL FORWARD Mode (ERROR - SHOULD NOT BE TRIGGERED: TRY_EXT_MODE)"; std::cerr << std::endl; std::cerr << "Address is Now: "; - std::cerr << rs_inet_ntoa(mOwnState.serveraddr.sin_addr); - std::cerr << ":" << htons(mOwnState.serveraddr.sin_port); + std::cerr << sockaddr_storage_tostring(mOwnState.serveraddr); std::cerr << std::endl; } else if (mOwnState.netMode & RS_NET_MODE_EXT) { - mOwnState.serveraddr.sin_addr.s_addr = extAddr.sin_addr.s_addr; + sockaddr_storage_copyip(mOwnState.serveraddr,extAddr); + std::cerr << "p3PeerMgrIMPL::UpdateOwnAddress() Disabling Update of Server Port "; std::cerr << " as MANUAL FORWARD Mode"; std::cerr << std::endl; std::cerr << "Address is Now: "; - std::cerr << rs_inet_ntoa(mOwnState.serveraddr.sin_addr); - std::cerr << ":" << htons(mOwnState.serveraddr.sin_port); + std::cerr << sockaddr_storage_tostring(mOwnState.serveraddr); std::cerr << std::endl; } else @@ -982,7 +989,7 @@ bool p3PeerMgrIMPL::UpdateOwnAddress(const struct sockaddr_in &localAddr, const -bool p3PeerMgrIMPL::setLocalAddress(const std::string &id, struct sockaddr_in addr) +bool p3PeerMgrIMPL::setLocalAddress(const std::string &id, const struct sockaddr_storage &addr) { bool changed = false; @@ -990,8 +997,7 @@ bool p3PeerMgrIMPL::setLocalAddress(const std::string &id, struct sockaddr_in { { RsStackMutex stack(mPeerMtx); /****** STACK LOCK MUTEX *******/ - if (mOwnState.localaddr.sin_addr.s_addr != addr.sin_addr.s_addr || - mOwnState.localaddr.sin_port != addr.sin_port) + if (!sockaddr_storage_same(mOwnState.localaddr, addr)) { mOwnState.localaddr = addr; changed = true; @@ -1023,8 +1029,8 @@ bool p3PeerMgrIMPL::setLocalAddress(const std::string &id, struct sockaddr_in } /* "it" points to peer */ - if ((it->second.localaddr.sin_addr.s_addr != addr.sin_addr.s_addr) || - (it->second.localaddr.sin_port != addr.sin_port)) { + if (!sockaddr_storage_same(it->second.localaddr, addr)) + { it->second.localaddr = addr; changed = true; } @@ -1044,7 +1050,7 @@ bool p3PeerMgrIMPL::setLocalAddress(const std::string &id, struct sockaddr_in return changed; } -bool p3PeerMgrIMPL::setExtAddress(const std::string &id, struct sockaddr_in addr) +bool p3PeerMgrIMPL::setExtAddress(const std::string &id, const struct sockaddr_storage &addr) { bool changed = false; @@ -1052,8 +1058,7 @@ bool p3PeerMgrIMPL::setExtAddress(const std::string &id, struct sockaddr_in a { { RsStackMutex stack(mPeerMtx); /****** STACK LOCK MUTEX *******/ - if (mOwnState.serveraddr.sin_addr.s_addr != addr.sin_addr.s_addr || - mOwnState.serveraddr.sin_port != addr.sin_port) + if (!sockaddr_storage_same(mOwnState.serveraddr, addr)) { mOwnState.serveraddr = addr; changed = true; @@ -1080,8 +1085,8 @@ bool p3PeerMgrIMPL::setExtAddress(const std::string &id, struct sockaddr_in a } /* "it" points to peer */ - if ((it->second.serveraddr.sin_addr.s_addr != addr.sin_addr.s_addr) || - (it->second.serveraddr.sin_port != addr.sin_port)) { + if (!sockaddr_storage_same(it->second.serveraddr, addr)) + { it->second.serveraddr = addr; changed = true; } @@ -1175,7 +1180,9 @@ bool p3PeerMgrIMPL::updateAddressList(const std::string& id, const pqiIpAddrS #ifdef PEER_DEBUG std::cerr << "p3PeerMgrIMPL::setLocalAddress() Updated Address for: " << id; std::cerr << std::endl; - it->second.ipAddrs.printAddrs(std::cerr); + std::string addrstr; + it->second.ipAddrs.printAddrs(addrstr); + std::cerr << addrstr; std::cerr << std::endl; #endif @@ -1206,7 +1213,7 @@ bool p3PeerMgrIMPL::updateCurrentAddress(const std::string& id, const pqiIpAd } } - if (isPrivateNet(&(addr.mAddr.sin_addr))) + if (sockaddr_storage_isPrivateNet(addr.mAddr)) { it->second.ipAddrs.updateLocalAddrs(addr); it->second.localaddr = addr.mAddr; @@ -1220,7 +1227,9 @@ bool p3PeerMgrIMPL::updateCurrentAddress(const std::string& id, const pqiIpAd #ifdef PEER_DEBUG std::cerr << "p3PeerMgrIMPL::updatedCurrentAddress() Updated Address for: " << id; std::cerr << std::endl; - it->second.ipAddrs.printAddrs(std::cerr); + std::string addrstr; + it->second.ipAddrs.printAddrs(addrstr); + std::cerr << addrstr; std::cerr << std::endl; #endif @@ -1465,11 +1474,11 @@ bool p3PeerMgrIMPL::saveList(bool &cleanup, std::list& saveData) item->visState = mOwnState.visState; item->lastContact = mOwnState.lastcontact; - item->currentlocaladdr = mOwnState.localaddr; - item->currentremoteaddr = mOwnState.serveraddr; - item->dyndns = mOwnState.dyndns; - mOwnState.ipAddrs.mLocal.loadTlv(item->localAddrList); - mOwnState.ipAddrs.mExt.loadTlv(item->extAddrList); + item->localAddr.addr = mOwnState.localaddr; + item->extAddr.addr = mOwnState.serveraddr; + item->dyndns = mOwnState.dyndns; + mOwnState.ipAddrs.mLocal.loadTlv(item->localAddrList); + mOwnState.ipAddrs.mExt.loadTlv(item->extAddrList); item->domain_addr = mOwnState.hiddenDomain; item->domain_port = mOwnState.hiddenPort; @@ -1495,8 +1504,8 @@ bool p3PeerMgrIMPL::saveList(bool &cleanup, std::list& saveData) item->netMode = (it->second).netMode; item->visState = (it->second).visState; item->lastContact = (it->second).lastcontact; - item->currentlocaladdr = (it->second).localaddr; - item->currentremoteaddr = (it->second).serveraddr; + item->localAddr.addr = (it->second).localaddr; + item->extAddr.addr = (it->second).serveraddr; item->dyndns = (it->second).dyndns; (it->second).ipAddrs.mLocal.loadTlv(item->localAddrList); (it->second).ipAddrs.mExt.loadTlv(item->extAddrList); @@ -1629,8 +1638,8 @@ bool p3PeerMgrIMPL::loadList(std::list& load) } else { - setLocalAddress(pitem->pid, pitem->currentlocaladdr); - setExtAddress(pitem->pid, pitem->currentremoteaddr); + setLocalAddress(pitem->pid, pitem->localAddr.addr); + setExtAddress(pitem->pid, pitem->extAddr.addr); setDynDNS (pitem->pid, pitem->dyndns); /* convert addresses */ diff --git a/libretroshare/src/pqi/p3peermgr.h b/libretroshare/src/pqi/p3peermgr.h index dc20830ca..8d8fcee95 100644 --- a/libretroshare/src/pqi/p3peermgr.h +++ b/libretroshare/src/pqi/p3peermgr.h @@ -93,8 +93,8 @@ class peerState uint32_t visState; /* STD, GRAY, DARK */ - struct sockaddr_in localaddr; - struct sockaddr_in serveraddr; + struct sockaddr_storage localaddr; + struct sockaddr_storage serveraddr; std::string dyndns; time_t lastcontact; @@ -161,8 +161,8 @@ virtual bool assignPeersToGroup(const std::string &groupId, const std::list mFriendsPermissionFlags ; // permission flags for each gpg key - struct sockaddr_in mProxyServerAddress; + struct sockaddr_storage mProxyServerAddress; }; #endif // MRK_PQI_PEER_MANAGER_HEADER diff --git a/libretroshare/src/pqi/p3upnpmgr.h b/libretroshare/src/pqi/p3upnpmgr.h index 99640d4f0..47b95d5cc 100644 --- a/libretroshare/src/pqi/p3upnpmgr.h +++ b/libretroshare/src/pqi/p3upnpmgr.h @@ -50,8 +50,8 @@ virtual void setInternalPort(unsigned short iport_in) = 0; virtual void setExternalPort(unsigned short eport_in) = 0; /* as determined by uPnP */ -virtual bool getInternalAddress(struct sockaddr_in &addr) = 0; -virtual bool getExternalAddress(struct sockaddr_in &addr) = 0; +virtual bool getInternalAddress(struct sockaddr_storage &addr) = 0; +virtual bool getExternalAddress(struct sockaddr_storage &addr) = 0; }; diff --git a/libretroshare/src/pqi/pqi_base.h b/libretroshare/src/pqi/pqi_base.h index 8bb563a77..6f1b90e67 100644 --- a/libretroshare/src/pqi/pqi_base.h +++ b/libretroshare/src/pqi/pqi_base.h @@ -351,17 +351,17 @@ public: virtual ~NetInterface() { return; } -virtual int connect(struct sockaddr_in raddr) = 0; +virtual int connect(const struct sockaddr_storage &raddr) = 0; virtual int listen() = 0; virtual int stoplistening() = 0; virtual int disconnect() = 0; virtual int reset() = 0; virtual std::string PeerId() { return peerId; } -virtual int getConnectAddress(struct sockaddr_in &raddr) = 0; +virtual int getConnectAddress(struct sockaddr_storage &raddr) = 0; virtual bool connect_parameter(uint32_t type, uint32_t value) = 0; virtual bool connect_parameter(uint32_t /* type */ , const std::string & /* value */ ) { return false; } // not generally used. -virtual bool connect_additional_address(uint32_t /*type*/, struct sockaddr_in * /*addr*/) { return false; } // only needed by udp. +virtual bool connect_additional_address(uint32_t /*type*/, const struct sockaddr_storage & /*addr*/) { return false; } // only needed by udp. protected: PQInterface *parent() { return p; } diff --git a/libretroshare/src/pqi/pqiassist.h b/libretroshare/src/pqi/pqiassist.h index 3bf984f8d..2823571b7 100644 --- a/libretroshare/src/pqi/pqiassist.h +++ b/libretroshare/src/pqi/pqiassist.h @@ -89,8 +89,8 @@ virtual void setInternalPort(unsigned short iport_in) = 0; virtual void setExternalPort(unsigned short eport_in) = 0; /* as determined by uPnP */ -virtual bool getInternalAddress(struct sockaddr_in &addr) = 0; -virtual bool getExternalAddress(struct sockaddr_in &addr) = 0; +virtual bool getInternalAddress(struct sockaddr_storage &addr) = 0; +virtual bool getExternalAddress(struct sockaddr_storage &addr) = 0; /* New Port Forward interface to support as many ports as necessary */ @@ -109,7 +109,7 @@ class pqiNetAssistPeerShare public: /* share Addresses for various reasons (bad peers, etc) */ -virtual void updatePeer(std::string id, struct sockaddr_in addr, int type, int reason, int age) = 0; +virtual void updatePeer(std::string id, const struct sockaddr_storage &addr, int type, int reason, int age) = 0; }; @@ -126,7 +126,7 @@ class pqiAddrAssist pqiAddrAssist() { return; } virtual ~pqiAddrAssist() { return; } -virtual bool getExternalAddr(struct sockaddr_in &remote, uint8_t &stable) = 0; +virtual bool getExternalAddr(struct sockaddr_storage &remote, uint8_t &stable) = 0; virtual void setRefreshPeriod(int32_t period) = 0; virtual int tick() = 0; /* for internal accounting */ @@ -163,14 +163,14 @@ virtual bool findPeer(std::string id) = 0; virtual bool dropPeer(std::string id) = 0; /* add non-active peers (can still toggle active/non-active via above) */ -virtual int addBadPeer(const struct sockaddr_in &addr, uint32_t reason, uint32_t flags, uint32_t age) = 0; -virtual int addKnownPeer(const std::string &pid, const struct sockaddr_in &addr, uint32_t flags) = 0; +virtual int addBadPeer(const struct sockaddr_storage &addr, uint32_t reason, uint32_t flags, uint32_t age) = 0; +virtual int addKnownPeer(const std::string &pid, const struct sockaddr_storage &addr, uint32_t flags) = 0; virtual void ConnectionFeedback(std::string pid, int mode) = 0; /* extract current peer status */ virtual bool getPeerStatus(std::string id, - struct sockaddr_in &laddr, struct sockaddr_in &raddr, + struct sockaddr_storage &laddr, struct sockaddr_storage &raddr, uint32_t &type, uint32_t &mode) = 0; // DEPRECIATE. virtual bool setAttachMode(bool on) = 0; // FIXUP. diff --git a/libretroshare/src/pqi/pqibin.cc b/libretroshare/src/pqi/pqibin.cc index 668188693..f7a7c32af 100644 --- a/libretroshare/src/pqi/pqibin.cc +++ b/libretroshare/src/pqi/pqibin.cc @@ -528,11 +528,10 @@ NetBinDummy::NetBinDummy(PQInterface *parent, std::string id, uint32_t t) } // Net Interface -int NetBinDummy::connect(struct sockaddr_in raddr) +int NetBinDummy::connect(const struct sockaddr_storage &raddr) { std::cerr << "NetBinDummy::connect("; - std::cerr << rs_inet_ntoa(raddr.sin_addr) << ":"; - std::cerr << htons(raddr.sin_port); + std::cerr << sockaddr_storage_tostring(raddr); std::cerr << ") "; printNetBinID(std::cerr, PeerId(), type); std::cerr << std::endl; diff --git a/libretroshare/src/pqi/pqibin.h b/libretroshare/src/pqi/pqibin.h index 55479e297..bcab734c7 100644 --- a/libretroshare/src/pqi/pqibin.h +++ b/libretroshare/src/pqi/pqibin.h @@ -193,7 +193,7 @@ public: virtual ~NetBinDummy() { return; } // Net Interface -virtual int connect(struct sockaddr_in raddr); +virtual int connect(const struct sockaddr_storage &raddr); virtual int listen(); virtual int stoplistening(); virtual int disconnect(); @@ -204,7 +204,7 @@ virtual bool connect_parameter(uint32_t type, uint32_t value) (void) value; /* suppress unused parameter warning */ return false; } -virtual int getConnectAddress(struct sockaddr_in &raddr) +virtual int getConnectAddress(struct sockaddr_storage &raddr) { (void) raddr; /* suppress unused parameter warning */ return 0; diff --git a/libretroshare/src/pqi/pqiipset.cc b/libretroshare/src/pqi/pqiipset.cc index f7bfdfe3b..fa6e7c543 100644 --- a/libretroshare/src/pqi/pqiipset.cc +++ b/libretroshare/src/pqi/pqiipset.cc @@ -29,15 +29,14 @@ bool pqiIpAddress::sameAddress(const pqiIpAddress &a) const { - return ((mAddr.sin_addr.s_addr == a.mAddr.sin_addr.s_addr) && - (mAddr.sin_port == a.mAddr.sin_port)); + return sockaddr_storage_same(mAddr, a.mAddr); } bool pqiIpAddress::validAddress() const { /* filter for unlikely addresses */ - if(isLoopbackNet(&(mAddr.sin_addr))) + if(sockaddr_storage_isLoopbackNet(mAddr)) { #ifdef IPADDR_DEBUG std::cerr << "pqiIpAddress::validAddress() ip parameter is loopback: disgarding." << std::endl ; @@ -45,7 +44,7 @@ bool pqiIpAddress::validAddress() const return false; } - if(mAddr.sin_addr.s_addr == 0 || mAddr.sin_addr.s_addr == 1 || mAddr.sin_port == 0) + if(sockaddr_storage_isnull(mAddr)) { #ifdef IPADDR_DEBUG std::cerr << "pqiIpAddress::validAddress() ip parameter is 0.0.0.0/1, or port is 0, ignoring." << std::endl; @@ -168,7 +167,7 @@ void pqiIpAddrList::extractFromTlv(const RsTlvIpAddrSet &tlvAddrs) for(it = tlvAddrs.addrs.begin(); it != tlvAddrs.addrs.end() ; ++it) { pqiIpAddress addr; - addr.mAddr = it->addr; + addr.mAddr = it->addr.addr; addr.mSeenTime = it->seenTime; addr.mSrc = it->source; @@ -183,7 +182,7 @@ void pqiIpAddrList::loadTlv(RsTlvIpAddrSet &tlvAddrs) for(it = mAddrs.begin(); it != mAddrs.end() ; ++it) { RsTlvIpAddressInfo addr; - addr.addr = it->mAddr; + addr.addr.addr = it->mAddr; addr.seenTime = it->mSeenTime; addr.source = it->mSrc; @@ -199,7 +198,8 @@ void pqiIpAddrList::printIpAddressList(std::string &out) const time_t now = time(NULL); for(it = mAddrs.begin(); it != mAddrs.end(); it++) { - rs_sprintf_append(out, "%s:%u ( %ld old)\n", rs_inet_ntoa(it->mAddr.sin_addr).c_str(), ntohs(it->mAddr.sin_port), now - it->mSeenTime); + out += sockaddr_storage_tostring(it->mAddr); + rs_sprintf_append(out, "( %ld old)\n", now - it->mSeenTime); } return; } diff --git a/libretroshare/src/pqi/pqiipset.h b/libretroshare/src/pqi/pqiipset.h index 863ed8739..f20dc1a5f 100644 --- a/libretroshare/src/pqi/pqiipset.h +++ b/libretroshare/src/pqi/pqiipset.h @@ -37,7 +37,7 @@ class pqiIpAddress bool sameAddress(const pqiIpAddress &a) const; bool validAddress() const; - struct sockaddr_in mAddr; + struct sockaddr_storage mAddr; time_t mSeenTime; uint32_t mSrc; }; diff --git a/libretroshare/src/pqi/pqilistener.h b/libretroshare/src/pqi/pqilistener.h index 0e0b980ee..46e030206 100644 --- a/libretroshare/src/pqi/pqilistener.h +++ b/libretroshare/src/pqi/pqilistener.h @@ -38,7 +38,7 @@ virtual ~pqilistener() { return; } virtual int tick() { return 1; } virtual int status() { return 1; } -virtual int setListenAddr(struct sockaddr_in addr) +virtual int setListenAddr(const struct sockaddr_storage &addr) { (void) addr; /* suppress unused parameter warning */ return 1; diff --git a/libretroshare/src/pqi/pqimonitor.cc b/libretroshare/src/pqi/pqimonitor.cc index 433f9d862..e76d3f6a2 100644 --- a/libretroshare/src/pqi/pqimonitor.cc +++ b/libretroshare/src/pqi/pqimonitor.cc @@ -62,23 +62,21 @@ void pqiConnectCbDummy::peerStatus(std::string id, const pqiIpAddrSet &addrs, } void pqiConnectCbDummy::peerConnectRequest(std::string id, - struct sockaddr_in raddr, uint32_t source) + const struct sockaddr_storage &raddr, uint32_t source) { std::cerr << "pqiConnectCbDummy::peerConnectRequest()"; std::cerr << " id: " << id; - std::cerr << " raddr: " << rs_inet_ntoa(raddr.sin_addr); - std::cerr << ":" << ntohs(raddr.sin_port); + std::cerr << " raddr: " << sockaddr_storage_tostring(raddr); std::cerr << " source: " << source; std::cerr << std::endl; } #if 0 -void pqiConnectCbDummy::stunStatus(std::string id, struct sockaddr_in raddr, +void pqiConnectCbDummy::stunStatus(std::string id, const struct sockaddr_storage *raddr, uint32_t type, uint32_t flags) { std::cerr << "pqiConnectCbDummy::stunStatus()"; - std::cerr << " idhash: " << RsUtil::BinToHex(id) << " raddr: " << rs_inet_ntoa(raddr.sin_addr); - std::cerr << ":" << ntohs(raddr.sin_port); + std::cerr << " idhash: " << RsUtil::BinToHex(id) << " raddr: " << sockaddr_storage_tostring(raddr); std::cerr << " type: " << type; std::cerr << " flags: " << flags; std::cerr << std::endl; diff --git a/libretroshare/src/pqi/pqimonitor.h b/libretroshare/src/pqi/pqimonitor.h index edf53d49f..3016308db 100644 --- a/libretroshare/src/pqi/pqimonitor.h +++ b/libretroshare/src/pqi/pqimonitor.h @@ -156,11 +156,11 @@ virtual ~pqiConnectCb() { return; } virtual void peerStatus(std::string id, const pqiIpAddrSet &addrs, uint32_t type, uint32_t flags, uint32_t source) = 0; -virtual void peerConnectRequest(std::string id, struct sockaddr_in raddr, - struct sockaddr_in proxyaddr, struct sockaddr_in srcaddr, +virtual void peerConnectRequest(std::string id, const struct sockaddr_storage &raddr, + const struct sockaddr_storage &proxyaddr, const struct sockaddr_storage &srcaddr, uint32_t source, uint32_t flags, uint32_t delay, uint32_t bandwidth) = 0; -//virtual void stunStatus(std::string id, struct sockaddr_in raddr, uint32_t type, uint32_t flags) = 0; +//virtual void stunStatus(std::string id, const struct sockaddr_storage &raddr, uint32_t type, uint32_t flags) = 0; }; @@ -174,9 +174,9 @@ virtual void peerStatus(std::string id, const pqiIpAddrSet &addrs, uint32_t type, uint32_t mode, uint32_t source); virtual void peerConnectRequest(std::string id, - struct sockaddr_in raddr, uint32_t source); + const struct sockaddr_storage &raddr, uint32_t source); -//virtual void stunStatus(std::string id, struct sockaddr_in raddr, uint32_t type, uint32_t flags); +//virtual void stunStatus(std::string id, const struct sockaddr_storage &raddr, uint32_t type, uint32_t flags); }; @@ -184,7 +184,7 @@ virtual void peerConnectRequest(std::string id, class pqiNetListener { public: -virtual bool resetListener(struct sockaddr_in &local) = 0; +virtual bool resetListener(const struct sockaddr_storage &local) = 0; }; diff --git a/libretroshare/src/pqi/pqinetstatebox.cc b/libretroshare/src/pqi/pqinetstatebox.cc index 22bd41134..fa265dc12 100644 --- a/libretroshare/src/pqi/pqinetstatebox.cc +++ b/libretroshare/src/pqi/pqinetstatebox.cc @@ -6,15 +6,14 @@ // External Interface. -void pqiNetStateBox::setAddressStunDht(struct sockaddr_in *addr, bool stable) +void pqiNetStateBox::setAddressStunDht(const struct sockaddr_storage &addr, bool stable) { if ((!mStunDhtSet) || (mStunDhtStable != stable) || - (addr->sin_addr.s_addr != mStunDhtAddr.sin_addr.s_addr) || - (addr->sin_port != mStunDhtAddr.sin_port)) + (!sockaddr_storage_same(addr, mStunDhtAddr))) { mStunDhtSet = true; mStunDhtStable = stable; - mStunDhtAddr = *addr; + mStunDhtAddr = addr; mStatusOkay = false; } @@ -22,15 +21,13 @@ void pqiNetStateBox::setAddressStunDht(struct sockaddr_in *addr, bool stable) } -void pqiNetStateBox::setAddressStunProxy(struct sockaddr_in *addr, bool stable) +void pqiNetStateBox::setAddressStunProxy(const struct sockaddr_storage &addr, bool stable) { if ((!mStunProxySet) || (mStunProxyStable != stable) || - (addr->sin_addr.s_addr != mStunProxyAddr.sin_addr.s_addr) || - (addr->sin_port != mStunProxyAddr.sin_port)) - + (!sockaddr_storage_same(addr, mStunProxyAddr))) { - if (addr->sin_addr.s_addr == mStunProxyAddr.sin_addr.s_addr) + if (sockaddr_storage_sameip(addr,mStunProxyAddr)) { if (mStunProxyStable != stable) { @@ -44,22 +41,20 @@ void pqiNetStateBox::setAddressStunProxy(struct sockaddr_in *addr, bool stable) mStunProxySet = true; mStunProxyStable = stable; - mStunProxyAddr = *addr; + mStunProxyAddr = addr; mStatusOkay = false; } mStunProxyTS = time(NULL); } -void pqiNetStateBox::setAddressUPnP(bool active, struct sockaddr_in *addr) +void pqiNetStateBox::setAddressUPnP(bool active, const struct sockaddr_storage &addr) { if ((!mUPnPSet) || (mUPnPActive != active) || - (addr->sin_addr.s_addr != mUPnPAddr.sin_addr.s_addr) || - (addr->sin_port != mUPnPAddr.sin_port)) - + (!sockaddr_storage_same(addr, mUPnPAddr))) { mUPnPSet = true; - mUPnPAddr = *addr; + mUPnPAddr = addr; mUPnPActive = active; mStatusOkay = false; @@ -68,15 +63,13 @@ void pqiNetStateBox::setAddressUPnP(bool active, struct sockaddr_in *addr) } -void pqiNetStateBox::setAddressNatPMP(bool active, struct sockaddr_in *addr) +void pqiNetStateBox::setAddressNatPMP(bool active, const struct sockaddr_storage &addr) { if ((!mNatPMPSet) || (mNatPMPActive != active) || - (addr->sin_addr.s_addr != mNatPMPAddr.sin_addr.s_addr) || - (addr->sin_port != mNatPMPAddr.sin_port)) - + (!sockaddr_storage_same(addr, mNatPMPAddr))) { mNatPMPSet = true; - mNatPMPAddr = *addr; + mNatPMPAddr = addr; mNatPMPActive = active; mStatusOkay = false; @@ -86,15 +79,13 @@ void pqiNetStateBox::setAddressNatPMP(bool active, struct sockaddr_in *addr) -void pqiNetStateBox::setAddressWebIP(bool active, struct sockaddr_in *addr) +void pqiNetStateBox::setAddressWebIP(bool active, const struct sockaddr_storage &addr) { if ((!mWebIPSet) || (mWebIPActive != active) || - (addr->sin_addr.s_addr != mWebIPAddr.sin_addr.s_addr) || - (addr->sin_port != mWebIPAddr.sin_port)) - + (!sockaddr_storage_same(addr, mWebIPAddr))) { mWebIPSet = true; - mWebIPAddr = *addr; + mWebIPAddr = addr; mWebIPActive = active; mStatusOkay = false; @@ -188,35 +179,25 @@ void pqiNetStateBox::reset() mStunDhtSet = false; mStunDhtTS = 0; mStunDhtStable = false; - mStunDhtAddr.sin_addr.s_addr = 0 ; - mStunDhtAddr.sin_port = 0 ; - //struct sockaddr_in mStunDhtAddr; + sockaddr_storage_clear(mStunDhtAddr); mStunProxySet = false; mStunProxySemiStable = false; mStunProxyTS = 0; mStunProxyStable = false; - mStunProxyAddr.sin_addr.s_addr = 0 ; - mStunProxyAddr.sin_port = 0 ; - //struct sockaddr_in mStunProxyAddr; + sockaddr_storage_clear(mStunProxyAddr); mUPnPSet = false; mUPnPActive = false; - mUPnPAddr.sin_addr.s_addr = 0 ; - mUPnPAddr.sin_port = 0 ; - //struct sockaddr_in mUPnPAddr; + sockaddr_storage_clear(mUPnPAddr); mNatPMPSet = false; mNatPMPActive = false; - mNatPMPAddr.sin_addr.s_addr = 0 ; - mNatPMPAddr.sin_port = 0 ; - //struct sockaddr_in mNatPMPAddr; + sockaddr_storage_clear(mNatPMPAddr); mWebIPSet = false; mWebIPActive = false; - mWebIPAddr.sin_addr.s_addr = 0 ; - mWebIPAddr.sin_port = 0 ; - //struct sockaddr_in mWebIPAddr; + sockaddr_storage_clear(mWebIPAddr); mPortForwardSet = false; mPortForwarded = false; diff --git a/libretroshare/src/pqi/pqinetstatebox.h b/libretroshare/src/pqi/pqinetstatebox.h index 9a56b975d..9d6f43e55 100644 --- a/libretroshare/src/pqi/pqinetstatebox.h +++ b/libretroshare/src/pqi/pqinetstatebox.h @@ -21,12 +21,12 @@ class pqiNetStateBox void reset(); /* input network bits */ - void setAddressStunDht(struct sockaddr_in *, bool stable); - void setAddressStunProxy(struct sockaddr_in *, bool stable); + void setAddressStunDht(const struct sockaddr_storage &addr, bool stable); + void setAddressStunProxy(const struct sockaddr_storage &addr, bool stable); - void setAddressUPnP(bool active, struct sockaddr_in *addr); - void setAddressNatPMP(bool active, struct sockaddr_in *addr); - void setAddressWebIP(bool active, struct sockaddr_in *addr); + void setAddressUPnP(bool active, const struct sockaddr_storage &addr); + void setAddressNatPMP(bool active, const struct sockaddr_storage &addr); + void setAddressWebIP(bool active, const struct sockaddr_storage &addr); void setPortForwarded(bool active, uint16_t port); @@ -63,13 +63,13 @@ class pqiNetStateBox bool mStunDhtSet; time_t mStunDhtTS; bool mStunDhtStable; - struct sockaddr_in mStunDhtAddr; + struct sockaddr_storage mStunDhtAddr; bool mStunProxySet; time_t mStunProxyTS; bool mStunProxyStable; bool mStunProxySemiStable; - struct sockaddr_in mStunProxyAddr; + struct sockaddr_storage mStunProxyAddr; bool mDhtSet; time_t mDhtTS; @@ -77,17 +77,17 @@ class pqiNetStateBox bool mDhtActive; bool mUPnPSet; - struct sockaddr_in mUPnPAddr; + struct sockaddr_storage mUPnPAddr; bool mUPnPActive; time_t mUPnPTS; bool mNatPMPSet; - struct sockaddr_in mNatPMPAddr; + struct sockaddr_storage mNatPMPAddr; bool mNatPMPActive; time_t mNatPMPTS; bool mWebIPSet; - struct sockaddr_in mWebIPAddr; + struct sockaddr_storage mWebIPAddr; bool mWebIPActive; time_t mWebIPTS; diff --git a/libretroshare/src/pqi/pqinetwork.cc b/libretroshare/src/pqi/pqinetwork.cc index b57db7ce9..4e3567e45 100644 --- a/libretroshare/src/pqi/pqinetwork.cc +++ b/libretroshare/src/pqi/pqinetwork.cc @@ -147,7 +147,7 @@ std::string socket_errorType(int err) #include #include -bool getLocalInterfaces(struct in_addr &/*routeAddr*/, std::list &addrs) +bool getLocalInterfaces_ipv4(struct in_addr &/*routeAddr*/, std::list &addrs) { int sock = 0; struct ifreq ifreq; @@ -328,7 +328,7 @@ std::string socket_errorType(int err) // A function to determine the interfaces on your computer.... // No idea of how to do this in windows.... // see if it compiles. -bool getLocalInterfaces(struct in_addr &routeAddr, std::list &addrs) +bool getLocalInterfaces_ipv4(struct in_addr &routeAddr, std::list &addrs) { // Get the best interface for transport to routeAddr // This interface should be first in list! @@ -556,8 +556,7 @@ int inaddr_cmp(struct sockaddr_in addr1, unsigned long addr2) return 1; } - -bool getPreferredInterface(in_addr &routeAddr, struct in_addr &prefAddr) // returns best addr. +bool getPreferredInterface_ipv4(in_addr &routeAddr, struct in_addr &prefAddr) // returns best addr. { std::list addrs; std::list::iterator it; @@ -572,7 +571,7 @@ bool getPreferredInterface(in_addr &routeAddr, struct in_addr &prefAddr) // ret bool found_priv = false; bool found_ext = false; - if (!getLocalInterfaces(routeAddr, addrs)) + if (!getLocalInterfaces_ipv4(routeAddr, addrs)) { return false; } @@ -686,6 +685,78 @@ bool getPreferredInterface(in_addr &routeAddr, struct in_addr &prefAddr) // ret return false; } + + +bool getPreferredInterface(struct sockaddr_storage &existAddr, struct sockaddr_storage &prefAddr) +{ + struct in_addr existing_addr; + struct in_addr pref_addr; + + { + struct sockaddr_in *eaddr = (sockaddr_in *) &existAddr; + if (eaddr->sin_family != AF_INET) + { + std::cerr << "getPreferredInterface() ERROR only valid for IPv4 for now"; + abort(); + return false; + } + existing_addr = eaddr->sin_addr; + } + + if (getPreferredInterface_ipv4(existing_addr, pref_addr)) + { + /* store into prefAddr */ + sockaddr_storage_clear(prefAddr); + struct sockaddr_in *addr = (sockaddr_in *) &prefAddr; + addr->sin_family = AF_INET; + addr->sin_addr = pref_addr; + addr->sin_port = htons(0); + + return true; + } + return false; +} + + +bool getLocalInterfaces(struct sockaddr_storage &existAddr, std::list &addrs) +{ + struct in_addr existing_addr; + std::list local_addrs; + + { + struct sockaddr_in *eaddr = (sockaddr_in *) &existAddr; + if (eaddr->sin_family != AF_INET) + { + std::cerr << "getLocalInterfaces() ERROR only valid for IPv4 for now"; + abort(); + return false; + } + existing_addr = eaddr->sin_addr; + } + + if (getLocalInterfaces_ipv4(existing_addr, local_addrs)) + { + std::list::iterator it; + for(it = local_addrs.begin(); it != local_addrs.end(); it++) + { + /* store into prefAddr */ + + sockaddr_storage localAddr; + sockaddr_storage_clear(localAddr); + struct sockaddr_in *addr = (sockaddr_in *) &localAddr; + addr->sin_family = AF_INET; + addr->sin_addr = *it; + addr->sin_port = htons(0); + addrs.push_back(localAddr); + } + return true; + } + return false; +} + + + + bool sameNet(const struct in_addr *addr, const struct in_addr *addr2) { #ifdef NET_DEBUG diff --git a/libretroshare/src/pqi/pqinetwork.h b/libretroshare/src/pqi/pqinetwork.h index 9c1be7473..4a48729dc 100644 --- a/libretroshare/src/pqi/pqinetwork.h +++ b/libretroshare/src/pqi/pqinetwork.h @@ -101,8 +101,8 @@ int sockaddr_cmp(struct sockaddr_in &addr1, struct sockaddr_in &addr2 ); int inaddr_cmp(struct sockaddr_in addr1, struct sockaddr_in addr2 ); int inaddr_cmp(struct sockaddr_in addr1, unsigned long); -bool getPreferredInterface(struct in_addr &routeAddr, struct in_addr &prefAddr); // returns best addr. -bool getLocalInterfaces(in_addr &routeAddr, std::list &addrs); // returns all possible addrs. +bool getPreferredInterface(struct sockaddr_storage &existAddr, struct sockaddr_storage &prefAddr); // returns best addr. +bool getLocalInterfaces(struct sockaddr_storage &existAddr, std::list &addrs); // returns all possible addrs. // checks (addr1 & 255.255.255.0) == (addr2 & 255.255.255.0) bool isSameSubnet(struct in_addr *addr1, struct in_addr *addr2); diff --git a/libretroshare/src/pqi/pqiperson.cc b/libretroshare/src/pqi/pqiperson.cc index 6783bd46d..d104e1326 100644 --- a/libretroshare/src/pqi/pqiperson.cc +++ b/libretroshare/src/pqi/pqiperson.cc @@ -33,9 +33,11 @@ const int pqipersonzone = 82371; #include "util/rsstring.h" /**** - * #define PERSON_DEBUG + * #define PERSON_DEBUG 1 ****/ +#define PERSON_DEBUG 1 + pqiperson::pqiperson(std::string id, pqipersongrp *pg) :PQInterface(id), active(false), activepqi(NULL), inConnectAttempt(false), waittimes(0), @@ -217,7 +219,7 @@ int pqiperson::notifyEvent(NetInterface *ni, int newState) /* notify */ if (pqipg) { - struct sockaddr_in remote_peer_address; + struct sockaddr_storage remote_peer_address; pqi->getConnectAddress(remote_peer_address); pqipg->notifyConnect(PeerId(), type, true, remote_peer_address); } @@ -287,8 +289,8 @@ int pqiperson::notifyEvent(NetInterface *ni, int newState) /* notify up */ if (pqipg) { - struct sockaddr_in raddr; - sockaddr_clear(&raddr); + struct sockaddr_storage raddr; + sockaddr_storage_clear(raddr); pqipg->notifyConnect(PeerId(), type, false, raddr); } @@ -366,8 +368,8 @@ int pqiperson::stoplistening() return 1; } -int pqiperson::connect(uint32_t type, struct sockaddr_in raddr, - struct sockaddr_in &proxyaddr, struct sockaddr_in &srcaddr, +int pqiperson::connect(uint32_t type, const struct sockaddr_storage &raddr, + const struct sockaddr_storage &proxyaddr, const struct sockaddr_storage &srcaddr, uint32_t delay, uint32_t period, uint32_t timeout, uint32_t flags, uint32_t bandwidth, const std::string &domain_addr, uint16_t domain_port) { @@ -376,9 +378,12 @@ int pqiperson::connect(uint32_t type, struct sockaddr_in raddr, { std::string out = "pqiperson::connect() Id: " + PeerId(); rs_sprintf_append(out, " type: %u", type); - rs_sprintf_append(out, " addr: %s:%u", rs_inet_ntoa(raddr.sin_addr).c_str(), ntohs(raddr.sin_port)); - rs_sprintf_append(out, " proxyaddr: %s:%u", rs_inet_ntoa(proxyaddr.sin_addr).c_str(), ntohs(proxyaddr.sin_port)); - rs_sprintf_append(out, " srcaddr: %s:%u", rs_inet_ntoa(srcaddr.sin_addr).c_str(), ntohs(srcaddr.sin_port)); + out += " addr: "; + out += sockaddr_storage_tostring(raddr); + out += " proxyaddr: "; + out += sockaddr_storage_tostring(proxyaddr); + out += " srcaddr: "; + out += sockaddr_storage_tostring(srcaddr); rs_sprintf_append(out, " delay: %u", delay); rs_sprintf_append(out, " period: %u", period); rs_sprintf_append(out, " timeout: %u", timeout); @@ -428,8 +433,8 @@ int pqiperson::connect(uint32_t type, struct sockaddr_in raddr, (it->second)->connect_parameter(NET_PARAM_CONNECT_FLAGS, flags); (it->second)->connect_parameter(NET_PARAM_CONNECT_BANDWIDTH, bandwidth); - (it->second)->connect_additional_address(NET_PARAM_CONNECT_PROXY, &proxyaddr); - (it->second)->connect_additional_address(NET_PARAM_CONNECT_SOURCE, &srcaddr); + (it->second)->connect_additional_address(NET_PARAM_CONNECT_PROXY, proxyaddr); + (it->second)->connect_additional_address(NET_PARAM_CONNECT_SOURCE, srcaddr); // These are used by Proxy/Hidden (it->second)->connect_parameter(NET_PARAM_CONNECT_DOMAIN_ADDRESS, domain_addr); diff --git a/libretroshare/src/pqi/pqiperson.h b/libretroshare/src/pqi/pqiperson.h index c2a495656..d3eec1866 100644 --- a/libretroshare/src/pqi/pqiperson.h +++ b/libretroshare/src/pqi/pqiperson.h @@ -65,18 +65,18 @@ public: virtual ~pqiconnect() { return; } // presents a virtual NetInterface -> passes to ni. -virtual int connect(struct sockaddr_in raddr) { return ni->connect(raddr); } +virtual int connect(const struct sockaddr_storage &raddr) { return ni->connect(raddr); } virtual int listen() { return ni -> listen(); } virtual int stoplistening() { return ni -> stoplistening(); } virtual int reset() { return ni -> reset(); } virtual int disconnect() { return ni -> reset(); } virtual bool connect_parameter(uint32_t type, uint32_t value) { return ni -> connect_parameter(type, value);} virtual bool connect_parameter(uint32_t type, std::string value) { return ni -> connect_parameter(type, value);} -virtual bool connect_additional_address(uint32_t type, struct sockaddr_in *addr) { return ni -> connect_additional_address(type, addr);} +virtual bool connect_additional_address(uint32_t type, const struct sockaddr_storage &addr) { return ni -> connect_additional_address(type, addr);} -virtual int getConnectAddress(struct sockaddr_in &raddr){ return ni->getConnectAddress(raddr); } +virtual int getConnectAddress(struct sockaddr_storage &raddr){ return ni->getConnectAddress(raddr); } // get the contact from the net side! virtual std::string PeerId() @@ -112,8 +112,8 @@ int reset(); int listen(); int stoplistening(); -int connect(uint32_t type, struct sockaddr_in raddr, - struct sockaddr_in &proxyaddr, struct sockaddr_in &srcaddr, +int connect(uint32_t type, const struct sockaddr_storage &raddr, + const struct sockaddr_storage &proxyaddr, const struct sockaddr_storage &srcaddr, uint32_t delay, uint32_t period, uint32_t timeout, uint32_t flags, uint32_t bandwidth, const std::string &domain_addr, uint16_t domain_port); diff --git a/libretroshare/src/pqi/pqipersongrp.cc b/libretroshare/src/pqi/pqipersongrp.cc index 5738cb046..061a0fb7e 100644 --- a/libretroshare/src/pqi/pqipersongrp.cc +++ b/libretroshare/src/pqi/pqipersongrp.cc @@ -43,7 +43,7 @@ static std::list waitingIds; /**** *#define PGRP_DEBUG 1 ****/ -//#define PGRP_DEBUG 1 +#define PGRP_DEBUG 1 #define DEFAULT_DOWNLOAD_KB_RATE (200.0) #define DEFAULT_UPLOAD_KB_RATE (50.0) @@ -184,7 +184,8 @@ int pqipersongrp::init_listener() { /* extract details from */ - struct sockaddr_in laddr = mLinkMgr->getLocalAddress(); + struct sockaddr_storage laddr; + mLinkMgr->getLocalAddress(laddr); RsStackMutex stack(coreMtx); /******* LOCKED MUTEX **********/ pqil = locked_createListener(laddr); @@ -192,7 +193,7 @@ int pqipersongrp::init_listener() return 1; } -bool pqipersongrp::resetListener(struct sockaddr_in &local) +bool pqipersongrp::resetListener(const struct sockaddr_storage &local) { #ifdef PGRP_DEBUG std::cerr << "pqipersongrp::resetListener()" << std::endl; @@ -536,15 +537,15 @@ int pqipersongrp::connectPeer(std::string id /////////////////////////////////////////////////////////// #endif - struct sockaddr_in addr; + struct sockaddr_storage addr; uint32_t delay; uint32_t period; uint32_t timeout; uint32_t type; uint32_t flags = 0 ; - struct sockaddr_in proxyaddr; - struct sockaddr_in srcaddr; + struct sockaddr_storage proxyaddr; + struct sockaddr_storage srcaddr; uint32_t bandwidth; std::string domain_addr; uint16_t domain_port; @@ -560,7 +561,7 @@ int pqipersongrp::connectPeer(std::string id #ifdef PGRP_DEBUG std::cerr << " pqipersongrp::connectPeer() connectAttempt data id: " << id; - std::cerr << " addr: " << rs_inet_ntoa(addr.sin_addr) << ":" << ntohs(addr.sin_port); + std::cerr << " addr: " << sockaddr_storage_tostring(addr); std::cerr << " delay: " << delay; std::cerr << " period: " << period; std::cerr << " type: " << type; @@ -611,7 +612,7 @@ int pqipersongrp::connectPeer(std::string id return 1; } -bool pqipersongrp::notifyConnect(std::string id, uint32_t ptype, bool success, struct sockaddr_in raddr) +bool pqipersongrp::notifyConnect(std::string id, uint32_t ptype, bool success, const struct sockaddr_storage &raddr) { uint32_t type = 0; if (ptype == PQI_CONNECT_TCP) @@ -633,7 +634,7 @@ bool pqipersongrp::notifyConnect(std::string id, uint32_t ptype, bool success #include "pqi/pqibin.h" -pqilistener * pqipersongrpDummy::locked_createListener(struct sockaddr_in /*laddr*/) +pqilistener * pqipersongrpDummy::locked_createListener(const struct sockaddr_storage & /*laddr*/) { pqilistener *listener = new pqilistener(); return listener; diff --git a/libretroshare/src/pqi/pqipersongrp.h b/libretroshare/src/pqi/pqipersongrp.h index 5245106fe..fdaaf5bfa 100644 --- a/libretroshare/src/pqi/pqipersongrp.h +++ b/libretroshare/src/pqi/pqipersongrp.h @@ -55,7 +55,7 @@ class pqipersongrp: public pqihandler, public pqiMonitor, public p3ServiceServer /*************************** Setup *************************/ /* pqilistener */ -virtual bool resetListener(struct sockaddr_in &local); // overloaded from pqiNetListener +virtual bool resetListener(const struct sockaddr_storage &local); // overloaded from pqiNetListener int init_listener(); /*************** pqiMonitor callback ***********************/ @@ -84,7 +84,7 @@ int connectPeer(std::string id int tagHeartbeatRecvd(std::string id); /*** callback from children ****/ -bool notifyConnect(std::string id, uint32_t type, bool success, struct sockaddr_in remote_peer_address); +bool notifyConnect(std::string id, uint32_t type, bool success, const struct sockaddr_storage &remote_peer_address); //bool notifyConnect(std::string id, uint32_t type, bool success); // tick interfaces. @@ -98,7 +98,7 @@ virtual bool locked_getCryptoParams(const std::string&, RsPeerCryptoParams&) { r /********* FUNCTIONS to OVERLOAD for specialisation ********/ // THESE NEED TO BE LOCKED UNTIL PQILISTENER IS THREAD-SAFE. -virtual pqilistener *locked_createListener(struct sockaddr_in laddr) = 0; +virtual pqilistener *locked_createListener(const struct sockaddr_storage &laddr) = 0; virtual pqiperson *locked_createPerson(std::string id, pqilistener *listener) = 0; /********* FUNCTIONS to OVERLOAD for specialisation ********/ @@ -131,7 +131,7 @@ class pqipersongrpDummy: public pqipersongrp protected: /********* FUNCTIONS to OVERLOAD for specialisation ********/ -virtual pqilistener *locked_createListener(struct sockaddr_in laddr); +virtual pqilistener *locked_createListener(const struct sockaddr_storage &laddr); virtual pqiperson *locked_createPerson(std::string id, pqilistener *listener); /********* FUNCTIONS to OVERLOAD for specialisation ********/ }; diff --git a/libretroshare/src/pqi/pqissl.cc b/libretroshare/src/pqi/pqissl.cc index 47f6bcc43..10f35d946 100644 --- a/libretroshare/src/pqi/pqissl.cc +++ b/libretroshare/src/pqi/pqissl.cc @@ -104,7 +104,7 @@ pqissl::pqissl(pqissllistener *l, PQInterface *parent, p3LinkMgr *lm) { /* set address to zero */ - sockaddr_clear(&remote_addr); + sockaddr_storage_clear(remote_addr); #ifdef PQISSL_LOG_DEBUG rslog(RSL_DEBUG_BASIC, pqisslzone, "pqissl for PeerId: " + PeerId()); @@ -142,11 +142,10 @@ pqissl::pqissl(pqissllistener *l, PQInterface *parent, p3LinkMgr *lm) /********** Implementation of NetInterface *************************/ -int pqissl::connect(struct sockaddr_in raddr) +int pqissl::connect(const struct sockaddr_storage &raddr) { // reset failures remote_addr = raddr; - remote_addr.sin_family = AF_INET; return ConnectAttempt(); } @@ -176,9 +175,10 @@ int pqissl::disconnect() return reset(); } -int pqissl::getConnectAddress(struct sockaddr_in &raddr) { +int pqissl::getConnectAddress(struct sockaddr_storage &raddr) { raddr = remote_addr; - return (remote_addr.sin_addr.s_addr == 0); + // TODO. + return (!sockaddr_storage_isnull(remote_addr)); } /* BinInterface version of reset() for pqistreamer */ @@ -267,6 +267,7 @@ int pqissl::reset() bool pqissl::connect_parameter(uint32_t type, const std::string &value) { + (void) value; return false; } @@ -584,7 +585,7 @@ int pqissl::Delay_Connection() int pqissl::Initiate_Connection() { int err; - struct sockaddr_in addr = remote_addr; + struct sockaddr_storage addr = remote_addr; #ifdef PQISSL_LOG_DEBUG rslog(RSL_DEBUG_BASIC, pqisslzone, @@ -644,11 +645,12 @@ int pqissl::Initiate_Connection() { std::string out; - rs_sprintf(out, "pqissl::Initiate_Connection() Connecting To: %s via: %s:%u", PeerId().c_str(), rs_inet_ntoa(addr.sin_addr).c_str(), ntohs(addr.sin_port)); + rs_sprintf(out, "pqissl::Initiate_Connection() Connecting To: %s via: ", PeerId().c_str()); + out += sockaddr_storage_tostring(addr); rslog(RSL_WARNING, pqisslzone, out); } - if (addr.sin_addr.s_addr == 0) + if (sockaddr_storage_isnull(addr)) { rslog(RSL_WARNING, pqisslzone, "pqissl::Initiate_Connection() Invalid (0.0.0.0) Remote Address, Aborting Connect."); waiting = WAITING_FAIL_INTERFACE; @@ -1279,7 +1281,7 @@ int pqissl::Authorise_SSL_Connection() return 0; } -int pqissl::accept(SSL *ssl, int fd, struct sockaddr_in foreign_addr) // initiate incoming connection. +int pqissl::accept(SSL *ssl, int fd, const struct sockaddr_storage &foreign_addr) // initiate incoming connection. { if (waiting != WAITING_NOT) { @@ -1373,13 +1375,14 @@ int pqissl::accept(SSL *ssl, int fd, struct sockaddr_in foreign_addr) // initiat /* check whether it is on the same LAN */ - struct sockaddr_in localaddr = mLinkMgr->getLocalAddress(); - sameLAN = isSameSubnet(&(remote_addr.sin_addr), &(localaddr.sin_addr)); + struct sockaddr_storage localaddr; + mLinkMgr->getLocalAddress(localaddr); + sameLAN = sockaddr_storage_samesubnet(remote_addr, localaddr); { std::string out = "pqissl::accept() SUCCESSFUL connection to: " + PeerId(); - out += " localaddr: " + rs_inet_ntoa(localaddr.sin_addr); - out += " remoteaddr: " + rs_inet_ntoa(remote_addr.sin_addr); + out += " localaddr: " + sockaddr_storage_iptostring(localaddr); + out += " remoteaddr: " + sockaddr_storage_iptostring(remote_addr); if (sameLAN) { diff --git a/libretroshare/src/pqi/pqissl.h b/libretroshare/src/pqi/pqissl.h index 58aa84f17..af9068a0a 100644 --- a/libretroshare/src/pqi/pqissl.h +++ b/libretroshare/src/pqi/pqissl.h @@ -93,12 +93,12 @@ public: virtual ~pqissl(); // NetInterface -virtual int connect(struct sockaddr_in raddr); +virtual int connect(const struct sockaddr_storage &raddr); virtual int listen(); virtual int stoplistening(); virtual int reset(); virtual int disconnect(); -virtual int getConnectAddress(struct sockaddr_in &raddr); +virtual int getConnectAddress(struct sockaddr_storage &raddr); virtual bool connect_parameter(uint32_t type, const std::string &value); virtual bool connect_parameter(uint32_t type, uint32_t value); @@ -152,7 +152,7 @@ public: * the listener (should make friends??) */ -int accept(SSL *ssl, int fd, struct sockaddr_in foreign_addr); +int accept(SSL *ssl, int fd, const struct sockaddr_storage &foreign_addr); void getCryptoParams(RsPeerCryptoParams& params) ; @@ -175,7 +175,7 @@ virtual int net_internal_fcntl_nonblock(int fd) { return unix_fcntl_nonblock(fd) int sockfd; pqissllistener *pqil; - struct sockaddr_in remote_addr; + struct sockaddr_storage remote_addr; void *readpkt; int pktlen; @@ -199,7 +199,7 @@ virtual int net_internal_fcntl_nonblock(int fd) { return unix_fcntl_nonblock(fd) private: // ssl only fns. -int connectInterface(sockaddr_in&); +int connectInterface(const struct sockaddr_storage &addr); }; diff --git a/libretroshare/src/pqi/pqissllistener.cc b/libretroshare/src/pqi/pqissllistener.cc index 9d0a4288a..49db80942 100644 --- a/libretroshare/src/pqi/pqissllistener.cc +++ b/libretroshare/src/pqi/pqissllistener.cc @@ -55,7 +55,7 @@ const int pqissllistenzone = 49787; */ -pqissllistenbase::pqissllistenbase(struct sockaddr_in addr, p3PeerMgr *pm) +pqissllistenbase::pqissllistenbase(const struct sockaddr_storage &addr, p3PeerMgr *pm) :laddr(addr), active(false), mPeerMgr(pm) { @@ -87,7 +87,7 @@ int pqissllistenbase::tick() int pqissllistenbase::status() { std::string out; - rs_sprintf(out, "pqissllistenbase::status(): Listening on port: %u", ntohs(laddr.sin_port)); + rs_sprintf(out, "pqissllistenbase::status(): Listening on port: %u", sockaddr_storage_port(laddr)); pqioutput(PQL_DEBUG_ALL, pqissllistenzone, out); return 1; } @@ -146,16 +146,11 @@ int pqissllistenbase::setuplisten() // setup listening address. - // fill in fconstant bits. - - laddr.sin_family = AF_INET; - { std::string out = "pqissllistenbase::setuplisten()\n"; - rs_sprintf_append(out, "\tAddress Family: %d\n", (int) laddr.sin_family); - rs_sprintf_append(out, "\tSetup Address: %s\n", rs_inet_ntoa(laddr.sin_addr).c_str()); - rs_sprintf_append(out, "\tSetup Port: %u", ntohs(laddr.sin_port)); - + out += "\t FAMILY: " + sockaddr_storage_familytostring(laddr); + out += "\t ADDRESS: " + sockaddr_storage_tostring(laddr); + pqioutput(PQL_DEBUG_BASIC, pqissllistenzone, out); //std::cerr << out.str() << std::endl; } @@ -185,8 +180,8 @@ int pqissllistenbase::setuplisten() } #ifdef OPEN_UNIVERSAL_PORT - struct sockaddr_in tmpaddr = laddr; - tmpaddr.sin_addr.s_addr = 0; + struct sockaddr_storage tmpaddr = laddr; + sockaddr_storage_zeroip(tmpaddr); if (0 != (err = bind(lsock, (struct sockaddr *) &tmpaddr, sizeof(tmpaddr)))) #else if (0 != (err = bind(lsock, (struct sockaddr *) &laddr, sizeof(laddr)))) @@ -268,7 +263,7 @@ int pqissllistenbase::setuplisten() return 1; } -int pqissllistenbase::setListenAddr(struct sockaddr_in addr) +int pqissllistenbase::setListenAddr(const struct sockaddr_storage &addr) { laddr = addr; return 1; @@ -305,7 +300,7 @@ int pqissllistenbase::acceptconnection() // These are local but temp variables... // can't be arsed making them all the time. - struct sockaddr_in remote_addr; + struct sockaddr_storage remote_addr; socklen_t addrlen = sizeof(remote_addr); int fd = accept(lsock, (struct sockaddr *) &remote_addr, &addrlen); int err = 0; @@ -356,7 +351,8 @@ int pqissllistenbase::acceptconnection() { std::string out; - rs_sprintf(out, "Accepted Connection from %s:%u", rs_inet_ntoa(remote_addr.sin_addr).c_str(), ntohs(remote_addr.sin_port)); + out += "Accepted Connection from "; + out += sockaddr_storage_tostring(remote_addr); pqioutput(PQL_DEBUG_BASIC, pqissllistenzone, out); } @@ -507,12 +503,14 @@ int pqissllistenbase::Extract_Failed_SSL_Certificate(const IncomingSSLInfo& inf std::cerr << " GPG id = " << info.gpgid << std::endl; std::cerr << " SSL id = " << info.sslid << std::endl; std::cerr << " SSL cn = " << info.sslcn << std::endl; - std::cerr << " addr+p = " << rs_inet_ntoa(info.addr.sin_addr) << ":" << ntohs(info.addr.sin_port) << std::endl; + std::cerr << " addr+p = " << sockaddr_storage_tostring(info.addr) << std::endl; if (peercert == NULL) { std::string out; - rs_sprintf(out, "pqissllistenbase::Extract_Failed_SSL_Certificate() from: %s:%u ERROR Peer didn't give Cert!", rs_inet_ntoa(info.addr.sin_addr).c_str(), ntohs(info.addr.sin_port)); + out += "pqissllistenbase::Extract_Failed_SSL_Certificate() from: "; + out += sockaddr_storage_tostring(info.addr); + out += " ERROR Peer didn't give Cert!"; std::cerr << out << std::endl; AuthSSL::getAuthSSL()->FailedCertificate(peercert, info.gpgid,info.sslid,info.sslcn,info.addr, true); @@ -525,7 +523,9 @@ int pqissllistenbase::Extract_Failed_SSL_Certificate(const IncomingSSLInfo& inf { std::string out; - rs_sprintf(out, "pqissllistenbase::Extract_Failed_SSL_Certificate() from: %s:%u Passing Cert to AuthSSL() for analysis", rs_inet_ntoa(info.addr.sin_addr).c_str(), ntohs(info.addr.sin_port)); + out += "pqissllistenbase::Extract_Failed_SSL_Certificate() from: "; + out += sockaddr_storage_tostring(info.addr); + out += " Passing Cert to AuthSSL() for analysis"; std::cerr << out << std::endl; pqioutput(PQL_WARNING, pqissllistenzone, out); @@ -675,7 +675,7 @@ int pqissllistenbase::isSSLActive(int /*fd*/, SSL *ssl) * */ -pqissllistener::pqissllistener(struct sockaddr_in addr, p3PeerMgr *lm) +pqissllistener::pqissllistener(const struct sockaddr_storage &addr, p3PeerMgr *lm) :pqissllistenbase(addr, lm) { return; @@ -743,8 +743,9 @@ int pqissllistener::status() // print certificates we are listening for. std::map::iterator it; - std::string out = "pqissllistener::status(): "; - rs_sprintf(out, " Listening (%u) for Certs:", ntohs(laddr.sin_port)); + std::string out = "pqissllistener::status(): Listening ("; + out += sockaddr_storage_tostring(laddr); + out += ") for Certs:"; for(it = listenaddr.begin(); it != listenaddr.end(); it++) { out += "\n" + it -> first ; @@ -820,7 +821,9 @@ int pqissllistener::completeConnection(int fd, IncomingSSLInfo& info) if (found == false) { - std::string out = "No Matching Certificate for Connection:" + rs_inet_ntoa(info.addr.sin_addr) +"\npqissllistenbase: Will shut it down!"; + std::string out = "No Matching Certificate for Connection:"; + out += sockaddr_storage_tostring(info.addr); + out += "\npqissllistenbase: Will shut it down!"; pqioutput(PQL_WARNING, pqissllistenzone, out); // but as it passed the authentication step, @@ -850,13 +853,15 @@ int pqissllistener::completeConnection(int fd, IncomingSSLInfo& info) accepted_ssl.push_back(as); std::string out = "pqissllistener::completeConnection() Successful Connection with: " + newPeerId; - out += " for Connection:" + rs_inet_ntoa(info.addr.sin_addr) + " Adding to WAIT-ACCEPT Queue"; + out += " for Connection:"; + out += sockaddr_storage_tostring(info.addr); + out += " Adding to WAIT-ACCEPT Queue"; pqioutput(PQL_WARNING, pqissllistenzone, out); return 1; } -int pqissllistener::finaliseConnection(int fd, SSL *ssl, std::string peerId, struct sockaddr_in &remote_addr) +int pqissllistener::finaliseConnection(int fd, SSL *ssl, std::string peerId, const struct sockaddr_storage &remote_addr) { std::map::iterator it; @@ -867,13 +872,15 @@ int pqissllistener::finaliseConnection(int fd, SSL *ssl, std::string peerId, str it = listenaddr.find(peerId); if (it == listenaddr.end()) { - out += "No Matching Peer for Connection:" + rs_inet_ntoa(remote_addr.sin_addr); + out += "No Matching Peer for Connection:"; + out += sockaddr_storage_tostring(remote_addr); out += "\npqissllistener => Shutting Down!"; pqioutput(PQL_WARNING, pqissllistenzone, out); return -1; } - out += "Found Matching Peer for Connection:" + rs_inet_ntoa(remote_addr.sin_addr); + out += "Found Matching Peer for Connection:"; + out += sockaddr_storage_tostring(remote_addr); out += "\npqissllistener => Passing to pqissl module!"; pqioutput(PQL_WARNING, pqissllistenzone, out); diff --git a/libretroshare/src/pqi/pqissllistener.h b/libretroshare/src/pqi/pqissllistener.h index 85f6df5af..74260e6e2 100644 --- a/libretroshare/src/pqi/pqissllistener.h +++ b/libretroshare/src/pqi/pqissllistener.h @@ -55,7 +55,7 @@ class AcceptedSSL SSL *mSSL; std::string mPeerId; - struct sockaddr_in mAddr; + struct sockaddr_storage mAddr; time_t mAcceptTS; }; @@ -67,7 +67,7 @@ class pqissllistenbase: public pqilistener public: - pqissllistenbase(struct sockaddr_in addr, p3PeerMgr *pm); + pqissllistenbase(const struct sockaddr_storage &addr, p3PeerMgr *pm); virtual ~pqissllistenbase(); /*************************************/ @@ -75,7 +75,7 @@ virtual ~pqissllistenbase(); virtual int tick(); virtual int status(); -virtual int setListenAddr(struct sockaddr_in addr); +virtual int setListenAddr(const struct sockaddr_storage &addr); virtual int setuplisten(); virtual int resetlisten(); @@ -88,7 +88,7 @@ int finaliseAccepts(); struct IncomingSSLInfo { SSL *ssl ; - sockaddr_in addr ; + sockaddr_storage addr ; std::string gpgid ; std::string sslid ; std::string sslcn ; @@ -100,10 +100,10 @@ int closeConnection(int fd, SSL *ssl); int isSSLActive(int fd, SSL *ssl); virtual int completeConnection(int sockfd, IncomingSSLInfo&) = 0; -virtual int finaliseConnection(int fd, SSL *ssl, std::string peerId, struct sockaddr_in &raddr) = 0; +virtual int finaliseConnection(int fd, SSL *ssl, std::string peerId, const struct sockaddr_storage &raddr) = 0; protected: - struct sockaddr_in laddr; + struct sockaddr_storage laddr; std::list accepted_ssl; private: @@ -126,7 +126,7 @@ class pqissllistener: public pqissllistenbase { public: - pqissllistener(struct sockaddr_in addr, p3PeerMgr *pm); + pqissllistener(const struct sockaddr_storage &addr, p3PeerMgr *pm); virtual ~pqissllistener(); int addlistenaddr(std::string id, pqissl *acc); @@ -136,7 +136,7 @@ int removeListenPort(std::string id); virtual int status(); virtual int completeConnection(int sockfd, IncomingSSLInfo&); -virtual int finaliseConnection(int fd, SSL *ssl, std::string peerId, struct sockaddr_in &raddr); +virtual int finaliseConnection(int fd, SSL *ssl, std::string peerId, const struct sockaddr_storage &raddr); private: diff --git a/libretroshare/src/pqi/pqisslpersongrp.cc b/libretroshare/src/pqi/pqisslpersongrp.cc index 4b771b7b2..5930f5dde 100644 --- a/libretroshare/src/pqi/pqisslpersongrp.cc +++ b/libretroshare/src/pqi/pqisslpersongrp.cc @@ -48,7 +48,7 @@ const int pqipersongrpzone = 354; #include "pqi/pqisslproxy.h" -pqilistener * pqisslpersongrp::locked_createListener(struct sockaddr_in laddr) +pqilistener * pqisslpersongrp::locked_createListener(const struct sockaddr_storage &laddr) { pqilistener *listener = new pqissllistener(laddr, mPeerMgr); return listener; diff --git a/libretroshare/src/pqi/pqisslpersongrp.h b/libretroshare/src/pqi/pqisslpersongrp.h index 02c197eef..eafd2fb73 100644 --- a/libretroshare/src/pqi/pqisslpersongrp.h +++ b/libretroshare/src/pqi/pqisslpersongrp.h @@ -45,7 +45,7 @@ class pqisslpersongrp: public pqipersongrp protected: /********* FUNCTIONS to OVERLOAD for specialisation ********/ -virtual pqilistener *locked_createListener(struct sockaddr_in laddr); +virtual pqilistener *locked_createListener(const struct sockaddr_storage &laddr); virtual pqiperson *locked_createPerson(std::string id, pqilistener *listener); /********* FUNCTIONS to OVERLOAD for specialisation ********/ diff --git a/libretroshare/src/pqi/pqisslproxy.cc b/libretroshare/src/pqi/pqisslproxy.cc index 5cfd391cd..a450d3cb1 100755 --- a/libretroshare/src/pqi/pqisslproxy.cc +++ b/libretroshare/src/pqi/pqisslproxy.cc @@ -51,7 +51,7 @@ const int pqisslproxyzone = 3517; pqisslproxy::pqisslproxy(pqissllistener *l, PQInterface *parent, p3LinkMgr *lm) :pqissl(l, parent, lm) { - sockaddr_clear(&remote_addr); + sockaddr_storage_clear(remote_addr); return; } diff --git a/libretroshare/src/pqi/pqissludp.cc b/libretroshare/src/pqi/pqissludp.cc index a7b6ab354..bf2d8747f 100644 --- a/libretroshare/src/pqi/pqissludp.cc +++ b/libretroshare/src/pqi/pqissludp.cc @@ -54,7 +54,7 @@ pqissludp::pqissludp(PQInterface *parent, p3LinkMgr *lm) :pqissl(NULL, parent, lm), tou_bio(NULL), listen_checktime(0), mConnectPeriod(PQI_SSLUDP_DEF_CONN_PERIOD) { - sockaddr_clear(&remote_addr); + sockaddr_storage_clear(remote_addr); return; } @@ -150,7 +150,7 @@ int pqissludp::Initiate_Connection() int err; attach(); /* open socket */ - remote_addr.sin_family = AF_INET; + //remote_addr.sin_family = AF_INET; rslog(RSL_DEBUG_BASIC, pqissludpzone, "pqissludp::Initiate_Connection() Attempting Outgoing Connection...."); @@ -196,7 +196,10 @@ int pqissludp::Initiate_Connection() { std::string out = "pqissludp::Initiate_Connection() Connecting To: " + PeerId(); - rs_sprintf(out, " via: %s:%u", rs_inet_ntoa(remote_addr.sin_addr).c_str(), ntohs(remote_addr.sin_port)); + out += " via: "; + out += sockaddr_storage_tostring(remote_addr); + out += " "; + if (sslmode) { out += "ACTIVE Connect (SSL_Connect)"; @@ -208,7 +211,7 @@ int pqissludp::Initiate_Connection() rslog(RSL_WARNING, pqissludpzone, out); } - if (remote_addr.sin_addr.s_addr == 0) + if (sockaddr_storage_isnull(remote_addr)) { rslog(RSL_WARNING, pqissludpzone, "pqissludp::Initiate_Connection() Invalid (0.0.0.0) Remote Address, Aborting Connect."); waiting = WAITING_FAIL_INTERFACE; @@ -234,11 +237,48 @@ int pqissludp::Initiate_Connection() else if (mConnectFlags & RS_CB_FLAG_MODE_UDP_RELAY) { std::cerr << "Calling tou_connect_via_relay("; - std::cerr << mConnectSrcAddr << ","; - std::cerr << mConnectProxyAddr << ","; - std::cerr << remote_addr << ")" << std::endl; + std::cerr << sockaddr_storage_tostring(mConnectSrcAddr) << ","; + std::cerr << sockaddr_storage_tostring(mConnectProxyAddr) << ","; + std::cerr << sockaddr_storage_tostring(remote_addr) << ")" << std::endl; - tou_connect_via_relay(sockfd, &(mConnectSrcAddr), &(mConnectProxyAddr), &(remote_addr)); + + { + std::cerr << "CONVERTING ALL ADDRESSES TO IPV4: TODO make IPV6"; + std::cerr << std::endl; + + struct sockaddr_in srcaddr; + struct sockaddr_in proxyaddr; + struct sockaddr_in remoteaddr; + + if ((mConnectSrcAddr.ss_family != AF_INET) || + (mConnectProxyAddr.ss_family != AF_INET) || + (remote_addr.ss_family != AF_INET)) + { + std::cerr << "Error One Address is not IPv4. aborting"; + std::cerr << std::endl; + abort(); + } + + struct sockaddr_in *rap = (struct sockaddr_in *) &remote_addr; + struct sockaddr_in *pap = (struct sockaddr_in *) &mConnectProxyAddr; + struct sockaddr_in *sap = (struct sockaddr_in *) &mConnectSrcAddr; + + srcaddr.sin_family = AF_INET; + proxyaddr.sin_family = AF_INET; + remoteaddr.sin_family = AF_INET; + + srcaddr.sin_addr = sap->sin_addr; + proxyaddr.sin_addr = pap->sin_addr; + remoteaddr.sin_addr = rap->sin_addr; + + srcaddr.sin_port = sap->sin_port; + proxyaddr.sin_port = pap->sin_port; + remoteaddr.sin_port = rap->sin_port; + + tou_connect_via_relay(sockfd, &srcaddr, &proxyaddr, &remoteaddr); + + } + /*** It seems that the UDP Layer sees x 1.2 the traffic of the SSL layer. * We need to compensate somewhere... we drop the maximum traffic to 75% of limit @@ -472,15 +512,16 @@ bool pqissludp::connect_parameter(uint32_t type, uint32_t value) return pqissl::connect_parameter(type, value); } -bool pqissludp::connect_additional_address(uint32_t type, struct sockaddr_in *addr) +bool pqissludp::connect_additional_address(uint32_t type, const struct sockaddr_storage &addr) { if (type == NET_PARAM_CONNECT_PROXY) { std::string out; - rs_sprintf(out, "pqissludp::connect_additional_address() Peer: %s PROXYADDR: %s:%u", PeerId().c_str(), rs_inet_ntoa(addr->sin_addr).c_str(), ntohs(addr->sin_port)); + rs_sprintf(out, "pqissludp::connect_additional_address() Peer: %s PROXYADDR: ", PeerId().c_str()); + out += sockaddr_storage_tostring(addr); rslog(RSL_WARNING, pqissludpzone, out); - mConnectProxyAddr = *addr; + mConnectProxyAddr = addr; std::cerr << out << std::endl; return true; @@ -488,10 +529,11 @@ bool pqissludp::connect_additional_address(uint32_t type, struct sockaddr_in *ad else if (type == NET_PARAM_CONNECT_SOURCE) { std::string out; - rs_sprintf(out, "pqissludp::connect_additional_address() Peer: %s SRCADDR: %s:%u", PeerId().c_str(), rs_inet_ntoa(addr->sin_addr).c_str(), ntohs(addr->sin_port)); + rs_sprintf(out, "pqissludp::connect_additional_address() Peer: %s SRCADDR: ", PeerId().c_str()); + out += sockaddr_storage_tostring(addr); rslog(RSL_WARNING, pqissludpzone, out); - mConnectSrcAddr = *addr; + mConnectSrcAddr = addr; std::cerr << out << std::endl; return true; diff --git a/libretroshare/src/pqi/pqissludp.h b/libretroshare/src/pqi/pqissludp.h index f07632dd4..10498840a 100644 --- a/libretroshare/src/pqi/pqissludp.h +++ b/libretroshare/src/pqi/pqissludp.h @@ -67,7 +67,7 @@ virtual int tick(); virtual int reset(); virtual bool connect_parameter(uint32_t type, uint32_t value); -virtual bool connect_additional_address(uint32_t type, struct sockaddr_in *addr); +virtual bool connect_additional_address(uint32_t type, const struct sockaddr_storage &addr); // BinInterface. // These are reimplemented. @@ -103,8 +103,8 @@ private: uint32_t mConnectFlags; uint32_t mConnectBandwidth; - struct sockaddr_in mConnectProxyAddr; - struct sockaddr_in mConnectSrcAddr; + struct sockaddr_storage mConnectProxyAddr; + struct sockaddr_storage mConnectSrcAddr; }; #endif // MRK_PQI_SSL_UDP_HEADER diff --git a/libretroshare/src/rsserver/p3peers.cc b/libretroshare/src/rsserver/p3peers.cc index e0385fd35..8854c3f25 100644 --- a/libretroshare/src/rsserver/p3peers.cc +++ b/libretroshare/src/rsserver/p3peers.cc @@ -324,10 +324,10 @@ bool p3Peers::getPeerDetails(const std::string &id, RsPeerDetails &d) d.isHiddenNode = false; d.hiddenNodeAddress = ""; - d.localAddr = rs_inet_ntoa(ps.localaddr.sin_addr); - d.localPort = ntohs(ps.localaddr.sin_port); - d.extAddr = rs_inet_ntoa(ps.serveraddr.sin_addr); - d.extPort = ntohs(ps.serveraddr.sin_port); + d.localAddr = sockaddr_storage_iptostring(ps.localaddr); + d.localPort = sockaddr_storage_port(ps.localaddr); + d.extAddr = sockaddr_storage_iptostring(ps.serveraddr); + d.extPort = sockaddr_storage_port(ps.serveraddr); d.dyndns = ps.dyndns; std::list::iterator it; @@ -335,15 +335,19 @@ bool p3Peers::getPeerDetails(const std::string &id, RsPeerDetails &d) it != ps.ipAddrs.mLocal.mAddrs.end(); it++) { std::string toto; - rs_sprintf(toto, "%u %ld sec", ntohs(it->mAddr.sin_port), time(NULL) - it->mSeenTime); - d.ipAddressList.push_back("L:" + rs_inet_ntoa(it->mAddr.sin_addr) + ":" + toto); + toto += "L:"; + toto += sockaddr_storage_tostring(it->mAddr); + rs_sprintf_append(toto, " %ld sec", time(NULL) - it->mSeenTime); + d.ipAddressList.push_back(toto); } for(it = ps.ipAddrs.mExt.mAddrs.begin(); it != ps.ipAddrs.mExt.mAddrs.end(); it++) { std::string toto; - rs_sprintf(toto, "%u %ld sec", ntohs(it->mAddr.sin_port), time(NULL) - it->mSeenTime); - d.ipAddressList.push_back("E:" + rs_inet_ntoa(it->mAddr.sin_addr) + ":" + toto); + toto += "E:"; + toto += sockaddr_storage_tostring(it->mAddr); + rs_sprintf_append(toto, " %ld sec", time(NULL) - it->mSeenTime); + d.ipAddressList.push_back(toto); } } @@ -420,10 +424,10 @@ bool p3Peers::getPeerDetails(const std::string &id, RsPeerDetails &d) { 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)); + d.connectStateString = sockaddr_storage_tostring(pcs.currentConnAddrAttempt.addr); } else if (pcs.currentConnAddrAttempt.type & RS_NET_CONN_UDP_ALL) { d.connectState = RS_PEER_CONNECTSTATE_TRYING_UDP; - rs_sprintf(d.connectStateString, "%s:%u", rs_inet_ntoa(pcs.currentConnAddrAttempt.addr.sin_addr).c_str(), ntohs(pcs.currentConnAddrAttempt.addr.sin_port)); + d.connectStateString = sockaddr_storage_tostring(pcs.currentConnAddrAttempt.addr); } } else if (pcs.state & RS_PEER_S_CONNECTED) @@ -782,16 +786,17 @@ bool p3Peers::setLocalAddress(const std::string &id, const std::string &addr_st std::cerr << "p3Peers::setLocalAddress() " << id << std::endl; #endif - struct sockaddr_in addr; - addr.sin_family = AF_INET; - addr.sin_port = htons(port); + struct sockaddr_storage addr; + struct sockaddr_in *addrv4p = (struct sockaddr_in *) &addr; + addrv4p->sin_family = AF_INET; + addrv4p->sin_port = htons(port); int ret = 1; /********************************** WINDOWS/UNIX SPECIFIC PART *******************/ #ifndef WINDOWS_SYS - if (ret && (0 != inet_aton(addr_str.c_str(), &(addr.sin_addr)))) + if (ret && (0 != inet_aton(addr_str.c_str(), &(addrv4p->sin_addr)))) #else - addr.sin_addr.s_addr = inet_addr(addr_str.c_str()); + addrv4p->sin_addr.s_addr = inet_addr(addr_str.c_str()); if (ret) #endif /********************************** WINDOWS/UNIX SPECIFIC PART *******************/ @@ -807,16 +812,18 @@ bool p3Peers::setExtAddress(const std::string &id, const std::string &addr_str, std::cerr << "p3Peers::setExtAddress() " << id << std::endl; #endif - struct sockaddr_in addr; - addr.sin_family = AF_INET; - addr.sin_port = htons(port); + // NOTE THIS IS IPV4 FOR NOW. + struct sockaddr_storage addr; + struct sockaddr_in *addrv4p = (struct sockaddr_in *) &addr; + addrv4p->sin_family = AF_INET; + addrv4p->sin_port = htons(port); int ret = 1; /********************************** WINDOWS/UNIX SPECIFIC PART *******************/ #ifndef WINDOWS_SYS - if (ret && (0 != inet_aton(addr_str.c_str(), &(addr.sin_addr)))) + if (ret && (0 != inet_aton(addr_str.c_str(), &(addrv4p->sin_addr)))) #else - addr.sin_addr.s_addr = inet_addr(addr_str.c_str()); + addrv4p->sin_addr.s_addr = inet_addr(addr_str.c_str()); if (ret) #endif /********************************** WINDOWS/UNIX SPECIFIC PART *******************/ diff --git a/libretroshare/src/rsserver/p3serverconfig.cc b/libretroshare/src/rsserver/p3serverconfig.cc index 617a0d611..180483bc2 100644 --- a/libretroshare/src/rsserver/p3serverconfig.cc +++ b/libretroshare/src/rsserver/p3serverconfig.cc @@ -150,11 +150,11 @@ int p3ServerConfig::getConfigNetStatus(RsConfigNetStatus &status) peerState pstate; mPeerMgr->getOwnNetStatus(pstate); - status.localAddr = rs_inet_ntoa(pstate.localaddr.sin_addr); - status.localPort = ntohs(pstate.localaddr.sin_port); + status.localAddr = sockaddr_storage_iptostring(pstate.localaddr); + status.localPort = sockaddr_storage_port(pstate.localaddr); - status.extAddr = rs_inet_ntoa(pstate.serveraddr.sin_addr); - status.extPort = ntohs(pstate.serveraddr.sin_port); + status.extAddr = sockaddr_storage_iptostring(pstate.serveraddr); + status.extPort = sockaddr_storage_port(pstate.serveraddr); status.extDynDns = pstate.dyndns; status.firewalled = true; diff --git a/libretroshare/src/rsserver/rsinit.cc b/libretroshare/src/rsserver/rsinit.cc index b1e4b146d..ec772ec2f 100644 --- a/libretroshare/src/rsserver/rsinit.cc +++ b/libretroshare/src/rsserver/rsinit.cc @@ -2568,16 +2568,18 @@ int RsServer::StartupRetroShare() if (RsInitConfig::forceLocalAddr) { - struct sockaddr_in laddr; + struct sockaddr_storage laddr; /* clean sockaddr before setting values (MaxOSX) */ - sockaddr_clear(&laddr); + sockaddr_storage_clear(laddr); - laddr.sin_family = AF_INET; - laddr.sin_port = htons(RsInitConfig::port); + struct sockaddr_in *lap = (struct sockaddr_in *) &laddr; + + lap->sin_family = AF_INET; + lap->sin_port = htons(RsInitConfig::port); // universal - laddr.sin_addr.s_addr = inet_addr(RsInitConfig::inet.c_str()); + lap->sin_addr.s_addr = inet_addr(RsInitConfig::inet.c_str()); mPeerMgr->setLocalAddress(ownId, laddr); } diff --git a/libretroshare/src/serialiser/rsconfigitems.cc b/libretroshare/src/serialiser/rsconfigitems.cc index 774b7c433..a5b5ab03a 100644 --- a/libretroshare/src/serialiser/rsconfigitems.cc +++ b/libretroshare/src/serialiser/rsconfigitems.cc @@ -37,8 +37,6 @@ #include -// For transition. -RsPeerNetItem *convertToNetItem(RsPeerOldNetItem *old); /*************************************************************************/ @@ -683,16 +681,11 @@ RsPeerConfigSerialiser::~RsPeerConfigSerialiser() uint32_t RsPeerConfigSerialiser::size(RsItem *i) { - RsPeerOldNetItem *oldpni; RsPeerStunItem *psi; RsPeerNetItem *pni; RsPeerGroupItem *pgi; RsPeerServicePermissionItem *pri; - if (NULL != (oldpni = dynamic_cast(i))) - { - return sizeOldNet(oldpni); - } if (NULL != (pni = dynamic_cast(i))) { return sizeNet(pni); @@ -716,16 +709,11 @@ uint32_t RsPeerConfigSerialiser::size(RsItem *i) /* serialise the data to the buffer */ bool RsPeerConfigSerialiser::serialise(RsItem *i, void *data, uint32_t *pktsize) { - RsPeerOldNetItem *oldpni; RsPeerNetItem *pni; RsPeerStunItem *psi; RsPeerGroupItem *pgi; RsPeerServicePermissionItem *pri; - if (NULL != (oldpni = dynamic_cast(i))) - { - return serialiseOldNet(oldpni, data, pktsize); - } if (NULL != (pni = dynamic_cast(i))) { return serialiseNet(pni, data, pktsize); @@ -761,13 +749,8 @@ RsItem *RsPeerConfigSerialiser::deserialise(void *data, uint32_t *pktsize) return NULL; /* wrong type */ } - RsPeerOldNetItem *old = NULL; switch(getRsItemSubType(rstype)) { - case RS_PKT_SUBTYPE_PEER_OLD_NET: - old = deserialiseOldNet(data, pktsize); - /* upgrade mechanism */ - return convertToNetItem(old); case RS_PKT_SUBTYPE_PEER_NET: return deserialiseNet(data, pktsize); case RS_PKT_SUBTYPE_PEER_STUN: @@ -783,260 +766,6 @@ RsItem *RsPeerConfigSerialiser::deserialise(void *data, uint32_t *pktsize) } -/*************************************************************************/ - -RsPeerOldNetItem::~RsPeerOldNetItem() -{ - return; -} - -void RsPeerOldNetItem::clear() -{ - pid.clear(); - gpg_id.clear(); - location.clear(); - netMode = 0; - visState = 0; - lastContact = 0; - - sockaddr_clear(¤tlocaladdr); - sockaddr_clear(¤tremoteaddr); - dyndns.clear(); -} - -std::ostream &RsPeerOldNetItem::print(std::ostream &out, uint16_t indent) -{ - printRsItemBase(out, "RsPeerOldNetItem", indent); - uint16_t int_Indent = indent + 2; - - printIndent(out, int_Indent); - out << "PeerId: " << pid << std::endl; - - printIndent(out, int_Indent); - out << "GPGid: " << gpg_id << std::endl; - - printIndent(out, int_Indent); - out << "location: " << location << std::endl; - - printIndent(out, int_Indent); - out << "netMode: " << netMode << std::endl; - - printIndent(out, int_Indent); - out << "visState: " << visState << std::endl; - - printIndent(out, int_Indent); - out << "lastContact: " << lastContact << std::endl; - - printIndent(out, int_Indent); - out << "currentlocaladdr: " << rs_inet_ntoa(currentlocaladdr.sin_addr); - out << ":" << htons(currentlocaladdr.sin_port) << std::endl; - - printIndent(out, int_Indent); - out << "currentremoteaddr: " << rs_inet_ntoa(currentremoteaddr.sin_addr); - out << ":" << htons(currentremoteaddr.sin_port) << std::endl; - - printIndent(out, int_Indent); - out << "DynDNS: " << dyndns << std::endl; - - printIndent(out, int_Indent); - out << "ipAdressList: size : " << ipAddressList.size() << ", adresses : " << std::endl; - for (std::list::iterator ipListIt = ipAddressList.begin(); ipListIt!=(ipAddressList.end()); ipListIt++) { - printIndent(out, int_Indent); - out << rs_inet_ntoa(ipListIt->ipAddr.sin_addr) << ":" << ntohs(ipListIt->ipAddr.sin_port) << " seenTime : " << ipListIt->seenTime << std::endl; - } - - printRsItemEnd(out, "RsPeerOldNetItem", indent); - return out; -} - -/*************************************************************************/ - -uint32_t RsPeerConfigSerialiser::sizeOldNet(RsPeerOldNetItem *i) -{ - uint32_t s = 8; /* header */ - s += GetTlvStringSize(i->pid); /* peerid */ - s += GetTlvStringSize(i->gpg_id); - s += GetTlvStringSize(i->location); - s += 4; /* netMode */ - s += 4; /* visState */ - s += 4; /* lastContact */ - s += GetTlvIpAddrPortV4Size(); /* localaddr */ - s += GetTlvIpAddrPortV4Size(); /* remoteaddr */ - s += GetTlvStringSize(i->dyndns); - - //add the size of the ip list - int ipListSize = i->ipAddressList.size(); - s += ipListSize * GetTlvIpAddrPortV4Size(); - s += ipListSize * 8; //size of an uint64 - - return s; - -} - -bool RsPeerConfigSerialiser::serialiseOldNet(RsPeerOldNetItem *item, void *data, uint32_t *size) -{ - uint32_t tlvsize = RsPeerConfigSerialiser::sizeOldNet(item); - uint32_t offset = 0; - -#ifdef RSSERIAL_ERROR_DEBUG - std::cerr << "RsPeerConfigSerialiser::serialiseOldNet() ERROR should never use this function" << std::endl; -#endif - - if(*size < tlvsize) - return false; /* not enough space */ - - *size = tlvsize; - - bool ok = true; - - // serialise header - - ok &= setRsItemHeader(data, tlvsize, item->PacketId(), tlvsize); - -#ifdef RSSERIAL_DEBUG - std::cerr << "RsPeerConfigSerialiser::serialiseOldNet() Header: " << ok << std::endl; - std::cerr << "RsPeerConfigSerialiser::serialiseOldNet() Header test: " << tlvsize << std::endl; -#endif - - /* skip the header */ - offset += 8; - - /* add mandatory parts first */ - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_PEERID, item->pid); /* Mandatory */ - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_GPGID, item->gpg_id); /* Mandatory */ - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_LOCATION, item->location); /* Mandatory */ - ok &= setRawUInt32(data, tlvsize, &offset, item->netMode); /* Mandatory */ - ok &= setRawUInt32(data, tlvsize, &offset, item->visState); /* Mandatory */ - ok &= setRawUInt32(data, tlvsize, &offset, item->lastContact); /* Mandatory */ - ok &= SetTlvIpAddrPortV4(data, tlvsize, &offset, TLV_TYPE_IPV4_LOCAL, &(item->currentlocaladdr)); - ok &= SetTlvIpAddrPortV4(data, tlvsize, &offset, TLV_TYPE_IPV4_REMOTE, &(item->currentremoteaddr)); - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_DYNDNS, item->dyndns); - - //store the ip list - std::list::iterator ipListIt; - for (ipListIt = item->ipAddressList.begin(); ipListIt!=(item->ipAddressList.end()); ipListIt++) { - ok &= SetTlvIpAddrPortV4(data, tlvsize, &offset, TLV_TYPE_IPV4_REMOTE, &(ipListIt->ipAddr)); - ok &= setRawUInt64(data, tlvsize, &offset, ipListIt->seenTime); - } - - if(offset != tlvsize) - { - ok = false; -#ifdef RSSERIAL_ERROR_DEBUG - std::cerr << "RsPeerConfigSerialiser::serialise() Size Error! " << std::endl; -#endif - } - - return ok; - -} - -RsPeerOldNetItem *RsPeerConfigSerialiser::deserialiseOldNet(void *data, uint32_t *size) -{ - /* get the type and size */ - uint32_t rstype = getRsItemId(data); - uint32_t rssize = getRsItemSize(data); - - uint32_t offset = 0; - -#ifdef RSSERIAL_ERROR_DEBUG - std::cerr << "RsPeerConfigSerialiser::serialiseOldNet() ERROR should never use this function" << std::endl; -#endif - - if ((RS_PKT_VERSION1 != getRsItemVersion(rstype)) || - (RS_PKT_CLASS_CONFIG != getRsItemClass(rstype)) || - (RS_PKT_TYPE_PEER_CONFIG != getRsItemType(rstype)) || - (RS_PKT_SUBTYPE_PEER_OLD_NET != getRsItemSubType(rstype))) - { - return NULL; /* wrong type */ - } - - if (*size < rssize) /* check size */ - return NULL; /* not enough data */ - - /* set the packet length */ - *size = rssize; - - bool ok = true; - - RsPeerOldNetItem *item = new RsPeerOldNetItem(); - item->clear(); - - /* skip the header */ - offset += 8; - - /* get mandatory parts first */ - ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_PEERID, item->pid); /* Mandatory */ - ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_GPGID, item->gpg_id); /* Mandatory */ - ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_LOCATION, item->location); /* Mandatory */ - ok &= getRawUInt32(data, rssize, &offset, &(item->netMode)); /* Mandatory */ - ok &= getRawUInt32(data, rssize, &offset, &(item->visState)); /* Mandatory */ - ok &= getRawUInt32(data, rssize, &offset, &(item->lastContact)); /* Mandatory */ - ok &= GetTlvIpAddrPortV4(data, rssize, &offset, TLV_TYPE_IPV4_LOCAL, &(item->currentlocaladdr)); - ok &= GetTlvIpAddrPortV4(data, rssize, &offset, TLV_TYPE_IPV4_REMOTE, &(item->currentremoteaddr)); - //ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_DYNDNS, item->dyndns); - GetTlvString(data, rssize, &offset, TLV_TYPE_STR_DYNDNS, item->dyndns); //use this line for backward compatibility - - //get the ip adress list - std::list ipTimedList; - while (offset < rssize) { - IpAddressTimed ipTimed; - sockaddr_clear(&ipTimed.ipAddr); - ok &= GetTlvIpAddrPortV4(data, rssize, &offset, TLV_TYPE_IPV4_REMOTE, &ipTimed.ipAddr); - if (!ok) { break;} - uint64_t time = 0; - ok &= getRawUInt64(data, rssize, &offset, &time); - if (!ok) { break;} - ipTimed.seenTime = time; - ipTimedList.push_back(ipTimed); - } - item->ipAddressList = ipTimedList; - - //if (offset != rssize) - if (false) //use this line for backward compatibility - { - - /* error */ - delete item; - return NULL; - } - - return item; -} - -/****************************************************************************/ -RsPeerNetItem *convertToNetItem(RsPeerOldNetItem *old) -{ - RsPeerNetItem *item = new RsPeerNetItem(); - - /* copy over data */ - item->pid = old->pid; - item->gpg_id = old->gpg_id; - item->location = old->location; - item->netMode = old->netMode; - item->visState = old->visState; - item->lastContact = old->lastContact; - - item->currentlocaladdr = old->currentlocaladdr; - item->currentremoteaddr = old->currentremoteaddr; - item->dyndns = old->dyndns; - - std::list::iterator it; - for(it = old->ipAddressList.begin(); it != old->ipAddressList.end(); it++) - { - RsTlvIpAddressInfo info; - info.addr = it->ipAddr; - info.seenTime = it->seenTime; - info.source = 0; - - item->extAddrList.addrs.push_back(info); - } - - /* delete old data */ - delete old; - - return item; -} /****************************************************************************/ @@ -1054,9 +783,9 @@ void RsPeerNetItem::clear() visState = 0; lastContact = 0; - sockaddr_clear(¤tlocaladdr); - sockaddr_clear(¤tremoteaddr); - dyndns.clear(); + localAddr.TlvClear(); + extAddr.TlvClear(); + dyndns.clear(); localAddrList.TlvClear(); extAddrList.TlvClear(); @@ -1089,15 +818,16 @@ std::ostream &RsPeerNetItem::print(std::ostream &out, uint16_t indent) out << "lastContact: " << lastContact << std::endl; printIndent(out, int_Indent); - out << "currentlocaladdr: " << rs_inet_ntoa(currentlocaladdr.sin_addr); - out << ":" << htons(currentlocaladdr.sin_port) << std::endl; + out << "localAddr: " << std::endl; + localAddr.print(out, int_Indent); printIndent(out, int_Indent); - out << "currentremoteaddr: " << rs_inet_ntoa(currentremoteaddr.sin_addr); - out << ":" << htons(currentremoteaddr.sin_port) << std::endl; + out << "extAddr: " << std::endl; + extAddr.print(out, int_Indent); + - printIndent(out, int_Indent); - out << "DynDNS: " << dyndns << std::endl; + printIndent(out, int_Indent); + out << "DynDNS: " << dyndns << std::endl; localAddrList.print(out, int_Indent); extAddrList.print(out, int_Indent); @@ -1117,9 +847,9 @@ uint32_t RsPeerConfigSerialiser::sizeNet(RsPeerNetItem *i) s += 4; /* netMode */ s += 4; /* visState */ s += 4; /* lastContact */ - s += GetTlvIpAddrPortV4Size(); /* localaddr */ - s += GetTlvIpAddrPortV4Size(); /* remoteaddr */ - s += GetTlvStringSize(i->dyndns); + s += i->localAddr.TlvSize(); /* localaddr */ + s += i->extAddr.TlvSize(); /* remoteaddr */ + s += GetTlvStringSize(i->dyndns); //add the size of the ip list s += i->localAddrList.TlvSize(); @@ -1166,21 +896,22 @@ bool RsPeerConfigSerialiser::serialiseNet(RsPeerNetItem *item, void *data, uint3 offset += 8; /* add mandatory parts first */ - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_PEERID, item->pid); /* Mandatory */ - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_GPGID, item->gpg_id); /* Mandatory */ - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_LOCATION, item->location); /* Mandatory */ - ok &= setRawUInt32(data, tlvsize, &offset, item->netMode); /* Mandatory */ + ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_PEERID, item->pid); /* Mandatory */ + ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_GPGID, item->gpg_id); /* Mandatory */ + ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_LOCATION, item->location); /* Mandatory */ + ok &= setRawUInt32(data, tlvsize, &offset, item->netMode); /* Mandatory */ ok &= setRawUInt32(data, tlvsize, &offset, item->visState); /* Mandatory */ ok &= setRawUInt32(data, tlvsize, &offset, item->lastContact); /* Mandatory */ - ok &= SetTlvIpAddrPortV4(data, tlvsize, &offset, TLV_TYPE_IPV4_LOCAL, &(item->currentlocaladdr)); - ok &= SetTlvIpAddrPortV4(data, tlvsize, &offset, TLV_TYPE_IPV4_REMOTE, &(item->currentremoteaddr)); - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_DYNDNS, item->dyndns); + ok &= item->localAddr.SetTlv(data, tlvsize, &offset); + ok &= item->extAddr.SetTlv(data, tlvsize, &offset); + + ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_DYNDNS, item->dyndns); ok &= item->localAddrList.SetTlv(data, tlvsize, &offset); ok &= item->extAddrList.SetTlv(data, tlvsize, &offset); // New for V0.6. - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_DOMADDR, item->domain_addr); + ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_DOMADDR, item->domain_addr); ok &= setRawUInt16(data, tlvsize, &offset, item->domain_port); /* Mandatory */ if(offset != tlvsize) @@ -1239,15 +970,17 @@ RsPeerNetItem *RsPeerConfigSerialiser::deserialiseNet(void *data, uint32_t *size offset += 8; /* get mandatory parts first */ - ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_PEERID, item->pid); /* Mandatory */ - ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_GPGID, item->gpg_id); /* Mandatory */ - ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_LOCATION, item->location); /* Mandatory */ - ok &= getRawUInt32(data, rssize, &offset, &(item->netMode)); /* Mandatory */ + ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_PEERID, item->pid); /* Mandatory */ + ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_GPGID, item->gpg_id); /* Mandatory */ + ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_LOCATION, item->location); /* Mandatory */ + ok &= getRawUInt32(data, rssize, &offset, &(item->netMode)); /* Mandatory */ ok &= getRawUInt32(data, rssize, &offset, &(item->visState)); /* Mandatory */ ok &= getRawUInt32(data, rssize, &offset, &(item->lastContact)); /* Mandatory */ - ok &= GetTlvIpAddrPortV4(data, rssize, &offset, TLV_TYPE_IPV4_LOCAL, &(item->currentlocaladdr)); - ok &= GetTlvIpAddrPortV4(data, rssize, &offset, TLV_TYPE_IPV4_REMOTE, &(item->currentremoteaddr)); - ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_DYNDNS, item->dyndns); + + ok &= item->localAddr.GetTlv(data, rssize, &offset); + ok &= item->extAddr.GetTlv(data, rssize, &offset); + + ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_DYNDNS, item->dyndns); ok &= item->localAddrList.GetTlv(data, rssize, &offset); ok &= item->extAddrList.GetTlv(data, rssize, &offset); diff --git a/libretroshare/src/serialiser/rsconfigitems.h b/libretroshare/src/serialiser/rsconfigitems.h index b979cf8fc..74ce1e9a8 100644 --- a/libretroshare/src/serialiser/rsconfigitems.h +++ b/libretroshare/src/serialiser/rsconfigitems.h @@ -48,9 +48,8 @@ const uint8_t RS_PKT_TYPE_HISTORY_CONFIG = 0x06; const uint8_t RS_PKT_SUBTYPE_KEY_VALUE = 0x01; /* PEER CONFIG SUBTYPES */ -const uint8_t RS_PKT_SUBTYPE_PEER_OLD_NET = 0x01; const uint8_t RS_PKT_SUBTYPE_PEER_STUN = 0x02; -const uint8_t RS_PKT_SUBTYPE_PEER_NET = 0x03; /* replacement for OLD_NET */ +const uint8_t RS_PKT_SUBTYPE_PEER_NET = 0x03; const uint8_t RS_PKT_SUBTYPE_PEER_GROUP = 0x04; const uint8_t RS_PKT_SUBTYPE_PEER_PERMISSIONS = 0x05; @@ -60,38 +59,6 @@ const uint8_t RS_PKT_SUBTYPE_FILE_ITEM = 0x02; /**************************************************************************/ -struct IpAddressTimed { - struct sockaddr_in ipAddr; - time_t seenTime; -}; - -class RsPeerOldNetItem: public RsItem -{ - public: - RsPeerOldNetItem() - :RsItem(RS_PKT_VERSION1, RS_PKT_CLASS_CONFIG, - RS_PKT_TYPE_PEER_CONFIG, - RS_PKT_SUBTYPE_PEER_OLD_NET) - { return; } -virtual ~RsPeerOldNetItem(); -virtual void clear(); -std::ostream &print(std::ostream &out, uint16_t indent = 0); - - /* networking information */ - std::string pid; /* Mandatory */ - std::string gpg_id; /* Mandatory */ - std::string location; /* not Mandatory */ - uint32_t netMode; /* Mandatory */ - uint32_t visState; /* Mandatory */ - uint32_t lastContact; /* Mandatory */ - - struct sockaddr_in currentlocaladdr; /* Mandatory */ - struct sockaddr_in currentremoteaddr; /* Mandatory */ - std::string dyndns; - - std::list ipAddressList; -}; - class RsPeerNetItem: public RsItem { public: @@ -112,8 +79,8 @@ std::ostream &print(std::ostream &out, uint16_t indent = 0); uint32_t visState; /* Mandatory */ uint32_t lastContact; /* Mandatory */ - struct sockaddr_in currentlocaladdr; /* Mandatory */ - struct sockaddr_in currentremoteaddr; /* Mandatory */ + RsTlvIpAddress localAddr; /* Mandatory */ + RsTlvIpAddress extAddr; /* Mandatory */ std::string dyndns; RsTlvIpAddrSet localAddrList; @@ -195,11 +162,6 @@ virtual RsItem * deserialise(void *data, uint32_t *size); private: -/* These are depreciated ... conversion functions used to seemlessly ungrade. - */ -virtual uint32_t sizeOldNet(RsPeerOldNetItem *); -virtual bool serialiseOldNet (RsPeerOldNetItem *item, void *data, uint32_t *size); -virtual RsPeerOldNetItem *deserialiseOldNet(void *data, uint32_t *size); virtual uint32_t sizeNet(RsPeerNetItem *); virtual bool serialiseNet (RsPeerNetItem *item, void *data, uint32_t *size); diff --git a/libretroshare/src/serialiser/rstlvaddrs.cc b/libretroshare/src/serialiser/rstlvaddrs.cc index 6be3b5ec0..12c48f3d5 100644 --- a/libretroshare/src/serialiser/rstlvaddrs.cc +++ b/libretroshare/src/serialiser/rstlvaddrs.cc @@ -35,18 +35,161 @@ #include +/************************************* RsTlvIpAddress ************************************/ + +RsTlvIpAddress::RsTlvIpAddress() + :RsTlvItem() +{ + sockaddr_storage_clear(addr); + return; +} + +void RsTlvIpAddress::TlvClear() +{ + sockaddr_storage_clear(addr); +} + +uint32_t RsTlvIpAddress::TlvSize() +{ + uint32_t s = TLV_HEADER_SIZE; + switch(addr.ss_family) + { + default: + case 0: + break; + case AF_INET: + s += GetTlvIpAddrPortV4Size(); + break; + case AF_INET6: + s += GetTlvIpAddrPortV6Size(); + break; + } + return s; +} + +bool RsTlvIpAddress::SetTlv(void *data, uint32_t size, uint32_t *offset) /* serialise */ +{ + /* must check sizes */ + uint32_t tlvsize = TlvSize(); + uint32_t tlvend = *offset + tlvsize; + + if (size < tlvend) + return false; /* not enough space */ + + bool ok = true; + + /* start at data[offset] */ + /* add mandatory parts first */ + + ok &= SetTlvBase(data, tlvend, offset, TLV_TYPE_ADDRESS, tlvsize); + + switch(addr.ss_family) + { + default: + case 0: + break; + case AF_INET: + ok &= SetTlvIpAddrPortV4(data, tlvend, offset, TLV_TYPE_IPV4, (struct sockaddr_in *) &addr); + break; + + case AF_INET6: + ok &= SetTlvIpAddrPortV6(data, tlvend, offset, TLV_TYPE_IPV6, (struct sockaddr_in6 *) &addr); + break; + } + return ok; + +} + + +bool RsTlvIpAddress::GetTlv(void *data, uint32_t size, uint32_t *offset) /* serialise */ +{ + if (size < *offset + TLV_HEADER_SIZE) + return false; + + uint16_t tlvtype = GetTlvType( &(((uint8_t *) data)[*offset]) ); + uint32_t tlvsize = GetTlvSize( &(((uint8_t *) data)[*offset]) ); + uint32_t tlvend = *offset + tlvsize; + + if (size < tlvend) /* check size */ + return false; /* not enough space */ + + if (tlvtype != TLV_TYPE_ADDRESS) /* check type */ + return false; + + bool ok = true; + + /* ready to load */ + TlvClear(); + + /* skip the header */ + (*offset) += TLV_HEADER_SIZE; + + if (*offset == tlvend) + { + /* empty address */ + return ok; + } + + uint16_t iptype = GetTlvType( &(((uint8_t *) data)[*offset]) ); + switch(iptype) + { + case TLV_TYPE_IPV4: + ok &= GetTlvIpAddrPortV4(data, tlvend, offset, TLV_TYPE_IPV4, (struct sockaddr_in *) &addr); + break; + case TLV_TYPE_IPV6: + ok &= GetTlvIpAddrPortV6(data, tlvend, offset, TLV_TYPE_IPV6, (struct sockaddr_in6 *) &addr); + break; + default: + break; + } + + /*************************************************************************** + * NB: extra components could be added (for future expansion of the type). + * or be present (if this code is reading an extended version). + * + * We must chew up the extra characters to conform with TLV specifications + ***************************************************************************/ + if (*offset != tlvend) + { +#ifdef TLV_DEBUG + std::cerr << "RsTlvIpAddress::GetTlv() Warning extra bytes at end of item"; + std::cerr << std::endl; +#endif + *offset = tlvend; + } + + return ok; + +} + + +std::ostream &RsTlvIpAddress::print(std::ostream &out, uint16_t indent) +{ + printBase(out, "RsTlvIpAddress", indent); + uint16_t int_Indent = indent + 2; + + printIndent(out, int_Indent); + out << "Address:" << sockaddr_storage_tostring(addr) << std::endl; + + printEnd(out, "RsTlvIpAddress", indent); + return out; +} + + + + /************************************* RsTlvIpAddressInfo ************************************/ RsTlvIpAddressInfo::RsTlvIpAddressInfo() :RsTlvItem(), seenTime(0), source(0) { - sockaddr_clear(&addr); + addr.TlvClear(); return; } void RsTlvIpAddressInfo::TlvClear() { - sockaddr_clear(&addr); + addr.TlvClear(); seenTime = 0; source = 0; } @@ -55,7 +198,7 @@ uint32_t RsTlvIpAddressInfo::TlvSize() { uint32_t s = TLV_HEADER_SIZE; /* header + IpAddr + 8 for time & 4 for size */ - s += GetTlvIpAddrPortV4Size(); + s += addr.TlvSize(); s += 8; // seenTime s += 4; // source @@ -79,7 +222,7 @@ bool RsTlvIpAddressInfo::SetTlv(void *data, uint32_t size, uint32_t *offset) /* ok &= SetTlvBase(data, tlvend, offset, TLV_TYPE_ADDRESS_INFO, tlvsize); - ok &= SetTlvIpAddrPortV4(data, tlvend, offset, TLV_TYPE_IPV4_LAST, &addr); + ok &= addr.SetTlv(data, tlvend, offset); ok &= setRawUInt64(data, tlvend, offset, seenTime); ok &= setRawUInt32(data, tlvend, offset, source); @@ -111,7 +254,7 @@ bool RsTlvIpAddressInfo::GetTlv(void *data, uint32_t size, uint32_t *offset) /* /* skip the header */ (*offset) += TLV_HEADER_SIZE; - ok &= GetTlvIpAddrPortV4(data, tlvend, offset, TLV_TYPE_IPV4_LAST, &addr); + ok &= addr.GetTlv(data, tlvend, offset); ok &= getRawUInt64(data, tlvend, offset, &(seenTime)); ok &= getRawUInt32(data, tlvend, offset, &(source)); @@ -141,9 +284,7 @@ std::ostream &RsTlvIpAddressInfo::print(std::ostream &out, uint16_t indent) printBase(out, "RsTlvIpAddressInfo", indent); uint16_t int_Indent = indent + 2; - printIndent(out, int_Indent); - out << "Address:" << rs_inet_ntoa(addr.sin_addr); - out << ":" << htons(addr.sin_port) << std::endl; + addr.print(out, int_Indent); printIndent(out, int_Indent); out << "SeenTime:" << seenTime; diff --git a/libretroshare/src/serialiser/rstlvaddrs.h b/libretroshare/src/serialiser/rstlvaddrs.h index 3de93ad66..e4234108d 100644 --- a/libretroshare/src/serialiser/rstlvaddrs.h +++ b/libretroshare/src/serialiser/rstlvaddrs.h @@ -34,6 +34,20 @@ #include "serialiser/rstlvtypes.h" #include "util/rsnet.h" +class RsTlvIpAddress: public RsTlvItem +{ + public: + RsTlvIpAddress(); +virtual ~RsTlvIpAddress() { return; } +virtual uint32_t TlvSize(); +virtual void TlvClear(); +virtual bool SetTlv(void *data, uint32_t size, uint32_t *offset); /* serialise */ +virtual bool GetTlv(void *data, uint32_t size, uint32_t *offset); /* deserialise */ +virtual std::ostream &print(std::ostream &out, uint16_t indent); + + struct sockaddr_storage addr; // Mandatory : +}; + class RsTlvIpAddressInfo: public RsTlvItem { @@ -46,7 +60,7 @@ virtual bool SetTlv(void *data, uint32_t size, uint32_t *offset); /* seriali virtual bool GetTlv(void *data, uint32_t size, uint32_t *offset); /* deserialise */ virtual std::ostream &print(std::ostream &out, uint16_t indent); - struct sockaddr_in addr; // Mandatory : + RsTlvIpAddress addr; // Mandatory : uint64_t seenTime; // Mandatory : uint32_t source; // Mandatory : }; diff --git a/libretroshare/src/serialiser/rstlvbanlist.cc b/libretroshare/src/serialiser/rstlvbanlist.cc index 3e3446ad0..c69db6b79 100644 --- a/libretroshare/src/serialiser/rstlvbanlist.cc +++ b/libretroshare/src/serialiser/rstlvbanlist.cc @@ -45,7 +45,7 @@ RsTlvBanListEntry::RsTlvBanListEntry() void RsTlvBanListEntry::TlvClear() { - sockaddr_clear(&addr); + addr.TlvClear(); level = 0; reason = 0; age = 0; @@ -55,7 +55,7 @@ uint32_t RsTlvBanListEntry::TlvSize() { uint32_t s = TLV_HEADER_SIZE; - s += GetTlvIpAddrPortV4Size(); + s += addr.TlvSize(); s += 4; // level; s += 4; // reason; s += 4; // age; @@ -80,7 +80,7 @@ bool RsTlvBanListEntry::SetTlv(void *data, uint32_t size, uint32_t *offset) /* ok &= SetTlvBase(data, tlvend, offset, TLV_TYPE_BAN_ENTRY, tlvsize); - ok &= SetTlvIpAddrPortV4(data, tlvend, offset, TLV_TYPE_IPV4_REMOTE, &addr); + ok &= addr.SetTlv(data, tlvend, offset); ok &= setRawUInt32(data, tlvend, offset, level); ok &= setRawUInt32(data, tlvend, offset, reason); ok &= setRawUInt32(data, tlvend, offset, age); @@ -112,7 +112,7 @@ bool RsTlvBanListEntry::GetTlv(void *data, uint32_t size, uint32_t *offset) /* /* skip the header */ (*offset) += TLV_HEADER_SIZE; - ok &= GetTlvIpAddrPortV4(data, tlvend, offset, TLV_TYPE_IPV4_REMOTE, &addr); + ok &= addr.GetTlv(data, tlvend, offset); ok &= getRawUInt32(data, tlvend, offset, &(level)); ok &= getRawUInt32(data, tlvend, offset, &(reason)); ok &= getRawUInt32(data, tlvend, offset, &(age)); @@ -143,8 +143,8 @@ std::ostream &RsTlvBanListEntry::print(std::ostream &out, uint16_t indent) uint16_t int_Indent = indent + 2; printIndent(out, int_Indent); - out << "addr:" << rs_inet_ntoa(addr.sin_addr) << ":" << htons(addr.sin_port); - out << std::endl; + out << "addr:" << std::endl; + addr.print(out, int_Indent); printIndent(out, int_Indent); out << "level:" << level; diff --git a/libretroshare/src/serialiser/rstlvbanlist.h b/libretroshare/src/serialiser/rstlvbanlist.h index 51695f919..40a31e9cb 100644 --- a/libretroshare/src/serialiser/rstlvbanlist.h +++ b/libretroshare/src/serialiser/rstlvbanlist.h @@ -32,6 +32,7 @@ #include #include "serialiser/rstlvtypes.h" +#include "serialiser/rstlvaddrs.h" #include "util/rsnet.h" #define RSDSDV_MAX_ROUTE_TABLE 1000 @@ -47,7 +48,7 @@ virtual bool SetTlv(void *data, uint32_t size, uint32_t *offset); /* seriali virtual bool GetTlv(void *data, uint32_t size, uint32_t *offset); /* deserialise */ virtual std::ostream &print(std::ostream &out, uint16_t indent); - struct sockaddr_in addr; + RsTlvIpAddress addr; uint32_t level; uint32_t reason; uint32_t age; diff --git a/libretroshare/src/serialiser/rstlvbase.cc b/libretroshare/src/serialiser/rstlvbase.cc index 801a2e5ed..f0547c3f8 100644 --- a/libretroshare/src/serialiser/rstlvbase.cc +++ b/libretroshare/src/serialiser/rstlvbase.cc @@ -697,7 +697,7 @@ bool SetTlvIpAddrPortV6(void *data, uint32_t size, uint32_t *offset, { ok &= setRawUInt32(data, tlvend, offset, ip6addr[i]); } - ok &= setRawUInt16(data, tlvend, offset, out->sin_port6); + ok &= setRawUInt16(data, tlvend, offset, out->sin6_port); return ok; } @@ -752,7 +752,7 @@ bool GetTlvIpAddrPortV6(void *data, uint32_t size, uint32_t *offset, uint32_t *ip6addr = (uint32_t *) in->sin6_addr.s6_addr; for(int i = 0; i < 4; i++) { - ok &= getRawUInt32(data, tlvend, offset, ip6addr[i]); + ok &= getRawUInt32(data, tlvend, offset, &(ip6addr[i])); } in->sin6_family = AF_INET6; /* set FAMILY */ diff --git a/libretroshare/src/serialiser/rstlvbase.h b/libretroshare/src/serialiser/rstlvbase.h index efe7c3aac..a7697c6cd 100644 --- a/libretroshare/src/serialiser/rstlvbase.h +++ b/libretroshare/src/serialiser/rstlvbase.h @@ -159,6 +159,10 @@ const uint16_t TLV_TYPE_IPV4_LAST = 0x0082; const uint16_t TLV_TYPE_STR_DYNDNS = 0x0083; const uint16_t TLV_TYPE_STR_DOMADDR = 0x0084; +// rearrange these in the future. +const uint16_t TLV_TYPE_IPV4 = 0x0085; +const uint16_t TLV_TYPE_IPV6 = 0x0086; + /*** MORE STRING IDS ****/ const uint16_t TLV_TYPE_STR_GROUPID = 0x00a0; const uint16_t TLV_TYPE_STR_MSGID = 0x00a1; @@ -202,6 +206,9 @@ const uint16_t TLV_TYPE_WKEYVALUESET = 0x1013; const uint16_t TLV_TYPE_STRINGSET = 0x1020; /* dummy non-existant */ const uint16_t TLV_TYPE_PEERSET = 0x1021; const uint16_t TLV_TYPE_HASHSET = 0x1022; + +const uint16_t TLV_TYPE_PGPIDSET = 0x1023; + const uint16_t TLV_TYPE_SERVICESET = 0x1030; const uint16_t TLV_TYPE_SECURITYKEY = 0x1040; @@ -215,6 +222,7 @@ const uint16_t TLV_TYPE_IMAGE = 0x1060; const uint16_t TLV_TYPE_ADDRESS_INFO = 0x1070; const uint16_t TLV_TYPE_ADDRESS_SET = 0x1071; +const uint16_t TLV_TYPE_ADDRESS = 0x1072; const uint16_t TLV_TYPE_DSDV_ENDPOINT = 0x1080; const uint16_t TLV_TYPE_DSDV_ENTRY = 0x1081; diff --git a/libretroshare/src/services/p3banlist.cc b/libretroshare/src/services/p3banlist.cc index 52beb6ecd..d531a1d3e 100644 --- a/libretroshare/src/services/p3banlist.cc +++ b/libretroshare/src/services/p3banlist.cc @@ -136,14 +136,14 @@ bool p3BanList::recvBanItem(RsBanListItem *item) for(it = item->peerList.entries.begin(); it != item->peerList.entries.end(); it++) { // Order is important!. - updated = (addBanEntry(item->PeerId(), it->addr, it->level, + updated = (addBanEntry(item->PeerId(), it->addr.addr, it->level, it->reason, it->age) || updated); } return updated; } /* overloaded from pqiNetAssistSharePeer */ -void p3BanList::updatePeer(std::string /*id*/, struct sockaddr_in addr, int /*type*/, int /*reason*/, int age) +void p3BanList::updatePeer(std::string /*id*/, const struct sockaddr_storage &addr, int /*type*/, int /*reason*/, int age) { std::string ownId = mLinkMgr->getOwnId(); @@ -160,7 +160,7 @@ void p3BanList::updatePeer(std::string /*id*/, struct sockaddr_in addr, int /*ty } -bool p3BanList::addBanEntry(const std::string &peerId, const struct sockaddr_in &addr, int level, uint32_t reason, uint32_t age) +bool p3BanList::addBanEntry(const std::string &peerId, const struct sockaddr_storage &addr, int level, uint32_t reason, uint32_t age) { RsStackMutex stack(mBanMtx); /****** LOCKED MUTEX *******/ @@ -174,10 +174,10 @@ bool p3BanList::addBanEntry(const std::string &peerId, const struct sockaddr_in #endif /* Only Accept it - if external address */ - if (!isExternalNet(&(addr.sin_addr))) + if (!sockaddr_storage_isExternalNet(addr)) { #ifdef DEBUG_BANLIST - std::cerr << "p3BanList::addBanEntry() Ignoring Non External Addr: " << rs_inet_ntoa(addr.sin_addr); + std::cerr << "p3BanList::addBanEntry() Ignoring Non External Addr: " << sockaddr_storage_iptostring(addr); std::cerr << std::endl; #endif return false; @@ -197,8 +197,14 @@ bool p3BanList::addBanEntry(const std::string &peerId, const struct sockaddr_in updated = true; } - std::map::iterator mit; - mit = it->second.mBanPeers.find(addr.sin_addr.s_addr); + // index is FAMILY + IP - the rest should be Zeros.. + struct sockaddr_storage bannedaddr; + sockaddr_storage_clear(bannedaddr); + sockaddr_storage_copyip(bannedaddr, addr); + sockaddr_storage_setport(bannedaddr, 0); + + std::map::iterator mit; + mit = it->second.mBanPeers.find(bannedaddr); if (mit == it->second.mBanPeers.end()) { /* add in */ @@ -208,7 +214,8 @@ bool p3BanList::addBanEntry(const std::string &peerId, const struct sockaddr_in blp.level = level; blp.mTs = now - age; - it->second.mBanPeers[addr.sin_addr.s_addr] = blp; + + it->second.mBanPeers[bannedaddr] = blp; it->second.mLastUpdate = now; updated = true; } @@ -266,7 +273,7 @@ int p3BanList::condenseBanSources_locked() std::cerr << std::endl; #endif - std::map::const_iterator lit; + std::map::const_iterator lit; for(lit = it->second.mBanPeers.begin(); lit != it->second.mBanPeers.end(); lit++) { @@ -276,7 +283,7 @@ int p3BanList::condenseBanSources_locked() #ifdef DEBUG_BANLIST_CONDENSE std::cerr << "p3BanList::condenseBanSources_locked()"; std::cerr << " Ignoring Out-Of-Date Entry for: "; - std::cerr << rs_inet_ntoa(lit->second.addr.sin_addr); + std::cerr << sockaddr_storage_iptostring(lit->second.addr); std::cerr << std::endl; #endif continue; @@ -289,19 +296,25 @@ int p3BanList::condenseBanSources_locked() lvl++; } + struct sockaddr_storage bannedaddr; + sockaddr_storage_clear(bannedaddr); + sockaddr_storage_copyip(bannedaddr, lit->second.addr); + sockaddr_storage_setport(bannedaddr, 0); + + /* check if it exists in the Set already */ - std::map::iterator sit; - sit = mBanSet.find(lit->second.addr.sin_addr.s_addr); + std::map::iterator sit; + sit = mBanSet.find(bannedaddr); if ((sit == mBanSet.end()) || (lvl < sit->second.level)) { BanListPeer bp = lit->second; bp.level = lvl; - bp.addr.sin_port = 0; - mBanSet[lit->second.addr.sin_addr.s_addr] = bp; + sockaddr_storage_setport(bp.addr, 0); + mBanSet[bannedaddr] = bp; #ifdef DEBUG_BANLIST_CONDENSE std::cerr << "p3BanList::condenseBanSources_locked()"; std::cerr << " Added New Entry for: "; - std::cerr << rs_inet_ntoa(lit->second.addr.sin_addr); + std::cerr << sockaddr_storage_iptostring(bannedaddr); std::cerr << std::endl; #endif } @@ -310,7 +323,7 @@ int p3BanList::condenseBanSources_locked() #ifdef DEBUG_BANLIST_CONDENSE std::cerr << "p3BanList::condenseBanSources_locked()"; std::cerr << " Merging Info for: "; - std::cerr << rs_inet_ntoa(lit->second.addr.sin_addr); + std::cerr << sockaddr_storage_iptostring(bannedaddr); std::cerr << std::endl; #endif /* update if necessary */ @@ -405,7 +418,7 @@ int p3BanList::sendBanSet(std::string peerid) { RsStackMutex stack(mBanMtx); /****** LOCKED MUTEX *******/ - std::map::iterator it; + std::map::iterator it; for(it = mBanSet.begin(); it != mBanSet.end(); it++) { if (it->second.level >= RSBANLIST_SOURCE_FRIEND) @@ -414,7 +427,7 @@ int p3BanList::sendBanSet(std::string peerid) } RsTlvBanListEntry bi; - bi.addr = it->second.addr; + bi.addr.addr = it->second.addr; bi.reason = it->second.reason; bi.level = it->second.level; bi.age = now - it->second.mTs; @@ -435,10 +448,10 @@ int p3BanList::printBanSet_locked(std::ostream &out) time_t now = time(NULL); - std::map::iterator it; + std::map::iterator it; for(it = mBanSet.begin(); it != mBanSet.end(); it++) { - out << "Ban: " << rs_inet_ntoa(it->second.addr.sin_addr); + out << "Ban: " << sockaddr_storage_iptostring(it->second.addr); out << " Reason: " << it->second.reason; out << " Level: " << it->second.level; if (it->second.level > RSBANLIST_SOURCE_FRIEND) @@ -465,12 +478,12 @@ int p3BanList::printBanSources_locked(std::ostream &out) out << " LastUpdate: " << now - it->second.mLastUpdate; out << std::endl; - std::map::const_iterator lit; + std::map::const_iterator lit; for(lit = it->second.mBanPeers.begin(); lit != it->second.mBanPeers.end(); lit++) { out << "\t"; - out << "Ban: " << rs_inet_ntoa(lit->second.addr.sin_addr); + out << "Ban: " << sockaddr_storage_iptostring(lit->second.addr); out << " Reason: " << lit->second.reason; out << " Level: " << lit->second.level; out << " Age: " << now - lit->second.mTs; diff --git a/libretroshare/src/services/p3banlist.h b/libretroshare/src/services/p3banlist.h index 56d3651d3..042a71308 100644 --- a/libretroshare/src/services/p3banlist.h +++ b/libretroshare/src/services/p3banlist.h @@ -42,7 +42,7 @@ class BanListPeer { public: - struct sockaddr_in addr; + struct sockaddr_storage addr; uint32_t reason; // Dup Self, Dup Friend int level; // LOCAL, FRIEND, FoF. time_t mTs; @@ -54,7 +54,7 @@ class BanList std::string mPeerId; /* from */ time_t mLastUpdate; - std::map mBanPeers; + std::map mBanPeers; }; @@ -74,7 +74,7 @@ class p3BanList: /* public RsBanList, */ public p3Service, public pqiNetAssistPe /***** overloaded from pqiNetAssistPeerShare *****/ - virtual void updatePeer(std::string id, struct sockaddr_in addr, int type, int reason, int age); + virtual void updatePeer(std::string id, const struct sockaddr_storage &addr, int type, int reason, int age); /***** overloaded from p3Service *****/ @@ -93,7 +93,7 @@ class p3BanList: /* public RsBanList, */ public p3Service, public pqiNetAssistPe bool processIncoming(); bool recvBanItem(RsBanListItem *item); - bool addBanEntry(const std::string &peerId, const struct sockaddr_in &addr, + bool addBanEntry(const std::string &peerId, const struct sockaddr_storage &addr, int level, uint32_t reason, uint32_t age); void sendBanLists(); int sendBanSet(std::string peerid); @@ -123,7 +123,7 @@ class p3BanList: /* public RsBanList, */ public p3Service, public pqiNetAssistPe time_t mSentListTime; std::map mBanSources; - std::map mBanSet; + std::map mBanSet; p3LinkMgr *mLinkMgr; p3NetMgr *mNetMgr; diff --git a/libretroshare/src/services/p3disc.cc b/libretroshare/src/services/p3disc.cc index 5b3af8d90..710c5c929 100644 --- a/libretroshare/src/services/p3disc.cc +++ b/libretroshare/src/services/p3disc.cc @@ -496,8 +496,8 @@ RsDiscReply *p3disc::createDiscReply(const std::string &to, const std::string &a rsPeerNetItem.netMode = detail.netMode; rsPeerNetItem.visState = detail.visState; rsPeerNetItem.lastContact = detail.lastcontact; - rsPeerNetItem.currentlocaladdr = detail.localaddr; - rsPeerNetItem.currentremoteaddr = detail.serveraddr; + rsPeerNetItem.localAddr.addr = detail.localaddr; + rsPeerNetItem.extAddr.addr = detail.serveraddr; rsPeerNetItem.dyndns = detail.dyndns; detail.ipAddrs.mLocal.loadTlv(rsPeerNetItem.localAddrList); detail.ipAddrs.mExt.loadTlv(rsPeerNetItem.extAddrList); @@ -526,8 +526,8 @@ RsDiscReply *p3disc::createDiscReply(const std::string &to, const std::string &a rsPeerNetItem.netMode = detail.netMode; rsPeerNetItem.visState = detail.visState; rsPeerNetItem.lastContact = time(NULL); - rsPeerNetItem.currentlocaladdr = detail.localaddr; - rsPeerNetItem.currentremoteaddr = detail.serveraddr; + rsPeerNetItem.localAddr.addr = detail.localaddr; + rsPeerNetItem.extAddr.addr = detail.serveraddr; rsPeerNetItem.dyndns = detail.dyndns; detail.ipAddrs.mLocal.loadTlv(rsPeerNetItem.localAddrList); detail.ipAddrs.mExt.loadTlv(rsPeerNetItem.extAddrList); @@ -677,7 +677,7 @@ void p3disc::recvPeerDetails(RsDiscReply *item, const std::string &certGpgId) bool new_info = false; addDiscoveryData(item->PeerId(), pit->pid,item_gpg_id, - item->aboutId, pit->currentlocaladdr, pit->currentremoteaddr, 0, time(NULL),new_info); + item->aboutId, pit->localAddr.addr, pit->extAddr.addr, 0, time(NULL),new_info); if(new_info) should_notify_discovery = true ; @@ -724,7 +724,7 @@ void p3disc::recvPeerDetails(RsDiscReply *item, const std::string &certGpgId) mNetMgr->netAssistFriend(pit->pid,false); /* inform NetMgr that we know this peer */ - mNetMgr->netAssistKnownPeer(pit->pid, pit->currentremoteaddr, + mNetMgr->netAssistKnownPeer(pit->pid, pit->extAddr.addr, NETASSIST_KNOWN_PEER_FOF | NETASSIST_KNOWN_PEER_OFFLINE); continue; @@ -752,10 +752,10 @@ void p3disc::recvPeerDetails(RsDiscReply *item, const std::string &certGpgId) if (mPeerMgr->setLocation(pit->pid, pit->location)) { peerDataChanged = true; } - if (mPeerMgr->setLocalAddress(pit->pid, pit->currentlocaladdr)) { + if (mPeerMgr->setLocalAddress(pit->pid, pit->localAddr.addr)) { peerDataChanged = true; } - if (mPeerMgr->setExtAddress(pit->pid, pit->currentremoteaddr)) { + if (mPeerMgr->setExtAddress(pit->pid, pit->extAddr.addr)) { peerDataChanged = true; } if (mPeerMgr->setVisState(pit->pid, pit->visState)) { @@ -1024,7 +1024,7 @@ void p3disc::setGPGOperation(AuthGPGOperation *operation) /*************************************************************************************/ /* Storing Network Graph */ /*************************************************************************************/ -int p3disc::addDiscoveryData(const std::string& fromId, const std::string& aboutId,const std::string& from_gpg_id,const std::string& about_gpg_id, const struct sockaddr_in& laddr, const struct sockaddr_in& raddr, uint32_t flags, time_t ts,bool& new_info) +int p3disc::addDiscoveryData(const std::string& fromId, const std::string& aboutId,const std::string& from_gpg_id,const std::string& about_gpg_id, const struct sockaddr_storage &laddr, const struct sockaddr_storage &raddr, uint32_t flags, time_t ts,bool& new_info) { RsStackMutex stack(mDiscMtx); /********** STACK LOCKED MTX ******/ diff --git a/libretroshare/src/services/p3disc.h b/libretroshare/src/services/p3disc.h index 5cf4663e1..4a3e8aca5 100644 --- a/libretroshare/src/services/p3disc.h +++ b/libretroshare/src/services/p3disc.h @@ -51,8 +51,8 @@ class autoserver :ts(0), discFlags(0) { return;} std::string id; - struct sockaddr_in localAddr; - struct sockaddr_in remoteAddr; + struct sockaddr_storage localAddr; + struct sockaddr_storage remoteAddr; time_t ts; uint32_t discFlags; @@ -137,7 +137,7 @@ void removeFriend(std::string ssl_id); //keep tracks of removed friend so we're /* handle network shape */ int addDiscoveryData(const std::string& fromId, const std::string& aboutId, const std::string& fromGPGId,const std::string& aboutGPGId, - const struct sockaddr_in& laddr, const struct sockaddr_in& raddr, + const struct sockaddr_storage &laddr, const struct sockaddr_storage &raddr, uint32_t flags, time_t ts,bool& new_info); //int idServers(); diff --git a/libretroshare/src/tcponudp/rsudpstack.h b/libretroshare/src/tcponudp/rsudpstack.h index e4e4668bc..f8d645450 100644 --- a/libretroshare/src/tcponudp/rsudpstack.h +++ b/libretroshare/src/tcponudp/rsudpstack.h @@ -62,13 +62,20 @@ class rsUdpStack: public UdpStack, public pqiNetListener :UdpStack(testmode, local) { return; } /* from pqiNetListener */ -virtual bool resetListener(struct sockaddr_in &local) +virtual bool resetListener(const struct sockaddr_storage &local) { - // The const_cast below is not so nice but without it, the compiler can't - // find the correct operator<<(). No idea why! - std::cerr << "rsUdpStack::resetListener(" << const_cast(local) << ")"; + std::cerr << "rsUdpStack::resetListener(" << sockaddr_storage_tostring(local) << ")"; std::cerr << std::endl; - return resetAddress(local); + + if (local.ss_family != AF_INET) + { + std::cerr << "rsUdpStack::resetListener() NOT IPv4 ERROR"; + std::cerr << std::endl; + abort(); + } + + struct sockaddr_in *addr = (struct sockaddr_in *) &local; + return resetAddress(*addr); } }; @@ -83,14 +90,14 @@ class rsFixedUdpStack: public UdpStack, public pqiNetListener :UdpStack(testmode, local) { return; } /* from pqiNetListener */ -virtual bool resetListener(struct sockaddr_in &local) +virtual bool resetListener(const struct sockaddr_storage &local) { struct sockaddr_in addr; getLocalAddress(addr); // The const_cast below is not so nice but without it, the compiler can't // find the correct operator<<(). No idea why! - std::cerr << "rsFixedUdpStack::resetListener(" << const_cast(local) << ")"; + std::cerr << "rsFixedUdpStack::resetListener(" << sockaddr_storage_tostring(local) << ")"; std::cerr << " Resetting with original addr: " << const_cast(addr); std::cerr << std::endl; diff --git a/libretroshare/src/util/dnsresolver.cc b/libretroshare/src/util/dnsresolver.cc index cd9b312d5..e318b38cb 100644 --- a/libretroshare/src/util/dnsresolver.cc +++ b/libretroshare/src/util/dnsresolver.cc @@ -1,6 +1,8 @@ #include "dnsresolver.h" #include "pqi/pqinetwork.h" +#include "util/rsnet.h" + #ifndef WIN32 #include @@ -64,13 +66,19 @@ void *solveDNSEntries(void *p) { RsStackMutex mut(dnsr->_rdnsMtx) ; + DNSResolver::AddrInfo &info = (*dnsr->_addr_map)[next_call]; + if(pHost) { - (*dnsr->_addr_map)[next_call].state = DNSResolver::DNS_HAVE ; - (*dnsr->_addr_map)[next_call].addr.s_addr = *(unsigned long*) (pHost->h_addr); + info.state = DNSResolver::DNS_HAVE ; + // IPv4 for the moment. + struct sockaddr_in *addrv4p = (struct sockaddr_in *) &(info.addr); + addrv4p->sin_family = AF_INET; + addrv4p->sin_addr.s_addr = *(unsigned long*) (pHost->h_addr); + addrv4p->sin_port = htons(0); } else - (*dnsr->_addr_map)[next_call].state = DNSResolver::DNS_LOOKUP_ERROR ; + info.state = DNSResolver::DNS_LOOKUP_ERROR ; } } } @@ -103,9 +111,9 @@ void DNSResolver::reset() _addr_map->clear(); } -bool DNSResolver::getIPAddressFromString(const std::string& server_name,struct in_addr& addr) +bool DNSResolver::getIPAddressFromString(const std::string& server_name,struct sockaddr_storage &addr) { - addr.s_addr = 0 ; + sockaddr_storage_clear(addr); bool running = false; { RsStackMutex mut(_rdnsMtx) ; diff --git a/libretroshare/src/util/dnsresolver.h b/libretroshare/src/util/dnsresolver.h index 51aa77dc2..1f9581d1e 100644 --- a/libretroshare/src/util/dnsresolver.h +++ b/libretroshare/src/util/dnsresolver.h @@ -18,7 +18,7 @@ class DNSResolver DNSResolver() ; ~DNSResolver() ; - bool getIPAddressFromString(const std::string& server_name,struct in_addr& addr) ; + bool getIPAddressFromString(const std::string& server_name,struct sockaddr_storage &addr) ; void start_request() ; void reset() ; @@ -30,7 +30,7 @@ class DNSResolver { uint32_t state ; // state: Looked-up, not found, have time_t last_lookup_time ; // last lookup time - struct in_addr addr ; + struct sockaddr_storage addr ; }; friend void *solveDNSEntries(void *p) ; diff --git a/libretroshare/src/util/extaddrfinder.cc b/libretroshare/src/util/extaddrfinder.cc index f6fd43b33..f41db4ef8 100644 --- a/libretroshare/src/util/extaddrfinder.cc +++ b/libretroshare/src/util/extaddrfinder.cc @@ -150,11 +150,11 @@ void* doExtAddrSearch(void *p) // thread safe copy results. // { - RsStackMutex mtx(af->_addrMtx) ; + RsStackMutex mtx(af->mAddrMtx) ; - *(af->_found) = false ; - *(af->mFoundTS) = time(NULL) ; - *(af->_searching) = false ; + af->mFound = false ; + af->mFoundTS = time(NULL) ; + af->mSearching = false ; } pthread_exit(NULL); return NULL ; @@ -163,24 +163,25 @@ void* doExtAddrSearch(void *p) sort(res.begin(),res.end()) ; // eliminates outliers. - if(!inet_aton(res[res.size()/2].c_str(),af->_addr)) + + if(!sockaddr_storage_ipv4_aton(af->mAddr, res[res.size()/2].c_str())) { std::cerr << "ExtAddrFinder: Could not convert " << res[res.size()/2] << " into an address." << std::endl ; { - RsStackMutex mtx(af->_addrMtx) ; - *(af->_found) = false ; - *(af->mFoundTS) = time(NULL) ; - *(af->_searching) = false ; + RsStackMutex mtx(af->mAddrMtx) ; + af->mFound = false ; + af->mFoundTS = time(NULL) ; + af->mSearching = false ; } pthread_exit(NULL); return NULL ; } { - RsStackMutex mtx(af->_addrMtx) ; - *(af->_found) = true ; - *(af->mFoundTS) = time(NULL) ; - *(af->_searching) = false ; + RsStackMutex mtx(af->mAddrMtx) ; + af->mFound = true ; + af->mFoundTS = time(NULL) ; + af->mSearching = false ; } pthread_exit(NULL); @@ -196,44 +197,44 @@ void ExtAddrFinder::start_request() pthread_detach(tid); /* so memory is reclaimed in linux */ } -bool ExtAddrFinder::hasValidIP(struct in_addr *addr) +bool ExtAddrFinder::hasValidIP(struct sockaddr_storage &addr) { #ifdef EXTADDRSEARCH_DEBUG std::cerr << "ExtAddrFinder: Getting ip." << std::endl ; #endif { - RsStackMutex mut(_addrMtx) ; - if(*_found) + RsStackMutex mut(mAddrMtx) ; + if(mFound) { #ifdef EXTADDRSEARCH_DEBUG std::cerr << "ExtAddrFinder: Has stored ip: responding with this ip." << std::endl ; #endif - *addr = *_addr; + addr = mAddr; } } time_t delta; { - RsStackMutex mut(_addrMtx) ; + RsStackMutex mut(mAddrMtx) ; //timeout the current ip - delta = time(NULL) - *mFoundTS; + delta = time(NULL) - mFoundTS; } if((uint32_t)delta > MAX_IP_STORE) {//launch a research - if( _addrMtx.trylock()) + if( mAddrMtx.trylock()) { - if(!*_searching) + if(!mSearching) { #ifdef EXTADDRSEARCH_DEBUG std::cerr << "ExtAddrFinder: No stored ip: Initiating new search." << std::endl ; #endif - *_searching = true ; + mSearching = true ; start_request() ; } #ifdef EXTADDRSEARCH_DEBUG else std::cerr << "ExtAddrFinder: Already searching." << std::endl ; #endif - _addrMtx.unlock(); + mAddrMtx.unlock(); } #ifdef EXTADDRSEARCH_DEBUG else @@ -241,24 +242,17 @@ bool ExtAddrFinder::hasValidIP(struct in_addr *addr) #endif } - RsStackMutex mut(_addrMtx) ; - return *_found ; + RsStackMutex mut(mAddrMtx) ; + return mFound ; } void ExtAddrFinder::reset() { -// while(*_searching) -//#ifdef WIN32 -// Sleep(1000) ; -//#else -// sleep(1) ; -//#endif + RsStackMutex mut(mAddrMtx) ; - RsStackMutex mut(_addrMtx) ; - - *_found = false ; - *_searching = false ; - *mFoundTS = time(NULL) - MAX_IP_STORE; + mFound = false ; + mSearching = false ; + mFoundTS = time(NULL) - MAX_IP_STORE; } ExtAddrFinder::~ExtAddrFinder() @@ -266,37 +260,20 @@ ExtAddrFinder::~ExtAddrFinder() #ifdef EXTADDRSEARCH_DEBUG std::cerr << "ExtAddrFinder: Deleting ExtAddrFinder." << std::endl ; #endif -// while(*_searching) -//#ifdef WIN32 -// Sleep(1000) ; -//#else -// sleep(1) ; -//#endif - RsStackMutex mut(_addrMtx) ; - - delete _found ; - delete _searching ; - free (_addr) ; } -ExtAddrFinder::ExtAddrFinder() : _addrMtx("ExtAddrFinder") +ExtAddrFinder::ExtAddrFinder() : mAddrMtx("ExtAddrFinder") { #ifdef EXTADDRSEARCH_DEBUG std::cerr << "ExtAddrFinder: Creating new ExtAddrFinder." << std::endl ; #endif - RsStackMutex mut(_addrMtx) ; + RsStackMutex mut(mAddrMtx) ; - _found = new bool ; - *_found = false ; - - _searching = new bool ; - *_searching = false ; - - mFoundTS = new time_t; - *mFoundTS = time(NULL) - MAX_IP_STORE; - - _addr = (in_addr*)malloc(sizeof(in_addr)) ; + mFound = false; + mSearching = false; + mFoundTS = time(NULL) - MAX_IP_STORE; + sockaddr_storage_clear(mAddr); _ip_servers.push_back(std::string( "checkip.dyndns.org" )) ; _ip_servers.push_back(std::string( "www.myip.dk" )) ; diff --git a/libretroshare/src/util/extaddrfinder.h b/libretroshare/src/util/extaddrfinder.h index ec8782c7c..203e1ff9e 100644 --- a/libretroshare/src/util/extaddrfinder.h +++ b/libretroshare/src/util/extaddrfinder.h @@ -3,6 +3,7 @@ #include #include #include "util/rsthreads.h" +#include "util/rsnet.h" struct sockaddr ; @@ -12,7 +13,7 @@ class ExtAddrFinder ExtAddrFinder() ; ~ExtAddrFinder() ; - bool hasValidIP(struct in_addr *addr) ; + bool hasValidIP(struct sockaddr_storage &addr) ; void getIPServersList(std::list& ip_servers) { ip_servers = _ip_servers ; } void start_request() ; @@ -22,10 +23,10 @@ class ExtAddrFinder private: friend void* doExtAddrSearch(void *p) ; - time_t *mFoundTS; - RsMutex _addrMtx ; - struct in_addr *_addr ; - bool *_found ; - bool *_searching ; + RsMutex mAddrMtx ; + time_t mFoundTS; + struct sockaddr_storage mAddr; + bool mFound ; + bool mSearching ; std::list _ip_servers ; }; diff --git a/libretroshare/src/util/rsnet.h b/libretroshare/src/util/rsnet.h index 15bf5749a..7b854c00c 100644 --- a/libretroshare/src/util/rsnet.h +++ b/libretroshare/src/util/rsnet.h @@ -75,4 +75,46 @@ std::ostream& operator<<(std::ostream& o,const struct sockaddr_in&) ; std::string rs_inet_ntoa(struct in_addr in); +/***************************/ +// sockaddr_storage fns. + +void sockaddr_storage_clear(struct sockaddr_storage &addr); + +// mods. +bool sockaddr_storage_zeroip(struct sockaddr_storage &addr); +bool sockaddr_storage_copyip(struct sockaddr_storage &dst, const struct sockaddr_storage &src); +uint16_t sockaddr_storage_port(const struct sockaddr_storage &addr); +bool sockaddr_storage_setport(struct sockaddr_storage &addr, uint16_t port); + +bool sockaddr_storage_ipv4_aton(struct sockaddr_storage &addr, const char *name); +bool sockaddr_storage_ipv4_setport(struct sockaddr_storage &addr, const uint16_t port); + +// comparisons. +bool operator<(const struct sockaddr_storage &a, const struct sockaddr_storage &b); + +bool sockaddr_storage_same(const struct sockaddr_storage &addr, const struct sockaddr_storage &addr2); +bool sockaddr_storage_samefamily(const struct sockaddr_storage &addr, const struct sockaddr_storage &addr2); +bool sockaddr_storage_sameip(const struct sockaddr_storage &addr, const struct sockaddr_storage &addr2); +bool sockaddr_storage_samenet(const struct sockaddr_storage &addr, const struct sockaddr_storage &addr2); +bool sockaddr_storage_samesubnet(const struct sockaddr_storage &addr, const struct sockaddr_storage &addr2); + +// string, +std::string sockaddr_storage_tostring(const struct sockaddr_storage &addr); +std::string sockaddr_storage_familytostring(const struct sockaddr_storage &addr); +std::string sockaddr_storage_iptostring(const struct sockaddr_storage &addr); +std::string sockaddr_storage_porttostring(const struct sockaddr_storage &addr); + +// output +//void sockaddr_storage_output(const struct sockaddr_storage &addr, std::ostream &out); +//void sockaddr_storage_ipoutput(const struct sockaddr_storage &addr, std::ostream &out); + +// net checks. +bool sockaddr_storage_isnull(const struct sockaddr_storage &addr); +bool sockaddr_storage_isValidNet(const struct sockaddr_storage &addr); +bool sockaddr_storage_isLoopbackNet(const struct sockaddr_storage &addr); +bool sockaddr_storage_isPrivateNet(const struct sockaddr_storage &addr); +bool sockaddr_storage_isExternalNet(const struct sockaddr_storage &addr); + + + #endif /* RS_UNIVERSAL_NETWORK_HEADER */ diff --git a/libretroshare/src/zeroconf/p3zcnatassist.cc b/libretroshare/src/zeroconf/p3zcnatassist.cc index 5bd45048a..1e35de50b 100644 --- a/libretroshare/src/zeroconf/p3zcnatassist.cc +++ b/libretroshare/src/zeroconf/p3zcnatassist.cc @@ -177,7 +177,7 @@ void p3zcNatAssist::setExternalPort(unsigned short eport_in) } } -bool p3zcNatAssist::getInternalAddress(struct sockaddr_in &addr) +bool p3zcNatAssist::getInternalAddress(struct sockaddr_storage &addr) { #ifdef DEBUG_ZCNATASSIST @@ -189,7 +189,7 @@ bool p3zcNatAssist::getInternalAddress(struct sockaddr_in &addr) } -bool p3zcNatAssist::getExternalAddress(struct sockaddr_in &addr) +bool p3zcNatAssist::getExternalAddress(struct sockaddr_storage &addr) { RsStackMutex stack(mZcMtx); /****** STACK LOCK MUTEX *******/ @@ -397,11 +397,18 @@ void p3zcNatAssist::callbackMapping(DNSServiceRef sdRef, DNSServiceFlags flags, mMapped = true; - mExternalAddress.sin_addr.s_addr = externalAddress; - mExternalAddress.sin_port = externalPort; + + // THIS APPEARS TO BE IPv4 ONLY!. + + sockaddr_storage_clear(mExternalAddress); + struct sockaddr_in *addr = (struct sockaddr_in *) &mExternalAddress; + + addr->sin_family = AF_INET; + addr->sin_addr.s_addr = externalAddress; + addr->sin_port = externalPort; + mTTL = ttl; - std::cerr << "p3zcNatAssist::callbackMapping() Success"; std::cerr << std::endl; @@ -411,8 +418,7 @@ void p3zcNatAssist::callbackMapping(DNSServiceRef sdRef, DNSServiceFlags flags, std::cerr << "internalPort: " << ntohs(internalPort); std::cerr << std::endl; - std::cerr << "externalAddress: " << rs_inet_ntoa(mExternalAddress.sin_addr); - std::cerr << ":" << ntohs(mExternalAddress.sin_port); + std::cerr << "externalAddress: " << sockaddr_storage_tostring(mExternalAddress); std::cerr << std::endl; std::cerr << "protocol: " << protocol; diff --git a/libretroshare/src/zeroconf/p3zcnatassist.h b/libretroshare/src/zeroconf/p3zcnatassist.h index 72bde8dea..ad92d9a2a 100644 --- a/libretroshare/src/zeroconf/p3zcnatassist.h +++ b/libretroshare/src/zeroconf/p3zcnatassist.h @@ -61,8 +61,8 @@ virtual bool getActive(); virtual void setInternalPort(unsigned short iport_in); virtual void setExternalPort(unsigned short eport_in); -virtual bool getInternalAddress(struct sockaddr_in &addr); -virtual bool getExternalAddress(struct sockaddr_in &addr); +virtual bool getInternalAddress(struct sockaddr_storage &addr); +virtual bool getExternalAddress(struct sockaddr_storage &addr); /* TO IMPLEMENT: New Port Forward interface to support as many ports as necessary */ virtual bool requestPortForward(const PortForwardParams ¶ms) { return false; } @@ -101,7 +101,7 @@ virtual bool statusPortForward(const uint32_t fwdId, PortForwardParams ¶m uint16_t mExternalPort; bool mExternalPortSet; - struct sockaddr_in mExternalAddress; + struct sockaddr_storage mExternalAddress; int mTTL; DNSServiceRef mMappingRef; diff --git a/libretroshare/src/zeroconf/p3zeroconf.cc b/libretroshare/src/zeroconf/p3zeroconf.cc index 82a9f8ee1..34cd22105 100644 --- a/libretroshare/src/zeroconf/p3zeroconf.cc +++ b/libretroshare/src/zeroconf/p3zeroconf.cc @@ -236,7 +236,7 @@ bool p3ZeroConf::dropPeer(std::string pid) /* extract current peer status */ bool p3ZeroConf::getPeerStatus(std::string id, - struct sockaddr_in &/*laddr*/, struct sockaddr_in &/*raddr*/, + struct sockaddr_storage &/*laddr*/, struct sockaddr_storage &/*raddr*/, uint32_t &/*type*/, uint32_t &/*mode*/) { /* remove unused parameter warnings */ @@ -251,7 +251,7 @@ bool p3ZeroConf::getPeerStatus(std::string id, } #if 0 -bool p3ZeroConf::getExternalInterface(struct sockaddr_in &/*raddr*/, +bool p3ZeroConf::getExternalInterface(struct sockaddr_storage &/*raddr*/, uint32_t &/*mode*/) { @@ -277,12 +277,12 @@ bool p3ZeroConf::setAttachMode(bool on) return true; } -int p3ZeroConf::addBadPeer(const struct sockaddr_in &addr, uint32_t reason, uint32_t flags, uint32_t age) +int p3ZeroConf::addBadPeer(const struct sockaddr_storage &addr, uint32_t reason, uint32_t flags, uint32_t age) { return 1; } -int p3ZeroConf::addKnownPeer(const std::string &pid, const struct sockaddr_in &addr, uint32_t flags) +int p3ZeroConf::addKnownPeer(const std::string &pid, const struct sockaddr_storage &addr, uint32_t flags) { return 1; } @@ -563,7 +563,9 @@ int p3ZeroConf::checkQueryResults() time_t now = time(NULL); uint32_t flags = RS_CB_FLAG_MODE_TCP; uint32_t source = RS_CB_DHT; // SHOULD ADD NEW SOURCE ZC??? - struct sockaddr_in dummyProxyAddr, dummySrcAddr; + struct sockaddr_storage dummyProxyAddr, dummySrcAddr; + sockaddr_storage_clear(dummyProxyAddr); + sockaddr_storage_clear(dummySrcAddr); mConnCb->peerConnectRequest(qr.sslId, qr.addr, dummyProxyAddr, dummySrcAddr, source, flags, 0, 0); @@ -1145,8 +1147,13 @@ void p3ZeroConf::callbackQueryIp( DNSServiceRef /* sdRef */, DNSServiceFlags fla if ((rrtype == kDNSServiceType_A) && (rdlen == 4)) { - qr.addr.sin_addr.s_addr = *((uint32_t *) rdata); - + // IPV4 type. + sockaddr_storage_clear(qr.addr); + struct sockaddr_in *addr = (struct sockaddr_in *) &(qr.addr); + addr->sin_family = AF_INET; + addr->sin_addr.s_addr = *((uint32_t *) rdata); + addr->sin_port = htons(0); + if (locked_completeQueryResult(qr)) // Saves Query Results, and fills in Port details. { mQueryResults.push_back(qr); @@ -1206,7 +1213,7 @@ int p3ZeroConf::locked_completeQueryResult(zcQueryResult &qr) std::cerr << "p3ZeroConf::locked_completeQueryResults() Filling in Peer IpAddress"; std::cerr << std::endl; - qr.addr.sin_port = htons(lit->second.mPort); + sockaddr_storage_setport(qr.addr, lit->second.mPort); lit->second.mAddress = qr.addr; lit->second.mStatus |= ZC_STATUS_IPADDRESS; lit->second.mAddrTs = time(NULL); diff --git a/libretroshare/src/zeroconf/p3zeroconf.h b/libretroshare/src/zeroconf/p3zeroconf.h index d1130cf94..46365633b 100644 --- a/libretroshare/src/zeroconf/p3zeroconf.h +++ b/libretroshare/src/zeroconf/p3zeroconf.h @@ -91,7 +91,7 @@ class zcQueryResult // Extra ones. std::string sslId; std::string gpgId; - struct sockaddr_in addr; + struct sockaddr_storage addr; }; @@ -121,7 +121,7 @@ class zcLocationDetails std::string mFullName; uint16_t mPort; - struct sockaddr_in mAddress; + struct sockaddr_storage mAddress; time_t mAddrTs; }; @@ -171,15 +171,15 @@ virtual bool getNetworkStats(uint32_t &netsize, uint32_t &localnetsize); virtual bool findPeer(std::string id); virtual bool dropPeer(std::string id); -virtual int addBadPeer(const struct sockaddr_in &addr, uint32_t reason, uint32_t flags, uint32_t age); -virtual int addKnownPeer(const std::string &pid, const struct sockaddr_in &addr, uint32_t flags); +virtual int addBadPeer(const struct sockaddr_storage &addr, uint32_t reason, uint32_t flags, uint32_t age); +virtual int addKnownPeer(const std::string &pid, const struct sockaddr_storage &addr, uint32_t flags); /* feedback on success failure of Connections */ virtual void ConnectionFeedback(std::string pid, int state); /* extract current peer status */ virtual bool getPeerStatus(std::string id, - struct sockaddr_in &laddr, struct sockaddr_in &raddr, + struct sockaddr_storage &laddr, struct sockaddr_storage &raddr, uint32_t &type, uint32_t &mode); virtual bool setAttachMode(bool on); From 3799910188fef53e4c447f3d92387c9a2b230b33 Mon Sep 17 00:00:00 2001 From: chrisparker126 Date: Sun, 15 Sep 2013 21:18:20 +0000 Subject: [PATCH 14/83] More changes to support front end of group update - still need to make sync changes git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.5-gxs_finale@6741 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/gxs/rsdataservice.cc | 2 +- libretroshare/src/gxs/rsdataservice.h | 2 +- libretroshare/src/gxs/rsgds.h | 11 +-- libretroshare/src/gxs/rsgenexchange.cc | 93 +++++++++++++++++++++++- libretroshare/src/gxs/rsgenexchange.h | 23 +++++- libretroshare/src/gxs/rsgxsdataaccess.cc | 7 ++ libretroshare/src/gxs/rsgxsdataaccess.h | 11 ++- 7 files changed, 131 insertions(+), 18 deletions(-) diff --git a/libretroshare/src/gxs/rsdataservice.cc b/libretroshare/src/gxs/rsdataservice.cc index f27633af2..a334d090f 100644 --- a/libretroshare/src/gxs/rsdataservice.cc +++ b/libretroshare/src/gxs/rsdataservice.cc @@ -663,7 +663,7 @@ int RsDataService::updateGroup(std::map &grp) if(!validSize(grpPtr)) continue; std::string grpFile = mServiceDir + "/" + grpPtr->grpId; - std::fstream ostrm(grpFile.c_str(), std::ios::binary | std::ios::app | std::ios::out); + std::fstream ostrm(grpFile.c_str(), std::ios::binary | std::ios::app | std::ios::trunc); ostrm.seekg(0, std::ios::end); // go to end to append uint32_t offset = ostrm.tellg(); // get fill offset diff --git a/libretroshare/src/gxs/rsdataservice.h b/libretroshare/src/gxs/rsdataservice.h index 666aa8e98..53f9c4fe8 100644 --- a/libretroshare/src/gxs/rsdataservice.h +++ b/libretroshare/src/gxs/rsdataservice.h @@ -111,7 +111,7 @@ public: * @param grpIds all grpids in store is inserted into this vector * @return error code */ - int RsDataService::retrieveGroupIds(std::vector &grpIds); + int retrieveGroupIds(std::vector &grpIds); /*! * @return the cache size set for this RsGeneralDataService in bytes diff --git a/libretroshare/src/gxs/rsgds.h b/libretroshare/src/gxs/rsgds.h index 9a82d3687..c2ba4d8ac 100644 --- a/libretroshare/src/gxs/rsgds.h +++ b/libretroshare/src/gxs/rsgds.h @@ -167,14 +167,14 @@ public: * @param grpIds ids of groups to be removed * @return error code */ - virtual int removeGroups(std::vector& grpIds) = 0; + virtual int removeGroups(const std::vector& grpIds) = 0; /*! * Retrieves all group ids in store * @param grpIds all grpids in store is inserted into this vector * @return error code */ - virtual int retrieveGroupIds(const std::vector& grpIds) = 0; + virtual int retrieveGroupIds(std::vector& grpIds) = 0; /*! * @return the cache size set for this RsGeneralDataService in bytes @@ -193,13 +193,6 @@ public: */ virtual int storeMessage(std::map& msgs) = 0; - /*! - * Stores a list of signed messages into data store - * @param msg map of message and decoded meta data information - * @return error code - */ - virtual int storeMessage(std::map& msgs) = 0; - /*! * Stores a list of groups in data store * @param grp map of group and decoded meta data diff --git a/libretroshare/src/gxs/rsgenexchange.cc b/libretroshare/src/gxs/rsgenexchange.cc index eac88e3b0..d67d36c00 100644 --- a/libretroshare/src/gxs/rsgenexchange.cc +++ b/libretroshare/src/gxs/rsgenexchange.cc @@ -1369,6 +1369,20 @@ void RsGenExchange::publishGroup(uint32_t& token, RsGxsGrpItem *grpItem) } + +void RsGenExchange::updateGroup(uint32_t& token, RsGxsGrpItem* grpItem) +{ + RsStackMutex stack(mGenMtx); + token = mDataAccess->generatePublicToken(); + mGroupUpdatePublish.push_back(GroupUpdatePublish(grpItem, token)); + +#ifdef GEN_EXCH_DEBUG + std::cerr << "RsGenExchange::updateGroup() token: " << token; + std::cerr << std::endl; +#endif +} + + void RsGenExchange::publishMsg(uint32_t& token, RsGxsMsgItem *msgItem) { RsStackMutex stack(mGenMtx); @@ -1785,6 +1799,76 @@ RsGenExchange::ServiceCreate_Return RsGenExchange::service_CreateGroup(RsGxsGrpI #define PENDING_SIGN_TIMEOUT 10 // 5 seconds + +void RsGenExchange::processGroupUpdatePublish() +{ + + RsStackMutex stack(mGenMtx); + + // get keys for group update publish + + // first build meta request map for groups to be updated + std::map grpMeta; + std::vector::iterator vit = mGroupUpdatePublish.begin(); + + for(; vit != mGroupUpdatePublish.end(); vit++) + { + GroupUpdatePublish& gup = *vit; + const RsGxsGroupId& groupId = gup.grpItem->meta.mGroupId; + grpMeta.insert(std::make_pair(groupId, (RsGxsGrpMetaData*)(NULL))); + } + + mDataStore->retrieveGxsGrpMetaData(grpMeta); + + // now + vit = mGroupUpdatePublish.begin(); + for(; vit != mGroupUpdatePublish.end(); vit++) + { + GroupUpdatePublish& gup = *vit; + const RsGxsGroupId& groupId = gup.grpItem->meta.mGroupId; + RsGxsGrpMetaData* meta = grpMeta[groupId]; + + GxsGrpPendingSign ggps(ggps.mItem, ggps.mToken); + + bool split = splitKeys(meta->keys, ggps.mPrivateKeys, ggps.mPublicKeys); + + if(split) + { + ggps.mHaveKeys = true; + ggps.mStartTS = time(NULL); + ggps.mLastAttemptTS = 0; + mGrpsToPublish.push_back(ggps); + }else + { + delete gup.grpItem; + mDataAccess->updatePublicRequestStatus(gup.mToken, RsTokenService::GXS_REQUEST_V2_STATUS_FAILED); + } + + } + + mGroupUpdatePublish.clear(); +} + +bool RsGenExchange::splitKeys(const RsTlvSecurityKeySet& keySet, RsTlvSecurityKeySet& privateKeySet, RsTlvSecurityKeySet& publicKeySet) +{ + + typedef std::map keyMap; + const keyMap& allKeys = keySet.keys; + keyMap::const_iterator cit = allKeys.begin(); + + for(; cit != allKeys.end(); cit++) + { + const RsTlvSecurityKey& key = cit->second; + if(key.keyFlags & RSTLV_KEY_TYPE_PUBLIC_ONLY) + publicKeySet.keys.insert(std::make_pair(key.keyId, key)); + else if(key.keyFlags & RSTLV_KEY_TYPE_FULL) + privateKeySet.keys.insert(std::make_pair(key.keyId, key)); + } + + // user must have both private and public parts of publish and admin keys + return (privateKeySet.keys.size() == 2) && (publicKeySet.keys.size() == 2); +} + void RsGenExchange::publishGrps() { RsStackMutex stack(mGenMtx); @@ -1906,7 +1990,11 @@ void RsGenExchange::publishGrps() { grpId = grp->grpId; computeHash(grp->grp, grp->metaData->mHash); - mDataAccess->addGroupData(grp); + + if(ggps.mIsUpdate) + mDataAccess->updateGroupData(grp); + else + mDataAccess->addGroupData(grp); } else { @@ -2195,7 +2283,8 @@ void RsGenExchange::processRecvdGroups() RsStackMutex stack(mGenMtx); NxsGrpPendValidVect::iterator vit = mReceivedGrps.begin(); - std::vector existingGrpIds, grpIds; + std::vector existingGrpIds; + std::list grpIds; std::map grps; diff --git a/libretroshare/src/gxs/rsgenexchange.h b/libretroshare/src/gxs/rsgenexchange.h index dc6a5026c..b7dc6e966 100644 --- a/libretroshare/src/gxs/rsgenexchange.h +++ b/libretroshare/src/gxs/rsgenexchange.h @@ -71,13 +71,14 @@ class GxsGrpPendingSign public: GxsGrpPendingSign(RsGxsGrpItem* item, uint32_t token): mLastAttemptTS(0), mStartTS(time(NULL)), mToken(token), - mItem(item), mHaveKeys(false) + mItem(item), mHaveKeys(false), mIsUpdate(false) {} time_t mLastAttemptTS, mStartTS; uint32_t mToken; RsGxsGrpItem* mItem; bool mHaveKeys; // mKeys->first == true if key present + bool mIsUpdate; RsTlvSecurityKeySet mPrivateKeys; RsTlvSecurityKeySet mPublicKeys; }; @@ -516,7 +517,6 @@ protected: /*! * Enables publication of a group item \n - * If the item exists already this is simply versioned \n * This will induce a related change message \n * Ownership of item passes to this rsgenexchange \n * @param token @@ -524,6 +524,16 @@ protected: */ void publishGroup(uint32_t& token, RsGxsGrpItem* grpItem); + + /*! + * Updates an existing group item \n + * This will induce a related change message \n + * Ownership of item passes to this rsgenexchange \n + * @param token + * @param grpItem + */ + void updateGroup(uint32_t& token, RsGxsGrpItem* grpItem); + public: /*! * Enables publication of a message item \n @@ -629,6 +639,8 @@ private: void publishGrps(); + void processGroupUpdatePublish(); + void publishMsgs(); /*! @@ -750,6 +762,8 @@ private: */ bool updateValid(RsGxsGrpMetaData& oldGrp, RsNxsGrp& newGrp) const; + bool splitKeys(const RsTlvSecurityKeySet& keySet, RsTlvSecurityKeySet& privateKeySet, RsTlvSecurityKeySet& publicKeySet); + private: RsMutex mGenMtx; @@ -815,7 +829,10 @@ private: private: - std::vector mGroupUpdates; + std::vector mGroupUpdates, mPeersGroupUpdate; + + std::vector mGroupUpdatePublish; + }; #endif // RSGENEXCHANGE_H diff --git a/libretroshare/src/gxs/rsgxsdataaccess.cc b/libretroshare/src/gxs/rsgxsdataaccess.cc index 5399c746e..39c428b37 100644 --- a/libretroshare/src/gxs/rsgxsdataaccess.cc +++ b/libretroshare/src/gxs/rsgxsdataaccess.cc @@ -1487,7 +1487,14 @@ bool RsGxsDataAccess::addGroupData(RsNxsGrp* grp) { return mDataStore->storeGroup(grpM); } +bool RsGxsDataAccess::updateGroupData(RsNxsGrp* grp) { + RsStackMutex stack(mDataMutex); + + std::map grpM; + grpM.insert(std::make_pair(grp, grp->metaData)); + return mDataStore->updateGroup(grpM); +} bool RsGxsDataAccess::addMsgData(RsNxsMsg* msg) { diff --git a/libretroshare/src/gxs/rsgxsdataaccess.h b/libretroshare/src/gxs/rsgxsdataaccess.h index de5258569..3b0aa8113 100644 --- a/libretroshare/src/gxs/rsgxsdataaccess.h +++ b/libretroshare/src/gxs/rsgxsdataaccess.h @@ -126,14 +126,21 @@ public: public: /*! - * This adds a groups to the gxs data base, this is a blocking call - * Responsibility for grp still lies with callee \n + * This adds a groups to the gxs data base, this is a blocking call \n * If function returns successfully DataAccess can be queried for grp * @param grp the group to add, responsibility grp passed lies with callee * @return false if group cound not be added */ bool addGroupData(RsNxsGrp* grp); + /*! + * This updates a groups in the gxs data base, this is a blocking call \n + * If function returns successfully DataAccess can be queried for grp + * @param grp the group to add, responsibility grp passed lies with callee + * @return false if group cound not be added + */ + bool updateGroupData(RsNxsGrp* grp); + /*! * This adds a group to the gxs data base, this is a blocking call \n * Responsibility for msg still lies with callee \n From 2a841d7ab3342fca8361e9c0108a88c338d5a86f Mon Sep 17 00:00:00 2001 From: chrisparker126 Date: Wed, 18 Sep 2013 18:13:38 +0000 Subject: [PATCH 15/83] fixed mem bug git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.5-gxs_finale@6747 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/gxs/rsgenexchange.cc | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/libretroshare/src/gxs/rsgenexchange.cc b/libretroshare/src/gxs/rsgenexchange.cc index d67d36c00..5b4baff0d 100644 --- a/libretroshare/src/gxs/rsgenexchange.cc +++ b/libretroshare/src/gxs/rsgenexchange.cc @@ -2388,13 +2388,19 @@ void RsGenExchange::performUpdateValidation() std::cerr << "RsGenExchange::performUpdateValidation() " << std::endl; #endif + if(mGroupUpdates.empty()) + return; + std::map grpMetas; std::vector::iterator vit = mGroupUpdates.begin(); for(; vit != mGroupUpdates.end(); vit++) grpMetas.insert(std::make_pair(vit->newGrp->grpId, (RsGxsGrpMetaData*)NULL)); - mDataStore->retrieveGxsGrpMetaData(grpMetas); + if(!grpMetas.empty()) + mDataStore->retrieveGxsGrpMetaData(grpMetas); + else + return; vit = mGroupUpdates.begin(); for(; vit != mGroupUpdates.end(); vit++) From 34ea22d5f65302e6aa3970bcb3f82f9f68ab2b20 Mon Sep 17 00:00:00 2001 From: drbob Date: Tue, 24 Sep 2013 05:30:01 +0000 Subject: [PATCH 16/83] Implemented sockaddr_storage functions. Fixed interfaces for UPnP. Some further tweaks to get TCP connections working again: - hiddenNode issue in p3peers.cc - fixed socklen_t for bind() and connect() calls. - initialise addr to IPv4 for netmgr. - change netAssist (Upnp) interfaces. Still todo: tou address functions, test UDP functionality. git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@6755 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/dht/p3bitdht_peers.cc | 31 +- libretroshare/src/libretroshare.pro | 1 + libretroshare/src/pqi/p3netmgr.cc | 6 + libretroshare/src/pqi/pqiassist.h | 4 +- libretroshare/src/pqi/pqinetwork.cc | 29 +- libretroshare/src/pqi/pqissl.cc | 3 +- libretroshare/src/pqi/pqissllistener.cc | 8 +- libretroshare/src/rsserver/p3peers.cc | 4 +- libretroshare/src/rsserver/rsinit.cc | 12 +- libretroshare/src/upnp/upnphandler_linux.cc | 16 +- libretroshare/src/upnp/upnphandler_linux.h | 4 +- .../src/upnp/upnphandler_miniupnp.cc | 15 +- libretroshare/src/upnp/upnphandler_miniupnp.h | 4 +- libretroshare/src/util/rsnet.h | 8 + libretroshare/src/util/rsnet_ss.cc | 971 ++++++++++++++++++ 15 files changed, 1076 insertions(+), 40 deletions(-) create mode 100644 libretroshare/src/util/rsnet_ss.cc diff --git a/libretroshare/src/dht/p3bitdht_peers.cc b/libretroshare/src/dht/p3bitdht_peers.cc index f488af671..1b5425209 100644 --- a/libretroshare/src/dht/p3bitdht_peers.cc +++ b/libretroshare/src/dht/p3bitdht_peers.cc @@ -219,22 +219,31 @@ int p3BitDht::addBadPeer(const struct sockaddr_storage &addr, uint32_t /*reason* int p3BitDht::addKnownPeer(const std::string &pid, const struct sockaddr_storage &addr, uint32_t flags) { struct sockaddr_in addrv4; + if (addr.ss_family != AF_INET) { - std::cerr << "p3BitDht::addKnownPeer() cannot handle IPV6 Yet, aborting"; + std::cerr << "p3BitDht::addKnownPeer() Warning! Non IPv4 Address - Cannot handle IPV6 Yet."; std::cerr << std::endl; - abort(); + sockaddr_clear(&addrv4); + + if (flags & NETASSIST_KNOWN_PEER_ONLINE) + { + std::cerr << "p3BitDht::addKnownPeer() Non IPv4 Address & ONLINE. Abort()ing."; + std::cerr << std::endl; + abort(); + } } - struct sockaddr_in *ap = (struct sockaddr_in *) &addr; - - // convert. - addrv4.sin_family = ap->sin_family; - addrv4.sin_addr = ap->sin_addr; - addrv4.sin_port = ap->sin_port; - - - + else + { + + // convert. + struct sockaddr_in *ap = (struct sockaddr_in *) &addr; + addrv4.sin_family = ap->sin_family; + addrv4.sin_addr = ap->sin_addr; + addrv4.sin_port = ap->sin_port; + } + int p3type = 0; diff --git a/libretroshare/src/libretroshare.pro b/libretroshare/src/libretroshare.pro index 643f0964f..013fa0531 100644 --- a/libretroshare/src/libretroshare.pro +++ b/libretroshare/src/libretroshare.pro @@ -541,6 +541,7 @@ SOURCES += util/folderiterator.cc \ util/rsdir.cc \ util/rsdiscspace.cc \ util/rsnet.cc \ + util/rsnet_ss.cc \ util/extaddrfinder.cc \ util/dnsresolver.cc \ util/rsprint.cc \ diff --git a/libretroshare/src/pqi/p3netmgr.cc b/libretroshare/src/pqi/p3netmgr.cc index 382c0f417..8eed3d093 100644 --- a/libretroshare/src/pqi/p3netmgr.cc +++ b/libretroshare/src/pqi/p3netmgr.cc @@ -135,6 +135,12 @@ p3NetMgrIMPL::p3NetMgrIMPL() mOldNatHole = RSNET_NATHOLE_UNKNOWN; sockaddr_storage_clear(mLocalAddr); sockaddr_storage_clear(mExtAddr); + + // force to IPv4 for the moment. + mLocalAddr.ss_family = AF_INET; + mExtAddr.ss_family = AF_INET; + + mVisState = 0 ; } diff --git a/libretroshare/src/pqi/pqiassist.h b/libretroshare/src/pqi/pqiassist.h index 2823571b7..5a2eaabb2 100644 --- a/libretroshare/src/pqi/pqiassist.h +++ b/libretroshare/src/pqi/pqiassist.h @@ -74,8 +74,8 @@ class PortForwardParams uint32_t fwdId; uint32_t status; uint32_t typeFlags; - struct sockaddr_in intAddr; - struct sockaddr_in extaddr; + struct sockaddr_storage intAddr; + struct sockaddr_storage extaddr; }; class pqiNetAssistFirewall: public pqiNetAssist diff --git a/libretroshare/src/pqi/pqinetwork.cc b/libretroshare/src/pqi/pqinetwork.cc index 4e3567e45..bc359edb6 100644 --- a/libretroshare/src/pqi/pqinetwork.cc +++ b/libretroshare/src/pqi/pqinetwork.cc @@ -946,9 +946,34 @@ int unix_fcntl_nonblock(int fd) } -int unix_connect(int fd, const struct sockaddr *serv_addr, socklen_t addrlen) +int unix_connect(int fd, const struct sockaddr *serv_addr, socklen_t socklen) { - int ret = connect(fd, serv_addr, addrlen); + std::cerr << "unix_connect()"; + std::cerr << std::endl; + + const struct sockaddr_storage *ss_addr = (struct sockaddr_storage *) serv_addr; + socklen_t len = socklen; + + switch (ss_addr->ss_family) + { + case AF_INET: + len = sizeof(struct sockaddr_in); + break; + case AF_INET6: + len = sizeof(struct sockaddr_in6); + break; + } + + if (len > socklen) + { + std::cerr << "unix_connect() ERROR len > socklen"; + std::cerr << std::endl; + + len = socklen; + //return EINVAL; + } + + int ret = connect(fd, serv_addr, len); /******************* WINDOWS SPECIFIC PART ******************/ #ifdef WINDOWS_SYS // WINDOWS diff --git a/libretroshare/src/pqi/pqissl.cc b/libretroshare/src/pqi/pqissl.cc index 10f35d946..6f68a543a 100644 --- a/libretroshare/src/pqi/pqissl.cc +++ b/libretroshare/src/pqi/pqissl.cc @@ -753,8 +753,9 @@ int pqissl::Initiate_Connection() waiting = WAITING_FAIL_INTERFACE; rslog(RSL_WARNING, pqisslzone, out); + // extra output for the moment. - //std::cerr << out.str(); + std::cerr << out; return -1; } diff --git a/libretroshare/src/pqi/pqissllistener.cc b/libretroshare/src/pqi/pqissllistener.cc index 49db80942..a9bbc9492 100644 --- a/libretroshare/src/pqi/pqissllistener.cc +++ b/libretroshare/src/pqi/pqissllistener.cc @@ -182,15 +182,19 @@ int pqissllistenbase::setuplisten() #ifdef OPEN_UNIVERSAL_PORT struct sockaddr_storage tmpaddr = laddr; sockaddr_storage_zeroip(tmpaddr); - if (0 != (err = bind(lsock, (struct sockaddr *) &tmpaddr, sizeof(tmpaddr)))) + if (0 != (err = universal_bind(lsock, (struct sockaddr *) &tmpaddr, sizeof(tmpaddr)))) #else - if (0 != (err = bind(lsock, (struct sockaddr *) &laddr, sizeof(laddr)))) + if (0 != (err = universal_bind(lsock, (struct sockaddr *) &laddr, sizeof(laddr)))) #endif { std::string out = "pqissllistenbase::setuplisten() Cannot Bind to Local Address!\n"; showSocketError(out); pqioutput(PQL_ALERT, pqissllistenzone, out); std::cerr << out << std::endl; + std::cerr << "laddr: " << sockaddr_storage_tostring(laddr) << std::endl; +#ifdef OPEN_UNIVERSAL_PORT + std::cerr << "Zeroed tmpaddr: " << sockaddr_storage_tostring(tmpaddr) << std::endl; +#endif exit(1); return -1; diff --git a/libretroshare/src/rsserver/p3peers.cc b/libretroshare/src/rsserver/p3peers.cc index 8854c3f25..9614708dd 100644 --- a/libretroshare/src/rsserver/p3peers.cc +++ b/libretroshare/src/rsserver/p3peers.cc @@ -999,12 +999,14 @@ bool p3Peers::loadDetailsFromStringCert(const std::string &certstr, RsPeerDetai pd.isOnlyGPGdetail = pd.id.empty(); pd.service_perm_flags = RS_SERVICE_PERM_ALL ; - if (pd.isHiddenNode) + if (!cert.hidden_node_string().empty()) { + pd.isHiddenNode = true; pd.hiddenNodeAddress = cert.hidden_node_string(); } else { + pd.isHiddenNode = false; pd.localAddr = cert.loc_ip_string(); pd.localPort = cert.loc_port_us(); pd.extAddr = cert.ext_ip_string(); diff --git a/libretroshare/src/rsserver/rsinit.cc b/libretroshare/src/rsserver/rsinit.cc index ec772ec2f..07f15f774 100644 --- a/libretroshare/src/rsserver/rsinit.cc +++ b/libretroshare/src/rsserver/rsinit.cc @@ -2110,22 +2110,16 @@ int RsServer::StartupRetroShare() // NOW WE BUILD THE SECOND STACK. // Create the Second UdpStack... Port should be random (but openable!). - - //#define MIN_RANDOM_PORT 30000 - //#define MAX_RANDOM_PORT 50000 + // We do this by binding to xx.xx.xx.xx:0 which which gives us a random port. struct sockaddr_in sndladdr; sockaddr_clear(&sndladdr); - // #ifdef LOCALNET_TESTING +#ifdef LOCALNET_TESTING + // // HACK Proxy Port near Dht Port - For Relay Testing. // uint16_t rndport = RsInitConfig::port + 3; // sndladdr.sin_port = htons(rndport); - // #else - // uint16_t rndport = MIN_RANDOM_PORT + RSRandom::random_u32() % (MAX_RANDOM_PORT - MIN_RANDOM_PORT); - // #endif - -#ifdef LOCALNET_TESTING rsFixedUdpStack *mProxyStack = new rsFixedUdpStack(UDP_TEST_RESTRICTED_LAYER, sndladdr); diff --git a/libretroshare/src/upnp/upnphandler_linux.cc b/libretroshare/src/upnp/upnphandler_linux.cc index 5d54b5581..f252d03f9 100644 --- a/libretroshare/src/upnp/upnphandler_linux.cc +++ b/libretroshare/src/upnp/upnphandler_linux.cc @@ -386,18 +386,22 @@ void upnphandler::setExternalPort(unsigned short eport_in) } /* as determined by uPnP */ -bool upnphandler::getInternalAddress(struct sockaddr_in &addr) +bool upnphandler::getInternalAddress(struct sockaddr_storage &addr) { dataMtx.lock(); /*** LOCK MUTEX ***/ - addr = upnp_iaddr; + bool valid = (upnpState >= RS_UPNP_S_ACTIVE); + // copy to universal addr. + sockaddr_storage_clear(addr); + sockaddr_storage_setipv4(addr, &upnp_iaddr); + dataMtx.unlock(); /*** UNLOCK MUTEX ***/ return valid; } -bool upnphandler::getExternalAddress(struct sockaddr_in &addr) +bool upnphandler::getExternalAddress(struct sockaddr_storage &addr) { std::string externalAdress = cUPnPControlPoint->getExternalAddress(); @@ -416,9 +420,13 @@ bool upnphandler::getExternalAddress(struct sockaddr_in &addr) inet_aton(externalIPAddress, &(upnp_eaddr.sin_addr)); upnp_eaddr.sin_family = AF_INET; upnp_eaddr.sin_port = htons(eport_curr); + + // copy to universal addr. + sockaddr_storage_clear(addr); + sockaddr_storage_setipv4(addr, &upnp_eaddr); + dataMtx.unlock(); /*** UNLOCK MUTEX ***/ - addr = upnp_eaddr; return true; } else diff --git a/libretroshare/src/upnp/upnphandler_linux.h b/libretroshare/src/upnp/upnphandler_linux.h index e0b8588a2..b0300dfc9 100644 --- a/libretroshare/src/upnp/upnphandler_linux.h +++ b/libretroshare/src/upnp/upnphandler_linux.h @@ -36,8 +36,8 @@ class upnphandler: public pqiNetAssistFirewall virtual void setInternalPort(unsigned short iport_in); virtual void setExternalPort(unsigned short eport_in); - virtual bool getInternalAddress(struct sockaddr_in &addr); - virtual bool getExternalAddress(struct sockaddr_in &addr); + virtual bool getInternalAddress(struct sockaddr_storage &addr); + virtual bool getExternalAddress(struct sockaddr_storage &addr); /* TO IMPLEMENT: New Port Forward interface to support as many ports as necessary */ virtual bool requestPortForward(const PortForwardParams ¶ms) { return false; } diff --git a/libretroshare/src/upnp/upnphandler_miniupnp.cc b/libretroshare/src/upnp/upnphandler_miniupnp.cc index b4cb3c199..3c2442527 100644 --- a/libretroshare/src/upnp/upnphandler_miniupnp.cc +++ b/libretroshare/src/upnp/upnphandler_miniupnp.cc @@ -535,7 +535,7 @@ void upnphandler::setExternalPort(unsigned short eport_in) } /* as determined by uPnP */ -bool upnphandler::getInternalAddress(struct sockaddr_in &addr) +bool upnphandler::getInternalAddress(struct sockaddr_storage &addr) { // std::cerr << "UPnPHandler::getInternalAddress() pre Lock!" << std::endl; dataMtx.lock(); /*** LOCK MUTEX ***/ @@ -543,7 +543,10 @@ bool upnphandler::getInternalAddress(struct sockaddr_in &addr) std::cerr << "UPnPHandler::getInternalAddress()" << std::endl; - addr = upnp_iaddr; + // copy to universal addr. + sockaddr_storage_clear(addr); + sockaddr_storage_setipv4(addr, &upnp_iaddr); + bool valid = (upnpState >= RS_UPNP_S_ACTIVE); dataMtx.unlock(); /*** UNLOCK MUTEX ***/ @@ -551,14 +554,18 @@ bool upnphandler::getInternalAddress(struct sockaddr_in &addr) return valid; } -bool upnphandler::getExternalAddress(struct sockaddr_in &addr) +bool upnphandler::getExternalAddress(struct sockaddr_storage &addr) { // std::cerr << "UPnPHandler::getExternalAddress() pre Lock!" << std::endl; dataMtx.lock(); /*** LOCK MUTEX ***/ // std::cerr << "UPnPHandler::getExternalAddress() postLock!" << std::endl; std::cerr << "UPnPHandler::getExternalAddress()" << std::endl; - addr = upnp_eaddr; + + // copy to universal addr. + sockaddr_storage_clear(addr); + sockaddr_storage_setipv4(addr, &upnp_eaddr); + bool valid = (upnpState == RS_UPNP_S_ACTIVE); dataMtx.unlock(); /*** UNLOCK MUTEX ***/ diff --git a/libretroshare/src/upnp/upnphandler_miniupnp.h b/libretroshare/src/upnp/upnphandler_miniupnp.h index c30b3e39a..6b4660e32 100644 --- a/libretroshare/src/upnp/upnphandler_miniupnp.h +++ b/libretroshare/src/upnp/upnphandler_miniupnp.h @@ -62,8 +62,8 @@ virtual bool getActive(); virtual void setInternalPort(unsigned short iport_in); virtual void setExternalPort(unsigned short eport_in); -virtual bool getInternalAddress(struct sockaddr_in &addr); -virtual bool getExternalAddress(struct sockaddr_in &addr); +virtual bool getInternalAddress(struct sockaddr_storage &addr); +virtual bool getExternalAddress(struct sockaddr_storage &addr); /* TO IMPLEMENT: New Port Forward interface to support as many ports as necessary */ virtual bool requestPortForward(const PortForwardParams &/*params*/) { return false; } diff --git a/libretroshare/src/util/rsnet.h b/libretroshare/src/util/rsnet.h index 7b854c00c..01f73a313 100644 --- a/libretroshare/src/util/rsnet.h +++ b/libretroshare/src/util/rsnet.h @@ -78,6 +78,10 @@ std::string rs_inet_ntoa(struct in_addr in); /***************************/ // sockaddr_storage fns. +// Standard bind, on OSX anyway will not accept a longer socklen for IPv4. +// so hidding details behind function. +int universal_bind(int fd, const struct sockaddr *addr, socklen_t socklen); + void sockaddr_storage_clear(struct sockaddr_storage &addr); // mods. @@ -86,9 +90,13 @@ bool sockaddr_storage_copyip(struct sockaddr_storage &dst, const struct sockaddr uint16_t sockaddr_storage_port(const struct sockaddr_storage &addr); bool sockaddr_storage_setport(struct sockaddr_storage &addr, uint16_t port); +bool sockaddr_storage_setipv4(struct sockaddr_storage &addr, const sockaddr_in *addr_ipv4); +bool sockaddr_storage_setipv6(struct sockaddr_storage &addr, const sockaddr_in6 *addr_ipv6); + bool sockaddr_storage_ipv4_aton(struct sockaddr_storage &addr, const char *name); bool sockaddr_storage_ipv4_setport(struct sockaddr_storage &addr, const uint16_t port); + // comparisons. bool operator<(const struct sockaddr_storage &a, const struct sockaddr_storage &b); diff --git a/libretroshare/src/util/rsnet_ss.cc b/libretroshare/src/util/rsnet_ss.cc new file mode 100644 index 000000000..ed4f188eb --- /dev/null +++ b/libretroshare/src/util/rsnet_ss.cc @@ -0,0 +1,971 @@ +/* + * libretroshare/src/util: rsnet_ss.cc + * + * sockaddr_storage functions for RetroShare. + * + * Copyright 2013-2013 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.1 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 "util/rsnet.h" +#include "util/rsstring.h" + +/***************************** Internal Helper Fns ******************************/ + +/******************************** Casting **************************************/ +struct sockaddr_in *to_ipv4_ptr(struct sockaddr_storage &addr); +struct sockaddr_in6 *to_ipv6_ptr(struct sockaddr_storage &addr); + +const struct sockaddr_in *to_const_ipv4_ptr(const struct sockaddr_storage &addr); +const struct sockaddr_in6 *to_const_ipv6_ptr(const struct sockaddr_storage &addr); + + +/******************************** Set / Clear ***********************************/ + +bool sockaddr_storage_ipv4_zeroip(struct sockaddr_storage &addr); +bool sockaddr_storage_ipv4_copyip(struct sockaddr_storage &dst, const struct sockaddr_storage &src); + +uint16_t sockaddr_storage_ipv4_port(const struct sockaddr_storage &addr); +bool sockaddr_storage_ipv4_setport(struct sockaddr_storage &addr, uint16_t port); + +bool sockaddr_storage_ipv6_zeroip(struct sockaddr_storage &addr); +bool sockaddr_storage_ipv6_copyip(struct sockaddr_storage &dst, const struct sockaddr_storage &src); + +uint16_t sockaddr_storage_ipv6_port(const struct sockaddr_storage &addr); +bool sockaddr_storage_ipv6_setport(struct sockaddr_storage &addr, uint16_t port); + +/******************************** Comparisions **********************************/ + +bool sockaddr_storage_ipv4_lessthan(const struct sockaddr_storage &addr, const struct sockaddr_storage &addr2); +bool sockaddr_storage_ipv4_same(const struct sockaddr_storage &addr, const struct sockaddr_storage &addr2); +bool sockaddr_storage_ipv4_sameip(const struct sockaddr_storage &addr, const struct sockaddr_storage &addr2); +bool sockaddr_storage_ipv4_samenet(const struct sockaddr_storage &addr, const struct sockaddr_storage &addr2); +bool sockaddr_storage_ipv4_samesubnet(const struct sockaddr_storage &addr, const struct sockaddr_storage &addr2); + +bool sockaddr_storage_ipv6_lessthan(const struct sockaddr_storage &addr, const struct sockaddr_storage &addr2); +bool sockaddr_storage_ipv6_same(const struct sockaddr_storage &addr, const struct sockaddr_storage &addr2); +bool sockaddr_storage_ipv6_sameip(const struct sockaddr_storage &addr, const struct sockaddr_storage &addr2); +bool sockaddr_storage_ipv6_samenet(const struct sockaddr_storage &addr, const struct sockaddr_storage &addr2); +bool sockaddr_storage_ipv6_samesubnet(const struct sockaddr_storage &addr, const struct sockaddr_storage &addr2); + + +/********************************* Output ***********************************/ +std::string sockaddr_storage_ipv4_iptostring(const struct sockaddr_storage &addr); +std::string sockaddr_storage_ipv6_iptostring(const struct sockaddr_storage &addr); + +/********************************* Net Checks ***********************************/ +bool sockaddr_storage_ipv4_isnull(const struct sockaddr_storage &addr); +bool sockaddr_storage_ipv4_isValidNet(const struct sockaddr_storage &addr); +bool sockaddr_storage_ipv4_isLoopbackNet(const struct sockaddr_storage &addr); +bool sockaddr_storage_ipv4_isPrivateNet(const struct sockaddr_storage &addr); +bool sockaddr_storage_ipv4_isExternalNet(const struct sockaddr_storage &addr); + +bool sockaddr_storage_ipv6_isnull(const struct sockaddr_storage &addr); +bool sockaddr_storage_ipv6_isValidNet(const struct sockaddr_storage &addr); +bool sockaddr_storage_ipv6_isLoopbackNet(const struct sockaddr_storage &addr); +bool sockaddr_storage_ipv6_isPrivateNet(const struct sockaddr_storage &addr); +bool sockaddr_storage_ipv6_isExternalNet(const struct sockaddr_storage &addr); + + +/***************************/ + +/******************************** Socket Fns ***********************************/ +// Standard bind, on OSX anyway will not accept a longer socklen for IPv4. +// so hidding details behind function. +int universal_bind(int fd, const struct sockaddr *addr, socklen_t socklen) +{ + std::cerr << "universal_bind()"; + std::cerr << std::endl; + + const struct sockaddr_storage *ss_addr = (struct sockaddr_storage *) addr; + socklen_t len = socklen; + + switch (ss_addr->ss_family) + { + case AF_INET: + len = sizeof(struct sockaddr_in); + break; + case AF_INET6: + len = sizeof(struct sockaddr_in6); + break; + } + + if (len > socklen) + { + std::cerr << "universal_bind() ERROR len > socklen"; + std::cerr << std::endl; + + len = socklen; + //return EINVAL; + } + + return bind(fd, addr, len); +} + + + + +/******************************** Set / Clear ***********************************/ + +void sockaddr_storage_clear(struct sockaddr_storage &addr) +{ + memset(&addr, 0, sizeof(addr)); +} + +// mods. +bool sockaddr_storage_zeroip(struct sockaddr_storage &addr) +{ + std::cerr << "sockaddr_storage_zeroip()"; + std::cerr << std::endl; + switch(addr.ss_family) + { + case AF_INET: + return sockaddr_storage_ipv4_zeroip(addr); + break; + case AF_INET6: + return sockaddr_storage_ipv6_zeroip(addr); + break; + default: + std::cerr << "sockaddr_storage_zeroip() invalid addr.ss_family clearing whole address"; + std::cerr << std::endl; + sockaddr_storage_clear(addr); + break; + } + return false; +} + +bool sockaddr_storage_copyip(struct sockaddr_storage &dst, const struct sockaddr_storage &src) +{ + std::cerr << "sockaddr_storage_copyip()"; + std::cerr << std::endl; + switch(src.ss_family) + { + case AF_INET: + return sockaddr_storage_ipv4_copyip(dst, src); + break; + case AF_INET6: + return sockaddr_storage_ipv6_copyip(dst, src); + break; + default: + std::cerr << "sockaddr_storage_copyip() invalid addr.ss_family"; + std::cerr << std::endl; + break; + } + return false; +} + + +uint16_t sockaddr_storage_port(const struct sockaddr_storage &addr) +{ + std::cerr << "sockaddr_storage_port()"; + std::cerr << std::endl; + switch(addr.ss_family) + { + case AF_INET: + return sockaddr_storage_ipv4_port(addr); + break; + case AF_INET6: + return sockaddr_storage_ipv6_port(addr); + break; + default: + std::cerr << "sockaddr_storage_port() invalid addr.ss_family"; + std::cerr << std::endl; + break; + } + return 0; +} + +bool sockaddr_storage_setport(struct sockaddr_storage &addr, uint16_t port) +{ + std::cerr << "sockaddr_storage_setport()"; + std::cerr << std::endl; + switch(addr.ss_family) + { + case AF_INET: + return sockaddr_storage_ipv4_setport(addr, port); + break; + case AF_INET6: + return sockaddr_storage_ipv6_setport(addr, port); + break; + default: + std::cerr << "sockaddr_storage_setport() invalid addr.ss_family"; + std::cerr << std::endl; + break; + } + return false; +} + + +bool sockaddr_storage_setipv4(struct sockaddr_storage &addr, const sockaddr_in *addr_ipv4) +{ + std::cerr << "sockaddr_storage_setipv4()"; + std::cerr << std::endl; + + sockaddr_storage_clear(addr); + struct sockaddr_in *ipv4_ptr = to_ipv4_ptr(addr); + + ipv4_ptr->sin_family = AF_INET; + ipv4_ptr->sin_addr = addr_ipv4->sin_addr; + ipv4_ptr->sin_port = addr_ipv4->sin_port; + + return true; +} + +bool sockaddr_storage_setipv6(struct sockaddr_storage &addr, const sockaddr_in6 *addr_ipv6) +{ + std::cerr << "sockaddr_storage_setipv6()"; + std::cerr << std::endl; + + sockaddr_storage_clear(addr); + struct sockaddr_in6 *ipv6_ptr = to_ipv6_ptr(addr); + + ipv6_ptr->sin6_family = AF_INET6; + ipv6_ptr->sin6_addr = addr_ipv6->sin6_addr; + ipv6_ptr->sin6_port = addr_ipv6->sin6_port; + + return true; +} + + +bool sockaddr_storage_ipv4_aton(struct sockaddr_storage &addr, const char *name) +{ + std::cerr << "sockaddr_storage_ipv4_aton()"; + std::cerr << std::endl; + + struct sockaddr_in *ipv4_ptr = to_ipv4_ptr(addr); + ipv4_ptr->sin_family = AF_INET; + return (1 == inet_aton(name, &(ipv4_ptr->sin_addr))); +} + + +/******************************** Comparisions **********************************/ + +bool operator<(const struct sockaddr_storage &a, const struct sockaddr_storage &b) +{ + if (!sockaddr_storage_samefamily(a, b)) + { + return (a.ss_family < b.ss_family); + } + + switch(a.ss_family) + { + case AF_INET: + return sockaddr_storage_ipv4_lessthan(a, b); + break; + case AF_INET6: + return sockaddr_storage_ipv6_lessthan(a, b); + break; + default: + std::cerr << "sockaddr_storage_operator<() INVALID Family - error"; + std::cerr << std::endl; + break; + } + return false; +} + + +bool sockaddr_storage_same(const struct sockaddr_storage &addr, const struct sockaddr_storage &addr2) +{ + std::cerr << "sockaddr_storage_same()"; + std::cerr << std::endl; + + if (!sockaddr_storage_samefamily(addr, addr2)) + return false; + + switch(addr.ss_family) + { + case AF_INET: + return sockaddr_storage_ipv4_same(addr, addr2); + break; + case AF_INET6: + return sockaddr_storage_ipv6_same(addr, addr2); + break; + default: + std::cerr << "sockaddr_storage_same() INVALID Family - error"; + std::cerr << std::endl; + break; + } + return false; +} + + +bool sockaddr_storage_samefamily(const struct sockaddr_storage &addr, const struct sockaddr_storage &addr2) +{ + std::cerr << "sockaddr_storage_samefamily()"; + std::cerr << std::endl; + + return (addr.ss_family == addr2.ss_family); +} + +bool sockaddr_storage_sameip(const struct sockaddr_storage &addr, const struct sockaddr_storage &addr2) +{ + std::cerr << "sockaddr_storage_sameip()"; + std::cerr << std::endl; + + if (!sockaddr_storage_samefamily(addr, addr2)) + return false; + + switch(addr.ss_family) + { + case AF_INET: + return sockaddr_storage_ipv4_sameip(addr, addr2); + break; + case AF_INET6: + return sockaddr_storage_ipv6_sameip(addr, addr2); + break; + default: + std::cerr << "sockaddr_storage_sameip() INVALID Family - error"; + std::cerr << std::endl; + break; + } + return false; +} + + +bool sockaddr_storage_samenet(const struct sockaddr_storage &addr, const struct sockaddr_storage &addr2) +{ + std::cerr << "sockaddr_storage_samenet()"; + std::cerr << std::endl; + + if (!sockaddr_storage_samefamily(addr, addr2)) + return false; + + switch(addr.ss_family) + { + case AF_INET: + return sockaddr_storage_ipv4_samenet(addr, addr2); + break; + case AF_INET6: + return sockaddr_storage_ipv6_samenet(addr, addr2); + break; + default: + std::cerr << "sockaddr_storage_samenet() INVALID Family - error"; + std::cerr << std::endl; + break; + } + return false; +} + +bool sockaddr_storage_samesubnet(const struct sockaddr_storage &addr, const struct sockaddr_storage &addr2) +{ + std::cerr << "sockaddr_storage_samesubnet()"; + std::cerr << std::endl; + + if (!sockaddr_storage_samefamily(addr, addr2)) + return false; + + switch(addr.ss_family) + { + case AF_INET: + return sockaddr_storage_ipv4_samesubnet(addr, addr2); + break; + case AF_INET6: + return sockaddr_storage_ipv6_samesubnet(addr, addr2); + break; + default: + std::cerr << "sockaddr_storage_samesubnet() INVALID Family - error"; + std::cerr << std::endl; + break; + } + return false; +} + + +/********************************* Output ***********************************/ + +std::string sockaddr_storage_tostring(const struct sockaddr_storage &addr) +{ + std::string output; + output += sockaddr_storage_familytostring(addr); + + switch(addr.ss_family) + { + case AF_INET: + case AF_INET6: + output += "="; + output += sockaddr_storage_iptostring(addr); + output += ":"; + output += sockaddr_storage_porttostring(addr); + break; + default: + break; + } + return output; +} + + + + +std::string sockaddr_storage_familytostring(const struct sockaddr_storage &addr) +{ + std::string output; + switch(addr.ss_family) + { + case AF_INET: + output = "IPv4"; + break; + case AF_INET6: + output = "IPv6"; + break; + default: + output = "AF_INVALID"; + break; + } + return output; +} + +std::string sockaddr_storage_iptostring(const struct sockaddr_storage &addr) +{ + std::string output; + switch(addr.ss_family) + { + case AF_INET: + output = sockaddr_storage_ipv4_iptostring(addr); + break; + case AF_INET6: + output = sockaddr_storage_ipv6_iptostring(addr); + break; + default: + output = "INVALID_IP"; + break; + } + return output; +} + +std::string sockaddr_storage_porttostring(const struct sockaddr_storage &addr) +{ + std::string output; + uint16_t port = sockaddr_storage_port(addr); + rs_sprintf(output, "%u", port); + return output; +} + + +/********************************* Net Checks ***********************************/ +bool sockaddr_storage_isnull(const struct sockaddr_storage &addr) +{ + std::cerr << "sockaddr_storage_isnull()"; + std::cerr << std::endl; + + if (addr.ss_family == 0) + return true; + + switch(addr.ss_family) + { + case AF_INET: + return sockaddr_storage_ipv4_isnull(addr); + break; + case AF_INET6: + return sockaddr_storage_ipv6_isnull(addr); + break; + default: + return true; + break; + } + return true; +} + +bool sockaddr_storage_isValidNet(const struct sockaddr_storage &addr) +{ + std::cerr << "sockaddr_storage_isValidNet()"; + std::cerr << std::endl; + + switch(addr.ss_family) + { + case AF_INET: + return sockaddr_storage_ipv4_isValidNet(addr); + break; + case AF_INET6: + return sockaddr_storage_ipv6_isValidNet(addr); + break; + default: + std::cerr << "sockaddr_storage_isValidNet() INVALID Family - error"; + std::cerr << std::endl; + break; + } + return false; +} + +bool sockaddr_storage_isLoopbackNet(const struct sockaddr_storage &addr) +{ + std::cerr << "sockaddr_storage_isLoopbackNet()"; + std::cerr << std::endl; + + switch(addr.ss_family) + { + case AF_INET: + return sockaddr_storage_ipv4_isLoopbackNet(addr); + break; + case AF_INET6: + return sockaddr_storage_ipv6_isLoopbackNet(addr); + break; + default: + std::cerr << "sockaddr_storage_isLoopbackNet() INVALID Family - error"; + std::cerr << std::endl; + break; + } + return false; +} + + +bool sockaddr_storage_isPrivateNet(const struct sockaddr_storage &addr) +{ + std::cerr << "sockaddr_storage_isPrivateNet()"; + std::cerr << std::endl; + + switch(addr.ss_family) + { + case AF_INET: + return sockaddr_storage_ipv4_isPrivateNet(addr); + break; + case AF_INET6: + return sockaddr_storage_ipv6_isPrivateNet(addr); + break; + default: + std::cerr << "sockaddr_storage_isPrivateNet() INVALID Family - error"; + std::cerr << std::endl; + break; + } + return false; +} + + +bool sockaddr_storage_isExternalNet(const struct sockaddr_storage &addr) +{ + std::cerr << "sockaddr_storage_isExternalNet()"; + std::cerr << std::endl; + + switch(addr.ss_family) + { + case AF_INET: + return sockaddr_storage_ipv4_isExternalNet(addr); + break; + case AF_INET6: + return sockaddr_storage_ipv6_isExternalNet(addr); + break; + default: + std::cerr << "sockaddr_storage_isExternalNet() INVALID Family - error"; + std::cerr << std::endl; + break; + } + return false; +} + + + + + +/***************************** Internal Helper Fns ******************************/ + + +/******************************** Casting **************************************/ + +struct sockaddr_in *to_ipv4_ptr(struct sockaddr_storage &addr) +{ + struct sockaddr_in *ipv4_ptr = (struct sockaddr_in *) &addr; + return ipv4_ptr; +} + +struct sockaddr_in6 *to_ipv6_ptr(struct sockaddr_storage &addr) +{ + struct sockaddr_in6 *ipv6_ptr = (struct sockaddr_in6 *) &addr; + return ipv6_ptr; +} + +const struct sockaddr_in *to_const_ipv4_ptr(const struct sockaddr_storage &addr) +{ + const struct sockaddr_in *ipv4_ptr = (const struct sockaddr_in *) &addr; + return ipv4_ptr; +} + +const struct sockaddr_in6 *to_const_ipv6_ptr(const struct sockaddr_storage &addr) +{ + const struct sockaddr_in6 *ipv6_ptr = (const struct sockaddr_in6 *) &addr; + return ipv6_ptr; +} + + +/******************************** Set / Clear ***********************************/ + +bool sockaddr_storage_ipv4_zeroip(struct sockaddr_storage &addr) +{ + std::cerr << "sockaddr_storage_ipv4_zeroip()"; + std::cerr << std::endl; + + struct sockaddr_in *ipv4_ptr = to_ipv4_ptr(addr); + memset(&(ipv4_ptr->sin_addr), 0, sizeof(ipv4_ptr->sin_addr)); + return true; +} + + +bool sockaddr_storage_ipv4_copyip(struct sockaddr_storage &dst, const struct sockaddr_storage &src) +{ + std::cerr << "sockaddr_storage_ipv4_copyip()"; + std::cerr << std::endl; + + struct sockaddr_in *dst_ptr = to_ipv4_ptr(dst); + const struct sockaddr_in *src_ptr = to_const_ipv4_ptr(src); + + dst_ptr->sin_family = AF_INET; + memcpy(&(dst_ptr->sin_addr), &(src_ptr->sin_addr), sizeof(src_ptr->sin_addr)); + return true; +} + +uint16_t sockaddr_storage_ipv4_port(const struct sockaddr_storage &addr) +{ + std::cerr << "sockaddr_storage_ipv4_port()"; + std::cerr << std::endl; + + const struct sockaddr_in *ipv4_ptr = to_const_ipv4_ptr(addr); + uint16_t port = ntohs(ipv4_ptr->sin_port); + return port; +} + +bool sockaddr_storage_ipv4_setport(struct sockaddr_storage &addr, uint16_t port) +{ + std::cerr << "sockaddr_storage_ipv4_setport()"; + std::cerr << std::endl; + + struct sockaddr_in *ipv4_ptr = to_ipv4_ptr(addr); + ipv4_ptr->sin_port = htons(port); + return true; +} + +bool sockaddr_storage_ipv6_zeroip(struct sockaddr_storage &addr) +{ + std::cerr << "sockaddr_storage_ipv6_zeroip()"; + std::cerr << std::endl; + + struct sockaddr_in6 *ipv6_ptr = to_ipv6_ptr(addr); + memset(&(ipv6_ptr->sin6_addr), 0, sizeof(ipv6_ptr->sin6_addr)); + return true; +} + +bool sockaddr_storage_ipv6_copyip(struct sockaddr_storage &dst, const struct sockaddr_storage &src) +{ + std::cerr << "sockaddr_storage_ipv6_copyip()"; + std::cerr << std::endl; + + struct sockaddr_in6 *dst_ptr = to_ipv6_ptr(dst); + const struct sockaddr_in6 *src_ptr = to_const_ipv6_ptr(src); + + dst_ptr->sin6_family = AF_INET6; + memcpy(&(dst_ptr->sin6_addr), &(src_ptr->sin6_addr), sizeof(src_ptr->sin6_addr)); + return true; +} + +uint16_t sockaddr_storage_ipv6_port(const struct sockaddr_storage &addr) +{ + std::cerr << "sockaddr_storage_ipv6_port()"; + std::cerr << std::endl; + + const struct sockaddr_in6 *ipv6_ptr = to_const_ipv6_ptr(addr); + uint16_t port = ntohs(ipv6_ptr->sin6_port); + return port; +} + +bool sockaddr_storage_ipv6_setport(struct sockaddr_storage &addr, uint16_t port) +{ + std::cerr << "sockaddr_storage_ipv6_setport()"; + std::cerr << std::endl; + + struct sockaddr_in6 *ipv6_ptr = to_ipv6_ptr(addr); + ipv6_ptr->sin6_port = htons(port); + return true; +} + + +/******************************** Comparisions **********************************/ + +bool sockaddr_storage_ipv4_lessthan(const struct sockaddr_storage &addr, const struct sockaddr_storage &addr2) +{ + std::cerr << "sockaddr_storage_ipv4_lessthan()"; + std::cerr << std::endl; + + const struct sockaddr_in *ptr1 = to_const_ipv4_ptr(addr); + const struct sockaddr_in *ptr2 = to_const_ipv4_ptr(addr2); + + if (ptr1->sin_addr.s_addr == ptr2->sin_addr.s_addr) + { + return ptr1->sin_port < ptr2->sin_port; + } + return (ptr1->sin_addr.s_addr < ptr2->sin_addr.s_addr); +} + +bool sockaddr_storage_ipv4_same(const struct sockaddr_storage &addr, const struct sockaddr_storage &addr2) +{ + std::cerr << "sockaddr_storage_ipv4_same()"; + std::cerr << std::endl; + + const struct sockaddr_in *ptr1 = to_const_ipv4_ptr(addr); + const struct sockaddr_in *ptr2 = to_const_ipv4_ptr(addr2); + + return (ptr1->sin_addr.s_addr == ptr2->sin_addr.s_addr) && + (ptr1->sin_port == ptr2->sin_port); +} + +bool sockaddr_storage_ipv4_sameip(const struct sockaddr_storage &addr, const struct sockaddr_storage &addr2) +{ + std::cerr << "sockaddr_storage_ipv4_sameip()"; + std::cerr << std::endl; + + const struct sockaddr_in *ptr1 = to_const_ipv4_ptr(addr); + const struct sockaddr_in *ptr2 = to_const_ipv4_ptr(addr2); + + return (ptr1->sin_addr.s_addr == ptr2->sin_addr.s_addr); +} + + +bool sockaddr_storage_ipv4_samenet(const struct sockaddr_storage &addr, const struct sockaddr_storage &addr2) +{ + (void) addr; + (void) addr2; + + std::cerr << "sockaddr_storage_ipv4_samenet()"; + std::cerr << std::endl; + + return false; +} + +bool sockaddr_storage_ipv4_samesubnet(const struct sockaddr_storage &addr, const struct sockaddr_storage &addr2) +{ + (void) addr; + (void) addr2; + + std::cerr << "sockaddr_storage_ipv4_samesubnet()"; + std::cerr << std::endl; + + return false; +} + +// IPV6 +bool sockaddr_storage_ipv6_lessthan(const struct sockaddr_storage &addr, const struct sockaddr_storage &addr2) +{ + std::cerr << "sockaddr_storage_ipv6_lessthan()"; + std::cerr << std::endl; + + const struct sockaddr_in6 *ptr1 = to_const_ipv6_ptr(addr); + const struct sockaddr_in6 *ptr2 = to_const_ipv6_ptr(addr2); + + uint32_t *ip6addr1 = (uint32_t *) ptr1->sin6_addr.s6_addr; + uint32_t *ip6addr2 = (uint32_t *) ptr2->sin6_addr.s6_addr; + for(int i = 0; i < 4; i++) + { + if (ip6addr1[i] == ip6addr2[i]) + { + continue; + } + + return (ip6addr1[i] < ip6addr2[i]); + } + + return (ptr1->sin6_port < ptr2->sin6_port); +} + +bool sockaddr_storage_ipv6_same(const struct sockaddr_storage &addr, const struct sockaddr_storage &addr2) +{ + std::cerr << "sockaddr_storage_ipv6_same()"; + std::cerr << std::endl; + const struct sockaddr_in6 *ptr1 = to_const_ipv6_ptr(addr); + const struct sockaddr_in6 *ptr2 = to_const_ipv6_ptr(addr2); + + return sockaddr_storage_ipv6_sameip(addr, addr2) && (ptr1->sin6_port == ptr2->sin6_port); +} + +bool sockaddr_storage_ipv6_sameip(const struct sockaddr_storage &addr, const struct sockaddr_storage &addr2) +{ + std::cerr << "sockaddr_storage_ipv6_sameip()"; + std::cerr << std::endl; + + const struct sockaddr_in6 *ptr1 = to_const_ipv6_ptr(addr); + const struct sockaddr_in6 *ptr2 = to_const_ipv6_ptr(addr2); + + uint32_t *ip6addr1 = (uint32_t *) ptr1->sin6_addr.s6_addr; + uint32_t *ip6addr2 = (uint32_t *) ptr2->sin6_addr.s6_addr; + + for(int i = 0; i < 4; i++) + { + if (ip6addr1[i] != ip6addr2[i]) + { + return false; + } + } + return true; +} + + +bool sockaddr_storage_ipv6_samenet(const struct sockaddr_storage &addr, const struct sockaddr_storage &addr2) +{ + (void) addr; + (void) addr2; + + std::cerr << "sockaddr_storage_ipv6_samenet() TODO"; + std::cerr << std::endl; + + return false; +} + +bool sockaddr_storage_ipv6_samesubnet(const struct sockaddr_storage &addr, const struct sockaddr_storage &addr2) +{ + (void) addr; + (void) addr2; + + std::cerr << "sockaddr_storage_ipv6_samesubnet() TODO"; + std::cerr << std::endl; + + return false; +} + + +/********************************* Output ***********************************/ +std::string sockaddr_storage_ipv4_iptostring(const struct sockaddr_storage &addr) +{ + const struct sockaddr_in *ptr = to_const_ipv4_ptr(addr); + std::string output; + output = rs_inet_ntoa(ptr->sin_addr); + return output; +} + +std::string sockaddr_storage_ipv6_iptostring(const struct sockaddr_storage & /* addr */) +{ + std::string output; + output += "IPv6-ADDRESS-TODO"; + return output; +} + + + + + +/********************************* Net Checks ***********************************/ +bool sockaddr_storage_ipv4_isnull(const struct sockaddr_storage &addr) +{ + std::cerr << "sockaddr_storage_ipv4_isnull()"; + std::cerr << std::endl; + + const struct sockaddr_in *ptr1 = to_const_ipv4_ptr(addr); + if (ptr1->sin_family != AF_INET) + { + return true; + } + if ((ptr1->sin_addr.s_addr == 0) || (ptr1->sin_addr.s_addr == 1)) + { + return true; + } + return false; +} + +bool sockaddr_storage_ipv4_isValidNet(const struct sockaddr_storage &addr) +{ + std::cerr << "sockaddr_storage_ipv4_isValidNet()"; + std::cerr << std::endl; + + const struct sockaddr_in *ptr1 = to_const_ipv4_ptr(addr); + if (ptr1->sin_family != AF_INET) + { + return false; + } + return isValidNet(&(ptr1->sin_addr)); +} + + +bool sockaddr_storage_ipv4_isLoopbackNet(const struct sockaddr_storage &addr) +{ + std::cerr << "sockaddr_storage_ipv4_isLoopbackNet()"; + std::cerr << std::endl; + + + const struct sockaddr_in *ptr1 = to_const_ipv4_ptr(addr); + if (ptr1->sin_family != AF_INET) + { + return false; + } + return isLoopbackNet(&(ptr1->sin_addr)); +} + +bool sockaddr_storage_ipv4_isPrivateNet(const struct sockaddr_storage &addr) +{ + std::cerr << "sockaddr_storage_ipv4_isPrivateNet()"; + std::cerr << std::endl; + + + const struct sockaddr_in *ptr1 = to_const_ipv4_ptr(addr); + if (ptr1->sin_family != AF_INET) + { + return false; + } + return isPrivateNet(&(ptr1->sin_addr)); +} + +bool sockaddr_storage_ipv4_isExternalNet(const struct sockaddr_storage &addr) +{ + std::cerr << "sockaddr_storage_ipv4_isExternalNet()"; + std::cerr << std::endl; + + const struct sockaddr_in *ptr1 = to_const_ipv4_ptr(addr); + if (ptr1->sin_family != AF_INET) + { + return false; + } + return isExternalNet(&(ptr1->sin_addr)); +} + + +bool sockaddr_storage_ipv6_isnull(const struct sockaddr_storage &addr) +{ + std::cerr << "sockaddr_storage_ipv6_isnull() TODO"; + std::cerr << std::endl; + + return false; +} + +bool sockaddr_storage_ipv6_isValidNet(const struct sockaddr_storage &addr) +{ + std::cerr << "sockaddr_storage_ipv6_isValidNet() TODO"; + std::cerr << std::endl; + + return false; +} + +bool sockaddr_storage_ipv6_isLoopbackNet(const struct sockaddr_storage &addr) +{ + std::cerr << "sockaddr_storage_ipv6_isLoopbackNet() TODO"; + std::cerr << std::endl; + + return false; +} + +bool sockaddr_storage_ipv6_isPrivateNet(const struct sockaddr_storage &addr) +{ + std::cerr << "sockaddr_storage_ipv6_isPrivateNet() TODO"; + std::cerr << std::endl; + + return false; +} + +bool sockaddr_storage_ipv6_isExternalNet(const struct sockaddr_storage &addr) +{ + std::cerr << "sockaddr_storage_ipv6_isExternalNet() TODO"; + std::cerr << std::endl; + + return false; +} + + + From 72c7569619f58aee7843af9fbf4a50bfc7c0665a Mon Sep 17 00:00:00 2001 From: thunder2 Date: Thu, 26 Sep 2013 23:53:06 +0000 Subject: [PATCH 17/83] Fixed compile of libretroshare on Windows. Cleaned some includes of openssl. git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@6769 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/gxs/rsgenexchange.cc | 5 ----- libretroshare/src/pqi/authgpg.h | 7 ------- libretroshare/src/pqi/authssl.cc | 5 +---- libretroshare/src/pqi/authssl.h | 2 +- libretroshare/src/pqi/pqihash.h | 1 + libretroshare/src/pqi/pqinetwork.h | 5 ----- libretroshare/src/pqi/pqissl.cc | 14 ++++++++++++++ libretroshare/src/pqi/pqissl.h | 8 +++----- libretroshare/src/pqi/pqisslproxy.cc | 8 ++++---- libretroshare/src/pqi/pqisslproxy.h | 2 -- libretroshare/src/pqi/pqissludp.cc | 2 +- libretroshare/src/pqi/pqissludp.h | 2 -- libretroshare/src/pqi/sslfns.h | 1 - libretroshare/src/rsserver/rsinit.cc | 2 ++ libretroshare/src/util/rsnet.h | 9 ++++----- retroshare-gui/src/gui/RetroShareLink.cpp | 1 + 16 files changed, 32 insertions(+), 42 deletions(-) diff --git a/libretroshare/src/gxs/rsgenexchange.cc b/libretroshare/src/gxs/rsgenexchange.cc index 5133d79ca..158bd2798 100644 --- a/libretroshare/src/gxs/rsgenexchange.cc +++ b/libretroshare/src/gxs/rsgenexchange.cc @@ -26,11 +26,6 @@ #include -#include -#include -#include -#include - #include "pqi/pqihash.h" #include "rsgenexchange.h" #include "gxssecurity.h" diff --git a/libretroshare/src/pqi/authgpg.h b/libretroshare/src/pqi/authgpg.h index 9ee944df5..2f476bd00 100644 --- a/libretroshare/src/pqi/authgpg.h +++ b/libretroshare/src/pqi/authgpg.h @@ -39,14 +39,7 @@ #ifndef RS_GPG_AUTH_HEADER #define RS_GPG_AUTH_HEADER -#include -#include #include "util/rsthreads.h" -//#include "retroshare/rspeers.h" -#include -#include -#include -#include #include "pqi/p3cfgmgr.h" #include "pgp/pgphandler.h" diff --git a/libretroshare/src/pqi/authssl.cc b/libretroshare/src/pqi/authssl.cc index 7cf8734e0..d8de4e042 100644 --- a/libretroshare/src/pqi/authssl.cc +++ b/libretroshare/src/pqi/authssl.cc @@ -46,11 +46,8 @@ /******************** notify of new Cert **************************/ #include "pqinotify.h" -#include -//#include -//#include #include -#include +#include #include diff --git a/libretroshare/src/pqi/authssl.h b/libretroshare/src/pqi/authssl.h index bf05b1793..efad0b044 100644 --- a/libretroshare/src/pqi/authssl.h +++ b/libretroshare/src/pqi/authssl.h @@ -39,8 +39,8 @@ * */ -#include #include +#include #include #include diff --git a/libretroshare/src/pqi/pqihash.h b/libretroshare/src/pqi/pqihash.h index acf56d290..f545588c9 100644 --- a/libretroshare/src/pqi/pqihash.h +++ b/libretroshare/src/pqi/pqihash.h @@ -29,6 +29,7 @@ #include #include #include +#include #include "util/rsstring.h" #include diff --git a/libretroshare/src/pqi/pqinetwork.h b/libretroshare/src/pqi/pqinetwork.h index 4a48729dc..82198b4ab 100644 --- a/libretroshare/src/pqi/pqinetwork.h +++ b/libretroshare/src/pqi/pqinetwork.h @@ -45,13 +45,8 @@ #else - #include "util/rsnet.h" /* more generic networking header */ -#include -typedef int socklen_t; -//typedef unsigned long in_addr_t; - // Some Network functions that are missing from windows. in_addr_t inet_netof(struct in_addr addr); diff --git a/libretroshare/src/pqi/pqissl.cc b/libretroshare/src/pqi/pqissl.cc index 6f68a543a..46e94c43c 100644 --- a/libretroshare/src/pqi/pqissl.cc +++ b/libretroshare/src/pqi/pqissl.cc @@ -1859,3 +1859,17 @@ std::string pqissl::gethash() /********** End of Implementation of BinInterface ******************/ +int pqissl::net_internal_close(int fd) +{ + return unix_close(fd); +} + +int pqissl::net_internal_SSL_set_fd(SSL *ssl, int fd) +{ + return SSL_set_fd(ssl, fd); +} + +int pqissl::net_internal_fcntl_nonblock(int fd) +{ + return unix_fcntl_nonblock(fd); +} diff --git a/libretroshare/src/pqi/pqissl.h b/libretroshare/src/pqi/pqissl.h index af9068a0a..48717d6ff 100644 --- a/libretroshare/src/pqi/pqissl.h +++ b/libretroshare/src/pqi/pqissl.h @@ -28,8 +28,6 @@ #ifndef MRK_PQI_SSL_HEADER #define MRK_PQI_SSL_HEADER -#include - // operating system specific network header. #include "pqi/pqinetwork.h" @@ -159,9 +157,9 @@ void getCryptoParams(RsPeerCryptoParams& params) ; protected: //protected internal fns that are overloaded for udp case. -virtual int net_internal_close(int fd) { return unix_close(fd); } -virtual int net_internal_SSL_set_fd(SSL *ssl, int fd) { return SSL_set_fd(ssl, fd); } -virtual int net_internal_fcntl_nonblock(int fd) { return unix_fcntl_nonblock(fd);} +virtual int net_internal_close(int fd); +virtual int net_internal_SSL_set_fd(SSL *ssl, int fd); +virtual int net_internal_fcntl_nonblock(int fd); /* data */ diff --git a/libretroshare/src/pqi/pqisslproxy.cc b/libretroshare/src/pqi/pqisslproxy.cc index a450d3cb1..80b9a6b71 100755 --- a/libretroshare/src/pqi/pqisslproxy.cc +++ b/libretroshare/src/pqi/pqisslproxy.cc @@ -168,7 +168,7 @@ int pqisslproxy::Proxy_Send_Method() #endif /* send hello to proxy server */ - uint8_t method_hello_data[3] = { 0x05, 0x01, 0x00 }; // [ Ver | nMethods (1) | No Auth Method ] + char method_hello_data[3] = { 0x05, 0x01, 0x00 }; // [ Ver | nMethods (1) | No Auth Method ] int sent = send(sockfd, method_hello_data, 3, 0); if (sent != 3) @@ -201,7 +201,7 @@ int pqisslproxy::Proxy_Method_Response() /* get response from proxy server */ - uint8_t method_response[2]; + char method_response[2]; // read from the socket. int recvd = recv(sockfd, method_response, 2, MSG_WAITALL); @@ -276,7 +276,7 @@ int pqisslproxy::Proxy_Send_Address() return ret; // Method Response not complete. } - uint8_t socks_request[MAX_SOCKS_REQUEST_LEN] = + char socks_request[MAX_SOCKS_REQUEST_LEN] = { 0x05, // SOCKS VERSION. 0x01, // CONNECT (Tor doesn't support BIND or UDP). 0x00, // RESERVED. @@ -332,7 +332,7 @@ int pqisslproxy::Proxy_Connection_Complete() /* get response from proxy server */ /* response is similar format to request - with variable length data */ - uint8_t socks_response[MAX_SOCKS_REQUEST_LEN]; + char socks_response[MAX_SOCKS_REQUEST_LEN]; int recvd = recv(sockfd, socks_response, 5, MSG_WAITALL); if (recvd != 5) diff --git a/libretroshare/src/pqi/pqisslproxy.h b/libretroshare/src/pqi/pqisslproxy.h index ff1db04a3..f9918832f 100755 --- a/libretroshare/src/pqi/pqisslproxy.h +++ b/libretroshare/src/pqi/pqisslproxy.h @@ -28,8 +28,6 @@ #ifndef MRK_PQI_SSL_PROXY_HEADER #define MRK_PQI_SSL_PROXY_HEADER -#include - // operating system specific network header. #include "pqi/pqinetwork.h" diff --git a/libretroshare/src/pqi/pqissludp.cc b/libretroshare/src/pqi/pqissludp.cc index bf2d8747f..074ef59db 100644 --- a/libretroshare/src/pqi/pqissludp.cc +++ b/libretroshare/src/pqi/pqissludp.cc @@ -30,7 +30,7 @@ #include "tcponudp/bio_tou.h" #include -#include +#include #include "util/rsdebug.h" diff --git a/libretroshare/src/pqi/pqissludp.h b/libretroshare/src/pqi/pqissludp.h index 10498840a..a39128372 100644 --- a/libretroshare/src/pqi/pqissludp.h +++ b/libretroshare/src/pqi/pqissludp.h @@ -28,8 +28,6 @@ #ifndef MRK_PQI_SSL_UDP_HEADER #define MRK_PQI_SSL_UDP_HEADER -#include - // operating system specific network header. #include "pqi/pqinetwork.h" diff --git a/libretroshare/src/pqi/sslfns.h b/libretroshare/src/pqi/sslfns.h index 98e3b2c0e..5015e6772 100644 --- a/libretroshare/src/pqi/sslfns.h +++ b/libretroshare/src/pqi/sslfns.h @@ -35,7 +35,6 @@ #include #include -#include #include #include diff --git a/libretroshare/src/rsserver/rsinit.cc b/libretroshare/src/rsserver/rsinit.cc index 07f15f774..e00337575 100644 --- a/libretroshare/src/rsserver/rsinit.cc +++ b/libretroshare/src/rsserver/rsinit.cc @@ -60,6 +60,8 @@ // for blocking signals #include +#include + #include "pqi/authssl.h" #include "pqi/sslfns.h" #include "pqi/authgpg.h" diff --git a/libretroshare/src/util/rsnet.h b/libretroshare/src/util/rsnet.h index 01f73a313..5e7802646 100644 --- a/libretroshare/src/util/rsnet.h +++ b/libretroshare/src/util/rsnet.h @@ -44,15 +44,14 @@ #else - -#include - -#include /* for ssize_t */ -//typedef uint32_t socklen_t; +#include typedef uint32_t in_addr_t; int inet_aton(const char *name, struct in_addr *addr); +// Missing defines in MinGW +#define MSG_WAITALL 8 + #endif /********************************** WINDOWS/UNIX SPECIFIC PART ******************/ diff --git a/retroshare-gui/src/gui/RetroShareLink.cpp b/retroshare-gui/src/gui/RetroShareLink.cpp index e5d6630c2..f4b4b494e 100644 --- a/retroshare-gui/src/gui/RetroShareLink.cpp +++ b/retroshare-gui/src/gui/RetroShareLink.cpp @@ -27,6 +27,7 @@ #include #include #include +#include #include "RetroShareLink.h" #include "MainWindow.h" From 70c947ba901506aa566768de8e300846b823605a Mon Sep 17 00:00:00 2001 From: drbob Date: Sat, 28 Sep 2013 02:42:59 +0000 Subject: [PATCH 18/83] fix for upnp use of sockaddr_storage git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@6772 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/upnp/upnphandler_linux.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libretroshare/src/upnp/upnphandler_linux.cc b/libretroshare/src/upnp/upnphandler_linux.cc index f252d03f9..4cec21bac 100644 --- a/libretroshare/src/upnp/upnphandler_linux.cc +++ b/libretroshare/src/upnp/upnphandler_linux.cc @@ -182,7 +182,7 @@ bool upnphandler::start_upnp() bool res = cUPnPControlPoint->AddPortMappings(upnpPortMapping1); bool res2 = cUPnPControlPoint->AddPortMappings(upnpPortMapping2); - struct sockaddr_in extAddr; + struct sockaddr_storage extAddr; bool extAddrResult = getExternalAddress(extAddr); { From 90aa57a0f07ac2734b383e6ade85fb67c2dad68f Mon Sep 17 00:00:00 2001 From: drbob Date: Sat, 28 Sep 2013 08:09:59 +0000 Subject: [PATCH 19/83] Rewrite of the discovery system to be more private, with less traffic. Split the visState into seperate vs_disc and vs_dht for easier handling. Split the heartbeat system into a separate service. Added IPv4 and IPv6 local/ext addresses into discovery & peer config. Fixed up samenet and samesubnet ipv4 calls. git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@6773 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/libretroshare.pro | 25 +- libretroshare/src/pqi/p3linkmgr.cc | 13 +- libretroshare/src/pqi/p3netmgr.cc | 15 +- libretroshare/src/pqi/p3netmgr.h | 7 +- libretroshare/src/pqi/p3peermgr.cc | 134 +- libretroshare/src/pqi/p3peermgr.h | 37 +- libretroshare/src/pqi/pqiipset.cc | 4 +- libretroshare/src/pqi/pqiipset.h | 2 +- libretroshare/src/pqi/pqiperson.cc | 1 - libretroshare/src/retroshare/rsdisc.h | 6 +- libretroshare/src/retroshare/rspeers.h | 15 +- libretroshare/src/rsserver/p3discovery.cc | 67 - libretroshare/src/rsserver/p3discovery.h | 51 - libretroshare/src/rsserver/p3face-server.cc | 3 +- libretroshare/src/rsserver/p3face.h | 7 +- libretroshare/src/rsserver/p3peers.cc | 31 +- libretroshare/src/rsserver/p3peers.h | 2 +- libretroshare/src/rsserver/rsinit.cc | 22 +- libretroshare/src/serialiser/itempriorities.h | 9 + libretroshare/src/serialiser/rsconfigitems.cc | 62 +- libretroshare/src/serialiser/rsconfigitems.h | 10 +- libretroshare/src/serialiser/rsdiscitems.cc | 770 ---------- libretroshare/src/serialiser/rsdiscitems.h | 193 --- .../src/serialiser/rsdiscovery2items.cc | 890 +++++++++++ .../src/serialiser/rsdiscovery2items.h | 203 +++ .../src/serialiser/rsheartbeatitems.cc | 206 +++ .../src/serialiser/rsheartbeatitems.h | 72 + libretroshare/src/serialiser/rsserviceids.h | 1 + libretroshare/src/serialiser/rstlvbase.h | 7 +- libretroshare/src/serialiser/rstlvtypes.h | 25 + libretroshare/src/services/p3disc.h | 178 --- .../services/{p3disc.cc => p3discovery2.cc} | 1367 +++++++++++++++-- libretroshare/src/services/p3discovery2.h | 151 ++ libretroshare/src/services/p3heartbeat.cc | 122 ++ libretroshare/src/services/p3heartbeat.h | 61 + libretroshare/src/services/p3posted.cc | 4 +- libretroshare/src/util/rsnet_ss.cc | 16 +- libretroshare/src/zeroconf/p3zeroconf.cc | 2 +- 38 files changed, 3248 insertions(+), 1543 deletions(-) delete mode 100644 libretroshare/src/rsserver/p3discovery.cc delete mode 100644 libretroshare/src/rsserver/p3discovery.h delete mode 100644 libretroshare/src/serialiser/rsdiscitems.cc delete mode 100644 libretroshare/src/serialiser/rsdiscitems.h create mode 100644 libretroshare/src/serialiser/rsdiscovery2items.cc create mode 100644 libretroshare/src/serialiser/rsdiscovery2items.h create mode 100644 libretroshare/src/serialiser/rsheartbeatitems.cc create mode 100644 libretroshare/src/serialiser/rsheartbeatitems.h delete mode 100644 libretroshare/src/services/p3disc.h rename libretroshare/src/services/{p3disc.cc => p3discovery2.cc} (51%) create mode 100644 libretroshare/src/services/p3discovery2.h create mode 100644 libretroshare/src/services/p3heartbeat.cc create mode 100644 libretroshare/src/services/p3heartbeat.h diff --git a/libretroshare/src/libretroshare.pro b/libretroshare/src/libretroshare.pro index 013fa0531..d2028c36a 100644 --- a/libretroshare/src/libretroshare.pro +++ b/libretroshare/src/libretroshare.pro @@ -358,8 +358,7 @@ HEADERS += pqi/authssl.h \ # pqi/p3dhtmgr.h \ -HEADERS += rsserver/p3discovery.h \ - rsserver/p3face.h \ +HEADERS += rsserver/p3face.h \ rsserver/p3history.h \ rsserver/p3msgs.h \ rsserver/p3peers.h \ @@ -369,7 +368,6 @@ HEADERS += rsserver/p3discovery.h \ HEADERS += serialiser/rsbaseitems.h \ serialiser/rsbaseserial.h \ serialiser/rsconfigitems.h \ - serialiser/rsdiscitems.h \ serialiser/rshistoryitems.h \ serialiser/rsmsgitems.h \ serialiser/rsserial.h \ @@ -387,17 +385,18 @@ HEADERS += serialiser/rsbaseitems.h \ serialiser/rstlvbanlist.h \ serialiser/rsbanlistitems.h \ serialiser/rsbwctrlitems.h \ + serialiser/rsdiscovery2items.h \ + serialiser/rsheartbeatitems.h \ HEADERS += services/p3chatservice.h \ - services/p3disc.h \ services/p3msgservice.h \ services/p3service.h \ services/p3statusservice.h \ services/p3dsdv.h \ services/p3banlist.h \ - services/p3bwctrl.h - -# services/p3discovery2.h \ + services/p3bwctrl.h \ + services/p3discovery2.h \ + services/p3heartbeat.h \ HEADERS += turtle/p3turtle.h \ turtle/rsturtleitem.h \ @@ -477,8 +476,7 @@ SOURCES += pqi/authgpg.cc \ # pqi/p3dhtmgr.cc \ -SOURCES += rsserver/p3discovery.cc \ - rsserver/p3face-config.cc \ +SOURCES += rsserver/p3face-config.cc \ rsserver/p3face-msgs.cc \ rsserver/p3face-server.cc \ rsserver/p3history.cc \ @@ -497,7 +495,6 @@ SOURCES += plugins/pluginmanager.cc \ SOURCES += serialiser/rsbaseitems.cc \ serialiser/rsbaseserial.cc \ serialiser/rsconfigitems.cc \ - serialiser/rsdiscitems.cc \ serialiser/rshistoryitems.cc \ serialiser/rsmsgitems.cc \ serialiser/rsserial.cc \ @@ -515,18 +512,18 @@ SOURCES += serialiser/rsbaseitems.cc \ serialiser/rstlvbanlist.cc \ serialiser/rsbanlistitems.cc \ serialiser/rsbwctrlitems.cc \ + serialiser/rsdiscovery2items.cc \ + serialiser/rsheartbeatitems.cc \ SOURCES += services/p3chatservice.cc \ - services/p3disc.cc \ services/p3msgservice.cc \ services/p3service.cc \ services/p3statusservice.cc \ services/p3dsdv.cc \ services/p3banlist.cc \ services/p3bwctrl.cc \ - - -# services/p3discovery2.cc \ + services/p3discovery2.cc \ + services/p3heartbeat.cc \ SOURCES += turtle/p3turtle.cc \ turtle/rsturtleitem.cc diff --git a/libretroshare/src/pqi/p3linkmgr.cc b/libretroshare/src/pqi/p3linkmgr.cc index 8e268c207..1557b0498 100644 --- a/libretroshare/src/pqi/p3linkmgr.cc +++ b/libretroshare/src/pqi/p3linkmgr.cc @@ -1085,7 +1085,8 @@ void p3LinkMgrIMPL::peerStatus(std::string id, const pqiIpAddrSet &addrs, details.ts = now; bool updateNetConfig = (source == RS_CB_PERSON); - uint32_t peerVisibility = 0; + uint32_t peer_vs_disc = 0; + uint32_t peer_vs_dht = 0; uint32_t peerNetMode = 0; uint32_t ownNetMode = mNetMgr->getNetworkMode(); @@ -1219,20 +1220,20 @@ void p3LinkMgrIMPL::peerStatus(std::string id, const pqiIpAddrSet &addrs, /* always update VIS status */ if (flags & RS_NET_FLAGS_USE_DISC) { - peerVisibility &= (~RS_VIS_STATE_NODISC); + peer_vs_disc = RS_VS_DISC_FULL; } else { - peerVisibility |= RS_VIS_STATE_NODISC; + peer_vs_disc = RS_VS_DISC_OFF; } if (flags & RS_NET_FLAGS_USE_DHT) { - peerVisibility &= (~RS_VIS_STATE_NODHT); + peer_vs_dht = RS_VS_DHT_FULL; } else { - peerVisibility |= RS_VIS_STATE_NODHT; + peer_vs_dht = RS_VS_DHT_OFF; } @@ -1303,7 +1304,7 @@ void p3LinkMgrIMPL::peerStatus(std::string id, const pqiIpAddrSet &addrs, bool newAddrs = mPeerMgr->updateAddressList(id, addrs); if (updateNetConfig) { - mPeerMgr -> setVisState(id, peerVisibility); + mPeerMgr -> setVisState(id, peer_vs_disc, peer_vs_dht); mPeerMgr -> setNetworkMode(id, peerNetMode); } diff --git a/libretroshare/src/pqi/p3netmgr.cc b/libretroshare/src/pqi/p3netmgr.cc index 8eed3d093..960a88ec5 100644 --- a/libretroshare/src/pqi/p3netmgr.cc +++ b/libretroshare/src/pqi/p3netmgr.cc @@ -140,8 +140,10 @@ p3NetMgrIMPL::p3NetMgrIMPL() mLocalAddr.ss_family = AF_INET; mExtAddr.ss_family = AF_INET; + // default to full. + mVsDisc = RS_VS_DISC_FULL; + mVsDht = RS_VS_DHT_FULL; - mVisState = 0 ; } #ifdef NETMGR_DEBUG @@ -570,10 +572,10 @@ void p3NetMgrIMPL::netDhtInit() uint32_t vs = 0; { RsStackMutex stack(mNetMtx); /*********** LOCKED MUTEX ************/ - vs = mVisState; + vs = mVsDht; } - enableNetAssistConnect(!(vs & RS_VIS_STATE_NODHT)); + enableNetAssistConnect(vs != RS_VS_DHT_OFF); } @@ -1167,15 +1169,16 @@ bool p3NetMgrIMPL::setNetworkMode(uint32_t netMode) } -bool p3NetMgrIMPL::setVisState(uint32_t visState) +bool p3NetMgrIMPL::setVisState(uint16_t vs_disc, uint16_t vs_dht) { RsStackMutex stack(mNetMtx); /****** STACK LOCK MUTEX *******/ - mVisState = visState; + mVsDisc = vs_disc; + mVsDht = vs_dht; /* if we've started up - then tweak Dht On/Off */ if (mNetStatus != RS_NET_UNKNOWN) { - enableNetAssistConnect(!(mVisState & RS_VIS_STATE_NODHT)); + enableNetAssistConnect(mVsDht != RS_VS_DHT_OFF); } return true; diff --git a/libretroshare/src/pqi/p3netmgr.h b/libretroshare/src/pqi/p3netmgr.h index b8ca67907..ac35eeab0 100644 --- a/libretroshare/src/pqi/p3netmgr.h +++ b/libretroshare/src/pqi/p3netmgr.h @@ -115,7 +115,7 @@ virtual ~p3NetMgr() { return; } // Setup Network State. virtual bool setNetworkMode(uint32_t netMode) = 0; -virtual bool setVisState(uint32_t visState) = 0; +virtual bool setVisState(uint16_t vs_disc, uint16_t vs_dht) = 0; // Switch DHT On/Off. virtual bool netAssistFriend(const std::string &id, bool on) = 0; @@ -171,7 +171,7 @@ class p3NetMgrIMPL: public p3NetMgr // Setup Network State. virtual bool setNetworkMode(uint32_t netMode); -virtual bool setVisState(uint32_t visState); +virtual bool setVisState(uint16_t vs_disc, uint16_t vs_dht); // Switch DHT On/Off. virtual bool netAssistFriend(const std::string &id, bool on); @@ -330,7 +330,8 @@ void netStatusReset_locked(); struct sockaddr_storage mExtAddr; uint32_t mNetMode; - uint32_t mVisState; + uint16_t mVsDisc; + uint16_t mVsDht; time_t mNetInitTS; uint32_t mNetStatus; diff --git a/libretroshare/src/pqi/p3peermgr.cc b/libretroshare/src/pqi/p3peermgr.cc index fb5d2c425..eb6ead1dc 100644 --- a/libretroshare/src/pqi/p3peermgr.cc +++ b/libretroshare/src/pqi/p3peermgr.cc @@ -78,7 +78,7 @@ void printConnectState(std::ostream &out, peerState &peer); peerState::peerState() :id("unknown"), gpg_id("unknown"), - netMode(RS_NET_MODE_UNKNOWN), visState(RS_VIS_STATE_STD), lastcontact(0), + netMode(RS_NET_MODE_UNKNOWN), vs_disc(RS_VS_DISC_FULL), vs_dht(RS_VS_DHT_FULL), lastcontact(0), hiddenNode(false), hiddenPort(0) { sockaddr_storage_clear(localaddr); @@ -91,7 +91,7 @@ std::string textPeerConnectState(peerState &state) { std::string out = "Id: " + state.id + "\n"; rs_sprintf_append(out, "NetMode: %lu\n", state.netMode); - rs_sprintf_append(out, "VisState: %lu\n", state.visState); + rs_sprintf_append(out, "VisState: Disc: %u Dht: %u\n", state.vs_disc, state.vs_dht); out += "laddr: "; out += sockaddr_storage_tostring(state.localaddr); @@ -122,7 +122,8 @@ p3PeerMgrIMPL::p3PeerMgrIMPL( const std::string& ssl_own_id, mOwnState.name = gpg_own_name ; mOwnState.location = ssl_own_location ; mOwnState.netMode = RS_NET_MODE_UPNP; // Default to UPNP. - mOwnState.visState = 0; + mOwnState.vs_disc = RS_VS_DISC_FULL; + mOwnState.vs_dht = RS_VS_DHT_FULL; lastGroupId = 1; @@ -163,7 +164,7 @@ bool p3PeerMgrIMPL::setupHiddenNode(const std::string &hiddenAddress, const uint mOwnState.hiddenDomain = hiddenAddress; // switch off DHT too. - setOwnVisState(RS_VIS_STATE_GRAY); + setOwnVisState(mOwnState.vs_disc, RS_VS_DHT_OFF); // Force the Port. struct sockaddr_storage loopback; @@ -206,29 +207,32 @@ bool p3PeerMgrIMPL::setOwnNetworkMode(uint32_t netMode) return changed; } -bool p3PeerMgrIMPL::setOwnVisState(uint32_t visState) +bool p3PeerMgrIMPL::setOwnVisState(uint16_t vs_disc, uint16_t vs_dht) { bool changed = false; { RsStackMutex stack(mPeerMtx); /****** STACK LOCK MUTEX *******/ std::string out; - rs_sprintf(out, "p3PeerMgr::setOwnVisState() Existing vis: %lu Input vis: %lu", mOwnState.visState, visState); + rs_sprintf(out, "p3PeerMgr::setOwnVisState() Existing vis: %u/%u Input vis: %u/%u", + mOwnState.vs_disc, mOwnState.vs_dht, vs_disc, vs_dht); rslog(RSL_WARNING, p3peermgrzone, out); #ifdef PEER_DEBUG std::cerr << out.c_str() << std::endl; #endif - if (mOwnState.visState != visState) { - mOwnState.visState = visState; + if (mOwnState.vs_disc != vs_disc || mOwnState.vs_dht != vs_dht) + { + mOwnState.vs_disc = vs_disc; + mOwnState.vs_dht = vs_dht; changed = true; IndicateConfigChanged(); /**** INDICATE MSG CONFIG CHANGED! *****/ } } // Pass on Flags to NetMgr. - mNetMgr->setVisState(visState); + mNetMgr->setVisState(vs_disc, vs_dht); return changed; } @@ -594,7 +598,7 @@ bool p3PeerMgrIMPL::haveOnceConnected() /*******************************************************************/ /*******************************************************************/ -bool p3PeerMgrIMPL::addFriend(const std::string& input_id, const std::string& input_gpg_id, uint32_t netMode, uint32_t visState, time_t lastContact,ServicePermissionFlags service_flags) +bool p3PeerMgrIMPL::addFriend(const std::string& input_id, const std::string& input_gpg_id, uint32_t netMode, uint16_t vs_disc, uint16_t vs_dht, time_t lastContact,ServicePermissionFlags service_flags) { bool notifyLinkMgr = false; std::string id = input_id ; @@ -670,7 +674,9 @@ bool p3PeerMgrIMPL::addFriend(const std::string& input_id, const std::string& in it = mFriendList.find(id); /* setup connectivity parameters */ - it->second.visState = visState; + it->second.vs_disc = vs_disc; + it->second.vs_dht = vs_dht; + it->second.netMode = netMode; it->second.lastcontact = lastContact; @@ -693,7 +699,8 @@ bool p3PeerMgrIMPL::addFriend(const std::string& input_id, const std::string& in pstate.gpg_id = gpg_id; pstate.name = AuthGPG::getAuthGPG()->getGPGName(gpg_id); - pstate.visState = visState; + pstate.vs_disc = vs_disc; + pstate.vs_dht = vs_dht; pstate.netMode = netMode; pstate.lastcontact = lastContact; @@ -711,7 +718,7 @@ bool p3PeerMgrIMPL::addFriend(const std::string& input_id, const std::string& in if (notifyLinkMgr) { - mLinkMgr->addFriend(id, !(visState & RS_VIS_STATE_NODHT)); + mLinkMgr->addFriend(id, vs_dht != RS_VS_DHT_OFF); } service_flags &= servicePermissionFlags(gpg_id) ; // Always reduce the permissions. @@ -1327,20 +1334,19 @@ bool p3PeerMgrIMPL::setLocation(const std::string &id, const std::string &loc return changed; } -bool p3PeerMgrIMPL::setVisState(const std::string &id, uint32_t visState) +bool p3PeerMgrIMPL::setVisState(const std::string &id, uint16_t vs_disc, uint16_t vs_dht) { { std::string out; - rs_sprintf(out, "p3PeerMgr::setVisState(%s, %lu)", id.c_str(), visState); + rs_sprintf(out, "p3PeerMgr::setVisState(%s, %u, %u)", id.c_str(), vs_disc, vs_dht); rslog(RSL_WARNING, p3peermgrzone, out); } if (id == AuthSSL::getAuthSSL()->OwnId()) { - return setOwnVisState(visState); + return setOwnVisState(vs_disc, vs_dht); } - bool dht_state ; bool isFriend = false; bool changed = false; { @@ -1361,53 +1367,47 @@ bool p3PeerMgrIMPL::setVisState(const std::string &id, uint32_t visState) } /* "it" points to peer */ - if (it->second.visState != visState) { - it->second.visState = visState; + if ((it->second.vs_disc != vs_disc) || (it->second.vs_dht = vs_dht)) + { + it->second.vs_disc = vs_disc; + it->second.vs_dht = vs_dht; changed = true; - dht_state = it->second.visState & RS_VIS_STATE_NODHT ; - - std::cerr << "p3PeerMgrIMPL::setVisState(" << id << ", " << std::hex << visState << std::dec << ") "; + std::cerr << "p3PeerMgrIMPL::setVisState(" << id << ", DISC: " << vs_disc << " DHT: " << vs_dht << ") "; std::cerr << " NAME: " << it->second.name; - if (it->second.visState & RS_VIS_STATE_NODHT) + switch(it->second.vs_disc) { - std::cerr << " NO-DHT "; + default: + case RS_VS_DISC_OFF: + std::cerr << " NO-DISC "; + break; + case RS_VS_DISC_MINIMAL: + std::cerr << " MIN-DISC "; + break; + case RS_VS_DISC_FULL: + std::cerr << " FULL-DISC "; + break; } - else + switch(it->second.vs_dht) { - std::cerr << " DHT-OK "; - } - if (it->second.visState & RS_VIS_STATE_NODISC) - { - std::cerr << " NO-DISC "; - } - else - { - std::cerr << " DISC-OK "; + default: + case RS_VS_DHT_OFF: + std::cerr << " NO-DHT "; + break; + case RS_VS_DHT_PASSIVE: + std::cerr << " PASSIVE-DHT "; + break; + case RS_VS_DHT_FULL: + std::cerr << " FULL-DHT "; + break; } std::cerr << std::endl; } } if(isFriend && changed) { - /* toggle DHT state */ - if(dht_state) - { - - std::cerr << "p3PeerMgrIMPL::setVisState() setFriendVisibility => false"; - std::cerr << std::endl; - - /* hidden from DHT world */ - mLinkMgr->setFriendVisibility(id, false); - } - else - { - std::cerr << "p3PeerMgrIMPL::setVisState() setFriendVisibility => true"; - std::cerr << std::endl; - - mLinkMgr->setFriendVisibility(id, true); - } + mLinkMgr->setFriendVisibility(id, vs_dht != RS_VS_DHT_OFF); } if (changed) { @@ -1471,11 +1471,16 @@ bool p3PeerMgrIMPL::saveList(bool &cleanup, std::list& saveData) #endif item->netMode = mOwnState.netMode; - item->visState = mOwnState.visState; + item->vs_disc = mOwnState.vs_disc; + item->vs_dht = mOwnState.vs_dht; + item->lastContact = mOwnState.lastcontact; - item->localAddr.addr = mOwnState.localaddr; - item->extAddr.addr = mOwnState.serveraddr; + item->localAddrV4.addr = mOwnState.localaddr; + item->extAddrV4.addr = mOwnState.serveraddr; + sockaddr_storage_clear(item->localAddrV6.addr); + sockaddr_storage_clear(item->extAddrV6.addr); + item->dyndns = mOwnState.dyndns; mOwnState.ipAddrs.mLocal.loadTlv(item->localAddrList); mOwnState.ipAddrs.mExt.loadTlv(item->extAddrList); @@ -1502,10 +1507,17 @@ bool p3PeerMgrIMPL::saveList(bool &cleanup, std::list& saveData) item->gpg_id = (it->second).gpg_id; item->location = (it->second).location; item->netMode = (it->second).netMode; - item->visState = (it->second).visState; + item->vs_disc = (it->second).vs_disc; + item->vs_dht = (it->second).vs_dht; + item->lastContact = (it->second).lastcontact; - item->localAddr.addr = (it->second).localaddr; - item->extAddr.addr = (it->second).serveraddr; + + item->localAddrV4.addr = (it->second).localaddr; + item->extAddrV4.addr = (it->second).serveraddr; + sockaddr_storage_clear(item->localAddrV6.addr); + sockaddr_storage_clear(item->extAddrV6.addr); + + item->dyndns = (it->second).dyndns; (it->second).ipAddrs.mLocal.loadTlv(item->localAddrList); (it->second).ipAddrs.mExt.loadTlv(item->extAddrList); @@ -1613,7 +1625,7 @@ bool p3PeerMgrIMPL::loadList(std::list& load) #endif /* add ownConfig */ setOwnNetworkMode(pitem->netMode); - setOwnVisState(pitem->visState); + setOwnVisState(pitem->vs_disc, pitem->vs_dht); mOwnState.gpg_id = AuthGPG::getAuthGPG()->getGPGOwnId(); mOwnState.location = AuthSSL::getAuthSSL()->getOwnLocation(); @@ -1626,7 +1638,7 @@ bool p3PeerMgrIMPL::loadList(std::list& load) std::cerr << std::endl; #endif /* ************* */ - addFriend(pitem->pid, pitem->gpg_id, pitem->netMode, pitem->visState, pitem->lastContact, RS_SERVICE_PERM_ALL); + addFriend(pitem->pid, pitem->gpg_id, pitem->netMode, pitem->vs_disc, pitem->vs_dht, pitem->lastContact, RS_SERVICE_PERM_ALL); setLocation(pitem->pid, pitem->location); } @@ -1638,8 +1650,8 @@ bool p3PeerMgrIMPL::loadList(std::list& load) } else { - setLocalAddress(pitem->pid, pitem->localAddr.addr); - setExtAddress(pitem->pid, pitem->extAddr.addr); + setLocalAddress(pitem->pid, pitem->localAddrV4.addr); + setExtAddress(pitem->pid, pitem->extAddrV4.addr); setDynDNS (pitem->pid, pitem->dyndns); /* convert addresses */ diff --git a/libretroshare/src/pqi/p3peermgr.h b/libretroshare/src/pqi/p3peermgr.h index 8d8fcee95..236f45e03 100644 --- a/libretroshare/src/pqi/p3peermgr.h +++ b/libretroshare/src/pqi/p3peermgr.h @@ -35,24 +35,8 @@ #include "util/rsthreads.h" - /* RS_VIS_STATE_XXXX - * determines how public this peer wants to be... - * - * STD = advertise to Peers / DHT checking etc - * GRAY = share with friends / but not DHT - * DARK = hidden from all - * BROWN? = hidden from friends / but on DHT - */ - -const uint32_t RS_VIS_STATE_NODISC = 0x0001; -const uint32_t RS_VIS_STATE_NODHT = 0x0002; - -const uint32_t RS_VIS_STATE_STD = 0x0000; -const uint32_t RS_VIS_STATE_GRAY = RS_VIS_STATE_NODHT; -const uint32_t RS_VIS_STATE_DARK = RS_VIS_STATE_NODISC | RS_VIS_STATE_NODHT; -const uint32_t RS_VIS_STATE_BROWN = RS_VIS_STATE_NODISC; - - +/* RS_VIS_STATE -> specified in rspeers.h + */ /* Startup Modes (confirmed later) */ const uint32_t RS_NET_MODE_TRYMODE = 0xff00; @@ -90,8 +74,9 @@ class peerState std::string gpg_id; uint32_t netMode; /* EXT / UPNP / UDP / HIDDEN / INVALID */ - uint32_t visState; /* STD, GRAY, DARK */ - + /* visState */ + uint16_t vs_disc; + uint16_t vs_dht; struct sockaddr_storage localaddr; struct sockaddr_storage serveraddr; @@ -130,7 +115,8 @@ class p3PeerMgr virtual ~p3PeerMgr() { return; } virtual bool addFriend(const std::string &ssl_id, const std::string &gpg_id, uint32_t netMode = RS_NET_MODE_UDP, - uint32_t visState = RS_VIS_STATE_STD , time_t lastContact = 0,ServicePermissionFlags = ServicePermissionFlags(RS_SERVICE_PERM_ALL)) = 0; + uint16_t vsDisc = RS_VS_DISC_FULL, uint16_t vsDht = RS_VS_DHT_FULL, + time_t lastContact = 0,ServicePermissionFlags = ServicePermissionFlags(RS_SERVICE_PERM_ALL)) = 0; virtual bool removeFriend(const std::string &ssl_id, bool removePgpId) = 0; virtual bool isFriend(const std::string &ssl_id) = 0; @@ -166,7 +152,7 @@ virtual bool setExtAddress(const std::string &id, const struct sockaddr_storage virtual bool setDynDNS(const std::string &id, const std::string &dyndns) = 0; virtual bool setNetworkMode(const std::string &id, uint32_t netMode) = 0; -virtual bool setVisState(const std::string &id, uint32_t visState) = 0; +virtual bool setVisState(const std::string &id, uint16_t vs_disc, uint16_t vs_dht) = 0; virtual bool setLocation(const std::string &pid, const std::string &location) = 0; virtual bool setHiddenDomainPort(const std::string &id, const std::string &domain_addr, const uint16_t domain_port) = 0; @@ -228,7 +214,8 @@ class p3PeerMgrIMPL: public p3PeerMgr, public p3Config /************************************************************************************************/ virtual bool addFriend(const std::string &ssl_id, const std::string &gpg_id, uint32_t netMode = RS_NET_MODE_UDP, - uint32_t visState = RS_VIS_STATE_STD , time_t lastContact = 0,ServicePermissionFlags = ServicePermissionFlags(RS_SERVICE_PERM_ALL)); + uint16_t vsDisc = RS_VS_DISC_FULL, uint16_t vsDht = RS_VS_DHT_FULL, + time_t lastContact = 0,ServicePermissionFlags = ServicePermissionFlags(RS_SERVICE_PERM_ALL)); virtual bool removeFriend(const std::string &ssl_id, bool removePgpId); virtual bool isFriend(const std::string &ssl_id); @@ -264,7 +251,7 @@ virtual bool setExtAddress(const std::string &id, const struct sockaddr_storage virtual bool setDynDNS(const std::string &id, const std::string &dyndns); virtual bool setNetworkMode(const std::string &id, uint32_t netMode); -virtual bool setVisState(const std::string &id, uint32_t visState); +virtual bool setVisState(const std::string &id, uint16_t vs_disc, uint16_t vs_dht); virtual bool setLocation(const std::string &pid, const std::string &location); virtual bool setHiddenDomainPort(const std::string &id, const std::string &domain_addr, const uint16_t domain_port); @@ -323,7 +310,7 @@ void tick(); const std::string getOwnId(); bool setOwnNetworkMode(uint32_t netMode); -bool setOwnVisState(uint32_t visState); +bool setOwnVisState(uint16_t vs_disc, uint16_t vs_dht); int getConnectAddresses(const std::string &id, struct sockaddr_storage &lAddr, struct sockaddr_storage &eAddr, diff --git a/libretroshare/src/pqi/pqiipset.cc b/libretroshare/src/pqi/pqiipset.cc index fa6e7c543..f0b033807 100644 --- a/libretroshare/src/pqi/pqiipset.cc +++ b/libretroshare/src/pqi/pqiipset.cc @@ -175,9 +175,9 @@ void pqiIpAddrList::extractFromTlv(const RsTlvIpAddrSet &tlvAddrs) } } -void pqiIpAddrList::loadTlv(RsTlvIpAddrSet &tlvAddrs) +void pqiIpAddrList::loadTlv(RsTlvIpAddrSet &tlvAddrs) const { - std::list::iterator it; + std::list::const_iterator it; for(it = mAddrs.begin(); it != mAddrs.end() ; ++it) { diff --git a/libretroshare/src/pqi/pqiipset.h b/libretroshare/src/pqi/pqiipset.h index f20dc1a5f..1ac7da3ea 100644 --- a/libretroshare/src/pqi/pqiipset.h +++ b/libretroshare/src/pqi/pqiipset.h @@ -51,7 +51,7 @@ class pqiIpAddrList bool updateIpAddressList(const pqiIpAddress &addr); void printIpAddressList(std::string &out) const; void extractFromTlv(const RsTlvIpAddrSet &tlvAddrs); - void loadTlv(RsTlvIpAddrSet &tlvAddrs); + void loadTlv(RsTlvIpAddrSet &tlvAddrs) const; // sorted list... based on seen time. std::list mAddrs; diff --git a/libretroshare/src/pqi/pqiperson.cc b/libretroshare/src/pqi/pqiperson.cc index d104e1326..a28a24382 100644 --- a/libretroshare/src/pqi/pqiperson.cc +++ b/libretroshare/src/pqi/pqiperson.cc @@ -26,7 +26,6 @@ #include "pqi/pqi.h" #include "pqi/pqiperson.h" #include "pqi/pqipersongrp.h" -#include "services/p3disc.h" const int pqipersonzone = 82371; #include "util/rsdebug.h" diff --git a/libretroshare/src/retroshare/rsdisc.h b/libretroshare/src/retroshare/rsdisc.h index c1f25cc15..a4f6352a9 100644 --- a/libretroshare/src/retroshare/rsdisc.h +++ b/libretroshare/src/retroshare/rsdisc.h @@ -42,9 +42,9 @@ class RsDisc RsDisc() { return; } virtual ~RsDisc() { return; } -virtual bool getDiscFriends(std::string id, std::list& friends) = 0; -virtual bool getDiscGPGFriends(std::string id, std::list& gpg_friends) = 0; -virtual bool getDiscVersions(std::map &versions) = 0; +virtual bool getDiscFriends(const std::string &id, std::list& friends) = 0; +virtual bool getDiscPgpFriends(const std::string &pgpid, std::list& gpg_friends) = 0; +virtual bool getPeerVersion(const std::string &id, std::string &versions) = 0; virtual bool getWaitingDiscCount(unsigned int *sendCount, unsigned int *recvCount) = 0; }; diff --git a/libretroshare/src/retroshare/rspeers.h b/libretroshare/src/retroshare/rspeers.h index fb04c649d..a1a73f9e0 100644 --- a/libretroshare/src/retroshare/rspeers.h +++ b/libretroshare/src/retroshare/rspeers.h @@ -58,8 +58,13 @@ const uint32_t RS_NETMODE_HIDDEN = 0x0004; const uint32_t RS_NETMODE_UNREACHABLE = 0x0005; /* Visibility */ -const uint32_t RS_VS_DHT_ON = 0x0001; -const uint32_t RS_VS_DISC_ON = 0x0002; +const uint32_t RS_VS_DISC_OFF = 0x0000; +const uint32_t RS_VS_DISC_MINIMAL = 0x0001; +const uint32_t RS_VS_DISC_FULL = 0x0002; + +const uint32_t RS_VS_DHT_OFF = 0x0000; +const uint32_t RS_VS_DHT_PASSIVE = 0x0001; +const uint32_t RS_VS_DHT_FULL = 0x0002; /* State */ const uint32_t RS_PEER_STATE_FRIEND = 0x0001; @@ -219,7 +224,9 @@ class RsPeerDetails std::list ipAddressList; uint32_t netMode; - uint32_t visState; + /* vis State */ + uint16_t vs_disc; + uint16_t vs_dht; /* basic stats */ uint32_t lastConnect; /* how long ago */ @@ -321,7 +328,7 @@ class RsPeers virtual bool setExtAddress( const std::string &ssl_id, const std::string &addr, uint16_t port) = 0; virtual bool setDynDNS(const std::string &id, const std::string &addr) = 0; virtual bool setNetworkMode(const std::string &ssl_id, uint32_t netMode) = 0; - virtual bool setVisState(const std::string &ssl_id, uint32_t vis) = 0; + virtual bool setVisState(const std::string &ssl_id, uint16_t vs_disc, uint16_t vs_dht) = 0; virtual void getIPServersList(std::list& ip_servers) = 0; virtual void allowServerIPDetermination(bool) = 0; diff --git a/libretroshare/src/rsserver/p3discovery.cc b/libretroshare/src/rsserver/p3discovery.cc deleted file mode 100644 index 401595304..000000000 --- a/libretroshare/src/rsserver/p3discovery.cc +++ /dev/null @@ -1,67 +0,0 @@ -/* - * libretroshare/src/rsserver: p3discovery.cc - * - * RetroShare C++ Interface. - * - * Copyright 2008-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 "rsserver/p3discovery.h" -#include - -RsDisc *rsDisc = NULL; - -bool p3Discovery::getDiscGPGFriends(std::string id, std::list& gpg_friends) -{ - if (mDisc) - { - return mDisc->potentialGPGproxies(id, gpg_friends); - } - return false; -} - -bool p3Discovery::getDiscFriends(std::string id, std::list &friends) -{ - if (mDisc) - { - return mDisc->potentialproxies(id, friends); - } - return false; -} - -bool p3Discovery::getDiscVersions(std::map &versions) -{ - if (mDisc) - { - mDisc->getversions(versions); - return true; - } - return false; -} - -bool p3Discovery::getWaitingDiscCount(unsigned int *sendCount, unsigned int *recvCount) -{ - if (mDisc) - { - mDisc->getWaitingDiscCount(sendCount, recvCount); - return true; - } - return false; -} diff --git a/libretroshare/src/rsserver/p3discovery.h b/libretroshare/src/rsserver/p3discovery.h deleted file mode 100644 index c1d70584f..000000000 --- a/libretroshare/src/rsserver/p3discovery.h +++ /dev/null @@ -1,51 +0,0 @@ -#ifndef RETROSHARE_P3_DISC_INTERFACE_H -#define RETROSHARE_P3_DISC_INTERFACE_H - -/* - * libretroshare/src/rsserver: p3discovery.h - * - * RetroShare C++ Interface. - * - * Copyright 2008-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/rsdisc.h" -#include "services/p3disc.h" - -class p3Discovery: public RsDisc -{ - public: - - p3Discovery(p3disc *disc) - :mDisc(disc) { return; } -virtual ~p3Discovery() { return; } - -virtual bool getDiscFriends(std::string id, std::list &friends); -virtual bool getDiscGPGFriends(std::string id, std::list &gpg_friends); -virtual bool getDiscVersions(std::map &versions); -virtual bool getWaitingDiscCount(unsigned int *sendCount, unsigned int *recvCount); - - private: - - p3disc *mDisc; -}; - -#endif - diff --git a/libretroshare/src/rsserver/p3face-server.cc b/libretroshare/src/rsserver/p3face-server.cc index 406881f6e..d4f6b768d 100644 --- a/libretroshare/src/rsserver/p3face-server.cc +++ b/libretroshare/src/rsserver/p3face-server.cc @@ -65,7 +65,8 @@ RsServer::RsServer(NotifyBase &callback) mPluginsManager = NULL; /* services */ - ad = NULL; + mHeart = NULL; + mDisc = NULL; msgSrv = NULL; chatSrv = NULL; mStatusSrv = NULL; diff --git a/libretroshare/src/rsserver/p3face.h b/libretroshare/src/rsserver/p3face.h index 47f4bdd3b..5de9ca42d 100644 --- a/libretroshare/src/rsserver/p3face.h +++ b/libretroshare/src/rsserver/p3face.h @@ -37,11 +37,13 @@ #include "retroshare/rstypes.h" #include "util/rsthreads.h" -#include "services/p3disc.h" #include "services/p3msgservice.h" #include "services/p3chatservice.h" #include "services/p3statusservice.h" +class p3heartbeat; +class p3discovery2; + /* GXS Classes - just declare the classes. so we don't have to totally recompile to switch */ @@ -171,7 +173,8 @@ class RsServer: public RsControl, public RsThread //sslroot *sslr; /* services */ - p3disc *ad; + p3heartbeat *mHeart; + p3discovery2 *mDisc; p3MsgService *msgSrv; p3ChatService *chatSrv; p3StatusService *mStatusSrv; diff --git a/libretroshare/src/rsserver/p3peers.cc b/libretroshare/src/rsserver/p3peers.cc index 9614708dd..e4b4207e4 100644 --- a/libretroshare/src/rsserver/p3peers.cc +++ b/libretroshare/src/rsserver/p3peers.cc @@ -373,18 +373,8 @@ bool p3Peers::getPeerDetails(const std::string &id, RsPeerDetails &d) break; } - d.visState = 0; - if (!(ps.visState & RS_VIS_STATE_NODISC)) - { - d.visState |= RS_VS_DISC_ON; - } - - if (!(ps.visState & RS_VIS_STATE_NODHT)) - { - d.visState |= RS_VS_DHT_ON; - } - - + d.vs_disc = ps.vs_disc; + d.vs_dht = ps.vs_dht; /* Translate */ @@ -645,7 +635,7 @@ bool p3Peers::addFriend(const std::string &ssl_id, const std::string &gpg_id,Se * This will cause the SSL certificate to be retained for 30 days... and give the person a chance to connect! * */ time_t now = time(NULL); - return mPeerMgr->addFriend(ssl_id, gpg_id, RS_NET_MODE_UDP, RS_VIS_STATE_STD, now, perm_flags); + return mPeerMgr->addFriend(ssl_id, gpg_id, RS_NET_MODE_UDP, RS_VS_DISC_FULL, RS_VS_DHT_FULL, now, perm_flags); } bool p3Peers::removeKeysFromPGPKeyring(const std::list& pgp_ids,std::string& backup_file,uint32_t& error_code) @@ -875,20 +865,15 @@ bool p3Peers::setNetworkMode(const std::string &id, uint32_t extNetMode) bool -p3Peers::setVisState(const std::string &id, uint32_t extVisState) +p3Peers::setVisState(const std::string &id, uint16_t vs_disc, uint16_t vs_dht) { #ifdef P3PEERS_DEBUG std::cerr << "p3Peers::setVisState() " << id << std::endl; #endif - std::cerr << "p3Peers::setVisState() " << id << " " << extVisState << std::endl; + std::cerr << "p3Peers::setVisState() " << id << " DISC: " << vs_disc; + std::cerr << " DHT: " << vs_dht << std::endl; - uint32_t visState = 0; - if (!(extVisState & RS_VS_DHT_ON)) - visState |= RS_VIS_STATE_NODHT; - if (!(extVisState & RS_VS_DISC_ON)) - visState |= RS_VIS_STATE_NODISC; - - return mPeerMgr->setVisState(id, visState); + return mPeerMgr->setVisState(id, vs_disc, vs_dht); } //=========================================================================== @@ -1242,7 +1227,7 @@ RsPeerDetails::RsPeerDetails() org(""),issuer(""),fpr(""),authcode(""), trustLvl(0), validLvl(0),ownsign(false), hasSignedMe(false),accept_connection(false), - state(0),localAddr(""),localPort(0),extAddr(""),extPort(0),netMode(0),visState(0), + state(0),localAddr(""),localPort(0),extAddr(""),extPort(0),netMode(0),vs_disc(0), vs_dht(0), lastConnect(0),connectState(0),connectStateString(""),connectPeriod(0),foundDHT(false), wasDeniedConnection(false), deniedTS(0) { diff --git a/libretroshare/src/rsserver/p3peers.h b/libretroshare/src/rsserver/p3peers.h index 6305dc1d7..d81e74cfd 100644 --- a/libretroshare/src/rsserver/p3peers.h +++ b/libretroshare/src/rsserver/p3peers.h @@ -90,7 +90,7 @@ virtual bool setLocalAddress(const std::string &id, const std::string &addr, uin virtual bool setExtAddress(const std::string &id, const std::string &addr, uint16_t port); virtual bool setDynDNS(const std::string &id, const std::string &dyndns); virtual bool setNetworkMode(const std::string &id, uint32_t netMode); -virtual bool setVisState(const std::string &id, uint32_t mode); +virtual bool setVisState(const std::string &id, uint16_t vs_disc, uint16_t vs_dht); virtual void getIPServersList(std::list& ip_servers) ; virtual void allowServerIPDetermination(bool) ; diff --git a/libretroshare/src/rsserver/rsinit.cc b/libretroshare/src/rsserver/rsinit.cc index e00337575..f0ad40f4c 100644 --- a/libretroshare/src/rsserver/rsinit.cc +++ b/libretroshare/src/rsserver/rsinit.cc @@ -289,7 +289,6 @@ void RsInit::InitRsConfig() //setZoneLevel(PQL_DEBUG_BASIC, 82371); // pqiperson. //setZoneLevel(PQL_DEBUG_BASIC, 34283); // pqihandler. //setZoneLevel(PQL_DEBUG_BASIC, 44863); // discItems. - //setZoneLevel(PQL_DEBUG_BASIC, 2482); // p3disc //setZoneLevel(PQL_DEBUG_BASIC, 1728); // pqi/p3proxy //setZoneLevel(PQL_DEBUG_BASIC, 1211); // sslroot. //setZoneLevel(PQL_DEBUG_BASIC, 37714); // pqissl. @@ -1780,8 +1779,9 @@ RsTurtle *rsTurtle = NULL ; #include "upnp/upnphandler_miniupnp.h" #endif #endif - -#include "services/p3disc.h" + +#include "services/p3heartbeat.h" +#include "services/p3discovery2.h" #include "services/p3msgservice.h" #include "services/p3chatservice.h" #include "services/p3statusservice.h" @@ -1815,7 +1815,6 @@ RsTurtle *rsTurtle = NULL ; #include "rsserver/p3face.h" #include "rsserver/p3peers.h" #include "rsserver/p3msgs.h" -#include "rsserver/p3discovery.h" #include "rsserver/p3status.h" #include "rsserver/p3history.h" #include "rsserver/p3serverconfig.h" @@ -2238,7 +2237,8 @@ int RsServer::StartupRetroShare() mPluginsManager->setInterfaces(interfaces); /* create Services */ - ad = new p3disc(mPeerMgr, mLinkMgr, mNetMgr, pqih); + mDisc = new p3discovery2(mPeerMgr, mLinkMgr, mNetMgr); + mHeart = new p3heartbeat(mLinkMgr, pqih); msgSrv = new p3MsgService(mLinkMgr); chatSrv = new p3ChatService(mLinkMgr, mHistoryMgr); mStatusSrv = new p3StatusService(mLinkMgr); @@ -2251,7 +2251,8 @@ int RsServer::StartupRetroShare() chatSrv->connectToTurtleRouter(tr) ; msgSrv->connectToTurtleRouter(tr) ; - pqih -> addService(ad); + pqih -> addService(mHeart); + pqih -> addService(mDisc); pqih -> addService(msgSrv); pqih -> addService(chatSrv); pqih ->addService(mStatusSrv); @@ -2503,7 +2504,7 @@ int RsServer::StartupRetroShare() /* need to Monitor too! */ mLinkMgr->addMonitor(pqih); mLinkMgr->addMonitor(mCacheStrapper); - //mLinkMgr->addMonitor(ad); + mLinkMgr->addMonitor(mDisc); mLinkMgr->addMonitor(msgSrv); mLinkMgr->addMonitor(mStatusSrv); mLinkMgr->addMonitor(chatSrv); @@ -2529,7 +2530,6 @@ int RsServer::StartupRetroShare() mConfigMgr->addConfiguration("p3History.cfg", mHistoryMgr); mConfigMgr->addConfiguration("p3Status.cfg", mStatusSrv); mConfigMgr->addConfiguration("turtle.cfg", tr); - //mConfigMgr->addConfiguration("p3disc.cfg", ad); #ifdef RS_USE_BITDHT mConfigMgr->addConfiguration("bitdht.cfg", mBitDht); @@ -2583,7 +2583,7 @@ int RsServer::StartupRetroShare() if (RsInitConfig::forceExtPort) { mPeerMgr->setOwnNetworkMode(RS_NET_MODE_EXT); - mPeerMgr->setOwnVisState(RS_VIS_STATE_STD); + mPeerMgr->setOwnVisState(RS_VS_DISC_FULL, RS_VS_DHT_FULL); } @@ -2633,7 +2633,7 @@ int RsServer::StartupRetroShare() /* Add AuthGPG services */ /**************************************************************************/ - AuthGPG::getAuthGPG()->addService(ad); + AuthGPG::getAuthGPG()->addService(mDisc); /**************************************************************************/ /* Force Any Last Configuration Options */ @@ -2701,7 +2701,7 @@ int RsServer::StartupRetroShare() /* Setup GUI Interfaces. */ - rsDisc = new p3Discovery(ad); + rsDisc = mDisc; rsBandwidthControl = mBwCtrl; rsConfig = serverConfig; diff --git a/libretroshare/src/serialiser/itempriorities.h b/libretroshare/src/serialiser/itempriorities.h index ef8dd2072..83f74b867 100644 --- a/libretroshare/src/serialiser/itempriorities.h +++ b/libretroshare/src/serialiser/itempriorities.h @@ -71,6 +71,15 @@ const uint8_t QOS_PRIORITY_RS_DISC_ASK_INFO = 2 ; const uint8_t QOS_PRIORITY_RS_DISC_REPLY = 1 ; const uint8_t QOS_PRIORITY_RS_DISC_VERSION = 1 ; +const uint8_t QOS_PRIORITY_RS_DISC_CONTACT = 2 ; // CONTACT and PGPLIST must have +const uint8_t QOS_PRIORITY_RS_DISC_PGP_LIST = 2 ; // same priority. +const uint8_t QOS_PRIORITY_RS_DISC_SERVICES = 2 ; +const uint8_t QOS_PRIORITY_RS_DISC_PGP_CERT = 1 ; + +// Heartbeat. +// +const uint8_t QOS_PRIORITY_RS_HEARTBEAT_PULSE = 8 ; + // Chat/Msgs // const uint8_t QOS_PRIORITY_RS_CHAT_ITEM = 7 ; diff --git a/libretroshare/src/serialiser/rsconfigitems.cc b/libretroshare/src/serialiser/rsconfigitems.cc index a5b5ab03a..c67cdab92 100644 --- a/libretroshare/src/serialiser/rsconfigitems.cc +++ b/libretroshare/src/serialiser/rsconfigitems.cc @@ -780,11 +780,15 @@ void RsPeerNetItem::clear() gpg_id.clear(); location.clear(); netMode = 0; - visState = 0; + vs_disc = 0; + vs_dht = 0; lastContact = 0; - localAddr.TlvClear(); - extAddr.TlvClear(); + localAddrV4.TlvClear(); + extAddrV4.TlvClear(); + localAddrV6.TlvClear(); + extAddrV6.TlvClear(); + dyndns.clear(); localAddrList.TlvClear(); @@ -812,19 +816,29 @@ std::ostream &RsPeerNetItem::print(std::ostream &out, uint16_t indent) out << "netMode: " << netMode << std::endl; printIndent(out, int_Indent); - out << "visState: " << visState << std::endl; + out << "vs_disc: " << vs_disc << std::endl; + + printIndent(out, int_Indent); + out << "vs_dht: " << vs_dht << std::endl; printIndent(out, int_Indent); out << "lastContact: " << lastContact << std::endl; printIndent(out, int_Indent); - out << "localAddr: " << std::endl; - localAddr.print(out, int_Indent); + out << "localAddrV4: " << std::endl; + localAddrV4.print(out, int_Indent); printIndent(out, int_Indent); - out << "extAddr: " << std::endl; - extAddr.print(out, int_Indent); - + out << "extAddrV4: " << std::endl; + extAddrV4.print(out, int_Indent); + + printIndent(out, int_Indent); + out << "localAddrV6: " << std::endl; + localAddrV6.print(out, int_Indent); + + printIndent(out, int_Indent); + out << "extAddrV6: " << std::endl; + extAddrV6.print(out, int_Indent); printIndent(out, int_Indent); out << "DynDNS: " << dyndns << std::endl; @@ -845,10 +859,15 @@ uint32_t RsPeerConfigSerialiser::sizeNet(RsPeerNetItem *i) s += GetTlvStringSize(i->gpg_id); s += GetTlvStringSize(i->location); s += 4; /* netMode */ - s += 4; /* visState */ + s += 2; /* vs_disc */ + s += 2; /* vs_dht */ s += 4; /* lastContact */ - s += i->localAddr.TlvSize(); /* localaddr */ - s += i->extAddr.TlvSize(); /* remoteaddr */ + + s += i->localAddrV4.TlvSize(); /* localaddr */ + s += i->extAddrV4.TlvSize(); /* remoteaddr */ + s += i->localAddrV6.TlvSize(); /* localaddr */ + s += i->extAddrV6.TlvSize(); /* remoteaddr */ + s += GetTlvStringSize(i->dyndns); //add the size of the ip list @@ -900,10 +919,14 @@ bool RsPeerConfigSerialiser::serialiseNet(RsPeerNetItem *item, void *data, uint3 ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_GPGID, item->gpg_id); /* Mandatory */ ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_LOCATION, item->location); /* Mandatory */ ok &= setRawUInt32(data, tlvsize, &offset, item->netMode); /* Mandatory */ - ok &= setRawUInt32(data, tlvsize, &offset, item->visState); /* Mandatory */ + ok &= setRawUInt16(data, tlvsize, &offset, item->vs_disc); /* Mandatory */ + ok &= setRawUInt16(data, tlvsize, &offset, item->vs_dht); /* Mandatory */ ok &= setRawUInt32(data, tlvsize, &offset, item->lastContact); /* Mandatory */ - ok &= item->localAddr.SetTlv(data, tlvsize, &offset); - ok &= item->extAddr.SetTlv(data, tlvsize, &offset); + + ok &= item->localAddrV4.SetTlv(data, tlvsize, &offset); + ok &= item->extAddrV4.SetTlv(data, tlvsize, &offset); + ok &= item->localAddrV6.SetTlv(data, tlvsize, &offset); + ok &= item->extAddrV6.SetTlv(data, tlvsize, &offset); ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_DYNDNS, item->dyndns); @@ -974,11 +997,14 @@ RsPeerNetItem *RsPeerConfigSerialiser::deserialiseNet(void *data, uint32_t *size ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_GPGID, item->gpg_id); /* Mandatory */ ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_LOCATION, item->location); /* Mandatory */ ok &= getRawUInt32(data, rssize, &offset, &(item->netMode)); /* Mandatory */ - ok &= getRawUInt32(data, rssize, &offset, &(item->visState)); /* Mandatory */ + ok &= getRawUInt16(data, rssize, &offset, &(item->vs_disc)); /* Mandatory */ + ok &= getRawUInt16(data, rssize, &offset, &(item->vs_dht)); /* Mandatory */ ok &= getRawUInt32(data, rssize, &offset, &(item->lastContact)); /* Mandatory */ - ok &= item->localAddr.GetTlv(data, rssize, &offset); - ok &= item->extAddr.GetTlv(data, rssize, &offset); + ok &= item->localAddrV4.GetTlv(data, rssize, &offset); + ok &= item->extAddrV4.GetTlv(data, rssize, &offset); + ok &= item->localAddrV6.GetTlv(data, rssize, &offset); + ok &= item->extAddrV6.GetTlv(data, rssize, &offset); ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_DYNDNS, item->dyndns); ok &= item->localAddrList.GetTlv(data, rssize, &offset); diff --git a/libretroshare/src/serialiser/rsconfigitems.h b/libretroshare/src/serialiser/rsconfigitems.h index 74ce1e9a8..b06c92370 100644 --- a/libretroshare/src/serialiser/rsconfigitems.h +++ b/libretroshare/src/serialiser/rsconfigitems.h @@ -76,11 +76,15 @@ std::ostream &print(std::ostream &out, uint16_t indent = 0); std::string gpg_id; /* Mandatory */ std::string location; /* not Mandatory */ uint32_t netMode; /* Mandatory */ - uint32_t visState; /* Mandatory */ + uint16_t vs_disc; /* Mandatory */ + uint16_t vs_dht; /* Mandatory */ uint32_t lastContact; /* Mandatory */ - RsTlvIpAddress localAddr; /* Mandatory */ - RsTlvIpAddress extAddr; /* Mandatory */ + RsTlvIpAddress localAddrV4; /* Mandatory */ + RsTlvIpAddress extAddrV4; /* Mandatory */ + RsTlvIpAddress localAddrV6; /* Mandatory */ + RsTlvIpAddress extAddrV6; /* Mandatory */ + std::string dyndns; RsTlvIpAddrSet localAddrList; diff --git a/libretroshare/src/serialiser/rsdiscitems.cc b/libretroshare/src/serialiser/rsdiscitems.cc deleted file mode 100644 index 91e114f03..000000000 --- a/libretroshare/src/serialiser/rsdiscitems.cc +++ /dev/null @@ -1,770 +0,0 @@ - -/* - * libretroshare/src/serialiser: rsdiscitems.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/rsbaseserial.h" - -#include "serialiser/rsserviceids.h" -#include "serialiser/rsdiscitems.h" - -#include "serialiser/rstlvbase.h" -#include "serialiser/rstlvtypes.h" - -/*** - * #define RSSERIAL_DEBUG 1 - * #define RSSERIAL_ERROR_DEBUG 1 - ***/ - -#define RSSERIAL_ERROR_DEBUG 1 - -#include - -/*************************************************************************/ - -uint32_t RsDiscSerialiser::size(RsItem *i) -{ - RsDiscAskInfo *inf; - RsDiscReply *rdr; - RsDiscVersion *rdv; - RsDiscHeartbeat *rdt; - - /* do reply first - as it is derived from Item */ - if (NULL != (rdr = dynamic_cast(i))) - { - return sizeReply(rdr); - } - else if (NULL != (inf = dynamic_cast(i))) - { - return sizeAskInfo(inf); - } - else if (NULL != (rdv = dynamic_cast(i))) - { - return sizeVersion(rdv); - } - else if (NULL != (rdt = dynamic_cast(i))) - { - return sizeHeartbeat(rdt); - } - - return 0; -} - -/* serialise the data to the buffer */ -bool RsDiscSerialiser::serialise(RsItem *i, void *data, uint32_t *pktsize) -{ - RsDiscAskInfo *inf; - RsDiscReply *rdr; - RsDiscVersion *rdv; - RsDiscHeartbeat *rdt; - - /* do reply first - as it is derived from Item */ - if (NULL != (rdr = dynamic_cast(i))) - { - return serialiseReply(rdr, data, pktsize); - } - else if (NULL != (inf = dynamic_cast(i))) - { - return serialiseAskInfo(inf, data, pktsize); - } - else if (NULL != (rdv = dynamic_cast(i))) - { - return serialiseVersion(rdv, data, pktsize); - } - else if (NULL != (rdt = dynamic_cast(i))) - { - return serialiseHeartbeat(rdt, data, pktsize); - } - - return false; -} - -RsItem *RsDiscSerialiser::deserialise(void *data, uint32_t *pktsize) -{ - /* get the type and size */ - uint32_t rstype = getRsItemId(data); - - if ((RS_PKT_VERSION_SERVICE != getRsItemVersion(rstype)) || - (RS_SERVICE_TYPE_DISC != getRsItemService(rstype))) - { - std::cerr << "RsDiscSerialiser::deserialise() Wrong Type" << std::endl; - return NULL; /* wrong type */ - } - - switch(getRsItemSubType(rstype)) - { - case RS_PKT_SUBTYPE_DISC_REPLY: - return deserialiseReply(data, pktsize); - break; - case RS_PKT_SUBTYPE_DISC_ASK_INFO: - return deserialiseAskInfo(data, pktsize); - break; - case RS_PKT_SUBTYPE_DISC_VERSION: - return deserialiseVersion(data, pktsize); - break; - case RS_PKT_SUBTYPE_DISC_HEARTBEAT: - return deserialiseHeartbeat(data, pktsize); - break; - default: - return NULL; - break; - } - return NULL; -} - -/*************************************************************************/ - -RsDiscAskInfo::~RsDiscAskInfo() -{ - return; -} - -void RsDiscAskInfo::clear() -{ - gpg_id.clear(); -} - -std::ostream &RsDiscAskInfo::print(std::ostream &out, uint16_t indent) -{ - printRsItemBase(out, "RsDiscAskInfo", indent); - uint16_t int_Indent = indent + 2; - - printIndent(out, int_Indent); - out << "gpg_id: " << gpg_id << std::endl; - - printRsItemEnd(out, "RsDiscAskInfo", indent); - return out; -} - - -uint32_t RsDiscSerialiser::sizeAskInfo(RsDiscAskInfo *item) -{ - uint32_t s = 8; /* header */ - s += GetTlvStringSize(item->gpg_id); - return s; -} - -/* serialise the data to the buffer */ -bool RsDiscSerialiser::serialiseAskInfo(RsDiscAskInfo *item, void *data, uint32_t *pktsize) -{ - uint32_t tlvsize = sizeAskInfo(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 << "RsDiscSerialiser::serialiseAskInfo() Header: " << ok << std::endl; - std::cerr << "RsDiscSerialiser::serialiseAskInfo() Size: " << tlvsize << std::endl; -#endif - - /* skip the header */ - offset += 8; - - /* add mandatory parts first */ - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_PEERID, item->gpg_id); - - if (offset != tlvsize) { - ok = false; -#ifdef RSSERIAL_ERROR_DEBUG - std::cerr << "RsDiscSerialiser::serialiseAskInfo() Size Error! " << std::endl; -#endif - } - - return ok; -} - -RsDiscAskInfo *RsDiscSerialiser::deserialiseAskInfo(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_DISC != getRsItemService(rstype)) || - (RS_PKT_SUBTYPE_DISC_ASK_INFO != getRsItemSubType(rstype))) - { -#ifdef RSSERIAL_ERROR_DEBUG - std::cerr << "RsDiscSerialiser::deserialiseAskInfo() Wrong Type" << std::endl; -#endif - return NULL; /* wrong type */ - } - - if (*pktsize < rssize) /* check size */ - { -#ifdef RSSERIAL_ERROR_DEBUG - std::cerr << "RsDiscSerialiser::deserialiseAskInfo() Not Enough Space" << std::endl; -#endif - return NULL; /* not enough data */ - } - - /* set the packet length */ - *pktsize = rssize; - - bool ok = true; - - /* ready to load */ - RsDiscAskInfo *item = new RsDiscAskInfo(); - item->clear(); - - /* skip the header */ - offset += 8; - - /* get mandatory parts first */ - ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_PEERID, item->gpg_id); - - if (offset != rssize) { -#ifdef RSSERIAL_ERROR_DEBUG - std::cerr << "RsDiscSerialiser::deserialiseAskInfo() offset != rssize" << std::endl; -#endif - /* error */ - delete item; - return NULL; - } - - if (!ok) { -#ifdef RSSERIAL_ERROR_DEBUG - std::cerr << "RsDiscSerialiser::deserialiseAskInfo() ok = false" << std::endl; -#endif - delete item; - return NULL; - } - - return item; -} - - -/*************************************************************************/ - - -RsDiscReply::~RsDiscReply() -{ - return; -} - -void RsDiscReply::clear() -{ - aboutId.clear(); - certGPG.clear(); - rsPeerList.clear(); -} - -std::ostream &RsDiscReply::print(std::ostream &out, uint16_t indent) -{ - printRsItemBase(out, "RsDiscReply", indent); - uint16_t int_Indent = indent + 2; - - printIndent(out, int_Indent); - out << "AboutId: " << aboutId << std::endl; - - printIndent(out, int_Indent); - out << "certGPG: " << certGPG << std::endl; - - printIndent(out, int_Indent); - out << "RsDiscReply::print() RsPeerNetItem list : " << std::endl; - for (std::list::iterator pitemIt = rsPeerList.begin(); pitemIt!=(rsPeerList.end()); pitemIt++) { - printIndent(out, int_Indent); - pitemIt->print(std::cerr, indent); - } - - printRsItemEnd(out, "RsDiscReply", indent); - return out; -} - - -uint32_t RsDiscSerialiser::sizeReply(RsDiscReply *item) -{ - uint32_t s = 8; /* header */ -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDiscSerialiser::sizeReply() Header Size: " << s << std::endl; -#endif - s += GetTlvStringSize(item->aboutId); - -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDiscSerialiser::sizeReply() +AboutId Size: " << s << std::endl; -#endif - s += GetTlvStringSize(item->certGPG); - -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDiscSerialiser::sizeReply() +certGPG Size: " << s << std::endl; -#endif - - RsPeerConfigSerialiser rss ; - - for (std::list::iterator it = item->rsPeerList.begin(); it != item->rsPeerList.end(); it++) - { - s += rss.size(&(*it)) ; -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDiscSerialiser::sizeReply() +RsPeerNetItem Size: " << s << std::endl; -#endif - } - -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDiscSerialiser::sizeReply() Total Size: " << s << std::endl; -#endif - - return s; -} - -/* serialise the data to the buffer */ -bool RsDiscSerialiser::serialiseReply(RsDiscReply *item, void *data, uint32_t *pktsize) -{ - uint32_t tlvsize = sizeReply(item); - uint32_t offset = 0; - -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDiscSerialiser::serialiseReply() tlvsize: " << tlvsize; - std::cerr << std::endl; -#endif - - if (*pktsize < tlvsize) - { -#ifdef RSSERIAL_ERROR_DEBUG - std::cerr << "RsDiscSerialiser::serialiseReply() ERROR not enough space" << std::endl; - std::cerr << "RsDiscSerialiser::serialiseReply() ERROR *pktsize: " << *pktsize << " tlvsize: " << tlvsize; - std::cerr << std::endl; -#endif - return false; /* not enough space */ - } - - *pktsize = tlvsize; - - bool ok = true; - - ok &= setRsItemHeader(data, tlvsize, item->PacketId(), tlvsize); - -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDiscSerialiser::serialiseReply() Header: " << ok << std::endl; - std::cerr << "RsDiscSerialiser::serialiseReply() Size: " << tlvsize << std::endl; -#endif - - /* skip the header */ - offset += 8; - - /* add mandatory parts first */ - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_PEERID, item->aboutId); - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_CERT_GPG, item->certGPG); - -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDiscSerialiser::serialiseReply() Offset After Strings: " << offset << std::endl; -#endif - - //store the ip list - RsPeerConfigSerialiser rss ; - std::list::iterator pitemIt; - - for (pitemIt = item->rsPeerList.begin(); pitemIt!=(item->rsPeerList.end()) && ok; ++pitemIt) - { - uint32_t size = *pktsize - offset ;//~(uint32_t)0; // we must be conservative otherwise the serialiser returns false !! - - ok &= rss.serialise(&(*pitemIt), (void *) (((char *) data) + offset), &size); - - // The size has been updated to its exact value. - offset += size; - -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDiscSerialiser::serialiseReply() RsPeerNetItem ok?: " << ok << std::endl; - std::cerr << "RsDiscSerialiser::serialiseReply() Offset After RsPeerNetItem: " << offset << std::endl; -#endif - - } - - if (offset != tlvsize) - { - ok = false; -#ifdef RSSERIAL_ERROR_DEBUG - std::cerr << "RsDiscSerialiser::serialiseReply() Size Error: " << tlvsize << " != " << offset << std::endl; -#endif - } - - return ok; -} - -RsDiscReply *RsDiscSerialiser::deserialiseReply(void *data, uint32_t *pktsize) -{ - /* get the type and size */ - uint32_t rstype = getRsItemId(data); - uint32_t rssize = getRsItemSize(data); - - uint32_t offset = 0; - -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDiscSerialiser::deserialiseReply() Pkt Type: " << std::hex << rstype << std::dec; - std::cerr << "RsDiscSerialiser::deserialiseReply() Pkt Size: " << rssize << std::endl; -#endif - - if ((RS_PKT_VERSION_SERVICE != getRsItemVersion(rstype)) || - (RS_SERVICE_TYPE_DISC != getRsItemService(rstype)) || - (RS_PKT_SUBTYPE_DISC_REPLY != getRsItemSubType(rstype))) - { -#ifdef RSSERIAL_ERROR_DEBUG - std::cerr << "RsDiscSerialiser::deserialiseReply() Wrong Type" << std::endl; -#endif - return NULL; /* wrong type */ - } - - if (*pktsize < rssize) /* check size */ - { -#ifdef RSSERIAL_ERROR_DEBUG - std::cerr << "RsDiscSerialiser::deserialiseReply() pktsize != rssize" << std::endl; -#endif - return NULL; /* not enough data */ - } - - /* set the packet length */ - *pktsize = rssize; - - bool ok = true; - - /* ready to load */ - RsDiscReply *item = new RsDiscReply(); - item->clear(); - - /* skip the header */ - offset += 8; - - /* get mandatory parts first */ - ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_PEERID, item->aboutId); - ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_CERT_GPG, item->certGPG); - -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDiscSerialiser::deserialiseReply() offset after Strings: " << offset << std::endl; -#endif - - //get the peernet address list - RsPeerConfigSerialiser rss ; - - while (offset < rssize) - { - uint32_t peerNetSize = rssize - offset ; - - RsPeerNetItem *rsPeerNetItem = (RsPeerNetItem*)rss.deserialise((void *) (((char *) data) + offset), &peerNetSize); - - offset += peerNetSize; - -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDiscSerialiser::deserialiseReply() offset aft PeerNetItem: " << offset << std::endl; -#endif - - if(rsPeerNetItem == NULL) - { -#ifdef RSSERIAL_ERROR_DEBUG - std::cerr << "RsDiscSerialiser::deserialiseReply() ERROR deserialise PeerNetItem Failed" << std::endl; -#endif - break ; - } - - item->rsPeerList.push_back(*rsPeerNetItem); - delete rsPeerNetItem ; - } - - if (offset != rssize) - { -#ifdef RSSERIAL_ERROR_DEBUG - std::cerr << "RsDiscSerialiser::deserialiseReply() offset != rssize" << std::endl; -#endif - /* error */ - delete item; - return NULL; - } - - if (!ok) - { -#ifdef RSSERIAL_ERROR_DEBUG - std::cerr << "RsDiscSerialiser::deserialiseReply() ok = false" << std::endl; -#endif - delete item; - return NULL; - } - - return item; -} - -/*************************************************************************/ - - -RsDiscVersion::~RsDiscVersion() -{ - return; -} -void RsDiscVersion::clear() -{ - version = ""; -} - -std::ostream &RsDiscVersion::print(std::ostream &out, uint16_t indent) -{ - printRsItemBase(out, "RsDiscVersion", indent); - uint16_t int_Indent = indent + 2; - - printIndent(out, int_Indent); - out << "Version String: " << version << std::endl; - - printRsItemEnd(out, "RsDiscVersion", indent); - return out; -} - -uint32_t RsDiscSerialiser::sizeVersion(RsDiscVersion *item) -{ - uint32_t s = 8; /* header */ - s += GetTlvStringSize(item->version); - - return s; -} - -/* serialise the data to the buffer */ -bool RsDiscSerialiser::serialiseVersion(RsDiscVersion *item, void *data, uint32_t *pktsize) -{ - uint32_t tlvsize = sizeVersion(item); - uint32_t offset = 0; - - if (*pktsize < tlvsize) - return false; /* not enough space */ - - *pktsize = tlvsize; - - bool ok = true; - - ok &= setRsItemHeader(data, *pktsize, item->PacketId(), *pktsize); - -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDiscSerialiser::serialiseVersion() Header: " << ok << std::endl; - std::cerr << "RsDiscSerialiser::serialiseVersion() Size: " << tlvsize << std::endl; -#endif - - /* skip the header */ - offset += 8; - - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_VALUE, item->version); - - if (offset != tlvsize) - { - ok = false; -#ifdef RSSERIAL_ERROR_DEBUG - std::cerr << "RsDiscSerialiser::serialiseVersion() Size Error! " << std::endl; - std::cerr << "Offset: " << offset << " tlvsize: " << tlvsize << std::endl; -#endif - } - - return ok; -} - -RsDiscVersion *RsDiscSerialiser::deserialiseVersion(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_DISC != getRsItemService(rstype)) || - (RS_PKT_SUBTYPE_DISC_VERSION != getRsItemSubType(rstype))) - { -#ifdef RSSERIAL_ERROR_DEBUG - std::cerr << "RsDiscSerialiser::deserialiseVersion() Wrong Type" << std::endl; -#endif - return NULL; /* wrong type */ - } - - if (*pktsize < rssize) /* check size */ - { -#ifdef RSSERIAL_ERROR_DEBUG - std::cerr << "RsDiscSerialiser::deserialiseVersion() pktsize != rssize" << std::endl; - std::cerr << "Pktsize: " << *pktsize << " Rssize: " << rssize << std::endl; -#endif - return NULL; /* not enough data */ - } - - /* set the packet length */ - *pktsize = rssize; - - bool ok = true; - - /* ready to load */ - RsDiscVersion *item = new RsDiscVersion(); - item->clear(); - - /* skip the header */ - offset += 8; - - ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_VALUE, item->version); - - if (offset != rssize) - { -#ifdef RSSERIAL_ERROR_DEBUG - std::cerr << "RsDiscSerialiser::deserialiseVersion() offset != rssize" << std::endl; - std::cerr << "Offset: " << offset << " Rssize: " << rssize << std::endl; -#endif - /* error */ - delete item; - return NULL; - } - - if (!ok) - { -#ifdef RSSERIAL_ERROR_DEBUG - std::cerr << "RsDiscSerialiser::deserialiseVersion() ok = false" << std::endl; -#endif - delete item; - return NULL; - } - - return item; -} - - -/*************************************************************************/ - - -RsDiscHeartbeat::~RsDiscHeartbeat() -{ - return; -} -void RsDiscHeartbeat::clear() -{ -} - -std::ostream &RsDiscHeartbeat::print(std::ostream &out, uint16_t indent) -{ - printRsItemBase(out, "RsDiscHeartbeat", indent); - printRsItemEnd(out, "RsDiscHeartbeat", indent); - return out; -} - -uint32_t RsDiscSerialiser::sizeHeartbeat(RsDiscHeartbeat */*item*/) -{ - uint32_t s = 8; /* header */ - - return s; -} - -/* serialise the data to the buffer */ -bool RsDiscSerialiser::serialiseHeartbeat(RsDiscHeartbeat *item, void *data, uint32_t *pktsize) -{ - uint32_t tlvsize = sizeHeartbeat(item); - uint32_t offset = 0; - - if (*pktsize < tlvsize) - return false; /* not enough space */ - - *pktsize = tlvsize; - - bool ok = true; - - ok &= setRsItemHeader(data, *pktsize, item->PacketId(), *pktsize); - -#ifdef RSSERIAL_DEBUG - std::cerr << "RsDiscSerialiser::serialiseHeartbeat() Header: " << ok << std::endl; - std::cerr << "RsDiscSerialiser::serialiseHeartbeat() Size: " << tlvsize << std::endl; -#endif - - /* skip the header */ - offset += 8; - - if (offset != tlvsize) - { - ok = false; -#ifdef RSSERIAL_ERROR_DEBUG - std::cerr << "RsDiscSerialiser::serialiseHeartbeat() Size Error! " << std::endl; - std::cerr << "Offset: " << offset << " tlvsize: " << tlvsize << std::endl; -#endif - } - - return ok; -} - -RsDiscHeartbeat *RsDiscSerialiser::deserialiseHeartbeat(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_DISC != getRsItemService(rstype)) || - (RS_PKT_SUBTYPE_DISC_HEARTBEAT != getRsItemSubType(rstype))) - { -#ifdef RSSERIAL_ERROR_DEBUG - std::cerr << "RsDiscSerialiser::deserialiseHeartbeat() Wrong Type" << std::endl; -#endif - return NULL; /* wrong type */ - } - - if (*pktsize < rssize) /* check size */ - { -#ifdef RSSERIAL_ERROR_DEBUG - std::cerr << "RsDiscSerialiser::deserialiseHeartbeat() pktsize != rssize" << std::endl; - std::cerr << "Pktsize: " << *pktsize << " Rssize: " << rssize << std::endl; -#endif - return NULL; /* not enough data */ - } - - /* set the packet length */ - *pktsize = rssize; - - bool ok = true; - - /* ready to load */ - RsDiscHeartbeat *item = new RsDiscHeartbeat(); - item->clear(); - - /* skip the header */ - offset += 8; - - if (offset != rssize) - { -#ifdef RSSERIAL_ERROR_DEBUG - std::cerr << "RsDiscSerialiser::deserialiseHeartbeat() offset != rssize" << std::endl; - std::cerr << "Offset: " << offset << " Rssize: " << rssize << std::endl; -#endif - /* error */ - delete item; - return NULL; - } - - if (!ok) - { -#ifdef RSSERIAL_ERROR_DEBUG - std::cerr << "RsDiscSerialiser::deserialiseHeartbeat() ok = false" << std::endl; -#endif - delete item; - return NULL; - } - - return item; -} - - -/*************************************************************************/ diff --git a/libretroshare/src/serialiser/rsdiscitems.h b/libretroshare/src/serialiser/rsdiscitems.h deleted file mode 100644 index cfa6e70a7..000000000 --- a/libretroshare/src/serialiser/rsdiscitems.h +++ /dev/null @@ -1,193 +0,0 @@ -/* - * libretroshare/src/serialiser: rsdiscitems.h - * - * Serialiser 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 RS_DISC_ITEMS_H -#define RS_DISC_ITEMS_H - -#include "serialiser/rsserial.h" -#include "serialiser/rstlvbase.h" -#include "serialiser/rstlvtypes.h" -#include "serialiser/rsserviceids.h" -#include "serialiser/rsconfigitems.h" - -//const uint8_t RS_PKT_SUBTYPE_DISC_OWN = 0x01; -const uint8_t RS_PKT_SUBTYPE_DISC_REPLY = 0x02; -const uint8_t RS_PKT_SUBTYPE_DISC_ASK_INFO = 0x03; -const uint8_t RS_PKT_SUBTYPE_DISC_VERSION = 0x05; -const uint8_t RS_PKT_SUBTYPE_DISC_HEARTBEAT = 0x06; - -class RsDiscItem: public RsItem -{ - protected: - RsDiscItem(uint8_t subtype) :RsItem(RS_PKT_VERSION_SERVICE, RS_SERVICE_TYPE_DISC, subtype) {} -}; - - -//class RsDiscOwnItem: public RsDiscItem -//{ -// public: -// -// RsDiscOwnItem() :RsDiscItem(RS_PKT_SUBTYPE_DISC_OWN ) {} -// -// -// virtual ~RsDiscOwnItem(); -// -// virtual void clear(); -// virtual std::ostream &print(std::ostream &out, uint16_t indent = 0); -// -// //use for transmitting ip address list -// std::list ipAddressList; -// -// //use for transmitting my own adress list -// struct sockaddr_in laddr; -// struct sockaddr_in saddr; -// -// // time frame of recent connections. -// uint16_t contact_tf; -// // flags... -// uint32_t discFlags; -//}; - -class RsDiscReply: public RsDiscItem -{ - public: - - RsDiscReply() - :RsDiscItem(RS_PKT_SUBTYPE_DISC_REPLY) - { - setPriorityLevel(QOS_PRIORITY_RS_DISC_REPLY); - } - -virtual ~RsDiscReply(); - -virtual void clear(); -virtual std::ostream &print(std::ostream &out, uint16_t indent = 0); - - //use for transmitting ip address list - std::list rsPeerList; - - //use for transmitting my own adress list -// struct sockaddr_in currentladdr; -// struct sockaddr_in currentsaddr; - - // time frame of recent connections. - //uint16_t contact_tf; - // flags... - //uint32_t discFlags; - - std::string aboutId; - std::string certGPG; -}; - -class RsDiscAskInfo: public RsDiscItem -{ - public: - - RsDiscAskInfo() - :RsDiscItem(RS_PKT_SUBTYPE_DISC_ASK_INFO) - { - setPriorityLevel(QOS_PRIORITY_RS_DISC_ASK_INFO); - } - -virtual ~RsDiscAskInfo(); - -virtual void clear(); -virtual std::ostream &print(std::ostream &out, uint16_t indent = 0); - - std::string gpg_id; -}; - -class RsDiscVersion: public RsDiscItem -{ -public: - RsDiscVersion() :RsDiscItem(RS_PKT_SUBTYPE_DISC_VERSION) - { - setPriorityLevel(QOS_PRIORITY_RS_DISC_VERSION); - } - - virtual ~RsDiscVersion(); - - virtual void clear(); - virtual std::ostream &print(std::ostream &out, uint16_t indent = 0); - - std::string version; -}; - -class RsDiscHeartbeat: public RsDiscItem -{ -public: - RsDiscHeartbeat() :RsDiscItem(RS_PKT_SUBTYPE_DISC_HEARTBEAT) - { - setPriorityLevel(QOS_PRIORITY_RS_DISC_HEART_BEAT) ; - } - - virtual ~RsDiscHeartbeat(); - - virtual void clear(); - virtual std::ostream &print(std::ostream &out, uint16_t indent = 0); -}; - -class RsDiscSerialiser: public RsSerialType -{ - public: - RsDiscSerialiser() - :RsSerialType(RS_PKT_VERSION_SERVICE, RS_SERVICE_TYPE_DISC) - { return; } - -virtual ~RsDiscSerialiser() { 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 sizeAskInfo(RsDiscAskInfo *); -virtual bool serialiseAskInfo(RsDiscAskInfo *item, void *data, uint32_t *size); -virtual RsDiscAskInfo *deserialiseAskInfo(void *data, uint32_t *size); - -virtual uint32_t sizeReply(RsDiscReply *); -virtual bool serialiseReply (RsDiscReply *item, void *data, uint32_t *size); -virtual RsDiscReply *deserialiseReply(void *data, uint32_t *size); - -//virtual uint32_t sizeIssuer(RsDiscIssuer *); -//virtual bool serialiseIssuer (RsDiscIssuer *item, void *data, uint32_t *size); -//virtual RsDiscIssuer *deserialiseIssuer(void *data, uint32_t *size); - -virtual uint32_t sizeVersion(RsDiscVersion *); -virtual bool serialiseVersion(RsDiscVersion *item, void *data, uint32_t *size); -virtual RsDiscVersion *deserialiseVersion(void *data, uint32_t *size); - -virtual uint32_t sizeHeartbeat(RsDiscHeartbeat *); -virtual bool serialiseHeartbeat(RsDiscHeartbeat *item, void *data, uint32_t *size); -virtual RsDiscHeartbeat *deserialiseHeartbeat(void *data, uint32_t *size); - -}; - - -#endif // RS_DISC_ITEMS_H - diff --git a/libretroshare/src/serialiser/rsdiscovery2items.cc b/libretroshare/src/serialiser/rsdiscovery2items.cc new file mode 100644 index 000000000..f66faac67 --- /dev/null +++ b/libretroshare/src/serialiser/rsdiscovery2items.cc @@ -0,0 +1,890 @@ + +/* + * libretroshare/src/serialiser: rsdiscitems.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/rsbaseserial.h" + +#include "serialiser/rsserviceids.h" +#include "serialiser/rsdiscovery2items.h" + +#include "serialiser/rstlvbase.h" +#include "serialiser/rstlvtypes.h" + +/*** + * #define RSSERIAL_DEBUG 1 + * #define RSSERIAL_ERROR_DEBUG 1 + ***/ + +#define RSSERIAL_ERROR_DEBUG 1 + +#include + +/*************************************************************************/ + +uint32_t RsDiscSerialiser::size(RsItem *i) +{ + RsDiscPgpListItem *pgplist; + RsDiscPgpCertItem *pgpcert; + RsDiscContactItem *contact; + //RsDiscServicesItem *services; + + if (NULL != (pgplist = dynamic_cast(i))) + { + return sizePgpList(pgplist); + } + else if (NULL != (pgpcert = dynamic_cast(i))) + { + return sizePgpCert(pgpcert); + } + else if (NULL != (contact = dynamic_cast(i))) + { + return sizeContact(contact); + } +#if 0 + else if (NULL != (services = dynamic_cast(i))) + { + return sizeServices(services); + } +#endif + return 0; +} + +/* serialise the data to the buffer */ +bool RsDiscSerialiser::serialise(RsItem *i, void *data, uint32_t *pktsize) +{ + RsDiscPgpListItem *pgplist; + RsDiscPgpCertItem *pgpcert; + RsDiscContactItem *contact; + //RsDiscServicesItem *services; + + if (NULL != (pgplist = dynamic_cast(i))) + { + return serialisePgpList(pgplist, data, pktsize); + } + else if (NULL != (pgpcert = dynamic_cast(i))) + { + return serialisePgpCert(pgpcert, data, pktsize); + } + else if (NULL != (contact = dynamic_cast(i))) + { + return serialiseContact(contact, data, pktsize); + } +#if 0 + else if (NULL != (services = dynamic_cast(i))) + { + return serialiseServices(services, data, pktsize); + } +#endif + + return false; +} + +RsItem *RsDiscSerialiser::deserialise(void *data, uint32_t *pktsize) +{ + /* get the type and size */ + uint32_t rstype = getRsItemId(data); + + if ((RS_PKT_VERSION_SERVICE != getRsItemVersion(rstype)) || + (RS_SERVICE_TYPE_DISC != getRsItemService(rstype))) + { + std::cerr << "RsDiscSerialiser::deserialise() Wrong Type" << std::endl; + return NULL; /* wrong type */ + } + + switch(getRsItemSubType(rstype)) + { + case RS_PKT_SUBTYPE_DISC_PGP_LIST: + return deserialisePgpList(data, pktsize); + break; + case RS_PKT_SUBTYPE_DISC_PGP_CERT: + return deserialisePgpCert(data, pktsize); + break; + case RS_PKT_SUBTYPE_DISC_CONTACT: + return deserialiseContact(data, pktsize); + break; +#if 0 + case RS_PKT_SUBTYPE_DISC_SERVICES: + return deserialiseServices(data, pktsize); + break; +#endif + default: + return NULL; + break; + } + return NULL; +} + +/*************************************************************************/ + +RsDiscPgpListItem::~RsDiscPgpListItem() +{ + return; +} + +void RsDiscPgpListItem::clear() +{ + mode = DISC_PGP_LIST_MODE_NONE; + pgpIdSet.TlvClear(); +} + +std::ostream &RsDiscPgpListItem::print(std::ostream &out, uint16_t indent) +{ + printRsItemBase(out, "RsDiscPgpListItem", indent); + uint16_t int_Indent = indent + 2; + + printIndent(out, int_Indent); + out << "mode: " << mode << std::endl; + pgpIdSet.print(out, int_Indent); + + printRsItemEnd(out, "RsDiscPgpList", indent); + return out; +} + + +uint32_t RsDiscSerialiser::sizePgpList(RsDiscPgpListItem *item) +{ + uint32_t s = 8; /* header */ + s += 4; /* mode */ + s += item->pgpIdSet.TlvSize(); + return s; +} + +/* serialise the data to the buffer */ +bool RsDiscSerialiser::serialisePgpList(RsDiscPgpListItem *item, void *data, uint32_t *pktsize) +{ + uint32_t tlvsize = sizePgpList(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 << "RsDiscSerialiser::serialisePgpList() Header: " << ok << std::endl; + std::cerr << "RsDiscSerialiser::serialisePgpList() Size: " << tlvsize << std::endl; +#endif + + /* skip the header */ + offset += 8; + + /* add mandatory parts first */ + ok &= setRawUInt32(data, tlvsize, &offset, item->mode); + ok &= item->pgpIdSet.SetTlv(data, tlvsize, &offset); + + if (offset != tlvsize) { + ok = false; +#ifdef RSSERIAL_ERROR_DEBUG + std::cerr << "RsDiscSerialiser::serialisePgpList() Size Error! " << std::endl; +#endif + } + + return ok; +} + +RsDiscPgpListItem *RsDiscSerialiser::deserialisePgpList(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_DISC != getRsItemService(rstype)) || + (RS_PKT_SUBTYPE_DISC_PGP_LIST != getRsItemSubType(rstype))) + { +#ifdef RSSERIAL_ERROR_DEBUG + std::cerr << "RsDiscSerialiser::deserialisePgpList() Wrong Type" << std::endl; +#endif + return NULL; /* wrong type */ + } + + if (*pktsize < rssize) /* check size */ + { +#ifdef RSSERIAL_ERROR_DEBUG + std::cerr << "RsDiscSerialiser::deserialisePgpList() Not Enough Space" << std::endl; +#endif + return NULL; /* not enough data */ + } + + /* set the packet length */ + *pktsize = rssize; + + bool ok = true; + + /* ready to load */ + RsDiscPgpListItem *item = new RsDiscPgpListItem(); + item->clear(); + + /* skip the header */ + offset += 8; + + /* get mandatory parts first */ + ok &= getRawUInt32(data, rssize, &offset, &(item->mode)); + ok &= item->pgpIdSet.GetTlv(data, rssize, &offset); + + if (offset != rssize) { +#ifdef RSSERIAL_ERROR_DEBUG + std::cerr << "RsDiscSerialiser::deserialisePgpList() offset != rssize" << std::endl; +#endif + /* error */ + delete item; + return NULL; + } + + if (!ok) { +#ifdef RSSERIAL_ERROR_DEBUG + std::cerr << "RsDiscSerialiser::deserialisePgpList() ok = false" << std::endl; +#endif + delete item; + return NULL; + } + + return item; +} + + +/*************************************************************************/ +/*************************************************************************/ +#if 0 + +RsDiscServicesItem::~RsDiscServicesItem() +{ + return; +} + +void RsDiscServicesItem::clear() +{ + version.clear(); + mServiceIdMap.TlvClear(); +} + +std::ostream &RsDiscServicesItem::print(std::ostream &out, uint16_t indent) +{ + printRsItemBase(out, "RsDiscServicesItem", indent); + uint16_t int_Indent = indent + 2; + + printIndent(out, int_Indent); + out << "version: " << version << std::endl; + mServiceIdMap.print(out, int_Indent); + + printRsItemEnd(out, "RsDiscServicesItem", indent); + return out; +} + + +uint32_t RsDiscSerialiser::sizeServices(RsDiscServicesItem *item) +{ + uint32_t s = 8; /* header */ + s += GetTlvStringSize(item->version); /* version */ + s += item->mServiceIdMap.TlvSize(); + return s; +} + +/* serialise the data to the buffer */ +bool RsDiscSerialiser::serialiseServices(RsDiscServicesItem *item, void *data, uint32_t *pktsize) +{ + uint32_t tlvsize = sizeServices(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 << "RsDiscSerialiser::serialiseServices() Header: " << ok << std::endl; + std::cerr << "RsDiscSerialiser::serialiseServices() Size: " << tlvsize << std::endl; +#endif + + /* skip the header */ + offset += 8; + + /* add mandatory parts first */ + ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_VERSION, item->version); + ok &= item->mServiceIdMap.SetTlv(data, tlvsize, &offset); + + if (offset != tlvsize) { + ok = false; +#ifdef RSSERIAL_ERROR_DEBUG + std::cerr << "RsDiscSerialiser::serialiseServices() Size Error! " << std::endl; +#endif + } + + return ok; +} + +RsDiscServicesItem *RsDiscSerialiser::deserialiseServices(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_DISC != getRsItemService(rstype)) || + (RS_PKT_SUBTYPE_DISC_PGP_LIST != getRsItemSubType(rstype))) + { +#ifdef RSSERIAL_ERROR_DEBUG + std::cerr << "RsDiscSerialiser::deserialiseServices() Wrong Type" << std::endl; +#endif + return NULL; /* wrong type */ + } + + if (*pktsize < rssize) /* check size */ + { +#ifdef RSSERIAL_ERROR_DEBUG + std::cerr << "RsDiscSerialiser::deserialiseServices() Not Enough Space" << std::endl; +#endif + return NULL; /* not enough data */ + } + + /* set the packet length */ + *pktsize = rssize; + + bool ok = true; + + /* ready to load */ + RsDiscServicesItem *item = new RsDiscServicesItem(); + item->clear(); + + /* skip the header */ + offset += 8; + + /* get mandatory parts first */ + ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_VERSION, item->version); + ok &= item->mServiceIdMap.GetTlv(data, rssize, &offset); + + if (offset != rssize) { +#ifdef RSSERIAL_ERROR_DEBUG + std::cerr << "RsDiscSerialiser::deserialiseServices() offset != rssize" << std::endl; +#endif + /* error */ + delete item; + return NULL; + } + + if (!ok) { +#ifdef RSSERIAL_ERROR_DEBUG + std::cerr << "RsDiscSerialiser::deserialiseServices() ok = false" << std::endl; +#endif + delete item; + return NULL; + } + + return item; +} + +#endif + + +/*************************************************************************/ + +RsDiscPgpCertItem::~RsDiscPgpCertItem() +{ + return; +} + +void RsDiscPgpCertItem::clear() +{ + pgpId.clear(); + pgpCert.clear(); +} + +std::ostream &RsDiscPgpCertItem::print(std::ostream &out, uint16_t indent) +{ + printRsItemBase(out, "RsDiscPgpCertItem", indent); + uint16_t int_Indent = indent + 2; + + printIndent(out, int_Indent); + out << "pgpId: " << pgpId << std::endl; + printIndent(out, int_Indent); + out << "pgpCert: " << pgpCert << std::endl; + + printRsItemEnd(out, "RsDiscPgpCert", indent); + return out; +} + + +uint32_t RsDiscSerialiser::sizePgpCert(RsDiscPgpCertItem *item) +{ + uint32_t s = 8; /* header */ + s += GetTlvStringSize(item->pgpId); + s += GetTlvStringSize(item->pgpCert); + return s; +} + +/* serialise the data to the buffer */ +bool RsDiscSerialiser::serialisePgpCert(RsDiscPgpCertItem *item, void *data, uint32_t *pktsize) +{ + uint32_t tlvsize = sizePgpCert(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 << "RsDiscSerialiser::serialisePgpCert() Header: " << ok << std::endl; + std::cerr << "RsDiscSerialiser::serialisePgpCert() Size: " << tlvsize << std::endl; +#endif + + /* skip the header */ + offset += 8; + + /* add mandatory parts first */ + ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_PGPID, item->pgpId); + ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_PGPCERT, item->pgpCert); + + if (offset != tlvsize) { + ok = false; +#ifdef RSSERIAL_ERROR_DEBUG + std::cerr << "RsDiscSerialiser::serialisePgpCert() Size Error! " << std::endl; +#endif + } + + return ok; +} + +RsDiscPgpCertItem *RsDiscSerialiser::deserialisePgpCert(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_DISC != getRsItemService(rstype)) || + (RS_PKT_SUBTYPE_DISC_PGP_CERT != getRsItemSubType(rstype))) + { +#ifdef RSSERIAL_ERROR_DEBUG + std::cerr << "RsDiscSerialiser::deserialisePgpCert() Wrong Type" << std::endl; +#endif + return NULL; /* wrong type */ + } + + if (*pktsize < rssize) /* check size */ + { +#ifdef RSSERIAL_ERROR_DEBUG + std::cerr << "RsDiscSerialiser::deserialisePgpCert() Not Enough Space" << std::endl; +#endif + return NULL; /* not enough data */ + } + + /* set the packet length */ + *pktsize = rssize; + + bool ok = true; + + /* ready to load */ + RsDiscPgpCertItem *item = new RsDiscPgpCertItem(); + item->clear(); + + /* skip the header */ + offset += 8; + + /* get mandatory parts first */ + ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_PGPID, item->pgpId); + ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_PGPCERT, item->pgpCert); + + if (offset != rssize) { +#ifdef RSSERIAL_ERROR_DEBUG + std::cerr << "RsDiscSerialiser::deserialisePgpCert() offset != rssize" << std::endl; +#endif + /* error */ + delete item; + return NULL; + } + + if (!ok) { +#ifdef RSSERIAL_ERROR_DEBUG + std::cerr << "RsDiscSerialiser::deserialisePgpCert() ok = false" << std::endl; +#endif + delete item; + return NULL; + } + + return item; +} + + +/*************************************************************************/ + + +RsDiscContactItem::~RsDiscContactItem() +{ + return; +} + +void RsDiscContactItem::clear() +{ + pgpId.clear(); + sslId.clear(); + + location.clear(); + version.clear(); + + netMode = 0; + vs_disc = 0; + vs_dht = 0; + lastContact = 0; + + isHidden = false; + hiddenAddr.clear(); + hiddenPort = 0; + + localAddrV4.TlvClear(); + extAddrV4.TlvClear(); + localAddrV6.TlvClear(); + extAddrV6.TlvClear(); + + + dyndns.clear(); + + localAddrList.TlvClear(); + extAddrList.TlvClear(); +} + +std::ostream &RsDiscContactItem::print(std::ostream &out, uint16_t indent) +{ + printRsItemBase(out, "RsDiscContact", indent); + uint16_t int_Indent = indent + 2; + + printIndent(out, int_Indent); + out << "pgpId: " << pgpId << std::endl; + + printIndent(out, int_Indent); + out << "sslId: " << sslId << std::endl; + + printIndent(out, int_Indent); + out << "location: " << location << std::endl; + + printIndent(out, int_Indent); + out << "version: " << version << std::endl; + + printIndent(out, int_Indent); + out << "netMode: " << netMode << std::endl; + + printIndent(out, int_Indent); + out << "vs_disc: " << vs_disc << std::endl; + + printIndent(out, int_Indent); + out << "vs_dht: " << vs_dht << std::endl; + + printIndent(out, int_Indent); + out << "lastContact: " << lastContact << std::endl; + + if (isHidden) + { + printIndent(out, int_Indent); + out << "hiddenAddr: " << hiddenAddr << std::endl; + + printIndent(out, int_Indent); + out << "hiddenPort: " << hiddenPort << std::endl; + } + else + { + printIndent(out, int_Indent); + out << "localAddrV4: " << std::endl; + localAddrV4.print(out, int_Indent); + + printIndent(out, int_Indent); + out << "extAddrV4: " << std::endl; + extAddrV4.print(out, int_Indent); + + printIndent(out, int_Indent); + out << "localAddrV6: " << std::endl; + localAddrV6.print(out, int_Indent); + + printIndent(out, int_Indent); + out << "extAddrV6: " << std::endl; + extAddrV6.print(out, int_Indent); + + printIndent(out, int_Indent); + out << "DynDNS: " << dyndns << std::endl; + + printIndent(out, int_Indent); + out << "localAddrList: " << std::endl; + localAddrList.print(out, int_Indent); + + printIndent(out, int_Indent); + out << "extAddrList: " << std::endl; + extAddrList.print(out, int_Indent); + } + + printRsItemEnd(out, "RsDiscContact", indent); + return out; +} + + +uint32_t RsDiscSerialiser::sizeContact(RsDiscContactItem *item) +{ + uint32_t s = 8; /* header */ + s += GetTlvStringSize(item->pgpId); + s += GetTlvStringSize(item->sslId); + + s += GetTlvStringSize(item->location); + s += GetTlvStringSize(item->version); + + s += 4; // netMode + s += 2; // vs_disc + s += 2; // vs_dht + s += 4; // last contact + + if (item->isHidden) + { + s += GetTlvStringSize(item->hiddenAddr); + s += 2; /* hidden port */ + } + else + { + s += item->localAddrV4.TlvSize(); /* localaddr */ + s += item->extAddrV4.TlvSize(); /* remoteaddr */ + + s += item->localAddrV6.TlvSize(); /* localaddr */ + s += item->extAddrV6.TlvSize(); /* remoteaddr */ + + s += GetTlvStringSize(item->dyndns); + + //add the size of the ip list + s += item->localAddrList.TlvSize(); + s += item->extAddrList.TlvSize(); + } + +#ifdef RSSERIAL_DEBUG + std::cerr << "RsDiscSerialiser::sizeContact() Total Size: " << s << std::endl; +#endif + + return s; +} + +/* serialise the data to the buffer */ +bool RsDiscSerialiser::serialiseContact(RsDiscContactItem *item, void *data, uint32_t *pktsize) +{ + uint32_t tlvsize = sizeContact(item); + uint32_t offset = 0; + +#ifdef RSSERIAL_DEBUG + std::cerr << "RsDiscSerialiser::serialiseContact() tlvsize: " << tlvsize; + std::cerr << std::endl; +#endif + + if (*pktsize < tlvsize) + { +#ifdef RSSERIAL_ERROR_DEBUG + std::cerr << "RsDiscSerialiser::serialiseContact() ERROR not enough space" << std::endl; + std::cerr << "RsDiscSerialiser::serialiseContact() ERROR *pktsize: " << *pktsize << " tlvsize: " << tlvsize; + std::cerr << std::endl; +#endif + return false; /* not enough space */ + } + + *pktsize = tlvsize; + + bool ok = true; + + ok &= setRsItemHeader(data, tlvsize, item->PacketId(), tlvsize); + +#ifdef RSSERIAL_DEBUG + std::cerr << "RsDiscSerialiser::serialiseContact() Header: " << ok << std::endl; + std::cerr << "RsDiscSerialiser::serialiseContact() Size: " << tlvsize << std::endl; +#endif + + /* skip the header */ + offset += 8; + + /* add mandatory parts first */ + ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_PGPID, item->pgpId); + ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_PEERID, item->sslId); + + ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_LOCATION, item->location); + ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_VERSION, item->version); + + ok &= setRawUInt32(data, tlvsize, &offset, item->netMode); + ok &= setRawUInt16(data, tlvsize, &offset, item->vs_disc); + ok &= setRawUInt16(data, tlvsize, &offset, item->vs_dht); + ok &= setRawUInt32(data, tlvsize, &offset, item->lastContact); /* Mandatory */ + + if (item->isHidden) + { + ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_DOMADDR, item->hiddenAddr); + ok &= setRawUInt16(data, tlvsize, &offset, item->hiddenPort); + } + else + { + ok &= item->localAddrV4.SetTlv(data, tlvsize, &offset); + ok &= item->extAddrV4.SetTlv(data, tlvsize, &offset); + ok &= item->localAddrV6.SetTlv(data, tlvsize, &offset); + ok &= item->extAddrV6.SetTlv(data, tlvsize, &offset); + + ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_DYNDNS, item->dyndns); + + ok &= item->localAddrList.SetTlv(data, tlvsize, &offset); + ok &= item->extAddrList.SetTlv(data, tlvsize, &offset); + } + + + if (offset != tlvsize) + { + ok = false; +#ifdef RSSERIAL_ERROR_DEBUG + std::cerr << "RsDiscSerialiser::serialiseContact() Size Error: " << tlvsize << " != " << offset << std::endl; +#endif + } + + return ok; +} + +RsDiscContactItem *RsDiscSerialiser::deserialiseContact(void *data, uint32_t *pktsize) +{ + /* get the type and size */ + uint32_t rstype = getRsItemId(data); + uint32_t rssize = getRsItemSize(data); + + uint32_t offset = 0; + +#ifdef RSSERIAL_DEBUG + std::cerr << "RsDiscSerialiser::deserialiseContact() Pkt Type: " << std::hex << rstype << std::dec; + std::cerr << "RsDiscSerialiser::deserialiseContact() Pkt Size: " << rssize << std::endl; +#endif + + if ((RS_PKT_VERSION_SERVICE != getRsItemVersion(rstype)) || + (RS_SERVICE_TYPE_DISC != getRsItemService(rstype)) || + (RS_PKT_SUBTYPE_DISC_CONTACT != getRsItemSubType(rstype))) + { +#ifdef RSSERIAL_ERROR_DEBUG + std::cerr << "RsDiscSerialiser::deserialiseContact() Wrong Type" << std::endl; +#endif + return NULL; /* wrong type */ + } + + if (*pktsize < rssize) /* check size */ + { +#ifdef RSSERIAL_ERROR_DEBUG + std::cerr << "RsDiscSerialiser::deserialiseContact() Not enough space" << std::endl; +#endif + return NULL; /* not enough data */ + } + + /* set the packet length */ + *pktsize = rssize; + + bool ok = true; + + /* ready to load */ + RsDiscContactItem *item = new RsDiscContactItem(); + item->clear(); + + /* skip the header */ + offset += 8; + + /* get mandatory parts first */ + ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_PGPID, item->pgpId); + ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_PEERID, item->sslId); + + ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_LOCATION, item->location); + ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_VERSION, item->version); + + ok &= getRawUInt32(data, rssize, &offset, &(item->netMode)); /* Mandatory */ + ok &= getRawUInt16(data, rssize, &offset, &(item->vs_disc)); /* Mandatory */ + ok &= getRawUInt16(data, rssize, &offset, &(item->vs_dht)); /* Mandatory */ + ok &= getRawUInt32(data, rssize, &offset, &(item->lastContact)); + + if (rssize < offset + TLV_HEADER_SIZE) + { +#ifdef RSSERIAL_ERROR_DEBUG + std::cerr << "RsDiscSerialiser::deserialiseContact() missized" << std::endl; +#endif + /* no extra */ + delete item; + return NULL; + } + + uint16_t tlvtype = GetTlvType( &(((uint8_t *) data)[offset]) ); + + if (tlvtype == TLV_TYPE_STR_DOMADDR) + { + item->isHidden = true; + + ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_DOMADDR, item->hiddenAddr); + ok &= getRawUInt16(data, rssize, &offset, &(item->hiddenPort)); /* Mandatory */ + + } + else + { + item->isHidden = false; + + ok &= item->localAddrV4.GetTlv(data, rssize, &offset); + ok &= item->extAddrV4.GetTlv(data, rssize, &offset); + ok &= item->localAddrV6.GetTlv(data, rssize, &offset); + ok &= item->extAddrV6.GetTlv(data, rssize, &offset); + + ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_DYNDNS, item->dyndns); + ok &= item->localAddrList.GetTlv(data, rssize, &offset); + ok &= item->extAddrList.GetTlv(data, rssize, &offset); + } + + + if (offset != rssize) + { +#ifdef RSSERIAL_ERROR_DEBUG + std::cerr << "RsDiscSerialiser::deserialiseContact() offset != rssize" << std::endl; +#endif + /* error */ + delete item; + return NULL; + } + + if (!ok) + { +#ifdef RSSERIAL_ERROR_DEBUG + std::cerr << "RsDiscSerialiser::deserialiseContact() ok = false" << std::endl; +#endif + delete item; + return NULL; + } + + return item; +} + +/*************************************************************************/ + diff --git a/libretroshare/src/serialiser/rsdiscovery2items.h b/libretroshare/src/serialiser/rsdiscovery2items.h new file mode 100644 index 000000000..ff8ac1491 --- /dev/null +++ b/libretroshare/src/serialiser/rsdiscovery2items.h @@ -0,0 +1,203 @@ +/* + * libretroshare/src/serialiser: rsdiscitems.h + * + * Serialiser 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 RS_DISC_ITEMS_H +#define RS_DISC_ITEMS_H + +#include "serialiser/rsserial.h" +#include "serialiser/rstlvbase.h" +#include "serialiser/rstlvtypes.h" +#include "serialiser/rsserviceids.h" +#include "serialiser/rsconfigitems.h" + +const uint8_t RS_PKT_SUBTYPE_DISC_PGP_LIST = 0x01; +const uint8_t RS_PKT_SUBTYPE_DISC_PGP_CERT = 0x02; +const uint8_t RS_PKT_SUBTYPE_DISC_CONTACT = 0x03; +const uint8_t RS_PKT_SUBTYPE_DISC_SERVICES = 0x04; + +class RsDiscItem: public RsItem +{ + protected: + RsDiscItem(uint8_t subtype) :RsItem(RS_PKT_VERSION_SERVICE, RS_SERVICE_TYPE_DISC, subtype) {} +}; + + +#define DISC_PGP_LIST_MODE_NONE 0x00 +#define DISC_PGP_LIST_MODE_FRIENDS 0x01 +#define DISC_PGP_LIST_MODE_GETCERT 0x02 + +class RsDiscPgpListItem: public RsDiscItem +{ + public: + + RsDiscPgpListItem() + :RsDiscItem(RS_PKT_SUBTYPE_DISC_PGP_LIST) + { + setPriorityLevel(QOS_PRIORITY_RS_DISC_PGP_LIST); + } + +virtual ~RsDiscPgpListItem(); + +virtual void clear(); +virtual std::ostream &print(std::ostream &out, uint16_t indent = 0); + + uint32_t mode; + RsTlvPgpIdSet pgpIdSet; +}; + + + +class RsDiscPgpCertItem: public RsDiscItem +{ + public: + + RsDiscPgpCertItem() + :RsDiscItem(RS_PKT_SUBTYPE_DISC_PGP_CERT) + { + setPriorityLevel(QOS_PRIORITY_RS_DISC_PGP_CERT); + } + +virtual ~RsDiscPgpCertItem(); + +virtual void clear(); +virtual std::ostream &print(std::ostream &out, uint16_t indent = 0); + + std::string pgpId; + std::string pgpCert; +}; + + +class RsDiscContactItem: public RsDiscItem +{ + public: + + RsDiscContactItem() + :RsDiscItem(RS_PKT_SUBTYPE_DISC_CONTACT) + { + setPriorityLevel(QOS_PRIORITY_RS_DISC_CONTACT); + } + +virtual ~RsDiscContactItem(); + +virtual void clear(); +virtual std::ostream &print(std::ostream &out, uint16_t indent = 0); + + std::string pgpId; + std::string sslId; + + // COMMON + std::string location; + std::string version; + + uint32_t netMode; /* Mandatory */ + uint16_t vs_disc; /* Mandatory */ + uint16_t vs_dht; /* Mandatory */ + uint32_t lastContact; + + bool isHidden; /* not serialised */ + + // HIDDEN. + std::string hiddenAddr; + uint16_t hiddenPort; + + // STANDARD. + + RsTlvIpAddress localAddrV4; /* Mandatory */ + RsTlvIpAddress extAddrV4; /* Mandatory */ + + RsTlvIpAddress localAddrV6; /* Mandatory */ + RsTlvIpAddress extAddrV6; /* Mandatory */ + + std::string dyndns; + + RsTlvIpAddrSet localAddrList; + RsTlvIpAddrSet extAddrList; +}; + +#if 0 +class RsDiscServicesItem: public RsDiscItem +{ + public: + + RsDiscServicesItem() + :RsDiscItem(RS_PKT_SUBTYPE_DISC_SERVICES) + { + setPriorityLevel(QOS_PRIORITY_RS_DISC_SERVICES); + } + +virtual ~RsDiscServicesItem(); + +virtual void clear(); +virtual std::ostream &print(std::ostream &out, uint16_t indent = 0); + + + std::string version; + RsTlvServiceIdMap mServiceIdMap; +}; + +#endif + + +class RsDiscSerialiser: public RsSerialType +{ + public: + RsDiscSerialiser() + :RsSerialType(RS_PKT_VERSION_SERVICE, RS_SERVICE_TYPE_DISC) + { return; } + +virtual ~RsDiscSerialiser() { 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 sizePgpList(RsDiscPgpListItem *); +virtual bool serialisePgpList(RsDiscPgpListItem *item, void *data, uint32_t *size); +virtual RsDiscPgpListItem *deserialisePgpList(void *data, uint32_t *size); + +virtual uint32_t sizePgpCert(RsDiscPgpCertItem *); +virtual bool serialisePgpCert(RsDiscPgpCertItem *item, void *data, uint32_t *size); +virtual RsDiscPgpCertItem *deserialisePgpCert(void *data, uint32_t *size); + +virtual uint32_t sizeContact(RsDiscContactItem *); +virtual bool serialiseContact(RsDiscContactItem *item, void *data, uint32_t *size); +virtual RsDiscContactItem *deserialiseContact(void *data, uint32_t *size); + +#if 0 +virtual uint32_t sizeServices(RsDiscServicesItem *); +virtual bool serialiseServices(RsDiscServicesItem *item, void *data, uint32_t *size); +virtual RsDiscServicesItem *deserialiseServices(void *data, uint32_t *size); + +#endif + +}; + + +#endif // RS_DISC_ITEMS_H + diff --git a/libretroshare/src/serialiser/rsheartbeatitems.cc b/libretroshare/src/serialiser/rsheartbeatitems.cc new file mode 100644 index 000000000..55f1e844a --- /dev/null +++ b/libretroshare/src/serialiser/rsheartbeatitems.cc @@ -0,0 +1,206 @@ + +/* + * libretroshare/src/serialiser: rsheartbeatitems.cc + * + * RetroShare Serialiser. + * + * Copyright 2013-2013 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.1 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/rsserviceids.h" +#include "serialiser/rsheartbeatitems.h" + +/*** + * #define HEART_DEBUG 1 + ***/ + +#define HEART_DEBUG 1 + +#include + +/*************************************************************************/ + +uint32_t RsHeartbeatSerialiser::size(RsItem *i) +{ + RsHeartbeatItem *beat; + + if (NULL != (beat = dynamic_cast(i))) + { + return sizeHeartbeat(beat); + } + return 0; +} + +/* serialise the data to the buffer */ +bool RsHeartbeatSerialiser::serialise(RsItem *i, void *data, uint32_t *pktsize) +{ + RsHeartbeatItem *beat; + + if (NULL != (beat = dynamic_cast(i))) + { + return serialiseHeartbeat(beat, data, pktsize); + } + return false; +} + +RsItem *RsHeartbeatSerialiser::deserialise(void *data, uint32_t *pktsize) +{ + /* get the type and size */ + uint32_t rstype = getRsItemId(data); + + if ((RS_PKT_VERSION_SERVICE != getRsItemVersion(rstype)) || + (RS_SERVICE_TYPE_HEARTBEAT != getRsItemService(rstype))) + { + +#ifdef HEART_DEBUG + std::cerr << "RsHeartbeatSerialiser::deserialise() Wrong Type" << std::endl; +#endif + return NULL; + } + + switch(getRsItemSubType(rstype)) + { + case RS_PKT_SUBTYPE_HEARTBEAT_PULSE: + return deserialiseHeartbeat(data, pktsize); + break; + default: + return NULL; + break; + } + return NULL; +} + +/*************************************************************************/ + + +void RsHeartbeatItem::clear() +{ +} + +std::ostream &RsHeartbeatItem::print(std::ostream &out, uint16_t indent) +{ + printRsItemBase(out, "RsHeartbeatItem", indent); + printRsItemEnd(out, "RsHeartbeatItem", indent); + return out; +} + +uint32_t RsHeartbeatSerialiser::sizeHeartbeat(RsHeartbeatItem */*item*/) +{ + uint32_t s = 8; /* header */ + return s; +} + +/* serialise the data to the buffer */ +bool RsHeartbeatSerialiser::serialiseHeartbeat(RsHeartbeatItem *item, void *data, uint32_t *pktsize) +{ + uint32_t tlvsize = sizeHeartbeat(item); + uint32_t offset = 0; + + if (*pktsize < tlvsize) + { +#ifdef HEART_DEBUG + std::cerr << "RsHeartbeatSerialiser::serialiseHeartbeat() Not enough space" << std::endl; +#endif + return false; /* not enough space */ + } + + *pktsize = tlvsize; + + bool ok = true; + + ok &= setRsItemHeader(data, *pktsize, item->PacketId(), *pktsize); + + /* skip the header */ + offset += 8; + + if (offset != tlvsize) + { +#ifdef HEART_DEBUG + std::cerr << "RsHeartbeatSerialiser::serialiseHeartbeat() size error" << std::endl; +#endif + ok = false; + } + + return ok; +} + +RsHeartbeatItem *RsHeartbeatSerialiser::deserialiseHeartbeat(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_HEARTBEAT != getRsItemService(rstype)) || + (RS_PKT_SUBTYPE_HEARTBEAT_PULSE != getRsItemSubType(rstype))) + { +#ifdef HEART_DEBUG + std::cerr << "RsHeartbeatSerialiser::deserialiseHeartbeat() Wrong Type" << std::endl; +#endif + return NULL; /* wrong type */ + } + + if (*pktsize < rssize) /* check size */ + { +#ifdef HEART_DEBUG + std::cerr << "RsHeartbeatSerialiser::deserialiseHeartbeat() size error" << std::endl; +#endif + return NULL; /* not enough data */ + } + + /* set the packet length */ + *pktsize = rssize; + + bool ok = true; + + /* ready to load */ + RsHeartbeatItem *item = new RsHeartbeatItem(); + item->clear(); + + /* skip the header */ + offset += 8; + + if (offset != rssize) + { +#ifdef HEART_DEBUG + std::cerr << "RsHeartbeatSerialiser::deserialiseHeartbeat() size error2" << std::endl; +#endif + /* error */ + delete item; + return NULL; + } + + if (!ok) + { +#ifdef HEART_DEBUG + std::cerr << "RsHeartbeatSerialiser::deserialiseHeartbeat() ok = false" << std::endl; +#endif + delete item; + return NULL; + } + + return item; +} + + +/*************************************************************************/ diff --git a/libretroshare/src/serialiser/rsheartbeatitems.h b/libretroshare/src/serialiser/rsheartbeatitems.h new file mode 100644 index 000000000..cfabae2ee --- /dev/null +++ b/libretroshare/src/serialiser/rsheartbeatitems.h @@ -0,0 +1,72 @@ +/* + * libretroshare/src/serialiser: rsheartbeatitems.h + * + * Serialiser for RetroShare. + * + * Copyright 2004-2013 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.1 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 RS_HEARTBEAT_ITEMS_H +#define RS_HEARTBEAT_ITEMS_H + +#include "serialiser/rsserial.h" +#include "serialiser/rsserviceids.h" + +const uint8_t RS_PKT_SUBTYPE_HEARTBEAT_PULSE = 0x01; + +class RsHeartbeatItem: public RsItem +{ +public: + RsHeartbeatItem() :RsItem(RS_PKT_VERSION_SERVICE, RS_SERVICE_TYPE_HEARTBEAT, RS_PKT_SUBTYPE_HEARTBEAT_PULSE) + { + setPriorityLevel(QOS_PRIORITY_RS_HEARTBEAT_PULSE) ; + } + virtual ~RsHeartbeatItem() {} + + virtual void clear(); + virtual std::ostream &print(std::ostream &out, uint16_t indent = 0); +}; + +class RsHeartbeatSerialiser: public RsSerialType +{ + public: + RsHeartbeatSerialiser() + :RsSerialType(RS_PKT_VERSION_SERVICE, RS_SERVICE_TYPE_HEARTBEAT) + { return; } + +virtual ~RsHeartbeatSerialiser() { 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 sizeHeartbeat(RsHeartbeatItem *); +virtual bool serialiseHeartbeat(RsHeartbeatItem *item, void *data, uint32_t *size); +virtual RsHeartbeatItem *deserialiseHeartbeat(void *data, uint32_t *size); + +}; + + +#endif // RS_DISC_ITEMS_H + diff --git a/libretroshare/src/serialiser/rsserviceids.h b/libretroshare/src/serialiser/rsserviceids.h index 8095ed575..73e08d42d 100644 --- a/libretroshare/src/serialiser/rsserviceids.h +++ b/libretroshare/src/serialiser/rsserviceids.h @@ -46,6 +46,7 @@ const uint16_t RS_SERVICE_TYPE_CHAT = 0x0012; const uint16_t RS_SERVICE_TYPE_MSG = 0x0013; const uint16_t RS_SERVICE_TYPE_TURTLE = 0x0014; const uint16_t RS_SERVICE_TYPE_TUNNEL = 0x0015; +const uint16_t RS_SERVICE_TYPE_HEARTBEAT = 0x0016; /* BanList Still Testing at the moment - Service Only */ const uint16_t RS_SERVICE_TYPE_BANLIST = 0x0101; diff --git a/libretroshare/src/serialiser/rstlvbase.h b/libretroshare/src/serialiser/rstlvbase.h index a7697c6cd..0f1ecb97c 100644 --- a/libretroshare/src/serialiser/rstlvbase.h +++ b/libretroshare/src/serialiser/rstlvbase.h @@ -131,10 +131,13 @@ const uint16_t TLV_TYPE_STR_MSG = 0x0057; const uint16_t TLV_TYPE_STR_SUBJECT = 0x0058; const uint16_t TLV_TYPE_STR_LINK = 0x0059; const uint16_t TLV_TYPE_STR_GENID = 0x005a; -const uint16_t TLV_TYPE_STR_GPGID = 0x005b; +const uint16_t TLV_TYPE_STR_GPGID = 0x005b; /* depreciated */ +const uint16_t TLV_TYPE_STR_PGPID = 0x005b; /* same as GPG */ const uint16_t TLV_TYPE_STR_LOCATION = 0x005c; -const uint16_t TLV_TYPE_STR_CERT_GPG = 0x005d; +const uint16_t TLV_TYPE_STR_CERT_GPG = 0x005d; +const uint16_t TLV_TYPE_STR_PGPCERT = 0x005d; /* same as CERT_GPG */ const uint16_t TLV_TYPE_STR_CERT_SSL = 0x005e; +const uint16_t TLV_TYPE_STR_VERSION = 0x005f; /* Wide Chars (4 bytes per char) for internationalisation */ const uint16_t TLV_TYPE_WSTR_PEERID = 0x0060; diff --git a/libretroshare/src/serialiser/rstlvtypes.h b/libretroshare/src/serialiser/rstlvtypes.h index 45e6e1e68..4fd45bd4a 100644 --- a/libretroshare/src/serialiser/rstlvtypes.h +++ b/libretroshare/src/serialiser/rstlvtypes.h @@ -33,6 +33,8 @@ #include #include +#include + #include #include @@ -246,6 +248,29 @@ virtual std::ostream &print(std::ostream &out, uint16_t indent); }; +class RsTlvIntStringMap: public RsTlvItem +{ + public: + RsTlvIntStringMap() { return; } +virtual ~RsTlvIntStringMap() { return; } +virtual uint32_t TlvSize(); +virtual void TlvClear(); +virtual bool SetTlv(void *data, uint32_t size, uint32_t *offset); /* serialise */ +virtual bool GetTlv(void *data, uint32_t size, uint32_t *offset); /* deserialise */ +virtual std::ostream &print(std::ostream &out, uint16_t indent); + + uint32_t mapType; + std::map map; +}; + + +class RsTlvServiceIdMap: public RsTlvIntStringMap +{ + public: + RsTlvServiceIdMap(); +}; + + class RsTlvImage: public RsTlvItem { public: diff --git a/libretroshare/src/services/p3disc.h b/libretroshare/src/services/p3disc.h deleted file mode 100644 index 4a3e8aca5..000000000 --- a/libretroshare/src/services/p3disc.h +++ /dev/null @@ -1,178 +0,0 @@ -/* - * libretroshare/src/services: p3disc.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 MRK_PQI_AUTODISC_H -#define MRK_PQI_AUTODISC_H - -// The AutoDiscovery Class - -#include -#include - -// system specific network headers -#include "pqi/pqinetwork.h" - -#include "pqi/pqi.h" -#include "pqi/pqipersongrp.h" - -class p3ConnectMgr; - -#include "pqi/pqimonitor.h" -#include "serialiser/rsdiscitems.h" -#include "services/p3service.h" -#include "pqi/authgpg.h" - -class autoserver -{ - public: - autoserver() - :ts(0), discFlags(0) { return;} - - std::string id; - struct sockaddr_storage localAddr; - struct sockaddr_storage remoteAddr; - - time_t ts; - uint32_t discFlags; -}; - - -class autoneighbour: public autoserver -{ - public: - autoneighbour() - :autoserver(), authoritative(false) {} - - bool authoritative; - bool validAddrs; - - std::map neighbour_of; - -}; - -class p3PeerMgr; -class p3LinkMgr; -class p3NetMgr; - - -class p3disc: public p3Service, public pqiMonitor, public p3Config, public AuthGPGService -{ - public: - - - p3disc(p3PeerMgr *pm, p3LinkMgr *lm, p3NetMgr *nm, pqipersongrp *persGrp); - - /************* from pqiMonitor *******************/ -virtual void statusChange(const std::list &plist); - /************* from pqiMonitor *******************/ - -int tick(); - - /* GUI requires access */ -bool potentialGPGproxies(const std::string& id, std::list &proxyGPGIds); -bool potentialproxies(const std::string& id, std::list &proxyIds); -void getversions(std::map &versions); -void getWaitingDiscCount(unsigned int *sendCount, unsigned int *recvCount); - - /************* from AuthGPService ****************/ -virtual AuthGPGOperation *getGPGOperation(); -virtual void setGPGOperation(AuthGPGOperation *operation); - - protected: -/*****************************************************************/ -/*********************** p3config ******************************/ -/* Key Functions to be overloaded for Full Configuration */ -virtual RsSerialiser *setupSerialiser(); -virtual bool saveList(bool &cleanup, std::list&); -virtual bool loadList(std::list& load); -/*****************************************************************/ - - private: - - -void sendAllInfoToJustConnectedPeer(const std::string &id); -void sendJustConnectedPeerInfoToAllPeer(const std::string &id); - - /* Network Output */ -//void sendOwnDetails(std::string to); -void sendOwnVersion(std::string to); -RsDiscReply *createDiscReply(const std::string &to, const std::string &about); -//void sendPeerIssuer(std::string to, std::string about); -void sendHeartbeat(std::string to); -void askInfoToAllPeers(std::string about); - - /* Network Input */ -int handleIncoming(); -void recvAskInfo(RsDiscAskInfo *item); -void recvPeerDetails(RsDiscReply *item, const std::string &certGpgId); -//void recvPeerIssuerMsg(RsDiscIssuer *item); -void recvPeerVersionMsg(RsDiscVersion *item); -void recvHeartbeatMsg(RsDiscHeartbeat *item); -void recvDiscReply(RsDiscReply *dri); - -void removeFriend(std::string ssl_id); //keep tracks of removed friend so we're not gonna add them again immediately - -/* handle network shape */ -int addDiscoveryData(const std::string& fromId, const std::string& aboutId, - const std::string& fromGPGId,const std::string& aboutGPGId, - const struct sockaddr_storage &laddr, const struct sockaddr_storage &raddr, - uint32_t flags, time_t ts,bool& new_info); - -//int idServers(); - - private: - - p3PeerMgr *mPeerMgr; - p3LinkMgr *mLinkMgr; - p3NetMgr *mNetMgr; - - pqipersongrp *mPqiPersonGrp; - - /* data */ - RsMutex mDiscMtx; - - time_t mLastSentHeartbeatTime; - bool mDiscEnabled; - - //std::map deletedSSLFriendsIds; - - - std::map > mSendIdList; - std::list mPendingDiscReplyInList; - - // Neighbors at the gpg level. - std::map > gpg_neighbors ; - - // Original mapping. - std::map neighbours; - - // Rs Version. - std::map versions; -}; - - - - -#endif // MRK_PQI_AUTODISC_H diff --git a/libretroshare/src/services/p3disc.cc b/libretroshare/src/services/p3discovery2.cc similarity index 51% rename from libretroshare/src/services/p3disc.cc rename to libretroshare/src/services/p3discovery2.cc index 710c5c929..606c6e631 100644 --- a/libretroshare/src/services/p3disc.cc +++ b/libretroshare/src/services/p3discovery2.cc @@ -1,13 +1,13 @@ /* - * libretroshare/src/services: p3disc.cc + * libretroshare/src/services: p3discovery2.cc * * Services for RetroShare. * - * Copyright 2004-2008 by Robert Fernie. + * Copyright 2004-2013 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. + * License Version 2.1 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 @@ -23,6 +23,1269 @@ * */ +#include "services/p3discovery2.h" +#include "util/rsversion.h" + +#include "retroshare/rsiface.h" + + +// Interface pointer. +RsDisc *rsDisc = NULL; + +#define P3DISC_DEBUG 1 + + + +bool populateContactInfo(const peerState &detail, RsDiscContactItem *pkt) +{ + pkt->clear(); + + pkt->pgpId = detail.gpg_id; + pkt->sslId = detail.id; + pkt->location = detail.location; + pkt->version = ""; + pkt->netMode = detail.netMode; + pkt->vs_disc = detail.vs_disc; + pkt->vs_dht = detail.vs_dht; + + pkt->lastContact = time(NULL); + + if (detail.hiddenNode) + { + pkt->isHidden = true; + pkt->hiddenAddr = detail.hiddenDomain; + pkt->hiddenPort = detail.hiddenPort; + } + else + { + pkt->isHidden = false; + + pkt->localAddrV4.addr = detail.localaddr; + pkt->extAddrV4.addr = detail.serveraddr; + sockaddr_storage_clear(pkt->localAddrV6.addr); + sockaddr_storage_clear(pkt->extAddrV6.addr); + + pkt->dyndns = detail.dyndns; + detail.ipAddrs.mLocal.loadTlv(pkt->localAddrList); + detail.ipAddrs.mExt.loadTlv(pkt->extAddrList); + } + + return true; +} + +void DiscPgpInfo::mergeFriendList(const std::list &friends) +{ + std::list::const_iterator it; + for(it = friends.begin(); it != friends.end(); it++) + { + mFriendSet.insert(*it); + } +} + + +p3discovery2::p3discovery2(p3PeerMgr *peerMgr, p3LinkMgr *linkMgr, p3NetMgr *netMgr) +:p3Service(RS_SERVICE_TYPE_DISC), mPeerMgr(peerMgr), mLinkMgr(linkMgr), mNetMgr(netMgr), + mDiscMtx("p3discovery2") +{ + RsStackMutex stack(mDiscMtx); /********** STACK LOCKED MTX ******/ + + addSerialType(new RsDiscSerialiser()); + +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::p3discovery2()"; + std::cerr << std::endl; +#endif + + mLastPgpUpdate = 0; + + // Add self into PGP FriendList. + mFriendList[AuthGPG::getAuthGPG()->getGPGOwnId()] = DiscPgpInfo(); + + return; +} + +p3discovery2::~p3discovery2() +{ + return; + +} + + +void p3discovery2::addFriend(const SSLID &sslId) +{ + PGPID pgpId = getPGPId(sslId); + + RsStackMutex stack(mDiscMtx); /********** STACK LOCKED MTX ******/ + + std::map::iterator it; + it = mFriendList.find(pgpId); + if (it == mFriendList.end()) + { +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::addFriend() adding pgp entry: " << pgpId; + std::cerr << std::endl; +#endif + + mFriendList[pgpId] = DiscPgpInfo(); + + it = mFriendList.find(pgpId); + } + + + /* now add SSLID */ + + std::map::iterator sit; + sit = it->second.mSslIds.find(sslId); + if (sit == it->second.mSslIds.end()) + { +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::addFriend() adding ssl entry: " << sslId; + std::cerr << std::endl; +#endif + + it->second.mSslIds[sslId] = DiscSslInfo(); + sit = it->second.mSslIds.find(sslId); + } + + /* update Settings from peerMgr */ + peerState detail; + if (mPeerMgr->getFriendNetStatus(sit->first, detail)) + { + sit->second.mDiscStatus = detail.vs_disc; + } + else + { + sit->second.mDiscStatus = RS_VS_DISC_OFF; + } +} + +void p3discovery2::removeFriend(const SSLID &sslId) +{ + PGPID pgpId = getPGPId(sslId); + + RsStackMutex stack(mDiscMtx); /********** STACK LOCKED MTX ******/ + + std::map::iterator it; + it = mFriendList.find(pgpId); + if (it == mFriendList.end()) + { +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::removeFriend() missing pgp entry: " << pgpId; + std::cerr << std::endl; +#endif + return; + } + + std::map::iterator sit; + sit = it->second.mSslIds.find(sslId); + if (sit == it->second.mSslIds.end()) + { +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::addFriend() missing ssl entry: " << sslId; + std::cerr << std::endl; +#endif + return; + } + +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::addFriend() removing ssl entry: " << sslId; + std::cerr << std::endl; +#endif + it->second.mSslIds.erase(sit); + + if (it->second.mSslIds.empty()) + { +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::addFriend() pgpId now has no sslIds"; + std::cerr << std::endl; +#endif + /* pgp peer without any ssl entries -> check if they are still a real friend */ + if (!(AuthGPG::getAuthGPG()->isGPGAccepted(pgpId))) + { +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::addFriend() pgpId is no longer a friend, removing"; + std::cerr << std::endl; +#endif + mFriendList.erase(it); + } + } +} + + +PGPID p3discovery2::getPGPId(const SSLID &id) +{ + PGPID pgpId; + mPeerMgr->getGpgId(id, pgpId); + return pgpId; +} + + +int p3discovery2::tick() +{ + return handleIncoming(); +} + +int p3discovery2::handleIncoming() +{ + RsItem *item = NULL; + +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::handleIncoming()" << std::endl; +#endif + + int nhandled = 0; + // While messages read + while(NULL != (item = recvItem())) + { + RsDiscPgpListItem *pgplist = NULL; + RsDiscPgpCertItem *pgpcert = NULL; + RsDiscContactItem *contact = NULL; + nhandled++; + +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::handleIncoming() Received Message!" << std::endl; + item -> print(std::cerr); + std::cerr << std::endl; +#endif + + if (NULL != (contact = dynamic_cast (item))) + { + if (item->PeerId() == contact->sslId) /* self describing */ + { + recvOwnContactInfo(item->PeerId(), contact); + } + else if (rsPeers->servicePermissionFlags_sslid(item->PeerId()) & RS_SERVICE_PERM_DISCOVERY) + { + processContactInfo(item->PeerId(), contact); + } + else + { + /* not allowed */ + delete item; + } + continue; + } + + /* any other packets should be dropped if they don't have permission */ + if(!(rsPeers->servicePermissionFlags_sslid(item->PeerId()) & RS_SERVICE_PERM_DISCOVERY)) + { + delete item; + continue; + } + + if (NULL != (pgpcert = dynamic_cast (item))) + { + recvPGPCertificate(item->PeerId(), pgpcert); + } + else if (NULL != (pgplist = dynamic_cast (item))) + { + /* two types */ + if (pgplist->mode == DISC_PGP_LIST_MODE_FRIENDS) + { + processPGPList(pgplist->PeerId(), pgplist); + + } + else if (pgplist->mode == DISC_PGP_LIST_MODE_GETCERT) + { + recvPGPCertificateRequest(pgplist->PeerId(), pgplist); + } + else + { + delete item ; + } + } + else + { +#ifdef P3DISC_DEBUG + std::cerr << "p3disc::handleIncoming() Unknown Received Message!" << std::endl; + item -> print(std::cerr); + std::cerr << std::endl; +#endif + delete item; + } + } + +#ifdef P3DISC_DEBUG + std::cerr << "p3disc::handleIncoming() finished." << std::endl; +#endif + + return nhandled; +} + + + +void p3discovery2::sendOwnContactInfo(const SSLID &sslid) +{ + +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::sendOwnContactInfo()"; + std::cerr << std::endl; +#endif + peerState detail; + if (mPeerMgr->getOwnNetStatus(detail)) + { + RsDiscContactItem *pkt = new RsDiscContactItem(); + populateContactInfo(detail, pkt); + pkt->version = RsUtil::retroshareVersion(); + + pkt->PeerId(sslid); + +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::sendOwnContactInfo() sending:" << std::endl; + pkt -> print(std::cerr); + std::cerr << std::endl; +#endif + sendItem(pkt); + } +} + + +void p3discovery2::recvOwnContactInfo(const SSLID &fromId, const RsDiscContactItem *item) +{ + +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::recvOwnContactInfo()"; + std::cerr << std::endl; + + std::cerr << "Info sent by the peer itself -> updating self info:" << std::endl; + std::cerr << " -> vs_disc : " << item->vs_disc << std::endl; + std::cerr << " -> vs_dht : " << item->vs_dht << std::endl; + std::cerr << " -> network mode : " << item->netMode << std::endl; + std::cerr << " -> location : " << item->location << std::endl; + std::cerr << std::endl; +#endif + + // Peer Own Info replaces the existing info, because the + // peer is the primary source of his own IPs. + + mPeerMgr->setNetworkMode(fromId, item->netMode); + mPeerMgr->setLocation(fromId, item->location); + mPeerMgr->setVisState(fromId, item->vs_disc, item->vs_dht); + + setPeerVersion(fromId, item->version); + updatePeerAddresses(item); + + // This information will be sent out to online peers, at the receipt of their PGPList. + // It is important that PGPList is received after the OwnContactItem. + // This should happen, but is not enforced by the protocol. + + // start peer list exchange. + sendPGPList(fromId); + + // Update mDiscStatus. + RsStackMutex stack(mDiscMtx); /********** STACK LOCKED MTX ******/ + + PGPID pgpId = getPGPId(fromId); + std::map::iterator it = mFriendList.find(pgpId); + if (it != mFriendList.end()) + { + std::map::iterator sit = it->second.mSslIds.find(fromId); + if (sit != it->second.mSslIds.end()) + { + sit->second.mDiscStatus = item->vs_disc; +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::recvOwnContactInfo()"; + std::cerr << "updating mDiscStatus to: " << sit->second.mDiscStatus; + std::cerr << std::endl; +#endif + } + else + { +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::recvOwnContactInfo()"; + std::cerr << " ERROR missing SSL Entry: " << fromId; + std::cerr << std::endl; +#endif + } + } + else + { +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::recvOwnContactInfo()"; + std::cerr << " ERROR missing PGP Entry: " << pgpId; + std::cerr << std::endl; +#endif + } + + // cleanup. + delete item; +} + +void p3discovery2::updatePeerAddresses(const RsDiscContactItem *item) +{ + if (item->isHidden) + { + mPeerMgr->setHiddenDomainPort(item->sslId, item->hiddenAddr, item->hiddenPort); + } + else + { + mPeerMgr->setLocalAddress(item->sslId, item->localAddrV4.addr); + mPeerMgr->setExtAddress(item->sslId, item->extAddrV4.addr); + mPeerMgr->setDynDNS(item->sslId, item->dyndns); + + updatePeerAddressList(item); + } +} + + +void p3discovery2::updatePeerAddressList(const RsDiscContactItem *item) +{ + if (item->isHidden) + { + } + else + { + pqiIpAddrSet addrsFromPeer; + addrsFromPeer.mLocal.extractFromTlv(item->localAddrList); + addrsFromPeer.mExt.extractFromTlv(item->extAddrList); + +#ifdef P3DISC_DEBUG + std::cerr << "Setting address list to peer " << item->sslId << ", to be:" << std::endl ; + + std::string addrstr; + addrsFromPeer.printAddrs(addrstr); + std::cerr << addrstr; + std::cerr << std::endl; +#endif + mPeerMgr->updateAddressList(item->sslId, addrsFromPeer); + } +} + + +// Starts the Discovery process. +// should only be called it DISC2_STATUS_NOT_HIDDEN(OwnInfo.status). +void p3discovery2::sendPGPList(const SSLID &toId) +{ + updatePgpFriendList(); + + RsStackMutex stack(mDiscMtx); /********** STACK LOCKED MTX ******/ + + +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::sendPGPList() to " << toId; + std::cerr << std::endl; +#endif + + RsDiscPgpListItem *pkt = new RsDiscPgpListItem(); + + pkt->mode = DISC_PGP_LIST_MODE_FRIENDS; + + std::map::const_iterator it; + for(it = mFriendList.begin(); it != mFriendList.end(); it++) + { + pkt->pgpIdSet.ids.push_back(it->first); + } + + pkt->PeerId(toId); + +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::sendPGPList() sending:" << std::endl; + pkt->print(std::cerr); + std::cerr << std::endl; +#endif + + sendItem(pkt); +} + +void p3discovery2::updatePgpFriendList() +{ +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::updatePgpFriendList()"; + std::cerr << std::endl; +#endif + + RsStackMutex stack(mDiscMtx); /********** STACK LOCKED MTX ******/ + +#define PGP_MAX_UPDATE_PERIOD 300 + + if (time(NULL) < mLastPgpUpdate + PGP_MAX_UPDATE_PERIOD ) + { +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::updatePgpFriendList() Already uptodate"; + std::cerr << std::endl; +#endif + return; + } + + mLastPgpUpdate = time(NULL); + + std::list pgpList; + std::set pgpSet; + + std::set::iterator sit; + std::list::iterator lit; + std::map::iterator it; + + PGPID ownPgpId = AuthGPG::getAuthGPG()->getGPGOwnId(); + AuthGPG::getAuthGPG()->getGPGAcceptedList(pgpList); + pgpList.push_back(ownPgpId); + + // convert to set for ordering. + for(lit = pgpList.begin(); lit != pgpList.end(); lit++) + { + pgpSet.insert(*lit); + } + + std::list pgpToAdd; + std::list pgpToRemove; + + + sit = pgpSet.begin(); + it = mFriendList.begin(); + while (sit != pgpSet.end() && it != mFriendList.end()) + { + if (*sit < it->first) + { + /* to add */ + pgpToAdd.push_back(*sit); + ++sit; + } + else if (it->first < *sit) + { + /* to remove */ + pgpToRemove.push_back(it->first); + ++it; + } + else + { + /* same - okay */ + ++sit; + ++it; + } + } + + /* more to add? */ + for(; sit != pgpSet.end(); sit++) + { + pgpToAdd.push_back(*sit); + } + + for(; it != mFriendList.end(); it++) + { + /* more to remove */ + pgpToRemove.push_back(it->first); + } + + for(lit = pgpToRemove.begin(); lit != pgpToRemove.end(); lit++) + { +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::updatePgpFriendList() Removing pgpId: " << *lit; + std::cerr << std::endl; +#endif + + it = mFriendList.find(*lit); + mFriendList.erase(it); + } + + for(lit = pgpToAdd.begin(); lit != pgpToAdd.end(); lit++) + { +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::updatePgpFriendList() Adding pgpId: " << *lit; + std::cerr << std::endl; +#endif + + mFriendList[*lit] = DiscPgpInfo(); + } + + /* finally install the pgpList on our own entry */ + DiscPgpInfo &ownInfo = mFriendList[ownPgpId]; + ownInfo.mergeFriendList(pgpList); + +} + + + + +void p3discovery2::processPGPList(const SSLID &fromId, const RsDiscPgpListItem *item) +{ + RsStackMutex stack(mDiscMtx); /********** STACK LOCKED MTX ******/ + +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::processPGPList() from " << fromId; + std::cerr << std::endl; +#endif + + std::map::iterator it; + PGPID fromPgpId = getPGPId(fromId); + it = mFriendList.find(fromPgpId); + if (it == mFriendList.end()) + { +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::processPGPList() is not friend: " << fromId; + std::cerr << std::endl; +#endif + + // cleanup. + delete item; + return; + } + + bool requestUnknownPgpCerts = true; + peerState pstate; + mPeerMgr->getOwnNetStatus(pstate); + if (pstate.vs_disc != RS_VS_DISC_FULL) + { + requestUnknownPgpCerts = false; + } + + uint32_t linkType = mLinkMgr->getLinkType(fromId); + if ((linkType & RS_NET_CONN_SPEED_TRICKLE) || + (linkType & RS_NET_CONN_SPEED_LOW)) + { + std::cerr << "p3discovery2::processPGPList() Not requesting Certificates from: " << fromId; + std::cerr << " (low bandwidth)" << std::endl; + requestUnknownPgpCerts = false; + } + + if (requestUnknownPgpCerts) + { + std::list::const_iterator fit; + for(fit = item->pgpIdSet.ids.begin(); fit != item->pgpIdSet.ids.end(); fit++) + { + if (!AuthGPG::getAuthGPG()->isGPGId(*fit)) + { +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::processPGPList() requesting PgpId: " << *fit; + std::cerr << " from SslId: " << fromId; + std::cerr << std::endl; +#endif + requestPGPCertificate(*fit, fromId); + } + } + } + + it->second.mergeFriendList(item->pgpIdSet.ids); + updatePeers_locked(fromId); + + // cleanup. + delete item; +} + + +/* + * -> Update Other Peers about B. + * -> Update B about Other Peers. + */ +void p3discovery2::updatePeers_locked(const SSLID &aboutId) +{ + +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::updatePeers_locked() about " << aboutId; + std::cerr << std::endl; +#endif + + PGPID aboutPgpId = getPGPId(aboutId); + + std::map::const_iterator ait; + ait = mFriendList.find(aboutPgpId); + if (ait == mFriendList.end()) + { + +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::updatePeers_locked() PgpId is not a friend: " << aboutPgpId; + std::cerr << std::endl; +#endif + return; + } + + std::set mutualFriends; + std::set onlineFriends; + std::set::const_iterator sit; + + const std::set &friendSet = ait->second.mFriendSet; + std::set::const_iterator fit; + for(fit = friendSet.begin(); fit != friendSet.end(); fit++) + { + +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::updatePeer_locked() checking their friend: " << *fit; + std::cerr << std::endl; +#endif + + std::map::const_iterator ffit; + ffit = mFriendList.find(*fit); + if (ffit == mFriendList.end()) + { + +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::updatePeer_locked() Ignoring not our friend"; + std::cerr << std::endl; +#endif + // Not our friend, or we have no Locations (SSL) for this PGPID (same difference) + continue; + } + + if (ffit->second.mFriendSet.find(aboutPgpId) != ffit->second.mFriendSet.end()) + { + +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::updatePeer_locked() Adding as Mutual Friend"; + std::cerr << std::endl; +#endif + mutualFriends.insert(*fit); + + std::map::const_iterator mit; + for(mit = ffit->second.mSslIds.begin(); + mit != ffit->second.mSslIds.end(); mit++) + { + SSLID sslid = mit->first; + if (mLinkMgr->isOnline(sslid)) + { + // TODO IGNORE if sslid == aboutId, or sslid == ownId. +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::updatePeer_locked() Adding Online SSLID: " << sslid; + std::cerr << std::endl; +#endif + onlineFriends.insert(sslid); + } + } + } + } + +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::updatePeer_locked() Updating " << aboutId << " about Mutual Friends"; + std::cerr << std::endl; +#endif + // update aboutId about Other Peers. + for(fit = mutualFriends.begin(); fit != mutualFriends.end(); fit++) + { + sendContactInfo_locked(*fit, aboutId); + } + +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::updatePeer_locked() Updating Online Peers about " << aboutId; + std::cerr << std::endl; +#endif + // update Other Peers about aboutPgpId. + for(sit = onlineFriends.begin(); sit != onlineFriends.end(); sit++) + { + // This could be more efficient, and only be specific about aboutId. + // but we'll leave it like this for the moment. + sendContactInfo_locked(aboutPgpId, *sit); + } +} + + +void p3discovery2::sendContactInfo_locked(const PGPID &aboutId, const SSLID &toId) +{ +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::sendContactInfo_locked() aboutPGPId: " << aboutId << " toId: " << toId; + std::cerr << std::endl; +#endif + if (!(rsPeers->servicePermissionFlags_sslid(toId) & RS_SERVICE_PERM_DISCOVERY)) + { +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::sendContactInfo_locked() discovery disabled for SSLID: " << toId; + std::cerr << std::endl; +#endif + return; + } + + std::map::const_iterator it; + it = mFriendList.find(aboutId); + if (it == mFriendList.end()) + { +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::sendContactInfo_locked() ERROR aboutId is not a friend"; + std::cerr << std::endl; +#endif + return; + } + + std::map::const_iterator sit; + for(sit = it->second.mSslIds.begin(); sit != it->second.mSslIds.end(); sit++) + { +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::sendContactInfo_locked() related sslId: " << sit->first; + std::cerr << std::endl; +#endif + + if ((sit->first == rsPeers->getOwnId()) || (sit->first == toId)) + { +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::processContactInfo() not sending info on self or theirself"; + std::cerr << std::endl; +#endif + continue; + } + + if (sit->second.mDiscStatus != RS_VS_DISC_OFF) + { + peerState detail; + if (mPeerMgr->getFriendNetStatus(sit->first, detail)) + { + RsDiscContactItem *pkt = new RsDiscContactItem(); + populateContactInfo(detail, pkt); + pkt->PeerId(toId); + +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::sendContactInfo_locked() Sending"; + std::cerr << std::endl; + pkt->print(std::cerr); + std::cerr << std::endl; +#endif + sendItem(pkt); + } + else + { +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::sendContactInfo_locked() No Net Status"; + std::cerr << std::endl; +#endif + } + } + else + { +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::sendContactInfo_locked() SSLID Hidden"; + std::cerr << std::endl; +#endif + } + } +} + + +void p3discovery2::processContactInfo(const SSLID &fromId, const RsDiscContactItem *item) +{ + RsStackMutex stack(mDiscMtx); /********** STACK LOCKED MTX ******/ + + if (item->sslId == rsPeers->getOwnId()) + { +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::processContactInfo(" << fromId << ") PGPID: "; + std::cerr << item->pgpId << " Ignoring Info on self"; + std::cerr << std::endl; +#endif + return; + } + + + /* */ + std::map::iterator it; + it = mFriendList.find(item->pgpId); + if (it == mFriendList.end()) + { +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::processContactInfo(" << fromId << ") PGPID: "; + std::cerr << item->pgpId << " Not Friend."; + std::cerr << std::endl; + std::cerr << "p3discovery2::processContactInfo(" << fromId << ") THIS SHOULD NEVER HAPPEN!"; + std::cerr << std::endl; +#endif + + /* THESE ARE OUR FRIEND OF FRIENDS ... pass this information along to NetMgr & DHT... + * as we can track FOF and use them as potential Proxies / Relays + */ + + if (!item->isHidden) + { + /* add into NetMgr and non-search, so we can detect connect attempts */ + mNetMgr->netAssistFriend(item->sslId,false); + + /* inform NetMgr that we know this peer */ + mNetMgr->netAssistKnownPeer(item->sslId, item->extAddrV4.addr, + NETASSIST_KNOWN_PEER_FOF | NETASSIST_KNOWN_PEER_OFFLINE); + } + return; + } + + bool should_notify_discovery = false; + std::map::iterator sit; + sit = it->second.mSslIds.find(item->sslId); + if (sit == it->second.mSslIds.end()) + { + /* insert! */ + DiscSslInfo sslInfo; + it->second.mSslIds[item->sslId] = sslInfo; + sit = it->second.mSslIds.find(item->sslId); + + should_notify_discovery = true; + + if (!mPeerMgr->isFriend(item->sslId)) + { + // Add with no disc by default. If friend already exists, it will do nothing + // NO DISC is important - otherwise, we'll just enter a nasty loop, + // where every addition triggers requests, then they are cleaned up, and readded... + + // This way we get their addresses, but don't advertise them until we get a + // connection. +#ifdef P3DISC_DEBUG + std::cerr << "--> Adding to friends list " << item->sslId << " - " << item->pgpId << std::endl; +#endif + mPeerMgr->addFriend(item->sslId, item->pgpId, item->netMode, RS_VS_DISC_OFF, RS_VS_DHT_FULL,(time_t)0,RS_SERVICE_PERM_ALL); + updatePeerAddresses(item); + } + } + + updatePeerAddressList(item); + + + rsicontrol->getNotify().notifyListChange(NOTIFY_LIST_NEIGHBOURS, NOTIFY_TYPE_MOD); + + if(should_notify_discovery) + rsicontrol->getNotify().notifyDiscInfoChanged(); +} + + + +/* we explictly request certificates, instead of getting them all the time + */ +void p3discovery2::requestPGPCertificate(const PGPID &aboutId, const SSLID &toId) +{ +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::requestPGPCertificate() aboutId: " << aboutId << " to: " << toId; + std::cerr << std::endl; +#endif + + RsDiscPgpListItem *pkt = new RsDiscPgpListItem(); + + pkt->mode = DISC_PGP_LIST_MODE_GETCERT; + pkt->pgpIdSet.ids.push_back(aboutId); + pkt->PeerId(toId); + +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::requestPGPCertificate() sending:" << std::endl; + pkt->print(std::cerr); + std::cerr << std::endl; +#endif + + sendItem(pkt); +} + + /* comment */ +void p3discovery2::recvPGPCertificateRequest(const SSLID &fromId, const RsDiscPgpListItem *item) +{ +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::recvPPGPCertificateRequest() from " << fromId; + std::cerr << std::endl; +#endif + + std::list::const_iterator it; + for(it = item->pgpIdSet.ids.begin(); it != item->pgpIdSet.ids.end(); it++) + { + // NB: This doesn't include own certificates? why not. + // shouldn't be a real problem. Peer must have own PgpCert already. + if (AuthGPG::getAuthGPG()->isGPGAccepted(*it)) + { + sendPGPCertificate(*it, fromId); + } + } + delete item; +} + + +void p3discovery2::sendPGPCertificate(const PGPID &aboutId, const SSLID &toId) +{ + + /* for Relay Connections (and other slow ones) we don't want to + * to waste bandwidth sending certificates. So don't add it. + */ + + uint32_t linkType = mLinkMgr->getLinkType(toId); + if ((linkType & RS_NET_CONN_SPEED_TRICKLE) || + (linkType & RS_NET_CONN_SPEED_LOW)) + { + std::cerr << "p3disc::sendPGPCertificate() Not sending Certificates to: " << toId; + std::cerr << " (low bandwidth)" << std::endl; + return; + } + + RsDiscPgpCertItem *item = new RsDiscPgpCertItem(); + item->pgpId = aboutId; + item->PeerId(toId); + + +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::sendPGPCertificate() queuing for Cert generation:" << std::endl; + item->print(std::cerr); + std::cerr << std::endl; +#endif + + RsStackMutex stack(mDiscMtx); /********** STACK LOCKED MTX ******/ + /* queue it! */ + + mPendingDiscPgpCertOutList.push_back(item); +} + + +void p3discovery2::recvPGPCertificate(const SSLID &fromId, RsDiscPgpCertItem *item) +{ + +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::recvPGPCertificate() queuing for Cert loading" << std::endl; + std::cerr << std::endl; +#endif + + + /* should only happen if in FULL Mode */ + peerState pstate; + mPeerMgr->getOwnNetStatus(pstate); + if (pstate.vs_disc != RS_VS_DISC_FULL) + { +#ifdef P3DISC_DEBUG + std::cerr << "p3disc::recvPGPCertificate() Not Loading Certificates as in MINIMAL MODE"; + std::cerr << std::endl; +#endif + + delete item; + } + + RsStackMutex stack(mDiscMtx); /********** STACK LOCKED MTX ******/ + /* push this back to be processed by pgp when possible */ + + mPendingDiscPgpCertInList.push_back(item); +} + + + + + + /************* from pqiMonitor *******************/ +void p3discovery2::statusChange(const std::list &plist) +{ +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::statusChange()" << std::endl; +#endif + + std::list::const_iterator pit; + for(pit = plist.begin(); pit != plist.end(); pit++) + { + if ((pit->state & RS_PEER_S_FRIEND) && (pit->actions & RS_PEER_CONNECTED)) + { +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::statusChange() Starting Disc with: " << pit->id << std::endl; +#endif + sendOwnContactInfo(pit->id); + } + else if (!(pit->state & RS_PEER_S_FRIEND) && (pit->actions & RS_PEER_MOVED)) + { +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::statusChange() Removing Friend: " << pit->id << std::endl; +#endif + removeFriend(pit->id); + } + else if ((pit->state & RS_PEER_S_FRIEND) && (pit->actions & RS_PEER_NEW)) + { +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::statusChange() Adding Friend: " << pit->id << std::endl; +#endif + addFriend(pit->id); + } + } +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::statusChange() finished." << std::endl; +#endif + return; +} + + + + /*************************************************************************************/ + /* Extracting Network Graph Details */ + /*************************************************************************************/ +bool p3discovery2::getDiscFriends(const std::string& id, std::list &proxyIds) +{ + // This is treated appart, because otherwise we don't receive any disc info about us + if(id == rsPeers->getOwnId()) // SSL id + return rsPeers->getFriendList(proxyIds) ; + + RsStackMutex stack(mDiscMtx); /********** STACK LOCKED MTX ******/ + + std::map::const_iterator it; + PGPID pgp_id = getPGPId(id); + + it = mFriendList.find(pgp_id); + if (it == mFriendList.end()) + { + // ERROR. + return false; + } + + // For each of their friends that we know, grab that set of SSLIDs. + const std::set &friendSet = it->second.mFriendSet; + std::set::const_iterator fit; + for(fit = friendSet.begin(); fit != friendSet.end(); fit++) + { + it = mFriendList.find(*fit); + if (it == mFriendList.end()) + { + continue; + } + + std::map::const_iterator sit; + for(sit = it->second.mSslIds.begin(); + sit != it->second.mSslIds.end(); sit++) + { + proxyIds.push_back(sit->first); + } + } + return true; + +} + + +bool p3discovery2::getDiscPgpFriends(const PGPID &pgp_id, std::list &proxyPgpIds) +{ + /* find id -> and extract the neighbour_of ids */ + + if(pgp_id == rsPeers->getGPGOwnId()) // SSL id // This is treated appart, because otherwise we don't receive any disc info about us + return rsPeers->getGPGAcceptedList(proxyPgpIds) ; + + RsStackMutex stack(mDiscMtx); /********** STACK LOCKED MTX ******/ + + std::map::const_iterator it; + it = mFriendList.find(pgp_id); + if (it == mFriendList.end()) + { + // ERROR. + return false; + } + + std::set::const_iterator fit; + for(fit = it->second.mFriendSet.begin(); fit != it->second.mFriendSet.end(); fit++) + { + proxyPgpIds.push_back(*fit); + } + return true; +} + + +bool p3discovery2::getPeerVersion(const SSLID &peerId, std::string &version) +{ + RsStackMutex stack(mDiscMtx); /********** STACK LOCKED MTX ******/ + + std::map::const_iterator it; + it = mLocationMap.find(peerId); + if (it == mLocationMap.end()) + { + // MISSING. + return false; + } + + version = it->second.mVersion; + return true; +} + + +bool p3discovery2::setPeerVersion(const SSLID &peerId, const std::string &version) +{ + RsStackMutex stack(mDiscMtx); /********** STACK LOCKED MTX ******/ + + std::map::iterator it; + it = mLocationMap.find(peerId); + if (it == mLocationMap.end()) + { + mLocationMap[peerId] = DiscPeerInfo(); + it = mLocationMap.find(peerId); + } + + it->second.mVersion = version; + return true; +} + + +bool p3discovery2::getWaitingDiscCount(unsigned int *sendCount, unsigned int *recvCount) +{ + if (sendCount == NULL && recvCount == NULL) { + /* Nothing to do */ + return false; + } + + RsStackMutex stack(mDiscMtx); /********** STACK LOCKED MTX ******/ + + if (sendCount) { + *sendCount = mPendingDiscPgpCertOutList.size(); + } + + if (recvCount) { + *recvCount = mPendingDiscPgpCertInList.size(); + } + return true; +} + + + +/*************************************************************************************/ +/* AuthGPGService */ +/*************************************************************************************/ +AuthGPGOperation *p3discovery2::getGPGOperation() +{ + { + RsStackMutex stack(mDiscMtx); /********** STACK LOCKED MTX ******/ + + /* process disc reply in list */ + if (!mPendingDiscPgpCertInList.empty()) { + RsDiscPgpCertItem *item = mPendingDiscPgpCertInList.front(); + mPendingDiscPgpCertInList.pop_front(); + + return new AuthGPGOperationLoadOrSave(true, item->pgpId, item->pgpCert, item); + } + } + + { + RsStackMutex stack(mDiscMtx); /********** STACK LOCKED MTX ******/ + + /* process disc reply in list */ + if (!mPendingDiscPgpCertOutList.empty()) { + RsDiscPgpCertItem *item = mPendingDiscPgpCertOutList.front(); + mPendingDiscPgpCertOutList.pop_front(); + + return new AuthGPGOperationLoadOrSave(false, item->pgpId, "", item); + } + } + return NULL; +} + +void p3discovery2::setGPGOperation(AuthGPGOperation *operation) +{ + AuthGPGOperationLoadOrSave *loadOrSave = dynamic_cast(operation); + if (loadOrSave) + { + RsDiscPgpCertItem *item = (RsDiscPgpCertItem *) loadOrSave->m_userdata; + if (!item) + { + return; + } + + if (loadOrSave->m_load) + { + +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::setGPGOperation() Loaded Cert" << std::endl; + item->print(std::cerr, 5); + std::cerr << std::endl; +#endif + // It has already been processed by PGP. + delete item; + } + else + { + // Attaching Certificate. + item->pgpCert = loadOrSave->m_certGpg; + +#ifdef P3DISC_DEBUG + std::cerr << "p3discovery2::setGPGOperation() Sending Message:" << std::endl; + item->print(std::cerr, 5); +#endif + + // Send off message + sendItem(item); + } + return; + } + + /* ignore other operations */ +} + + + +#if 0 +/***************************************************************************************/ +/***************************************************************************************/ +/************** OLD CODE ***************************/ +/***************************************************************************************/ +/***************************************************************************************/ + #include "retroshare/rsiface.h" #include "retroshare/rspeers.h" @@ -496,8 +1759,8 @@ RsDiscReply *p3disc::createDiscReply(const std::string &to, const std::string &a rsPeerNetItem.netMode = detail.netMode; rsPeerNetItem.visState = detail.visState; rsPeerNetItem.lastContact = detail.lastcontact; - rsPeerNetItem.localAddr.addr = detail.localaddr; - rsPeerNetItem.extAddr.addr = detail.serveraddr; + rsPeerNetItem.currentlocaladdr = detail.localaddr; + rsPeerNetItem.currentremoteaddr = detail.serveraddr; rsPeerNetItem.dyndns = detail.dyndns; detail.ipAddrs.mLocal.loadTlv(rsPeerNetItem.localAddrList); detail.ipAddrs.mExt.loadTlv(rsPeerNetItem.extAddrList); @@ -526,8 +1789,8 @@ RsDiscReply *p3disc::createDiscReply(const std::string &to, const std::string &a rsPeerNetItem.netMode = detail.netMode; rsPeerNetItem.visState = detail.visState; rsPeerNetItem.lastContact = time(NULL); - rsPeerNetItem.localAddr.addr = detail.localaddr; - rsPeerNetItem.extAddr.addr = detail.serveraddr; + rsPeerNetItem.currentlocaladdr = detail.localaddr; + rsPeerNetItem.currentremoteaddr = detail.serveraddr; rsPeerNetItem.dyndns = detail.dyndns; detail.ipAddrs.mLocal.loadTlv(rsPeerNetItem.localAddrList); detail.ipAddrs.mExt.loadTlv(rsPeerNetItem.extAddrList); @@ -677,7 +1940,7 @@ void p3disc::recvPeerDetails(RsDiscReply *item, const std::string &certGpgId) bool new_info = false; addDiscoveryData(item->PeerId(), pit->pid,item_gpg_id, - item->aboutId, pit->localAddr.addr, pit->extAddr.addr, 0, time(NULL),new_info); + item->aboutId, pit->currentlocaladdr, pit->currentremoteaddr, 0, time(NULL),new_info); if(new_info) should_notify_discovery = true ; @@ -724,7 +1987,7 @@ void p3disc::recvPeerDetails(RsDiscReply *item, const std::string &certGpgId) mNetMgr->netAssistFriend(pit->pid,false); /* inform NetMgr that we know this peer */ - mNetMgr->netAssistKnownPeer(pit->pid, pit->extAddr.addr, + mNetMgr->netAssistKnownPeer(pit->pid, pit->currentremoteaddr, NETASSIST_KNOWN_PEER_FOF | NETASSIST_KNOWN_PEER_OFFLINE); continue; @@ -752,10 +2015,10 @@ void p3disc::recvPeerDetails(RsDiscReply *item, const std::string &certGpgId) if (mPeerMgr->setLocation(pit->pid, pit->location)) { peerDataChanged = true; } - if (mPeerMgr->setLocalAddress(pit->pid, pit->localAddr.addr)) { + if (mPeerMgr->setLocalAddress(pit->pid, pit->currentlocaladdr)) { peerDataChanged = true; } - if (mPeerMgr->setExtAddress(pit->pid, pit->extAddr.addr)) { + if (mPeerMgr->setExtAddress(pit->pid, pit->currentremoteaddr)) { peerDataChanged = true; } if (mPeerMgr->setVisState(pit->pid, pit->visState)) { @@ -1024,7 +2287,7 @@ void p3disc::setGPGOperation(AuthGPGOperation *operation) /*************************************************************************************/ /* Storing Network Graph */ /*************************************************************************************/ -int p3disc::addDiscoveryData(const std::string& fromId, const std::string& aboutId,const std::string& from_gpg_id,const std::string& about_gpg_id, const struct sockaddr_storage &laddr, const struct sockaddr_storage &raddr, uint32_t flags, time_t ts,bool& new_info) +int p3disc::addDiscoveryData(const std::string& fromId, const std::string& aboutId,const std::string& from_gpg_id,const std::string& about_gpg_id, const struct sockaddr_in& laddr, const struct sockaddr_in& raddr, uint32_t flags, time_t ts,bool& new_info) { RsStackMutex stack(mDiscMtx); /********** STACK LOCKED MTX ******/ @@ -1242,82 +2505,4 @@ int p3disc::idServers() // return (int) (pow(10.0, trange) - 1.5); // (int) xxx98.5 -> xxx98 //} -// -----------------------------------------------------------------------------------// -// -------------------------------- Config functions ------------------------------ // -// -----------------------------------------------------------------------------------// -// -RsSerialiser *p3disc::setupSerialiser() -{ - RsSerialiser *rss = new RsSerialiser ; - rss->addSerialType(new RsGeneralConfigSerialiser()); - return rss ; -} - -bool p3disc::saveList(bool& cleanup, std::list& /*lst*/) -{ - #ifdef P3DISC_DEBUG - std::cerr << "p3disc::saveList() called" << std::endl; - #endif - cleanup = true ; - -// DON'T KNOW WHY SSL IDS were saved -> the results are never used -#if 0 - // Now save config for network digging strategies - RsConfigKeyValueSet *vitem = new RsConfigKeyValueSet ; - std::map::iterator mapIt; - for (mapIt = deletedSSLFriendsIds.begin(); mapIt != deletedSSLFriendsIds.end(); mapIt++) - { - RsTlvKeyValue kv; - kv.key = mapIt->first; - rs_sprintf(kv.value, "%ld", mapIt->second); - vitem->tlvkvs.pairs.push_back(kv) ; - #ifdef P3DISC_DEBUG - std::cerr << "p3disc::saveList() saving : " << mapIt->first << " ; " << mapIt->second << std::endl ; - #endif - } - lst.push_back(vitem); -#endif - - return true ; -} - -bool p3disc::loadList(std::list& load) -{ - #ifdef P3DISC_DEBUG - std::cerr << "p3disc::loadList() Item Count: " << load.size() << std::endl; - #endif - - - RsStackMutex stack(mDiscMtx); /****** STACK LOCK MUTEX *******/ - - /* load the list of accepted gpg keys */ - std::list::iterator it; - for(it = load.begin(); it != load.end(); it++) - { -// DON'T KNOW WHY SSL IDS were saved -> the results are never used -#if 0 - RsConfigKeyValueSet *vitem = dynamic_cast(*it); - - if(vitem) - { - #ifdef P3DISC_DEBUG - std::cerr << "p3disc::loadList() General Variable Config Item:" << std::endl; - vitem->print(std::cerr, 10); - std::cerr << std::endl; - #endif - - std::list::iterator kit; - for(kit = vitem->tlvkvs.pairs.begin(); kit != vitem->tlvkvs.pairs.end(); kit++) - { - std::istringstream instream(kit->value); // please do not use std::istringstream - time_t deleted_time_t; - instream >> deleted_time_t; - deletedSSLFriendsIds[kit->key] = deleted_time_t; - } - } -#endif - - delete (*it); - } - return true; -} +#endif // #if 0 diff --git a/libretroshare/src/services/p3discovery2.h b/libretroshare/src/services/p3discovery2.h new file mode 100644 index 000000000..2b3984890 --- /dev/null +++ b/libretroshare/src/services/p3discovery2.h @@ -0,0 +1,151 @@ +/* + * libretroshare/src/services: p3discovery2.h + * + * Services for RetroShare. + * + * Copyright 2004-2013 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.1 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_SERVICES_DISCOVERY2_H +#define MRK_SERVICES_DISCOVERY2_H + +// Discovery2: Improved discovery service. + +#include "retroshare/rsdisc.h" + +#include "pqi/p3peermgr.h" +#include "pqi/p3linkmgr.h" +#include "pqi/p3netmgr.h" + +#include "pqi/pqimonitor.h" +#include "serialiser/rsdiscovery2items.h" +#include "services/p3service.h" +#include "pqi/authgpg.h" + + + +typedef std::string PGPID; +typedef std::string SSLID; + +class DiscSslInfo +{ + public: + DiscSslInfo() { mDiscStatus = 0; } + uint16_t mDiscStatus; +}; + +class DiscPeerInfo +{ + public: + DiscPeerInfo() {} + + std::string mVersion; + //uint32_t mStatus; +}; + +class DiscPgpInfo +{ + public: + DiscPgpInfo() {} + +void mergeFriendList(const std::list &friends); + + //PGPID mPgpId; + std::set mFriendSet; + std::map mSslIds; +}; + + + +class p3discovery2: public RsDisc, public p3Service, public pqiMonitor, public AuthGPGService +{ + public: + + p3discovery2(p3PeerMgr *peerMgr, p3LinkMgr *linkMgr, p3NetMgr *netMgr); +virtual ~p3discovery2(); + + /************* from pqiMonitor *******************/ + virtual void statusChange(const std::list &plist); + /************* from pqiMonitor *******************/ + + int tick(); + + /* external interface */ +virtual bool getDiscFriends(const std::string &id, std::list &friends); +virtual bool getDiscPgpFriends(const std::string &pgpid, std::list &gpg_friends); +virtual bool getPeerVersion(const std::string &id, std::string &version); +virtual bool getWaitingDiscCount(unsigned int *sendCount, unsigned int *recvCount); + + /************* from AuthGPService ****************/ +virtual AuthGPGOperation *getGPGOperation(); +virtual void setGPGOperation(AuthGPGOperation *operation); + + + private: + + PGPID getPGPId(const SSLID &id); + + int handleIncoming(); + void updatePgpFriendList(); + + void addFriend(const SSLID &sslId); + void removeFriend(const SSLID &sslId); + + void updatePeerAddresses(const RsDiscContactItem *item); + void updatePeerAddressList(const RsDiscContactItem *item); + + void sendOwnContactInfo(const SSLID &sslid); + void recvOwnContactInfo(const SSLID &fromId, const RsDiscContactItem *item); + + void sendPGPList(const SSLID &toId); + void processPGPList(const SSLID &fromId, const RsDiscPgpListItem *item); + + void processContactInfo(const SSLID &fromId, const RsDiscContactItem *info); + + void requestPGPCertificate(const PGPID &aboutId, const SSLID &toId); + void recvPGPCertificateRequest(const SSLID &fromId, const RsDiscPgpListItem *item); + void sendPGPCertificate(const PGPID &aboutId, const SSLID &toId); + void recvPGPCertificate(const SSLID &fromId, RsDiscPgpCertItem *item); + + bool setPeerVersion(const SSLID &peerId, const std::string &version); + + private: + + p3PeerMgr *mPeerMgr; + p3LinkMgr *mLinkMgr; + p3NetMgr *mNetMgr; + + /* data */ + RsMutex mDiscMtx; + + void updatePeers_locked(const SSLID &aboutId); + void sendContactInfo_locked(const PGPID &aboutId, const SSLID &toId); + + time_t mLastPgpUpdate; + + std::map mFriendList; + std::map mLocationMap; + + std::list mPendingDiscPgpCertInList; + std::list mPendingDiscPgpCertOutList; +}; + + +#endif // MRK_SERVICES_DISCOVERY2_H diff --git a/libretroshare/src/services/p3heartbeat.cc b/libretroshare/src/services/p3heartbeat.cc new file mode 100644 index 000000000..b431fdae7 --- /dev/null +++ b/libretroshare/src/services/p3heartbeat.cc @@ -0,0 +1,122 @@ +/* + * libretroshare/src/services: p3heartbeat.cc + * + * Services for RetroShare. + * + * Copyright 2004-2013 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.1 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/p3heartbeat.h" +#include "serialiser/rsheartbeatitems.h" + +#define HEART_DEBUG 1 + + +p3heartbeat::p3heartbeat(p3LinkMgr *linkMgr, pqipersongrp *pqipg) +:p3Service(RS_SERVICE_TYPE_HEARTBEAT), mLinkMgr(linkMgr), mPqiPersonGrp(pqipg), + mHeartMtx("p3heartbeat") +{ + RsStackMutex stack(mHeartMtx); /********** STACK LOCKED MTX ******/ + + addSerialType(new RsHeartbeatSerialiser()); + +#ifdef HEART_DEBUG + std::cerr << "p3heartbeat::p3heartbeat()"; + std::cerr << std::endl; +#endif + + mLastHeartbeat = 0; + + return; +} + +p3heartbeat::~p3heartbeat() +{ + return; + +} + +int p3heartbeat::tick() +{ + //send a heartbeat to all connected peers + RsStackMutex stack(mHeartMtx); /********** STACK LOCKED MTX ******/ + + if (time(NULL) - mLastHeartbeat > HEARTBEAT_REPEAT_TIME) + { + mLastHeartbeat = time(NULL); + + std::list peers; + std::list::const_iterator pit; + + mLinkMgr->getOnlineList(peers); + for (pit = peers.begin(); pit != peers.end(); ++pit) + { + sendHeartbeat(*pit); + } + } + + int nhandled = 0; + RsItem *item = NULL; + + // While messages read + while(NULL != (item = recvItem())) + { + RsHeartbeatItem *beat = NULL; + nhandled++; + + // if discovery reply then respond if haven't already. + if (NULL != (beat = dynamic_cast (item))) + { + recvHeartbeat(beat->PeerId()); + } + else + { + // unknown. + } + + delete item; + } +} + +void p3heartbeat::sendHeartbeat(const std::string &toId) +{ + +#ifdef HEART_DEBUG + std::cerr << "p3heartbeat::sendHeartbeat() to " << toId; + std::cerr << std::endl; +#endif + RsHeartbeatItem *item = new RsHeartbeatItem(); + item->PeerId(toId); + sendItem(item); +} + + +void p3heartbeat::recvHeartbeat(const std::string &fromId) +{ + +#ifdef HEART_DEBUG + std::cerr << "p3heartbeat::recvHeartbeat() from " << fromId; + std::cerr << std::endl; +#endif + + mPqiPersonGrp->tagHeartbeatRecvd(fromId); +} + + diff --git a/libretroshare/src/services/p3heartbeat.h b/libretroshare/src/services/p3heartbeat.h new file mode 100644 index 000000000..1f686a73f --- /dev/null +++ b/libretroshare/src/services/p3heartbeat.h @@ -0,0 +1,61 @@ +/* + * libretroshare/src/services: p3heartbeat.h + * + * Services for RetroShare. + * + * Copyright 2004-2013 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.1 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_SERVICES_HEARTBEAT_H +#define MRK_SERVICES_HEARTBEAT_H + +// Moved Heartbeat to a seperate service. + +#include "pqi/p3linkmgr.h" +#include "pqi/pqipersongrp.h" +#include "services/p3service.h" + + +class p3heartbeat: public p3Service +{ + public: + + p3heartbeat(p3LinkMgr *linkMgr, pqipersongrp *pqipg); +virtual ~p3heartbeat(); + + int tick(); + + private: + + void sendHeartbeat(const std::string &toId); + void recvHeartbeat(const std::string &fromId); + + private: + + p3LinkMgr *mLinkMgr; + pqipersongrp *mPqiPersonGrp; + + /* data */ + RsMutex mHeartMtx; + + time_t mLastHeartbeat; +}; + +#endif // MRK_SERVICES_HEARTBEAT_H diff --git a/libretroshare/src/services/p3posted.cc b/libretroshare/src/services/p3posted.cc index b6afe5e2d..2f74fb554 100644 --- a/libretroshare/src/services/p3posted.cc +++ b/libretroshare/src/services/p3posted.cc @@ -560,7 +560,7 @@ bool p3Posted::generatePost(uint32_t &token, const RsGxsGroupId &grpId) uint32_t idx = (uint32_t) (ownIds.size() * RSRandom::random_f32()); uint32_t i = 0; - for(it = ownIds.begin(); (it != ownIds.end()) && (i < idx); it++, i++); + for(it = ownIds.begin(); (it != ownIds.end()) && (i < idx); it++, i++) ; if (it != ownIds.end()) { @@ -605,7 +605,7 @@ bool p3Posted::generateComment(uint32_t &token, const RsGxsGroupId &grpId, const uint32_t idx = (uint32_t) (ownIds.size() * RSRandom::random_f32()); uint32_t i = 0; - for(it = ownIds.begin(); (it != ownIds.end()) && (i < idx); it++, i++); + for(it = ownIds.begin(); (it != ownIds.end()) && (i < idx); it++, i++) ; if (it != ownIds.end()) { diff --git a/libretroshare/src/util/rsnet_ss.cc b/libretroshare/src/util/rsnet_ss.cc index ed4f188eb..4eb343a1a 100644 --- a/libretroshare/src/util/rsnet_ss.cc +++ b/libretroshare/src/util/rsnet_ss.cc @@ -25,6 +25,7 @@ #include "util/rsnet.h" #include "util/rsstring.h" +#include "pqi/pqinetwork.h" /***************************** Internal Helper Fns ******************************/ @@ -173,8 +174,10 @@ bool sockaddr_storage_copyip(struct sockaddr_storage &dst, const struct sockaddr uint16_t sockaddr_storage_port(const struct sockaddr_storage &addr) { +#ifdef SS_DEBUG std::cerr << "sockaddr_storage_port()"; std::cerr << std::endl; +#endif switch(addr.ss_family) { case AF_INET: @@ -629,8 +632,10 @@ bool sockaddr_storage_ipv4_copyip(struct sockaddr_storage &dst, const struct soc uint16_t sockaddr_storage_ipv4_port(const struct sockaddr_storage &addr) { +#ifdef SS_DEBUG std::cerr << "sockaddr_storage_ipv4_port()"; std::cerr << std::endl; +#endif const struct sockaddr_in *ipv4_ptr = to_const_ipv4_ptr(addr); uint16_t port = ntohs(ipv4_ptr->sin_port); @@ -740,7 +745,10 @@ bool sockaddr_storage_ipv4_samenet(const struct sockaddr_storage &addr, const st std::cerr << "sockaddr_storage_ipv4_samenet()"; std::cerr << std::endl; - return false; + + const struct sockaddr_in *ptr1 = to_const_ipv4_ptr(addr); + const struct sockaddr_in *ptr2 = to_const_ipv4_ptr(addr2); + return sameNet(&(ptr1->sin_addr),&(ptr2->sin_addr)); } bool sockaddr_storage_ipv4_samesubnet(const struct sockaddr_storage &addr, const struct sockaddr_storage &addr2) @@ -748,10 +756,12 @@ bool sockaddr_storage_ipv4_samesubnet(const struct sockaddr_storage &addr, const (void) addr; (void) addr2; - std::cerr << "sockaddr_storage_ipv4_samesubnet()"; + std::cerr << "sockaddr_storage_ipv4_samesubnet() using pqinetwork::isSameSubnet()"; std::cerr << std::endl; - return false; + const struct sockaddr_in *ptr1 = to_const_ipv4_ptr(addr); + const struct sockaddr_in *ptr2 = to_const_ipv4_ptr(addr2); + return isSameSubnet((struct in_addr *) &(ptr1->sin_addr),(struct in_addr *) &(ptr2->sin_addr)); } // IPV6 diff --git a/libretroshare/src/zeroconf/p3zeroconf.cc b/libretroshare/src/zeroconf/p3zeroconf.cc index 34cd22105..31d6368fa 100644 --- a/libretroshare/src/zeroconf/p3zeroconf.cc +++ b/libretroshare/src/zeroconf/p3zeroconf.cc @@ -500,7 +500,7 @@ int p3ZeroConf::checkLocationResults() std::cerr << std::endl; time_t now = time(NULL); - mPeerMgr->addFriend(lr.sslId, lr.gpgId, RS_NET_MODE_UDP, RS_VIS_STATE_STD, now); + mPeerMgr->addFriend(lr.sslId, lr.gpgId, RS_NET_MODE_UDP, RS_VS_DISC_FULL, RS_VS_DHT_FULL, now); return 1; } From ba157e4891e3a88338d7718c8f47f8b026447de0 Mon Sep 17 00:00:00 2001 From: drbob Date: Sun, 29 Sep 2013 07:10:19 +0000 Subject: [PATCH 20/83] Fixes for visState -> vs_disc & vs_dht. Added RTT Gui. git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@6775 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- retroshare-gui/src/gui/AboutDialog.cpp | 58 +-- .../src/gui/FileTransfer/TransfersDialog.cpp | 23 +- .../src/gui/FileTransfer/TransfersDialog.h | 2 +- retroshare-gui/src/gui/GetStartedDialog.cpp | 10 +- retroshare-gui/src/gui/NetworkDialog.cpp | 9 +- retroshare-gui/src/gui/NetworkView.cpp | 4 +- retroshare-gui/src/gui/QuickStartWizard.cpp | 106 ++--- retroshare-gui/src/gui/RttStatistics.cpp | 379 ++++++++++++++++++ retroshare-gui/src/gui/RttStatistics.h | 68 ++++ retroshare-gui/src/gui/RttStatistics.ui | 55 +++ .../src/gui/connect/ConfCertDialog.cpp | 8 +- .../src/gui/profile/ProfileWidget.cpp | 10 +- .../src/gui/settings/CryptoPage.cpp | 10 +- .../src/gui/settings/ServerPage.cpp | 24 +- retroshare-gui/src/retroshare-gui.pro | 12 +- 15 files changed, 644 insertions(+), 134 deletions(-) create mode 100644 retroshare-gui/src/gui/RttStatistics.cpp create mode 100644 retroshare-gui/src/gui/RttStatistics.h create mode 100644 retroshare-gui/src/gui/RttStatistics.ui diff --git a/retroshare-gui/src/gui/AboutDialog.cpp b/retroshare-gui/src/gui/AboutDialog.cpp index 8bd0ad504..2017866b0 100644 --- a/retroshare-gui/src/gui/AboutDialog.cpp +++ b/retroshare-gui/src/gui/AboutDialog.cpp @@ -50,15 +50,15 @@ AboutDialog::AboutDialog(QWidget* parent) tWidget = NULL; installAWidget(); + QString title = tr("About RetroShare "); + /* get libretroshare version */ - std::map::iterator vit; - std::map versions; - bool retv = rsDisc->getDiscVersions(versions); - if (retv && versions.end() != (vit = versions.find(rsPeers->getOwnId()))) + std::string version; + if (rsDisc->getPeerVersion(rsPeers->getOwnId(), version)) { - QString version = QString::fromStdString(vit->second); - setWindowTitle(tr("About RetroShare %1").arg(version)); + title += QString::fromStdString(version); } + setWindowTitle(title); #ifdef Q_OS_WIN setWindowFlags(windowFlags() | Qt::MSWindowsFixedSizeDialogHint); @@ -134,20 +134,20 @@ void AboutDialog::sl_levelChanged(int level) { void AboutDialog::updateTitle() { - if (tWidget == NULL) { - - /* get libretroshare version */ - std::map::iterator vit; - std::map versions; - bool retv = rsDisc->getDiscVersions(versions); - if (retv && versions.end() != (vit = versions.find(rsPeers->getOwnId()))) - { - - QString version = QString::fromStdString(vit->second); - setWindowTitle(tr("About RetroShare %1").arg(version)); - - } - } else { + if (tWidget == NULL) + { + QString title = tr("About RetroShare "); + + /* get libretroshare version */ + std::string version; + if (rsDisc->getPeerVersion(rsPeers->getOwnId(), version)) + { + title += QString::fromStdString(version); + } + setWindowTitle(title); + } + else + { setWindowTitle(tr("Have fun ;-)")); } } @@ -183,18 +183,18 @@ AWidget::AWidget() { QPainter p(&image); p.setPen(Qt::lightGray); - /* get libretroshare version */ - std::map::iterator vit; - std::map versions; - bool retv = rsDisc->getDiscVersions(versions); - if (retv && versions.end() != (vit = versions.find(rsPeers->getOwnId()))) + QString title = tr("About RetroShare "); + + /* get libretroshare version */ + std::string version; + if (rsDisc->getPeerVersion(rsPeers->getOwnId(), version)) { - QString version = QString::fromStdString("RetroShare version : \n") + QString::fromStdString(vit->second); - p.drawText(QRect(10, 10, width()-10, 60), version); - + QString versionq = QString::fromStdString("RetroShare version : \n") + QString::fromStdString(version); + p.drawText(QRect(10, 10, width()-10, 60), versionq); + } p.end(); - + image1 = image2 = image; setFixedSize(image1.size()); diff --git a/retroshare-gui/src/gui/FileTransfer/TransfersDialog.cpp b/retroshare-gui/src/gui/FileTransfer/TransfersDialog.cpp index 869b98a8f..8551d94d5 100644 --- a/retroshare-gui/src/gui/FileTransfer/TransfersDialog.cpp +++ b/retroshare-gui/src/gui/FileTransfer/TransfersDialog.cpp @@ -62,9 +62,10 @@ /**** * #define SHOW_RTT_STATISTICS 1 ****/ +#define SHOW_RTT_STATISTICS 1 #ifdef SHOW_RTT_STATISTICS - #include "VoipStatistics.h" + #include "RttStatistics.h" #endif /* Images for context menu icons */ @@ -333,6 +334,10 @@ TransfersDialog::TransfersDialog(QWidget *parent) ui.tabWidget->addTab(localSharedFiles = new LocalSharedFilesDialog(), QIcon(IMAGE_MYFILES), tr("My files")) ; +#ifdef SHOW_RTT_STATISTICS + ui.tabWidget->addTab( new RttStatistics(), tr("RTT Statistics")) ; +#endif + //ui.tabWidget->addTab( new TurtleRouterStatistics(), tr("Router Statistics")) ; //ui.tabWidget->addTab( new TurtleRouterDialog(), tr("Router Requests")) ; @@ -899,7 +904,7 @@ void TransfersDialog::setDestinationDirectory() } } -int TransfersDialog::addItem(int row, const FileInfo &fileInfo, const std::map &versions) +int TransfersDialog::addItem(int row, const FileInfo &fileInfo) { QString fileHash = QString::fromStdString(fileInfo.hash); double fileDlspeed = (fileInfo.downloadStatus == FT_STATE_DOWNLOADING) ? (fileInfo.tfRate * 1024.0) : 0.0; @@ -1026,8 +1031,10 @@ int TransfersDialog::addItem(int row, const FileInfo &fileInfo, const std::mapsecond); + std::string rsversion; + if (rsDisc->getPeerVersion(transferInfo.peerId, rsversion)) + { + version = tr("version: ") + QString::fromStdString(rsversion); } double peerDlspeed = 0; @@ -1222,10 +1229,6 @@ void TransfersDialog::insertTransfers() std::list downHashes; rsFiles->FileDownloads(downHashes); - /* get only once */ - std::map versions; - rsDisc->getDiscVersions(versions); - /* build set for quick search */ std::set hashs; std::list::iterator it; @@ -1266,7 +1269,7 @@ void TransfersDialog::insertTransfers() hashs.erase(hashIt); - if (addItem(row, fileInfo, versions) < 0) { + if (addItem(row, fileInfo) < 0) { DLListModel->removeRow(row); rowCount = DLListModel->rowCount(); continue; @@ -1288,7 +1291,7 @@ void TransfersDialog::insertTransfers() continue; } - addItem(-1, fileInfo, versions); + addItem(-1, fileInfo); } ui.downloadList->setSortingEnabled(true); diff --git a/retroshare-gui/src/gui/FileTransfer/TransfersDialog.h b/retroshare-gui/src/gui/FileTransfer/TransfersDialog.h index 9b5fd0c28..e349da4b0 100644 --- a/retroshare-gui/src/gui/FileTransfer/TransfersDialog.h +++ b/retroshare-gui/src/gui/FileTransfer/TransfersDialog.h @@ -236,7 +236,7 @@ private: public slots: // these two functions add entries to the transfers dialog, and return the row id of the entry modified/added // - int addItem(int row, const FileInfo &fileInfo, const std::map &versions); + int addItem(int row, const FileInfo &fileInfo); int addPeerToItem(QStandardItem *dlItem, const QString& name, const QString& coreID, double dlspeed, uint32_t status, const FileProgressInfo& peerInfo); int addUploadItem(const QString& symbol, const QString& name, const QString& coreID, qlonglong size, const FileProgressInfo& pinfo, double dlspeed, const QString& sources,const QString& source_id, const QString& status, qlonglong completed, qlonglong remaining); diff --git a/retroshare-gui/src/gui/GetStartedDialog.cpp b/retroshare-gui/src/gui/GetStartedDialog.cpp index d6115196a..0598a9b77 100644 --- a/retroshare-gui/src/gui/GetStartedDialog.cpp +++ b/retroshare-gui/src/gui/GetStartedDialog.cpp @@ -335,15 +335,7 @@ void GetStartedDialog::emailSupport() { RsAutoUpdatePage::lockAllEvents(); - /* set retroshare version */ - std::map::iterator vit; - std::map versions; - bool retv = rsDisc->getDiscVersions(versions); - std::string id = rsPeers->getOwnId(); - if (retv && versions.end() != (vit = versions.find(id))) - { - versionString = vit->second; - } + rsDisc->getPeerVersion(rsPeers->getOwnId(), versionString); userLevel = rsConfig->getUserLevel(); RsAutoUpdatePage::unlockAllEvents() ; diff --git a/retroshare-gui/src/gui/NetworkDialog.cpp b/retroshare-gui/src/gui/NetworkDialog.cpp index a0ac14763..6256bbac8 100644 --- a/retroshare-gui/src/gui/NetworkDialog.cpp +++ b/retroshare-gui/src/gui/NetworkDialog.cpp @@ -121,11 +121,10 @@ NetworkDialog::NetworkDialog(QWidget *parent) ui.onlyTrustedKeys->setMinimumWidth(20); QString version = "-"; - std::map::iterator vit; - std::map versions; - bool retv = rsDisc->getDiscVersions(versions); - if (retv && versions.end() != (vit = versions.find(rsPeers->getOwnId()))) { - version = QString::fromStdString(vit->second); + std::string rsversion; + if (rsDisc->getPeerVersion(rsPeers->getOwnId(), rsversion)) + { + version = QString::fromStdString(rsversion); } QMenu *menu = new QMenu(); diff --git a/retroshare-gui/src/gui/NetworkView.cpp b/retroshare-gui/src/gui/NetworkView.cpp index ba2708978..a72bd009b 100644 --- a/retroshare-gui/src/gui/NetworkView.cpp +++ b/retroshare-gui/src/gui/NetworkView.cpp @@ -176,7 +176,7 @@ void NetworkView::updateDisplay() } std::list friendList; - rsDisc->getDiscGPGFriends(info.gpg_id, friendList); + rsDisc->getDiscPgpFriends(info.gpg_id, friendList); #ifdef DEBUG_NETWORKVIEW std::cerr << " Got a list of " << friendList.size() << " friends for this peer." << std::endl ; @@ -204,7 +204,7 @@ void NetworkView::updateDisplay() { std::list friendList ; - if(rsDisc->getDiscGPGFriends(it->first,friendList)) + if(rsDisc->getDiscPgpFriends(it->first,friendList)) for(std::list::const_iterator sit(friendList.begin()); sit != friendList.end(); sit++) { #ifdef DEBUG_NETWORKVIEW diff --git a/retroshare-gui/src/gui/QuickStartWizard.cpp b/retroshare-gui/src/gui/QuickStartWizard.cpp index 6d832f65e..8215e2ab1 100644 --- a/retroshare-gui/src/gui/QuickStartWizard.cpp +++ b/retroshare-gui/src/gui/QuickStartWizard.cpp @@ -123,32 +123,40 @@ void QuickStartWizard::on_pushButtonConnectionNext_clicked() rsPeers->setNetworkMode(rsPeers->getOwnId(), netMode); /* Check if vis has changed */ - uint32_t visState = 0; - switch(ui.discoveryComboBox->currentIndex()) - { - case 0: - visState |= (RS_VS_DISC_ON | RS_VS_DHT_ON); - break; - case 1: - visState |= RS_VS_DISC_ON; - break; - case 2: - visState |= RS_VS_DHT_ON; - break; - case 3: - default: - break; - } + uint16_t vs_disc = 0; + uint16_t vs_dht = 0; + switch(ui.discoveryComboBox->currentIndex()) + { + case 0: + vs_disc = RS_VS_DISC_FULL; + vs_dht = RS_VS_DHT_FULL; + break; + case 1: + vs_disc = RS_VS_DISC_FULL; + vs_dht = RS_VS_DHT_OFF; + break; + case 2: + vs_disc = RS_VS_DISC_OFF; + vs_dht = RS_VS_DHT_FULL; + break; + case 3: + default: + vs_disc = RS_VS_DISC_OFF; + vs_dht = RS_VS_DHT_OFF; + break; + } + RsPeerDetails detail; if (!rsPeers->getPeerDetails(rsPeers->getOwnId(), detail)) { return; } - if (visState != detail.visState) - { - rsPeers->setVisState(rsPeers->getOwnId(), visState); - } + if ((vs_disc != detail.vs_disc) || (vs_dht != detail.vs_dht)) + { + rsPeers->setVisState(rsPeers->getOwnId(), vs_disc, vs_dht); + } + rsConfig->SetMaxDataRates( ui.doubleSpinBoxDownloadSpeed->value(), ui.doubleSpinBoxUploadSpeed->value() ); ui.pagesWizard->setCurrentIndex(2); @@ -425,9 +433,9 @@ void QuickStartWizard::loadNetwork() */ netIndex = 3; // NONE. - if (detail.visState & RS_VS_DHT_ON) + if (detail.vs_dht != RS_VS_DISC_OFF) { - if (detail.visState & RS_VS_DISC_ON) + if (detail.vs_disc != RS_VS_DISC_OFF) { netIndex = 0; // PUBLIC } @@ -438,7 +446,7 @@ void QuickStartWizard::loadNetwork() } else { - if (detail.visState & RS_VS_DISC_ON) + if (detail.vs_disc != RS_VS_DISC_OFF) { netIndex = 1; // PRIVATE } @@ -450,7 +458,7 @@ void QuickStartWizard::loadNetwork() ui.discoveryComboBox->setCurrentIndex(netIndex); - int dlrate = 0; + int dlrate = 0; int ulrate = 0; rsConfig->GetMaxDataRates(dlrate, ulrate); ui.doubleSpinBoxDownloadSpeed->setValue(dlrate); @@ -494,28 +502,34 @@ void QuickStartWizard::saveChanges() rsPeers->setNetworkMode(ownId, netMode); - uint32_t visState = 0; - /* Check if vis has changed */ - switch(ui.discoveryComboBox->currentIndex()) - { - case 0: - visState |= (RS_VS_DISC_ON | RS_VS_DHT_ON); - break; - case 1: - visState |= RS_VS_DISC_ON; - break; - case 2: - visState |= RS_VS_DHT_ON; - break; - case 3: - default: - break; - } - - if (visState != detail.visState) - { - rsPeers->setVisState(ownId, visState); - } + /* Check if vis has changed */ + uint16_t vs_disc = 0; + uint16_t vs_dht = 0; + switch(ui.discoveryComboBox->currentIndex()) + { + case 0: + vs_disc = RS_VS_DISC_FULL; + vs_dht = RS_VS_DHT_FULL; + break; + case 1: + vs_disc = RS_VS_DISC_FULL; + vs_dht = RS_VS_DHT_OFF; + break; + case 2: + vs_disc = RS_VS_DISC_OFF; + vs_dht = RS_VS_DHT_FULL; + break; + case 3: + default: + vs_disc = RS_VS_DISC_OFF; + vs_dht = RS_VS_DHT_OFF; + break; + } + + if ((vs_disc != detail.vs_disc) || (vs_dht != detail.vs_dht)) + { + rsPeers->setVisState(ownId, vs_disc, vs_dht); + } /*if (0 != netIndex) { diff --git a/retroshare-gui/src/gui/RttStatistics.cpp b/retroshare-gui/src/gui/RttStatistics.cpp new file mode 100644 index 000000000..3aca89989 --- /dev/null +++ b/retroshare-gui/src/gui/RttStatistics.cpp @@ -0,0 +1,379 @@ +/**************************************************************** + * RetroShare is distributed under the following license: + * + * Copyright (C) 20011, RetroShare Team + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + ****************************************************************/ + +#include +#include +#include + +#include +#include + +#include +#include +#include "RttStatistics.h" +#include "time.h" + +#include "gui/settings/rsharesettings.h" + +#define PLOT_HEIGHT 100 +#define PLOT_WIDTH 500 + +#define MAX_DISPLAY_PERIOD 300 + +double convertDtToPixels(double refTs, double minTs, double ts) +{ + double dt = refTs - ts; + double maxdt = refTs - minTs; + double pix = PLOT_WIDTH - dt / maxdt * PLOT_WIDTH; + return pix; +} + + +double convertRttToPixels(double maxRTT, double rtt) +{ + double pix = rtt / maxRTT * PLOT_HEIGHT; + return PLOT_HEIGHT - pix; +} + +class RttPlot +{ + public: + RttPlot(const std::map > &info, + double refTS, double maxRTT, double minTS, double maxTS) + :mInfo(info), mRefTS(refTS), mMaxRTT(maxRTT), mMinTS(minTS), mMaxTS(maxTS) {} + + + QColor colorScale(float f) + { + if(f == 0) + return QColor::fromHsv(0,0,192) ; + else + return QColor::fromHsv((int)((1.0-f)*280),200,255) ; + } + + virtual void draw(QPainter *painter,int& ox,int& oy,const QString& title) + { + static const int cellx = 7 ; + static const int celly = 12 ; + + //int save_ox = ox ; + painter->setPen(QColor::fromRgb(0,0,0)) ; + painter->drawText(2+ox,celly+oy,title) ; + oy+=2+2*celly ; + + painter->drawRect(ox, oy, PLOT_WIDTH, PLOT_HEIGHT); + + if(mInfo.empty()) + return ; + + double maxdt = mRefTS - mMinTS; + if (maxdt > MAX_DISPLAY_PERIOD) + { + mMinTS = mRefTS - MAX_DISPLAY_PERIOD; + } + + /* draw a different line for each peer */ + std::map >::const_iterator mit; + int i = 0; + int nLines = mInfo.size(); + for(mit = mInfo.begin(); mit != mInfo.end(); mit++, i++) + { + QPainterPath path; + std::list::const_iterator it = mit->second.begin(); + if (it != mit->second.end()) + { + double x = convertDtToPixels(mRefTS, mMinTS, it->mTS); + double y = convertRttToPixels(mMaxRTT, it->mRTT); + path.moveTo(ox + x, oy + y); + it++; + } + + for(; it != mit->second.end(); it++) + { + /* skip old elements */ + if (it->mTS < mMinTS) + { + continue; + } + + double x = convertDtToPixels(mRefTS, mMinTS, it->mTS); + double y = convertRttToPixels(mMaxRTT, it->mRTT); + + path.lineTo(ox + x, oy + y); + } + + /* draw line */ + painter->setPen(QColor::fromRgb(((255.0 * i) / (nLines-1)),0, 255 - (255.0 * i) / (nLines-1))) ; + painter->drawPath(path); + + /* draw name */ + } + + painter->setPen(QColor::fromRgb(0,0,0)) ; + painter->drawText(ox+PLOT_WIDTH + cellx ,oy + celly / 2, QString::number(mMaxRTT)+" "+QObject::tr("secs")) ; + oy += PLOT_HEIGHT / 2; + painter->drawText(ox+PLOT_WIDTH + cellx ,oy + celly / 2, QString::number(mMaxRTT / 2.0)+" "+QObject::tr("secs")) ; + oy += PLOT_HEIGHT / 2; + painter->drawText(ox+PLOT_WIDTH + cellx ,oy + celly / 2, QString::number(0.0)+" "+QObject::tr("secs")) ; + oy += celly; + painter->drawText(ox ,oy, QObject::tr("Old")); + painter->drawText(ox + PLOT_WIDTH - cellx ,oy, QObject::tr("Now")); + oy += celly; + + // Now do names. + i = 0; + for(mit = mInfo.begin(); mit != mInfo.end(); mit++, i++) + { + painter->fillRect(ox,oy,cellx,celly, + QColor::fromRgb(((255.0 * i) / (nLines-1)),0, 255 - (255.0 * i) / (nLines-1))) ; + + painter->setPen(QColor::fromRgb(0,0,0)) ; + painter->drawRect(ox,oy,cellx,celly) ; + painter->drawText(ox + cellx + 4,oy + celly / 2,RttStatistics::getPeerName(mit->first)); + + oy += 2 * celly; + } + } + + private: + const std::map > &mInfo; + double mRefTS; + double mMaxRTT; + double mMinTS; + double mMaxTS; + +}; + +RttStatistics::RttStatistics(QWidget *parent) + : RsAutoUpdatePage(2000,parent) +{ + setupUi(this) ; + + m_bProcessSettings = false; + + _tunnel_statistics_F->setWidget( _tst_CW = new RttStatisticsWidget() ) ; + _tunnel_statistics_F->setWidgetResizable(true); + _tunnel_statistics_F->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + _tunnel_statistics_F->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); + _tunnel_statistics_F->viewport()->setBackgroundRole(QPalette::NoRole); + _tunnel_statistics_F->setFrameStyle(QFrame::NoFrame); + _tunnel_statistics_F->setFocusPolicy(Qt::NoFocus); + + // load settings + processSettings(true); +} + +RttStatistics::~RttStatistics() +{ + + // save settings + processSettings(false); +} + +void RttStatistics::processSettings(bool bLoad) +{ + m_bProcessSettings = true; + + Settings->beginGroup(QString("RttStatistics")); + + if (bLoad) { + // load settings + + // state of splitter + //splitter->restoreState(Settings->value("Splitter").toByteArray()); + } else { + // save settings + + // state of splitter + //Settings->setValue("Splitter", splitter->saveState()); + + } + + Settings->endGroup(); + + m_bProcessSettings = false; + +} + + +void RttStatistics::updateDisplay() +{ + std::map > info; + + if (!rsRtt) + { + return; + } + + std::list idList; + std::list::iterator it; + + rsPeers->getOnlineList(idList); + + time_t now = time(NULL); + time_t minTS = now; + time_t maxTS = 0; + double maxRTT = 0; + + for(it = idList.begin(); it != idList.end(); it++) + { + std::list results; + std::list::iterator rit; + +#define MAX_RESULTS 60 + rsRtt->getPongResults(*it, MAX_RESULTS, results); + + for(rit = results.begin(); rit != results.end(); rit++) + { + /* only want maxRTT to include plotted bit */ + double dt = now - rit->mTS; + if (dt < MAX_DISPLAY_PERIOD) + { + if (maxRTT < rit->mRTT) + { + maxRTT = rit->mRTT; + } + } + if (minTS > rit->mTS) + { + minTS = rit->mTS; + } + if (maxTS < rit->mTS) + { + maxTS = rit->mTS; + } + } + + info[*it] = results; + } + + + _tst_CW->updateRttStatistics(info, maxRTT, minTS, maxTS); + _tst_CW->update(); +} + +QString RttStatistics::getPeerName(const std::string& peer_id) +{ + static std::map names ; + + std::map::const_iterator it = names.find(peer_id) ; + + if( it != names.end()) + return it->second ; + else + { + RsPeerDetails detail ; + if(!rsPeers->getPeerDetails(peer_id,detail)) + return "unknown peer"; + + return (names[peer_id] = QString::fromUtf8(detail.name.c_str())) ; + } +} + +RttStatisticsWidget::RttStatisticsWidget(QWidget *parent) + : QWidget(parent) +{ + maxWidth = 200 ; + maxHeight = 0 ; +} + +void RttStatisticsWidget::updateRttStatistics(const std::map >& info, + double maxRTT, double minTS, double maxTS) +{ + //static const int cellx = 6 ; + //static const int celly = 10+4 ; + + QPixmap tmppixmap(maxWidth, maxHeight); + tmppixmap.fill(this, 0, 0); + setFixedHeight(maxHeight); + + QPainter painter(&tmppixmap); + painter.initFrom(this); + + maxHeight = 500 ; + + //std::cerr << "Drawing into pixmap of size " << maxWidth << "x" << maxHeight << std::endl; + // draw... + int ox=5,oy=5 ; + + double refTS = time(NULL); + + //painter.setPen(QColor::fromRgb(70,70,70)) ; + //painter.drawLine(0,oy,maxWidth,oy) ; + //oy += celly ; + //painter.setPen(QColor::fromRgb(0,0,0)) ; + + // round up RTT to nearest + double roundedRTT = maxRTT; + if (maxRTT < 0.15) + { + roundedRTT = 0.2; + } + else if (maxRTT < 0.4) + { + roundedRTT = 0.5; + } + else if (maxRTT < 0.8) + { + roundedRTT = 1.0; + } + else if (maxRTT < 1.8) + { + roundedRTT = 2.0; + } + else if (maxRTT < 4.5) + { + roundedRTT = 5.0; + } + + RttPlot(info, refTS, roundedRTT, minTS, maxTS).draw(&painter,ox,oy,QObject::tr("Round Trip Time:")) ; + + // update the pixmap + pixmap = tmppixmap; + maxHeight = oy; // + PLOT_HEIGHT * 2; +} + +QString RttStatisticsWidget::speedString(float f) +{ + if(f < 1.0f) + return QString("0 B/s") ; + if(f < 1024.0f) + return QString::number((int)f)+" B/s" ; + + return QString::number(f/1024.0,'f',2) + " KB/s"; +} + +void RttStatisticsWidget::paintEvent(QPaintEvent */*event*/) +{ + QStylePainter(this).drawPixmap(0, 0, pixmap); +} + +void RttStatisticsWidget::resizeEvent(QResizeEvent *event) +{ + QRect TaskGraphRect = geometry(); + maxWidth = TaskGraphRect.width(); + maxHeight = TaskGraphRect.height() ; + + QWidget::resizeEvent(event); + update(); +} + + diff --git a/retroshare-gui/src/gui/RttStatistics.h b/retroshare-gui/src/gui/RttStatistics.h new file mode 100644 index 000000000..10fd6b654 --- /dev/null +++ b/retroshare-gui/src/gui/RttStatistics.h @@ -0,0 +1,68 @@ +/**************************************************************** + * RetroShare is distributed under the following license: + * + * Copyright (C) 20011, RetroShare Team + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + ****************************************************************/ + +#pragma once + +#include +#include +#include "ui_RttStatistics.h" +#include "RsAutoUpdatePage.h" + +class RttStatisticsWidget ; + +class RttStatistics: public RsAutoUpdatePage, public Ui::RttStatistics +{ + public: + RttStatistics(QWidget *parent = NULL) ; + ~RttStatistics(); + + // Cache for peer names. + static QString getPeerName(const std::string& peer_id) ; + + private: + + void processSettings(bool bLoad); + bool m_bProcessSettings; + + virtual void updateDisplay() ; + + RttStatisticsWidget *_tst_CW ; +} ; + +class RttStatisticsWidget: public QWidget +{ + public: + RttStatisticsWidget(QWidget *parent = NULL) ; + + virtual void paintEvent(QPaintEvent *event) ; + virtual void resizeEvent(QResizeEvent *event); + + + void updateRttStatistics(const std::map >& info, + double maxRTT, double minTS, double maxTS); + + private: + static QString speedString(float f) ; + + QPixmap pixmap ; + int maxWidth,maxHeight ; +}; + diff --git a/retroshare-gui/src/gui/RttStatistics.ui b/retroshare-gui/src/gui/RttStatistics.ui new file mode 100644 index 000000000..3bcee25d8 --- /dev/null +++ b/retroshare-gui/src/gui/RttStatistics.ui @@ -0,0 +1,55 @@ + + + RttStatistics + + + + 0 + 0 + 611 + 408 + + + + RTT Statistics + + + + :/images/rstray3.png:/images/rstray3.png + + + + + + Qt::Vertical + + + + QFrame::NoFrame + + + Qt::ScrollBarAlwaysOff + + + true + + + + + 0 + 0 + 587 + 384 + + + + + + + + + + + + + diff --git a/retroshare-gui/src/gui/connect/ConfCertDialog.cpp b/retroshare-gui/src/gui/connect/ConfCertDialog.cpp index aa5b41c2b..86c5f80a6 100644 --- a/retroshare-gui/src/gui/connect/ConfCertDialog.cpp +++ b/retroshare-gui/src/gui/connect/ConfCertDialog.cpp @@ -195,11 +195,9 @@ void ConfCertDialog::load() ui.lastcontact->setText(DateTime::formatLongDateTime(detail.lastConnect)); /* set retroshare version */ - std::map::iterator vit; - std::map versions; - bool retv = rsDisc->getDiscVersions(versions); - if (retv && versions.end() != (vit = versions.find(detail.id))) - ui.version->setText(QString::fromStdString(vit->second)); + std::string version; + rsDisc->getPeerVersion(detail.id, version); + ui.version->setText(QString::fromStdString(version)); RsPeerCryptoParams cdet ; if(rsicontrol->getPeerCryptoDetails(detail.id,cdet) && cdet.connexion_state!=0) diff --git a/retroshare-gui/src/gui/profile/ProfileWidget.cpp b/retroshare-gui/src/gui/profile/ProfileWidget.cpp index ab6747747..9a2f5f96c 100644 --- a/retroshare-gui/src/gui/profile/ProfileWidget.cpp +++ b/retroshare-gui/src/gui/profile/ProfileWidget.cpp @@ -59,13 +59,9 @@ void ProfileWidget::showEvent ( QShowEvent * /*event*/ ) ui.peerid->setText(QString::fromStdString(detail.id)); /* set retroshare version */ - std::map::iterator vit; - std::map versions; - bool retv = rsDisc->getDiscVersions(versions); - if (retv && versions.end() != (vit = versions.find(detail.id))) - { - ui.version->setText(QString::fromStdString(vit->second)); - } + std::string version; + rsDisc->getPeerVersion(detail.id, version); + ui.version->setText(QString::fromStdString(version)); ui.ipAddressList->clear(); for(std::list::const_iterator it(detail.ipAddressList.begin());it!=detail.ipAddressList.end();++it) diff --git a/retroshare-gui/src/gui/settings/CryptoPage.cpp b/retroshare-gui/src/gui/settings/CryptoPage.cpp index 385170d49..c988099f7 100755 --- a/retroshare-gui/src/gui/settings/CryptoPage.cpp +++ b/retroshare-gui/src/gui/settings/CryptoPage.cpp @@ -78,13 +78,9 @@ void CryptoPage::showEvent ( QShowEvent * /*event*/ ) ui.pgpid->setText(QString::fromStdString(detail.gpg_id)); /* set retroshare version */ - std::map::iterator vit; - std::map versions; - bool retv = rsDisc->getDiscVersions(versions); - if (retv && versions.end() != (vit = versions.find(detail.id))) - { - ui.version->setText(QString::fromStdString(vit->second)); - } + std::string version; + rsDisc->getPeerVersion(detail.id, version); + ui.version->setText(QString::fromStdString(version)); std::list ids; ids.clear(); diff --git a/retroshare-gui/src/gui/settings/ServerPage.cpp b/retroshare-gui/src/gui/settings/ServerPage.cpp index b26fcf176..edeaada4b 100755 --- a/retroshare-gui/src/gui/settings/ServerPage.cpp +++ b/retroshare-gui/src/gui/settings/ServerPage.cpp @@ -171,9 +171,9 @@ void ServerPage::load() */ netIndex = 3; // NONE. - if (detail.visState & RS_VS_DHT_ON) + if (detail.vs_dht != RS_VS_DISC_OFF) { - if (detail.visState & RS_VS_DISC_ON) + if (detail.vs_disc != RS_VS_DISC_OFF) { netIndex = 0; // PUBLIC } @@ -184,7 +184,7 @@ void ServerPage::load() } else { - if (detail.visState & RS_VS_DISC_ON) + if (detail.vs_disc != RS_VS_DISC_OFF) { netIndex = 1; // PRIVATE } @@ -342,26 +342,32 @@ void ServerPage::saveAddresses() if (detail.netMode != netMode) rsPeers->setNetworkMode(ownId, netMode); - uint32_t visState = 0; + uint16_t vs_disc = 0; + uint16_t vs_dht = 0; /* Check if vis has changed */ switch(ui.discComboBox->currentIndex()) { case 0: - visState |= (RS_VS_DISC_ON | RS_VS_DHT_ON); + vs_disc = RS_VS_DISC_FULL; + vs_dht = RS_VS_DHT_FULL; break; case 1: - visState |= RS_VS_DISC_ON; + vs_disc = RS_VS_DISC_FULL; + vs_dht = RS_VS_DHT_OFF; break; case 2: - visState |= RS_VS_DHT_ON; + vs_disc = RS_VS_DISC_OFF; + vs_dht = RS_VS_DHT_FULL; break; case 3: default: + vs_disc = RS_VS_DISC_OFF; + vs_dht = RS_VS_DHT_OFF; break; } - if (visState != detail.visState) - rsPeers->setVisState(ownId, visState); + if ((vs_disc != detail.vs_disc) || (vs_dht != detail.vs_dht)) + rsPeers->setVisState(ownId, vs_disc, vs_dht); if (0 != netIndex) saveAddr = true; diff --git a/retroshare-gui/src/retroshare-gui.pro b/retroshare-gui/src/retroshare-gui.pro index 7e0a3fbd7..ee6a310b7 100644 --- a/retroshare-gui/src/retroshare-gui.pro +++ b/retroshare-gui/src/retroshare-gui.pro @@ -193,7 +193,8 @@ macx { gxs { LIBS += ../../supportlibs/pegmarkdown/lib/libpegmarkdown.a - LIBS += -lsqlite3 + LIBS += ../../../lib/libsqlcipher.a + #LIBS += -lsqlite3 } @@ -479,7 +480,8 @@ HEADERS += rshare.h \ gui/dht/DhtWindow.h \ gui/bwctrl/BwCtrlWindow.h \ gui/channels/ShareKey.h \ - gui/GetStartedDialog.h + gui/GetStartedDialog.h \ + gui/RttStatistics.h \ # gui/ForumsDialog.h \ # gui/forums/ForumDetails.h \ @@ -585,7 +587,8 @@ FORMS += gui/StartDialog.ui \ gui/dht/DhtWindow.ui \ gui/bwctrl/BwCtrlWindow.ui \ gui/channels/ShareKey.ui \ - gui/GetStartedDialog.ui + gui/GetStartedDialog.ui \ + gui/RttStatistics.ui \ # gui/ForumsDialog.ui \ # gui/forums/CreateForum.ui \ @@ -787,7 +790,8 @@ SOURCES += main.cpp \ gui/dht/DhtWindow.cpp \ gui/bwctrl/BwCtrlWindow.cpp \ gui/channels/ShareKey.cpp \ - gui/GetStartedDialog.cpp + gui/GetStartedDialog.cpp \ + gui/RttStatistics.cpp \ # gui/ForumsDialog.cpp \ # gui/forums/ForumDetails.cpp \ From 41daabe1efadf8cf3c99e855571cf5be1c8de9bf Mon Sep 17 00:00:00 2001 From: drbob Date: Sun, 29 Sep 2013 07:11:02 +0000 Subject: [PATCH 21/83] Added Round Trip Time service (revived old p3VoRS service). - Fixed gxs priority level. git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@6776 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/libretroshare.pro | 6 +- libretroshare/src/retroshare/rsrtt.h | 63 +++ libretroshare/src/rsserver/rsinit.cc | 18 +- libretroshare/src/serialiser/itempriorities.h | 4 +- libretroshare/src/serialiser/rsnxsitems.h | 2 +- libretroshare/src/serialiser/rsrttitems.cc | 373 ++++++++++++++ libretroshare/src/serialiser/rsrttitems.h | 108 ++++ libretroshare/src/serialiser/rsserviceids.h | 3 + libretroshare/src/services/p3rtt.cc | 461 ++++++++++++++++++ libretroshare/src/services/p3rtt.h | 118 +++++ 10 files changed, 1147 insertions(+), 9 deletions(-) create mode 100644 libretroshare/src/retroshare/rsrtt.h create mode 100644 libretroshare/src/serialiser/rsrttitems.cc create mode 100644 libretroshare/src/serialiser/rsrttitems.h create mode 100644 libretroshare/src/services/p3rtt.cc create mode 100644 libretroshare/src/services/p3rtt.h diff --git a/libretroshare/src/libretroshare.pro b/libretroshare/src/libretroshare.pro index d2028c36a..851436c4b 100644 --- a/libretroshare/src/libretroshare.pro +++ b/libretroshare/src/libretroshare.pro @@ -3,7 +3,6 @@ CONFIG += staticlib bitdht CONFIG -= qt TARGET = retroshare -CONFIG += test_voip #GXS Stuff. # This should be disabled for releases until further notice. @@ -91,6 +90,7 @@ PUBLIC_HEADERS = retroshare/rsdisc.h \ retroshare/rstypes.h \ retroshare/rsdht.h \ retroshare/rsdsdv.h \ + retroshare/rsrtt.h \ retroshare/rsconfig.h @@ -387,6 +387,7 @@ HEADERS += serialiser/rsbaseitems.h \ serialiser/rsbwctrlitems.h \ serialiser/rsdiscovery2items.h \ serialiser/rsheartbeatitems.h \ + serialiser/rsrttitems.h \ HEADERS += services/p3chatservice.h \ services/p3msgservice.h \ @@ -397,6 +398,7 @@ HEADERS += services/p3chatservice.h \ services/p3bwctrl.h \ services/p3discovery2.h \ services/p3heartbeat.h \ + services/p3rtt.h \ HEADERS += turtle/p3turtle.h \ turtle/rsturtleitem.h \ @@ -514,6 +516,7 @@ SOURCES += serialiser/rsbaseitems.cc \ serialiser/rsbwctrlitems.cc \ serialiser/rsdiscovery2items.cc \ serialiser/rsheartbeatitems.cc \ + serialiser/rsrttitems.cc \ SOURCES += services/p3chatservice.cc \ services/p3msgservice.cc \ @@ -524,6 +527,7 @@ SOURCES += services/p3chatservice.cc \ services/p3bwctrl.cc \ services/p3discovery2.cc \ services/p3heartbeat.cc \ + services/p3rtt.cc \ SOURCES += turtle/p3turtle.cc \ turtle/rsturtleitem.cc diff --git a/libretroshare/src/retroshare/rsrtt.h b/libretroshare/src/retroshare/rsrtt.h new file mode 100644 index 000000000..12f29f3a5 --- /dev/null +++ b/libretroshare/src/retroshare/rsrtt.h @@ -0,0 +1,63 @@ +#ifndef RETROSHARE_RTT_INTERFACE_H +#define RETROSHARE_RTT_INTERFACE_H + +/* + * libretroshare/src/retroshare: rsvoip.h + * + * RetroShare C++ Interface. + * + * Copyright 2011-2011 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 + +/* The Main Interface Class - for information about your Peers */ +class RsRtt; +extern RsRtt *rsRtt; + + +class RsRttPongResult +{ + public: + RsRttPongResult() + :mTS(0), mRTT(0), mOffset(0) { return; } + + RsRttPongResult(double ts, double rtt, double offset) + :mTS(ts), mRTT(rtt), mOffset(offset) { return; } + + double mTS; + double mRTT; + double mOffset; +}; + +class RsRtt +{ + public: + + RsRtt() { return; } +virtual ~RsRtt() { return; } + +virtual uint32_t getPongResults(std::string id, int n, std::list &results) = 0; + +}; + +#endif diff --git a/libretroshare/src/rsserver/rsinit.cc b/libretroshare/src/rsserver/rsinit.cc index f0ad40f4c..b8d2ca306 100644 --- a/libretroshare/src/rsserver/rsinit.cc +++ b/libretroshare/src/rsserver/rsinit.cc @@ -1842,9 +1842,17 @@ RsTurtle *rsTurtle = NULL ; /**** * #define RS_RELEASE 1 + * #define RS_RTT 1 ****/ -#define RS_RELEASE 1 +#define RS_RELEASE 1 +#define RS_RTT 1 + + +#ifdef RS_RTT +#include "services/p3rtt.h" +#endif + #include "services/p3banlist.h" #include "services/p3bwctrl.h" @@ -2452,10 +2460,10 @@ int RsServer::StartupRetroShare() #endif // RS_ENABLE_GXS. -#ifdef RS_VOIPTEST - p3VoRS *mVoipTest = new p3VoRS(mLinkMgr); - pqih -> addService(mVoipTest); - rsVoip = mVoipTest; +#ifdef RS_RTT + p3rtt *mRtt = new p3rtt(mLinkMgr); + pqih -> addService(mRtt); + rsRtt = mRtt; #endif // new services to test. diff --git a/libretroshare/src/serialiser/itempriorities.h b/libretroshare/src/serialiser/itempriorities.h index 83f74b867..61bcc1978 100644 --- a/libretroshare/src/serialiser/itempriorities.h +++ b/libretroshare/src/serialiser/itempriorities.h @@ -87,9 +87,9 @@ const uint8_t QOS_PRIORITY_RS_CHAT_AVATAR_ITEM = 2 ; const uint8_t QOS_PRIORITY_RS_MSG_ITEM = 2 ; const uint8_t QOS_PRIORITY_RS_STATUS_ITEM = 2 ; -// VOIP +// RTT // -const uint8_t QOS_PRIORITY_RS_VOIP_PING = 9 ; +const uint8_t QOS_PRIORITY_RS_RTT_PING = 9 ; // BanList // diff --git a/libretroshare/src/serialiser/rsnxsitems.h b/libretroshare/src/serialiser/rsnxsitems.h index c15b0ce44..ee326495b 100644 --- a/libretroshare/src/serialiser/rsnxsitems.h +++ b/libretroshare/src/serialiser/rsnxsitems.h @@ -70,7 +70,7 @@ public: RsNxsItem(uint16_t servtype, uint8_t subtype) : RsItem(RS_PKT_VERSION_SERVICE, servtype, subtype), transactionNumber(0) { - setPriorityLevel(QOS_PRIORITY_RS_VOIP_PING); + setPriorityLevel(QOS_PRIORITY_RS_GXS_NET); return; } virtual ~RsNxsItem(){ return; } diff --git a/libretroshare/src/serialiser/rsrttitems.cc b/libretroshare/src/serialiser/rsrttitems.cc new file mode 100644 index 000000000..ed0046fd9 --- /dev/null +++ b/libretroshare/src/serialiser/rsrttitems.cc @@ -0,0 +1,373 @@ + +/* + * libretroshare/src/serialiser: rsrttitems.cc + * + * RetroShare Serialiser. + * + * Copyright 2011-2013 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.1 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/rsrttitems.h" +#include "serialiser/rstlvbase.h" + +/*** +#define RSSERIAL_DEBUG 1 +***/ + +#include + +/*************************************************************************/ + + +RsRttPingItem::~RsRttPingItem() +{ + return; +} + +void RsRttPingItem::clear() +{ + mSeqNo = 0; + mPingTS = 0; +} + +std::ostream& RsRttPingItem::print(std::ostream &out, uint16_t indent) +{ + printRsItemBase(out, "RsRttPingItem", indent); + uint16_t int_Indent = indent + 2; + printIndent(out, int_Indent); + out << "SeqNo: " << mSeqNo << std::endl; + + printIndent(out, int_Indent); + out << "PingTS: " << std::hex << mPingTS << std::dec << std::endl; + + printRsItemEnd(out, "RsRttPingItem", indent); + return out; +} + + + + + +RsRttPongItem::~RsRttPongItem() +{ + return; +} + +void RsRttPongItem::clear() +{ + mSeqNo = 0; + mPingTS = 0; + mPongTS = 0; +} + + +std::ostream& RsRttPongItem::print(std::ostream &out, uint16_t indent) +{ + printRsItemBase(out, "RsRttPongItem", indent); + uint16_t int_Indent = indent + 2; + printIndent(out, int_Indent); + out << "SeqNo: " << mSeqNo << std::endl; + + printIndent(out, int_Indent); + out << "PingTS: " << std::hex << mPingTS << std::dec << std::endl; + + printIndent(out, int_Indent); + out << "PongTS: " << std::hex << mPongTS << std::dec << std::endl; + + printRsItemEnd(out, "RsRttPongItem", indent); + return out; +} + + +/*************************************************************************/ + + +uint32_t RsRttSerialiser::sizeRttPingItem(RsRttPingItem */*item*/) +{ + uint32_t s = 8; /* header */ + s += 4; /* seqno */ + s += 8; /* pingTS */ + + return s; +} + +/* serialise the data to the buffer */ +bool RsRttSerialiser::serialiseRttPingItem(RsRttPingItem *item, void *data, uint32_t *pktsize) +{ + uint32_t tlvsize = sizeRttPingItem(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 << "RsRttSerialiser::serialiseRttPingItem() Header: " << ok << std::endl; + std::cerr << "RsRttSerialiser::serialiseRttPingItem() Size: " << tlvsize << std::endl; +#endif + + /* skip the header */ + offset += 8; + + /* add mandatory parts first */ + ok &= setRawUInt32(data, tlvsize, &offset, item->mSeqNo); + ok &= setRawUInt64(data, tlvsize, &offset, item->mPingTS); + + if (offset != tlvsize) + { + ok = false; + std::cerr << "RsRttSerialiser::serialiseRttPingItem() Size Error! " << std::endl; + } + + return ok; +} + +RsRttPingItem *RsRttSerialiser::deserialiseRttPingItem(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_RTT != getRsItemService(rstype)) || + (RS_PKT_SUBTYPE_RTT_PING != 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 */ + RsRttPingItem *item = new RsRttPingItem(); + item->clear(); + + /* skip the header */ + offset += 8; + + /* get mandatory parts first */ + ok &= getRawUInt32(data, rssize, &offset, &(item->mSeqNo)); + ok &= getRawUInt64(data, rssize, &offset, &(item->mPingTS)); + + if (offset != rssize) + { + /* error */ + delete item; + return NULL; + } + + if (!ok) + { + delete item; + return NULL; + } + + return item; +} + +/*************************************************************************/ +/*************************************************************************/ + + +uint32_t RsRttSerialiser::sizeRttPongItem(RsRttPongItem */*item*/) +{ + uint32_t s = 8; /* header */ + s += 4; /* seqno */ + s += 8; /* pingTS */ + s += 8; /* pongTS */ + + return s; +} + +/* serialise the data to the buffer */ +bool RsRttSerialiser::serialiseRttPongItem(RsRttPongItem *item, void *data, uint32_t *pktsize) +{ + uint32_t tlvsize = sizeRttPongItem(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 << "RsRttSerialiser::serialiseRttPongItem() Header: " << ok << std::endl; + std::cerr << "RsRttSerialiser::serialiseRttPongItem() Size: " << tlvsize << std::endl; +#endif + + /* skip the header */ + offset += 8; + + /* add mandatory parts first */ + ok &= setRawUInt32(data, tlvsize, &offset, item->mSeqNo); + ok &= setRawUInt64(data, tlvsize, &offset, item->mPingTS); + ok &= setRawUInt64(data, tlvsize, &offset, item->mPongTS); + + if (offset != tlvsize) + { + ok = false; + std::cerr << "RsRttSerialiser::serialiseRttPongItem() Size Error! " << std::endl; + } + + return ok; +} + +RsRttPongItem *RsRttSerialiser::deserialiseRttPongItem(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_RTT != getRsItemService(rstype)) || + (RS_PKT_SUBTYPE_RTT_PONG != 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 */ + RsRttPongItem *item = new RsRttPongItem(); + item->clear(); + + /* skip the header */ + offset += 8; + + /* get mandatory parts first */ + ok &= getRawUInt32(data, rssize, &offset, &(item->mSeqNo)); + ok &= getRawUInt64(data, rssize, &offset, &(item->mPingTS)); + ok &= getRawUInt64(data, rssize, &offset, &(item->mPongTS)); + + if (offset != rssize) + { + /* error */ + delete item; + return NULL; + } + + if (!ok) + { + delete item; + return NULL; + } + + return item; +} + +/*************************************************************************/ + +uint32_t RsRttSerialiser::size(RsItem *i) +{ + RsRttPingItem *ping; + RsRttPongItem *pong; + + if (NULL != (ping = dynamic_cast(i))) + { + return sizeRttPingItem(ping); + } + else if (NULL != (pong = dynamic_cast(i))) + { + return sizeRttPongItem(pong); + } + return 0; +} + +bool RsRttSerialiser::serialise(RsItem *i, void *data, uint32_t *pktsize) +{ +#ifdef RSSERIAL_DEBUG + std::cerr << "RsMsgSerialiser::serialise()" << std::endl; +#endif + + RsRttPingItem *ping; + RsRttPongItem *pong; + + if (NULL != (ping = dynamic_cast(i))) + { + return serialiseRttPingItem(ping, data, pktsize); + } + else if (NULL != (pong = dynamic_cast(i))) + { + return serialiseRttPongItem(pong, data, pktsize); + } + return false; +} + +RsItem* RsRttSerialiser::deserialise(void *data, uint32_t *pktsize) +{ +#ifdef RSSERIAL_DEBUG + std::cerr << "RsRttSerialiser::deserialise()" << std::endl; +#endif + + /* get the type and size */ + uint32_t rstype = getRsItemId(data); + + if ((RS_PKT_VERSION_SERVICE != getRsItemVersion(rstype)) || + (RS_SERVICE_TYPE_RTT != getRsItemService(rstype))) + { + return NULL; /* wrong type */ + } + + switch(getRsItemSubType(rstype)) + { + case RS_PKT_SUBTYPE_RTT_PING: + return deserialiseRttPingItem(data, pktsize); + break; + case RS_PKT_SUBTYPE_RTT_PONG: + return deserialiseRttPongItem(data, pktsize); + break; + default: + return NULL; + break; + } + + return NULL; +} + + +/*************************************************************************/ + diff --git a/libretroshare/src/serialiser/rsrttitems.h b/libretroshare/src/serialiser/rsrttitems.h new file mode 100644 index 000000000..2e51b1f30 --- /dev/null +++ b/libretroshare/src/serialiser/rsrttitems.h @@ -0,0 +1,108 @@ +#ifndef RS_RTT_ITEMS_H +#define RS_RTT_ITEMS_H + +/* + * libretroshare/src/serialiser: rsrttitems.h + * + * RetroShare Serialiser. + * + * Copyright 2011-2013 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.1 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" + +/**************************************************************************/ + +const uint8_t RS_PKT_SUBTYPE_RTT_PING = 0x01; +const uint8_t RS_PKT_SUBTYPE_RTT_PONG = 0x02; + +class RsRttItem: public RsItem +{ + public: + RsRttItem(uint8_t chat_subtype) : RsItem(RS_PKT_VERSION_SERVICE,RS_SERVICE_TYPE_RTT,chat_subtype) + { setPriorityLevel(QOS_PRIORITY_RS_RTT_PING) ;} // should be refined later. + + virtual ~RsRttItem() {}; + virtual void clear() {}; + virtual std::ostream& print(std::ostream &out, uint16_t indent = 0) = 0 ; +}; + +class RsRttPingItem: public RsRttItem +{ + public: + RsRttPingItem() :RsRttItem(RS_PKT_SUBTYPE_RTT_PING) {} + + virtual ~RsRttPingItem(); + virtual void clear(); + virtual std::ostream& print(std::ostream &out, uint16_t indent = 0); + + uint32_t mSeqNo; + uint64_t mPingTS; +}; + +class RsRttPongItem: public RsRttItem +{ + public: + RsRttPongItem() :RsRttItem(RS_PKT_SUBTYPE_RTT_PONG) {} + + virtual ~RsRttPongItem(); + virtual void clear(); + virtual std::ostream& print(std::ostream &out, uint16_t indent = 0); + + uint32_t mSeqNo; + uint64_t mPingTS; + uint64_t mPongTS; +}; + + +class RsRttSerialiser: public RsSerialType +{ + public: + RsRttSerialiser() + :RsSerialType(RS_PKT_VERSION_SERVICE, RS_SERVICE_TYPE_RTT) + { return; } + +virtual ~RsRttSerialiser() { 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 sizeRttPingItem(RsRttPingItem *); +virtual bool serialiseRttPingItem (RsRttPingItem *item, void *data, uint32_t *size); +virtual RsRttPingItem *deserialiseRttPingItem(void *data, uint32_t *size); + +virtual uint32_t sizeRttPongItem(RsRttPongItem *); +virtual bool serialiseRttPongItem (RsRttPongItem *item, void *data, uint32_t *size); +virtual RsRttPongItem *deserialiseRttPongItem(void *data, uint32_t *size); + +}; + +/**************************************************************************/ + +#endif /* RS_RTT_ITEMS_H */ + + diff --git a/libretroshare/src/serialiser/rsserviceids.h b/libretroshare/src/serialiser/rsserviceids.h index 73e08d42d..08c64c992 100644 --- a/libretroshare/src/serialiser/rsserviceids.h +++ b/libretroshare/src/serialiser/rsserviceids.h @@ -104,12 +104,15 @@ const uint16_t RS_SERVICE_TYPE_PROXY = 0xf030; /* DSDV Testing at the moment - Service Only */ const uint16_t RS_SERVICE_TYPE_DSDV = 0xf050; +/* Latency RTT Measurements */ +const uint16_t RS_SERVICE_TYPE_RTT = 0xf051; /* Bandwidth Testing at the moment - Service Only */ const uint16_t RS_SERVICE_TYPE_BWCTRL = 0xf060; + //const uint16_t RS_SERVICE_TYPE_DISTRIB = 0xf110; //const uint16_t RS_SERVICE_TYPE_FORUM = 0xf120; //const uint16_t RS_SERVICE_TYPE_CHANNEL = 0xf130; diff --git a/libretroshare/src/services/p3rtt.cc b/libretroshare/src/services/p3rtt.cc new file mode 100644 index 000000000..91fb51b9e --- /dev/null +++ b/libretroshare/src/services/p3rtt.cc @@ -0,0 +1,461 @@ +/* + * libretroshare/src/services p3rtt.cc + * + * Round Trip Time Measurement for RetroShare. + * + * Copyright 2011-2013 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.1 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 "util/rsdir.h" +#include "retroshare/rsiface.h" +#include "pqi/pqibin.h" +#include "pqi/pqinotify.h" +#include "pqi/pqistore.h" +#include "pqi/p3linkmgr.h" + +#include "services/p3rtt.h" +#include "serialiser/rsrttitems.h" + +#include + +/**** + * #define DEBUG_RTT 1 + ****/ + + +/* DEFINE INTERFACE POINTER! */ +RsRtt *rsRtt = NULL; + + +#define MAX_PONG_RESULTS 150 +#define RTT_PING_PERIOD 10 + +/************ IMPLEMENTATION NOTES ********************************* + * + * Voice over Retroshare ;) + * + * This will be a simple test VoIP system aimed at testing out the possibilities. + * + * Important things to test: + * 1) lag, and variability in data rate + * - To do this we time tag every packet..., the destination can use this info to calculate the results. + * - Like imixitup. Dt = clock_diff + lag. + * we expect clock_diff to be relatively constant, but lag to vary. + * lag cannot be negative, so minimal Dt is ~clock_diff, and delays on this are considered +lag. + * + * 2) we could directly measure lag. ping back and forth with Timestamps. + * + * 3) we also want to measure bandwidth... + * - not sure the best method? + * one way: send a ping, then a large amount of data (5 seconds worth), then another ping. + * the delta in timestamps should be a decent indication of bandwidth. + * say we have a 100kb/s connection... need 500kb. + * actually the amount of data should be based on a reasonable maximum that we require. + * what does decent video require? + * Audio we can test for 64kb/s - which seems like a decent rate: e.g. mono, 16bit 22k = 1 x 2 x 22k = 44 kilobytes/sec + * best to do this without a VoIP call going on ;) + * + * + */ + + +#ifdef WINDOWS_SYS +#include +#include +#endif + +static double getCurrentTS() +{ + +#ifndef WINDOWS_SYS + struct timeval cts_tmp; + gettimeofday(&cts_tmp, NULL); + double cts = (cts_tmp.tv_sec) + ((double) cts_tmp.tv_usec) / 1000000.0; +#else + struct _timeb timebuf; + _ftime( &timebuf); + double cts = (timebuf.time) + ((double) timebuf.millitm) / 1000.0; +#endif + return cts; +} + +static uint64_t convertTsTo64bits(double ts) +{ + uint32_t secs = (uint32_t) ts; + uint32_t usecs = (uint32_t) ((ts - (double) secs) * 1000000); + uint64_t bits = (((uint64_t) secs) << 32) + usecs; + return bits; +} + + +static double convert64bitsToTs(uint64_t bits) +{ + uint32_t usecs = (uint32_t) (bits & 0xffffffff); + uint32_t secs = (uint32_t) ((bits >> 32) & 0xffffffff); + double ts = (secs) + ((double) usecs) / 1000000.0; + + return ts; +} + + + + +p3rtt::p3rtt(p3LinkMgr *lm) + :p3Service(RS_SERVICE_TYPE_RTT), /* p3Config(CONFIG_TYPE_RTT), */ mRttMtx("p3rtt"), mLinkMgr(lm) +{ + addSerialType(new RsRttSerialiser()); + + mSentPingTime = 0; + mCounter = 0; + +} + + +int p3rtt::tick() +{ + processIncoming(); + sendPackets(); + + return 0; +} + +int p3rtt::status() +{ + return 1; +} + + + +int p3rtt::sendPackets() +{ + time_t now = time(NULL); + time_t pt; + { + RsStackMutex stack(mRttMtx); /****** LOCKED MUTEX *******/ + pt = mSentPingTime; + } + + if (now - pt > RTT_PING_PERIOD) + { + sendPingMeasurements(); + + RsStackMutex stack(mRttMtx); /****** LOCKED MUTEX *******/ + mSentPingTime = now; + } + return true ; +} + + + +void p3rtt::sendPingMeasurements() +{ + + + /* we ping our peers */ + /* who is online? */ + std::list idList; + + mLinkMgr->getOnlineList(idList); + + double ts = getCurrentTS(); + +#ifdef DEBUG_RTT + std::cerr << "p3rtt::sendPingMeasurements() @ts: " << ts; + std::cerr << std::endl; +#endif + + /* prepare packets */ + std::list::iterator it; + for(it = idList.begin(); it != idList.end(); it++) + { +#ifdef DEBUG_RTT + std::cerr << "p3rtt::sendPingMeasurements() Pinging: " << *it; + std::cerr << std::endl; +#endif + + /* create the packet */ + RsRttPingItem *pingPkt = new RsRttPingItem(); + pingPkt->PeerId(*it); + pingPkt->mSeqNo = mCounter; + pingPkt->mPingTS = convertTsTo64bits(ts); + + storePingAttempt(*it, ts, mCounter); + +#ifdef DEBUG_RTT + std::cerr << "p3rtt::sendPingMeasurements() With Packet:"; + std::cerr << std::endl; + pingPkt->print(std::cerr, 10); +#endif + + sendItem(pingPkt); + } + + RsStackMutex stack(mRttMtx); /****** LOCKED MUTEX *******/ + mCounter++; +} + + + + +int p3rtt::processIncoming() +{ + /* for each packet - pass to specific handler */ + RsItem *item = NULL; + while(NULL != (item = recvItem())) + { + switch(item->PacketSubType()) + { + default: + break; + case RS_PKT_SUBTYPE_RTT_PING: + { + handlePing(item); + } + break; + case RS_PKT_SUBTYPE_RTT_PONG: + { + handlePong(item); + } + break; + +#if 0 + /* THESE ARE ALL FUTURISTIC DATA TYPES */ + case RS_DATA_ITEM: + { + handleData(item); + } + break; + + case RS_BANDWIDTH_PING_ITEM: + { + handleBandwidthPing(item); + } + break; + + case RS_BANDWIDTH_PONG_ITEM: + { + handleBandwidthPong(item); + } + break; +#endif + } + + /* clean up */ + delete item; + } + return true ; +} + +int p3rtt::handlePing(RsItem *item) +{ + /* cast to right type */ + RsRttPingItem *ping = (RsRttPingItem *) item; + +#ifdef DEBUG_RTT + std::cerr << "p3rtt::handlePing() Recvd Packet from: " << ping->PeerId(); + std::cerr << std::endl; +#endif + + /* with a ping, we just respond as quickly as possible - they do all the analysis */ + RsRttPongItem *pong = new RsRttPongItem(); + + + pong->PeerId(ping->PeerId()); + pong->mPingTS = ping->mPingTS; + pong->mSeqNo = ping->mSeqNo; + + // add our timestamp. + double ts = getCurrentTS(); + pong->mPongTS = convertTsTo64bits(ts); + + +#ifdef DEBUG_RTT + std::cerr << "p3rtt::handlePing() With Packet:"; + std::cerr << std::endl; + pong->print(std::cerr, 10); +#endif + + sendItem(pong); + return true ; +} + + +int p3rtt::handlePong(RsItem *item) +{ + /* cast to right type */ + RsRttPongItem *pong = (RsRttPongItem *) item; + +#ifdef DEBUG_RTT + std::cerr << "p3rtt::handlePong() Recvd Packet from: " << pong->PeerId(); + std::cerr << std::endl; + pong->print(std::cerr, 10); +#endif + + /* with a pong, we do the maths! */ + double recvTS = getCurrentTS(); + double pingTS = convert64bitsToTs(pong->mPingTS); + double pongTS = convert64bitsToTs(pong->mPongTS); + + double rtt = recvTS - pingTS; + double offset = pongTS - (recvTS - rtt / 2.0); // so to get to their time, we go ourTS + offset. + +#ifdef DEBUG_RTT + std::cerr << "p3rtt::handlePong() Timing:"; + std::cerr << std::endl; + std::cerr << "\tpingTS: " << pingTS; + std::cerr << std::endl; + std::cerr << "\tpongTS: " << pongTS; + std::cerr << std::endl; + std::cerr << "\trecvTS: " << recvTS; + std::cerr << std::endl; + std::cerr << "\t ==> rtt: " << rtt; + std::cerr << std::endl; + std::cerr << "\t ==> offset: " << offset; + std::cerr << std::endl; +#endif + + storePongResult(pong->PeerId(), pong->mSeqNo, pingTS, rtt, offset); + return true ; +} + + + + +int p3rtt::storePingAttempt(std::string id, double ts, uint32_t seqno) +{ + RsStackMutex stack(mRttMtx); /****** LOCKED MUTEX *******/ + + /* find corresponding local data */ + RttPeerInfo *peerInfo = locked_GetPeerInfo(id); + + peerInfo->mCurrentPingTS = ts; + peerInfo->mCurrentPingCounter = seqno; + + peerInfo->mSentPings++; + if (!peerInfo->mCurrentPongRecvd) + { + peerInfo->mLostPongs++; + } + + peerInfo->mCurrentPongRecvd = true; + + return 1; +} + + + +int p3rtt::storePongResult(std::string id, uint32_t counter, double ts, double rtt, double offset) +{ + RsStackMutex stack(mRttMtx); /****** LOCKED MUTEX *******/ + + /* find corresponding local data */ + RttPeerInfo *peerInfo = locked_GetPeerInfo(id); + + if (peerInfo->mCurrentPingCounter != counter) + { +#ifdef DEBUG_RTT + std::cerr << "p3rtt::storePongResult() ERROR Severly Delayed Measurements!" << std::endl; +#endif + } + else + { + peerInfo->mCurrentPongRecvd = true; + } + + peerInfo->mPongResults.push_back(RsRttPongResult(ts, rtt, offset)); + + + while(peerInfo->mPongResults.size() > MAX_PONG_RESULTS) + { + peerInfo->mPongResults.pop_front(); + } + + /* should do calculations */ + return 1; +} + + +uint32_t p3rtt::getPongResults(std::string id, int n, std::list &results) +{ + RsStackMutex stack(mRttMtx); /****** LOCKED MUTEX *******/ + + RttPeerInfo *peer = locked_GetPeerInfo(id); + + std::list::reverse_iterator it; + int i = 0; + for(it = peer->mPongResults.rbegin(); (it != peer->mPongResults.rend()) && (i < n); it++, i++) + { + /* reversing order - so its easy to trim later */ + results.push_back(*it); + } + return i ; +} + + + +RttPeerInfo *p3rtt::locked_GetPeerInfo(std::string id) +{ + std::map::iterator it; + it = mPeerInfo.find(id); + if (it == mPeerInfo.end()) + { + /* add it in */ + RttPeerInfo pinfo; + + /* initialise entry */ + pinfo.initialisePeerInfo(id); + + mPeerInfo[id] = pinfo; + + it = mPeerInfo.find(id); + + } + + return &(it->second); +} + + + +bool RttPeerInfo::initialisePeerInfo(std::string id) +{ + mId = id; + + /* reset variables */ + mCurrentPingTS = 0; + mCurrentPingCounter = 0; + mCurrentPongRecvd = true; + + mSentPings = 0; + mLostPongs = 0; + + mPongResults.clear(); + + return true; +} + + + + + + + + + + diff --git a/libretroshare/src/services/p3rtt.h b/libretroshare/src/services/p3rtt.h new file mode 100644 index 000000000..68c90fdfb --- /dev/null +++ b/libretroshare/src/services/p3rtt.h @@ -0,0 +1,118 @@ +/* + * libretroshare/src/services/p3rtt.h + * + * Round Trip Time Measurement for RetroShare. + * + * Copyright 2011-2013 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.1 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_RSRTT_HEADER +#define SERVICE_RSRTT_HEADER + +#include +#include + +#include "serialiser/rsrttitems.h" +#include "services/p3service.h" +#include "retroshare/rsrtt.h" + +class p3LinkMgr; + +class RttPeerInfo +{ + public: + + bool initialisePeerInfo(std::string id); + + std::string mId; + double mCurrentPingTS; + double mCurrentPingCounter; + bool mCurrentPongRecvd; + + uint32_t mLostPongs; + uint32_t mSentPings; + + std::list mPongResults; +}; + + +//!The RS Rtt Test service. + /** + * + * Used to test Latency. + */ + +class p3rtt: public RsRtt, public p3Service +{ + public: + p3rtt(p3LinkMgr *cm); + + /***** overloaded from rsRtt *****/ + +virtual uint32_t getPongResults(std::string id, int n, std::list &results); + + /***** overloaded from p3Service *****/ + + virtual int tick(); + virtual int status(); + + + int sendPackets(); + void sendPingMeasurements(); + int processIncoming(); + + int handlePing(RsItem *item); + int handlePong(RsItem *item); + + int storePingAttempt(std::string id, double ts, uint32_t mCounter); + int storePongResult(std::string id, uint32_t counter, double ts, double rtt, double offset); + + + /*! + * This retrieves all public chat msg items + */ + //bool getPublicChatQueue(std::list &chats); + + /*************** pqiMonitor callback ***********************/ + //virtual void statusChange(const std::list &plist); + + + /************* from p3Config *******************/ + //virtual RsSerialiser *setupSerialiser() ; + //virtual bool saveList(bool& cleanup, std::list&) ; + //virtual void saveDone(); + //virtual bool loadList(std::list& load) ; + + private: + RsMutex mRttMtx; + + RttPeerInfo *locked_GetPeerInfo(std::string id); + + std::map mPeerInfo; + time_t mSentPingTime; + uint32_t mCounter; + + p3LinkMgr *mLinkMgr; + +}; + +#endif // SERVICE_RSRTT_HEADER + From ccc25745990ae53ef6d2d2334058abe88aeb2105 Mon Sep 17 00:00:00 2001 From: csoler Date: Sun, 29 Sep 2013 12:51:56 +0000 Subject: [PATCH 22/83] fixed include git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@6778 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- retroshare-gui/src/gui/FileTransfer/TransfersDialog.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/retroshare-gui/src/gui/FileTransfer/TransfersDialog.cpp b/retroshare-gui/src/gui/FileTransfer/TransfersDialog.cpp index 8551d94d5..001902a82 100644 --- a/retroshare-gui/src/gui/FileTransfer/TransfersDialog.cpp +++ b/retroshare-gui/src/gui/FileTransfer/TransfersDialog.cpp @@ -65,7 +65,7 @@ #define SHOW_RTT_STATISTICS 1 #ifdef SHOW_RTT_STATISTICS - #include "RttStatistics.h" + #include "gui/RttStatistics.h" #endif /* Images for context menu icons */ From 4e4b4f08229ab8ce6b8c0d3c4a0202c7c3803b66 Mon Sep 17 00:00:00 2001 From: csoler Date: Mon, 30 Sep 2013 21:15:01 +0000 Subject: [PATCH 23/83] fixed missing return git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@6781 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/services/p3heartbeat.cc | 2 ++ 1 file changed, 2 insertions(+) diff --git a/libretroshare/src/services/p3heartbeat.cc b/libretroshare/src/services/p3heartbeat.cc index b431fdae7..18d433732 100644 --- a/libretroshare/src/services/p3heartbeat.cc +++ b/libretroshare/src/services/p3heartbeat.cc @@ -93,6 +93,8 @@ int p3heartbeat::tick() delete item; } + + return nhandled ; } void p3heartbeat::sendHeartbeat(const std::string &toId) From 8e7fe9f79bcb0761e19699156a392b0532344d80 Mon Sep 17 00:00:00 2001 From: csoler Date: Tue, 1 Oct 2013 08:11:15 +0000 Subject: [PATCH 24/83] made file transfer a service. Removed all the old FT code from pqiHandler, and got rid of deprecated CRC32 computation/exchange methods git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@6782 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/ft/ftdata.h | 9 - libretroshare/src/ft/ftdatamultiplex.cc | 257 +-- libretroshare/src/ft/ftdatamultiplex.h | 14 - libretroshare/src/ft/ftserver.cc | 576 ++----- libretroshare/src/ft/ftserver.h | 32 +- libretroshare/src/ft/fttransfermodule.cc | 168 -- libretroshare/src/libretroshare.pro | 10 +- libretroshare/src/pqi/pqi.h | 37 +- libretroshare/src/pqi/pqihandler.cc | 285 +--- libretroshare/src/pqi/pqihandler.h | 29 +- libretroshare/src/pqi/pqipersongrp.cc | 5 +- libretroshare/src/pqi/pqisslpersongrp.cc | 7 +- libretroshare/src/pqi/pqistreamer.cc | 1 - libretroshare/src/rsserver/p3face-config.cc | 1 - libretroshare/src/rsserver/p3face-server.cc | 5 +- libretroshare/src/rsserver/p3face.h | 2 +- libretroshare/src/rsserver/rsinit.cc | 4 +- libretroshare/src/serialiser/rsbaseitems.cc | 1519 ----------------- libretroshare/src/serialiser/rsbaseitems.h | 331 ---- .../src/serialiser/rsfiletransferitems.cc | 900 ++++++++++ .../src/serialiser/rsfiletransferitems.h | 271 +++ libretroshare/src/serialiser/rsserviceids.h | 15 +- .../src/serialiser/rsserviceserialiser.cc | 99 ++ .../src/serialiser/rsserviceserialiser.h | 40 + libretroshare/src/services/p3chatservice.cc | 83 - libretroshare/src/services/p3chatservice.h | 2 - 26 files changed, 1505 insertions(+), 3197 deletions(-) delete mode 100644 libretroshare/src/serialiser/rsbaseitems.cc delete mode 100644 libretroshare/src/serialiser/rsbaseitems.h create mode 100644 libretroshare/src/serialiser/rsfiletransferitems.cc create mode 100644 libretroshare/src/serialiser/rsfiletransferitems.h create mode 100644 libretroshare/src/serialiser/rsserviceserialiser.cc create mode 100644 libretroshare/src/serialiser/rsserviceserialiser.h diff --git a/libretroshare/src/ft/ftdata.h b/libretroshare/src/ft/ftdata.h index a60851498..ae84a1811 100644 --- a/libretroshare/src/ft/ftdata.h +++ b/libretroshare/src/ft/ftdata.h @@ -64,10 +64,6 @@ class ftDataSend virtual bool sendChunkMapRequest(const std::string& peer_id,const std::string& hash,bool is_client) = 0; virtual bool sendChunkMap(const std::string& peer_id,const std::string& hash,const CompressedChunkMap& cmap,bool is_client) = 0; - /// Send a request for a chunk crc map - virtual bool sendCRC32MapRequest(const std::string& peer_id,const std::string& hash) = 0; - /// Send a chunk crc map - virtual bool sendCRC32Map(const std::string& peer_id,const std::string& hash,const CRC32Map& crc_map) = 0; /// Send a request for a chunk crc map virtual bool sendSingleChunkCRCRequest(const std::string& peer_id,const std::string& hash,uint32_t chunk_number) = 0; /// Send a chunk crc map @@ -94,11 +90,6 @@ class ftDataRecv /// Send a chunk map virtual bool recvChunkMap(const std::string& peer_id,const std::string& hash,const CompressedChunkMap& cmap,bool is_client) = 0; - /// Send a request for a chunk map - virtual bool recvCRC32MapRequest(const std::string& peer_id,const std::string& hash) = 0; - - /// Send a chunk map - virtual bool recvCRC32Map(const std::string& peer_id,const std::string& hash,const CRC32Map& crcmap) = 0; virtual bool recvSingleChunkCRCRequest(const std::string& peer_id,const std::string& hash,uint32_t chunk_id) = 0; virtual bool recvSingleChunkCRC(const std::string& peer_id,const std::string& hash,uint32_t chunk_id,const Sha1CheckSum& sum) = 0; diff --git a/libretroshare/src/ft/ftdatamultiplex.cc b/libretroshare/src/ft/ftdatamultiplex.cc index 802dbb6d3..031d6c917 100644 --- a/libretroshare/src/ft/ftdatamultiplex.cc +++ b/libretroshare/src/ft/ftdatamultiplex.cc @@ -59,7 +59,7 @@ const uint32_t FT_DATA = 0x0001; // data cuhnk to be stored const uint32_t FT_DATA_REQ = 0x0002; // data request to be treated const uint32_t FT_CLIENT_CHUNK_MAP_REQ = 0x0003; // chunk map request to be treated by client const uint32_t FT_SERVER_CHUNK_MAP_REQ = 0x0004; // chunk map request to be treated by server -const uint32_t FT_CRC32MAP_REQ = 0x0005; // crc32 map request to be treated by server +//const uint32_t FT_CRC32MAP_REQ = 0x0005; // crc32 map request to be treated by server const uint32_t FT_CLIENT_CHUNK_CRC_REQ = 0x0006; // chunk sha1 crc request to be treated ftRequest::ftRequest(uint32_t type, std::string peerId, std::string hash, uint64_t size, uint64_t offset, uint32_t chunk, void *data) @@ -272,19 +272,6 @@ bool ftDataMultiplex::recvChunkMapRequest(const std::string& peerId, const std:: return true; } -bool ftDataMultiplex::recvCRC32MapRequest(const std::string& peerId, const std::string& hash) -{ -#ifdef MPLEX_DEBUG - std::cerr << "ftDataMultiplex::recvChunkMapRequest() Server Recv"; - std::cerr << std::endl; -#endif - /* Store in Queue */ - RsStackMutex stack(dataMtx); /******* LOCK MUTEX ******/ - - mRequestQueue.push_back(ftRequest(FT_CRC32MAP_REQ,peerId,hash,0,0,0,NULL)); - - return true; -} bool ftDataMultiplex::recvSingleChunkCRCRequest(const std::string& peerId, const std::string& hash,uint32_t chunk_number) { #ifdef MPLEX_DEBUG @@ -298,27 +285,6 @@ bool ftDataMultiplex::recvSingleChunkCRCRequest(const std::string& peerId, const return true; } -class CRC32Thread: public RsThread -{ - public: - CRC32Thread(ftDataMultiplex *dataplex,const std::string& peerId,const std::string& hash) - : _plex(dataplex),_finished(false),_peerId(peerId),_hash(hash) {} - - virtual void run() - { -#ifdef MPLEX_DEBUG - std::cerr << "CRC32Thread is running for file " << _hash << std::endl; -#endif - _plex->computeAndSendCRC32Map(_peerId,_hash) ; - _finished = true ; - } - bool finished() { return _finished ; } - private: - ftDataMultiplex *_plex ; - bool _finished ; - std::string _peerId ; - std::string _hash ; -}; /*********** BACKGROUND THREAD OPERATIONS ***********/ bool ftDataMultiplex::workQueued() @@ -340,7 +306,6 @@ bool ftDataMultiplex::workQueued() bool ftDataMultiplex::doWork() { bool doRequests = true; - time_t now = time(NULL) ; /* Handle All the current Requests */ while(doRequests) @@ -395,14 +360,6 @@ bool ftDataMultiplex::doWork() handleRecvServerChunkMapRequest(req.mPeerId,req.mHash) ; break ; - case FT_CRC32MAP_REQ: -#ifdef MPLEX_DEBUG - std::cerr << "ftDataMultiplex::doWork() Handling FT_CLIENT_CRC32_MAP_REQ"; - std::cerr << std::endl; -#endif - handleRecvCRC32MapRequest(req.mPeerId,req.mHash) ; - break ; - case FT_CLIENT_CHUNK_CRC_REQ: #ifdef MPLEX_DEBUG std::cerr << "ftDataMultiplex::doWork() Handling FT_CLIENT_CHUNK_CRC_REQ"; @@ -420,47 +377,6 @@ bool ftDataMultiplex::doWork() } } - // Look for potentially finished CRC32Map threads, and destroys them. - - { - RsStackMutex stack(dataMtx); /******* LOCK MUTEX ******/ - - for(std::list::iterator lit(_crc32map_threads.begin());lit!=_crc32map_threads.end();) - if((*lit)->finished()) - { - std::cerr << "ftDataMultiplex::doWork: thread " << *lit << " ended. Deleting it." << std::endl; - (*lit)->join() ; - delete (*lit) ; - std::list::iterator tmp(lit) ; - ++lit ; - _crc32map_threads.erase(tmp) ; - } - else - { - std::cerr << "ftDataMultiplex::doWork: thread " << *lit << " still working. Not quitting it." << std::endl; - ++lit ; - } - - // Take the opportunity to cleanup the list, so that it cannot grow indefinitely -#ifdef MPLEX_DEBUG - std::cerr << "ftDataMultiplex::doWork: Cleaning up list of cached maps." << std::endl ; -#endif - - // Keep CRC32 maps in cache for 30 mins max. - // - for(std::map >::iterator it = _cached_crc32maps.begin();it!=_cached_crc32maps.end();) - if(it->second.first + 30*60 < now) - { - std::cerr << "Removing cached map for file " << it->first << " that was kept for too long now." << std::endl; - - std::map >::iterator tmp(it) ; - ++it ; - _cached_crc32maps.erase(tmp) ; - } - else - ++it ; - } - /* Only Handle One Search Per Period.... * Lower Priority */ @@ -582,27 +498,6 @@ bool ftDataMultiplex::dispatchReceivedChunkCheckSum() return true ; } -bool ftDataMultiplex::recvCRC32Map(const std::string& /*peerId*/, const std::string& hash,const CRC32Map& crc_map) -{ - RsStackMutex stack(dataMtx); /******* LOCK MUTEX ******/ - - std::map::iterator it = mClients.find(hash); - - if(it == mClients.end()) - { - std::cerr << "ftDataMultiplex::recvCRCMap() ERROR: No matching Client for CRC32map. This is an error. " << hash << " !" << std::endl; - /* error */ - return false; - } - -#ifdef MPLEX_DEBUG - std::cerr << "ftDataMultiplex::recvCRCMap() Passing crc map of file " << hash << ", to FT Module" << std::endl; -#endif - - (it->second).mModule->addCRC32Map(crc_map); - return true ; -} - // A chunk map has arrived. It can be two different situations: // - an uploader has sent his chunk map, so we need to store it in the corresponding ftFileProvider // - a source for a download has sent his chunk map, so we need to send it to the corresponding ftFileCreator. @@ -653,152 +548,6 @@ bool ftDataMultiplex::recvChunkMap(const std::string& peerId, const std::string& return false; } - -bool ftDataMultiplex::handleRecvCRC32MapRequest(const std::string& peerId, const std::string& hash) -{ - bool found = false ; - CRC32Map cmap ; - - // 1 - look into cache - -#ifdef MPLEX_DEBUG - std::cerr << "ftDataMultiplex::handleRecvChunkMapReq() : source " << peerId << " asked for CRC32 map for file " << hash << std::endl; -#endif - { - RsStackMutex stack(dataMtx); /******* LOCK MUTEX ******/ - std::map >::iterator it = _cached_crc32maps.find(hash) ; - - if(it != _cached_crc32maps.end()) - { - cmap = it->second.second ; - it->second.first = time(NULL) ; // update time stamp - found = true ; -#ifdef MPLEX_DEBUG - std::cerr << "ftDataMultiplex::handleRecvChunkMapReq() : CRC32 map found in cache !!" << std::endl; -#endif - - } - } - - if(found) - { -#ifdef MPLEX_DEBUG - std::cerr << "File CRC32 map was obtained successfully. Sending it." << std::endl ; -#endif - - mDataSend->sendCRC32Map(peerId,hash,cmap); - return true ; - } - else - { - std::cerr << "File CRC32 Not found. Computing it." << std::endl ; - - { - RsStackMutex stack(dataMtx); /******* LOCK MUTEX ******/ - if(_crc32map_threads.size() > 1) - { - std::cerr << "Too many threads already computing CRC32Maps (2 is the current maximum)! Giving up." << std::endl; - return false ; - } - } - - CRC32Thread *thread = new CRC32Thread(this,peerId,hash); - - { - RsStackMutex stack(dataMtx); /******* LOCK MUTEX ******/ - _crc32map_threads.push_back(thread) ; - } - thread->start() ; - return true ; - } -} - -bool ftDataMultiplex::computeAndSendCRC32Map(const std::string& peerId, const std::string& hash) -{ - bool found ; - std::map::iterator it ; - std::string filename ; - uint64_t filesize =0; - - // 1 - look into the list of servers - { - RsStackMutex stack(dataMtx); /******* LOCK MUTEX ******/ - - it = mServers.find(hash) ; - - if(it == mServers.end()) - found = false ; - } - - // 2 - if not found, create a server. - // - if(!found) - { -#ifdef MPLEX_DEBUG - std::cerr << "ftDataMultiplex::handleRecvChunkMapReq() ERROR: No matching file Provider for hash " << hash ; - std::cerr << std::endl; -#endif - if(!handleSearchRequest(peerId,hash)) - return false ; - -#ifdef MPLEX_DEBUG - std::cerr << "ftDataMultiplex::handleRecvChunkMapReq() A new file Provider has been made up for hash " << hash ; - std::cerr << std::endl; -#endif - } - - { - RsStackMutex stack(dataMtx); /******* LOCK MUTEX ******/ - it = mServers.find(hash) ; - - if(it == mServers.end()) // handleSearchRequest should have filled mServers[hash], but we have been off-mutex since, - { - std::cerr << "Could definitely not find a provider for file " << hash << ". Maybe the file does not exist?" << std::endl; - return false ; // so it's safer to check again. - } - else - { - filesize = it->second->fileSize() ; - filename = it->second->fileName() ; - } - } - -#ifdef MPLEX_DEBUG - std::cerr << "Computing CRC32Map for file " << filename << ", hash=" << hash << ", size=" << filesize << std::endl; -#endif - - FILE *fd = RsDirUtil::rs_fopen(filename.c_str(),"rb") ; - - if(fd == NULL) - { - std::cerr << "Could not open file " << filename << " for read!! CRC32Map computation cancelled." << std::endl ; - return false ; - } - - CRC32Map cmap ; - if(!RsDirUtil::crc32File(fd,filesize,ChunkMap::CHUNKMAP_FIXED_CHUNK_SIZE,cmap)) - { - std::cerr << "CRC32Map computation failed." << std::endl ; - fclose(fd) ; - return false ; - } - fclose(fd) ; - - { - RsStackMutex stack(dataMtx); /******* LOCK MUTEX ******/ - std::cerr << "File CRC32 was successfully computed. Storing it into cache." << std::endl ; - - _cached_crc32maps[hash] = std::pair(time(NULL),cmap) ; - } - -#ifdef MPLEX_DEBUG - std::cerr << "File CRC32 was successfully computed. Sending it." << std::endl ; -#endif - mDataSend->sendCRC32Map(peerId,hash,cmap); - - return true ; -} - bool ftDataMultiplex::handleRecvClientChunkMapRequest(const std::string& peerId, const std::string& hash) { CompressedChunkMap cmap ; @@ -1151,10 +900,6 @@ bool ftDataMultiplex::sendChunkMapRequest(const std::string& peer_id,const std:: { return mDataSend->sendChunkMapRequest(peer_id,hash,is_client); } -bool ftDataMultiplex::sendCRC32MapRequest(const std::string& peer_id,const std::string& hash) -{ - return mDataSend->sendCRC32MapRequest(peer_id,hash); -} bool ftDataMultiplex::sendSingleChunkCRCRequests(const std::string& hash, const std::vector& to_ask) { RsStackMutex stack(dataMtx); /******* LOCK MUTEX ******/ diff --git a/libretroshare/src/ft/ftdatamultiplex.h b/libretroshare/src/ft/ftdatamultiplex.h index 54cdae691..23bac4cf8 100644 --- a/libretroshare/src/ft/ftdatamultiplex.h +++ b/libretroshare/src/ft/ftdatamultiplex.h @@ -36,7 +36,6 @@ class ftTransferModule; class ftFileProvider; class ftFileCreator; class ftSearch; -class CRC32Thread; #include #include @@ -121,11 +120,6 @@ class ftDataMultiplex: public ftDataRecv, public RsQueueThread /* Server/client Send */ bool sendChunkMapRequest(const std::string& peerId, const std::string& hash,bool is_client) ; - /* Client Send */ - bool sendCRC32MapRequest(const std::string& peerId, const std::string& hash) ; - - /* called from a separate thread */ - bool computeAndSendCRC32Map(const std::string& peerId, const std::string& hash) ; /* called from a separate thread */ bool sendSingleChunkCRCRequests(const std::string& hash, const std::vector& to_ask) ; @@ -143,10 +137,6 @@ class ftDataMultiplex: public ftDataRecv, public RsQueueThread virtual bool recvChunkMapRequest(const std::string& peer_id,const std::string& hash,bool is_client) ; /// Receive a chunk map virtual bool recvChunkMap(const std::string& peer_id,const std::string& hash,const CompressedChunkMap& cmap,bool is_client) ; - /// Receive a CRC map - virtual bool recvCRC32Map(const std::string& peer_id,const std::string& hash,const CRC32Map& crc_map) ; - /// Receive a CRC map request - virtual bool recvCRC32MapRequest(const std::string& peer_id,const std::string& hash) ; virtual bool recvSingleChunkCRCRequest(const std::string& peer_id,const std::string& hash,uint32_t chunk_id) ; virtual bool recvSingleChunkCRC(const std::string& peer_id,const std::string& hash,uint32_t chunk_id,const Sha1CheckSum& sum) ; @@ -170,7 +160,6 @@ class ftDataMultiplex: public ftDataRecv, public RsQueueThread bool handleSearchRequest(const std::string& peerId, const std::string& hash); bool handleRecvClientChunkMapRequest(const std::string& peerId, const std::string& hash) ; bool handleRecvServerChunkMapRequest(const std::string& peerId, const std::string& hash) ; - bool handleRecvCRC32MapRequest(const std::string& peerId, const std::string& hash) ; bool handleRecvChunkCrcRequest(const std::string& peerId, const std::string& hash,uint32_t chunk_id) ; /* We end up doing the actual server job here */ @@ -185,9 +174,6 @@ class ftDataMultiplex: public ftDataRecv, public RsQueueThread std::list mSearchQueue; // std::map mUnknownHashs; - std::list _crc32map_threads ; - std::map > _cached_crc32maps ; - std::map _cached_sha1maps ; // one cache entry per file hash. Handled dynamically. ftDataSend *mDataSend; diff --git a/libretroshare/src/ft/ftserver.cc b/libretroshare/src/ft/ftserver.cc index 8c802d5e6..933d99c55 100644 --- a/libretroshare/src/ft/ftserver.cc +++ b/libretroshare/src/ft/ftserver.cc @@ -49,6 +49,7 @@ const int ftserverzone = 29539; #include "pqi/pqi.h" #include "pqi/p3linkmgr.h" +#include "serialiser/rsfiletransferitems.h" #include "serialiser/rsserviceids.h" /*** @@ -56,16 +57,19 @@ const int ftserverzone = 29539; * #define DEBUG_TICK 1 ***/ +static const time_t FILE_TRANSFER_LOW_PRIORITY_TASKS_PERIOD = 5 ; // low priority tasks handling every 5 seconds + /* Setup */ ftServer::ftServer(p3PeerMgr *pm, p3LinkMgr *lm) - : mP3iface(NULL), mPeerMgr(pm), + : p3Service(RS_SERVICE_TYPE_FILE_TRANSFER), + mPeerMgr(pm), mLinkMgr(lm), mCacheStrapper(NULL), mFiStore(NULL), mFiMon(NULL), mFtController(NULL), mFtExtra(NULL), mFtDataplex(NULL), mFtSearch(NULL), srvMutex("ftServer") { - mCacheStrapper = new ftCacheStrapper(lm); + mCacheStrapper = new ftCacheStrapper(lm); } void ftServer::setConfigDirectory(std::string path) @@ -85,11 +89,6 @@ void ftServer::setConfigDirectory(std::string path) RsDirUtil::checkCreateDirectory(remotecachedir) ; } -void ftServer::setP3Interface(P3Interface *pqi) -{ - mP3iface = pqi; -} - /* Control Interface */ /* add Config Items (Extra, Controller) */ @@ -179,16 +178,10 @@ void ftServer::StartupThreads() /* Dataplex */ mFtDataplex->start(); - - /* start own thread */ - start(); } void ftServer::StopThreads() { - /* stop own thread */ - join(); - /* stop Dataplex */ mFtDataplex->join(); @@ -225,31 +218,22 @@ CacheTransfer *ftServer::getCacheTransfer() return mFtController; } -void ftServer::run() + +/***************************************************************/ +/********************** RsFiles Interface **********************/ +/***************************************************************/ + +/***************************************************************/ +/********************** Controller Access **********************/ +/***************************************************************/ + +bool ftServer::ResumeTransfers() { - while(isRunning()) - { - mFtDataplex->deleteUnusedServers() ; - mFtDataplex->handlePendingCrcRequests() ; - mFtDataplex->dispatchReceivedChunkCheckSum() ; -#ifdef WIN32 - Sleep(5000); -#else - sleep(5); -#endif - } + mFtController->activate(); + + return true; } - - /***************************************************************/ - /********************** RsFiles Interface **********************/ - /***************************************************************/ - - - /***************************************************************/ - /********************** Controller Access **********************/ - /***************************************************************/ - bool ftServer::checkHash(const std::string& hash,std::string& error_string) { static const uint32_t HASH_LENGTH = 40 ; @@ -897,7 +881,7 @@ bool ftServer::sendDataRequest(const std::string& peerId, const std::string& has { /* create a packet */ /* push to networking part */ - RsFileRequest *rfi = new RsFileRequest(); + RsFileTransferDataRequestItem *rfi = new RsFileTransferDataRequestItem(); /* id */ rfi->PeerId(peerId); @@ -910,7 +894,7 @@ bool ftServer::sendDataRequest(const std::string& peerId, const std::string& has rfi->fileoffset = offset; /* ftr->offset; */ rfi->chunksize = chunksize; /* ftr->chunk; */ - mP3iface->SendFileRequest(rfi); + sendItem(rfi); } return true; @@ -927,7 +911,7 @@ bool ftServer::sendChunkMapRequest(const std::string& peerId,const std::string& { /* create a packet */ /* push to networking part */ - RsFileChunkMapRequest *rfi = new RsFileChunkMapRequest(); + RsFileTransferChunkMapRequestItem *rfi = new RsFileTransferChunkMapRequestItem(); /* id */ rfi->PeerId(peerId); @@ -936,7 +920,7 @@ bool ftServer::sendChunkMapRequest(const std::string& peerId,const std::string& rfi->hash = hash; /* ftr->hash; */ rfi->is_client = is_client ; - mP3iface->SendFileChunkMapRequest(rfi); + sendItem(rfi); } return true ; @@ -954,7 +938,7 @@ bool ftServer::sendChunkMap(const std::string& peerId,const std::string& hash,co { /* create a packet */ /* push to networking part */ - RsFileChunkMap *rfi = new RsFileChunkMap(); + RsFileTransferChunkMapItem *rfi = new RsFileTransferChunkMapItem(); /* id */ rfi->PeerId(peerId); @@ -964,36 +948,12 @@ bool ftServer::sendChunkMap(const std::string& peerId,const std::string& hash,co rfi->is_client = is_client; /* ftr->hash; */ rfi->compressed_map = map; /* ftr->hash; */ - mP3iface->SendFileChunkMap(rfi); + sendItem(rfi); } return true ; } -bool ftServer::sendCRC32MapRequest(const std::string& peerId,const std::string& hash) -{ - if(mTurtleRouter->isTurtlePeer(peerId)) - { - RsTurtleFileCrcRequestItem *item = new RsTurtleFileCrcRequestItem; - mTurtleRouter->sendTurtleData(peerId,item) ; - } - else - { - /* create a packet */ - /* push to networking part */ - RsFileCRC32MapRequest *rfi = new RsFileCRC32MapRequest(); - - /* id */ - rfi->PeerId(peerId); - - /* file info */ - rfi->hash = hash; /* ftr->hash; */ - - mP3iface->SendFileCRC32MapRequest(rfi); - } - - return true ; -} bool ftServer::sendSingleChunkCRCRequest(const std::string& peerId,const std::string& hash,uint32_t chunk_number) { if(mTurtleRouter->isTurtlePeer(peerId)) @@ -1007,7 +967,7 @@ bool ftServer::sendSingleChunkCRCRequest(const std::string& peerId,const std::st { /* create a packet */ /* push to networking part */ - RsFileSingleChunkCrcRequest *rfi = new RsFileSingleChunkCrcRequest(); + RsFileTransferSingleChunkCrcRequestItem *rfi = new RsFileTransferSingleChunkCrcRequestItem(); /* id */ rfi->PeerId(peerId); @@ -1016,39 +976,12 @@ bool ftServer::sendSingleChunkCRCRequest(const std::string& peerId,const std::st rfi->hash = hash; /* ftr->hash; */ rfi->chunk_number = chunk_number ; - mP3iface->SendFileSingleChunkCrcRequest(rfi); + sendItem(rfi); } return true ; } -bool ftServer::sendCRC32Map(const std::string& peerId,const std::string& hash,const CRC32Map& crcmap) -{ - if(mTurtleRouter->isTurtlePeer(peerId)) - { - RsTurtleFileCrcItem *item = new RsTurtleFileCrcItem ; - item->crc_map = crcmap ; - - mTurtleRouter->sendTurtleData(peerId,item) ; - } - else - { - /* create a packet */ - /* push to networking part */ - RsFileCRC32Map *rfi = new RsFileCRC32Map(); - - /* id */ - rfi->PeerId(peerId); - - /* file info */ - rfi->hash = hash; /* ftr->hash; */ - rfi->crc_map = crcmap; /* ftr->hash; */ - - mP3iface->SendFileCRC32Map(rfi); - } - - return true ; -} bool ftServer::sendSingleChunkCRC(const std::string& peerId,const std::string& hash,uint32_t chunk_number,const Sha1CheckSum& crc) { if(mTurtleRouter->isTurtlePeer(peerId)) @@ -1063,7 +996,7 @@ bool ftServer::sendSingleChunkCRC(const std::string& peerId,const std::string& h { /* create a packet */ /* push to networking part */ - RsFileSingleChunkCrc *rfi = new RsFileSingleChunkCrc(); + RsFileTransferSingleChunkCrcItem *rfi = new RsFileTransferSingleChunkCrcItem(); /* id */ rfi->PeerId(peerId); @@ -1073,16 +1006,12 @@ bool ftServer::sendSingleChunkCRC(const std::string& peerId,const std::string& h rfi->check_sum = crc; rfi->chunk_number = chunk_number; - mP3iface->SendFileSingleChunkCrc(rfi); + sendItem(rfi); } return true ; } -//const uint32_t MAX_FT_CHUNK = 32 * 1024; /* 32K */ -//const uint32_t MAX_FT_CHUNK = 16 * 1024; /* 16K */ -const uint32_t MAX_FT_CHUNK = 8 * 1024; /* 16K */ - /* Server Send */ bool ftServer::sendData(const std::string& peerId, const std::string& hash, uint64_t size, uint64_t baseoffset, uint32_t chunksize, void *data) { @@ -1103,6 +1032,11 @@ bool ftServer::sendData(const std::string& peerId, const std::string& hash, uint while(tosend > 0) { + //static const uint32_t MAX_FT_CHUNK = 32 * 1024; /* 32K */ + //static const uint32_t MAX_FT_CHUNK = 16 * 1024; /* 16K */ + // + static const uint32_t MAX_FT_CHUNK = 8 * 1024; /* 16K */ + /* workout size */ chunk = MAX_FT_CHUNK; if (chunk > tosend) @@ -1132,7 +1066,7 @@ bool ftServer::sendData(const std::string& peerId, const std::string& hash, uint } else { - RsFileData *rfd = new RsFileData(); + RsFileTransferDataItem *rfd = new RsFileTransferDataItem(); /* set id */ rfd->PeerId(peerId); @@ -1150,7 +1084,7 @@ bool ftServer::sendData(const std::string& peerId, const std::string& hash, uint /* file data */ rfd->fd.binData.setBinData( &(((uint8_t *) data)[offset]), chunk); - mP3iface->SendFileData(rfd); + sendItem(rfd); /* print the data pointer */ #ifdef SERVER_DEBUG @@ -1173,6 +1107,8 @@ bool ftServer::sendData(const std::string& peerId, const std::string& hash, uint return true; } +// Dont delete the item. The client (p3turtle) is doing it after calling this. +// void ftServer::receiveTurtleData(RsTurtleGenericTunnelItem *i, const std::string& hash, const std::string& virtual_peer_id, @@ -1207,24 +1143,11 @@ void ftServer::receiveTurtleData(RsTurtleGenericTunnelItem *i, case RS_TURTLE_SUBTYPE_FILE_MAP_REQUEST: { - RsTurtleFileMapRequestItem *item = dynamic_cast(i) ; + //RsTurtleFileMapRequestItem *item = dynamic_cast(i) ; getMultiplexer()->recvChunkMapRequest(virtual_peer_id,hash,direction == RsTurtleGenericTunnelItem::DIRECTION_CLIENT) ; } break ; - case RS_TURTLE_SUBTYPE_FILE_CRC : - { - RsTurtleFileCrcItem *item = dynamic_cast(i) ; - getMultiplexer()->recvCRC32Map(virtual_peer_id,hash,item->crc_map) ; - } - break ; - - case RS_TURTLE_SUBTYPE_FILE_CRC_REQUEST: - { - getMultiplexer()->recvCRC32MapRequest(virtual_peer_id,hash) ; - } - break ; - case RS_TURTLE_SUBTYPE_CHUNK_CRC : { RsTurtleChunkCrcItem *item = dynamic_cast(i) ; @@ -1243,358 +1166,180 @@ void ftServer::receiveTurtleData(RsTurtleGenericTunnelItem *i, } } - /* NB: The rsCore lock must be activated before calling this. * This Lock should be moved lower into the system... * most likely destination is in ftServer. */ int ftServer::tick() { - rslog(RSL_DEBUG_BASIC, ftserverzone, - "filedexserver::tick()"); + bool moreToTick = false ; - if (mP3iface == NULL) + moreToTick = handleIncoming() || moreToTick ; // order is important!! + moreToTick = handleCacheData() || moreToTick ; + + static time_t last_law_priority_tasks_handling_time = 0 ; + time_t now = time(NULL) ; + + if(last_law_priority_tasks_handling_time + FILE_TRANSFER_LOW_PRIORITY_TASKS_PERIOD < now) { -#ifdef SERVER_DEBUG - std::cerr << "ftServer::tick() ERROR: mP3iface == NULL"; -#endif + last_law_priority_tasks_handling_time = now ; - rslog(RSL_DEBUG_BASIC, ftserverzone, - "filedexserver::tick() Invalid Interface()"); - - return 1; + mFtDataplex->deleteUnusedServers() ; + mFtDataplex->handlePendingCrcRequests() ; + mFtDataplex->dispatchReceivedChunkCheckSum() ; } - int moreToTick = 0; - - if (0 < mP3iface -> tick()) - { - moreToTick = 1; -#ifdef DEBUG_TICK - std::cerr << "filedexserver::tick() moreToTick from mP3iface" << std::endl; -#endif - } - - if (0 < handleInputQueues()) - { - moreToTick = 1; -#ifdef DEBUG_TICK - std::cerr << "filedexserver::tick() moreToTick from InputQueues" << std::endl; -#endif - } - return moreToTick; -} - - -// This function needs to be divided up. -bool ftServer::handleInputQueues() -{ - bool moreToTick = false; - - if (handleCacheData()) - moreToTick = true; - - if (handleFileData()) - moreToTick = true; - return moreToTick; } -bool ftServer::handleCacheData() +bool ftServer::handleCacheData() { - // get all the incoming results.. and print to the screen. - RsCacheRequest *cr; - RsCacheItem *ci; + std::list > cacheUpdates; + std::list >::iterator it; + int i=0 ; - // Loop through Search Results. - int i = 0; - int i_init = 0; - -#ifdef SERVER_DEBUG - //std::cerr << "ftServer::handleCacheData()" << std::endl; -#endif - while((ci = mP3iface -> GetSearchResult()) != NULL) + mCacheStrapper->getCacheUpdates(cacheUpdates); + for(it = cacheUpdates.begin(); it != cacheUpdates.end(); it++) { + /* construct reply */ + RsFileTransferCacheItem *ci = new RsFileTransferCacheItem(); + + /* id from incoming */ + ci -> PeerId(it->first); + + ci -> file.hash = (it->second).hash; + ci -> file.name = (it->second).name; + ci -> file.path = ""; // (it->second).path; + ci -> file.filesize = (it->second).size; + ci -> cacheType = (it->second).cid.type; + ci -> cacheSubId = (it->second).cid.subid; #ifdef SERVER_DEBUG - std::cerr << "ftServer::handleCacheData() Recvd SearchResult (CacheResponse!)" << std::endl; - std::string out; - if (i++ == i_init) - { - out += "Recieved Search Results:\n"; - } - ci -> print_string(out); - rslog(RSL_DEBUG_BASIC, ftserverzone, out); + std::string out2 = "Outgoing CacheStrapper Update -> RsCacheItem:\n"; + ci -> print_string(out2); + std::cerr << out2 << std::endl; #endif - /* these go to the CacheStrapper! */ - CacheData data; - data.pid = ci->PeerId(); - data.cid = CacheId(ci->cacheType, ci->cacheSubId); - data.path = ci->file.path; - data.name = ci->file.name; - data.hash = ci->file.hash; - data.size = ci->file.filesize; - data.recvd = time(NULL) ; + sendItem(ci); - mCacheStrapper->recvCacheResponse(data, time(NULL)); - - delete ci; + i++; } - // now requested Searches. - i_init = i; - while((cr = mP3iface -> RequestedSearch()) != NULL) - { -#ifdef SERVER_DEBUG - /* just delete these */ - std::string out = "Requested Search:\n"; - cr -> print_string(out); - rslog(RSL_DEBUG_BASIC, ftserverzone, out); -#endif - delete cr; - } - - - // Now handle it replacement (pushed cache results) - { - std::list > cacheUpdates; - std::list >::iterator it; - - mCacheStrapper->getCacheUpdates(cacheUpdates); - for(it = cacheUpdates.begin(); it != cacheUpdates.end(); it++) - { - /* construct reply */ - RsCacheItem *ci = new RsCacheItem(); - - /* id from incoming */ - ci -> PeerId(it->first); - - ci -> file.hash = (it->second).hash; - ci -> file.name = (it->second).name; - ci -> file.path = ""; // (it->second).path; - ci -> file.filesize = (it->second).size; - ci -> cacheType = (it->second).cid.type; - ci -> cacheSubId = (it->second).cid.subid; - -#ifdef SERVER_DEBUG - std::string out2 = "Outgoing CacheStrapper Update -> RsCacheItem:\n"; - ci -> print_string(out2); - std::cerr << out2 << std::endl; -#endif - - //rslog(RSL_DEBUG_BASIC, ftserverzone, out2.str()); - mP3iface -> SendSearchResult(ci); - - i++; - } - } - return (i > 0); + return i>0 ; } - -bool ftServer::handleFileData() +int ftServer::handleIncoming() { // now File Input. - RsFileRequest *fr; - RsFileData *fd; - RsFileChunkMapRequest *fcmr; - RsFileChunkMap *fcm; - RsFileCRC32MapRequest *fccrcmr; - RsFileCRC32Map *fccrcm; - RsFileSingleChunkCrcRequest *fscrcr; - RsFileSingleChunkCrc *fscrc; + int nhandled = 0 ; - int i_init = 0; - int i = 0; + RsItem *item = NULL ; - i_init = i; - while((fr = mP3iface -> GetFileRequest()) != NULL ) + while(NULL != (item = recvItem())) { -#ifdef SERVER_DEBUG - std::cerr << "ftServer::handleFileData() Recvd ftFiler Request" << std::endl; - std::string out; - if (i == i_init) + nhandled++ ; + + switch(item->PacketSubType()) { - out += "Incoming(Net) File Item:\n"; - } - fr -> print_string(out); - rslog(RSL_DEBUG_BASIC, ftserverzone, out); -#endif - - i++; /* count */ - mFtDataplex->recvDataRequest(fr->PeerId(), - fr->file.hash, fr->file.filesize, - fr->fileoffset, fr->chunksize); - -FileInfo(ffr); - delete fr; - } - - // now File Data. - i_init = i; - while((fd = mP3iface -> GetFileData()) != NULL ) - { + case RS_PKT_SUBTYPE_FT_DATA_REQUEST: + { + RsFileTransferDataRequestItem *f = dynamic_cast(item) ; #ifdef SERVER_DEBUG - std::cerr << "ftServer::handleFileData() Recvd ftFiler Data" << std::endl; - std::cerr << "hash: " << fd->fd.file.hash; - std::cerr << " length: " << fd->fd.binData.bin_len; - std::cerr << " data: " << fd->fd.binData.bin_data; - std::cerr << std::endl; - - std::string out; - if (i == i_init) - { - out += "Incoming(Net) File Data:\n"; - } - fd -> print_string(out); - rslog(RSL_DEBUG_BASIC, ftserverzone, out); + std::cerr << "ftServer::handleIncoming: received data request for hash " << f->file.hash << ", offset=" << f->fileoffset << ", chunk size=" << f->chunksize << std::endl; #endif - i++; /* count */ + mFtDataplex->recvDataRequest(f->PeerId(), f->file.hash, f->file.filesize, f->fileoffset, f->chunksize); + } + break ; - /* incoming data */ - mFtDataplex->recvData(fd->PeerId(), - fd->fd.file.hash, fd->fd.file.filesize, - fd->fd.file_offset, - fd->fd.binData.bin_len, - fd->fd.binData.bin_data); - - /* we've stolen the data part -> so blank before delete - */ - fd->fd.binData.TlvShallowClear(); - delete fd; - } - // now file chunkmap requests - i_init = i; - while((fcmr = mP3iface -> GetFileChunkMapRequest()) != NULL ) - { + case RS_PKT_SUBTYPE_FT_DATA: + { + RsFileTransferDataItem *f = dynamic_cast(item) ; #ifdef SERVER_DEBUG - std::cerr << "ftServer::handleFileData() Recvd ChunkMap request" << std::endl; - std::string out; - if (i == i_init) - { - out += "Incoming(Net) File Data:\n"; - } - fcmr -> print_string(out); - rslog(RSL_DEBUG_BASIC, ftserverzone, out); + std::cerr << "ftServer::handleIncoming: received data for hash " << f->fd.file.hash << ", offset=" << f->fd.file_offset << ", chunk size=" << f->fd.binData.bin_len << std::endl; #endif - i++; /* count */ + mFtDataplex->recvData(f->PeerId(), f->fd.file.hash, f->fd.file.filesize, f->fd.file_offset, f->fd.binData.bin_len, f->fd.binData.bin_data); - /* incoming data */ - mFtDataplex->recvChunkMapRequest(fcmr->PeerId(), fcmr->hash,fcmr->is_client) ; + /* we've stolen the data part -> so blank before delete + */ + f->fd.binData.TlvShallowClear(); + } + break ; - delete fcmr; - } - // now file chunkmaps - i_init = i; - while((fcm = mP3iface -> GetFileChunkMap()) != NULL ) - { + case RS_PKT_SUBTYPE_FT_CHUNK_MAP_REQUEST: + { + RsFileTransferChunkMapRequestItem *f = dynamic_cast(item) ; #ifdef SERVER_DEBUG - std::cerr << "ftServer::handleFileData() Recvd ChunkMap request" << std::endl; - std::string out; - if (i == i_init) - { - out += "Incoming(Net) File Data:\n"; - } - fcm -> print_string(out); - rslog(RSL_DEBUG_BASIC, ftserverzone, out); + std::cerr << "ftServer::handleIncoming: received chunkmap request for hash " << f->hash << ", client=" << f->is_client << std::endl; #endif - i++; /* count */ + mFtDataplex->recvChunkMapRequest(f->PeerId(), f->hash,f->is_client) ; + } + break ; - /* incoming data */ - mFtDataplex->recvChunkMap(fcm->PeerId(), fcm->hash,fcm->compressed_map,fcm->is_client) ; - - delete fcm; - } - // now file chunkmap requests - i_init = i; - while((fccrcmr = mP3iface -> GetFileCRC32MapRequest()) != NULL ) - { + case RS_PKT_SUBTYPE_FT_CHUNK_MAP: + { + RsFileTransferChunkMapItem *f = dynamic_cast(item) ; #ifdef SERVER_DEBUG - std::cerr << "ftServer::handleFileData() Recvd ChunkMap request" << std::endl; - std::string out; - if (i == i_init) - { - out += "Incoming(Net) File Data:\n"; - } - fccrcmr -> print_string(out); - rslog(RSL_DEBUG_BASIC, ftserverzone, out); + std::cerr << "ftServer::handleIncoming: received chunkmap for hash " << f->hash << ", client=" << f->is_client << ", map=" << f->compressed_map << std::endl; #endif - i++; /* count */ + mFtDataplex->recvChunkMap(f->PeerId(), f->hash,f->compressed_map,f->is_client) ; + } + break ; - /* incoming data */ - mFtDataplex->recvCRC32MapRequest(fccrcmr->PeerId(), fccrcmr->hash) ; - - delete fccrcmr; - } - // now file chunkmaps - i_init = i; - while((fccrcm = mP3iface -> GetFileCRC32Map()) != NULL ) - { + case RS_PKT_SUBTYPE_FT_CHUNK_CRC_REQUEST: + { + RsFileTransferSingleChunkCrcRequestItem *f = dynamic_cast(item) ; #ifdef SERVER_DEBUG - std::cerr << "ftServer::handleFileData() Recvd ChunkMap request" << std::endl; - std::string out; - if (i == i_init) - { - out += "Incoming(Net) File Data:\n"; - } - fccrcm -> print_string(out); - rslog(RSL_DEBUG_BASIC, ftserverzone, out); + std::cerr << "ftServer::handleIncoming: received single chunk crc req for hash " << f->hash << ", chunk number=" << f->chunk_number << std::endl; #endif - i++; /* count */ + mFtDataplex->recvSingleChunkCRCRequest(f->PeerId(), f->hash,f->chunk_number) ; + } + break ; - /* incoming data */ - mFtDataplex->recvCRC32Map(fccrcm->PeerId(), fccrcm->hash,fccrcm->crc_map); - - delete fccrcm; - } - // now file chunk crc requests - i_init = i; - while((fscrcr = mP3iface -> GetFileSingleChunkCrcRequest()) != NULL ) - { + case RS_PKT_SUBTYPE_FT_CHUNK_CRC: + { + RsFileTransferSingleChunkCrcItem *f = dynamic_cast(item) ; #ifdef SERVER_DEBUG - std::cerr << "ftServer::handleFileData() Recvd ChunkMap request" << std::endl; - std::string out; - if (i == i_init) - { - out += "Incoming(Net) File CRC Request:\n"; - } - fscrcr -> print_string(out); - rslog(RSL_DEBUG_BASIC, ftserverzone, out); + std::cerr << "ftServer::handleIncoming: received single chunk crc req for hash " << f->hash << ", chunk number=" << f->chunk_number << ", checksum = " << f->check_sum << std::endl; #endif - i++; /* count */ + mFtDataplex->recvSingleChunkCRC(f->PeerId(), f->hash,f->chunk_number,f->check_sum); + } + break ; - /* incoming data */ - mFtDataplex->recvSingleChunkCRCRequest(fscrcr->PeerId(), fscrcr->hash,fscrcr->chunk_number) ; - - delete fscrcr; - } - // now file chunkmaps - i_init = i; - while((fscrc = mP3iface -> GetFileSingleChunkCrc()) != NULL ) - { + case RS_PKT_SUBTYPE_FT_CACHE_ITEM: + { + RsFileTransferCacheItem *ci = dynamic_cast(item) ; #ifdef SERVER_DEBUG - std::cerr << "ftServer::handleFileData() Recvd ChunkMap request" << std::endl; - std::string out; - if (i == i_init) - { - out += "Incoming(Net) File Data:\n"; - } - fscrc -> print_string(out); - rslog(RSL_DEBUG_BASIC, ftserverzone, out); + std::cerr << "ftServer::handleIncoming: received cache item hash=" << ci->file.hash << ". from peer " << ci->PeerId() << std::ednl; #endif - i++; /* count */ + /* these go to the CacheStrapper! */ + CacheData data; + data.pid = ci->PeerId(); + data.cid = CacheId(ci->cacheType, ci->cacheSubId); + data.path = ci->file.path; + data.name = ci->file.name; + data.hash = ci->file.hash; + data.size = ci->file.filesize; + data.recvd = time(NULL) ; - /* incoming data */ - mFtDataplex->recvSingleChunkCRC(fscrc->PeerId(), fscrc->hash,fscrc->chunk_number,fscrc->check_sum); + mCacheStrapper->recvCacheResponse(data, time(NULL)); + } + break ; - delete fscrcr; + case RS_PKT_SUBTYPE_FT_CACHE_REQUEST: + { + // do nothing + RsFileTransferCacheRequestItem *cr = dynamic_cast(item) ; +#ifdef SERVER_DEBUG + std::cerr << "ftServer::handleIncoming: received cache request from peer " << cr->PeerId() << std::ednl; +#endif + } + break ; + } + + delete item ; } - if (i > 0) - { - return 1; - } - return 0; + + return nhandled; } /********************************** @@ -1614,10 +1359,3 @@ bool ftServer::addConfiguration(p3ConfigMgr *cfgmgr) return true; } -bool ftServer::ResumeTransfers() -{ - mFtController->activate(); - - return true; -} - diff --git a/libretroshare/src/ft/ftserver.h b/libretroshare/src/ft/ftserver.h index 20e1b48ed..e621268f5 100644 --- a/libretroshare/src/ft/ftserver.h +++ b/libretroshare/src/ft/ftserver.h @@ -45,6 +45,7 @@ #include "ft/ftdata.h" #include "turtle/turtleclientservice.h" +#include "services/p3service.h" #include "retroshare/rsfiles.h" //#include "dbase/cachestrapper.h" @@ -73,7 +74,7 @@ class ftDwlQueue; class p3PeerMgr; class p3LinkMgr; -class ftServer: public RsFiles, public ftDataSend, public RsTurtleClientService, public RsThread +class ftServer: public p3Service, public RsFiles, public ftDataSend, public RsTurtleClientService { public: @@ -87,8 +88,6 @@ class ftServer: public RsFiles, public ftDataSend, public RsTurtleClientService, /* Assign important variables */ void setConfigDirectory(std::string path); - void setP3Interface(P3Interface *pqi); - /* add Config Items (Extra, Controller) */ void addConfigComponents(p3ConfigMgr *mgr); @@ -102,12 +101,6 @@ class ftServer: public RsFiles, public ftDataSend, public RsTurtleClientService, void SetupFtServer(NotifyBase *cb); void connectToTurtleRouter(p3turtle *p) ; - void StartupThreads(); - void StopThreads(); - - /* own thread */ - virtual void run(); - // Checks that the given hash is well formed. Used to chase // string bugs. static bool checkHash(const std::string& hash,std::string& error_string) ; @@ -126,6 +119,9 @@ class ftServer: public RsFiles, public ftDataSend, public RsTurtleClientService, /************** (Implements RsFiles) ***************************/ /***************************************************************/ + void StartupThreads(); + void StopThreads(); + // member access ftDataMultiplex *getMultiplexer() const { return mFtDataplex ; } @@ -239,8 +235,6 @@ class ftServer: public RsFiles, public ftDataSend, public RsTurtleClientService, virtual bool sendDataRequest(const std::string& peerId, const std::string& hash, uint64_t size, uint64_t offset, uint32_t chunksize); virtual bool sendChunkMapRequest(const std::string& peer_id,const std::string& hash,bool is_client) ; virtual bool sendChunkMap(const std::string& peer_id,const std::string& hash,const CompressedChunkMap& cmap,bool is_client) ; - virtual bool sendCRC32MapRequest(const std::string&, const std::string&) ; - virtual bool sendCRC32Map(const std::string&, const std::string&, const CRC32Map&) ; virtual bool sendSingleChunkCRCRequest(const std::string& peer_id,const std::string& hash,uint32_t chunk_number) ; virtual bool sendSingleChunkCRC(const std::string& peer_id,const std::string& hash,uint32_t chunk_number,const Sha1CheckSum& crc) ; @@ -251,17 +245,12 @@ class ftServer: public RsFiles, public ftDataSend, public RsTurtleClientService, bool addConfiguration(p3ConfigMgr *cfgmgr); bool ResumeTransfers(); - private: - bool handleInputQueues(); - bool handleCacheData(); - bool handleFileData(); - /******************* p3 Config Overload ************************/ protected: /* Key Functions to be overloaded for Full Configuration */ virtual RsSerialiser *setupSerialiser(); virtual bool saveList(bool &cleanup, std::list&); - virtual bool loadList(std::list& load); + virtual bool loadList(std::list& load); private: bool loadConfigMap(std::map &configMap); @@ -269,6 +258,10 @@ class ftServer: public RsFiles, public ftDataSend, public RsTurtleClientService, /*************************** p3 Config Overload ********************/ + protected: + int handleIncoming() ; + bool handleCacheData() ; + private: /**** INTERNAL FUNCTIONS ***/ @@ -280,9 +273,6 @@ class ftServer: public RsFiles, public ftDataSend, public RsTurtleClientService, /* no need for Mutex protection - * as each component is protected independently. */ - - P3Interface *mP3iface; /* XXX THIS NEEDS PROTECTION */ - p3PeerMgr *mPeerMgr; p3LinkMgr *mLinkMgr; @@ -296,7 +286,6 @@ class ftServer: public RsFiles, public ftDataSend, public RsTurtleClientService, ftDataMultiplex *mFtDataplex; p3turtle *mTurtleRouter ; - ftFileSearch *mFtSearch; ftDwlQueue *mFtDwlQueue; @@ -305,7 +294,6 @@ class ftServer: public RsFiles, public ftDataSend, public RsTurtleClientService, std::string mConfigPath; std::string mDownloadPath; std::string mPartialsPath; - }; diff --git a/libretroshare/src/ft/fttransfermodule.cc b/libretroshare/src/ft/fttransfermodule.cc index c6d911a7d..1f18961aa 100644 --- a/libretroshare/src/ft/fttransfermodule.cc +++ b/libretroshare/src/ft/fttransfermodule.cc @@ -515,9 +515,6 @@ int ftTransferModule::tick() case FT_TM_FLAG_CHECKING: // Check if file hash matches the hashed data checkFile() ; break ; - case FT_TM_FLAG_CHUNK_CRC: // File is waiting for CRC32 map. Check if received, and re-set matched chunks - checkCRC() ; - break ; default: break; } @@ -633,171 +630,6 @@ void ftTransferModule::forceCheck() mFileStatus.stat = ftFileStatus::PQIFILE_DOWNLOADING; } -bool ftTransferModule::checkCRC() -{ - // We have a finite state machine here. - // - // The states are, for each chunk, and what should be done: - // DONT_HAVE - // -> ask for the chunk CRC - // ASKED - // -> do nothing - // RECEIVED - // -> check the chunk - // CHECKED - // -> do nothing - // - // CRCs are asked by group of CRC_REQUEST_MAX_SIZE chunks at a time. The response may contain a different - // number of CRCs, depending on the availability. - // - // Server side: - // - Only complete files can compute CRCs, as the CRCs of downloaded chunks in an unchecked file are un-verified. - // - CRCs of files are cached, so that they don't get computed twice. - // -#ifdef FT_DEBUG - std::cerr << "ftTransferModule::checkCRC(): looking for CRC32 map." << std::endl ; -#endif - - // Loop over chunks. Collect the ones to ask for, and hash the ones received. - // If we have - // - time_t now = time(NULL) ; - - RsStackMutex stack(tfMtx); /******* STACK LOCKED ******/ - - switch(_crcmap_state) - { - case FT_TM_CRC_MAP_STATE_NOCHECK: - _crcreq_source = "" ; -#ifdef FT_DEBUG - std::cerr << "ftTransferModule::checkCRC(): state is NOCHECK. Doing nothing." << std::endl ; -#endif - break ; - - case FT_TM_CRC_MAP_STATE_DONT_HAVE: - { - // Check wether we have a CRC map or not. - // - std::cerr << "FT_TM_CRC_MAP_STATE_ASKED: last time is " << _crcmap_last_asked_time << std::endl ; - std::cerr << "FT_TM_CRC_MAP_STATE_ASKED: now is " << now << std::endl ; - - uint64_t threshold = (uint64_t)(FT_TM_CRC_MAP_MAX_WAIT_PER_GIG * (1+mSize/float(1024ull*1024ull*1024ull))) ; - - std::cerr << "Threshold is " << threshold << std::endl; - std::cerr << "Limit is " << (uint64_t)_crcmap_last_asked_time + threshold << std::endl ; - std::cerr << "Requested source is \"" << _crcreq_source << "\"" << std::endl; - - if( _crcreq_source != "" && (uint64_t)_crcmap_last_tunnel_keepup + 10 <= (uint64_t)now) - { -#ifdef FT_DEBUG - std::cerr << "ftTransferModule::checkCRC(): sending keepup to source " << _crcreq_source << std::endl ; -#endif - locked_requestData(_crcreq_source,0,(uint32_t)std::min((uint64_t)512,mSize)); - _crcmap_last_tunnel_keepup = now ; - } - - if( (uint64_t)_crcmap_last_asked_time + threshold > (uint64_t)now) - { -#ifdef FT_DEBUG - std::cerr << "ftTransferModule::checkCRC(): state is NOCHECK. Doing nothing." << std::endl ; -#endif - break ; - } - // Ask the ones we should ask for. We use a very coarse strategy now: we - // send the request to a random source. We'll make this more sensible - // later. - -#ifdef FT_DEBUG - std::cerr << "ftTransferModule::checkCRC(): state is DONT_HAVE or last request is too old. Selecting a source for asking a CRC map." << std::endl ; -#endif - if(mFileSources.empty()) - { - std::cerr << "ftTransferModule::checkCRC(): No sources available for checking file " << mHash << ": waiting 3 additional sec." <::const_iterator mit = mFileSources.begin();mit != mFileSources.end();++mit) - if(mFileCreator->sourceIsComplete(mit->first)) - { -//#ifdef FT_DEBUG - std::cerr << "ftTransferModule::checkCRC(): sending CRC map request to source " << mit->first << std::endl ; -//#endif - _crcmap_last_asked_time = now ; - _crcreq_source = mit->first ; - - mMultiplexor->sendCRC32MapRequest(mit->first,mHash); - found = true ; - break ; - } - } - break ; - - case FT_TM_CRC_MAP_STATE_HAVE: - { -#ifdef FT_DEBUG - std::cerr << "ftTransferModule::checkCRC(): got a CRC32 map. Matching chunks..." << std::endl ; -#endif - // The CRCmap is complete. Let's cross check it with existing chunks in ftFileCreator ! - // - uint32_t bad_chunks ; - uint32_t incomplete_chunks ; - - if(!mFileCreator->crossCheckChunkMap(_crcmap,bad_chunks,incomplete_chunks)) - { - std::cerr << "ftTransferModule::checkCRC(): could not check CRC chunks!" << std::endl ; - return false; - } - - // go back to download stage, if not all chunks are correct. - // - if(bad_chunks > 0) - { - mFlag = FT_TM_FLAG_DOWNLOADING ; - mFileStatus.stat = ftFileStatus::PQIFILE_DOWNLOADING; - std::cerr << "ftTransferModule::checkCRC(): Done. File has errors: " << bad_chunks << " bad chunks found. Restarting download for these chunks only." << std::endl ; - } - else if(incomplete_chunks > 0) - { - mFlag = FT_TM_FLAG_DOWNLOADING ; - mFileStatus.stat = ftFileStatus::PQIFILE_DOWNLOADING; -#ifdef FT_DEBUG - std::cerr << "ftTransferModule::checkCRC(): Done. all chunks ok. Continuing download for remaining chunks." << std::endl ; -#endif - } - else - { - // We do as if the file is not complete. This way, it finishes properly. - // - //mFlag = FT_TM_FLAG_COMPLETE ; // Transfer is complete. - mFlag = FT_TM_FLAG_DOWNLOADING ; - mFileStatus.stat = ftFileStatus::PQIFILE_DOWNLOADING; -#ifdef FT_DEBUG - std::cerr << "ftTransferModule::checkCRC(): Done. CRC check is ok, file is complete." << std::endl ; -#endif - } - - _crcmap_state = FT_TM_CRC_MAP_STATE_NOCHECK ; - _crcreq_source = "" ; - } - } - - return true ; -} - -void ftTransferModule::addCRC32Map(const CRC32Map& crc_map) -{ - RsStackMutex stack(tfMtx); /******* STACK LOCKED ******/ - - // Note: for now, we only send complete CRC32 maps, so the crc_map is always complete. When we - // send partial CRC maps, we will have to check them for completness. - // - _crcmap_state = FT_TM_CRC_MAP_STATE_HAVE ; - _crcmap = crc_map ; -} - void ftTransferModule::adjustSpeed() { RsStackMutex stack(tfMtx); /******* STACK LOCKED ******/ diff --git a/libretroshare/src/libretroshare.pro b/libretroshare/src/libretroshare.pro index 851436c4b..682dfdcee 100644 --- a/libretroshare/src/libretroshare.pro +++ b/libretroshare/src/libretroshare.pro @@ -365,8 +365,9 @@ HEADERS += rsserver/p3face.h \ rsserver/p3status.h \ rsserver/p3serverconfig.h -HEADERS += serialiser/rsbaseitems.h \ - serialiser/rsbaseserial.h \ +HEADERS += serialiser/rsbaseserial.h \ + serialiser/rsfiletransferitems.h \ + serialiser/rsserviceserialiser.h \ serialiser/rsconfigitems.h \ serialiser/rshistoryitems.h \ serialiser/rsmsgitems.h \ @@ -494,8 +495,9 @@ SOURCES += plugins/pluginmanager.cc \ plugins/dlfcn_win32.cc \ serialiser/rspluginitems.cc -SOURCES += serialiser/rsbaseitems.cc \ - serialiser/rsbaseserial.cc \ +SOURCES += serialiser/rsbaseserial.cc \ + serialiser/rsfiletransferitems.cc \ + serialiser/rsserviceserialiser.cc \ serialiser/rsconfigitems.cc \ serialiser/rshistoryitems.cc \ serialiser/rsmsgitems.cc \ diff --git a/libretroshare/src/pqi/pqi.h b/libretroshare/src/pqi/pqi.h index d82f12a39..3faffe03e 100644 --- a/libretroshare/src/pqi/pqi.h +++ b/libretroshare/src/pqi/pqi.h @@ -34,7 +34,6 @@ #include "pqi/pqi_base.h" #include "pqi/pqinetwork.h" #include "serialiser/rsserial.h" -#include "serialiser/rsbaseitems.h" #include #include @@ -49,41 +48,7 @@ class SearchInterface public: SearchInterface() { return; } -virtual ~SearchInterface() { return; } - - // Cache Requests -virtual int SearchSpecific(RsCacheRequest *) = 0; -virtual RsCacheRequest *RequestedSearch() = 0; - - // Cache Results -virtual int SendSearchResult(RsCacheItem *item) = 0; -virtual RsCacheItem *GetSearchResult() = 0; - - // FileTransfer. -virtual RsFileRequest *GetFileRequest() = 0; -virtual int SendFileRequest(RsFileRequest *) = 0; - -virtual RsFileData *GetFileData() = 0; -virtual int SendFileData(RsFileData *) = 0; - -virtual RsFileChunkMapRequest *GetFileChunkMapRequest() = 0; -virtual int SendFileChunkMapRequest(RsFileChunkMapRequest *) = 0; - -virtual RsFileChunkMap *GetFileChunkMap() = 0; -virtual int SendFileChunkMap(RsFileChunkMap *) = 0; - -virtual RsFileCRC32MapRequest *GetFileCRC32MapRequest() = 0; -virtual int SendFileCRC32MapRequest(RsFileCRC32MapRequest *) = 0; - -virtual RsFileCRC32Map *GetFileCRC32Map() = 0; -virtual int SendFileCRC32Map(RsFileCRC32Map *) = 0; - -virtual RsFileSingleChunkCrcRequest *GetFileSingleChunkCrcRequest()=0; -virtual int SendFileSingleChunkCrcRequest(RsFileSingleChunkCrcRequest *ns)=0; - -virtual RsFileSingleChunkCrc *GetFileSingleChunkCrc()=0; -virtual int SendFileSingleChunkCrc(RsFileSingleChunkCrc *ns)=0; - + virtual ~SearchInterface() { return; } }; class P3Interface: public SearchInterface diff --git a/libretroshare/src/pqi/pqihandler.cc b/libretroshare/src/pqi/pqihandler.cc index 834bc1353..d1dcf0fe8 100644 --- a/libretroshare/src/pqi/pqihandler.cc +++ b/libretroshare/src/pqi/pqihandler.cc @@ -286,50 +286,6 @@ int pqihandler::locked_HandleRsItem(RsItem *item, int allowglobal,uint32_t& comp return 1; } -int pqihandler::SearchSpecific(RsCacheRequest *ns) -{ - return queueOutRsItem(ns) ; -} - -int pqihandler::SendSearchResult(RsCacheItem *ns) -{ - return queueOutRsItem(ns) ; -} - -int pqihandler::SendFileRequest(RsFileRequest *ns) -{ - return queueOutRsItem(ns) ; -} - -int pqihandler::SendFileData(RsFileData *ns) -{ - return queueOutRsItem(ns) ; -} -int pqihandler::SendFileChunkMapRequest(RsFileChunkMapRequest *ns) -{ - return queueOutRsItem(ns) ; -} -int pqihandler::SendFileChunkMap(RsFileChunkMap *ns) -{ - return queueOutRsItem(ns) ; -} -int pqihandler::SendFileCRC32MapRequest(RsFileCRC32MapRequest *ns) -{ - return queueOutRsItem(ns) ; -} -int pqihandler::SendFileCRC32Map(RsFileCRC32Map *ns) -{ - return queueOutRsItem(ns) ; -} -int pqihandler::SendFileSingleChunkCrcRequest(RsFileSingleChunkCrcRequest *ns) -{ - return queueOutRsItem(ns) ; -} -int pqihandler::SendFileSingleChunkCrc(RsFileSingleChunkCrc *ns) -{ - return queueOutRsItem(ns) ; -} - int pqihandler::SendRsRawItem(RsRawItem *ns) { pqioutput(PQL_DEBUG_BASIC, pqihandlerzone, "pqihandler::SendRsRawItem()"); @@ -409,9 +365,6 @@ void pqihandler::locked_SortnStoreItem(RsItem *item) { /* get class type / subtype out of the item */ uint8_t vers = item -> PacketVersion(); - uint8_t cls = item -> PacketClass(); - uint8_t type = item -> PacketType(); - uint8_t subtype = item -> PacketSubType(); /* whole Version reserved for SERVICES/CACHES */ if (vers == RS_PKT_VERSION_SERVICE) @@ -422,257 +375,25 @@ void pqihandler::locked_SortnStoreItem(RsItem *item) item = NULL; return; } + std::cerr << "pqihandler::locked_SortnStoreItem() : unhandled item! Will be deleted. This is certainly a bug." << std::endl; if (vers != RS_PKT_VERSION1) { - pqioutput(PQL_DEBUG_BASIC, pqihandlerzone, - "SortnStore -> Invalid VERSION! Deleting!"); + pqioutput(PQL_DEBUG_BASIC, pqihandlerzone, "SortnStore -> Invalid VERSION! Deleting!"); delete item; item = NULL; return; } - switch(cls) - { - case RS_PKT_CLASS_BASE: - switch(type) - { - case RS_PKT_TYPE_CACHE: - switch(subtype) - { - case RS_PKT_SUBTYPE_CACHE_REQUEST: - pqioutput(PQL_DEBUG_BASIC, pqihandlerzone, - "SortnStore -> Cache Request"); - in_search.push_back(item); - item = NULL; - break; - - case RS_PKT_SUBTYPE_CACHE_ITEM: - pqioutput(PQL_DEBUG_BASIC, pqihandlerzone, - "SortnStore -> Cache Result"); - in_result.push_back(item); - item = NULL; - break; - - default: - break; /* no match! */ - } - break; - - case RS_PKT_TYPE_FILE: - switch(subtype) - { - case RS_PKT_SUBTYPE_FI_REQUEST: - pqioutput(PQL_DEBUG_BASIC, pqihandlerzone, - "SortnStore -> File Request"); - in_request.push_back(item); - item = NULL; - break; - - case RS_PKT_SUBTYPE_FI_DATA: - pqioutput(PQL_DEBUG_BASIC, pqihandlerzone, "SortnStore -> File Data"); - in_data.push_back(item); - item = NULL; - break; - - case RS_PKT_SUBTYPE_FI_CHUNK_MAP_REQUEST: - pqioutput(PQL_DEBUG_BASIC, pqihandlerzone, "SortnStore -> File ChunkMap Request"); - in_chunkmap_request.push_back(item); - item = NULL; - break; - - case RS_PKT_SUBTYPE_FI_CHUNK_MAP: - pqioutput(PQL_DEBUG_BASIC, pqihandlerzone, "SortnStore -> File ChunkMap"); - in_chunkmap.push_back(item); - item = NULL; - break; - - case RS_PKT_SUBTYPE_FI_CRC32_MAP_REQUEST: - pqioutput(PQL_DEBUG_BASIC, pqihandlerzone, "SortnStore -> File Crc32Map Request"); - in_crc32map_request.push_back(item); - item = NULL; - break; - - case RS_PKT_SUBTYPE_FI_CRC32_MAP: - pqioutput(PQL_DEBUG_BASIC, pqihandlerzone, "SortnStore -> File CRC32Map"); - in_crc32map.push_back(item); - item = NULL; - break; - - case RS_PKT_SUBTYPE_FI_CHUNK_CRC_REQUEST: - pqioutput(PQL_DEBUG_BASIC, pqihandlerzone, "SortnStore -> File Crc Request"); - in_singlechunkcrc_request.push_back(item); - item = NULL; - break; - - case RS_PKT_SUBTYPE_FI_CHUNK_CRC: - pqioutput(PQL_DEBUG_BASIC, pqihandlerzone, "SortnStore -> File CRC32Map"); - in_singlechunkcrc.push_back(item); - item = NULL; - break; - - default: - break; /* no match! */ - } - break; - - default: - break; /* no match! */ - } - break; - - default: - pqioutput(PQL_DEBUG_BASIC, pqihandlerzone, - "SortnStore -> Unknown"); - break; - - } - if (item) { - pqioutput(PQL_DEBUG_BASIC, pqihandlerzone, - "SortnStore -> Deleting Unsorted Item"); + pqioutput(PQL_DEBUG_BASIC, pqihandlerzone, "SortnStore -> Deleting Unsorted Item"); delete item; } return; } - -// much like the input stuff. -RsCacheItem *pqihandler::GetSearchResult() -{ - RsStackMutex stack(coreMtx); /**************** LOCKED MUTEX ****************/ - - if (in_result.size() != 0) - { - RsCacheItem *fi = dynamic_cast(in_result.front()); - if (!fi) { delete in_result.front(); } - in_result.pop_front(); - return fi; - } - return NULL; -} - -RsCacheRequest *pqihandler::RequestedSearch() -{ - RsStackMutex stack(coreMtx); /**************** LOCKED MUTEX ****************/ - - if (in_search.size() != 0) - { - RsCacheRequest *fi = dynamic_cast(in_search.front()); - if (!fi) { delete in_search.front(); } - in_search.pop_front(); - return fi; - } - return NULL; -} - -RsFileRequest *pqihandler::GetFileRequest() -{ - RsStackMutex stack(coreMtx); /**************** LOCKED MUTEX ****************/ - - if (in_request.size() != 0) - { - RsFileRequest *fi = dynamic_cast(in_request.front()); - if (!fi) { delete in_request.front(); } - in_request.pop_front(); - return fi; - } - return NULL; -} - -RsFileData *pqihandler::GetFileData() -{ - RsStackMutex stack(coreMtx); /**************** LOCKED MUTEX ****************/ - - if (in_data.size() != 0) - { - RsFileData *fi = dynamic_cast(in_data.front()); - if (!fi) { delete in_data.front(); } - in_data.pop_front(); - return fi; - } - return NULL; -} -RsFileChunkMapRequest *pqihandler::GetFileChunkMapRequest() -{ - RsStackMutex stack(coreMtx); /**************** LOCKED MUTEX ****************/ - - if (in_chunkmap_request.size() != 0) - { - RsFileChunkMapRequest *fi = dynamic_cast(in_chunkmap_request.front()); - if (!fi) { delete in_chunkmap_request.front(); } - in_chunkmap_request.pop_front(); - return fi; - } - return NULL; -} -RsFileChunkMap *pqihandler::GetFileChunkMap() -{ - RsStackMutex stack(coreMtx); /**************** LOCKED MUTEX ****************/ - - if (in_chunkmap.size() != 0) - { - RsFileChunkMap *fi = dynamic_cast(in_chunkmap.front()); - if (!fi) { delete in_chunkmap.front(); } - in_chunkmap.pop_front(); - return fi; - } - return NULL; -} -RsFileCRC32MapRequest *pqihandler::GetFileCRC32MapRequest() -{ - RsStackMutex stack(coreMtx); /**************** LOCKED MUTEX ****************/ - - if (in_crc32map_request.size() != 0) - { - RsFileCRC32MapRequest *fi = dynamic_cast(in_crc32map_request.front()); - if (!fi) { delete in_crc32map_request.front(); } - in_crc32map_request.pop_front(); - return fi; - } - return NULL; -} -RsFileCRC32Map *pqihandler::GetFileCRC32Map() -{ - RsStackMutex stack(coreMtx); /**************** LOCKED MUTEX ****************/ - - if (in_crc32map.size() != 0) - { - RsFileCRC32Map *fi = dynamic_cast(in_crc32map.front()); - if (!fi) { delete in_crc32map.front(); } - in_crc32map.pop_front(); - return fi; - } - return NULL; -} -RsFileSingleChunkCrcRequest *pqihandler::GetFileSingleChunkCrcRequest() -{ - RsStackMutex stack(coreMtx); /**************** LOCKED MUTEX ****************/ - - if (in_singlechunkcrc_request.size() != 0) - { - RsFileSingleChunkCrcRequest *fi = dynamic_cast(in_singlechunkcrc_request.front()); - if (!fi) { delete in_singlechunkcrc_request.front(); } - in_singlechunkcrc_request.pop_front(); - return fi; - } - return NULL; -} -RsFileSingleChunkCrc *pqihandler::GetFileSingleChunkCrc() -{ - RsStackMutex stack(coreMtx); /**************** LOCKED MUTEX ****************/ - - if (in_singlechunkcrc.size() != 0) - { - RsFileSingleChunkCrc *fi = dynamic_cast(in_singlechunkcrc.front()); - if (!fi) { delete in_singlechunkcrc.front(); } - in_singlechunkcrc.pop_front(); - return fi; - } - return NULL; -} RsRawItem *pqihandler::GetRsRawItem() { RsStackMutex stack(coreMtx); /**************** LOCKED MUTEX ****************/ diff --git a/libretroshare/src/pqi/pqihandler.h b/libretroshare/src/pqi/pqihandler.h index 7c78971be..35eacfd67 100644 --- a/libretroshare/src/pqi/pqihandler.h +++ b/libretroshare/src/pqi/pqihandler.h @@ -53,32 +53,6 @@ class pqihandler: public P3Interface bool AddSearchModule(SearchModule *mod); bool RemoveSearchModule(SearchModule *mod); - // P3Interface. - virtual int SearchSpecific(RsCacheRequest *ns); - virtual int SendSearchResult(RsCacheItem *); - - // inputs. - virtual RsCacheRequest * RequestedSearch(); - virtual RsCacheItem * GetSearchResult(); - - // file i/o - virtual int SendFileRequest(RsFileRequest *ns); - virtual int SendFileData(RsFileData *ns); - virtual int SendFileChunkMapRequest(RsFileChunkMapRequest *ns); - virtual int SendFileChunkMap(RsFileChunkMap *ns); - virtual int SendFileCRC32MapRequest(RsFileCRC32MapRequest *ns); - virtual int SendFileCRC32Map(RsFileCRC32Map *ns); - virtual int SendFileSingleChunkCrcRequest(RsFileSingleChunkCrcRequest *ns); - virtual int SendFileSingleChunkCrc(RsFileSingleChunkCrc *ns); - virtual RsFileRequest *GetFileRequest(); - virtual RsFileData *GetFileData(); - virtual RsFileChunkMapRequest *GetFileChunkMapRequest(); - virtual RsFileChunkMap *GetFileChunkMap(); - virtual RsFileCRC32MapRequest *GetFileCRC32MapRequest(); - virtual RsFileCRC32Map *GetFileCRC32Map(); - virtual RsFileSingleChunkCrcRequest *GetFileSingleChunkCrcRequest(); - virtual RsFileSingleChunkCrc *GetFileSingleChunkCrc(); - // Rest of P3Interface virtual int tick(); virtual int status(); @@ -113,8 +87,7 @@ class pqihandler: public P3Interface std::map mods; SecurityPolicy *globsec; - // Temporary storage... - std::list in_result, in_search, in_request, in_data, in_service,in_chunkmap,in_chunkmap_request,in_crc32map_request,in_crc32map,in_singlechunkcrc,in_singlechunkcrc_request; + std::list in_service; private: diff --git a/libretroshare/src/pqi/pqipersongrp.cc b/libretroshare/src/pqi/pqipersongrp.cc index 061a0fb7e..b5822eacf 100644 --- a/libretroshare/src/pqi/pqipersongrp.cc +++ b/libretroshare/src/pqi/pqipersongrp.cc @@ -26,6 +26,7 @@ #include "pqi/pqipersongrp.h" #include "pqi/p3linkmgr.h" #include "util/rsdebug.h" +#include "serialiser/rsserviceserialiser.h" #include @@ -651,8 +652,6 @@ pqiperson * pqipersongrpDummy::locked_createPerson(std::string id, pqilistener * NetBinDummy *d1 = new NetBinDummy(pqip, id, PQI_CONNECT_TCP); RsSerialiser *rss = new RsSerialiser(); - rss->addSerialType(new RsFileItemSerialiser()); - rss->addSerialType(new RsCacheItemSerialiser()); rss->addSerialType(new RsServiceSerialiser()); pqiconnect *pqic = new pqiconnect(rss, d1); @@ -663,8 +662,6 @@ pqiperson * pqipersongrpDummy::locked_createPerson(std::string id, pqilistener * NetBinDummy *d2 = new NetBinDummy(pqip, id, PQI_CONNECT_UDP); RsSerialiser *rss2 = new RsSerialiser(); - rss2->addSerialType(new RsFileItemSerialiser()); - rss2->addSerialType(new RsCacheItemSerialiser()); rss2->addSerialType(new RsServiceSerialiser()); pqiconnect *pqic2 = new pqiconnect(rss2, d2); diff --git a/libretroshare/src/pqi/pqisslpersongrp.cc b/libretroshare/src/pqi/pqisslpersongrp.cc index 5930f5dde..1766359d5 100644 --- a/libretroshare/src/pqi/pqisslpersongrp.cc +++ b/libretroshare/src/pqi/pqisslpersongrp.cc @@ -23,6 +23,7 @@ * */ +#include "serialiser/rsserviceserialiser.h" #include "util/rsdebug.h" #include "pqi/pqisslpersongrp.h" @@ -92,8 +93,6 @@ pqiperson * pqisslpersongrp::locked_createPerson(std::string id, pqilistener *li ssl_tunnels[id] = pqis ; // keeps for getting crypt info per peer. RsSerialiser *rss = new RsSerialiser(); - rss->addSerialType(new RsFileItemSerialiser()); - rss->addSerialType(new RsCacheItemSerialiser()); rss->addSerialType(new RsServiceSerialiser()); pqiconnect *pqisc = new pqiconnect(rss, pqis); @@ -117,8 +116,6 @@ pqiperson * pqisslpersongrp::locked_createPerson(std::string id, pqilistener *li ssl_tunnels[id] = pqis ; // keeps for getting crypt info per peer. RsSerialiser *rss = new RsSerialiser(); - rss->addSerialType(new RsFileItemSerialiser()); - rss->addSerialType(new RsCacheItemSerialiser()); rss->addSerialType(new RsServiceSerialiser()); pqiconnect *pqisc = new pqiconnect(rss, pqis); @@ -129,8 +126,6 @@ pqiperson * pqisslpersongrp::locked_createPerson(std::string id, pqilistener *li pqissludp *pqius = new pqissludp(pqip, mLinkMgr); RsSerialiser *rss2 = new RsSerialiser(); - rss2->addSerialType(new RsFileItemSerialiser()); - rss2->addSerialType(new RsCacheItemSerialiser()); rss2->addSerialType(new RsServiceSerialiser()); pqiconnect *pqiusc = new pqiconnect(rss2, pqius); diff --git a/libretroshare/src/pqi/pqistreamer.cc b/libretroshare/src/pqi/pqistreamer.cc index 1b66ba135..a26ebcacb 100644 --- a/libretroshare/src/pqi/pqistreamer.cc +++ b/libretroshare/src/pqi/pqistreamer.cc @@ -33,7 +33,6 @@ #include "pqi/pqinotify.h" #include "serialiser/rsserial.h" -#include "serialiser/rsbaseitems.h" /***** For RsFileData *****/ const int pqistreamerzone = 8221; diff --git a/libretroshare/src/rsserver/p3face-config.cc b/libretroshare/src/rsserver/p3face-config.cc index af21674b7..dc93d23f3 100644 --- a/libretroshare/src/rsserver/p3face-config.cc +++ b/libretroshare/src/rsserver/p3face-config.cc @@ -85,7 +85,6 @@ void RsServer::rsGlobalShutDown() mNetMgr->shutdown(); /* Handles UPnP */ join(); - ftserver->StopThreads(); mPluginsManager->stopPlugins(); diff --git a/libretroshare/src/rsserver/p3face-server.cc b/libretroshare/src/rsserver/p3face-server.cc index d4f6b768d..1db57374e 100644 --- a/libretroshare/src/rsserver/p3face-server.cc +++ b/libretroshare/src/rsserver/p3face-server.cc @@ -54,7 +54,7 @@ int rsserverzone = 101; RsServer::RsServer(NotifyBase &callback) :RsControl(callback), coreMutex("RsServer") { - ftserver = NULL; + //ftserver = NULL; mPeerMgr = NULL; mLinkMgr = NULL; @@ -163,7 +163,8 @@ void RsServer::run() /******************************** RUN SERVER *****************/ lockRsCore(); - int moreToTick = ftserver -> tick(); + //int moreToTick = ftserver -> tick(); + int moreToTick = pqih->tick(); #ifdef DEBUG_TICK std::cerr << "RsServer::run() ftserver->tick(): moreToTick: " << moreToTick << std::endl; diff --git a/libretroshare/src/rsserver/p3face.h b/libretroshare/src/rsserver/p3face.h index 5de9ca42d..45ff2314f 100644 --- a/libretroshare/src/rsserver/p3face.h +++ b/libretroshare/src/rsserver/p3face.h @@ -159,7 +159,7 @@ class RsServer: public RsControl, public RsThread // The real Server Parts. //filedexserver *server; - ftServer *ftserver; + //ftServer *ftserver; p3PeerMgrIMPL *mPeerMgr; p3LinkMgrIMPL *mLinkMgr; diff --git a/libretroshare/src/rsserver/rsinit.cc b/libretroshare/src/rsserver/rsinit.cc index b8d2ca306..87335fe2c 100644 --- a/libretroshare/src/rsserver/rsinit.cc +++ b/libretroshare/src/rsserver/rsinit.cc @@ -2177,8 +2177,7 @@ int RsServer::StartupRetroShare() //pqih = new pqipersongrpDummy(none, flags); /****** New Ft Server **** !!! */ - ftserver = new ftServer(mPeerMgr, mLinkMgr); - ftserver->setP3Interface(pqih); + ftServer *ftserver = new ftServer(mPeerMgr, mLinkMgr); ftserver->setConfigDirectory(RsInitConfig::configDir); ftserver->SetupFtServer(&(getNotify())); @@ -2254,6 +2253,7 @@ int RsServer::StartupRetroShare() p3turtle *tr = new p3turtle(mLinkMgr) ; rsTurtle = tr ; pqih -> addService(tr); + pqih -> addService(ftserver); ftserver->connectToTurtleRouter(tr) ; chatSrv->connectToTurtleRouter(tr) ; diff --git a/libretroshare/src/serialiser/rsbaseitems.cc b/libretroshare/src/serialiser/rsbaseitems.cc deleted file mode 100644 index df6dca7fe..000000000 --- a/libretroshare/src/serialiser/rsbaseitems.cc +++ /dev/null @@ -1,1519 +0,0 @@ - -/* - * libretroshare/src/serialiser: rsbaseitems.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/rsbaseitems.h" -#include "serialiser/rstlvbase.h" - -/*** - * #define RSSERIAL_DEBUG 1 - * #define DEBUG_TRANSFERS 1 -***/ - - -#ifdef DEBUG_TRANSFERS - #include "util/rsprint.h" -#endif - -#include - -/*************************************************************************/ - -uint32_t RsFileItemSerialiser::size(RsItem *i) -{ - RsFileRequest *rfr; - RsFileData *rfd; - RsFileChunkMapRequest *rfcmr; - RsFileChunkMap *rfcm; - RsFileCRC32MapRequest *rfcrcr; - RsFileCRC32Map *rfcrc; - RsFileSingleChunkCrcRequest *rfscrcr; - RsFileSingleChunkCrc *rfscrc; - - if (NULL != (rfr = dynamic_cast(i))) - { - return sizeReq(rfr); - } - else if (NULL != (rfd = dynamic_cast(i))) - { - return sizeData(rfd); - } - else if (NULL != (rfcmr = dynamic_cast(i))) - { - return sizeChunkMapReq(rfcmr); - } - else if (NULL != (rfcm = dynamic_cast(i))) - { - return sizeChunkMap(rfcm); - } - else if (NULL != (rfcrcr = dynamic_cast(i))) - { - return sizeCRC32MapReq(rfcrcr); - } - else if (NULL != (rfcrc = dynamic_cast(i))) - { - return sizeCRC32Map(rfcrc); - } - else if (NULL != (rfscrcr = dynamic_cast(i))) - { - return sizeChunkCrcReq(rfscrcr); - } - else if (NULL != (rfscrc = dynamic_cast(i))) - { - return sizeChunkCrc(rfscrc); - } - - return 0; -} - -/* serialise the data to the buffer */ -bool RsFileItemSerialiser::serialise(RsItem *i, void *data, uint32_t *pktsize) -{ - RsFileRequest *rfr; - RsFileData *rfd; - RsFileChunkMapRequest *rfcmr; - RsFileChunkMap *rfcm; - RsFileCRC32MapRequest *rfcrcr; - RsFileCRC32Map *rfcrc; - RsFileSingleChunkCrcRequest *rfscrcr; - RsFileSingleChunkCrc *rfscrc; - - if (NULL != (rfr = dynamic_cast(i))) - { - return serialiseReq(rfr, data, pktsize); - } - else if (NULL != (rfd = dynamic_cast(i))) - { - return serialiseData(rfd, data, pktsize); - } - else if (NULL != (rfcmr = dynamic_cast(i))) - { - return serialiseChunkMapReq(rfcmr,data,pktsize); - } - else if (NULL != (rfcm = dynamic_cast(i))) - { - return serialiseChunkMap(rfcm,data,pktsize); - } - else if (NULL != (rfcrcr = dynamic_cast(i))) - { - return serialiseCRC32MapReq(rfcrcr,data,pktsize); - } - else if (NULL != (rfcrc = dynamic_cast(i))) - { - return serialiseCRC32Map(rfcrc,data,pktsize); - } - else if (NULL != (rfscrcr = dynamic_cast(i))) - { - return serialiseChunkCrcReq(rfscrcr,data,pktsize); - } - else if (NULL != (rfscrc = dynamic_cast(i))) - { - return serialiseChunkCrc(rfscrc,data,pktsize); - } - - std::cerr << "RsFileItemSerialiser::serialize(): unhandled packet type !!" << std::endl; - return false; -} - -RsItem *RsFileItemSerialiser::deserialise(void *data, uint32_t *pktsize) -{ - /* get the type and size */ - uint32_t rstype = getRsItemId(data); - - if ((RS_PKT_VERSION1 != getRsItemVersion(rstype)) || - (RS_PKT_CLASS_BASE != getRsItemClass(rstype)) || - (RS_PKT_TYPE_FILE != getRsItemType(rstype))) - { - return NULL; /* wrong type */ - } - - switch(getRsItemSubType(rstype)) - { - case RS_PKT_SUBTYPE_FI_REQUEST: - return deserialiseReq(data, pktsize); - break; - case RS_PKT_SUBTYPE_FI_DATA: - return deserialiseData(data, pktsize); - break; - case RS_PKT_SUBTYPE_FI_CHUNK_MAP_REQUEST: - return deserialiseChunkMapReq(data, pktsize); - break; - case RS_PKT_SUBTYPE_FI_CHUNK_MAP: - return deserialiseChunkMap(data, pktsize); - break; - case RS_PKT_SUBTYPE_FI_CRC32_MAP_REQUEST: - return deserialiseCRC32MapReq(data, pktsize); - break; - case RS_PKT_SUBTYPE_FI_CRC32_MAP: - return deserialiseCRC32Map(data, pktsize); - break; - case RS_PKT_SUBTYPE_FI_CHUNK_CRC_REQUEST: - return deserialiseChunkCrcReq(data, pktsize); - break; - case RS_PKT_SUBTYPE_FI_CHUNK_CRC: - return deserialiseChunkCrc(data, pktsize); - break; - default: - return NULL; - break; - } - return NULL; -} - -/*************************************************************************/ - -RsFileRequest::~RsFileRequest() -{ - return; -} - -void RsFileRequest::clear() -{ - file.TlvClear(); - fileoffset = 0; - chunksize = 0; -} - -std::ostream &RsFileRequest::print(std::ostream &out, uint16_t indent) -{ - printRsItemBase(out, "RsFileRequest", indent); - uint16_t int_Indent = indent + 2; - printIndent(out, int_Indent); - out << "FileOffset: " << fileoffset; - out << " ChunkSize: " << chunksize << std::endl; - file.print(out, int_Indent); - printRsItemEnd(out, "RsFileRequest", indent); - return out; -} - - -uint32_t RsFileItemSerialiser::sizeReq(RsFileRequest *item) -{ - uint32_t s = 8; /* header */ - s += 8; /* offset */ - s += 4; /* chunksize */ - s += item->file.TlvSize(); - - return s; -} - -/* serialise the data to the buffer */ -bool RsFileItemSerialiser::serialiseReq(RsFileRequest *item, void *data, uint32_t *pktsize) -{ - uint32_t tlvsize = sizeReq(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 << "RsFileItemSerialiser::serialiseReq() Header: " << ok << std::endl; - std::cerr << "RsFileItemSerialiser::serialiseReq() Size: " << tlvsize << std::endl; -#endif - - /* skip the header */ - offset += 8; - - /* add mandatory parts first */ - ok &= setRawUInt64(data, tlvsize, &offset, item->fileoffset); - ok &= setRawUInt32(data, tlvsize, &offset, item->chunksize); - ok &= item->file.SetTlv(data, tlvsize, &offset); - - if (offset != tlvsize) - { - ok = false; -#ifdef RSSERIAL_DEBUG - std::cerr << "RsFileItemSerialiser::serialiseReq() Size Error! " << std::endl; -#endif - } - - /*** Debugging Transfer rates. - * print timestamp, and file details so we can workout packet lags. - ***/ - -#ifdef DEBUG_TRANSFERS - std::cerr << "RsFileItemSerialiser::serialiseReq() at: " << RsUtil::AccurateTimeString() << std::endl; - item->print(std::cerr, 10); -#endif - - return ok; -} - -RsFileRequest *RsFileItemSerialiser::deserialiseReq(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_VERSION1 != getRsItemVersion(rstype)) || - (RS_PKT_CLASS_BASE != getRsItemClass(rstype)) || - (RS_PKT_TYPE_FILE != getRsItemType(rstype)) || - (RS_PKT_SUBTYPE_FI_REQUEST != 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 */ - RsFileRequest *item = new RsFileRequest(); - item->clear(); - - /* skip the header */ - offset += 8; - - /* get mandatory parts first */ - ok &= getRawUInt64(data, rssize, &offset, &(item->fileoffset)); - ok &= getRawUInt32(data, rssize, &offset, &(item->chunksize)); - ok &= item->file.GetTlv(data, rssize, &offset); - - if (offset != rssize) - { - /* error */ - delete item; - return NULL; - } - - if (!ok) - { - delete item; - return NULL; - } - - - /*** Debugging Transfer rates. - * print timestamp, and file details so we can workout packet lags. - ***/ - -#ifdef DEBUG_TRANSFERS - std::cerr << "RsFileItemSerialiser::deserialiseReq() at: " << RsUtil::AccurateTimeString() << std::endl; - item->print(std::cerr, 10); -#endif - - return item; -} - - -/*************************************************************************/ - -RsFileData::~RsFileData() -{ - return; -} - -void RsFileData::clear() -{ - fd.TlvClear(); -} -std::ostream &RsFileChunkMap::print(std::ostream &out, uint16_t indent) -{ - printRsItemBase(out, "RsFileChunkMap", indent); - uint16_t int_Indent = indent + 2; - printIndent(out, int_Indent); out << "PeerId: " << PeerId() << std::endl ; - printIndent(out, int_Indent); out << " hash: " << hash << std::endl ; - printIndent(out, int_Indent); out << "chunks: " << std::hex << compressed_map._map[0] << std::dec << "..." << std::endl ; - printRsItemEnd(out, "RsFileChunkMap", indent); - return out; -} -std::ostream &RsFileChunkMapRequest::print(std::ostream &out, uint16_t indent) -{ - printRsItemBase(out, "RsFileChunkMapRequest", indent); - uint16_t int_Indent = indent + 2; - printIndent(out, int_Indent); out << "PeerId: " << PeerId() << std::endl ; - printIndent(out, int_Indent); out << " hash: " << hash << std::endl ; - printRsItemEnd(out, "RsFileChunkMapRequest", indent); - return out; -} -std::ostream& RsFileCRC32Map::print(std::ostream &out, uint16_t indent) -{ - printRsItemBase(out, "RsFileCRC32Map", indent); - uint16_t int_Indent = indent + 2; - printIndent(out, int_Indent); out << "PeerId: " << PeerId() << std::endl ; - printIndent(out, int_Indent); out << " hash: " << hash << std::endl ; - printIndent(out, int_Indent); out << "chunks: " << std::hex << crc_map._ccmap._map[0] << std::dec<< "..." << std::endl ; - printRsItemEnd(out, "RsFileCRC32Map", indent); - return out; -} -std::ostream& RsFileSingleChunkCrcRequest::print(std::ostream &out, uint16_t indent) -{ - printRsItemBase(out, "RsFileSingleChunkCrcRequest", indent); - uint16_t int_Indent = indent + 2; - printIndent(out, int_Indent); out << "PeerId: " << PeerId() << std::endl ; - printIndent(out, int_Indent); out << " hash: " << hash << std::endl ; - printIndent(out, int_Indent); out << " chunk: " << chunk_number << "..." << std::endl ; - printRsItemEnd(out, "RsFileSingleChunkCrcRequest", indent); - return out; -} -std::ostream& RsFileSingleChunkCrc::print(std::ostream &out, uint16_t indent) -{ - printRsItemBase(out, "RsFileSingleChunkCrc", indent); - uint16_t int_Indent = indent + 2; - printIndent(out, int_Indent); out << "PeerId: " << PeerId() << std::endl ; - printIndent(out, int_Indent); out << " hash: " << hash << std::endl ; - printIndent(out, int_Indent); out << " chunk: " << chunk_number << "..." << std::endl ; - printIndent(out, int_Indent); out << " sha1: " << check_sum.toStdString() << "..." << std::endl ; - printRsItemEnd(out, "RsFileSingleChunkCrc", indent); - return out; -} -std::ostream& RsFileCRC32MapRequest::print(std::ostream &out, uint16_t indent) -{ - printRsItemBase(out, "RsFileCRC32MapRequest", indent); - uint16_t int_Indent = indent + 2; - printIndent(out, int_Indent); out << "PeerId: " << PeerId() << std::endl ; - printIndent(out, int_Indent); out << " hash: " << hash << std::endl ; - printRsItemEnd(out, "RsFileCRC32MapRequest", indent); - return out; -} -std::ostream &RsFileData::print(std::ostream &out, uint16_t indent) -{ - printRsItemBase(out, "RsFileData", indent); - uint16_t int_Indent = indent + 2; - fd.print(out, int_Indent); - printRsItemEnd(out, "RsFileData", indent); - return out; -} - - -uint32_t RsFileItemSerialiser::sizeData(RsFileData *item) -{ - uint32_t s = 8; /* header */ - s += item->fd.TlvSize(); - - return s; -} - -/* serialise the data to the buffer */ -bool RsFileItemSerialiser::serialiseData(RsFileData *item, void *data, uint32_t *pktsize) -{ - uint32_t tlvsize = sizeData(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 << "RsFileItemSerialiser::serialiseData() Header: " << ok << std::endl; -#endif - - /* skip the header */ - offset += 8; - - /* add mandatory parts first */ - ok &= item->fd.SetTlv(data, tlvsize, &offset); - - if (offset != tlvsize) - { - ok = false; -#ifdef RSSERIAL_DEBUG - std::cerr << "RsFileItemSerialiser::serialiseData() Size Error! " << std::endl; -#endif - } - -#ifdef DEBUG_TRANSFERS - std::cerr << "RsFileItemSerialiser::serialiseData() at: " << RsUtil::AccurateTimeString() << std::endl; - item->print(std::cerr, 10); -#endif - - - return ok; -} - -RsFileData *RsFileItemSerialiser::deserialiseData(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_VERSION1 != getRsItemVersion(rstype)) || - (RS_PKT_CLASS_BASE != getRsItemClass(rstype)) || - (RS_PKT_TYPE_FILE != getRsItemType(rstype)) || - (RS_PKT_SUBTYPE_FI_DATA != 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 */ - RsFileData *item = new RsFileData(); - item->clear(); - - /* skip the header */ - offset += 8; - - /* get mandatory parts first */ - ok &= item->fd.GetTlv(data, rssize, &offset); - - if (offset != rssize) - { - /* error */ - delete item; - return NULL; - } - - if (!ok) - { - delete item; - return NULL; - } - -#ifdef DEBUG_TRANSFERS - std::cerr << "RsFileItemSerialiser::deserialiseData() at: " << RsUtil::AccurateTimeString() << std::endl; - item->print(std::cerr, 10); -#endif - - - return item; -} - -uint32_t RsFileItemSerialiser::sizeChunkMapReq(RsFileChunkMapRequest *item) -{ - uint32_t s = 8; /* header */ - s += 1 ; // is_client - s += GetTlvStringSize(item->hash) ; // hash - - return s; -} -uint32_t RsFileItemSerialiser::sizeChunkMap(RsFileChunkMap *item) -{ - uint32_t s = 8; /* header */ - s += 1 ; // is_client - s += GetTlvStringSize(item->hash) ; // hash - s += 4 ; // compressed map size - s += 4 * item->compressed_map._map.size() ; // compressed chunk map - - return s; -} -uint32_t RsFileItemSerialiser::sizeChunkCrc(RsFileSingleChunkCrc *item) -{ - uint32_t s = 8; /* header */ - s += GetTlvStringSize(item->hash) ; // hash - s += 4 ; // chunk number - s += 20 ; // sha1 - - return s; -} -uint32_t RsFileItemSerialiser::sizeChunkCrcReq(RsFileSingleChunkCrcRequest *item) -{ - uint32_t s = 8; /* header */ - s += GetTlvStringSize(item->hash) ; // hash - s += 4 ; // chunk number - - return s; -} -uint32_t RsFileItemSerialiser::sizeCRC32MapReq(RsFileCRC32MapRequest *item) -{ - uint32_t s = 8; /* header */ - s += GetTlvStringSize(item->hash) ; // hash - - return s; -} -uint32_t RsFileItemSerialiser::sizeCRC32Map(RsFileCRC32Map *item) -{ - uint32_t s = 8; /* header */ - s += GetTlvStringSize(item->hash) ; // hash - s += 4 ; // crc32 map size - s += 4 * item->crc_map._ccmap._map.size() ; // compressed chunk map - s += 4 ; // crc32 map size - s += 4 * item->crc_map._crcs.size() ; // compressed chunk map - - return s; -} -/* serialise the data to the buffer */ -bool RsFileItemSerialiser::serialiseCRC32MapReq(RsFileCRC32MapRequest *item, void *data, uint32_t *pktsize) -{ - uint32_t tlvsize = sizeCRC32MapReq(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 << "RsFileItemSerialiser::serialiseData() Header: " << ok << std::endl; -#endif - - /* skip the header */ - offset += 8; - - /* add mandatory parts first */ - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_VALUE, item->hash); - - if (offset != tlvsize) - { - ok = false; -#ifdef RSSERIAL_DEBUG - std::cerr << "RsFileItemSerialiser::serialiseData() Size Error! " << std::endl; -#endif - } - - return ok; -} -bool RsFileItemSerialiser::serialiseCRC32Map(RsFileCRC32Map *item, void *data, uint32_t *pktsize) -{ - uint32_t tlvsize = sizeCRC32Map(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 << "RsFileItemSerialiser::serialiseData() Header: " << ok << std::endl; -#endif - - /* skip the header */ - offset += 8; - - /* add mandatory parts first */ - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_VALUE, item->hash); - ok &= setRawUInt32(data, tlvsize, &offset, item->crc_map._ccmap._map.size()); - - for(uint32_t i=0;icrc_map._ccmap._map.size();++i) - ok &= setRawUInt32(data, tlvsize, &offset, item->crc_map._ccmap._map[i]); - - ok &= setRawUInt32(data, tlvsize, &offset, item->crc_map._crcs.size()); - - for(uint32_t i=0;icrc_map._crcs.size();++i) - ok &= setRawUInt32(data, tlvsize, &offset, item->crc_map._crcs[i]); - - if (offset != tlvsize) - { - ok = false; -#ifdef RSSERIAL_DEBUG - std::cerr << "RsFileItemSerialiser::serialiseData() Size Error! " << std::endl; -#endif - } - - return ok; -} -RsFileCRC32MapRequest *RsFileItemSerialiser::deserialiseCRC32MapReq(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_VERSION1 != getRsItemVersion(rstype)) || - (RS_PKT_CLASS_BASE != getRsItemClass(rstype)) || - (RS_PKT_TYPE_FILE != getRsItemType(rstype)) || - (RS_PKT_SUBTYPE_FI_CRC32_MAP_REQUEST != 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 */ - RsFileCRC32MapRequest *item = new RsFileCRC32MapRequest(); - item->clear(); - - /* skip the header */ - offset += 8; - ok &= GetTlvString(data, *pktsize, &offset, TLV_TYPE_STR_VALUE, item->hash); // file hash - - if (offset != rssize) - { - /* error */ - delete item; - return NULL; - } - - if (!ok) - { - delete item; - return NULL; - } - - return item; -} -RsFileCRC32Map *RsFileItemSerialiser::deserialiseCRC32Map(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_VERSION1 != getRsItemVersion(rstype)) || - (RS_PKT_CLASS_BASE != getRsItemClass(rstype)) || - (RS_PKT_TYPE_FILE != getRsItemType(rstype)) || - (RS_PKT_SUBTYPE_FI_CRC32_MAP != 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 */ - RsFileCRC32Map *item = new RsFileCRC32Map(); - item->clear(); - - /* skip the header */ - offset += 8; - ok &= GetTlvString(data, *pktsize, &offset, TLV_TYPE_STR_VALUE, item->hash); // file hash - uint32_t size =0; - ok &= getRawUInt32(data, *pktsize, &offset, &size); - - if(ok) - { - item->crc_map._ccmap._map.resize(size) ; - - for(uint32_t i=0;icrc_map._ccmap._map[i])); - } - - uint32_t size2 =0; - ok &= getRawUInt32(data, *pktsize, &offset, &size2); - - if(ok) - { - item->crc_map._crcs.resize(size2) ; - - for(uint32_t i=0;icrc_map._crcs[i])); - } - if (offset != rssize) - { - /* error */ - delete item; - return NULL; - } - - if (!ok) - { - delete item; - return NULL; - } - - return item; -} - -/* serialise the data to the buffer */ -bool RsFileItemSerialiser::serialiseChunkMapReq(RsFileChunkMapRequest *item, void *data, uint32_t *pktsize) -{ - uint32_t tlvsize = sizeChunkMapReq(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 << "RsFileItemSerialiser::serialiseData() Header: " << ok << std::endl; -#endif - - /* skip the header */ - offset += 8; - - /* add mandatory parts first */ - ok &= setRawUInt8(data, tlvsize, &offset, item->is_client); - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_VALUE, item->hash); - - if (offset != tlvsize) - { - ok = false; -#ifdef RSSERIAL_DEBUG - std::cerr << "RsFileItemSerialiser::serialiseData() Size Error! " << std::endl; -#endif - } - - return ok; -} -bool RsFileItemSerialiser::serialiseChunkCrcReq(RsFileSingleChunkCrcRequest *item, void *data, uint32_t *pktsize) -{ - uint32_t tlvsize = sizeChunkCrcReq(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 << "RsFileItemSerialiser::serialiseData() Header: " << ok << std::endl; -#endif - - /* skip the header */ - offset += 8; - - /* add mandatory parts first */ - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_VALUE, item->hash); - ok &= setRawUInt32(data, tlvsize, &offset, item->chunk_number) ; - - if (offset != tlvsize) - { - ok = false; -#ifdef RSSERIAL_DEBUG - std::cerr << "RsFileItemSerialiser::serialiseData() Size Error! " << std::endl; -#endif - } - - return ok; -} -bool RsFileItemSerialiser::serialiseChunkCrc(RsFileSingleChunkCrc *item, void *data, uint32_t *pktsize) -{ - uint32_t tlvsize = sizeChunkCrc(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 << "RsFileItemSerialiser::serialiseData() Header: " << ok << std::endl; -#endif - - /* skip the header */ - offset += 8; - - /* add mandatory parts first */ - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_VALUE, item->hash); - ok &= setRawUInt32(data, tlvsize, &offset, item->chunk_number) ; - ok &= setRawUInt32(data, tlvsize, &offset, item->check_sum.fourbytes[0]) ; - ok &= setRawUInt32(data, tlvsize, &offset, item->check_sum.fourbytes[1]) ; - ok &= setRawUInt32(data, tlvsize, &offset, item->check_sum.fourbytes[2]) ; - ok &= setRawUInt32(data, tlvsize, &offset, item->check_sum.fourbytes[3]) ; - ok &= setRawUInt32(data, tlvsize, &offset, item->check_sum.fourbytes[4]) ; - - if (offset != tlvsize) - { - ok = false; -#ifdef RSSERIAL_DEBUG - std::cerr << "RsFileItemSerialiser::serialiseData() Size Error! " << std::endl; -#endif - } - - return ok; -} -bool RsFileItemSerialiser::serialiseChunkMap(RsFileChunkMap *item, void *data, uint32_t *pktsize) -{ - uint32_t tlvsize = sizeChunkMap(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 << "RsFileItemSerialiser::serialiseData() Header: " << ok << std::endl; -#endif - - /* skip the header */ - offset += 8; - - /* add mandatory parts first */ - ok &= setRawUInt8(data, tlvsize, &offset, item->is_client); - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_VALUE, item->hash); - ok &= setRawUInt32(data, tlvsize, &offset, item->compressed_map._map.size()); - - for(uint32_t i=0;icompressed_map._map.size();++i) - ok &= setRawUInt32(data, tlvsize, &offset, item->compressed_map._map[i]); - - if (offset != tlvsize) - { - ok = false; -#ifdef RSSERIAL_DEBUG - std::cerr << "RsFileItemSerialiser::serialiseData() Size Error! " << std::endl; -#endif - } - - return ok; -} -RsFileChunkMapRequest *RsFileItemSerialiser::deserialiseChunkMapReq(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_VERSION1 != getRsItemVersion(rstype)) || - (RS_PKT_CLASS_BASE != getRsItemClass(rstype)) || - (RS_PKT_TYPE_FILE != getRsItemType(rstype)) || - (RS_PKT_SUBTYPE_FI_CHUNK_MAP_REQUEST != 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 */ - RsFileChunkMapRequest *item = new RsFileChunkMapRequest(); - item->clear(); - - /* skip the header */ - offset += 8; - uint8_t tmp ; - ok &= getRawUInt8(data, *pktsize, &offset, &tmp); item->is_client = tmp; - ok &= GetTlvString(data, *pktsize, &offset, TLV_TYPE_STR_VALUE, item->hash); // file hash - - if (offset != rssize) - { - /* error */ - delete item; - return NULL; - } - - if (!ok) - { - delete item; - return NULL; - } - - return item; -} -RsFileChunkMap *RsFileItemSerialiser::deserialiseChunkMap(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_VERSION1 != getRsItemVersion(rstype)) || - (RS_PKT_CLASS_BASE != getRsItemClass(rstype)) || - (RS_PKT_TYPE_FILE != getRsItemType(rstype)) || - (RS_PKT_SUBTYPE_FI_CHUNK_MAP != 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 */ - RsFileChunkMap *item = new RsFileChunkMap(); - item->clear(); - - /* skip the header */ - offset += 8; - uint8_t tmp ; - ok &= getRawUInt8(data, *pktsize, &offset, &tmp); item->is_client = tmp; - ok &= GetTlvString(data, *pktsize, &offset, TLV_TYPE_STR_VALUE, item->hash); // file hash - uint32_t size =0; - ok &= getRawUInt32(data, *pktsize, &offset, &size); - - if(ok) - { - item->compressed_map._map.resize(size) ; - - for(uint32_t i=0;icompressed_map._map[i])); - } - - if (offset != rssize) - { - /* error */ - delete item; - return NULL; - } - - if (!ok) - { - delete item; - return NULL; - } - - return item; -} -/*************************************************************************/ -/*************************************************************************/ - -uint32_t RsCacheItemSerialiser::size(RsItem *i) -{ - RsCacheRequest *rfr; - RsCacheItem *rfi; - - if (NULL != (rfr = dynamic_cast(i))) - { - return sizeReq(rfr); - } - else if (NULL != (rfi = dynamic_cast(i))) - { - return sizeItem(rfi); - } - - return 0; -} - -/* serialise the data to the buffer */ -bool RsCacheItemSerialiser::serialise(RsItem *i, void *data, uint32_t *pktsize) -{ - RsCacheRequest *rfr; - RsCacheItem *rfi; - - if (NULL != (rfr = dynamic_cast(i))) - { - return serialiseReq(rfr, data, pktsize); - } - else if (NULL != (rfi = dynamic_cast(i))) - { - return serialiseItem(rfi, data, pktsize); - } - - return false; -} - -RsItem *RsCacheItemSerialiser::deserialise(void *data, uint32_t *pktsize) -{ - /* get the type and size */ - uint32_t rstype = getRsItemId(data); - - if ((RS_PKT_VERSION1 != getRsItemVersion(rstype)) || - (RS_PKT_CLASS_BASE != getRsItemClass(rstype)) || - (RS_PKT_TYPE_CACHE != getRsItemType(rstype))) - { - return NULL; /* wrong type */ - } - - switch(getRsItemSubType(rstype)) - { - case RS_PKT_SUBTYPE_CACHE_REQUEST: - return deserialiseReq(data, pktsize); - break; - case RS_PKT_SUBTYPE_CACHE_ITEM: - return deserialiseItem(data, pktsize); - break; - default: - return NULL; - break; - } - return NULL; -} - -/*************************************************************************/ - -RsCacheRequest::~RsCacheRequest() -{ - return; -} - -void RsCacheRequest::clear() -{ - cacheType = 0; - cacheSubId = 0; - file.TlvClear(); -} - -std::ostream &RsCacheRequest::print(std::ostream &out, uint16_t indent) -{ - printRsItemBase(out, "RsCacheRequest", indent); - uint16_t int_Indent = indent + 2; - printIndent(out, int_Indent); - out << "CacheId: " << cacheType << "/" << cacheSubId << std::endl; - file.print(out, int_Indent); - printRsItemEnd(out, "RsCacheRequest", indent); - return out; -} - - -uint32_t RsCacheItemSerialiser::sizeReq(RsCacheRequest *item) -{ - uint32_t s = 8; /* header */ - s += 4; /* type/subid */ - s += item->file.TlvSize(); - - return s; -} - -/* serialise the data to the buffer */ -bool RsCacheItemSerialiser::serialiseReq(RsCacheRequest *item, void *data, uint32_t *pktsize) -{ - uint32_t tlvsize = sizeReq(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 << "RsCacheItemSerialiser::serialiseReq() Header: " << ok << std::endl; -#endif - - /* skip the header */ - offset += 8; - - /* add mandatory parts first */ - ok &= setRawUInt16(data, tlvsize, &offset, item->cacheType); - ok &= setRawUInt16(data, tlvsize, &offset, item->cacheSubId); - ok &= item->file.SetTlv(data, tlvsize, &offset); - - if (offset != tlvsize) - { - ok = false; -#ifdef RSSERIAL_DEBUG - std::cerr << "RsFileItemSerialiser::serialiseReq() Size Error! " << std::endl; -#endif - } - - return ok; -} - -RsCacheRequest *RsCacheItemSerialiser::deserialiseReq(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_VERSION1 != getRsItemVersion(rstype)) || - (RS_PKT_CLASS_BASE != getRsItemClass(rstype)) || - (RS_PKT_TYPE_CACHE != getRsItemType(rstype)) || - (RS_PKT_SUBTYPE_CACHE_REQUEST != 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 */ - RsCacheRequest *item = new RsCacheRequest(); - item->clear(); - - /* skip the header */ - offset += 8; - - /* get mandatory parts first */ - ok &= getRawUInt16(data, rssize, &offset, &(item->cacheType)); - ok &= getRawUInt16(data, rssize, &offset, &(item->cacheSubId)); - ok &= item->file.GetTlv(data, rssize, &offset); - - if (offset != rssize) - { - /* error */ - delete item; - return NULL; - } - - if (!ok) - { - delete item; - return NULL; - } - - return item; -} - - -/*************************************************************************/ - - -RsCacheItem::~RsCacheItem() -{ - return; -} - -void RsCacheItem::clear() -{ - cacheType = 0; - cacheSubId = 0; - file.TlvClear(); -} - -std::ostream &RsCacheItem::print(std::ostream &out, uint16_t indent) -{ - printRsItemBase(out, "RsCacheItem", indent); - uint16_t int_Indent = indent + 2; - printIndent(out, int_Indent); - out << "CacheId: " << cacheType << "/" << cacheSubId << std::endl; - file.print(out, int_Indent); - printRsItemEnd(out, "RsCacheItem", indent); - return out; -} - - -uint32_t RsCacheItemSerialiser::sizeItem(RsCacheItem *item) -{ - uint32_t s = 8; /* header */ - s += 4; /* type/subid */ - s += item->file.TlvSize(); - - return s; -} - -/* serialise the data to the buffer */ -bool RsCacheItemSerialiser::serialiseItem(RsCacheItem *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 << "RsCacheItemSerialiser::serialiseItem() Header: " << ok << std::endl; -#endif - - /* skip the header */ - offset += 8; - - /* add mandatory parts first */ - ok &= setRawUInt16(data, tlvsize, &offset, item->cacheType); - ok &= setRawUInt16(data, tlvsize, &offset, item->cacheSubId); - ok &= item->file.SetTlv(data, tlvsize, &offset); - - if (offset != tlvsize) - { - ok = false; -#ifdef RSSERIAL_DEBUG - std::cerr << "RsFileItemSerialiser::serialiseItem() Size Error! " << std::endl; -#endif - } - - return ok; -} - -RsCacheItem *RsCacheItemSerialiser::deserialiseItem(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_VERSION1 != getRsItemVersion(rstype)) || - (RS_PKT_CLASS_BASE != getRsItemClass(rstype)) || - (RS_PKT_TYPE_CACHE != getRsItemType(rstype)) || - (RS_PKT_SUBTYPE_CACHE_ITEM != 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 */ - RsCacheItem *item = new RsCacheItem(); - item->clear(); - - /* skip the header */ - offset += 8; - - /* get mandatory parts first */ - ok &= getRawUInt16(data, rssize, &offset, &(item->cacheType)); - ok &= getRawUInt16(data, rssize, &offset, &(item->cacheSubId)); - ok &= item->file.GetTlv(data, rssize, &offset); - - if (offset != rssize) - { - /* error */ - delete item; - return NULL; - } - - if (!ok) - { - delete item; - return NULL; - } - - return item; -} - -RsFileSingleChunkCrcRequest *RsFileItemSerialiser::deserialiseChunkCrcReq(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_VERSION1 != getRsItemVersion(rstype)) || - (RS_PKT_CLASS_BASE != getRsItemClass(rstype)) || - (RS_PKT_TYPE_FILE != getRsItemType(rstype)) || - (RS_PKT_SUBTYPE_FI_CHUNK_CRC_REQUEST != 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 */ - RsFileSingleChunkCrcRequest *item = new RsFileSingleChunkCrcRequest(); - item->clear(); - - /* skip the header */ - offset += 8; - ok &= GetTlvString(data, *pktsize, &offset, TLV_TYPE_STR_VALUE, item->hash); // file hash - ok &= getRawUInt32(data, rssize, &offset, &(item->chunk_number)); - - if (offset != rssize) - { - /* error */ - delete item; - return NULL; - } - - if (!ok) - { - delete item; - return NULL; - } - - return item; -} -RsFileSingleChunkCrc *RsFileItemSerialiser::deserialiseChunkCrc(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_VERSION1 != getRsItemVersion(rstype)) || - (RS_PKT_CLASS_BASE != getRsItemClass(rstype)) || - (RS_PKT_TYPE_FILE != getRsItemType(rstype)) || - (RS_PKT_SUBTYPE_FI_CHUNK_CRC != 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 */ - RsFileSingleChunkCrc *item = new RsFileSingleChunkCrc(); - item->clear(); - - /* skip the header */ - offset += 8; - ok &= GetTlvString(data, *pktsize, &offset, TLV_TYPE_STR_VALUE, item->hash); // file hash - ok &= getRawUInt32(data, rssize, &offset, &(item->chunk_number)); - ok &= getRawUInt32(data, rssize, &offset, &(item->check_sum.fourbytes[0])); - ok &= getRawUInt32(data, rssize, &offset, &(item->check_sum.fourbytes[1])); - ok &= getRawUInt32(data, rssize, &offset, &(item->check_sum.fourbytes[2])); - ok &= getRawUInt32(data, rssize, &offset, &(item->check_sum.fourbytes[3])); - ok &= getRawUInt32(data, rssize, &offset, &(item->check_sum.fourbytes[4])); - - if (offset != rssize) - { - /* error */ - delete item; - return NULL; - } - - if (!ok) - { - delete item; - return NULL; - } - - return item; -} -/*************************************************************************/ -/*************************************************************************/ - -uint32_t RsServiceSerialiser::size(RsItem *i) -{ - RsRawItem *item = dynamic_cast(i); - - if (item) - { - return item->getRawLength(); - } - return 0; -} - -/* serialise the data to the buffer */ -bool RsServiceSerialiser::serialise(RsItem *i, void *data, uint32_t *pktsize) -{ - RsRawItem *item = dynamic_cast(i); - if (!item) - { - return false; - } - - #ifdef RSSERIAL_DEBUG - std::cerr << "RsServiceSerialiser::serialise() serializing raw item. pktsize : " << *pktsize; - #endif - - uint32_t tlvsize = item->getRawLength(); - #ifdef RSSERIAL_DEBUG - std::cerr << "tlvsize : " << tlvsize << std::endl; - #endif - - if (*pktsize < tlvsize) - return false; /* not enough space */ - - if (tlvsize > getRsPktMaxSize()) - return false; /* packet too big */ - - *pktsize = tlvsize; - - /* its serialised already!!! */ - memcpy(data, item->getRawData(), tlvsize); - - return true; -} - -RsItem *RsServiceSerialiser::deserialise(void *data, uint32_t *pktsize) -{ - /* get the type and size */ - uint32_t rstype = getRsItemId(data); - uint32_t rssize = getRsItemSize(data); - - if (RS_PKT_VERSION_SERVICE != getRsItemVersion(rstype)) - { - return NULL; /* wrong type */ - } - - if (*pktsize < rssize) /* check size */ - return NULL; /* not enough data */ - - if (rssize > getRsPktMaxSize()) - return NULL; /* packet too big */ - - /* set the packet length */ - *pktsize = rssize; - - RsRawItem *item = new RsRawItem(rstype, rssize); - void *item_data = item->getRawData(); - - memcpy(item_data, data, rssize); - - return item; -} - - diff --git a/libretroshare/src/serialiser/rsbaseitems.h b/libretroshare/src/serialiser/rsbaseitems.h deleted file mode 100644 index 4fdc65d8b..000000000 --- a/libretroshare/src/serialiser/rsbaseitems.h +++ /dev/null @@ -1,331 +0,0 @@ -#ifndef RS_BASE_ITEMS_H -#define RS_BASE_ITEMS_H - -/* - * libretroshare/src/serialiser: rsbaseitems.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 "retroshare/rstypes.h" -#include "serialiser/rsserial.h" -#include "serialiser/rstlvtypes.h" - -const uint8_t RS_PKT_TYPE_FILE = 0x01; -const uint8_t RS_PKT_TYPE_CACHE = 0x02; - -const uint8_t RS_PKT_SUBTYPE_FI_REQUEST = 0x01; -const uint8_t RS_PKT_SUBTYPE_FI_DATA = 0x02; -const uint8_t RS_PKT_SUBTYPE_FI_TRANSFER = 0x03; -const uint8_t RS_PKT_SUBTYPE_FI_CHUNK_MAP_REQUEST = 0x04; -const uint8_t RS_PKT_SUBTYPE_FI_CHUNK_MAP = 0x05; -const uint8_t RS_PKT_SUBTYPE_FI_CRC32_MAP_REQUEST = 0x06; -const uint8_t RS_PKT_SUBTYPE_FI_CRC32_MAP = 0x07; -const uint8_t RS_PKT_SUBTYPE_FI_CHUNK_CRC_REQUEST = 0x08; -const uint8_t RS_PKT_SUBTYPE_FI_CHUNK_CRC = 0x09; - -const uint8_t RS_PKT_SUBTYPE_CACHE_ITEM = 0x01; -const uint8_t RS_PKT_SUBTYPE_CACHE_REQUEST = 0x02; - -/**************************************************************************/ - -class RsFileRequest: public RsItem -{ - public: - RsFileRequest() - :RsItem(RS_PKT_VERSION1, RS_PKT_CLASS_BASE, - RS_PKT_TYPE_FILE, - RS_PKT_SUBTYPE_FI_REQUEST) - { - setPriorityLevel(QOS_PRIORITY_RS_FILE_REQUEST) ; - } -virtual ~RsFileRequest(); -virtual void clear(); -std::ostream &print(std::ostream &out, uint16_t indent = 0); - - uint64_t fileoffset; /* start of data requested */ - uint32_t chunksize; /* size of data requested */ - RsTlvFileItem file; /* file information */ -}; - -/**************************************************************************/ - -class RsFileData: public RsItem -{ - public: - RsFileData() - :RsItem(RS_PKT_VERSION1, RS_PKT_CLASS_BASE, - RS_PKT_TYPE_FILE, - RS_PKT_SUBTYPE_FI_DATA) - { - setPriorityLevel(QOS_PRIORITY_RS_FILE_DATA) ; - } -virtual ~RsFileData(); -virtual void clear(); -std::ostream &print(std::ostream &out, uint16_t indent = 0); - - RsTlvFileData fd; -}; - -class RsFileChunkMapRequest: public RsItem -{ - public: - RsFileChunkMapRequest() - :RsItem(RS_PKT_VERSION1, RS_PKT_CLASS_BASE, RS_PKT_TYPE_FILE, RS_PKT_SUBTYPE_FI_CHUNK_MAP_REQUEST) - { - setPriorityLevel(QOS_PRIORITY_RS_FILE_MAP_REQUEST) ; - } - virtual ~RsFileChunkMapRequest() {} - virtual void clear() {} - - bool is_client ; // is the request for a client, or a server ? - std::string hash ; // hash of the file for which we request the chunk map - - std::ostream &print(std::ostream &out, uint16_t indent = 0); -}; - -class RsFileChunkMap: public RsItem -{ - public: - RsFileChunkMap() - :RsItem(RS_PKT_VERSION1, RS_PKT_CLASS_BASE, RS_PKT_TYPE_FILE, RS_PKT_SUBTYPE_FI_CHUNK_MAP) - { - setPriorityLevel(QOS_PRIORITY_RS_FILE_MAP) ; - } - virtual ~RsFileChunkMap() {} - virtual void clear() {} - - bool is_client ; // is the request for a client, or a server ? - std::string hash ; // hash of the file for which we request the chunk map - CompressedChunkMap compressed_map ; // Chunk map of the file. - - std::ostream &print(std::ostream &out, uint16_t indent = 0); -}; - -class RsFileCRC32MapRequest: public RsItem -{ - public: - RsFileCRC32MapRequest() - :RsItem(RS_PKT_VERSION1, RS_PKT_CLASS_BASE, RS_PKT_TYPE_FILE, RS_PKT_SUBTYPE_FI_CRC32_MAP_REQUEST) - { - setPriorityLevel(QOS_PRIORITY_RS_FILE_CRC_REQUEST) ; - } - virtual ~RsFileCRC32MapRequest() {} - virtual void clear() {} - - std::string hash ; // hash of the file for which we request the chunk map - - std::ostream &print(std::ostream &out, uint16_t indent = 0); -}; - -class RsFileSingleChunkCrcRequest: public RsItem -{ - public: - RsFileSingleChunkCrcRequest() - :RsItem(RS_PKT_VERSION1, RS_PKT_CLASS_BASE, RS_PKT_TYPE_FILE, RS_PKT_SUBTYPE_FI_CHUNK_CRC_REQUEST) - { - setPriorityLevel(QOS_PRIORITY_RS_CHUNK_CRC_REQUEST) ; - } - virtual ~RsFileSingleChunkCrcRequest() {} - virtual void clear() {} - - std::string hash ; // hash of the file for which we request the crc - uint32_t chunk_number ; // chunk number - - std::ostream &print(std::ostream &out, uint16_t indent = 0); -}; - - -class RsFileCRC32Map: public RsItem -{ - public: - RsFileCRC32Map() - :RsItem(RS_PKT_VERSION1, RS_PKT_CLASS_BASE, RS_PKT_TYPE_FILE, RS_PKT_SUBTYPE_FI_CRC32_MAP) - { - setPriorityLevel(QOS_PRIORITY_RS_FILE_CRC) ; - } - virtual ~RsFileCRC32Map() {} - virtual void clear() {} - - std::string hash ; // hash of the file for which we request the chunk map - CRC32Map crc_map ; // CRC32 map of the file. - - std::ostream &print(std::ostream &out, uint16_t indent = 0); -}; - -class RsFileSingleChunkCrc: public RsItem -{ - public: - RsFileSingleChunkCrc() - :RsItem(RS_PKT_VERSION1, RS_PKT_CLASS_BASE, RS_PKT_TYPE_FILE, RS_PKT_SUBTYPE_FI_CHUNK_CRC) - { - setPriorityLevel(QOS_PRIORITY_RS_CHUNK_CRC) ; - } - virtual ~RsFileSingleChunkCrc() {} - virtual void clear() {} - - std::string hash ; // hash of the file for which we request the chunk map - uint32_t chunk_number ; - Sha1CheckSum check_sum ; // CRC32 map of the file. - - std::ostream &print(std::ostream &out, uint16_t indent = 0); -}; - -/**************************************************************************/ - -class RsFileItemSerialiser: public RsSerialType -{ - public: - RsFileItemSerialiser() - :RsSerialType(RS_PKT_VERSION1, RS_PKT_CLASS_BASE, - RS_PKT_TYPE_FILE) - { return; } - virtual ~RsFileItemSerialiser() { 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: - - /* sub types */ - virtual uint32_t sizeReq(RsFileRequest *); - virtual uint32_t sizeData(RsFileData *); - virtual uint32_t sizeChunkMapReq(RsFileChunkMapRequest *); - virtual uint32_t sizeChunkMap(RsFileChunkMap *); - virtual uint32_t sizeChunkCrcReq(RsFileSingleChunkCrcRequest *); - virtual uint32_t sizeChunkCrc(RsFileSingleChunkCrc *); - virtual uint32_t sizeCRC32MapReq(RsFileCRC32MapRequest *); - virtual uint32_t sizeCRC32Map(RsFileCRC32Map *); - - virtual bool serialiseReq (RsFileRequest *item, void *data, uint32_t *size); - virtual bool serialiseData (RsFileData *item, void *data, uint32_t *size); - virtual bool serialiseChunkMapReq(RsFileChunkMapRequest *item, void *data, uint32_t *size); - virtual bool serialiseChunkMap(RsFileChunkMap *item, void *data, uint32_t *size); - virtual bool serialiseCRC32MapReq(RsFileCRC32MapRequest *item, void *data, uint32_t *size); - virtual bool serialiseCRC32Map(RsFileCRC32Map *item, void *data, uint32_t *size); - virtual bool serialiseChunkCrcReq(RsFileSingleChunkCrcRequest *item, void *data, uint32_t *size); - virtual bool serialiseChunkCrc(RsFileSingleChunkCrc *item, void *data, uint32_t *size); - - virtual RsFileRequest *deserialiseReq(void *data, uint32_t *size); - virtual RsFileData *deserialiseData(void *data, uint32_t *size); - virtual RsFileChunkMapRequest *deserialiseChunkMapReq(void *data, uint32_t *size); - virtual RsFileChunkMap *deserialiseChunkMap(void *data, uint32_t *size); - virtual RsFileCRC32MapRequest *deserialiseCRC32MapReq(void *data, uint32_t *size); - virtual RsFileCRC32Map *deserialiseCRC32Map(void *data, uint32_t *size); - virtual RsFileSingleChunkCrcRequest *deserialiseChunkCrcReq(void *data, uint32_t *size); - virtual RsFileSingleChunkCrc *deserialiseChunkCrc(void *data, uint32_t *size); -}; - -/**************************************************************************/ - -class RsCacheRequest: public RsItem -{ - public: - RsCacheRequest() - :RsItem(RS_PKT_VERSION1, RS_PKT_CLASS_BASE, - RS_PKT_TYPE_CACHE, - RS_PKT_SUBTYPE_CACHE_REQUEST) - { - setPriorityLevel(QOS_PRIORITY_RS_CACHE_REQUEST); - } -virtual ~RsCacheRequest(); -virtual void clear(); -std::ostream &print(std::ostream &out, uint16_t indent = 0); - - uint16_t cacheType; - uint16_t cacheSubId; - RsTlvFileItem file; /* file information */ -}; - -/**************************************************************************/ - -class RsCacheItem: public RsItem -{ - public: - RsCacheItem() - :RsItem(RS_PKT_VERSION1, RS_PKT_CLASS_BASE, - RS_PKT_TYPE_CACHE, - RS_PKT_SUBTYPE_CACHE_ITEM) - { - setPriorityLevel(QOS_PRIORITY_RS_CACHE_ITEM); - } -virtual ~RsCacheItem(); -virtual void clear(); -std::ostream &print(std::ostream &out, uint16_t indent = 0); - - uint16_t cacheType; - uint16_t cacheSubId; - RsTlvFileItem file; /* file information */ -}; - -/**************************************************************************/ - -class RsCacheItemSerialiser: public RsSerialType -{ - public: - RsCacheItemSerialiser() - :RsSerialType(RS_PKT_VERSION1, RS_PKT_CLASS_BASE, - RS_PKT_TYPE_CACHE) - { return; } -virtual ~RsCacheItemSerialiser() { 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: - - /* sub types */ -virtual uint32_t sizeReq(RsCacheRequest *); -virtual bool serialiseReq (RsCacheRequest *item, void *data, uint32_t *size); -virtual RsCacheRequest * deserialiseReq(void *data, uint32_t *size); - -virtual uint32_t sizeItem(RsCacheItem *); -virtual bool serialiseItem (RsCacheItem *item, void *data, uint32_t *size); -virtual RsCacheItem * deserialiseItem(void *data, uint32_t *size); - -}; - -/**************************************************************************/ - -class RsServiceSerialiser: public RsSerialType -{ - public: - RsServiceSerialiser() - :RsSerialType(RS_PKT_VERSION_SERVICE, 0, 0) - { return; } -virtual ~RsServiceSerialiser() - { return; } - -virtual uint32_t size(RsItem *); -virtual bool serialise (RsItem *item, void *data, uint32_t *size); -virtual RsItem * deserialise(void *data, uint32_t *size); - -}; - -/**************************************************************************/ - -#endif - diff --git a/libretroshare/src/serialiser/rsfiletransferitems.cc b/libretroshare/src/serialiser/rsfiletransferitems.cc new file mode 100644 index 000000000..32d87f4dd --- /dev/null +++ b/libretroshare/src/serialiser/rsfiletransferitems.cc @@ -0,0 +1,900 @@ + +/* + * libretroshare/src/serialiser: rsbaseitems.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/rstlvbase.h" +#include "serialiser/rsfiletransferitems.h" + +/*** + * #define RSSERIAL_DEBUG 1 + * #define DEBUG_TRANSFERS 1 +***/ + + +#ifdef DEBUG_TRANSFERS + #include "util/rsprint.h" +#endif + +#include + +/**********************************************************************************************/ +/* SERIALISER STUFF */ +/**********************************************************************************************/ + +RsFileTransferItem *RsFileTransferSerialiser::deserialise(void *data, uint32_t *pktsize) +{ + /* get the type and size */ + uint32_t rstype = getRsItemId(data); + + if(RS_PKT_VERSION_SERVICE != getRsItemVersion(rstype) || RS_SERVICE_TYPE_FILE_TRANSFER != getRsItemService(rstype)) + { + return NULL; /* wrong type */ + } + + switch(getRsItemSubType(rstype)) + { + case RS_PKT_SUBTYPE_FT_CACHE_REQUEST: return deserialise_RsFileTransferCacheRequestItem(data, *pktsize); + case RS_PKT_SUBTYPE_FT_CACHE_ITEM: return deserialise_RsFileTransferCacheItem(data, *pktsize); + case RS_PKT_SUBTYPE_FT_DATA_REQUEST: return deserialise_RsFileTransferDataRequestItem(data, *pktsize); + case RS_PKT_SUBTYPE_FT_DATA: return deserialise_RsFileTransferDataItem(data, *pktsize); + case RS_PKT_SUBTYPE_FT_CHUNK_MAP_REQUEST: return deserialise_RsFileTransferChunkMapRequestItem(data,*pktsize) ; + case RS_PKT_SUBTYPE_FT_CHUNK_MAP: return deserialise_RsFileTransferChunkMapItem(data,*pktsize) ; + case RS_PKT_SUBTYPE_FT_CHUNK_CRC_REQUEST: return deserialise_RsFileTransferSingleChunkCrcRequestItem(data,*pktsize) ; + case RS_PKT_SUBTYPE_FT_CHUNK_CRC: return deserialise_RsFileTransferSingleChunkCrcItem(data,*pktsize) ; + default: + return NULL; + } + return NULL; +} + +/**********************************************************************************************/ +/* OUTPUTS */ +/**********************************************************************************************/ + +std::ostream& RsFileTransferCacheRequestItem::print(std::ostream &out, uint16_t indent) +{ + printRsItemBase(out, "RsFileTransferCacheRequestItem", indent); + uint16_t int_Indent = indent + 2; + printIndent(out, int_Indent); + out << "CacheId: " << cacheType << "/" << cacheSubId << std::endl; + file.print(out, int_Indent); + printRsItemEnd(out, "RsFileTransferCacheRequestItem", indent); + return out; +} + +std::ostream& RsFileTransferCacheItem::print(std::ostream &out, uint16_t indent) +{ + printRsItemBase(out, "RsFileTransferCacheItem", indent); + uint16_t int_Indent = indent + 2; + printIndent(out, int_Indent); + out << "CacheId: " << cacheType << "/" << cacheSubId << std::endl; + file.print(out, int_Indent); + printRsItemEnd(out, "RsFileTransferCacheItem", indent); + return out; +} +std::ostream& RsFileTransferDataRequestItem::print(std::ostream &out, uint16_t indent) +{ + printRsItemBase(out, "RsFileTransferDataRequestItem", indent); + uint16_t int_Indent = indent + 2; + printIndent(out, int_Indent); + out << "FileOffset: " << fileoffset; + out << " ChunkSize: " << chunksize << std::endl; + file.print(out, int_Indent); + printRsItemEnd(out, "RsFileTransferDataRequestItem", indent); + return out; +} +std::ostream& RsFileTransferChunkMapItem::print(std::ostream &out, uint16_t indent) +{ + printRsItemBase(out, "RsFileTransferChunkMapItem", indent); + uint16_t int_Indent = indent + 2; + printIndent(out, int_Indent); out << "PeerId: " << PeerId() << std::endl ; + printIndent(out, int_Indent); out << " hash: " << hash << std::endl ; + printIndent(out, int_Indent); out << "chunks: " << std::hex << compressed_map._map[0] << std::dec << "..." << std::endl ; + printRsItemEnd(out, "RsFileTransferChunkMapItem", indent); + return out; +} +std::ostream& RsFileTransferChunkMapRequestItem::print(std::ostream &out, uint16_t indent) +{ + printRsItemBase(out, "RsFileTransferChunkMapRequestItem", indent); + uint16_t int_Indent = indent + 2; + printIndent(out, int_Indent); out << "PeerId: " << PeerId() << std::endl ; + printIndent(out, int_Indent); out << " hash: " << hash << std::endl ; + printRsItemEnd(out, "RsFileTransferChunkMapRequestItem", indent); + return out; +} +std::ostream& RsFileTransferSingleChunkCrcRequestItem::print(std::ostream &out, uint16_t indent) +{ + printRsItemBase(out, "RsFileTransferSingleChunkCrcRequestItem", indent); + uint16_t int_Indent = indent + 2; + printIndent(out, int_Indent); out << "PeerId: " << PeerId() << std::endl ; + printIndent(out, int_Indent); out << " hash: " << hash << std::endl ; + printIndent(out, int_Indent); out << " chunk: " << chunk_number << "..." << std::endl ; + printRsItemEnd(out, "RsFileTransferSingleChunkCrcRequestItem", indent); + return out; +} +std::ostream& RsFileTransferSingleChunkCrcItem::print(std::ostream &out, uint16_t indent) +{ + printRsItemBase(out, "RsFileTransferSingleChunkCrcItem", indent); + uint16_t int_Indent = indent + 2; + printIndent(out, int_Indent); out << "PeerId: " << PeerId() << std::endl ; + printIndent(out, int_Indent); out << " hash: " << hash << std::endl ; + printIndent(out, int_Indent); out << " chunk: " << chunk_number << "..." << std::endl ; + printIndent(out, int_Indent); out << " sha1: " << check_sum.toStdString() << "..." << std::endl ; + printRsItemEnd(out, "RsFileTransferSingleChunkCrcItem", indent); + return out; +} +std::ostream& RsFileTransferDataItem::print(std::ostream &out, uint16_t indent) +{ + printRsItemBase(out, "RsFileTransferDataItem", indent); + uint16_t int_Indent = indent + 2; + fd.print(out, int_Indent); + printRsItemEnd(out, "RsFileTransferDataItem", indent); + return out; +} + +/**********************************************************************************************/ +/* SERIAL SIZE */ +/**********************************************************************************************/ + +uint32_t RsFileTransferDataRequestItem::serial_size() +{ + uint32_t s = 8; /* header */ + s += 8; /* offset */ + s += 4; /* chunksize */ + s += file.TlvSize(); + + return s; +} +uint32_t RsFileTransferCacheItem::serial_size() +{ + uint32_t s = 8; /* header */ + s += 4; /* type/subid */ + s += file.TlvSize(); + + return s; +} +uint32_t RsFileTransferDataItem::serial_size() +{ + uint32_t s = 8; /* header */ + s += fd.TlvSize(); + + return s; +} +uint32_t RsFileTransferCacheRequestItem::serial_size() +{ + uint32_t s = 8; /* header */ + s += 4; /* type/subid */ + s += file.TlvSize(); + + return s; +} +uint32_t RsFileTransferChunkMapRequestItem::serial_size() +{ + uint32_t s = 8; /* header */ + s += 1 ; // is_client + s += GetTlvStringSize(hash) ; // hash + + return s; +} +uint32_t RsFileTransferChunkMapItem::serial_size() +{ + uint32_t s = 8; /* header */ + s += 1 ; // is_client + s += GetTlvStringSize(hash) ; // hash + s += 4 ; // compressed map size + s += 4 * compressed_map._map.size() ; // compressed chunk map + + return s; +} +uint32_t RsFileTransferSingleChunkCrcItem::serial_size() +{ + uint32_t s = 8; /* header */ + s += GetTlvStringSize(hash) ; // hash + s += 4 ; // chunk number + s += 20 ; // sha1 + + return s; +} +uint32_t RsFileTransferSingleChunkCrcRequestItem::serial_size() +{ + uint32_t s = 8; /* header */ + s += GetTlvStringSize(hash) ; // hash + s += 4 ; // chunk number + + return s; +} + +/*************************************************************************/ + +void RsFileTransferDataRequestItem::clear() +{ + file.TlvClear(); + fileoffset = 0; + chunksize = 0; +} +void RsFileTransferCacheItem::clear() +{ + cacheType = 0; + cacheSubId = 0; + file.TlvClear(); +} +void RsFileTransferDataItem::clear() +{ + fd.TlvClear(); +} +void RsFileTransferCacheRequestItem::clear() +{ + cacheType = 0; + cacheSubId = 0; + file.TlvClear(); +} + +/**********************************************************************************************/ +/* SERIALISATION */ +/**********************************************************************************************/ + +bool RsFileTransferItem::serialise_header(void *data,uint32_t& pktsize,uint32_t& tlvsize, uint32_t& offset) +{ + tlvsize = serial_size() ; + offset = 0; + + if (pktsize < tlvsize) + return false; /* not enough space */ + + pktsize = tlvsize; + + bool ok = true; + + if(!setRsItemHeader(data, tlvsize, PacketId(), tlvsize)) + { + std::cerr << "RsFileTransferItem::serialise_header(): ERROR. Not enough size!" << std::endl; + return false ; + } +#ifdef RSSERIAL_DEBUG + std::cerr << "RsFileItemSerialiser::serialiseData() Header: " << ok << std::endl; +#endif + offset += 8; + + return true ; +} + +/* serialise the data to the buffer */ +bool RsFileTransferChunkMapRequestItem::serialise(void *data, uint32_t& pktsize) +{ + uint32_t tlvsize,offset=0; + bool ok = true; + + if(!serialise_header(data,pktsize,tlvsize,offset)) + return false ; + + /* add mandatory parts first */ + ok &= setRawUInt8(data, tlvsize, &offset, is_client); + ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_VALUE, hash); + + if (offset != tlvsize) + { + ok = false; + std::cerr << "RsFileItemSerialiser::serialiseData() Size Error! " << std::endl; + } + + return ok; +} +bool RsFileTransferSingleChunkCrcRequestItem::serialise(void *data, uint32_t& pktsize) +{ + uint32_t tlvsize,offset=0; + bool ok = true; + + if(!serialise_header(data,pktsize,tlvsize,offset)) + return false ; + + /* add mandatory parts first */ + ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_VALUE, hash); + ok &= setRawUInt32(data, tlvsize, &offset, chunk_number) ; + + if (offset != tlvsize) + { + ok = false; + std::cerr << "RsFileItemSerialiser::serialiseData() Size Error! " << std::endl; + } + + return ok; +} +bool RsFileTransferSingleChunkCrcItem::serialise(void *data, uint32_t& pktsize) +{ + uint32_t tlvsize,offset=0; + bool ok = true; + + if(!serialise_header(data,pktsize,tlvsize,offset)) + return false ; + + /* add mandatory parts first */ + ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_VALUE, hash); + ok &= setRawUInt32(data, tlvsize, &offset, chunk_number) ; + ok &= setRawUInt32(data, tlvsize, &offset, check_sum.fourbytes[0]) ; + ok &= setRawUInt32(data, tlvsize, &offset, check_sum.fourbytes[1]) ; + ok &= setRawUInt32(data, tlvsize, &offset, check_sum.fourbytes[2]) ; + ok &= setRawUInt32(data, tlvsize, &offset, check_sum.fourbytes[3]) ; + ok &= setRawUInt32(data, tlvsize, &offset, check_sum.fourbytes[4]) ; + + if (offset != tlvsize) + { + ok = false; + std::cerr << "RsFileItemSerialiser::serialiseData() Size Error! " << std::endl; + } + + return ok; +} +bool RsFileTransferChunkMapItem::serialise(void *data, uint32_t& pktsize) +{ + uint32_t tlvsize,offset=0; + bool ok = true; + + if(!serialise_header(data,pktsize,tlvsize,offset)) + return false ; + + /* add mandatory parts first */ + ok &= setRawUInt8(data, tlvsize, &offset, is_client); + ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_VALUE, hash); + ok &= setRawUInt32(data, tlvsize, &offset, compressed_map._map.size()); + + for(uint32_t i=0;iclear(); + + /* skip the header */ + offset += 8; + + /* get mandatory parts first */ + ok &= getRawUInt16(data, rssize, &offset, &(item->cacheType)); + ok &= getRawUInt16(data, rssize, &offset, &(item->cacheSubId)); + ok &= item->file.GetTlv(data, rssize, &offset); + + if (offset != rssize) + { + /* error */ + delete item; + return NULL; + } + + if (!ok) + { + delete item; + return NULL; + } + + return item; +} + + +RsFileTransferItem *RsFileTransferSerialiser::deserialise_RsFileTransferCacheItem(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_FILE_TRANSFER != getRsItemType(rstype) || RS_PKT_SUBTYPE_FT_CACHE_ITEM != getRsItemSubType(rstype)) + { + std::cerr << "RsFileTransferSerialiser::deserialise_RsFileTransferCacheItem(): wong subtype!" << std::endl; + return NULL; /* wrong type */ + } + + if (pktsize < rssize) /* check size */ + { + std::cerr << "RsFileTransferSerialiser::deserialise_RsFileTransferCacheItem(): size inconsistency!" << std::endl; + return NULL; /* not enough data */ + } + + bool ok = true; + + /* ready to load */ + RsFileTransferCacheItem *item = new RsFileTransferCacheItem(); + item->clear(); + + /* skip the header */ + offset += 8; + + /* get mandatory parts first */ + ok &= getRawUInt16(data, rssize, &offset, &(item->cacheType)); + ok &= getRawUInt16(data, rssize, &offset, &(item->cacheSubId)); + ok &= item->file.GetTlv(data, rssize, &offset); + + if (offset != rssize) + { + /* error */ + delete item; + return NULL; + } + + if (!ok) + { + delete item; + return NULL; + } + + return item; +} + +RsFileTransferItem *RsFileTransferSerialiser::deserialise_RsFileTransferChunkMapRequestItem(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_FILE_TRANSFER != getRsItemType(rstype) || RS_PKT_SUBTYPE_FT_CHUNK_MAP_REQUEST != getRsItemSubType(rstype)) + { + std::cerr << "RsFileTransferSerialiser::deserialise_RsFileTransferChunkMapRequestItem(): wong subtype!" << std::endl; + return NULL; /* wrong type */ + } + + if (pktsize < rssize) /* check size */ + { + std::cerr << "RsFileTransferSerialiser::deserialise_RsFileTransferChunkMapRequestItem(): size inconsistency!" << std::endl; + return NULL; /* not enough data */ + } + + bool ok = true; + + /* ready to load */ + RsFileTransferChunkMapRequestItem *item = new RsFileTransferChunkMapRequestItem(); + item->clear(); + + /* skip the header */ + offset += 8; + uint8_t tmp ; + ok &= getRawUInt8(data, rssize, &offset, &tmp); item->is_client = tmp; + ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_VALUE, item->hash); // file hash + + if (offset != rssize) + { + /* error */ + delete item; + return NULL; + } + + if (!ok) + { + delete item; + return NULL; + } + + return item; +} + +RsFileTransferItem *RsFileTransferSerialiser::deserialise_RsFileTransferDataItem(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_FILE_TRANSFER != getRsItemType(rstype) || RS_PKT_SUBTYPE_FT_DATA != getRsItemSubType(rstype)) + { + std::cerr << "RsFileTransferSerialiser::deserialise_RsFileTransferDataItem(): wong subtype!" << std::endl; + return NULL; /* wrong type */ + } + + if (pktsize < rssize) /* check size */ + { + std::cerr << "RsFileTransferSerialiser::deserialise_RsFileTransferDataItem(): size inconsistency!" << std::endl; + return NULL; /* not enough data */ + } + + bool ok = true; + + /* ready to load */ + RsFileTransferDataItem *item = new RsFileTransferDataItem(); + item->clear(); + + /* skip the header */ + offset += 8; + + /* get mandatory parts first */ + ok &= item->fd.GetTlv(data, rssize, &offset); + + if (offset != rssize) + { + /* error */ + delete item; + return NULL; + } + + if (!ok) + { + delete item; + return NULL; + } + +#ifdef DEBUG_TRANSFERS + std::cerr << "RsFileTransferSerialiser::deserialise_RsFileTransferDataItem() at: " << RsUtil::AccurateTimeString() << std::endl; + item->print(std::cerr, 10); +#endif + + return item; +} + + +RsFileTransferItem *RsFileTransferSerialiser::deserialise_RsFileTransferDataRequestItem(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_FILE_TRANSFER != getRsItemType(rstype) || RS_PKT_SUBTYPE_FT_DATA_REQUEST != getRsItemSubType(rstype)) + { + std::cerr << "RsFileTransferSerialiser::deserialise_RsFileTransferDataRequestItem(): wrong subtype!" << std::endl; + return NULL; /* wrong type */ + } + + if (pktsize < rssize) /* check size */ + { + std::cerr << "RsFileTransferSerialiser::deserialise_RsFileTransferDataRequestItem(): size inconsistency!" << std::endl; + return NULL; /* not enough data */ + } + + RsFileTransferDataRequestItem *item = new RsFileTransferDataRequestItem() ; + + bool ok = true; + + /* skip the header */ + offset += 8; + + /* get mandatory parts first */ + ok &= getRawUInt64(data, rssize, &offset, &item->fileoffset); + ok &= getRawUInt32(data, rssize, &offset, &item->chunksize); + ok &= item->file.GetTlv(data, rssize, &offset); + + if (offset != rssize) + { + /* error */ + delete item; + return NULL; + } + + if (!ok) + { + delete item; + return NULL; + } + + /*** Debugging Transfer rates. + * print timestamp, and file details so we can workout packet lags. + ***/ + +#ifdef DEBUG_TRANSFERS + std::cerr << "RsFileItemSerialiser::deserialise_RsFileTransferDataRequestItem() at: " << RsUtil::AccurateTimeString() << std::endl; + item->print(std::cerr, 10); +#endif + + return item; +} +RsFileTransferItem *RsFileTransferSerialiser::deserialise_RsFileTransferChunkMapItem(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_FILE_TRANSFER != getRsItemType(rstype) || RS_PKT_SUBTYPE_FT_CHUNK_MAP != getRsItemSubType(rstype)) + { + std::cerr << "RsFileTransferSerialiser::deserialise_RsFileTransferChunkMapItem(): wrong subtype!" << std::endl; + return NULL; /* wrong type */ + } + + if (pktsize < rssize) /* check size */ + { + std::cerr << "RsFileTransferSerialiser::deserialise_RsFileTransferChunkMapItem(): size inconsistency!" << std::endl; + return NULL; /* not enough data */ + } + + bool ok = true; + + /* ready to load */ + RsFileTransferChunkMapItem *item = new RsFileTransferChunkMapItem(); + item->clear(); + + /* skip the header */ + offset += 8; + uint8_t tmp ; + ok &= getRawUInt8(data, rssize, &offset, &tmp); item->is_client = tmp; + ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_VALUE, item->hash); // file hash + uint32_t size =0; + ok &= getRawUInt32(data, rssize, &offset, &size); + + if(ok) + { + item->compressed_map._map.resize(size) ; + + for(uint32_t i=0;icompressed_map._map[i])); + } + + if (offset != rssize) + { + /* error */ + delete item; + return NULL; + } + + if (!ok) + { + delete item; + return NULL; + } + + return item; +} + +RsFileTransferItem *RsFileTransferSerialiser::deserialise_RsFileTransferSingleChunkCrcRequestItem(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_FILE_TRANSFER != getRsItemType(rstype) || RS_PKT_SUBTYPE_FT_CHUNK_CRC_REQUEST != getRsItemSubType(rstype)) + { + std::cerr << "RsFileTransferSerialiser::deserialise_RsFileTransferSingleChunkCrcRequestItem(): wrong subtype!" << std::endl; + return NULL; /* wrong type */ + } + + if (pktsize < rssize) /* check size */ + { + std::cerr << "RsFileTransferSerialiser::deserialise_RsFileTransferSingleChunkCrcRequestItem(): size inconsistency!" << std::endl; + return NULL; /* not enough data */ + } + + bool ok = true; + + /* ready to load */ + RsFileTransferSingleChunkCrcRequestItem *item = new RsFileTransferSingleChunkCrcRequestItem(); + item->clear(); + + /* skip the header */ + offset += 8; + ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_VALUE, item->hash); // file hash + ok &= getRawUInt32(data, rssize, &offset, &(item->chunk_number)); + + if (offset != rssize) + { + /* error */ + delete item; + return NULL; + } + + if (!ok) + { + delete item; + return NULL; + } + + return item; +} +RsFileTransferItem *RsFileTransferSerialiser::deserialise_RsFileTransferSingleChunkCrcItem(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_FILE_TRANSFER != getRsItemType(rstype) || RS_PKT_SUBTYPE_FT_CHUNK_CRC != getRsItemSubType(rstype)) + { + std::cerr << "RsFileTransferSerialiser::deserialise_RsFileTransferSingleChunkCrcItem(): wrong subtype!" << std::endl; + return NULL; /* wrong type */ + } + + if (pktsize < rssize) /* check size */ + { + std::cerr << "RsFileTransferSerialiser::deserialise_RsFileTransferSingleChunkCrcItem(): size inconsistency!" << std::endl; + return NULL; /* not enough data */ + } + + bool ok = true; + + /* ready to load */ + RsFileTransferSingleChunkCrcItem *item = new RsFileTransferSingleChunkCrcItem(); + item->clear(); + + /* skip the header */ + offset += 8; + ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_VALUE, item->hash); // file hash + ok &= getRawUInt32(data, rssize, &offset, &(item->chunk_number)); + ok &= getRawUInt32(data, rssize, &offset, &(item->check_sum.fourbytes[0])); + ok &= getRawUInt32(data, rssize, &offset, &(item->check_sum.fourbytes[1])); + ok &= getRawUInt32(data, rssize, &offset, &(item->check_sum.fourbytes[2])); + ok &= getRawUInt32(data, rssize, &offset, &(item->check_sum.fourbytes[3])); + ok &= getRawUInt32(data, rssize, &offset, &(item->check_sum.fourbytes[4])); + + if (offset != rssize) + { + /* error */ + delete item; + return NULL; + } + + if (!ok) + { + delete item; + return NULL; + } + + return item; +} +/*************************************************************************/ diff --git a/libretroshare/src/serialiser/rsfiletransferitems.h b/libretroshare/src/serialiser/rsfiletransferitems.h new file mode 100644 index 000000000..96697b1e3 --- /dev/null +++ b/libretroshare/src/serialiser/rsfiletransferitems.h @@ -0,0 +1,271 @@ +#pragma once + +/* + * libretroshare/src/serialiser: rsbaseitems.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 "retroshare/rstypes.h" +#include "serialiser/rsserial.h" +#include "serialiser/rstlvtypes.h" +#include "serialiser/rsserviceids.h" + +const uint8_t RS_PKT_SUBTYPE_FT_DATA_REQUEST = 0x01; +const uint8_t RS_PKT_SUBTYPE_FT_DATA = 0x02; +const uint8_t RS_PKT_SUBTYPE_FT_CHUNK_MAP_REQUEST = 0x04; +const uint8_t RS_PKT_SUBTYPE_FT_CHUNK_MAP = 0x05; +const uint8_t RS_PKT_SUBTYPE_FT_CHUNK_CRC_REQUEST = 0x08; +const uint8_t RS_PKT_SUBTYPE_FT_CHUNK_CRC = 0x09; + +const uint8_t RS_PKT_SUBTYPE_FT_CACHE_ITEM = 0x0A; +const uint8_t RS_PKT_SUBTYPE_FT_CACHE_REQUEST = 0x0B; + +//const uint8_t RS_PKT_SUBTYPE_FT_TRANSFER = 0x03; +//const uint8_t RS_PKT_SUBTYPE_FT_CRC32_MAP_REQUEST = 0x06; +//const uint8_t RS_PKT_SUBTYPE_FT_CRC32_MAP = 0x07; + +/**************************************************************************/ + +class RsFileTransferItem: public RsItem +{ + public: + RsFileTransferItem(uint8_t ft_subtype) + : RsItem(RS_PKT_VERSION_SERVICE,RS_SERVICE_TYPE_FILE_TRANSFER,ft_subtype) + {} + + virtual ~RsFileTransferItem() {} + + virtual bool serialise(void *data,uint32_t& size) = 0 ; + virtual uint32_t serial_size() = 0 ; + + virtual std::ostream &print(std::ostream &out, uint16_t indent = 0) = 0; + virtual void clear() = 0 ; + + protected: + bool serialise_header(void *data, uint32_t& pktsize, uint32_t& tlvsize, uint32_t& offset) ; +}; + +class RsFileTransferDataRequestItem: public RsFileTransferItem +{ + public: + RsFileTransferDataRequestItem() :RsFileTransferItem(RS_PKT_SUBTYPE_FT_DATA_REQUEST) + { + setPriorityLevel(QOS_PRIORITY_RS_FILE_REQUEST) ; + } + virtual ~RsFileTransferDataRequestItem() {} + + virtual bool serialise(void *data,uint32_t& size) ; + virtual uint32_t serial_size() ; + + virtual void clear(); + + std::ostream &print(std::ostream &out, uint16_t indent = 0); + + // Private data part. + // + uint64_t fileoffset; /* start of data requested */ + uint32_t chunksize; /* size of data requested */ + RsTlvFileItem file; /* file information */ +}; + +/**************************************************************************/ + +class RsFileTransferDataItem: public RsFileTransferItem +{ + public: + RsFileTransferDataItem() :RsFileTransferItem(RS_PKT_SUBTYPE_FT_DATA) + { + setPriorityLevel(QOS_PRIORITY_RS_FILE_DATA) ; + } + virtual ~RsFileTransferDataItem() { clear() ; } + + virtual bool serialise(void *data,uint32_t& size) ; + virtual uint32_t serial_size() ; + virtual void clear(); + + virtual std::ostream& print(std::ostream &out, uint16_t indent = 0); + + // Private data part. + // + RsTlvFileData fd; +}; + +class RsFileTransferChunkMapRequestItem: public RsFileTransferItem +{ + public: + RsFileTransferChunkMapRequestItem() :RsFileTransferItem(RS_PKT_SUBTYPE_FT_CHUNK_MAP_REQUEST) + { + setPriorityLevel(QOS_PRIORITY_RS_FILE_MAP_REQUEST) ; + } + virtual ~RsFileTransferChunkMapRequestItem() {} + virtual bool serialise(void *data,uint32_t& size) ; + virtual uint32_t serial_size() ; + virtual void clear() {} + virtual std::ostream &print(std::ostream &out, uint16_t indent = 0); + + // Private data part. + // + bool is_client ; // is the request for a client, or a server ? + std::string hash ; // hash of the file for which we request the chunk map +}; + +class RsFileTransferChunkMapItem: public RsFileTransferItem +{ + public: + RsFileTransferChunkMapItem() + :RsFileTransferItem(RS_PKT_SUBTYPE_FT_CHUNK_MAP) + { + setPriorityLevel(QOS_PRIORITY_RS_FILE_MAP) ; + } + virtual ~RsFileTransferChunkMapItem() {} + virtual bool serialise(void *data,uint32_t& size) ; + virtual uint32_t serial_size() ; + virtual void clear() {} + + virtual std::ostream &print(std::ostream &out, uint16_t indent = 0); + + // Private data part. + // + bool is_client ; // is the request for a client, or a server ? + std::string hash ; // hash of the file for which we request the chunk map + CompressedChunkMap compressed_map ; // Chunk map of the file. +}; + +class RsFileTransferSingleChunkCrcRequestItem: public RsFileTransferItem +{ + public: + RsFileTransferSingleChunkCrcRequestItem() :RsFileTransferItem(RS_PKT_SUBTYPE_FT_CHUNK_CRC_REQUEST) + { + setPriorityLevel(QOS_PRIORITY_RS_CHUNK_CRC_REQUEST) ; + } + virtual ~RsFileTransferSingleChunkCrcRequestItem() {} + virtual bool serialise(void *data,uint32_t& size) ; + virtual uint32_t serial_size() ; + virtual void clear() {} + + virtual std::ostream &print(std::ostream &out, uint16_t indent = 0); + + // Private data part. + // + std::string hash ; // hash of the file for which we request the crc + uint32_t chunk_number ; // chunk number +}; + +class RsFileTransferSingleChunkCrcItem: public RsFileTransferItem +{ + public: + RsFileTransferSingleChunkCrcItem() :RsFileTransferItem(RS_PKT_SUBTYPE_FT_CHUNK_CRC) + { + setPriorityLevel(QOS_PRIORITY_RS_CHUNK_CRC) ; + } + virtual ~RsFileTransferSingleChunkCrcItem() {} + virtual bool serialise(void *data,uint32_t& size) ; + virtual uint32_t serial_size() ; + virtual void clear() {} + + virtual std::ostream &print(std::ostream &out, uint16_t indent = 0); + + // Private data part. + // + std::string hash ; // hash of the file for which we request the chunk map + uint32_t chunk_number ; + Sha1CheckSum check_sum ; // CRC32 map of the file. +}; + +class RsFileTransferCacheRequestItem: public RsFileTransferItem +{ + public: + RsFileTransferCacheRequestItem() :RsFileTransferItem(RS_PKT_SUBTYPE_FT_CACHE_REQUEST) + { + setPriorityLevel(QOS_PRIORITY_RS_CACHE_REQUEST); + } + virtual ~RsFileTransferCacheRequestItem() {} + virtual bool serialise(void *data,uint32_t& size) ; + virtual uint32_t serial_size() ; + virtual void clear(); + std::ostream &print(std::ostream &out, uint16_t indent = 0); + + // private part + // + uint16_t cacheType; + uint16_t cacheSubId; + RsTlvFileItem file; /* file information */ +}; + +class RsFileTransferCacheItem: public RsFileTransferItem +{ + public: + RsFileTransferCacheItem() :RsFileTransferItem(RS_PKT_SUBTYPE_FT_CACHE_ITEM) + { + setPriorityLevel(QOS_PRIORITY_RS_CACHE_ITEM); + } + + virtual ~RsFileTransferCacheItem(){ clear() ; } + virtual bool serialise(void *data,uint32_t& size) ; + virtual uint32_t serial_size() ; + virtual void clear(); + virtual std::ostream &print(std::ostream &out, uint16_t indent = 0); + + // private part. + // + uint16_t cacheType; + uint16_t cacheSubId; + RsTlvFileItem file; /* file information */ +}; + + +/**************************************************************************/ + +class RsFileTransferSerialiser: public RsSerialType +{ + public: + RsFileTransferSerialiser(): RsSerialType(RS_PKT_VERSION_SERVICE, RS_SERVICE_TYPE_FILE_TRANSFER) {} + + virtual ~RsFileTransferSerialiser() {} + + virtual uint32_t size(RsItem *item) + { + return dynamic_cast(item)->serial_size() ; + } + virtual bool serialise(RsItem *item, void *data, uint32_t *size) + { + return dynamic_cast(item)->serialise(data,*size) ; + } + virtual RsFileTransferItem *deserialise(void *data, uint32_t *size); + + private: + RsFileTransferItem *deserialise_RsFileTransferCacheRequestItem(void *data, uint32_t pktsize); + RsFileTransferItem *deserialise_RsFileTransferCacheItem(void *data, uint32_t pktsize); + RsFileTransferItem *deserialise_RsFileTransferChunkMapRequestItem(void *data, uint32_t pktsize); + RsFileTransferItem *deserialise_RsFileTransferChunkMapItem(void *data, uint32_t pktsize); + RsFileTransferItem *deserialise_RsFileTransferDataRequestItem(void *data, uint32_t pktsize); + RsFileTransferItem *deserialise_RsFileTransferDataItem(void *data, uint32_t pktsize); + RsFileTransferItem *deserialise_RsFileTransferSingleChunkCrcItem(void *data, uint32_t pktsize); + RsFileTransferItem *deserialise_RsFileTransferSingleChunkCrcRequestItem(void *data, uint32_t pktsize); + +}; + +/**************************************************************************/ + diff --git a/libretroshare/src/serialiser/rsserviceids.h b/libretroshare/src/serialiser/rsserviceids.h index 08c64c992..aa2ca0a8b 100644 --- a/libretroshare/src/serialiser/rsserviceids.h +++ b/libretroshare/src/serialiser/rsserviceids.h @@ -38,15 +38,16 @@ */ /* These are Cache Only */ -const uint16_t RS_SERVICE_TYPE_FILE_INDEX = 0x0001; +const uint16_t RS_SERVICE_TYPE_FILE_INDEX = 0x0001; /* These are Services only */ -const uint16_t RS_SERVICE_TYPE_DISC = 0x0011; -const uint16_t RS_SERVICE_TYPE_CHAT = 0x0012; -const uint16_t RS_SERVICE_TYPE_MSG = 0x0013; -const uint16_t RS_SERVICE_TYPE_TURTLE = 0x0014; -const uint16_t RS_SERVICE_TYPE_TUNNEL = 0x0015; -const uint16_t RS_SERVICE_TYPE_HEARTBEAT = 0x0016; +const uint16_t RS_SERVICE_TYPE_DISC = 0x0011; +const uint16_t RS_SERVICE_TYPE_CHAT = 0x0012; +const uint16_t RS_SERVICE_TYPE_MSG = 0x0013; +const uint16_t RS_SERVICE_TYPE_TURTLE = 0x0014; +const uint16_t RS_SERVICE_TYPE_TUNNEL = 0x0015; +const uint16_t RS_SERVICE_TYPE_HEARTBEAT = 0x0016; +const uint16_t RS_SERVICE_TYPE_FILE_TRANSFER = 0x0017; /* BanList Still Testing at the moment - Service Only */ const uint16_t RS_SERVICE_TYPE_BANLIST = 0x0101; diff --git a/libretroshare/src/serialiser/rsserviceserialiser.cc b/libretroshare/src/serialiser/rsserviceserialiser.cc new file mode 100644 index 000000000..247b2281e --- /dev/null +++ b/libretroshare/src/serialiser/rsserviceserialiser.cc @@ -0,0 +1,99 @@ +/* + * libretroshare/src/serialiser: rsserviceserialiser.cc + * + * 3P/PQI network interface for RetroShare. + * + * Copyright 2013-2013 by Cyril Soler & 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 "rsserviceserialiser.h" + +uint32_t RsServiceSerialiser::size(RsItem *i) +{ + RsRawItem *item = dynamic_cast(i); + + if (item) + { + return item->getRawLength(); + } + return 0; +} + +/* serialise the data to the buffer */ +bool RsServiceSerialiser::serialise(RsItem *i, void *data, uint32_t *pktsize) +{ + RsRawItem *item = dynamic_cast(i); + if (!item) + { + return false; + } + + #ifdef RSSERIAL_DEBUG + std::cerr << "RsServiceSerialiser::serialise() serializing raw item. pktsize : " << *pktsize; + #endif + + uint32_t tlvsize = item->getRawLength(); + #ifdef RSSERIAL_DEBUG + std::cerr << "tlvsize : " << tlvsize << std::endl; + #endif + + if (*pktsize < tlvsize) + return false; /* not enough space */ + + if (tlvsize > getRsPktMaxSize()) + return false; /* packet too big */ + + *pktsize = tlvsize; + + /* its serialised already!!! */ + memcpy(data, item->getRawData(), tlvsize); + + return true; +} + +RsItem *RsServiceSerialiser::deserialise(void *data, uint32_t *pktsize) +{ + /* get the type and size */ + uint32_t rstype = getRsItemId(data); + uint32_t rssize = getRsItemSize(data); + + if (RS_PKT_VERSION_SERVICE != getRsItemVersion(rstype)) + { + return NULL; /* wrong type */ + } + + if (*pktsize < rssize) /* check size */ + return NULL; /* not enough data */ + + if (rssize > getRsPktMaxSize()) + return NULL; /* packet too big */ + + /* set the packet length */ + *pktsize = rssize; + + RsRawItem *item = new RsRawItem(rstype, rssize); + void *item_data = item->getRawData(); + + memcpy(item_data, data, rssize); + + return item; +} + + diff --git a/libretroshare/src/serialiser/rsserviceserialiser.h b/libretroshare/src/serialiser/rsserviceserialiser.h new file mode 100644 index 000000000..9bc7d728d --- /dev/null +++ b/libretroshare/src/serialiser/rsserviceserialiser.h @@ -0,0 +1,40 @@ +/* + * libretroshare/src/serialiser: rsserviceserialiser.h + * + * 3P/PQI network interface for RetroShare. + * + * Copyright 2013-2013 by Cyril Soler & 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". + * + */ + +#pragma once + +#include "rsserial.h" + +class RsServiceSerialiser: public RsSerialType +{ + public: + RsServiceSerialiser() :RsSerialType(RS_PKT_VERSION_SERVICE, 0, 0) { } + virtual ~RsServiceSerialiser() { } + + virtual uint32_t size(RsItem *); + virtual bool serialise (RsItem *item, void *data, uint32_t *size); + virtual RsItem * deserialise(void *data, uint32_t *size); +}; + diff --git a/libretroshare/src/services/p3chatservice.cc b/libretroshare/src/services/p3chatservice.cc index 89bed4704..be71584f3 100644 --- a/libretroshare/src/services/p3chatservice.cc +++ b/libretroshare/src/services/p3chatservice.cc @@ -724,7 +724,6 @@ void p3ChatService::handleIncomingItem(RsItem *item) case RS_PKT_SUBTYPE_CHAT_LOBBY_UNSUBSCRIBE: handleFriendUnsubscribeLobby (dynamic_cast(item)) ; break ; case RS_PKT_SUBTYPE_CHAT_LOBBY_LIST_REQUEST: handleRecvChatLobbyListRequest(dynamic_cast(item)) ; break ; case RS_PKT_SUBTYPE_CHAT_LOBBY_LIST: handleRecvChatLobbyList (dynamic_cast(item)) ; break ; - case RS_PKT_SUBTYPE_CHAT_LOBBY_LIST_deprecated: handleRecvChatLobbyList (dynamic_cast(item)) ; break ; default: { @@ -785,90 +784,8 @@ void p3ChatService::handleRecvChatLobbyListRequest(RsChatLobbyListRequestItem *c std::cerr << " Sending list to " << clr->PeerId() << std::endl; #endif sendItem(item); - - // *********** Also send an item in old formats. To be removed. - - RsChatLobbyListItem_deprecated *itemd = new RsChatLobbyListItem_deprecated; - RsChatLobbyListItem_deprecated2 *itemd2 = new RsChatLobbyListItem_deprecated2; - - for(uint32_t i=0;ilobby_ids.size();++i) - if(item->lobby_privacy_levels[i] == RS_CHAT_LOBBY_PRIVACY_LEVEL_PUBLIC) - { - itemd->lobby_ids.push_back(item->lobby_ids[i]) ; - itemd->lobby_names.push_back(item->lobby_names[i]) ; - itemd->lobby_counts.push_back(item->lobby_counts[i]) ; - - itemd2->lobby_ids.push_back(item->lobby_ids[i]) ; - itemd2->lobby_names.push_back(item->lobby_names[i]) ; - itemd2->lobby_counts.push_back(item->lobby_counts[i]) ; - itemd2->lobby_topics.push_back(item->lobby_topics[i]) ; - } - - itemd->PeerId(clr->PeerId()) ; - itemd2->PeerId(clr->PeerId()) ; - - sendItem(itemd) ; - sendItem(itemd2) ; - - // End of part to remove in future versions. ************* } -void p3ChatService::handleRecvChatLobbyList(RsChatLobbyListItem_deprecated *item) -{ - { - time_t now = time(NULL) ; - RsStackMutex stack(mChatMtx); /********** STACK LOCKED MTX ******/ - - for(uint32_t i=0;ilobby_ids.size();++i) - { - VisibleChatLobbyRecord& rec(_visible_lobbies[item->lobby_ids[i]]) ; - - rec.lobby_id = item->lobby_ids[i] ; - rec.lobby_name = item->lobby_names[i] ; - rec.participating_friends.insert(item->PeerId()) ; - - if(_should_reset_lobby_counts) - rec.total_number_of_peers = item->lobby_counts[i] ; - else - rec.total_number_of_peers = std::max(rec.total_number_of_peers,item->lobby_counts[i]) ; - - rec.last_report_time = now ; - rec.lobby_privacy_level = RS_CHAT_LOBBY_PRIVACY_LEVEL_PUBLIC ; - } - } - - rsicontrol->getNotify().notifyListChange(NOTIFY_LIST_CHAT_LOBBY_LIST, NOTIFY_TYPE_ADD) ; - _should_reset_lobby_counts = false ; -} -void p3ChatService::handleRecvChatLobbyList(RsChatLobbyListItem_deprecated2 *item) -{ - { - time_t now = time(NULL) ; - - RsStackMutex stack(mChatMtx); /********** STACK LOCKED MTX ******/ - - for(uint32_t i=0;ilobby_ids.size();++i) - { - VisibleChatLobbyRecord& rec(_visible_lobbies[item->lobby_ids[i]]) ; - - rec.lobby_id = item->lobby_ids[i] ; - rec.lobby_name = item->lobby_names[i] ; - rec.lobby_topic = item->lobby_topics[i] ; - rec.participating_friends.insert(item->PeerId()) ; - - if(_should_reset_lobby_counts) - rec.total_number_of_peers = item->lobby_counts[i] ; - else - rec.total_number_of_peers = std::max(rec.total_number_of_peers,item->lobby_counts[i]) ; - - rec.last_report_time = now ; - rec.lobby_privacy_level = RS_CHAT_LOBBY_PRIVACY_LEVEL_PUBLIC ; - } - } - - rsicontrol->getNotify().notifyListChange(NOTIFY_LIST_CHAT_LOBBY_LIST, NOTIFY_TYPE_ADD) ; - _should_reset_lobby_counts = false ; -} void p3ChatService::handleRecvChatLobbyList(RsChatLobbyListItem *item) { std::list chatLobbyToSubscribe; diff --git a/libretroshare/src/services/p3chatservice.h b/libretroshare/src/services/p3chatservice.h index 9abb50b1a..d48f157a8 100644 --- a/libretroshare/src/services/p3chatservice.h +++ b/libretroshare/src/services/p3chatservice.h @@ -226,8 +226,6 @@ class p3ChatService: public p3Service, public p3Config, public pqiMonitor, publi void handleRecvChatAvatarItem(RsChatAvatarItem *item) ; void handleRecvChatLobbyListRequest(RsChatLobbyListRequestItem *item) ; void handleRecvChatLobbyList(RsChatLobbyListItem *item) ; - void handleRecvChatLobbyList(RsChatLobbyListItem_deprecated *item) ; - void handleRecvChatLobbyList(RsChatLobbyListItem_deprecated2 *item) ; void handleRecvChatLobbyEventItem(RsChatLobbyEventItem *item) ; /// Sends a request for an avatar to the peer of given id From a7dd9ad9e38c2a2547805c33b9c11904c9995dc6 Mon Sep 17 00:00:00 2001 From: drbob Date: Tue, 1 Oct 2013 10:11:34 +0000 Subject: [PATCH 25/83] Work-in-progress to reduce latency time: * service->SendItem() now goes direct to pqistreamer buffer. * split p3FastService out of p3Service. p3FastService removes the recv buffer for faster processing. p3Service maintains its original interface, so derivate classes can remain unchanged. * Added uint32_t usec (wait period) to BinInterface.moretoread() & cansend() for future threading. * Added Mutex protection to pqistreamer, pqissl and derivatives of both. git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@6783 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/pqi/pqi.h | 15 + libretroshare/src/pqi/pqi_base.h | 9 +- libretroshare/src/pqi/pqiarchive.cc | 4 +- libretroshare/src/pqi/pqibin.cc | 21 +- libretroshare/src/pqi/pqibin.h | 20 +- libretroshare/src/pqi/pqihandler.h | 9 +- libretroshare/src/pqi/pqiperson.cc | 8 +- libretroshare/src/pqi/pqiperson.h | 2 +- libretroshare/src/pqi/pqipersongrp.cc | 35 ++- libretroshare/src/pqi/pqipersongrp.h | 4 +- libretroshare/src/pqi/pqiqosstreamer.cc | 3 + libretroshare/src/pqi/pqiqosstreamer.h | 2 +- libretroshare/src/pqi/pqiservice.cc | 97 ++----- libretroshare/src/pqi/pqiservice.h | 25 +- libretroshare/src/pqi/pqissl.cc | 116 +++++--- libretroshare/src/pqi/pqissl.h | 44 +-- libretroshare/src/pqi/pqisslproxy.cc | 49 ++-- libretroshare/src/pqi/pqissludp.cc | 148 ++++++---- libretroshare/src/pqi/pqissludp.h | 9 +- libretroshare/src/pqi/pqistore.cc | 8 +- libretroshare/src/pqi/pqistreamer.cc | 354 ++++++++++++------------ libretroshare/src/pqi/pqistreamer.h | 68 ++--- libretroshare/src/services/p3service.cc | 169 +++++------ libretroshare/src/services/p3service.h | 68 +++-- 24 files changed, 713 insertions(+), 574 deletions(-) diff --git a/libretroshare/src/pqi/pqi.h b/libretroshare/src/pqi/pqi.h index 3faffe03e..a253d53ac 100644 --- a/libretroshare/src/pqi/pqi.h +++ b/libretroshare/src/pqi/pqi.h @@ -65,5 +65,20 @@ virtual RsRawItem *GetRsRawItem() = 0; }; + +/* interface to allow outgoing messages to be sent directly + * through to the pqiperson, rather than being queued + */ + +class pqiPublisher +{ + public: +virtual ~pqiPublisher() { return; } +virtual bool sendItem(RsRawItem *item) = 0; + +}; + + + #endif // PQI_TOP_HEADER diff --git a/libretroshare/src/pqi/pqi_base.h b/libretroshare/src/pqi/pqi_base.h index 6f1b90e67..f41cf854a 100644 --- a/libretroshare/src/pqi/pqi_base.h +++ b/libretroshare/src/pqi/pqi_base.h @@ -219,10 +219,11 @@ class PQInterface: public RateInterface virtual std::string PeerId() { return peerId; } // the callback from NetInterface Connection Events. - virtual int notifyEvent(NetInterface *ni, int event) + virtual int notifyEvent(NetInterface *ni, int event, const struct sockaddr_storage &remote_peer_address) { (void) ni; /* remove unused parameter warnings */ (void) event; /* remove unused parameter warnings */ + (void) remote_peer_address; return 0; } @@ -278,11 +279,13 @@ virtual int readdata(void *data, int len) = 0; /** * Is more particular the case of the sending data through a socket (internet) + * moretoread and candsend, take a microsec timeout argument. + * */ virtual int netstatus() = 0; virtual int isactive() = 0; -virtual bool moretoread() = 0; -virtual bool cansend() = 0; +virtual bool moretoread(uint32_t usec) = 0; +virtual bool cansend(uint32_t usec) = 0; /** * method for streamer to shutdown bininterface diff --git a/libretroshare/src/pqi/pqiarchive.cc b/libretroshare/src/pqi/pqiarchive.cc index 2fe24ad25..34865c6a9 100644 --- a/libretroshare/src/pqi/pqiarchive.cc +++ b/libretroshare/src/pqi/pqiarchive.cc @@ -239,7 +239,7 @@ int pqiarchive::writePkt(RsItem *pqi) } - if (!(bio->cansend())) + if (!(bio->cansend(0))) { std::string out = "pqiarchive::writePkt() BIO cannot write!\nDiscarding:\n"; pqi -> print_string(out); @@ -321,7 +321,7 @@ int pqiarchive::readPkt(RsItem **item_out, long *ts_out) { pqioutput(PQL_DEBUG_ALL, pqiarchivezone, "pqiarchive::readPkt()"); - if ((!(bio->isactive())) || (!(bio->moretoread()))) + if ((!(bio->isactive())) || (!(bio->moretoread(0)))) { return 0; } diff --git a/libretroshare/src/pqi/pqibin.cc b/libretroshare/src/pqi/pqibin.cc index f7a7c32af..e38903d13 100644 --- a/libretroshare/src/pqi/pqibin.cc +++ b/libretroshare/src/pqi/pqibin.cc @@ -302,7 +302,7 @@ uint64_t BinEncryptedFileInterface::bytecount() return cpyCount; } -bool BinEncryptedFileInterface::moretoread() +bool BinEncryptedFileInterface::moretoread(uint32_t /* usec */) { if(haveData) return (cpyCount < sizeData); @@ -545,7 +545,8 @@ int NetBinDummy::connect(const struct sockaddr_storage &raddr) std::cerr << std::endl; if (parent()) { - parent()->notifyEvent(this, CONNECT_FAILED); + struct sockaddr_storage addr = raddr; + parent()->notifyEvent(this, CONNECT_FAILED, raddr); } } else if (!dummyConnected) @@ -595,7 +596,10 @@ int NetBinDummy::disconnect() if (parent()) { - parent()->notifyEvent(this, CONNECT_FAILED); + struct sockaddr_storage addr; + sockaddr_storage_clear(addr); + + parent()->notifyEvent(this, CONNECT_FAILED, addr); } return 1; @@ -627,7 +631,12 @@ int NetBinDummy::tick() dummyConnected = true; toConnect = false; if (parent()) - parent()->notifyEvent(this, CONNECT_SUCCESS); + { + struct sockaddr_storage addr; + sockaddr_storage_clear(addr); + + parent()->notifyEvent(this, CONNECT_SUCCESS, addr); + } } else { @@ -681,7 +690,7 @@ int NetBinDummy::isactive() return dummyConnected; } -bool NetBinDummy::moretoread() +bool NetBinDummy::moretoread(uint32_t /* usec */) { std::cerr << "NetBinDummy::moretoread() "; printNetBinID(std::cerr, PeerId(), type); @@ -690,7 +699,7 @@ bool NetBinDummy::moretoread() return false; } -bool NetBinDummy::cansend() +bool NetBinDummy::cansend(uint32_t /* usec */) { std::cerr << "NetBinDummy::cansend() "; printNetBinID(std::cerr, PeerId(), type); diff --git a/libretroshare/src/pqi/pqibin.h b/libretroshare/src/pqi/pqibin.h index bcab734c7..fd3684907 100644 --- a/libretroshare/src/pqi/pqibin.h +++ b/libretroshare/src/pqi/pqibin.h @@ -52,7 +52,7 @@ virtual int senddata(void *data, int len); virtual int readdata(void *data, int len); virtual int netstatus() { return 1;} virtual int isactive() { return (buf != NULL);} -virtual bool moretoread() +virtual bool moretoread(uint32_t /* usec */ ) { if ((buf) && (bin_flags | BIN_FLAGS_READABLE)) { @@ -65,7 +65,10 @@ virtual bool moretoread() } virtual int close(); -virtual bool cansend() { return (bin_flags | BIN_FLAGS_WRITEABLE); } +virtual bool cansend(uint32_t /* usec */) + { + return (bin_flags | BIN_FLAGS_WRITEABLE); + } virtual bool bandwidthLimited() { return false; } //! if HASHing is switched on @@ -118,7 +121,7 @@ public: int close(); uint64_t bytecount(); - bool moretoread(); + bool moretoread(uint32_t usec); private: @@ -156,7 +159,7 @@ virtual int senddata(void *data, int len); virtual int readdata(void *data, int len); virtual int netstatus() { return 1; } virtual int isactive() { return 1; } -virtual bool moretoread() +virtual bool moretoread(uint32_t /* usec */) { if ((buf) && (bin_flags | BIN_FLAGS_READABLE )) { @@ -169,7 +172,10 @@ virtual bool moretoread() } virtual int close(); -virtual bool cansend() { return (bin_flags | BIN_FLAGS_WRITEABLE); } +virtual bool cansend(uint32_t /* usec */) + { + return (bin_flags | BIN_FLAGS_WRITEABLE); + } virtual bool bandwidthLimited() { return false; } virtual std::string gethash(); @@ -217,8 +223,8 @@ virtual int senddata(void *data, int len); virtual int readdata(void *data, int len); virtual int netstatus(); virtual int isactive(); -virtual bool moretoread(); -virtual bool cansend(); +virtual bool moretoread(uint32_t usec); +virtual bool cansend(uint32_t usec); virtual int close(); virtual std::string gethash(); diff --git a/libretroshare/src/pqi/pqihandler.h b/libretroshare/src/pqi/pqihandler.h index 35eacfd67..3cafa62e7 100644 --- a/libretroshare/src/pqi/pqihandler.h +++ b/libretroshare/src/pqi/pqihandler.h @@ -46,10 +46,17 @@ class SearchModule // Presents a P3 Face to the world! // and funnels data through to a PQInterface. // -class pqihandler: public P3Interface +class pqihandler: public P3Interface, public pqiPublisher { public: pqihandler(SecurityPolicy *Global); + + /**** Overloaded from pqiPublisher ****/ + virtual bool sendItem(RsRawItem *item) + { + return SendRsRawItem(item); + } + bool AddSearchModule(SearchModule *mod); bool RemoveSearchModule(SearchModule *mod); diff --git a/libretroshare/src/pqi/pqiperson.cc b/libretroshare/src/pqi/pqiperson.cc index a28a24382..f4a42e75a 100644 --- a/libretroshare/src/pqi/pqiperson.cc +++ b/libretroshare/src/pqi/pqiperson.cc @@ -172,7 +172,7 @@ int pqiperson::tick() // callback function for the child - notify of a change. // This is only used for out-of-band info.... // otherwise could get dangerous loops. -int pqiperson::notifyEvent(NetInterface *ni, int newState) +int pqiperson::notifyEvent(NetInterface *ni, int newState, const struct sockaddr_storage &remote_peer_address) { { std::string out = "pqiperson::notifyEvent() Id: " + PeerId() + "\n"; @@ -218,8 +218,6 @@ int pqiperson::notifyEvent(NetInterface *ni, int newState) /* notify */ if (pqipg) { - struct sockaddr_storage remote_peer_address; - pqi->getConnectAddress(remote_peer_address); pqipg->notifyConnect(PeerId(), type, true, remote_peer_address); } @@ -288,9 +286,7 @@ int pqiperson::notifyEvent(NetInterface *ni, int newState) /* notify up */ if (pqipg) { - struct sockaddr_storage raddr; - sockaddr_storage_clear(raddr); - pqipg->notifyConnect(PeerId(), type, false, raddr); + pqipg->notifyConnect(PeerId(), type, false, remote_peer_address); } return 1; diff --git a/libretroshare/src/pqi/pqiperson.h b/libretroshare/src/pqi/pqiperson.h index d3eec1866..d0d0f05b2 100644 --- a/libretroshare/src/pqi/pqiperson.h +++ b/libretroshare/src/pqi/pqiperson.h @@ -135,7 +135,7 @@ virtual int status(); virtual int tick(); // overloaded callback function for the child - notify of a change. -int notifyEvent(NetInterface *ni, int event); +virtual int notifyEvent(NetInterface *ni, int event, const struct sockaddr_storage &addr); // PQInterface for rate control overloaded.... virtual int getQueueSize(bool in); diff --git a/libretroshare/src/pqi/pqipersongrp.cc b/libretroshare/src/pqi/pqipersongrp.cc index b5822eacf..42aa7b110 100644 --- a/libretroshare/src/pqi/pqipersongrp.cc +++ b/libretroshare/src/pqi/pqipersongrp.cc @@ -62,7 +62,7 @@ int pqipersongrp::tickServiceRecv() RsRawItem *pqi = NULL; int i = 0; - pqioutput(PQL_DEBUG_ALL, pqipersongrpzone, "pqipersongrp::tickTunnelServer()"); + pqioutput(PQL_DEBUG_ALL, pqipersongrpzone, "pqipersongrp::tickServiceRecv()"); //p3ServiceServer::tick(); @@ -70,8 +70,8 @@ int pqipersongrp::tickServiceRecv() { ++i; pqioutput(PQL_DEBUG_BASIC, pqipersongrpzone, - "pqipersongrp::tickTunnelServer() Incoming TunnelItem"); - incoming(pqi); + "pqipersongrp::tickServiceRecv() Incoming TunnelItem"); + recvItem(pqi); } if (0 < i) @@ -82,6 +82,11 @@ int pqipersongrp::tickServiceRecv() } // handle the tunnel services. + +// Improvements: +// This function is no longer necessary, and data is pushed directly to pqihandler. + +#if 0 int pqipersongrp::tickServiceSend() { RsRawItem *pqi = NULL; @@ -106,10 +111,12 @@ int pqipersongrp::tickServiceSend() return 0; } +#endif + // init pqipersongrp::pqipersongrp(SecurityPolicy *glob, unsigned long flags) - :pqihandler(glob), pqil(NULL), initFlags(flags) + :pqihandler(glob), p3ServiceServer(this), pqil(NULL), initFlags(flags) { } @@ -130,6 +137,7 @@ int pqipersongrp::tick() int i = 0; +#if 0 if (tickServiceSend()) { i = 1; @@ -137,14 +145,18 @@ int pqipersongrp::tick() std::cerr << "pqipersongrp::tick() moreToTick from tickServiceSend()" << std::endl; #endif } +#endif - if (pqihandler::tick()) /* does actual Send/Recv */ + +#if 0 + if (pqihandler::tick()) /* does Send/Recv */ { i = 1; #ifdef PGRP_DEBUG std::cerr << "pqipersongrp::tick() moreToTick from pqihandler::tick()" << std::endl; #endif } +#endif if (tickServiceRecv()) @@ -155,6 +167,19 @@ int pqipersongrp::tick() #endif } + p3ServiceServer::tick(); + +#if 1 + if (pqihandler::tick()) /* does Send/Recv */ + { + i = 1; +#ifdef PGRP_DEBUG + std::cerr << "pqipersongrp::tick() moreToTick from pqihandler::tick()" << std::endl; +#endif + } + +#endif + return i; } diff --git a/libretroshare/src/pqi/pqipersongrp.h b/libretroshare/src/pqi/pqipersongrp.h index fdaaf5bfa..cc79d89cf 100644 --- a/libretroshare/src/pqi/pqipersongrp.h +++ b/libretroshare/src/pqi/pqipersongrp.h @@ -114,9 +114,9 @@ virtual int checkOutgoingRsItem(RsItem *item, int global) private: - // The tunnelserver operation. + // The serviceserver operation. int tickServiceRecv(); - int tickServiceSend(); + //int tickServiceSend(); pqilistener *pqil; unsigned long initFlags; diff --git a/libretroshare/src/pqi/pqiqosstreamer.cc b/libretroshare/src/pqi/pqiqosstreamer.cc index bb16a7e82..f42cb761c 100644 --- a/libretroshare/src/pqi/pqiqosstreamer.cc +++ b/libretroshare/src/pqi/pqiqosstreamer.cc @@ -37,7 +37,10 @@ int pqiQoSstreamer::getQueueSize(bool in) if(in) return pqistreamer::getQueueSize(in) ; else + { + RsStackMutex stack(mStreamerMtx); /**** LOCKED MUTEX ****/ return qos_queue_size() ; + } } void pqiQoSstreamer::locked_storeInOutputQueue(void *ptr,int priority) diff --git a/libretroshare/src/pqi/pqiqosstreamer.h b/libretroshare/src/pqi/pqiqosstreamer.h index 3a79015e3..2e95d52d1 100644 --- a/libretroshare/src/pqi/pqiqosstreamer.h +++ b/libretroshare/src/pqi/pqiqosstreamer.h @@ -37,7 +37,7 @@ class pqiQoSstreamer: public pqistreamer, public pqiQoS static const float PQI_QOS_STREAMER_ALPHA = 2.0 ; virtual void locked_storeInOutputQueue(void *ptr,int priority) ; - virtual int out_queue_size() const { return _total_item_count ; } + virtual int locked_out_queue_size() const { return _total_item_count ; } virtual void locked_clear_out_queue() ; virtual int locked_compute_out_pkt_size() const { return _total_item_size ; } virtual void *locked_pop_out_data() ; diff --git a/libretroshare/src/pqi/pqiservice.cc b/libretroshare/src/pqi/pqiservice.cc index c4d6b4610..c9301db43 100644 --- a/libretroshare/src/pqi/pqiservice.cc +++ b/libretroshare/src/pqi/pqiservice.cc @@ -3,11 +3,11 @@ * * 3P/PQI network interface for RetroShare. * - * Copyright 2004-2008 by Robert Fernie. + * Copyright 2004-2013 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. + * License Version 2.1 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 @@ -33,7 +33,18 @@ const int pqiservicezone = 60478; * #define SERVICE_DEBUG 1 ****/ -p3ServiceServer::p3ServiceServer() : srvMtx("p3ServiceServer") +void pqiService::setServiceServer(p3ServiceServer *server) +{ + mServiceServer = server; +} + +bool pqiService::send(RsRawItem *item) +{ + return mServiceServer->sendItem(item); +} + + +p3ServiceServer::p3ServiceServer(pqiPublisher *pub) : mPublisher(pub), srvMtx("p3ServiceServer") { RsStackMutex stack(srvMtx); /********* LOCKED *********/ @@ -42,7 +53,6 @@ p3ServiceServer::p3ServiceServer() : srvMtx("p3ServiceServer") "p3ServiceServer::p3ServiceServer()"); #endif - rrit = services.begin(); return; } @@ -55,6 +65,7 @@ int p3ServiceServer::addService(pqiService *ts) "p3ServiceServer::addService()"); #endif + std::map::iterator it; it = services.find(ts -> getType()); if (it != services.end()) @@ -63,12 +74,13 @@ int p3ServiceServer::addService(pqiService *ts) return -1; } + ts->setServiceServer(this); services[ts -> getType()] = ts; - rrit = services.begin(); + return 1; } -int p3ServiceServer::incoming(RsRawItem *item) +bool p3ServiceServer::recvItem(RsRawItem *item) { RsStackMutex stack(srvMtx); /********* LOCKED *********/ @@ -92,12 +104,8 @@ int p3ServiceServer::incoming(RsRawItem *item) pqioutput(PQL_DEBUG_BASIC, pqiservicezone, "p3ServiceServer::incoming() Service: No Service - deleting"); #endif - - // delete it. delete item; - - // it exists already! - return -1; + return false; } { @@ -107,75 +115,28 @@ int p3ServiceServer::incoming(RsRawItem *item) pqioutput(PQL_DEBUG_BASIC, pqiservicezone, out); #endif - return (it->second) -> receive(item); + return (it->second) -> recv(item); } delete item; - return -1; + return false; } -RsRawItem *p3ServiceServer::outgoing() +bool p3ServiceServer::sendItem(RsRawItem *item) { - RsStackMutex stack(srvMtx); /********* LOCKED *********/ - #ifdef SERVICE_DEBUG - pqioutput(PQL_DEBUG_ALL, pqiservicezone, - "p3ServiceServer::outgoing()"); + std::cerr << "p3ServiceServer::sendItem()"; + std::cerr << std::endl; + item -> print_string(out); + std::cerr << std::endl; #endif - if (rrit != services.end()) - { - rrit++; - } - else - { - rrit = services.begin(); - } + /* any filtering ??? */ - std::map::iterator sit = rrit; - // run to the end. - RsRawItem *item; - - // run through to the end, - for(;rrit != services.end();rrit++) - { - if (NULL != (item = (rrit -> second) -> send())) - { - -#ifdef SERVICE_DEBUG - std::string out; - rs_sprintf(out, "p3ServiceServer::outgoing() Got Item From: %p\n", rrit -> second); - - item -> print_string(out); - std::cerr << out << std::endl; - pqioutput(PQL_DEBUG_BASIC, pqiservicezone, out); -#endif - - return item; - } - } - - // from the beginning to where we started. - for(rrit = services.begin();rrit != sit; rrit++) - { - if (NULL != (item = (rrit -> second) -> send())) - { - -#ifdef SERVICE_DEBUG - std::string out; - rs_sprintf(out, "p3ServiceServer::outgoing() Got Item From: %p\n", rrit -> second); - - item -> print_string(out); - pqioutput(PQL_DEBUG_BASIC, pqiservicezone, out); - std::cerr << out << std::endl; -#endif - - return item; - } - } - return NULL; + mPublisher->sendItem(item); + return true; } diff --git a/libretroshare/src/pqi/pqiservice.h b/libretroshare/src/pqi/pqiservice.h index 5286d2013..90dced84b 100644 --- a/libretroshare/src/pqi/pqiservice.h +++ b/libretroshare/src/pqi/pqiservice.h @@ -27,6 +27,7 @@ #ifndef PQI_SERVICE_HEADER #define PQI_SERVICE_HEADER +#include "pqi/pqi.h" #include "pqi/pqi_base.h" #include "util/rsthreads.h" @@ -51,20 +52,23 @@ // DataType is defined in the serialiser directory. class RsRawItem; +class p3ServiceServer; + class pqiService { protected: pqiService(uint32_t t) // our type of packets. - :type(t) { return; } + :type(t), mServiceServer(NULL) { return; } virtual ~pqiService() { return; } public: +void setServiceServer(p3ServiceServer *server); // -virtual int receive(RsRawItem *) = 0; -virtual RsRawItem * send() = 0; +virtual bool recv(RsRawItem *) = 0; +virtual bool send(RsRawItem *item); uint32_t getType() { return type; } @@ -72,28 +76,35 @@ virtual int tick() { return 0; } private: uint32_t type; + p3ServiceServer *mServiceServer; // const, no need for mutex. }; #include +/* We are pushing the packets back through p3ServiceServer2, + * so that we can filter services at this level later... + * if we decide not to do this, pqiService2 can call through + * to the base level pqiPublisher instead. + */ class p3ServiceServer { public: - p3ServiceServer(); + p3ServiceServer(pqiPublisher *pub); int addService(pqiService *); -int incoming(RsRawItem *); -RsRawItem *outgoing(); +bool recvItem(RsRawItem *); +bool sendItem(RsRawItem *); int tick(); private: + pqiPublisher *mPublisher; // constant no need for mutex. + RsMutex srvMtx; std::map services; -std::map::iterator rrit; }; diff --git a/libretroshare/src/pqi/pqissl.cc b/libretroshare/src/pqi/pqissl.cc index 46e94c43c..b8c916da8 100644 --- a/libretroshare/src/pqi/pqissl.cc +++ b/libretroshare/src/pqi/pqissl.cc @@ -93,6 +93,7 @@ static const int PQISSL_SSL_CONNECT_TIMEOUT = 30; pqissl::pqissl(pqissllistener *l, PQInterface *parent, p3LinkMgr *lm) :NetBinInterface(parent, parent->PeerId()), + mSslMtx("pqissl"), waiting(WAITING_NOT), active(false), certvalid(false), sslmode(PQISSL_ACTIVE), ssl_connection(NULL), sockfd(-1), pqil(l), // no init for remote_addr. @@ -100,9 +101,11 @@ pqissl::pqissl(pqissllistener *l, PQInterface *parent, p3LinkMgr *lm) attempt_ts(0), sameLAN(false), n_read_zero(0), mReadZeroTS(0), mConnectDelay(0), mConnectTS(0), - mConnectTimeout(0), mTimeoutTS(0), mLinkMgr(lm) + mConnectTimeout(0), mTimeoutTS(0), mLinkMgr(lm) { + RsStackMutex stack(mSslMtx); /**** LOCKED MUTEX ****/ + /* set address to zero */ sockaddr_storage_clear(remote_addr); @@ -144,6 +147,8 @@ pqissl::pqissl(pqissllistener *l, PQInterface *parent, p3LinkMgr *lm) int pqissl::connect(const struct sockaddr_storage &raddr) { + RsStackMutex stack(mSslMtx); /**** LOCKED MUTEX ****/ + // reset failures remote_addr = raddr; @@ -175,10 +180,13 @@ int pqissl::disconnect() return reset(); } -int pqissl::getConnectAddress(struct sockaddr_storage &raddr) { - raddr = remote_addr; - // TODO. - return (!sockaddr_storage_isnull(remote_addr)); +int pqissl::getConnectAddress(struct sockaddr_storage &raddr) +{ + RsStackMutex stack(mSslMtx); /**** LOCKED MUTEX ****/ + + raddr = remote_addr; + // TODO. + return (!sockaddr_storage_isnull(remote_addr)); } /* BinInterface version of reset() for pqistreamer */ @@ -191,8 +199,17 @@ int pqissl::close() // put back on the listening queue. int pqissl::reset() { - std::string outLog; + RsStackMutex stack(mSslMtx); /**** LOCKED MUTEX ****/ + return reset_locked(); +} + +int pqissl::reset_locked() +{ + std::string outLog; + bool neededReset = false; + + /* a reset shouldn't cause us to stop listening * only reasons for stoplistening() are; * @@ -211,7 +228,6 @@ int pqissl::reset() outLog += "\n"; #endif - bool neededReset = false; if (ssl_connection != NULL) { @@ -259,7 +275,9 @@ int pqissl::reset() // clean up the streamer if (parent()) { - parent() -> notifyEvent(this, NET_CONNECT_FAILED); + struct sockaddr_storage addr; + sockaddr_storage_clear(addr); + parent() -> notifyEvent(this, NET_CONNECT_FAILED, addr); } } return 1; @@ -267,6 +285,8 @@ int pqissl::reset() bool pqissl::connect_parameter(uint32_t type, const std::string &value) { + RsStackMutex stack(mSslMtx); /**** LOCKED MUTEX ****/ + (void) value; return false; } @@ -274,6 +294,8 @@ bool pqissl::connect_parameter(uint32_t type, const std::string &value) bool pqissl::connect_parameter(uint32_t type, uint32_t value) { + RsStackMutex stack(mSslMtx); /**** LOCKED MUTEX ****/ + #ifdef PQISSL_LOG_DEBUG { std::string out = "pqissl::connect_parameter() Peer: " + PeerId(); @@ -319,6 +341,8 @@ bool pqissl::connect_parameter(uint32_t type, uint32_t value) void pqissl::getCryptoParams(RsPeerCryptoParams& params) { + RsStackMutex stack(mSslMtx); /**** LOCKED MUTEX ****/ + if(active) { params.connexion_state = 1 ; @@ -350,6 +374,7 @@ void pqissl::getCryptoParams(RsPeerCryptoParams& params) int pqissl::status() { + RsStackMutex stack(mSslMtx); /**** LOCKED MUTEX ****/ #ifdef PQISSL_LOG_DEBUG std::string out = "pqissl::status()"; @@ -388,6 +413,8 @@ int pqissl::status() // tick...... int pqissl::tick() { + RsStackMutex stack(mSslMtx); /**** LOCKED MUTEX ****/ + //pqistreamer::tick(); // continue existing connection attempt. @@ -480,7 +507,7 @@ int pqissl::ConnectAttempt() rslog(RSL_ALERT, pqisslzone, "pqissl::ConnectAttempt() STATE = Unknown - calling reset()"); - reset(); + reset_locked(); break; } rslog(RSL_ALERT, pqisslzone, "pqissl::ConnectAttempt() Unknown"); @@ -510,8 +537,11 @@ int pqissl::Failed_Connection() if (parent()) { - parent() -> notifyEvent(this, NET_CONNECT_UNREACHABLE); + struct sockaddr_storage addr; + sockaddr_storage_clear(addr); + parent() -> notifyEvent(this, NET_CONNECT_UNREACHABLE, addr); } + waiting = WAITING_NOT; return 1; @@ -810,7 +840,7 @@ int pqissl::Basic_Connection_Complete() /* as sockfd is valid, this should close it all up */ rslog(RSL_ALERT, pqisslzone, "pqissl::Basic_Connection_Complete() -> calling reset()"); - reset(); + reset_locked(); return -1; } @@ -827,7 +857,7 @@ int pqissl::Basic_Connection_Complete() rslog(RSL_ALERT, pqisslzone, "pqissl::Basic_Connection_Complete() problem with the socket descriptor. Aborting"); rslog(RSL_ALERT, pqisslzone, "pqissl::Basic_Connection_Complete() -> calling reset()"); - reset(); + reset_locked(); return -1; } @@ -1128,7 +1158,7 @@ int pqissl::SSL_Connection_Complete() Extract_Failed_SSL_Certificate(); rslog(RSL_ALERT, pqisslzone, "pqissl::SSL_Connection_Complete() -> calling reset()"); - reset(); + reset_locked(); waiting = WAITING_FAIL_INTERFACE; return -1; @@ -1207,7 +1237,7 @@ int pqissl::Authorise_SSL_Connection() "pqissl::Authorise_SSL_Connection() Connection Timed Out!"); /* as sockfd is valid, this should close it all up */ rslog(RSL_ALERT, pqisslzone, "pqissl::Authorise_Connection_Complete() -> calling reset()"); - reset(); + reset_locked(); } int err; @@ -1233,7 +1263,7 @@ int pqissl::Authorise_SSL_Connection() rslog(RSL_ALERT, pqisslzone, "pqissl::Authorise_Connection_Complete() -> calling reset()"); // Failed completely - reset(); + reset_locked(); return -1; } @@ -1245,7 +1275,7 @@ int pqissl::Authorise_SSL_Connection() rslog(RSL_ALERT, pqisslzone, "pqissl::Authorise_Connection_Complete() -> calling reset()"); // Failed completely - reset(); + reset_locked(); return -1; } @@ -1269,7 +1299,7 @@ int pqissl::Authorise_SSL_Connection() // then okay... rslog(RSL_WARNING, pqisslzone, "pqissl::Authorise_SSL_Connection() Accepting Conn. Peer: " + PeerId()); - accept(ssl_connection, sockfd, remote_addr); + accept_locked(ssl_connection, sockfd, remote_addr); return 1; } @@ -1278,11 +1308,20 @@ int pqissl::Authorise_SSL_Connection() // else shutdown ssl connection. rslog(RSL_ALERT, pqisslzone, "pqissl::Authorise_Connection_Complete() -> calling reset()"); - reset(); + reset_locked(); return 0; } + +/* This function is public, and callable from pqilistener - so must be mutex protected */ int pqissl::accept(SSL *ssl, int fd, const struct sockaddr_storage &foreign_addr) // initiate incoming connection. +{ + RsStackMutex stack(mSslMtx); /**** LOCKED MUTEX ****/ + + return accept_locked(ssl, fd, foreign_addr); +} + +int pqissl::accept_locked(SSL *ssl, int fd, const struct sockaddr_storage &foreign_addr) // initiate incoming connection. { if (waiting != WAITING_NOT) { @@ -1340,7 +1379,7 @@ int pqissl::accept(SSL *ssl, int fd, const struct sockaddr_storage &foreign_addr "pqissl::accept() STATE = Unknown - ignore?"); rslog(RSL_ALERT, pqisslzone, "pqissl::accept() -> calling reset()"); - reset(); + reset_locked(); break; } @@ -1421,7 +1460,7 @@ int pqissl::accept(SSL *ssl, int fd, const struct sockaddr_storage &foreign_addr waiting = WAITING_FAIL_INTERFACE; // failed completely. rslog(RSL_ALERT, pqisslzone, "pqissl::accept() -> calling reset()"); - reset(); + reset_locked(); return -1; } else @@ -1440,18 +1479,22 @@ int pqissl::accept(SSL *ssl, int fd, const struct sockaddr_storage &foreign_addr // Notify the pqiperson.... (Both Connect/Receive) if (parent()) { - parent() -> notifyEvent(this, NET_CONNECT_SUCCESS); + struct sockaddr_storage addr = remote_addr; + parent() -> notifyEvent(this, NET_CONNECT_SUCCESS, addr); } return 1; } /********** Implementation of BinInterface ************************** * All the rest of the BinInterface. + * This functions much be Mutex protected. * */ int pqissl::senddata(void *data, int len) { + RsStackMutex stack(mSslMtx); /**** LOCKED MUTEX ****/ + int tmppktlen ; #ifdef PQISSL_DEBUG @@ -1493,7 +1536,7 @@ int pqissl::senddata(void *data, int len) } rslog(RSL_ALERT, pqisslzone, "pqissl::senddata() -> calling reset()"); - reset(); + reset_locked(); return -1; } else if (err == SSL_ERROR_WANT_WRITE) @@ -1518,7 +1561,7 @@ int pqissl::senddata(void *data, int len) rslog(RSL_ALERT, pqisslzone, out); rslog(RSL_ALERT, pqisslzone, "pqissl::senddata() -> calling reset()"); - reset(); + reset_locked(); return -1; } } @@ -1527,6 +1570,8 @@ int pqissl::senddata(void *data, int len) int pqissl::readdata(void *data, int len) { + RsStackMutex stack(mSslMtx); /**** LOCKED MUTEX ****/ + #ifdef PQISSL_DEBUG std::cout << "Reading data thread=" << pthread_self() << ", ssl=" << (void*)this << std::endl ; #endif @@ -1598,7 +1643,7 @@ int pqissl::readdata(void *data, int len) rs_sprintf_append(out, " ReadZero Age: %ld", time(NULL) - mReadZeroTS); rslog(RSL_ALERT, pqisslzone, "pqissl::readdata() -> calling reset()"); - reset(); + reset_locked(); } rslog(RSL_ALERT, pqisslzone, out); @@ -1635,7 +1680,7 @@ int pqissl::readdata(void *data, int len) } rslog(RSL_ALERT, pqisslzone, "pqissl::readdata() -> calling reset()"); - reset(); + reset_locked(); std::cerr << out << std::endl ; return -1; } @@ -1666,7 +1711,7 @@ int pqissl::readdata(void *data, int len) std::cerr << out << std::endl ; rslog(RSL_ALERT, pqisslzone, "pqissl::readdata() -> calling reset()"); - reset(); + reset_locked(); return -1; } @@ -1702,11 +1747,15 @@ int pqissl::netstatus() int pqissl::isactive() { + RsStackMutex stack(mSslMtx); /**** LOCKED MUTEX ****/ + return active; } -bool pqissl::moretoread() +bool pqissl::moretoread(uint32_t usec) { + RsStackMutex stack(mSslMtx); /**** LOCKED MUTEX ****/ + #ifdef PQISSL_DEBUG { std::string out; @@ -1726,7 +1775,7 @@ bool pqissl::moretoread() struct timeval timeout; timeout.tv_sec = 0; - timeout.tv_usec = 0; + timeout.tv_usec = usec; if (select(sockfd + 1, &ReadFDs, &WriteFDs, &ExceptFDs, &timeout) < 0) { @@ -1744,7 +1793,7 @@ bool pqissl::moretoread() // this is a definite bad socket!. // reset. rslog(RSL_ALERT, pqisslzone, "pqissl::moretoread() -> calling reset()"); - reset(); + reset_locked(); return 0; } @@ -1784,8 +1833,10 @@ bool pqissl::moretoread() } -bool pqissl::cansend() +bool pqissl::cansend(uint32_t usec) { + RsStackMutex stack(mSslMtx); /**** LOCKED MUTEX ****/ + #ifdef PQISSL_DEBUG rslog(RSL_DEBUG_ALL, pqisslzone, "pqissl::cansend() polling socket!"); @@ -1804,7 +1855,8 @@ bool pqissl::cansend() struct timeval timeout; timeout.tv_sec = 0; - timeout.tv_usec = 0; + timeout.tv_usec = usec; + if (select(sockfd + 1, &ReadFDs, &WriteFDs, &ExceptFDs, &timeout) < 0) { @@ -1824,7 +1876,7 @@ bool pqissl::cansend() // this is a definite bad socket!. // reset. rslog(RSL_ALERT, pqisslzone, "pqissl::cansend() -> calling reset()"); - reset(); + reset_locked(); return 0; } diff --git a/libretroshare/src/pqi/pqissl.h b/libretroshare/src/pqi/pqissl.h index 48717d6ff..de8813cd9 100644 --- a/libretroshare/src/pqi/pqissl.h +++ b/libretroshare/src/pqi/pqissl.h @@ -109,14 +109,37 @@ virtual int senddata(void*, int); virtual int readdata(void*, int); virtual int netstatus(); virtual int isactive(); -virtual bool moretoread(); -virtual bool cansend(); +virtual bool moretoread(uint32_t usec); +virtual bool cansend(uint32_t usec); 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 +public: + +/* Completion of the SSL connection, + * this is public, so it can be called by + * the listener (should make friends??) + */ + +int accept(SSL *ssl, int fd, const struct sockaddr_storage &foreign_addr); +void getCryptoParams(RsPeerCryptoParams& params) ; + + protected: + + + /* no mutex protection for these ones */ + + p3LinkMgr *mLinkMgr; + pqissllistener *pqil; + + RsMutex mSslMtx; /**** MUTEX protects data and fn below ****/ + +virtual int reset_locked(); +int accept_locked(SSL *ssl, int fd, const struct sockaddr_storage &foreign_addr); + // A little bit of information to describe // the SSL state, this is needed // to allow full Non-Blocking Connect behaviour. @@ -124,7 +147,6 @@ protected: // to complete an SSL. int ConnectAttempt(); -int waiting; virtual int Failed_Connection(); @@ -143,18 +165,6 @@ int Authorise_SSL_Connection(); int Extract_Failed_SSL_Certificate(); // try to get cert anyway. -public: - -/* Completion of the SSL connection, - * this is public, so it can be called by - * the listener (should make friends??) - */ - -int accept(SSL *ssl, int fd, const struct sockaddr_storage &foreign_addr); - -void getCryptoParams(RsPeerCryptoParams& params) ; - -protected: //protected internal fns that are overloaded for udp case. virtual int net_internal_close(int fd); @@ -166,13 +176,14 @@ virtual int net_internal_fcntl_nonblock(int fd); bool active; bool certvalid; + int waiting; + // addition for udp (tcp version == ACTIVE). int sslmode; SSL *ssl_connection; int sockfd; - pqissllistener *pqil; struct sockaddr_storage remote_addr; void *readpkt; @@ -193,7 +204,6 @@ virtual int net_internal_fcntl_nonblock(int fd); uint32_t mConnectTimeout; time_t mTimeoutTS; - p3LinkMgr *mLinkMgr; private: // ssl only fns. diff --git a/libretroshare/src/pqi/pqisslproxy.cc b/libretroshare/src/pqi/pqisslproxy.cc index 80b9a6b71..45c9d4c19 100755 --- a/libretroshare/src/pqi/pqisslproxy.cc +++ b/libretroshare/src/pqi/pqisslproxy.cc @@ -60,6 +60,10 @@ pqisslproxy::~pqisslproxy() { rslog(RSL_ALERT, pqisslproxyzone, "pqisslproxy::~pqisslproxy -> destroying pqisslproxy"); + + stoplistening(); + reset(); + return; } @@ -455,31 +459,40 @@ int pqisslproxy::Proxy_Connection_Complete() bool pqisslproxy::connect_parameter(uint32_t type, const std::string &value) { - if (type == NET_PARAM_CONNECT_DOMAIN_ADDRESS) - { - std::string out; - rs_sprintf(out, "pqisslproxy::connect_parameter() Peer: %s DOMAIN_ADDRESS: %s", PeerId().c_str(), value.c_str()); - rslog(RSL_WARNING, pqisslproxyzone, out); + { + RsStackMutex stack(mSslMtx); /**** LOCKED MUTEX ****/ + + if (type == NET_PARAM_CONNECT_DOMAIN_ADDRESS) + { + std::string out; + rs_sprintf(out, "pqisslproxy::connect_parameter() Peer: %s DOMAIN_ADDRESS: %s", PeerId().c_str(), value.c_str()); + rslog(RSL_WARNING, pqisslproxyzone, out); + + mDomainAddress = value; + std::cerr << out << std::endl; + return true; + } + } - mDomainAddress = value; - std::cerr << out << std::endl; - return true; - } return pqissl::connect_parameter(type, value); } bool pqisslproxy::connect_parameter(uint32_t type, uint32_t value) { - if (type == NET_PARAM_CONNECT_REMOTE_PORT) - { - std::string out; - rs_sprintf(out, "pqisslproxy::connect_parameter() Peer: %s REMOTE_PORT: %lu", PeerId().c_str(), value); - rslog(RSL_WARNING, pqisslproxyzone, out); + { + RsStackMutex stack(mSslMtx); /**** LOCKED MUTEX ****/ - mRemotePort = value; - std::cerr << out << std::endl; - return true; - } + if (type == NET_PARAM_CONNECT_REMOTE_PORT) + { + std::string out; + rs_sprintf(out, "pqisslproxy::connect_parameter() Peer: %s REMOTE_PORT: %lu", PeerId().c_str(), value); + rslog(RSL_WARNING, pqisslproxyzone, out); + + mRemotePort = value; + std::cerr << out << std::endl; + return true; + } + } return pqissl::connect_parameter(type, value); } diff --git a/libretroshare/src/pqi/pqissludp.cc b/libretroshare/src/pqi/pqissludp.cc index 074ef59db..71be7dd71 100644 --- a/libretroshare/src/pqi/pqissludp.cc +++ b/libretroshare/src/pqi/pqissludp.cc @@ -54,6 +54,8 @@ pqissludp::pqissludp(PQInterface *parent, p3LinkMgr *lm) :pqissl(NULL, parent, lm), tou_bio(NULL), listen_checktime(0), mConnectPeriod(PQI_SSLUDP_DEF_CONN_PERIOD) { + RsStackMutex stack(mSslMtx); /**** LOCKED MUTEX ****/ + sockaddr_storage_clear(remote_addr); return; } @@ -74,6 +76,8 @@ pqissludp::~pqissludp() stoplistening(); /* remove from p3proxy listenqueue */ reset(); + RsStackMutex stack(mSslMtx); /**** LOCKED MUTEX ****/ + if (tou_bio) // this should be in the reset? { BIO_free(tou_bio); @@ -81,12 +85,13 @@ pqissludp::~pqissludp() return; } -int pqissludp::reset() +int pqissludp::reset_locked() { /* reset for next time.*/ mConnectFlags = 0; mConnectPeriod = PQI_SSLUDP_DEF_CONN_PERIOD; - return pqissl::reset(); + + return pqissl::reset_locked(); } @@ -216,7 +221,7 @@ int pqissludp::Initiate_Connection() rslog(RSL_WARNING, pqissludpzone, "pqissludp::Initiate_Connection() Invalid (0.0.0.0) Remote Address, Aborting Connect."); waiting = WAITING_FAIL_INTERFACE; - reset(); + reset_locked(); return -1; } @@ -322,7 +327,7 @@ int pqissludp::Initiate_Connection() rslog(RSL_WARNING, pqissludpzone, out); - reset(); + reset_locked(); return -1; } @@ -356,7 +361,7 @@ int pqissludp::Basic_Connection_Complete() /* as sockfd is valid, this should close it all up */ - reset(); + reset_locked(); return -1; } @@ -387,7 +392,7 @@ int pqissludp::Basic_Connection_Complete() rs_sprintf_append(out, "Error: Connection Failed: %d - %s", err, socket_errorType(err).c_str()); rslog(RSL_DEBUG_BASIC, pqissludpzone, out); - reset(); + reset_locked(); // Then send unreachable message. waiting = WAITING_FAIL_INTERFACE; @@ -478,73 +483,90 @@ int pqissludp::stoplistening() bool pqissludp::connect_parameter(uint32_t type, uint32_t value) { - //std::cerr << "pqissludp::connect_parameter() type: " << type << "value: " << value << std::endl; - if (type == NET_PARAM_CONNECT_PERIOD) { - std::string out; - rs_sprintf(out, "pqissludp::connect_parameter() Peer: %s PERIOD: %lu", PeerId().c_str(), value); - rslog(RSL_WARNING, pqissludpzone, out); - - mConnectPeriod = value; - std::cerr << out << std::endl; - return true; + RsStackMutex stack(mSslMtx); /**** LOCKED MUTEX ****/ + + //std::cerr << "pqissludp::connect_parameter() type: " << type << "value: " << value << std::endl; + if (type == NET_PARAM_CONNECT_PERIOD) + { + std::string out; + rs_sprintf(out, "pqissludp::connect_parameter() Peer: %s PERIOD: %lu", PeerId().c_str(), value); + rslog(RSL_WARNING, pqissludpzone, out); + + mConnectPeriod = value; + std::cerr << out << std::endl; + return true; + } + else if (type == NET_PARAM_CONNECT_FLAGS) + { + std::string out; + rs_sprintf(out, "pqissludp::connect_parameter() Peer: %s FLAGS: %lu", PeerId().c_str(), value); + rslog(RSL_WARNING, pqissludpzone, out); + + mConnectFlags = value; + std::cerr << out<< std::endl; + return true; + } + else if (type == NET_PARAM_CONNECT_BANDWIDTH) + { + std::string out; + rs_sprintf(out, "pqissludp::connect_parameter() Peer: %s BANDWIDTH: %lu", PeerId().c_str(), value); + rslog(RSL_WARNING, pqissludpzone, out); + + mConnectBandwidth = value; + std::cerr << out << std::endl; + return true; + } } - else if (type == NET_PARAM_CONNECT_FLAGS) - { - std::string out; - rs_sprintf(out, "pqissludp::connect_parameter() Peer: %s FLAGS: %lu", PeerId().c_str(), value); - rslog(RSL_WARNING, pqissludpzone, out); - mConnectFlags = value; - std::cerr << out<< std::endl; - return true; - } - else if (type == NET_PARAM_CONNECT_BANDWIDTH) - { - std::string out; - rs_sprintf(out, "pqissludp::connect_parameter() Peer: %s BANDWIDTH: %lu", PeerId().c_str(), value); - rslog(RSL_WARNING, pqissludpzone, out); - - mConnectBandwidth = value; - std::cerr << out << std::endl; - return true; - } return pqissl::connect_parameter(type, value); } bool pqissludp::connect_additional_address(uint32_t type, const struct sockaddr_storage &addr) { - if (type == NET_PARAM_CONNECT_PROXY) { - std::string out; - rs_sprintf(out, "pqissludp::connect_additional_address() Peer: %s PROXYADDR: ", PeerId().c_str()); - out += sockaddr_storage_tostring(addr); - rslog(RSL_WARNING, pqissludpzone, out); - - mConnectProxyAddr = addr; - - std::cerr << out << std::endl; - return true; - } - else if (type == NET_PARAM_CONNECT_SOURCE) - { - std::string out; - rs_sprintf(out, "pqissludp::connect_additional_address() Peer: %s SRCADDR: ", PeerId().c_str()); - out += sockaddr_storage_tostring(addr); - rslog(RSL_WARNING, pqissludpzone, out); - - mConnectSrcAddr = addr; - - std::cerr << out << std::endl; - return true; + RsStackMutex stack(mSslMtx); /**** LOCKED MUTEX ****/ + + if (type == NET_PARAM_CONNECT_PROXY) + { + std::string out; + rs_sprintf(out, "pqissludp::connect_additional_address() Peer: %s PROXYADDR: ", PeerId().c_str()); + out += sockaddr_storage_tostring(addr); + rslog(RSL_WARNING, pqissludpzone, out); + + mConnectProxyAddr = addr; + + std::cerr << out << std::endl; + return true; + } + else if (type == NET_PARAM_CONNECT_SOURCE) + { + std::string out; + rs_sprintf(out, "pqissludp::connect_additional_address() Peer: %s SRCADDR: ", PeerId().c_str()); + out += sockaddr_storage_tostring(addr); + rslog(RSL_WARNING, pqissludpzone, out); + + mConnectSrcAddr = addr; + + std::cerr << out << std::endl; + return true; + } } return pqissl::connect_additional_address(type, addr); } /********** PQI STREAMER OVERLOADING *********************************/ -bool pqissludp::moretoread() +bool pqissludp::moretoread(uint32_t usec) { + RsStackMutex stack(mSslMtx); /**** LOCKED MUTEX ****/ + + if (usec) + { + std::cerr << "pqissludp::moretoread() usec parameter not implemented"; + std::cerr << std::endl; + } + { std::string out = "pqissludp::moretoread()"; rs_sprintf_append(out, " polling socket (%d)", sockfd); @@ -590,7 +612,7 @@ bool pqissludp::moretoread() rslog(RSL_WARNING, pqissludpzone, out); } - reset(); + reset_locked(); return 0; } @@ -603,8 +625,16 @@ bool pqissludp::moretoread() } -bool pqissludp::cansend() +bool pqissludp::cansend(uint32_t usec) { + RsStackMutex stack(mSslMtx); /**** LOCKED MUTEX ****/ + + if (usec) + { + std::cerr << "pqissludp::cansend() usec parameter not implemented"; + std::cerr << std::endl; + } + rslog(RSL_DEBUG_ALL, pqissludpzone, "pqissludp::cansend() polling socket!"); diff --git a/libretroshare/src/pqi/pqissludp.h b/libretroshare/src/pqi/pqissludp.h index a39128372..86b2bc27a 100644 --- a/libretroshare/src/pqi/pqissludp.h +++ b/libretroshare/src/pqi/pqissludp.h @@ -62,23 +62,24 @@ virtual ~pqissludp(); virtual int listen(); virtual int stoplistening(); virtual int tick(); -virtual int reset(); virtual bool connect_parameter(uint32_t type, uint32_t value); virtual bool connect_additional_address(uint32_t type, const struct sockaddr_storage &addr); // BinInterface. // These are reimplemented. -virtual bool moretoread(); -virtual bool cansend(); +virtual bool moretoread(uint32_t usec); +virtual bool cansend(uint32_t usec); /* UDP always through firewalls -> always bandwidth Limited */ virtual bool bandwidthLimited() { return true; } +protected: + // pqissludp specific. // called to initiate a connection; int attach(); -protected: +virtual int reset_locked(); virtual int Initiate_Connection(); virtual int Basic_Connection_Complete(); diff --git a/libretroshare/src/pqi/pqistore.cc b/libretroshare/src/pqi/pqistore.cc index 35353e381..c5b163ee4 100644 --- a/libretroshare/src/pqi/pqistore.cc +++ b/libretroshare/src/pqi/pqistore.cc @@ -224,7 +224,7 @@ int pqistore::writePkt(RsItem *pqi) } - if (!(bio->cansend())) + if (!(bio->cansend(0))) { std::string out; rs_sprintf(out, "pqistore::writePkt() BIO cannot write!\niscarding:\n"); @@ -278,7 +278,7 @@ int pqistore::readPkt(RsItem **item_out) pqioutput(PQL_DEBUG_ALL, pqistorezone, "pqistore::readPkt()"); #endif - if ((!(bio->isactive())) || (!(bio->moretoread()))) + if ((!(bio->isactive())) || (!(bio->moretoread(0)))) { return 0; } @@ -418,7 +418,7 @@ bool pqiSSLstore::getEncryptedItems(std::list& rsItemList) { if (NULL != (item = GetItem())) rsItemList.push_back(item); - } while (enc_bio->isactive() && enc_bio->moretoread()); + } while (enc_bio->isactive() && enc_bio->moretoread(0)); return true; } @@ -471,7 +471,7 @@ int pqiSSLstore::readPkt(RsItem **item_out) pqioutput(PQL_DEBUG_ALL, pqistorezone, "pqistore::readPkt()"); #endif - if ((!(enc_bio->isactive())) || (!(enc_bio->moretoread()))) + if ((!(enc_bio->isactive())) || (!(enc_bio->moretoread(0)))) { return 0; } diff --git a/libretroshare/src/pqi/pqistreamer.cc b/libretroshare/src/pqi/pqistreamer.cc index a26ebcacb..d9e48293e 100644 --- a/libretroshare/src/pqi/pqistreamer.cc +++ b/libretroshare/src/pqi/pqistreamer.cc @@ -45,6 +45,7 @@ const int PQISTREAM_ABS_MAX = 100000000; /* 100 MB/sec (actually per loop) */ #define DEBUG_PQISTREAMER 1 ***/ +#define DEBUG_PQISTREAMER 1 #ifdef DEBUG_TRANSFERS #include "util/rsprint.h" @@ -52,22 +53,24 @@ const int PQISTREAM_ABS_MAX = 100000000; /* 100 MB/sec (actually per loop) */ pqistreamer::pqistreamer(RsSerialiser *rss, std::string id, BinInterface *bio_in, int bio_flags_in) - :PQInterface(id), rsSerialiser(rss), bio(bio_in), bio_flags(bio_flags_in), - pkt_wpending(NULL), - totalRead(0), totalSent(0), - currRead(0), currSent(0), - avgReadCount(0), avgSentCount(0), streamerMtx("pqistreamer") + :PQInterface(id), mStreamerMtx("pqistreamer"), + mRsSerialiser(rss), mBio(bio_in), mBio_flags(bio_flags_in), + mPkt_wpending(NULL), + mTotalRead(0), mTotalSent(0), + mCurrRead(0), mCurrSent(0), + mAvgReadCount(0), mAvgSentCount(0) { - avgLastUpdate = currReadTS = currSentTS = time(NULL); + RsStackMutex stack(mStreamerMtx); /**** LOCKED MUTEX ****/ + + mAvgLastUpdate = mCurrReadTS = mCurrSentTS = time(NULL); /* allocated once */ - pkt_rpend_size = getRsPktMaxSize(); - pkt_rpending = malloc(pkt_rpend_size); - reading_state = reading_state_initial ; + mPkt_rpend_size = getRsPktMaxSize(); + mPkt_rpending = malloc(mPkt_rpend_size); + mReading_state = reading_state_initial ; -// thread_id = pthread_self() ; // avoid uninitialized (and random) memory read. - memset(pkt_rpending,0,pkt_rpend_size) ; + memset(mPkt_rpending,0,mPkt_rpend_size) ; // 100 B/s (minimal) setMaxRate(true, 0.1); @@ -83,48 +86,48 @@ pqistreamer::pqistreamer(RsSerialiser *rss, std::string id, BinInterface *bio_in exit(1); } - failed_read_attempts = 0 ; // reset failed read, as no packet is still read. + mFailed_read_attempts = 0; // reset failed read, as no packet is still read. return; } pqistreamer::~pqistreamer() { - RsStackMutex stack(streamerMtx) ; // lock out_pkt and out_data + RsStackMutex stack(mStreamerMtx); /**** LOCKED MUTEX ****/ pqioutput(PQL_DEBUG_ALL, pqistreamerzone, "pqistreamer::~pqistreamer() Destruction!"); - if (bio_flags & BIN_FLAGS_NO_CLOSE) + if (mBio_flags & BIN_FLAGS_NO_CLOSE) { pqioutput(PQL_DEBUG_ALL, pqistreamerzone, "pqistreamer::~pqistreamer() Not Closing BinInterface!"); } - else if (bio) + else if (mBio) { pqioutput(PQL_DEBUG_ALL, pqistreamerzone, "pqistreamer::~pqistreamer() Deleting BinInterface!"); - delete bio; + delete mBio; } /* clean up serialiser */ - if (rsSerialiser) - delete rsSerialiser; + if (mRsSerialiser) + delete mRsSerialiser; // clean up outgoing. (cntrl packets) locked_clear_out_queue() ; - if (pkt_wpending) + if (mPkt_wpending) { - free(pkt_wpending); - pkt_wpending = NULL; + free(mPkt_wpending); + mPkt_wpending = NULL; } - free(pkt_rpending); + free(mPkt_rpending); // clean up incoming. - while(incoming.size() > 0) + while(mIncoming.size() > 0) { - RsItem *i = incoming.front(); - incoming.pop_front(); + RsItem *i = mIncoming.front(); + mIncoming.pop_front(); delete i; } return; @@ -143,7 +146,9 @@ int pqistreamer::SendItem(RsItem *si,uint32_t& out_size) } #endif - return queue_outpqi(si,out_size); + RsStackMutex stack(mStreamerMtx); /**** LOCKED MUTEX ****/ + + return queue_outpqi_locked(si,out_size); } RsItem *pqistreamer::GetItem() @@ -152,12 +157,13 @@ RsItem *pqistreamer::GetItem() pqioutput(PQL_DEBUG_ALL, pqistreamerzone, "pqistreamer::GetItem()"); #endif + RsStackMutex stack(mStreamerMtx); /**** LOCKED MUTEX ****/ - if(incoming.empty()) + if(mIncoming.empty()) return NULL; - RsItem *osr = incoming.front() ; - incoming.pop_front() ; + RsItem *osr = mIncoming.front() ; + mIncoming.pop_front() ; return osr; } @@ -165,19 +171,21 @@ RsItem *pqistreamer::GetItem() // // PQInterface int pqistreamer::tick() { + RsStackMutex stack(mStreamerMtx); /**** LOCKED MUTEX ****/ + #ifdef DEBUG_PQISTREAMER { std::string out = "pqistreamer::tick()\n" + PeerId(); - rs_sprintf_append(out, ": currRead/Sent: %d/%d", currRead, currSent); + rs_sprintf_append(out, ": currRead/Sent: %d/%d", mCurrRead, mCurrSent); pqioutput(PQL_DEBUG_ALL, pqistreamerzone, out); } #endif - bio->tick(); + mBio->tick(); /* short circuit everything is bio isn't active */ - if (!(bio->isactive())) + if (!(mBio->isactive())) { return 0; } @@ -187,8 +195,8 @@ int pqistreamer::tick() * that incoming will not */ - handleincoming(); - handleoutgoing(); + handleincoming_locked(); + handleoutgoing_locked(); #ifdef DEBUG_PQISTREAMER /* give details of the packets */ @@ -197,7 +205,7 @@ int pqistreamer::tick() std::string out = "pqistreamer::tick() Queued Data: for " + PeerId(); - if (bio->isactive()) + if (mBio->isactive()) { out += " (active)"; } @@ -208,11 +216,10 @@ int pqistreamer::tick() out += "\n"; { - RsStackMutex stack(streamerMtx) ; // lock out_pkt and out_data - int total = compute_out_pkt_size() ; + int total = locked_compute_out_pkt_size() ; - rs_sprintf_append(out, "\t Out Packets [%d] => %d bytes\n", out_queue_size(), total); - rs_sprintf_append(out, "\t Incoming [%d]\n", incoming.size()); + rs_sprintf_append(out, "\t Out Packets [%d] => %d bytes\n", locked_out_queue_size(), total); + rs_sprintf_append(out, "\t Incoming [%d]\n", mIncoming.size()); } pqioutput(PQL_DEBUG_BASIC, pqistreamerzone, out); @@ -220,7 +227,7 @@ int pqistreamer::tick() #endif /* if there is more stuff in the queues */ - if ((incoming.size() > 0) || (out_queue_size() > 0)) + if ((mIncoming.size() > 0) || (locked_out_queue_size() > 0)) { return 1; } @@ -229,13 +236,16 @@ int pqistreamer::tick() int pqistreamer::status() { + RsStackMutex stack(mStreamerMtx); /**** LOCKED MUTEX ****/ + + #ifdef DEBUG_PQISTREAMER pqioutput(PQL_DEBUG_ALL, pqistreamerzone, "pqistreamer::status()"); - if (bio->isactive()) + if (mBio->isactive()) { std::string out; - rs_sprintf(out, "Data in:%d out:%d", totalRead, totalSent); + rs_sprintf(out, "Data in:%d out:%d", mTotalRead, mTotalSent); pqioutput(PQL_DEBUG_BASIC, pqistreamerzone, out); } #endif @@ -245,44 +255,32 @@ int pqistreamer::status() void pqistreamer::locked_storeInOutputQueue(void *ptr,int) { - out_pkt.push_back(ptr); + mOutPkts.push_back(ptr); } // /**************** HANDLE OUTGOING TRANSLATION + TRANSMISSION ******/ -int pqistreamer::queue_outpqi(RsItem *pqi,uint32_t& pktsize) +int pqistreamer::queue_outpqi_locked(RsItem *pqi,uint32_t& pktsize) { pktsize = 0 ; #ifdef DEBUG_PQISTREAMER std::cerr << "pqistreamer::queue_outpqi() called." << std::endl; #endif - RsStackMutex stack(streamerMtx) ; // lock out_pkt and out_data - // This is called by different threads, and by threads that are not the handleoutgoing thread, - // so it should be protected by a mutex !! - -#ifdef DEBUG_PQISTREAMER - if(dynamic_cast(pqi)!=NULL && (bio_flags & BIN_FLAGS_NO_DELETE)) - { - std::cerr << "Having file data with flags = " << bio_flags << std::endl ; - } - - pqioutput(PQL_DEBUG_ALL, pqistreamerzone, "pqistreamer::queue_outpqi()"); -#endif /* decide which type of packet it is */ - pktsize = rsSerialiser->size(pqi); + pktsize = mRsSerialiser->size(pqi); void *ptr = malloc(pktsize); #ifdef DEBUG_PQISTREAMER std::cerr << "pqistreamer::queue_outpqi() serializing packet with packet size : " << pktsize << std::endl; #endif - if (rsSerialiser->serialise(pqi, ptr, &pktsize)) + if (mRsSerialiser->serialise(pqi, ptr, &pktsize)) { locked_storeInOutputQueue(ptr,pqi->priority_level()) ; - if (!(bio_flags & BIN_FLAGS_NO_DELETE)) + if (!(mBio_flags & BIN_FLAGS_NO_DELETE)) { delete pqi; } @@ -298,41 +296,42 @@ int pqistreamer::queue_outpqi(RsItem *pqi,uint32_t& pktsize) pqi -> print_string(out); pqioutput(PQL_ALERT, pqistreamerzone, out); - if (!(bio_flags & BIN_FLAGS_NO_DELETE)) + if (!(mBio_flags & BIN_FLAGS_NO_DELETE)) { delete pqi; } return 1; // keep error internal. } -int pqistreamer::handleincomingitem(RsItem *pqi) +int pqistreamer::handleincomingitem_locked(RsItem *pqi) { + #ifdef DEBUG_PQISTREAMER - pqioutput(PQL_DEBUG_ALL, pqistreamerzone, "pqistreamer::handleincomingitem()"); + pqioutput(PQL_DEBUG_ALL, pqistreamerzone, "pqistreamer::handleincomingitem_locked()"); #endif // timestamp last received packet. mLastIncomingTs = time(NULL); // Use overloaded Contact function pqi -> PeerId(PeerId()); - incoming.push_back(pqi); + mIncoming.push_back(pqi); return 1; } time_t pqistreamer::getLastIncomingTS() { + RsStackMutex stack(mStreamerMtx); /**** LOCKED MUTEX ****/ + return mLastIncomingTs; } -int pqistreamer::handleoutgoing() +int pqistreamer::handleoutgoing_locked() { - RsStackMutex stack(streamerMtx) ; // lock out_pkt and out_data - #ifdef DEBUG_PQISTREAMER - pqioutput(PQL_DEBUG_ALL, pqistreamerzone, "pqistreamer::handleoutgoing()"); + pqioutput(PQL_DEBUG_ALL, pqistreamerzone, "pqistreamer::handleoutgoing_locked()"); #endif - int maxbytes = outAllowedBytes(); + int maxbytes = outAllowedBytes_locked(); int sentbytes = 0; int len; int ss; @@ -341,19 +340,19 @@ int pqistreamer::handleoutgoing() std::list::iterator it; // if not connection, or cannot send anything... pause. - if (!(bio->isactive())) + if (!(mBio->isactive())) { /* if we are not active - clear anything in the queues. */ locked_clear_out_queue() ; /* also remove the pending packets */ - if (pkt_wpending) + if (mPkt_wpending) { - free(pkt_wpending); - pkt_wpending = NULL; + free(mPkt_wpending); + mPkt_wpending = NULL; } - outSentBytes(sentbytes); + outSentBytes_locked(sentbytes); return 0; } @@ -364,41 +363,41 @@ int pqistreamer::handleoutgoing() { sent = false; - if ((!(bio->cansend())) || (maxbytes < sentbytes)) + if ((!(mBio->cansend(0))) || (maxbytes < sentbytes)) { #ifdef DEBUG_TRANSFERS if (maxbytes < sentbytes) { - std::cerr << "pqistreamer::handleoutgoing() Stopped sending sentbytes > maxbytes. Sent " << sentbytes << " bytes "; + std::cerr << "pqistreamer::handleoutgoing_locked() Stopped sending sentbytes > maxbytes. Sent " << sentbytes << " bytes "; std::cerr << std::endl; } else { - std::cerr << "pqistreamer::handleoutgoing() Stopped sending at cansend() is false"; + std::cerr << "pqistreamer::handleoutgoing_locked() Stopped sending at cansend() is false"; std::cerr << std::endl; } #endif - outSentBytes(sentbytes); + outSentBytes_locked(sentbytes); return 0; } // send a out_pkt., else send out_data. unless // there is a pending packet. - if (!pkt_wpending) - pkt_wpending = locked_pop_out_data() ; + if (!mPkt_wpending) + mPkt_wpending = locked_pop_out_data() ; - if (pkt_wpending) + if (mPkt_wpending) { // write packet. - len = getRsItemSize(pkt_wpending); + len = getRsItemSize(mPkt_wpending); #ifdef DEBUG_PQISTREAMER std::cout << "Sending Out Pkt of size " << len << " !" << std::endl; #endif - if (len != (ss = bio->senddata(pkt_wpending, len))) + if (len != (ss = mBio->senddata(mPkt_wpending, len))) { #ifdef DEBUG_PQISTREAMER std::string out; @@ -407,60 +406,60 @@ int pqistreamer::handleoutgoing() pqioutput(PQL_DEBUG_BASIC, pqistreamerzone, out); #endif - outSentBytes(sentbytes); + outSentBytes_locked(sentbytes); // pkt_wpending will kept til next time. // ensuring exactly the same data is written (openSSL requirement). return -1; } #ifdef DEBUG_TRANSFERS - std::cerr << "pqistreamer::handleoutgoing() Sent Packet len: " << len << " @ " << RsUtil::AccurateTimeString(); + std::cerr << "pqistreamer::handleoutgoing_locked() Sent Packet len: " << len << " @ " << RsUtil::AccurateTimeString(); std::cerr << std::endl; #endif - free(pkt_wpending); - pkt_wpending = NULL; + free(mPkt_wpending); + mPkt_wpending = NULL; sentbytes += len; sent = true; } } - outSentBytes(sentbytes); + outSentBytes_locked(sentbytes); return 1; } /* Handles reading from input stream. */ -int pqistreamer::handleincoming() +int pqistreamer::handleincoming_locked() { int readbytes = 0; static const int max_failed_read_attempts = 2000 ; #ifdef DEBUG_PQISTREAMER - pqioutput(PQL_DEBUG_ALL, pqistreamerzone, "pqistreamer::handleincoming()"); + pqioutput(PQL_DEBUG_ALL, pqistreamerzone, "pqistreamer::handleincoming_locked()"); #endif - if(!(bio->isactive())) + if(!(mBio->isactive())) { - reading_state = reading_state_initial ; - inReadBytes(readbytes); + mReading_state = reading_state_initial ; + inReadBytes_locked(readbytes); return 0; } // enough space to read any packet. - int maxlen = pkt_rpend_size; - void *block = pkt_rpending; + int maxlen = mPkt_rpend_size; + void *block = mPkt_rpending; // initial read size: basic packet. int blen = getRsPktBaseSize(); - int maxin = inAllowedBytes(); + int maxin = inAllowedBytes_locked(); #ifdef DEBUG_PQISTREAMER - std::cerr << "[" << (void*)pthread_self() << "] " << "reading state = " << reading_state << std::endl ; + std::cerr << "[" << (void*)pthread_self() << "] " << "reading state = " << mReading_state << std::endl ; #endif - switch(reading_state) + switch(mReading_state) { case reading_state_initial: /*std::cerr << "jumping to start" << std::endl; */ goto start_packet_read ; case reading_state_packet_started: /*std::cerr << "jumping to middle" << std::endl;*/ goto continue_packet ; @@ -475,11 +474,11 @@ start_packet_read: #endif memset(block,0,blen) ; // reset the block, to avoid uninitialized memory reads. - if (blen != (tmplen = bio->readdata(block, blen))) + if (blen != (tmplen = mBio->readdata(block, blen))) { pqioutput(PQL_DEBUG_BASIC, pqistreamerzone, "pqistreamer::handleincoming() Didn't read BasePkt!"); - inReadBytes(readbytes); + inReadBytes_locked(readbytes); // error.... (either blocked or failure) if (tmplen == 0) @@ -498,7 +497,7 @@ start_packet_read: // //pqioutput(PQL_WARNING, pqistreamerzone, "pqistreamer::handleincoming() Error in bio read"); #ifdef DEBUG_PQISTREAMER - std::cerr << "[" << (void*)pthread_self() << "] " << "given up 2, state = " << reading_state << std::endl ; + std::cerr << "[" << (void*)pthread_self() << "] " << "given up 2, state = " << mReading_state << std::endl ; #endif return 0; } @@ -525,8 +524,8 @@ start_packet_read: #endif readbytes += blen; - reading_state = reading_state_packet_started ; - failed_read_attempts = 0 ; // reset failed read, as the packet has been totally read. + mReading_state = reading_state_packet_started ; + mFailed_read_attempts = 0 ; // reset failed read, as the packet has been totally read. } continue_packet: { @@ -537,7 +536,7 @@ continue_packet: std::cerr << "[" << (void*)pthread_self() << "] " << "continuing packet getRsItemSize(block) = " << getRsItemSize(block) << std::endl ; std::cerr << "[" << (void*)pthread_self() << "] " << "continuing packet extralen = " << extralen << std::endl ; - std::cerr << "[" << (void*)pthread_self() << "] " << "continuing packet state=" << reading_state << std::endl ; + std::cerr << "[" << (void*)pthread_self() << "] " << "continuing packet state=" << mReading_state << std::endl ; std::cerr << "[" << (void*)pthread_self() << "] " << "block 1 : " << (int)(((unsigned char*)block)[0]) << " " << (int)(((unsigned char*)block)[1]) << " " << (int)(((unsigned char*)block)[2]) << " " << (int)(((unsigned char*)block)[3]) << " " << (int)(((unsigned char*)block)[4]) << " " << (int)(((unsigned char*)block)[5]) << " " @@ -588,9 +587,9 @@ continue_packet: std::cerr << std::endl; } - bio->close(); - reading_state = reading_state_initial ; // restart at state 1. - failed_read_attempts = 0 ; + mBio->close(); + mReading_state = reading_state_initial ; // restart at state 1. + mFailed_read_attempts = 0 ; return -1; // Used to exit now! exit(1); @@ -609,14 +608,14 @@ continue_packet: // so, don't do that: // memset( extradata,0,extralen ) ; - if (extralen != (tmplen = bio->readdata(extradata, extralen))) + if (extralen != (tmplen = mBio->readdata(extradata, extralen))) { #ifdef DEBUG_PQISTREAMER if(tmplen > 0) std::cerr << "[" << (void*)pthread_self() << "] " << "Incomplete packet read ! This is a real problem ;-)" << std::endl ; #endif - if(++failed_read_attempts > max_failed_read_attempts) + if(++mFailed_read_attempts > max_failed_read_attempts) { std::string out; rs_sprintf(out, "Error Completing Read (read %d/%d)", tmplen, extralen); @@ -653,22 +652,22 @@ continue_packet: std::cerr << msgout << std::endl; } - bio->close(); - reading_state = reading_state_initial ; // restart at state 1. - failed_read_attempts = 0 ; + mBio->close(); + mReading_state = reading_state_initial ; // restart at state 1. + mFailed_read_attempts = 0 ; return -1; } else { #ifdef DEBUG_PQISTREAMER - std::cerr << "[" << (void*)pthread_self() << "] " << "given up 5, state = " << reading_state << std::endl ; + std::cerr << "[" << (void*)pthread_self() << "] " << "given up 5, state = " << mReading_state << std::endl ; #endif return 0 ; // this is just a SSL_WANT_READ error. Don't panic, we'll re-try the read soon. // we assume readdata() returned either -1 or the complete read size. } } #ifdef DEBUG_PQISTREAMER - std::cerr << "[" << (void*)pthread_self() << "] " << "continuing packet state=" << reading_state << std::endl ; + std::cerr << "[" << (void*)pthread_self() << "] " << "continuing packet state=" << mReading_state << std::endl ; std::cerr << "[" << (void*)pthread_self() << "] " << "block 2 : " << (int)(((unsigned char*)extradata)[0]) << " " << (int)(((unsigned char*)extradata)[1]) << " " << (int)(((unsigned char*)extradata)[2]) << " " << (int)(((unsigned char*)extradata)[3]) << " " << (int)(((unsigned char*)extradata)[4]) << " " << (int)(((unsigned char*)extradata)[5]) << " " @@ -676,7 +675,7 @@ continue_packet: << (int)(((unsigned char*)extradata)[7]) << " " << std::endl ; #endif - failed_read_attempts = 0 ; + mFailed_read_attempts = 0 ; readbytes += extralen; } @@ -704,9 +703,9 @@ continue_packet: // fclose(f) ; // exit(-1) ; // } - RsItem *pkt = rsSerialiser->deserialise(block, &pktlen); + RsItem *pkt = mRsSerialiser->deserialise(block, &pktlen); - if ((pkt != NULL) && (0 < handleincomingitem(pkt))) + if ((pkt != NULL) && (0 < handleincomingitem_locked(pkt))) { #ifdef DEBUG_PQISTREAMER pqioutput(PQL_DEBUG_BASIC, pqistreamerzone, "Successfully Read a Packet!"); @@ -719,11 +718,11 @@ continue_packet: #endif } - reading_state = reading_state_initial ; // restart at state 1. - failed_read_attempts = 0 ; // reset failed read, as the packet has been totally read. + mReading_state = reading_state_initial ; // restart at state 1. + mFailed_read_attempts = 0 ; // reset failed read, as the packet has been totally read. } - if(maxin > readbytes && bio->moretoread()) + if(maxin > readbytes && mBio->moretoread(0)) goto start_packet_read ; #ifdef DEBUG_TRANSFERS @@ -734,14 +733,14 @@ continue_packet: } #endif - inReadBytes(readbytes); + inReadBytes_locked(readbytes); return 0; } /* BandWidth Management Assistance */ -float pqistreamer::outTimeSlice() +float pqistreamer::outTimeSlice_locked() { #ifdef DEBUG_PQISTREAMER pqioutput(PQL_DEBUG_ALL, pqistreamerzone, "pqistreamer::outTimeSlice()"); @@ -752,87 +751,87 @@ float pqistreamer::outTimeSlice() } // very simple..... -int pqistreamer::outAllowedBytes() +int pqistreamer::outAllowedBytes_locked() { int t = time(NULL); // get current timestep. /* allow a lot if not bandwidthLimited */ - if (!bio->bandwidthLimited()) + if (!mBio->bandwidthLimited()) { - currSent = 0; - currSentTS = t; + mCurrSent = 0; + mCurrSentTS = t; return PQISTREAM_ABS_MAX; } - int dt = t - currSentTS; + int dt = t - mCurrSentTS; // limiter -> for when currSentTs -> 0. if (dt > 5) dt = 5; int maxout = (int) (getMaxRate(false) * 1000.0); - currSent -= dt * maxout; - if (currSent < 0) + mCurrSent -= dt * maxout; + if (mCurrSent < 0) { - currSent = 0; + mCurrSent = 0; } - currSentTS = t; + mCurrSentTS = t; #ifdef DEBUG_PQISTREAMER { std::string out; - rs_sprintf(out, "pqistreamer::outAllowedBytes() is %d/%d", maxout - currSent, maxout); + rs_sprintf(out, "pqistreamer::outAllowedBytes() is %d/%d", maxout - mCurrSent, maxout); pqioutput(PQL_DEBUG_ALL, pqistreamerzone, out); } #endif - return maxout - currSent; + return maxout - mCurrSent; } -int pqistreamer::inAllowedBytes() +int pqistreamer::inAllowedBytes_locked() { int t = time(NULL); // get current timestep. /* allow a lot if not bandwidthLimited */ - if (!bio->bandwidthLimited()) + if (!mBio->bandwidthLimited()) { - currReadTS = t; - currRead = 0; + mCurrReadTS = t; + mCurrRead = 0; return PQISTREAM_ABS_MAX; } - int dt = t - currReadTS; + int dt = t - mCurrReadTS; // limiter -> for when currReadTs -> 0. if (dt > 5) dt = 5; int maxin = (int) (getMaxRate(true) * 1000.0); - currRead -= dt * maxin; - if (currRead < 0) + mCurrRead -= dt * maxin; + if (mCurrRead < 0) { - currRead = 0; + mCurrRead = 0; } - currReadTS = t; + mCurrReadTS = t; #ifdef DEBUG_PQISTREAMER { std::string out; - rs_sprintf(out, "pqistreamer::inAllowedBytes() is %d/%d", maxin - currRead, maxin); + rs_sprintf(out, "pqistreamer::inAllowedBytes() is %d/%d", maxin - mCurrRead, maxin); pqioutput(PQL_DEBUG_ALL, pqistreamerzone, out); } #endif - return maxin - currRead; + return maxin - mCurrRead; } static const float AVG_PERIOD = 5; // sec static const float AVG_FRAC = 0.8; // for low pass filter. -void pqistreamer::outSentBytes(int outb) +void pqistreamer::outSentBytes_locked(int outb) { #ifdef DEBUG_PQISTREAMER { @@ -861,29 +860,29 @@ void pqistreamer::outSentBytes(int outb) - totalSent += outb; - currSent += outb; - avgSentCount += outb; + mTotalSent += outb; + mCurrSent += outb; + mAvgSentCount += outb; int t = time(NULL); // get current timestep. - if (t - avgLastUpdate > AVG_PERIOD) + if (t - mAvgLastUpdate > AVG_PERIOD) { float avgReadpSec = getRate(true); float avgSentpSec = getRate(false); avgReadpSec *= AVG_FRAC; - avgReadpSec += (1.0 - AVG_FRAC) * avgReadCount / - (1000.0 * (t - avgLastUpdate)); + avgReadpSec += (1.0 - AVG_FRAC) * mAvgReadCount / + (1000.0 * (t - mAvgLastUpdate)); avgSentpSec *= AVG_FRAC; - avgSentpSec += (1.0 - AVG_FRAC) * avgSentCount / - (1000.0 * (t - avgLastUpdate)); + avgSentpSec += (1.0 - AVG_FRAC) * mAvgSentCount / + (1000.0 * (t - mAvgLastUpdate)); /* pretend our rate is zero if we are * not bandwidthLimited(). */ - if (bio->bandwidthLimited()) + if (mBio->bandwidthLimited()) { setRate(true, avgReadpSec); setRate(false, avgSentpSec); @@ -895,14 +894,14 @@ void pqistreamer::outSentBytes(int outb) } - avgLastUpdate = t; - avgReadCount = 0; - avgSentCount = 0; + mAvgLastUpdate = t; + mAvgReadCount = 0; + mAvgSentCount = 0; } return; } -void pqistreamer::inReadBytes(int inb) +void pqistreamer::inReadBytes_locked(int inb) { #ifdef DEBUG_PQISTREAMER { @@ -912,45 +911,50 @@ void pqistreamer::inReadBytes(int inb) } #endif - totalRead += inb; - currRead += inb; - avgReadCount += inb; + mTotalRead += inb; + mCurrRead += inb; + mAvgReadCount += inb; return; } int pqistreamer::getQueueSize(bool in) { + RsStackMutex stack(mStreamerMtx); /**** LOCKED MUTEX ****/ + if (in) - return incoming.size(); - return out_queue_size(); + return mIncoming.size(); + return locked_out_queue_size(); } void pqistreamer::getRates(RsBwRates &rates) { RateInterface::getRates(rates); - rates.mQueueIn = incoming.size(); - rates.mQueueOut = out_queue_size(); + + RsStackMutex stack(mStreamerMtx); /**** LOCKED MUTEX ****/ + + rates.mQueueIn = mIncoming.size(); + rates.mQueueOut = locked_out_queue_size(); } -int pqistreamer::out_queue_size() const +int pqistreamer::locked_out_queue_size() const { // Warning: because out_pkt is a list, calling size // is O(n) ! Makign algorithms pretty inefficient. We should record how many // items get stored and discarded to have a proper size value at any time // - return out_pkt.size() ; + return mOutPkts.size() ; } void pqistreamer::locked_clear_out_queue() { - for(std::list::iterator it = out_pkt.begin(); it != out_pkt.end(); ) + for(std::list::iterator it = mOutPkts.begin(); it != mOutPkts.end(); ) { free(*it); - it = out_pkt.erase(it); + it = mOutPkts.erase(it); #ifdef DEBUG_PQISTREAMER - std::string out = "pqistreamer::handleoutgoing() Not active -> Clearing Pkt!"; - // std::cerr << out ; + std::string out = "pqistreamer::locked_clear_out_queue() Not active -> Clearing Pkt!"; + std::cerr << out << std::endl; pqioutput(PQL_DEBUG_BASIC, pqistreamerzone, out); #endif } @@ -960,7 +964,7 @@ int pqistreamer::locked_compute_out_pkt_size() const { int total = 0 ; - for(std::list::const_iterator it = out_pkt.begin(); it != out_pkt.end(); ++it) + for(std::list::const_iterator it = mOutPkts.begin(); it != mOutPkts.end(); ++it) total += getRsItemSize(*it); return total ; @@ -970,12 +974,12 @@ void *pqistreamer::locked_pop_out_data() { void *res = NULL ; - if (!out_pkt.empty()) + if (!mOutPkts.empty()) { - res = *(out_pkt.begin()); - out_pkt.pop_front(); + res = *(mOutPkts.begin()); + mOutPkts.pop_front(); #ifdef DEBUG_TRANSFERS - std::cerr << "pqistreamer::handleoutgoing() getting next pkt from out_pkt queue"; + std::cerr << "pqistreamer::locked_pop_out_data() getting next pkt from mOutPkts queue"; std::cerr << std::endl; #endif } diff --git a/libretroshare/src/pqi/pqistreamer.h b/libretroshare/src/pqi/pqistreamer.h index 51187b101..db08072c7 100644 --- a/libretroshare/src/pqi/pqistreamer.h +++ b/libretroshare/src/pqi/pqistreamer.h @@ -67,69 +67,71 @@ class pqistreamer: public PQInterface // These methods are redefined in pqiQoSstreamer // virtual void locked_storeInOutputQueue(void *ptr,int priority) ; - virtual int out_queue_size() const ; + virtual int locked_out_queue_size() const ; virtual void locked_clear_out_queue() ; virtual int locked_compute_out_pkt_size() const ; virtual void *locked_pop_out_data() ; + + protected: + RsMutex mStreamerMtx ; // Protects data, fns below, protected so pqiqos can use it too. + private: - // to filter functions - detect filecancel/data and act! - int queue_outpqi(RsItem *i,uint32_t& serialized_size); - int handleincomingitem(RsItem *i); + int queue_outpqi_locked(RsItem *i,uint32_t& serialized_size); + int handleincomingitem_locked(RsItem *i); // ticked regularly (manages out queues and sending // via above interfaces. - virtual int handleoutgoing(); - virtual int handleincoming(); + virtual int handleoutgoing_locked(); + virtual int handleincoming_locked(); // Bandwidth/Streaming Management. - float outTimeSlice(); + float outTimeSlice_locked(); + + int outAllowedBytes_locked(); + void outSentBytes_locked(int ); + + int inAllowedBytes_locked(); + void inReadBytes_locked(int ); - int outAllowedBytes(); - void outSentBytes(int ); - int inAllowedBytes(); - void inReadBytes(int ); // RsSerialiser - determines which packets can be serialised. - RsSerialiser *rsSerialiser; + RsSerialiser *mRsSerialiser; // Binary Interface for IO, initialisated at startup. - BinInterface *bio; - unsigned int bio_flags; // BIN_FLAGS_NO_CLOSE | BIN_FLAGS_NO_DELETE + BinInterface *mBio; + unsigned int mBio_flags; // BIN_FLAGS_NO_CLOSE | BIN_FLAGS_NO_DELETE - void *pkt_wpending; // storage for pending packet to write. - int pkt_rpend_size; // size of pkt_rpending. - void *pkt_rpending; // storage for read in pending packets. + void *mPkt_wpending; // storage for pending packet to write. + int mPkt_rpend_size; // size of pkt_rpending. + void *mPkt_rpending; // storage for read in pending packets. enum {reading_state_packet_started=1, reading_state_initial=0 } ; - int reading_state ; - int failed_read_attempts ; + int mReading_state ; + int mFailed_read_attempts ; // Temp Storage for transient data..... - std::list out_pkt; // Cntrl / Search / Results queue - std::list incoming; + std::list mOutPkts; // Cntrl / Search / Results queue + std::list mIncoming; // data for network stats. - int totalRead; - int totalSent; + int mTotalRead; + int mTotalSent; // these are representative (but not exact) - int currRead; - int currSent; - int currReadTS; // TS from which these are measured. - int currSentTS; + int mCurrRead; + int mCurrSent; + int mCurrReadTS; // TS from which these are measured. + int mCurrSentTS; - int avgLastUpdate; // TS from which these are measured. - float avgReadCount; - float avgSentCount; + int mAvgLastUpdate; // TS from which these are measured. + float mAvgReadCount; + float mAvgSentCount; time_t mLastIncomingTs; - RsMutex streamerMtx ; // WHAT IS THIS PROTECTING. XXX - // pthread_t thread_id;A - }; diff --git a/libretroshare/src/services/p3service.cc b/libretroshare/src/services/p3service.cc index 7a16d5756..121f9505a 100644 --- a/libretroshare/src/services/p3service.cc +++ b/libretroshare/src/services/p3service.cc @@ -3,11 +3,11 @@ * * 3P/PQI network interface for RetroShare. * - * Copyright 2004-2008 by Robert Fernie. + * Copyright 2004-2013 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. + * License Version 2.1 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 @@ -32,18 +32,14 @@ * #define SERV_DEBUG 1 ****/ -void p3Service::addSerialType(RsSerialType *st) -{ - rsSerialiser->addSerialType(st); -} + RsItem *p3Service::recvItem() { - srvMtx.lock(); /***** LOCK MUTEX *****/ + RsStackMutex stack(srvMtx); /***** LOCK MUTEX *****/ if (recv_queue.size() == 0) { - srvMtx.unlock(); /***** UNLOCK MUTEX *****/ return NULL; /* nothing there! */ } @@ -51,75 +47,81 @@ RsItem *p3Service::recvItem() RsItem *item = recv_queue.front(); recv_queue.pop_front(); - srvMtx.unlock(); /***** UNLOCK MUTEX *****/ return item; } bool p3Service::receivedItems() { - srvMtx.lock(); /***** LOCK MUTEX *****/ + RsStackMutex stack(srvMtx); /***** LOCK MUTEX *****/ - bool moreData = (recv_queue.size() != 0); - - srvMtx.unlock(); /***** UNLOCK MUTEX *****/ - - return moreData; + return (!recv_queue.empty()); } -int p3Service::sendItem(RsItem *item) +bool p3Service::recvItem(RsItem *item) { - srvMtx.lock(); /***** LOCK MUTEX *****/ + if (item) + { + RsStackMutex stack(srvMtx); /***** LOCK MUTEX *****/ - send_queue.push_back(item); - - srvMtx.unlock(); /***** UNLOCK MUTEX *****/ - - return 1; + recv_queue.push_back(item); + } } + + + + +void p3FastService::addSerialType(RsSerialType *st) +{ + rsSerialiser->addSerialType(st); +} + + // overloaded pqiService interface. -int p3Service::receive(RsRawItem *raw) +bool p3FastService::recv(RsRawItem *raw) { - srvMtx.lock(); /***** LOCK MUTEX *****/ - -#ifdef SERV_DEBUG - std::cerr << "p3Service::receive()"; - std::cerr << std::endl; -#endif - - /* convert to RsServiceItem */ - uint32_t size = raw->getRawLength(); - RsItem *item = rsSerialiser->deserialise(raw->getRawData(), &size); - if ((!item) || (size != raw->getRawLength())) + RsItem *item = NULL; { - /* error in conversion */ -#ifdef SERV_DEBUG - std::cerr << "p3Service::receive() Error" << std::endl; - std::cerr << "p3Service::receive() Size: " << size << std::endl; - std::cerr << "p3Service::receive() RawLength: " << raw->getRawLength() << std::endl; -#endif - - if (item) + RsStackMutex stack(srvMtx); /***** LOCK MUTEX *****/ + + #ifdef SERV_DEBUG + std::cerr << "p3Service::recv()"; + std::cerr << std::endl; + #endif + + /* convert to RsServiceItem */ + uint32_t size = raw->getRawLength(); + item = rsSerialiser->deserialise(raw->getRawData(), &size); + if ((!item) || (size != raw->getRawLength())) { -#ifdef SERV_DEBUG - std::cerr << "p3Service::receive() Bad Item:"; - std::cerr << std::endl; - item->print(std::cerr, 0); - std::cerr << std::endl; -#endif - delete item; - item=NULL ; + /* error in conversion */ + #ifdef SERV_DEBUG + std::cerr << "p3Service::recv() Error" << std::endl; + std::cerr << "p3Service::recv() Size: " << size << std::endl; + std::cerr << "p3Service::recv() RawLength: " << raw->getRawLength() << std::endl; + #endif + + if (item) + { + #ifdef SERV_DEBUG + std::cerr << "p3Service::recv() Bad Item:"; + std::cerr << std::endl; + item->print(std::cerr, 0); + std::cerr << std::endl; + #endif + delete item; + item=NULL ; + } } } - - + /* if we have something - pass it on */ if (item) { #ifdef SERV_DEBUG - std::cerr << "p3Service::receive() item:"; + std::cerr << "p3Service::recv() item:"; std::cerr << std::endl; item->print(std::cerr, 0); std::cerr << std::endl; @@ -127,33 +129,22 @@ int p3Service::receive(RsRawItem *raw) /* ensure PeerId is transferred */ item->PeerId(raw->PeerId()); - recv_queue.push_back(item); + recvItem(item); } /* cleanup input */ delete raw; - - srvMtx.unlock(); /***** UNLOCK MUTEX *****/ - return (item != NULL); } -RsRawItem *p3Service::send() + + +int p3FastService::sendItem(RsItem *si) { - srvMtx.lock(); /***** LOCK MUTEX *****/ - - if (send_queue.size() == 0) - { - srvMtx.unlock(); /***** UNLOCK MUTEX *****/ - return NULL; /* nothing there! */ - } - - /* get something off front */ - RsItem *si = send_queue.front(); - send_queue.pop_front(); + RsStackMutex stack(srvMtx); /***** LOCK MUTEX *****/ #ifdef SERV_DEBUG - std::cerr << "p3Service::send() Sending item:"; + std::cerr << "p3Service::sendItem() Sending item:"; std::cerr << std::endl; si->print(std::cerr, 0); std::cerr << std::endl; @@ -170,8 +161,7 @@ RsRawItem *p3Service::send() /* can't convert! */ delete si; - srvMtx.unlock(); /***** UNLOCK MUTEX *****/ - return NULL; + return 0; } RsRawItem *raw = new RsRawItem(si->PacketId(), size); @@ -203,7 +193,7 @@ RsRawItem *p3Service::send() if(si->priority_level() == QOS_PRIORITY_UNKNOWN) { std::cerr << "************************************************************" << std::endl; - std::cerr << "********** Warning: p3service::send() ********" << std::endl; + std::cerr << "********** Warning: p3Service::send() ********" << std::endl; std::cerr << "********** Warning: caught a RsItem with undefined ********" << std::endl; std::cerr << "********** priority level. That should not ********" << std::endl; std::cerr << "********** happen. Please fix your items! ********" << std::endl; @@ -215,38 +205,11 @@ RsRawItem *p3Service::send() /* cleanup */ delete si; - srvMtx.unlock(); /***** UNLOCK MUTEX *****/ #ifdef SERV_DEBUG - std::cerr << "p3Service::send() returning RawItem."; - std::cerr << std::endl; + std::cerr << "p3Service::send() returning RawItem."; + std::cerr << std::endl; #endif - return raw; + return pqiService::send(raw); } -std::string generateRandomServiceId() -{ - std::string out; - -/********************************** WINDOWS/UNIX SPECIFIC PART ******************/ -#ifndef WINDOWS_SYS - /* 4 bytes per random number: 4 x 4 = 16 bytes */ - for(int i = 0; i < 4; i++) - { - uint32_t rint = random(); - rs_sprintf_append(out, "%08x", rint); - } -#else - srand(time(NULL)); - /* 2 bytes per random number: 8 x 2 = 16 bytes */ - for(int i = 0; i < 8; i++) - { - uint16_t rint = rand(); /* only gives 16 bits */ - rs_sprintf_append(out, "%04x", rint); - } -#endif -/********************************** WINDOWS/UNIX SPECIFIC PART ******************/ - return out; -} - - diff --git a/libretroshare/src/services/p3service.h b/libretroshare/src/services/p3service.h index c4b7506ed..9d527ccb2 100644 --- a/libretroshare/src/services/p3service.h +++ b/libretroshare/src/services/p3service.h @@ -52,13 +52,14 @@ std::string generateRandomServiceId(); //TODO : encryption and upload / download rate implementation -class p3Service: public pqiService + +class p3FastService: public pqiService { protected: - p3Service(uint16_t type) + p3FastService(uint16_t type) :pqiService((((uint32_t) RS_PKT_VERSION_SERVICE) << 24) + (((uint32_t) type) << 8)), - srvMtx("p3Service"), rsSerialiser(NULL) + srvMtx("p3FastService"), rsSerialiser(NULL) { rsSerialiser = new RsSerialiser(); return; @@ -66,33 +67,59 @@ class p3Service: public pqiService public: -virtual ~p3Service() { delete rsSerialiser; return; } +virtual ~p3FastService() { delete rsSerialiser; return; } /*************** INTERFACE ******************************/ - /* called from Thread/tick/GUI */ int sendItem(RsItem *); -RsItem * recvItem(); -bool receivedItems(); - virtual int tick() { return 0; } /*************** INTERFACE ******************************/ - public: // overloaded pqiService interface. -virtual int receive(RsRawItem *); -virtual RsRawItem * send(); +virtual bool recv(RsRawItem *); + + // called by recv(). +virtual bool recvItem(RsItem *item) = 0; + protected: void addSerialType(RsSerialType *); - private: - - RsMutex srvMtx; - /* below locked by Mutex */ + RsMutex srvMtx; /* below locked by Mutex */ RsSerialiser *rsSerialiser; - std::list recv_queue, send_queue; +}; + + +class p3Service: public p3FastService +{ + protected: + + p3Service(uint16_t type) + :p3FastService(type) + { + return; + } + + public: + +/*************** INTERFACE ******************************/ + /* called from Thread/tick/GUI */ +//int sendItem(RsItem *); +RsItem * recvItem(); +bool receivedItems(); + +//virtual int tick() { return 0; } +/*************** INTERFACE ******************************/ + + public: + // overloaded p3FastService interface. +virtual bool recvItem(RsItem *item); + + private: + + /* below locked by srvMtx Mutex */ + std::list recv_queue; }; @@ -110,16 +137,17 @@ class nullService: public pqiService public: // overloaded NULL pqiService interface. -virtual int receive(RsRawItem *item) +virtual bool recv(RsRawItem *item) { /* drop any items */ delete item; - return 1; + return true; } -virtual RsRawItem * send() +virtual bool send(RsRawItem *item) { - return NULL; + delete item; + return true; } }; From b587301b5a63e2a1b3a1b1b965cb0f7e6bf72ca2 Mon Sep 17 00:00:00 2001 From: drbob Date: Wed, 2 Oct 2013 03:21:04 +0000 Subject: [PATCH 26/83] Added a thread per active peer - to reduce RTT and increase throughout. * Added pqithreadstreamer, tweaked pqistreamer to support derivation. * Shifted RTT from p3Service to p3FastService. * Disabled lots of debug. git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@6787 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/libretroshare.pro | 2 + libretroshare/src/pqi/p3netmgr.cc | 4 - libretroshare/src/pqi/pqi_base.h | 1 + libretroshare/src/pqi/pqihandler.cc | 2 - libretroshare/src/pqi/pqiperson.cc | 247 ++-- libretroshare/src/pqi/pqiperson.h | 41 +- libretroshare/src/pqi/pqipersongrp.cc | 20 +- libretroshare/src/pqi/pqipersongrp.h | 4 + libretroshare/src/pqi/pqiqosstreamer.cc | 4 +- libretroshare/src/pqi/pqiqosstreamer.h | 6 +- libretroshare/src/pqi/pqissl.cc | 26 +- libretroshare/src/pqi/pqisslpersongrp.cc | 6 +- libretroshare/src/pqi/pqissludp.cc | 27 +- libretroshare/src/pqi/pqistreamer.cc | 63 +- libretroshare/src/pqi/pqistreamer.h | 12 +- libretroshare/src/pqi/pqithreadstreamer.cc | 174 +++ libretroshare/src/pqi/pqithreadstreamer.h | 62 + libretroshare/src/services/p3discovery2.cc | 1241 +------------------- libretroshare/src/services/p3rtt.cc | 62 +- libretroshare/src/services/p3rtt.h | 6 +- libretroshare/src/services/p3service.cc | 1 + libretroshare/src/util/rsnet_ss.cc | 61 + 22 files changed, 658 insertions(+), 1414 deletions(-) create mode 100644 libretroshare/src/pqi/pqithreadstreamer.cc create mode 100644 libretroshare/src/pqi/pqithreadstreamer.h diff --git a/libretroshare/src/libretroshare.pro b/libretroshare/src/libretroshare.pro index 682dfdcee..d4058dc10 100644 --- a/libretroshare/src/libretroshare.pro +++ b/libretroshare/src/libretroshare.pro @@ -352,6 +352,7 @@ HEADERS += pqi/authssl.h \ pqi/pqisslproxy.h \ pqi/pqistore.h \ pqi/pqistreamer.h \ + pqi/pqithreadstreamer.h \ pqi/pqiqosstreamer.h \ pqi/sslfns.h \ pqi/pqinetstatebox.h @@ -473,6 +474,7 @@ SOURCES += pqi/authgpg.cc \ pqi/pqisslproxy.cc \ pqi/pqistore.cc \ pqi/pqistreamer.cc \ + pqi/pqithreadstreamer.cc \ pqi/pqiqosstreamer.cc \ pqi/sslfns.cc \ pqi/pqinetstatebox.cc diff --git a/libretroshare/src/pqi/p3netmgr.cc b/libretroshare/src/pqi/p3netmgr.cc index 960a88ec5..c76b54bdb 100644 --- a/libretroshare/src/pqi/p3netmgr.cc +++ b/libretroshare/src/pqi/p3netmgr.cc @@ -74,10 +74,6 @@ const uint32_t MIN_TIME_BETWEEN_NET_RESET = 5; * #define NETMGR_DEBUG_STATEBOX 1 ***/ -#define NETMGR_DEBUG 1 -#define NETMGR_DEBUG_RESET 1 -#define NETMGR_DEBUG_TICK 1 -#define NETMGR_DEBUG_STATEBOX 1 pqiNetStatus::pqiNetStatus() :mLocalAddrOk(false), mExtAddrOk(false), mExtAddrStableOk(false), diff --git a/libretroshare/src/pqi/pqi_base.h b/libretroshare/src/pqi/pqi_base.h index f41cf854a..b2ffcd491 100644 --- a/libretroshare/src/pqi/pqi_base.h +++ b/libretroshare/src/pqi/pqi_base.h @@ -210,6 +210,7 @@ class PQInterface: public RateInterface * Retrieve RsItem from a facility */ virtual RsItem *GetItem() = 0; + virtual bool RecvItem(RsItem *item) { return false; } /* alternative for for GetItem(), when we want to push */ /** * also there are tick + person id functions. diff --git a/libretroshare/src/pqi/pqihandler.cc b/libretroshare/src/pqi/pqihandler.cc index d1dcf0fe8..214f33c86 100644 --- a/libretroshare/src/pqi/pqihandler.cc +++ b/libretroshare/src/pqi/pqihandler.cc @@ -295,8 +295,6 @@ int pqihandler::SendRsRawItem(RsRawItem *ns) return queueOutRsItem(ns) ; } - - // inputs. This is a very basic // system that is completely biased and slow... // someone please fix. diff --git a/libretroshare/src/pqi/pqiperson.cc b/libretroshare/src/pqi/pqiperson.cc index f4a42e75a..8c45fff1e 100644 --- a/libretroshare/src/pqi/pqiperson.cc +++ b/libretroshare/src/pqi/pqiperson.cc @@ -35,10 +35,9 @@ const int pqipersonzone = 82371; * #define PERSON_DEBUG 1 ****/ -#define PERSON_DEBUG 1 - pqiperson::pqiperson(std::string id, pqipersongrp *pg) - :PQInterface(id), active(false), activepqi(NULL), + :PQInterface(id), mNotifyMtx("pqiperson-notify"), mPersonMtx("pqiperson"), + active(false), activepqi(NULL), inConnectAttempt(false), waittimes(0), pqipg(pg) { @@ -50,6 +49,8 @@ pqiperson::pqiperson(std::string id, pqipersongrp *pg) pqiperson::~pqiperson() { + RsStackMutex stack(mPersonMtx); /**** LOCK MUTEX ****/ + // clean up the children. std::map::iterator it; for(it = kids.begin(); it != kids.end(); it++) @@ -64,6 +65,8 @@ pqiperson::~pqiperson() // The PQInterface interface. int pqiperson::SendItem(RsItem *i,uint32_t& serialized_size) { + RsStackMutex stack(mPersonMtx); /**** LOCK MUTEX ****/ + std::string out = "pqiperson::SendItem()"; if (active) { @@ -86,14 +89,27 @@ int pqiperson::SendItem(RsItem *i,uint32_t& serialized_size) RsItem *pqiperson::GetItem() { + RsStackMutex stack(mPersonMtx); /**** LOCK MUTEX ****/ + if (active) return activepqi -> GetItem(); // else not possible. return NULL; } +bool pqiperson::RecvItem(RsItem *item) +{ + std::cerr << "pqiperson::RecvItem()"; + std::cerr << std::endl; + + return pqipg->recvItem((RsRawItem *) item); +} + + int pqiperson::status() { + RsStackMutex stack(mPersonMtx); /**** LOCK MUTEX ****/ + if (active) return activepqi -> status(); return -1; @@ -101,6 +117,8 @@ int pqiperson::status() int pqiperson::receiveHeartbeat() { + RsStackMutex stack(mPersonMtx); /**** LOCK MUTEX ****/ + pqioutput(PQL_WARNING, pqipersonzone, "pqiperson::receiveHeartbeat() from peer : " + PeerId()); lastHeartbeatReceived = time(NULL); @@ -110,61 +128,68 @@ int pqiperson::receiveHeartbeat() // tick...... int pqiperson::tick() { - //if lastHeartbeatReceived is 0, it might be not activated so don't do a net reset. - if (active && (lastHeartbeatReceived != 0) && - (time(NULL) - lastHeartbeatReceived) > HEARTBEAT_REPEAT_TIME * 5) + int activeTick = 0; { - int ageLastIncoming = time(NULL) - activepqi->getLastIncomingTS(); - std::string out = "pqiperson::tick() WARNING No heartbeat from: " + PeerId(); - //out << " assume dead. calling pqissl::reset(), LastHeartbeat was: "; - rs_sprintf_append(out, " LastHeartbeat was: %ld secs ago", time(NULL) - lastHeartbeatReceived); - rs_sprintf_append(out, " LastIncoming was: %d secs ago", ageLastIncoming); - pqioutput(PQL_WARNING, pqipersonzone, out); - -#define NO_PACKET_TIMEOUT 60 - - if (ageLastIncoming > NO_PACKET_TIMEOUT) + RsStackMutex stack(mPersonMtx); /**** LOCK MUTEX ****/ + + //if lastHeartbeatReceived is 0, it might be not activated so don't do a net reset. + if (active && (lastHeartbeatReceived != 0) && + (time(NULL) - lastHeartbeatReceived) > HEARTBEAT_REPEAT_TIME * 5) { - out = "pqiperson::tick() " + PeerId(); - out += " No Heartbeat & No Packets -> assume dead. calling pqissl::reset()"; + int ageLastIncoming = time(NULL) - activepqi->getLastIncomingTS(); + std::string out = "pqiperson::tick() WARNING No heartbeat from: " + PeerId(); + //out << " assume dead. calling pqissl::reset(), LastHeartbeat was: "; + rs_sprintf_append(out, " LastHeartbeat was: %ld secs ago", time(NULL) - lastHeartbeatReceived); + rs_sprintf_append(out, " LastIncoming was: %d secs ago", ageLastIncoming); pqioutput(PQL_WARNING, pqipersonzone, out); - - this->reset(); + + #define NO_PACKET_TIMEOUT 60 + + if (ageLastIncoming > NO_PACKET_TIMEOUT) + { + out = "pqiperson::tick() " + PeerId(); + out += " No Heartbeat & No Packets -> assume dead. calling pqissl::reset()"; + pqioutput(PQL_WARNING, pqipersonzone, out); + + this->reset(); + } + } - + + + { + std::string out = "pqiperson::tick() Id: " + PeerId() + " "; + if (active) + out += "***Active***"; + else + out += ">>InActive<<"; + + out += "\n"; + rs_sprintf_append(out, "Activepqi: %p inConnectAttempt: ", activepqi); + + if (inConnectAttempt) + out += "In Connection Attempt"; + else + out += " Not Connecting "; + out += "\n"; + + // tick the children. + std::map::iterator it; + for(it = kids.begin(); it != kids.end(); it++) + { + if (0 < (it->second) -> tick()) + { + activeTick = 1; + } + rs_sprintf_append(out, "\tTicking Child: %d\n", it->first); + } + + pqioutput(PQL_DEBUG_ALL, pqipersonzone, out); + } // end of pqioutput. } - int activeTick = 0; - - { - std::string out = "pqiperson::tick() Id: " + PeerId() + " "; - if (active) - out += "***Active***"; - else - out += ">>InActive<<"; - - out += "\n"; - rs_sprintf_append(out, "Activepqi: %p inConnectAttempt: ", activepqi); - - if (inConnectAttempt) - out += "In Connection Attempt"; - else - out += " Not Connecting "; - out += "\n"; - - // tick the children. - std::map::iterator it; - for(it = kids.begin(); it != kids.end(); it++) - { - if (0 < (it->second) -> tick()) - { - activeTick = 1; - } - rs_sprintf_append(out, "\tTicking Child: %d\n", it->first); - } - - pqioutput(PQL_DEBUG_ALL, pqipersonzone, out); - } // end of pqioutput. + // handle Notify Events that were generated. + processNotifyEvents(); return activeTick; } @@ -172,8 +197,60 @@ int pqiperson::tick() // callback function for the child - notify of a change. // This is only used for out-of-band info.... // otherwise could get dangerous loops. +// - Actually, now we have - must store and process later. int pqiperson::notifyEvent(NetInterface *ni, int newState, const struct sockaddr_storage &remote_peer_address) { + if (mPersonMtx.trylock()) + { + handleNotifyEvent_locked(ni, newState, remote_peer_address); + + mPersonMtx.unlock(); + + return 1; + } + + + RsStackMutex stack(mNotifyMtx); /**** LOCK MUTEX ****/ + + mNotifyQueue.push_back(NotifyData(ni, newState, remote_peer_address)); + + return 1; +} + + +void pqiperson::processNotifyEvents() +{ + NetInterface *ni; + int state; + struct sockaddr_storage addr; + + while(1) + { + { + RsStackMutex stack(mNotifyMtx); /**** LOCK MUTEX ****/ + + if (mNotifyQueue.empty()) + { + return; + } + NotifyData &data = mNotifyQueue.front(); + ni = data.mNi; + state = data.mState; + addr = data.mAddr; + + mNotifyQueue.pop_front(); + } + + RsStackMutex stack(mPersonMtx); /**** LOCK MUTEX ****/ + handleNotifyEvent_locked(ni, state, addr); + } + return; +} + + +int pqiperson::handleNotifyEvent_locked(NetInterface *ni, int newState, const struct sockaddr_storage &remote_peer_address) +{ + { std::string out = "pqiperson::notifyEvent() Id: " + PeerId() + "\n"; rs_sprintf_append(out, "Message: %d from: %p\n", newState, ni); @@ -243,6 +320,8 @@ int pqiperson::notifyEvent(NetInterface *ni, int newState, const struct sockadd activepqi = pqi; inConnectAttempt = false; + activepqi->start(); // STARTUP THREAD. + /* reset all other children? (clear up long UDP attempt) */ for(it = kids.begin(); it != kids.end(); it++) { @@ -270,6 +349,7 @@ int pqiperson::notifyEvent(NetInterface *ni, int newState, const struct sockadd { pqioutput(PQL_WARNING, pqipersonzone, "pqiperson::notifyEvent() Id: " + PeerId() + " CONNECT_FAILED->marking so!"); + activepqi->stop(); // STOP THREAD. active = false; activepqi = NULL; } @@ -302,11 +382,14 @@ int pqiperson::notifyEvent(NetInterface *ni, int newState, const struct sockadd int pqiperson::reset() { + RsStackMutex stack(mPersonMtx); /**** LOCK MUTEX ****/ + pqioutput(PQL_WARNING, pqipersonzone, "pqiperson::reset() resetting all pqiconnect for Id: " + PeerId()); std::map::iterator it; for(it = kids.begin(); it != kids.end(); it++) { + (it->second) -> stop(); // STOP THREAD. (it->second) -> reset(); } @@ -317,8 +400,29 @@ int pqiperson::reset() return 1; } +int pqiperson::fullstopthreads() +{ + RsStackMutex stack(mPersonMtx); /**** LOCK MUTEX ****/ + + pqioutput(PQL_WARNING, pqipersonzone, "pqiperson::fullstopthreads() for Id: " + PeerId()); + + std::map::iterator it; + for(it = kids.begin(); it != kids.end(); it++) + { + (it->second) -> fullstop(); // WAIT FOR THREAD TO STOP. + } + + activepqi = NULL; + active = false; + lastHeartbeatReceived = 0; + + return 1; +} + int pqiperson::addChildInterface(uint32_t type, pqiconnect *pqi) { + RsStackMutex stack(mPersonMtx); /**** LOCK MUTEX ****/ + { std::string out; rs_sprintf(out, "pqiperson::addChildInterface() : Id %s %u", PeerId().c_str(), type); @@ -335,6 +439,8 @@ int pqiperson::addChildInterface(uint32_t type, pqiconnect *pqi) int pqiperson::listen() { + RsStackMutex stack(mPersonMtx); /**** LOCK MUTEX ****/ + pqioutput(PQL_DEBUG_BASIC, pqipersonzone, "pqiperson::listen() Id: " + PeerId()); if (!active) @@ -352,6 +458,8 @@ int pqiperson::listen() int pqiperson::stoplistening() { + RsStackMutex stack(mPersonMtx); /**** LOCK MUTEX ****/ + pqioutput(PQL_DEBUG_BASIC, pqipersonzone, "pqiperson::stoplistening() Id: " + PeerId()); std::map::iterator it; @@ -368,6 +476,8 @@ int pqiperson::connect(uint32_t type, const struct sockaddr_storage &raddr, uint32_t delay, uint32_t period, uint32_t timeout, uint32_t flags, uint32_t bandwidth, const std::string &domain_addr, uint16_t domain_port) { + RsStackMutex stack(mPersonMtx); /**** LOCK MUTEX ****/ + #ifdef PERSON_DEBUG #endif { @@ -413,7 +523,7 @@ int pqiperson::connect(uint32_t type, const struct sockaddr_storage &raddr, #ifdef PERSON_DEBUG std::cerr << "pqiperson::connect() WARNING, clearing rate cap" << std::endl; #endif - setRateCap(0,0); + setRateCap_locked(0,0); #ifdef PERSON_DEBUG std::cerr << "pqiperson::connect() setting connect_parameters" << std::endl; @@ -444,25 +554,10 @@ int pqiperson::connect(uint32_t type, const struct sockaddr_storage &raddr, } -pqiconnect *pqiperson::getKid(uint32_t type) -{ - std::map::iterator it; - - if (kids.empty()) { - return NULL; - } - - it = kids.find(type); - if (it == kids.end()) - { - return NULL; - } else { - return it->second; - } -} - void pqiperson::getRates(RsBwRates &rates) { + RsStackMutex stack(mPersonMtx); /**** LOCK MUTEX ****/ + // get the rate from the active one. if ((!active) || (activepqi == NULL)) return; @@ -471,6 +566,8 @@ void pqiperson::getRates(RsBwRates &rates) int pqiperson::getQueueSize(bool in) { + RsStackMutex stack(mPersonMtx); /**** LOCK MUTEX ****/ + // get the rate from the active one. if ((!active) || (activepqi == NULL)) return 0; @@ -480,6 +577,8 @@ int pqiperson::getQueueSize(bool in) float pqiperson::getRate(bool in) { + RsStackMutex stack(mPersonMtx); /**** LOCK MUTEX ****/ + // get the rate from the active one. if ((!active) || (activepqi == NULL)) return 0; @@ -488,6 +587,8 @@ float pqiperson::getRate(bool in) void pqiperson::setMaxRate(bool in, float val) { + RsStackMutex stack(mPersonMtx); /**** LOCK MUTEX ****/ + // set to all of them. (and us) PQInterface::setMaxRate(in, val); // clean up the children. @@ -499,6 +600,12 @@ void pqiperson::setMaxRate(bool in, float val) } void pqiperson::setRateCap(float val_in, float val_out) +{ + RsStackMutex stack(mPersonMtx); /**** LOCK MUTEX ****/ + return setRateCap_locked(val_in, val_out); +} + +void pqiperson::setRateCap_locked(float val_in, float val_out) { // set to all of them. (and us) PQInterface::setRateCap(val_in, val_out); diff --git a/libretroshare/src/pqi/pqiperson.h b/libretroshare/src/pqi/pqiperson.h index d0d0f05b2..bcb2de6a8 100644 --- a/libretroshare/src/pqi/pqiperson.h +++ b/libretroshare/src/pqi/pqiperson.h @@ -30,6 +30,7 @@ #include "pqi/pqi.h" +#include "util/rsnet.h" #include @@ -44,12 +45,13 @@ static const int CONNECT_FAILED = 5; static const int HEARTBEAT_REPEAT_TIME = 5; #include "pqi/pqiqosstreamer.h" +#include "pqi/pqithreadstreamer.h" class pqiconnect: public pqiQoSstreamer, public NetInterface { public: - pqiconnect(RsSerialiser *rss, NetBinInterface *ni_in) - :pqiQoSstreamer(rss, ni_in->PeerId(), ni_in, 0), // pqistreamer will cleanup NetInterface. + pqiconnect(PQInterface *parent, RsSerialiser *rss, NetBinInterface *ni_in) + :pqiQoSstreamer(parent, rss, ni_in->PeerId(), ni_in, 0), // pqistreamer will cleanup NetInterface. NetInterface(NULL, ni_in->PeerId()), // No need for callback ni(ni_in) { @@ -75,7 +77,6 @@ virtual bool connect_parameter(uint32_t type, std::string value) { return ni -> virtual bool connect_additional_address(uint32_t type, const struct sockaddr_storage &addr) { return ni -> connect_additional_address(type, addr);} - virtual int getConnectAddress(struct sockaddr_storage &raddr){ return ni->getConnectAddress(raddr); } // get the contact from the net side! @@ -101,6 +102,25 @@ protected: class pqipersongrp; + +class NotifyData +{ + public: + NotifyData() + :mNi(NULL), mState(0) + { + sockaddr_storage_clear(mAddr); + } + + NotifyData(NetInterface *ni, int state, const struct sockaddr_storage &addr) + :mNi(ni), mState(state), mAddr(addr) { return; } + + NetInterface *mNi; + int mState; + struct sockaddr_storage mAddr; +}; + + class pqiperson: public PQInterface { public: @@ -117,6 +137,8 @@ int connect(uint32_t type, const struct sockaddr_storage &raddr, uint32_t delay, uint32_t period, uint32_t timeout, uint32_t flags, uint32_t bandwidth, const std::string &domain_addr, uint16_t domain_port); +int fullstopthreads(); + int receiveHeartbeat(); // add in connection method. int addChildInterface(uint32_t type, pqiconnect *pqi); @@ -130,6 +152,7 @@ virtual int SendItem(RsItem *item) return SendItem(item,serialized_size) ; } virtual RsItem *GetItem(); +virtual bool RecvItem(RsItem *item); virtual int status(); virtual int tick(); @@ -144,10 +167,20 @@ virtual float getRate(bool in); virtual void setMaxRate(bool in, float val); virtual void setRateCap(float val_in, float val_out); -pqiconnect *getKid(uint32_t type); private: +void processNotifyEvents(); +int handleNotifyEvent_locked(NetInterface *ni, int event, const struct sockaddr_storage &addr); + + RsMutex mNotifyMtx; /**** LOCKS Notify Queue ****/ + + std::list mNotifyQueue; + + RsMutex mPersonMtx; /**** LOCKS below ****/ + +void setRateCap_locked(float val_in, float val_out); + std::map kids; bool active; pqiconnect *activepqi; diff --git a/libretroshare/src/pqi/pqipersongrp.cc b/libretroshare/src/pqi/pqipersongrp.cc index 42aa7b110..e3128c6ed 100644 --- a/libretroshare/src/pqi/pqipersongrp.cc +++ b/libretroshare/src/pqi/pqipersongrp.cc @@ -56,6 +56,21 @@ static std::list waitingIds; * pqilistener and when accessing pqihandlers data. */ + + // New speedy recv. +bool pqipersongrp::RecvRsRawItem(RsRawItem *item) +{ + std::cerr << "pqipersongrp::RecvRsRawItem()"; + std::cerr << std::endl; + + p3ServiceServer::recvItem(item); + + return true; +} + + + + // handle the tunnel services. int pqipersongrp::tickServiceRecv() { @@ -433,6 +448,7 @@ int pqipersongrp::removePeer(std::string id) p -> stoplistening(); pqioutput(PQL_WARNING, pqipersongrpzone, "pqipersongrp::removePeer() => reset() called before deleting person"); p -> reset(); + p -> fullstopthreads(); delete p; mods.erase(it); } @@ -679,7 +695,7 @@ pqiperson * pqipersongrpDummy::locked_createPerson(std::string id, pqilistener * RsSerialiser *rss = new RsSerialiser(); rss->addSerialType(new RsServiceSerialiser()); - pqiconnect *pqic = new pqiconnect(rss, d1); + pqiconnect *pqic = new pqiconnect(pqip, rss, d1); pqip -> addChildInterface(PQI_CONNECT_TCP, pqic); @@ -689,7 +705,7 @@ pqiperson * pqipersongrpDummy::locked_createPerson(std::string id, pqilistener * RsSerialiser *rss2 = new RsSerialiser(); rss2->addSerialType(new RsServiceSerialiser()); - pqiconnect *pqic2 = new pqiconnect(rss2, d2); + pqiconnect *pqic2 = new pqiconnect(pqip, rss2, d2); pqip -> addChildInterface(PQI_CONNECT_UDP, pqic2); diff --git a/libretroshare/src/pqi/pqipersongrp.h b/libretroshare/src/pqi/pqipersongrp.h index cc79d89cf..4e8cd66a8 100644 --- a/libretroshare/src/pqi/pqipersongrp.h +++ b/libretroshare/src/pqi/pqipersongrp.h @@ -80,6 +80,10 @@ int connectPeer(std::string id #endif ); + // New speedy recv. +virtual bool RecvRsRawItem(RsRawItem *item); + + /* Work-around to dodgy pointer stuff */ int tagHeartbeatRecvd(std::string id); diff --git a/libretroshare/src/pqi/pqiqosstreamer.cc b/libretroshare/src/pqi/pqiqosstreamer.cc index f42cb761c..5a8bd8167 100644 --- a/libretroshare/src/pqi/pqiqosstreamer.cc +++ b/libretroshare/src/pqi/pqiqosstreamer.cc @@ -25,8 +25,8 @@ #include "pqiqosstreamer.h" -pqiQoSstreamer::pqiQoSstreamer(RsSerialiser *rss, std::string peerid, BinInterface *bio_in, int bio_flagsin) - : pqistreamer(rss,peerid,bio_in,bio_flagsin), pqiQoS(PQI_QOS_STREAMER_MAX_LEVELS, PQI_QOS_STREAMER_ALPHA) +pqiQoSstreamer::pqiQoSstreamer(PQInterface *parent, RsSerialiser *rss, std::string peerid, BinInterface *bio_in, int bio_flagsin) + : pqithreadstreamer(parent,rss,peerid,bio_in,bio_flagsin), pqiQoS(PQI_QOS_STREAMER_MAX_LEVELS, PQI_QOS_STREAMER_ALPHA) { _total_item_size = 0 ; _total_item_count = 0 ; diff --git a/libretroshare/src/pqi/pqiqosstreamer.h b/libretroshare/src/pqi/pqiqosstreamer.h index 2e95d52d1..9f75ce5d8 100644 --- a/libretroshare/src/pqi/pqiqosstreamer.h +++ b/libretroshare/src/pqi/pqiqosstreamer.h @@ -26,12 +26,12 @@ #pragma once #include "pqiqos.h" -#include "pqistreamer.h" +#include "pqithreadstreamer.h" -class pqiQoSstreamer: public pqistreamer, public pqiQoS +class pqiQoSstreamer: public pqithreadstreamer, public pqiQoS { public: - pqiQoSstreamer(RsSerialiser *rss, std::string peerid, BinInterface *bio_in, int bio_flagsin); + pqiQoSstreamer(PQInterface *parent, RsSerialiser *rss, std::string peerid, BinInterface *bio_in, int bio_flagsin); static const uint32_t PQI_QOS_STREAMER_MAX_LEVELS = 10 ; static const float PQI_QOS_STREAMER_ALPHA = 2.0 ; diff --git a/libretroshare/src/pqi/pqissl.cc b/libretroshare/src/pqi/pqissl.cc index b8c916da8..32fefbffa 100644 --- a/libretroshare/src/pqi/pqissl.cc +++ b/libretroshare/src/pqi/pqissl.cc @@ -1316,6 +1316,9 @@ int pqissl::Authorise_SSL_Connection() /* This function is public, and callable from pqilistener - so must be mutex protected */ int pqissl::accept(SSL *ssl, int fd, const struct sockaddr_storage &foreign_addr) // initiate incoming connection. { + std::cerr << "pqissl::accept()"; + std::cerr << std::endl; + RsStackMutex stack(mSslMtx); /**** LOCKED MUTEX ****/ return accept_locked(ssl, fd, foreign_addr); @@ -1476,6 +1479,9 @@ int pqissl::accept_locked(SSL *ssl, int fd, const struct sockaddr_storage &forei active = true; waiting = WAITING_NOT; + std::cerr << "pqissl::accept_locked() connection complete - notifying parent"; + std::cerr << std::endl; + // Notify the pqiperson.... (Both Connect/Receive) if (parent()) { @@ -1770,7 +1776,7 @@ bool pqissl::moretoread(uint32_t usec) FD_ZERO(&ExceptFDs); FD_SET(sockfd, &ReadFDs); - FD_SET(sockfd, &WriteFDs); + // Dont set WriteFDs. FD_SET(sockfd, &ExceptFDs); struct timeval timeout; @@ -1797,22 +1803,6 @@ bool pqissl::moretoread(uint32_t usec) return 0; } - if (FD_ISSET(sockfd, &WriteFDs)) - { -#ifdef PQISSL_DEBUG - // write can work. - rslog(RSL_DEBUG_ALL, pqisslzone, - "pqissl::moretoread() Can Write!"); -#endif - } - else - { -#ifdef PQISSL_DEBUG - // write can work. - rslog(RSL_DEBUG_BASIC, pqisslzone, - "pqissl::moretoread() Can *NOT* Write!"); -#endif - } if (FD_ISSET(sockfd, &ReadFDs)) { @@ -1849,7 +1839,7 @@ bool pqissl::cansend(uint32_t usec) FD_ZERO(&WriteFDs); FD_ZERO(&ExceptFDs); - FD_SET(sockfd, &ReadFDs); + // Dont Set ReadFDs. FD_SET(sockfd, &WriteFDs); FD_SET(sockfd, &ExceptFDs); diff --git a/libretroshare/src/pqi/pqisslpersongrp.cc b/libretroshare/src/pqi/pqisslpersongrp.cc index 1766359d5..a0fdb6733 100644 --- a/libretroshare/src/pqi/pqisslpersongrp.cc +++ b/libretroshare/src/pqi/pqisslpersongrp.cc @@ -95,7 +95,7 @@ pqiperson * pqisslpersongrp::locked_createPerson(std::string id, pqilistener *li RsSerialiser *rss = new RsSerialiser(); rss->addSerialType(new RsServiceSerialiser()); - pqiconnect *pqisc = new pqiconnect(rss, pqis); + pqiconnect *pqisc = new pqiconnect(pqip, rss, pqis); pqip -> addChildInterface(PQI_CONNECT_HIDDEN_TCP, pqisc); } @@ -118,7 +118,7 @@ pqiperson * pqisslpersongrp::locked_createPerson(std::string id, pqilistener *li RsSerialiser *rss = new RsSerialiser(); rss->addSerialType(new RsServiceSerialiser()); - pqiconnect *pqisc = new pqiconnect(rss, pqis); + pqiconnect *pqisc = new pqiconnect(pqip, rss, pqis); pqip -> addChildInterface(PQI_CONNECT_TCP, pqisc); @@ -128,7 +128,7 @@ pqiperson * pqisslpersongrp::locked_createPerson(std::string id, pqilistener *li RsSerialiser *rss2 = new RsSerialiser(); rss2->addSerialType(new RsServiceSerialiser()); - pqiconnect *pqiusc = new pqiconnect(rss2, pqius); + pqiconnect *pqiusc = new pqiconnect(pqip, rss2, pqius); // add a ssl + proxy interface. // Add Proxy First. diff --git a/libretroshare/src/pqi/pqissludp.cc b/libretroshare/src/pqi/pqissludp.cc index 71be7dd71..fef91d8db 100644 --- a/libretroshare/src/pqi/pqissludp.cc +++ b/libretroshare/src/pqi/pqissludp.cc @@ -561,18 +561,24 @@ bool pqissludp::moretoread(uint32_t usec) { RsStackMutex stack(mSslMtx); /**** LOCKED MUTEX ****/ - if (usec) - { - std::cerr << "pqissludp::moretoread() usec parameter not implemented"; - std::cerr << std::endl; - } - { std::string out = "pqissludp::moretoread()"; rs_sprintf_append(out, " polling socket (%d)", sockfd); rslog(RSL_DEBUG_ALL, pqissludpzone, out); } + if (usec) + { + std::cerr << "pqissludp::moretoread() usec parameter: " << usec; + std::cerr << std::endl; + + if (0 < tou_maxread(sockfd)) + { + return true; + } + usleep(usec); + } + /* check for more to read first ... if nothing... check error */ /* <===================== UDP Difference *******************/ @@ -631,8 +637,15 @@ bool pqissludp::cansend(uint32_t usec) if (usec) { - std::cerr << "pqissludp::cansend() usec parameter not implemented"; + std::cerr << "pqissludp::cansend() usec parameter: " << usec; std::cerr << std::endl; + + if (0 < tou_maxwrite(sockfd)) + { + return true; + } + + usleep(usec); } rslog(RSL_DEBUG_ALL, pqissludpzone, diff --git a/libretroshare/src/pqi/pqistreamer.cc b/libretroshare/src/pqi/pqistreamer.cc index d9e48293e..ca4b533ab 100644 --- a/libretroshare/src/pqi/pqistreamer.cc +++ b/libretroshare/src/pqi/pqistreamer.cc @@ -45,7 +45,6 @@ const int PQISTREAM_ABS_MAX = 100000000; /* 100 MB/sec (actually per loop) */ #define DEBUG_PQISTREAMER 1 ***/ -#define DEBUG_PQISTREAMER 1 #ifdef DEBUG_TRANSFERS #include "util/rsprint.h" @@ -54,7 +53,7 @@ const int PQISTREAM_ABS_MAX = 100000000; /* 100 MB/sec (actually per loop) */ pqistreamer::pqistreamer(RsSerialiser *rss, std::string id, BinInterface *bio_in, int bio_flags_in) :PQInterface(id), mStreamerMtx("pqistreamer"), - mRsSerialiser(rss), mBio(bio_in), mBio_flags(bio_flags_in), + mBio(bio_in), mBio_flags(bio_flags_in), mRsSerialiser(rss), mPkt_wpending(NULL), mTotalRead(0), mTotalSent(0), mCurrRead(0), mCurrSent(0), @@ -171,10 +170,10 @@ RsItem *pqistreamer::GetItem() // // PQInterface int pqistreamer::tick() { - RsStackMutex stack(mStreamerMtx); /**** LOCKED MUTEX ****/ #ifdef DEBUG_PQISTREAMER { + RsStackMutex stack(mStreamerMtx); /**** LOCKED MUTEX ****/ std::string out = "pqistreamer::tick()\n" + PeerId(); rs_sprintf_append(out, ": currRead/Sent: %d/%d", mCurrRead, mCurrSent); @@ -182,22 +181,15 @@ int pqistreamer::tick() } #endif - mBio->tick(); - - /* short circuit everything is bio isn't active */ - if (!(mBio->isactive())) + if (!tick_bio()) { return 0; } + tick_recv(0); + tick_send(0); - /* must do both, as outgoing will catch some bad sockets, - * that incoming will not - */ - - handleincoming_locked(); - handleoutgoing_locked(); - + RsStackMutex stack(mStreamerMtx); /**** LOCKED MUTEX ****/ #ifdef DEBUG_PQISTREAMER /* give details of the packets */ { @@ -234,6 +226,49 @@ int pqistreamer::tick() return 0; } +int pqistreamer::tick_bio() +{ + RsStackMutex stack(mStreamerMtx); /**** LOCKED MUTEX ****/ + mBio->tick(); + + /* short circuit everything is bio isn't active */ + if (!(mBio->isactive())) + { + return 0; + } + return 1; +} + + +int pqistreamer::tick_recv(uint32_t timeout) +{ + RsStackMutex stack(mStreamerMtx); /**** LOCKED MUTEX ****/ + + if (mBio->moretoread(timeout)) + { + handleincoming_locked(); + } + return 1; +} + + +int pqistreamer::tick_send(uint32_t timeout) +{ + RsStackMutex stack(mStreamerMtx); /**** LOCKED MUTEX ****/ + + /* short circuit everything is bio isn't active */ + if (!(mBio->isactive())) + { + return 0; + } + + if (mBio->cansend(timeout)) + { + handleoutgoing_locked(); + } + return 1; +} + int pqistreamer::status() { RsStackMutex stack(mStreamerMtx); /**** LOCKED MUTEX ****/ diff --git a/libretroshare/src/pqi/pqistreamer.h b/libretroshare/src/pqi/pqistreamer.h index db08072c7..ce6555532 100644 --- a/libretroshare/src/pqi/pqistreamer.h +++ b/libretroshare/src/pqi/pqistreamer.h @@ -62,6 +62,11 @@ class pqistreamer: public PQInterface virtual void getRates(RsBwRates &rates); virtual int getQueueSize(bool in); // extracting data. protected: + + int tick_bio(); + int tick_send(uint32_t timeout); + int tick_recv(uint32_t timeout); + /* Implementation */ // These methods are redefined in pqiQoSstreamer @@ -76,6 +81,10 @@ class pqistreamer: public PQInterface protected: RsMutex mStreamerMtx ; // Protects data, fns below, protected so pqiqos can use it too. + // Binary Interface for IO, initialisated at startup. + BinInterface *mBio; + unsigned int mBio_flags; // BIN_FLAGS_NO_CLOSE | BIN_FLAGS_NO_DELETE + private: int queue_outpqi_locked(RsItem *i,uint32_t& serialized_size); int handleincomingitem_locked(RsItem *i); @@ -98,9 +107,6 @@ class pqistreamer: public PQInterface // RsSerialiser - determines which packets can be serialised. RsSerialiser *mRsSerialiser; - // Binary Interface for IO, initialisated at startup. - BinInterface *mBio; - unsigned int mBio_flags; // BIN_FLAGS_NO_CLOSE | BIN_FLAGS_NO_DELETE void *mPkt_wpending; // storage for pending packet to write. int mPkt_rpend_size; // size of pkt_rpending. diff --git a/libretroshare/src/pqi/pqithreadstreamer.cc b/libretroshare/src/pqi/pqithreadstreamer.cc new file mode 100644 index 000000000..196059665 --- /dev/null +++ b/libretroshare/src/pqi/pqithreadstreamer.cc @@ -0,0 +1,174 @@ +/* + * pqithreadstreamer.cc + * + * 3P/PQI network interface for RetroShare. + * + * Copyright 2004-2013 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.1 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/pqithreadstreamer.h" + +#define DEFAULT_STREAMER_TIMEOUT 10000 // 10 ms. +#define DEFAULT_STREAMER_SLEEP 1000 // 1 ms. +#define DEFAULT_STREAMER_IDLE_SLEEP 1000000 // 1 sec + +pqithreadstreamer::pqithreadstreamer(PQInterface *parent, RsSerialiser *rss, std::string id, BinInterface *bio_in, int bio_flags_in) +:pqistreamer(rss, id, bio_in, bio_flags_in), mThreadMutex("pqithreadstreamer"), mParent(parent), mTimeout(0) +{ + mTimeout = DEFAULT_STREAMER_TIMEOUT; + mSleepPeriod = DEFAULT_STREAMER_SLEEP; + return; +} + +bool pqithreadstreamer::RecvItem(RsItem *item) +{ + return mParent->RecvItem(item); +} + +int pqithreadstreamer::tick() +{ + tick_bio(); + + return 0; +} + +void pqithreadstreamer::start() +{ + { + RsStackMutex stack(mThreadMutex); + mToRun = true; + } + RsThread::start(); +} + +void pqithreadstreamer::run() +{ + std::cerr << "pqithreadstream::run()"; + std::cerr << std::endl; + + { + RsStackMutex stack(mThreadMutex); + mRunning = true; + } + + while(1) + { + { + RsStackMutex stack(mThreadMutex); + if (!mToRun) + { + std::cerr << "pqithreadstream::run() stopping"; + std::cerr << std::endl; + + mRunning = false; + return; + } + } + data_tick(); + } +} + +void pqithreadstreamer::stop() +{ + RsStackMutex stack(mThreadMutex); + + std::cerr << "pqithreadstream::stop()"; + std::cerr << std::endl; + + mToRun = false; +} + +void pqithreadstreamer::fullstop() +{ + stop(); + + while(1) + { + RsStackMutex stack(mThreadMutex); + if (!mRunning) + { + std::cerr << "pqithreadstream::fullstop() complete"; + std::cerr << std::endl; + return; + } + usleep(1000); + } +} + +bool pqithreadstreamer::threadrunning() +{ + RsStackMutex stack(mThreadMutex); + return mRunning; +} + + +int pqithreadstreamer::data_tick() +{ + //std::cerr << "pqithreadstream::data_tick()"; + //std::cerr << std::endl; + + uint32_t recv_timeout = 0; + uint32_t sleep_period = 0; + bool isactive = false; + { + RsStackMutex stack(mStreamerMtx); + recv_timeout = mTimeout; + sleep_period = mSleepPeriod; + isactive = mBio->isactive(); + } + + if (!isactive) + { + usleep(DEFAULT_STREAMER_IDLE_SLEEP); + return 0; + } + + + //std::cerr << "pqithreadstream::data_tick() tick_recv"; + //std::cerr << std::endl; + + tick_recv(recv_timeout); + + // Push Items, Outside of Mutex. + RsItem *incoming = NULL; + while((incoming = GetItem())) + { + RecvItem(incoming); + } + + //std::cerr << "pqithreadstream::data_tick() tick_send"; + //std::cerr << std::endl; + + tick_send(0); + + if (sleep_period) + { + //std::cerr << "pqithreadstream::data_tick() usleep"; + //std::cerr << std::endl; + + usleep(sleep_period); + } + return 1; +} + + + + diff --git a/libretroshare/src/pqi/pqithreadstreamer.h b/libretroshare/src/pqi/pqithreadstreamer.h new file mode 100644 index 000000000..7c07aeb3d --- /dev/null +++ b/libretroshare/src/pqi/pqithreadstreamer.h @@ -0,0 +1,62 @@ +/* + * libretroshare/src/pqi pqithreadstreamer.h + * + * 3P/PQI network interface for RetroShare. + * + * Copyright 2004-2013 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.1 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_THREAD_STREAMER_HEADER +#define MRK_PQI_THREAD_STREAMER_HEADER + +#include "pqi/pqistreamer.h" +#include "util/rsthreads.h" + +class pqithreadstreamer: public pqistreamer, public RsThread +{ + public: + pqithreadstreamer(PQInterface *parent, RsSerialiser *rss, std::string peerid, BinInterface *bio_in, int bio_flagsin); + +virtual void run(); +virtual void start(); +virtual void stop(); +virtual void fullstop(); +virtual bool threadrunning(); + +virtual bool RecvItem(RsItem *item); +virtual int tick(); + +protected: + +int data_tick(); + + PQInterface *mParent; + uint32_t mTimeout; + uint32_t mSleepPeriod; + +private: + /* thread variables */ + RsMutex mThreadMutex; + bool mRunning; + bool mToRun; + +}; + +#endif //MRK_PQI_THREAD_STREAMER_HEADER diff --git a/libretroshare/src/services/p3discovery2.cc b/libretroshare/src/services/p3discovery2.cc index 606c6e631..0fb722fd8 100644 --- a/libretroshare/src/services/p3discovery2.cc +++ b/libretroshare/src/services/p3discovery2.cc @@ -32,8 +32,9 @@ // Interface pointer. RsDisc *rsDisc = NULL; -#define P3DISC_DEBUG 1 - +/**** + * #define P3DISC_DEBUG 1 + ****/ bool populateContactInfo(const peerState &detail, RsDiscContactItem *pkt) @@ -297,7 +298,7 @@ int p3discovery2::handleIncoming() else { #ifdef P3DISC_DEBUG - std::cerr << "p3disc::handleIncoming() Unknown Received Message!" << std::endl; + std::cerr << "p3discovery2::handleIncoming() Unknown Received Message!" << std::endl; item -> print(std::cerr); std::cerr << std::endl; #endif @@ -306,7 +307,7 @@ int p3discovery2::handleIncoming() } #ifdef P3DISC_DEBUG - std::cerr << "p3disc::handleIncoming() finished." << std::endl; + std::cerr << "p3discovery2::handleIncoming() finished." << std::endl; #endif return nhandled; @@ -985,7 +986,7 @@ void p3discovery2::sendPGPCertificate(const PGPID &aboutId, const SSLID &toId) if ((linkType & RS_NET_CONN_SPEED_TRICKLE) || (linkType & RS_NET_CONN_SPEED_LOW)) { - std::cerr << "p3disc::sendPGPCertificate() Not sending Certificates to: " << toId; + std::cerr << "p3discovery2::sendPGPCertificate() Not sending Certificates to: " << toId; std::cerr << " (low bandwidth)" << std::endl; return; } @@ -1023,7 +1024,7 @@ void p3discovery2::recvPGPCertificate(const SSLID &fromId, RsDiscPgpCertItem *it if (pstate.vs_disc != RS_VS_DISC_FULL) { #ifdef P3DISC_DEBUG - std::cerr << "p3disc::recvPGPCertificate() Not Loading Certificates as in MINIMAL MODE"; + std::cerr << "p3discovery2::recvPGPCertificate() Not Loading Certificates as in MINIMAL MODE"; std::cerr << std::endl; #endif @@ -1278,1231 +1279,3 @@ void p3discovery2::setGPGOperation(AuthGPGOperation *operation) } - -#if 0 -/***************************************************************************************/ -/***************************************************************************************/ -/************** OLD CODE ***************************/ -/***************************************************************************************/ -/***************************************************************************************/ - - -#include "retroshare/rsiface.h" -#include "retroshare/rspeers.h" -#include "services/p3disc.h" - -#include "pqi/p3peermgr.h" -#include "pqi/p3linkmgr.h" -#include "pqi/p3netmgr.h" - -#include "pqi/authssl.h" -#include "pqi/authgpg.h" - -#include -#include -#include - -const uint32_t AUTODISC_LDI_SUBTYPE_PING = 0x01; -const uint32_t AUTODISC_LDI_SUBTYPE_RPLY = 0x02; - -#include "util/rsdebug.h" -#include "util/rsprint.h" -#include "util/rsversion.h" - -const int pqidisczone = 2482; - -//static int convertTDeltaToTRange(double tdelta); -//static int convertTRangeToTDelta(int trange); - -// Operating System specific includes. -#include "pqi/pqinetwork.h" - -/* DISC FLAGS */ - -const uint32_t P3DISC_FLAGS_USE_DISC = 0x0001; -const uint32_t P3DISC_FLAGS_USE_DHT = 0x0002; -const uint32_t P3DISC_FLAGS_EXTERNAL_ADDR = 0x0004; -const uint32_t P3DISC_FLAGS_STABLE_UDP = 0x0008; -const uint32_t P3DISC_FLAGS_PEER_ONLINE = 0x0010; -const uint32_t P3DISC_FLAGS_OWN_DETAILS = 0x0020; -const uint32_t P3DISC_FLAGS_PEER_TRUSTS_ME = 0x0040; -const uint32_t P3DISC_FLAGS_ASK_VERSION = 0x0080; - - -/***** - * #define P3DISC_DEBUG 1 - ****/ - -//#define P3DISC_DEBUG 1 - -/****************************************************************************************** - ****************************** NEW DISCOVERY ******************************************* - ****************************************************************************************** - *****************************************************************************************/ - -p3disc::p3disc(p3PeerMgr *pm, p3LinkMgr *lm, p3NetMgr *nm, pqipersongrp *pqih) - :p3Service(RS_SERVICE_TYPE_DISC), - p3Config(CONFIG_TYPE_P3DISC), - mPeerMgr(pm), mLinkMgr(lm), mNetMgr(nm), - mPqiPersonGrp(pqih), mDiscMtx("p3disc") -{ - RsStackMutex stack(mDiscMtx); /********** STACK LOCKED MTX ******/ - - addSerialType(new RsDiscSerialiser()); - - mLastSentHeartbeatTime = time(NULL); - mDiscEnabled = true; - - //add own version to versions map - versions[AuthSSL::getAuthSSL()->OwnId()] = RsUtil::retroshareVersion(); -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::p3disc() setup"; - std::cerr << std::endl; -#endif - - return; -} - -int p3disc::tick() -{ - //send a heartbeat to all connected peers - time_t hbTime; - { - RsStackMutex stack(mDiscMtx); /********** STACK LOCKED MTX ******/ - hbTime = mLastSentHeartbeatTime; - } - - if (time(NULL) - hbTime > HEARTBEAT_REPEAT_TIME) - { -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::tick() sending heartbeat to all peers" << std::endl; -#endif - - std::list peers; - std::list::const_iterator pit; - - mLinkMgr->getOnlineList(peers); - for (pit = peers.begin(); pit != peers.end(); ++pit) - { - sendHeartbeat(*pit); - } - - /* check our Discovery flag */ - peerState detail; - mPeerMgr->getOwnNetStatus(detail); - - RsStackMutex stack(mDiscMtx); /********** STACK LOCKED MTX ******/ - - mDiscEnabled = (!(detail.visState & RS_VIS_STATE_NODISC)); - mLastSentHeartbeatTime = time(NULL); - } - - return handleIncoming(); -} - -int p3disc::handleIncoming() -{ - RsItem *item = NULL; - -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::handleIncoming()" << std::endl; -#endif - - int nhandled = 0; - // While messages read - while(NULL != (item = recvItem())) - { - RsDiscAskInfo *inf = NULL; - RsDiscReply *dri = NULL; - RsDiscVersion *dvi = NULL; - RsDiscHeartbeat *dta = NULL; - -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::handleIncoming() Received Message!" << std::endl; - item -> print(std::cerr); - std::cerr << std::endl; -#endif - - // if discovery reply then respond if haven't already. - if (NULL != (dri = dynamic_cast (item))) - { - if(rsPeers->servicePermissionFlags_sslid(item->PeerId()) & RS_SERVICE_PERM_DISCOVERY) - recvDiscReply(dri); - else - delete item ; - } - else if (NULL != (dvi = dynamic_cast (item))) - { - recvPeerVersionMsg(dvi); - nhandled++; - delete item; - } - else if (NULL != (inf = dynamic_cast (item))) /* Ping */ - { - if(rsPeers->servicePermissionFlags_sslid(item->PeerId()) & RS_SERVICE_PERM_DISCOVERY) - recvAskInfo(inf); - - nhandled++; - delete item; - } - else if (NULL != (dta = dynamic_cast (item))) - { - recvHeartbeatMsg(dta); - nhandled++ ; - delete item; - } - else - { -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::handleIncoming() Unknown Received Message!" << std::endl; - item -> print(std::cerr); - std::cerr << std::endl; -#endif - delete item; - } - } - -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::handleIncoming() finished." << std::endl; -#endif - - return nhandled; -} - - - - - /************* from pqiMonitor *******************/ -void p3disc::statusChange(const std::list &plist) -{ -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::statusChange()" << std::endl; -#endif - - std::list::const_iterator pit; - /* if any have switched to 'connected' then we notify */ - for(pit = plist.begin(); pit != plist.end(); pit++) - { - if ((pit->state & RS_PEER_S_FRIEND) && (pit->actions & RS_PEER_CONNECTED)) - { -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::statusChange() Starting Disc with: " << pit->id << std::endl; -#endif - sendOwnVersion(pit->id); - - if(rsPeers->servicePermissionFlags_sslid(pit->id) & RS_SERVICE_PERM_DISCOVERY) - sendAllInfoToJustConnectedPeer(pit->id); - - sendJustConnectedPeerInfoToAllPeer(pit->id); - } - else if (!(pit->state & RS_PEER_S_FRIEND) && (pit->actions & RS_PEER_MOVED)) - { -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::statusChange() Removing Friend: " << pit->id << std::endl; -#endif - removeFriend(pit->id); - } - else if ((pit->state & RS_PEER_S_FRIEND) && (pit->actions & RS_PEER_NEW)) - { -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::statusChange() Adding Friend: " << pit->id << std::endl; -#endif - askInfoToAllPeers(pit->id); - } - } -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::statusChange() finished." << std::endl; -#endif - return; -} - -void p3disc::sendAllInfoToJustConnectedPeer(const std::string &id) -{ - /* get a peer lists */ - -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::sendAllInfoToJustConnectedPeer() id: " << id << std::endl; -#endif - - std::list friendIds; - std::list::iterator it; - std::set gpgIds; - std::set::iterator git; - - /* We send our full friends list - if we have Discovery Enabled */ - if (mDiscEnabled) - { -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::sendAllInfoToJustConnectedPeer() Discovery Enabled, sending Friend List" << std::endl; -#endif - mLinkMgr->getFriendList(friendIds); - - /* send them a list of all friend's details */ - for(it = friendIds.begin(); it != friendIds.end(); it++) - { - /* get details */ - peerState detail; - if (!mPeerMgr->getFriendNetStatus(*it, detail)) - { - /* major error! */ -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::sendAllInfoToJustConnectedPeer() No Info, Skipping: " << *it; - std::cerr << std::endl; -#endif - continue; - } - - if (!(detail.visState & RS_VIS_STATE_NODISC)) - { -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::sendAllInfoToJustConnectedPeer() Adding GPGID: " << detail.gpg_id; - std::cerr << " (SSLID: " << *it << ")"; - std::cerr << std::endl; -#endif - gpgIds.insert(detail.gpg_id); - } - else - { -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::sendAllInfoToJustConnectedPeer() DISC OFF for GPGID: " << detail.gpg_id; - std::cerr << " (SSLID: " << *it << ")"; - std::cerr << std::endl; -#endif - } - } - } - - //add own info, this info is sent whether discovery is enabled - or not. - gpgIds.insert(rsPeers->getGPGOwnId()); - - { - RsStackMutex stack(mDiscMtx); /********** STACK LOCKED MTX ******/ - - /* refresh with new list */ - std::list &idList = mSendIdList[id]; - idList.clear(); - for(git = gpgIds.begin(); git != gpgIds.end(); git++) - { - idList.push_back(*git); - } - } - - #ifdef P3DISC_DEBUG - std::cerr << "p3disc::sendAllInfoToJustConnectedPeer() finished." << std::endl; - #endif -} - -void p3disc::sendJustConnectedPeerInfoToAllPeer(const std::string &connectedPeerId) -{ - -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::sendJustConnectedPeerInfoToAllPeer() connectedPeerId : " << connectedPeerId << std::endl; -#endif - - /* only ask info if discovery is on */ - { - RsStackMutex stack(mDiscMtx); /********** STACK LOCKED MTX ******/ - if (!mDiscEnabled) - { -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::sendJustConnectedPeerInfoToAllPeer() Disc Disabled => NULL OP" << std::endl; -#endif - return; - } - } - - /* get details */ - peerState detail; - if (!mPeerMgr->getFriendNetStatus(connectedPeerId, detail)) - { -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::sendJustConnectedPeerInfoToAllPeer() No NetStatus => FAILED" << std::endl; -#endif - return; - } - - if (detail.visState & RS_VIS_STATE_NODISC) - { -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::sendJustConnectedPeerInfoToAllPeer() Peer Disc Discable => NULL OP" << std::endl; -#endif - return; - } - - - std::string gpg_connectedPeerId = rsPeers->getGPGId(connectedPeerId); - std::list onlineIds; - - /* get a peer lists */ - rsPeers->getOnlineList(onlineIds); - - { - RsStackMutex stack(mDiscMtx); /********** STACK LOCKED MTX ******/ - - /* append gpg id's of all friend's to the sending list */ - - std::list::iterator it; - for (it = onlineIds.begin(); it != onlineIds.end(); it++) - if(rsPeers->servicePermissionFlags_sslid(*it) & RS_SERVICE_PERM_DISCOVERY) - { - std::list &idList = mSendIdList[*it]; - - if (std::find(idList.begin(), idList.end(), gpg_connectedPeerId) == idList.end()) - { -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::sendJustConnectedPeerInfoToAllPeer() adding to queue for: "; - std::cerr << *it << std::endl; -#endif - idList.push_back(gpg_connectedPeerId); - } - else - { -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::sendJustConnectedPeerInfoToAllPeer() already in queue for: "; - std::cerr << *it << std::endl; -#endif - } - } - } -} - - -bool isDummyFriend(const std::string &id) -{ - bool ret = (id.substr(0,5) == "dummy"); - return ret; -} - - /* (dest (to), source (cert)) */ -RsDiscReply *p3disc::createDiscReply(const std::string &to, const std::string &about) -{ - -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::createDiscReply() called. Sending details of: " << about << " to: " << to << std::endl; -#endif - - std::string aboutGpgId = rsPeers->getGPGId(about); - if (aboutGpgId.empty()) { -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::createDiscReply() no info about this id" << std::endl; -#endif - return NULL; - } - - - // Construct a message - RsDiscReply *di = new RsDiscReply(); - - // Fill the message - // Set Target as input cert. - di -> PeerId(to); - di -> aboutId = aboutGpgId; - - // set the ip addresse list. - std::list sslChilds; - rsPeers->getAssociatedSSLIds(aboutGpgId, sslChilds); - bool shouldWeSendGPGKey = false;//the GPG key is send only if we've got a valid friend with DISC enabled - - { - RsStackMutex stack(mDiscMtx); /********** STACK LOCKED MTX ******/ - if (!mDiscEnabled) - { -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::createDiscReply() Disc Disabled, removing all friend SSL Ids"; - std::cerr << std::endl; -#endif - sslChilds.clear(); - } - } - - std::list::iterator it; - for (it = sslChilds.begin(); it != sslChilds.end(); it++) - { - /* skip dummy ones - until they are removed fully */ - if (isDummyFriend(*it)) - { -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::createDiscReply() Skipping Dummy Child SSL Id:" << *it; - std::cerr << std::endl; -#endif - continue; - } - - peerState detail; - if (!mPeerMgr->getFriendNetStatus(*it, detail) - || detail.visState & RS_VIS_STATE_NODISC) - { -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::createDiscReply() Skipping cos No Details or NODISC flag id: " << *it; - std::cerr << std::endl; -#endif - continue; - } - -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::createDiscReply() Found Child SSL Id:" << *it; - std::cerr << std::endl; -#endif - -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::createDiscReply() Adding Child SSL Id Details"; - std::cerr << std::endl; -#endif - shouldWeSendGPGKey = true; - - RsPeerNetItem rsPeerNetItem ; - rsPeerNetItem.clear(); - - rsPeerNetItem.pid = detail.id; - rsPeerNetItem.gpg_id = detail.gpg_id; - rsPeerNetItem.location = detail.location; - rsPeerNetItem.netMode = detail.netMode; - rsPeerNetItem.visState = detail.visState; - rsPeerNetItem.lastContact = detail.lastcontact; - rsPeerNetItem.currentlocaladdr = detail.localaddr; - rsPeerNetItem.currentremoteaddr = detail.serveraddr; - rsPeerNetItem.dyndns = detail.dyndns; - detail.ipAddrs.mLocal.loadTlv(rsPeerNetItem.localAddrList); - detail.ipAddrs.mExt.loadTlv(rsPeerNetItem.extAddrList); - - - di->rsPeerList.push_back(rsPeerNetItem); - } - - - //send own details - if (about == rsPeers->getGPGOwnId()) - { -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::createDiscReply() Adding Own Id Details"; - std::cerr << std::endl; -#endif - peerState detail; - if (mPeerMgr->getOwnNetStatus(detail)) - { - shouldWeSendGPGKey = true; - RsPeerNetItem rsPeerNetItem ; - rsPeerNetItem.clear(); - rsPeerNetItem.pid = detail.id; - rsPeerNetItem.gpg_id = detail.gpg_id; - rsPeerNetItem.location = detail.location; - rsPeerNetItem.netMode = detail.netMode; - rsPeerNetItem.visState = detail.visState; - rsPeerNetItem.lastContact = time(NULL); - rsPeerNetItem.currentlocaladdr = detail.localaddr; - rsPeerNetItem.currentremoteaddr = detail.serveraddr; - rsPeerNetItem.dyndns = detail.dyndns; - detail.ipAddrs.mLocal.loadTlv(rsPeerNetItem.localAddrList); - detail.ipAddrs.mExt.loadTlv(rsPeerNetItem.extAddrList); - - di->rsPeerList.push_back(rsPeerNetItem); - } - } - - if (!shouldWeSendGPGKey) { -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::createDiscReply() GPG key should not be send, no friend with disc on found about it." << std::endl; -#endif - // cleanup! - delete di; - return NULL; - } - - return di; -} - -void p3disc::sendOwnVersion(std::string to) -{ -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::sendOwnVersion() Sending rs version to: " << to << std::endl; -#endif - - /* only ask info if discovery is on */ - if (!mDiscEnabled) - { -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::sendOwnVersion() Disc Disabled => NULL OP" << std::endl; -#endif - return; - } - - - RsDiscVersion *di = new RsDiscVersion(); - di->PeerId(to); - di->version = RsUtil::retroshareVersion(); - - /* send the message */ - sendItem(di); - -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::sendOwnVersion() finished." << std::endl; -#endif -} - -void p3disc::sendHeartbeat(std::string to) -{ - { - std::string out = "p3disc::sendHeartbeat() to : " + to; -#ifdef P3DISC_DEBUG - std::cerr << out << std::endl; -#endif - rslog(RSL_WARNING, pqidisczone, out); - } - - - RsDiscHeartbeat *di = new RsDiscHeartbeat(); - di->PeerId(to); - - /* send the message */ - sendItem(di); - -#ifdef P3DISC_DEBUG - std::cerr << "Sent tick Message" << std::endl; -#endif -} - -void p3disc::askInfoToAllPeers(std::string about) -{ - -#ifdef P3DISC_DEBUG - std::cerr <<"p3disc::askInfoToAllPeers() about " << about << std::endl; -#endif - - // We Still Ask even if Disc isn't Enabled... if they want to give us the info ;) - - - peerState connectState; - if (!mPeerMgr->getFriendNetStatus(about, connectState) || (connectState.visState & RS_VIS_STATE_NODISC)) - { -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::askInfoToAllPeers() friend disc is off, don't send the request." << std::endl; -#endif - return; - } - - std::string aboutGpgId = rsPeers->getGPGId(about); - if (aboutGpgId == "") - { -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::askInfoToAllPeers() no gpg id found" << std::endl; -#endif - } - - std::list onlineIds; - std::list::iterator it; - - rsPeers->getOnlineList(onlineIds); - - /* ask info to trusted friends */ - for(it = onlineIds.begin(); it != onlineIds.end(); it++) - { - RsDiscAskInfo *di = new RsDiscAskInfo(); - di->PeerId(*it); - di->gpg_id = aboutGpgId; - sendItem(di); -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::askInfoToAllPeers() question sent to : " << *it << std::endl; -#endif - } -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::askInfoToAllPeers() finished." << std::endl; -#endif -} - -void p3disc::recvPeerDetails(RsDiscReply *item, const std::string &certGpgId) -{ - -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::recvPeerFriendMsg() From: " << item->PeerId() << " About " << item->aboutId << std::endl; -#endif - - if (certGpgId.empty()) - { -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::recvPeerFriendMsg() gpg cert Id is empty - cert not transmitted" << std::endl; -#endif - } - else if (item->aboutId == "" || item->aboutId != certGpgId) - { - std::cerr << "p3disc::recvPeerFriendMsg() Error : about id is not the same as gpg id." << std::endl; - return; - } - - bool should_notify_discovery = false ; - std::string item_gpg_id = rsPeers->getGPGId(item->PeerId()) ; - - for (std::list::iterator pit = item->rsPeerList.begin(); pit != item->rsPeerList.end(); pit++) - { - if(isDummyFriend(pit->pid)) - { - continue; - } - - bool new_info = false; - addDiscoveryData(item->PeerId(), pit->pid,item_gpg_id, - item->aboutId, pit->currentlocaladdr, pit->currentremoteaddr, 0, time(NULL),new_info); - - if(new_info) - should_notify_discovery = true ; - -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::recvPeerFriendMsg() Peer Config Item:" << std::endl; - pit->print(std::cerr, 10); - std::cerr << std::endl; -#endif - - if (pit->pid != rsPeers->getOwnId()) - { - // Apparently, the connect manager won't add a friend if the gpg id is not - // trusted. However, this should be tested here for consistency and security - // in case of modifications in mConnMgr. - // - - // Check if already friend. - if(AuthGPG::getAuthGPG()->isGPGAccepted(pit->gpg_id) || pit->gpg_id == AuthGPG::getAuthGPG()->getGPGOwnId()) - { - if (!mPeerMgr->isFriend(pit->pid)) - { - // Add with no disc by default. If friend already exists, it will do nothing - // NO DISC is important - otherwise, we'll just enter a nasty loop, - // where every addition triggers requests, then they are cleaned up, and readded... - - // This way we get their addresses, but don't advertise them until we get a - // connection. -#ifdef P3DISC_DEBUG - std::cerr << "--> Adding to friends list " << pit->pid << " - " << pit->gpg_id << std::endl; -#endif - mPeerMgr->addFriend(pit->pid, pit->gpg_id, pit->netMode, RS_VIS_STATE_NODISC,(time_t)0,RS_SERVICE_PERM_ALL); - } - } - - /* skip if not one of our peers */ - if (!mPeerMgr->isFriend(pit->pid)) - { - /* THESE ARE OUR FRIEND OF FRIENDS ... pass this information along to NetMgr & DHT... - * as we can track FOF and use them as potential Proxies / Relays - */ - - /* add into NetMgr and non-search, so we can detect connect attempts */ - mNetMgr->netAssistFriend(pit->pid,false); - - /* inform NetMgr that we know this peer */ - mNetMgr->netAssistKnownPeer(pit->pid, pit->currentremoteaddr, - NETASSIST_KNOWN_PEER_FOF | NETASSIST_KNOWN_PEER_OFFLINE); - - continue; - } - - if (item->PeerId() == pit->pid) - { -#ifdef P3DISC_DEBUG - std::cerr << "Info sent by the peer itself -> updating self info:" << std::endl; - std::cerr << " -> current local addr = " << pit->currentlocaladdr << std::endl; - std::cerr << " -> current remote addr = " << pit->currentremoteaddr << std::endl; - std::cerr << " -> visState = " << std::hex << pit->visState << std::dec; - std::cerr << " -> network mode: " << pit->netMode << std::endl; - std::cerr << " -> location: " << pit->location << std::endl; - std::cerr << std::endl; -#endif - - bool peerDataChanged = false; - - // When the peer sends his own list of IPs, the info replaces the existing info, because the - // peer is the primary source of his own IPs. - if (mPeerMgr->setNetworkMode(pit->pid, pit->netMode)) { - peerDataChanged = true; - } - if (mPeerMgr->setLocation(pit->pid, pit->location)) { - peerDataChanged = true; - } - if (mPeerMgr->setLocalAddress(pit->pid, pit->currentlocaladdr)) { - peerDataChanged = true; - } - if (mPeerMgr->setExtAddress(pit->pid, pit->currentremoteaddr)) { - peerDataChanged = true; - } - if (mPeerMgr->setVisState(pit->pid, pit->visState)) { - peerDataChanged = true; - } - if (mPeerMgr->setDynDNS(pit->pid, pit->dyndns)) { - peerDataChanged = true; - } - - if (peerDataChanged == true) - { - // inform all connected peers of change - sendJustConnectedPeerInfoToAllPeer(pit->pid); - } - } - - // always update historical address list... this should be enough to let us connect. - - pqiIpAddrSet addrsFromPeer; - addrsFromPeer.mLocal.extractFromTlv(pit->localAddrList); - addrsFromPeer.mExt.extractFromTlv(pit->extAddrList); - -#ifdef P3DISC_DEBUG - std::cerr << "Setting address list to peer " << pit->pid << ", to be:" << std::endl ; - - addrsFromPeer.printAddrs(std::cerr); - std::cerr << std::endl; -#endif - mPeerMgr->updateAddressList(pit->pid, addrsFromPeer); - - } -#ifdef P3DISC_DEBUG - else - { - std::cerr << "Skipping info about own id " << pit->pid << std::endl ; - } -#endif - - } - - rsicontrol->getNotify().notifyListChange(NOTIFY_LIST_NEIGHBOURS, NOTIFY_TYPE_MOD); - - if(should_notify_discovery) - rsicontrol->getNotify().notifyDiscInfoChanged(); - - /* cleanup (handled by caller) */ -} - -void p3disc::recvPeerVersionMsg(RsDiscVersion *item) -{ -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::recvPeerVersionMsg() From: " << item->PeerId(); - std::cerr << std::endl; -#endif - - // dont need protection - versions[item->PeerId()] = item->version; - - return; -} - -void p3disc::recvHeartbeatMsg(RsDiscHeartbeat *item) -{ -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::recvHeartbeatMsg() From: " << item->PeerId(); - std::cerr << std::endl; -#endif - - mPqiPersonGrp->tagHeartbeatRecvd(item->PeerId()); - - return; -} - -void p3disc::recvAskInfo(RsDiscAskInfo *item) -{ -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::recvAskInfo() From: " << item->PeerId(); - std::cerr << std::endl; -#endif - RsStackMutex stack(mDiscMtx); /********** STACK LOCKED MTX ******/ - - /* only provide info if discovery is on */ - if (!mDiscEnabled) - { -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::recvAskInfo() Disc Disabled => NULL OP"; - std::cerr << std::endl; -#endif - return; - } - - std::list &idList = mSendIdList[item->PeerId()]; - - if (std::find(idList.begin(), idList.end(), item->gpg_id) == idList.end()) { - idList.push_back(item->gpg_id); - } -} - -void p3disc::recvDiscReply(RsDiscReply *dri) -{ - RsStackMutex stack(mDiscMtx); /********** STACK LOCKED MTX ******/ - -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::recvDiscReply() From: " << dri->PeerId() << " About: " << dri->aboutId; - std::cerr << std::endl; -#endif - - /* search pending item and remove it, when already exist */ - std::list::iterator it; - for (it = mPendingDiscReplyInList.begin(); it != mPendingDiscReplyInList.end(); it++) - { - if ((*it)->PeerId() == dri->PeerId() && (*it)->aboutId == dri->aboutId) - { - delete (*it); - mPendingDiscReplyInList.erase(it); - break; - } - } - - // add item to list for later process - - if(mDiscEnabled || dri->aboutId == rsPeers->getGPGId(dri->PeerId())) - mPendingDiscReplyInList.push_back(dri); // no delete - else - delete dri ; -} - - - - -void p3disc::removeFriend(std::string /*ssl_id*/) -{ -} - -/*************************************************************************************/ -/* AuthGPGService */ -/*************************************************************************************/ -AuthGPGOperation *p3disc::getGPGOperation() -{ - { - RsStackMutex stack(mDiscMtx); /********** STACK LOCKED MTX ******/ - - /* process disc reply in list */ - if (mPendingDiscReplyInList.empty() == false) { - RsDiscReply *item = mPendingDiscReplyInList.front(); - - return new AuthGPGOperationLoadOrSave(true, item->aboutId, item->certGPG, item); - } - } - - /* process disc reply out list */ - - std::string destId; - std::string srcId; - - { - RsStackMutex stack(mDiscMtx); /********** STACK LOCKED MTX ******/ - - while (!mSendIdList.empty()) - { - std::map >::iterator it = mSendIdList.begin(); - - if (!it->second.empty() && mLinkMgr->isOnline(it->first)) { - std::string gpgId = it->second.front(); - it->second.pop_front(); - - destId = it->first; - srcId = gpgId; - - break; - } else { - /* peer is not online anymore ... try next */ - mSendIdList.erase(it); - } - } - } - - if (!destId.empty() && !srcId.empty()) { - RsDiscReply *item = createDiscReply(destId, srcId); - if (item) { - return new AuthGPGOperationLoadOrSave(false, item->aboutId, "", item); - } - } - - return NULL; -} - -void p3disc::setGPGOperation(AuthGPGOperation *operation) -{ - AuthGPGOperationLoadOrSave *loadOrSave = dynamic_cast(operation); - if (loadOrSave) { - if (loadOrSave->m_load) { - /* search in pending in list */ - RsDiscReply *item = NULL; - - { - RsStackMutex stack(mDiscMtx); /********** STACK LOCKED MTX ******/ - - std::list::iterator it; - it = std::find(mPendingDiscReplyInList.begin(), mPendingDiscReplyInList.end(), loadOrSave->m_userdata); - if (it != mPendingDiscReplyInList.end()) { - item = *it; - mPendingDiscReplyInList.erase(it); - } - } - - if (item) { - recvPeerDetails(item, loadOrSave->m_certGpgId); - delete item; - } - } else { - RsDiscReply *item = (RsDiscReply*) loadOrSave->m_userdata; - - if (item) - { -// It is okay to send an empty certificate! - This is to reduce the network load at connection time. -// Hopefully, we'll get the stripped down certificates working soon!... even then still be okay to send null. -#if 0 - if (loadOrSave->m_certGpg.empty()) - { -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::setGPGOperation() don't send details because the gpg cert is not good" << std::endl; -#endif - delete item; - return; - } -#endif - - /* for Relay Connections (and other slow ones) we don't want to - * to waste bandwidth sending certificates. So don't add it. - */ - - uint32_t linkType = mLinkMgr->getLinkType(item->PeerId()); - if ((linkType & RS_NET_CONN_SPEED_TRICKLE) || - (linkType & RS_NET_CONN_SPEED_LOW)) - { - std::cerr << "p3disc::setGPGOperation() Send DiscReply Packet to: "; - std::cerr << item->PeerId(); - std::cerr << " without Certificate (low bandwidth)" << std::endl; - } - else - { - // Attaching Certificate. - item->certGPG = loadOrSave->m_certGpg; - } - -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::setGPGOperation() About to Send Message:" << std::endl; - item->print(std::cerr, 5); -#endif - - // Send off message - sendItem(item); - -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::cbkGPGOperationSave() discovery reply sent." << std::endl; -#endif - } - } - return; - } - - /* ignore other operations */ -} - -/*************************************************************************************/ -/* Storing Network Graph */ -/*************************************************************************************/ -int p3disc::addDiscoveryData(const std::string& fromId, const std::string& aboutId,const std::string& from_gpg_id,const std::string& about_gpg_id, const struct sockaddr_in& laddr, const struct sockaddr_in& raddr, uint32_t flags, time_t ts,bool& new_info) -{ - RsStackMutex stack(mDiscMtx); /********** STACK LOCKED MTX ******/ - - new_info = false ; - - gpg_neighbors[from_gpg_id].insert(about_gpg_id) ; - -#ifdef P3DISC_DEBUG - std::cerr << "Adding discovery data " << fromId << " - " << aboutId << std::endl ; -#endif - /* Store Network information */ - std::map::iterator it; - if (neighbours.end() == (it = neighbours.find(aboutId))) - { - /* doesn't exist */ - autoneighbour an; - - /* an data */ - an.id = aboutId; - an.validAddrs = false; - an.discFlags = 0; - an.ts = 0; - - neighbours[aboutId] = an; - - it = neighbours.find(aboutId); - new_info = true ; - } - - /* it always valid */ - - /* just update packet */ - - autoserver as; - - as.id = fromId; - as.localAddr = laddr; - as.remoteAddr = raddr; - as.discFlags = flags; - as.ts = ts; - - bool authDetails = (as.id == it->second.id); - - /* KEY decision about address */ - if ((authDetails) || - ((!(it->second.authoritative)) && (as.ts > it->second.ts))) - { - /* copy details to an */ - it->second.authoritative = authDetails; - it->second.ts = as.ts; - it->second.validAddrs = true; - it->second.localAddr = as.localAddr; - it->second.remoteAddr = as.remoteAddr; - it->second.discFlags = as.discFlags; - } - - if(it->second.neighbour_of.find(fromId) == it->second.neighbour_of.end()) - { - (it->second).neighbour_of[fromId] = as; - new_info =true ; - } - - /* do we update network address info??? */ - return 1; - -} - - - -/*************************************************************************************/ -/* Extracting Network Graph Details */ -/*************************************************************************************/ -bool p3disc::potentialproxies(const std::string& id, std::list &proxyIds) -{ - /* find id -> and extract the neighbour_of ids */ - - if(id == rsPeers->getOwnId()) // SSL id // This is treated appart, because otherwise we don't receive any disc info about us - return rsPeers->getFriendList(proxyIds) ; - - RsStackMutex stack(mDiscMtx); /********** STACK LOCKED MTX ******/ - - std::map::iterator it; - std::map::iterator sit; - if (neighbours.end() == (it = neighbours.find(id))) - { - return false; - } - - for(sit = it->second.neighbour_of.begin(); sit != it->second.neighbour_of.end(); sit++) - { - proxyIds.push_back(sit->first); - } - return true; -} - - -bool p3disc::potentialGPGproxies(const std::string& gpg_id, std::list &proxyGPGIds) -{ - /* find id -> and extract the neighbour_of ids */ - - if(gpg_id == rsPeers->getGPGOwnId()) // SSL id // This is treated appart, because otherwise we don't receive any disc info about us - return rsPeers->getGPGAcceptedList(proxyGPGIds) ; - - RsStackMutex stack(mDiscMtx); /********** STACK LOCKED MTX ******/ - - std::map >::iterator it = gpg_neighbors.find(gpg_id) ; - - if(it == gpg_neighbors.end()) - return false; - - for(std::set::const_iterator sit(it->second.begin()); sit != it->second.end(); ++sit) - proxyGPGIds.push_back(*sit); - - return true; -} - -void p3disc::getversions(std::map &versions) -{ - versions = this->versions; -} - -void p3disc::getWaitingDiscCount(unsigned int *sendCount, unsigned int *recvCount) -{ - if (sendCount == NULL && recvCount == NULL) { - /* Nothing to do */ - return; - } - - RsStackMutex stack(mDiscMtx); /********** STACK LOCKED MTX ******/ - - if (sendCount) { - *sendCount = 0; - - std::map >::iterator it; - for (it = mSendIdList.begin(); it != mSendIdList.end(); it++) { - *sendCount += it->second.size(); - } - } - - if (recvCount) { - *recvCount = mPendingDiscReplyInList.size(); - } -} - -#ifdef UNUSED_CODE -int p3disc::idServers() -{ - RsStackMutex stack(mDiscMtx); /********** STACK LOCKED MTX ******/ - - std::map::iterator nit; - std::map::iterator sit; - int cts = time(NULL); - - std::string out = "::::AutoDiscovery Neighbours::::\n"; - for(nit = neighbours.begin(); nit != neighbours.end(); nit++) - { - out += "Neighbour: " + (nit->second).id + "\n"; - rs_sprintf_append(out, "-> LocalAddr: %s:%u\n", rs_inet_ntoa(nit->second.localAddr.sin_addr).c_str(), ntohs(nit->second.localAddr.sin_port)); - rs_sprintf_append(out, "-> RemoteAddr: %s:%u\n", rs_inet_ntoa(nit->second.remoteAddr.sin_addr).c_str(), ntohs(nit->second.remoteAddr.sin_port)); - rs_sprintf_append(out, " Last Contact: %ld sec ago\n", cts - (nit->second.ts)); - - rs_sprintf_append(out, " -->DiscFlags: 0x%x\n", nit->second.discFlags); - - for(sit = (nit->second.neighbour_of).begin(); - sit != (nit->second.neighbour_of).end(); sit++) - { - out += "\tConnected via: " + (sit->first) + "\n"; - rs_sprintf_append(out, "\t\tLocalAddr: %s:%u\n", rs_inet_ntoa(sit->second.localAddr.sin_addr).c_str(), ntohs(sit->second.localAddr.sin_port)); - rs_sprintf_append(out, "\t\tRemoteAddr: %s:%u\n", rs_inet_ntoa(sit->second.remoteAddr.sin_addr).c_str(), ntohs(sit->second.remoteAddr.sin_port)); - - rs_sprintf_append(out, "\t\tLast Contact: %ld sec ago\n", cts - (sit->second.ts)); - rs_sprintf_append(out, "\t\tDiscFlags: 0x%x\n", sit->second.discFlags); - } - } - -#ifdef P3DISC_DEBUG - std::cerr << "p3disc::idServers()" << std::endl; - std::cerr << out; -#endif - - return 1; -} -#endif - -// tdelta -> trange. -// -inf...<0 0 (invalid) -// 0.. <9 1 -// 9...<99 2 -// 99...<999 3 -// 999...<9999 4 -// etc... - -//int convertTDeltaToTRange(double tdelta) -//{ -// if (tdelta < 0) -// return 0; -// int trange = 1 + (int) log10(tdelta + 1.0); -// return trange; -// -//} - -// trange -> tdelta -// -inf...0 -1 (invalid) -// 1 8 -// 2 98 -// 3 998 -// 4 9998 -// etc... - -//int convertTRangeToTDelta(int trange) -//{ -// if (trange <= 0) -// return -1; -// -// return (int) (pow(10.0, trange) - 1.5); // (int) xxx98.5 -> xxx98 -//} - -#endif // #if 0 diff --git a/libretroshare/src/services/p3rtt.cc b/libretroshare/src/services/p3rtt.cc index 91fb51b9e..bea7ce492 100644 --- a/libretroshare/src/services/p3rtt.cc +++ b/libretroshare/src/services/p3rtt.cc @@ -118,7 +118,7 @@ static double convert64bitsToTs(uint64_t bits) p3rtt::p3rtt(p3LinkMgr *lm) - :p3Service(RS_SERVICE_TYPE_RTT), /* p3Config(CONFIG_TYPE_RTT), */ mRttMtx("p3rtt"), mLinkMgr(lm) + :p3FastService(RS_SERVICE_TYPE_RTT), mRttMtx("p3rtt"), mLinkMgr(lm) { addSerialType(new RsRttSerialiser()); @@ -130,7 +130,6 @@ p3rtt::p3rtt(p3LinkMgr *lm) int p3rtt::tick() { - processIncoming(); sendPackets(); return 0; @@ -212,57 +211,30 @@ void p3rtt::sendPingMeasurements() } - - -int p3rtt::processIncoming() +bool p3rtt::recvItem(RsItem *item) { - /* for each packet - pass to specific handler */ - RsItem *item = NULL; - while(NULL != (item = recvItem())) + switch(item->PacketSubType()) { - switch(item->PacketSubType()) + default: + break; + case RS_PKT_SUBTYPE_RTT_PING: { - default: - break; - case RS_PKT_SUBTYPE_RTT_PING: - { - handlePing(item); - } - break; - case RS_PKT_SUBTYPE_RTT_PONG: - { - handlePong(item); - } - break; - -#if 0 - /* THESE ARE ALL FUTURISTIC DATA TYPES */ - case RS_DATA_ITEM: - { - handleData(item); - } - break; - - case RS_BANDWIDTH_PING_ITEM: - { - handleBandwidthPing(item); - } - break; - - case RS_BANDWIDTH_PONG_ITEM: - { - handleBandwidthPong(item); - } - break; -#endif + handlePing(item); } - - /* clean up */ - delete item; + break; + case RS_PKT_SUBTYPE_RTT_PONG: + { + handlePong(item); + } + break; } + + /* clean up */ + delete item; return true ; } + int p3rtt::handlePing(RsItem *item) { /* cast to right type */ diff --git a/libretroshare/src/services/p3rtt.h b/libretroshare/src/services/p3rtt.h index 68c90fdfb..e2e42fb24 100644 --- a/libretroshare/src/services/p3rtt.h +++ b/libretroshare/src/services/p3rtt.h @@ -60,7 +60,7 @@ class RttPeerInfo * Used to test Latency. */ -class p3rtt: public RsRtt, public p3Service +class p3rtt: public RsRtt, public p3FastService { public: p3rtt(p3LinkMgr *cm); @@ -74,10 +74,10 @@ virtual uint32_t getPongResults(std::string id, int n, std::listsin_family = AF_INET; @@ -285,8 +300,10 @@ bool operator<(const struct sockaddr_storage &a, const struct sockaddr_storage & bool sockaddr_storage_same(const struct sockaddr_storage &addr, const struct sockaddr_storage &addr2) { +#ifdef SS_DEBUG std::cerr << "sockaddr_storage_same()"; std::cerr << std::endl; +#endif if (!sockaddr_storage_samefamily(addr, addr2)) return false; @@ -310,16 +327,20 @@ bool sockaddr_storage_same(const struct sockaddr_storage &addr, const struct soc bool sockaddr_storage_samefamily(const struct sockaddr_storage &addr, const struct sockaddr_storage &addr2) { +#ifdef SS_DEBUG std::cerr << "sockaddr_storage_samefamily()"; std::cerr << std::endl; +#endif return (addr.ss_family == addr2.ss_family); } bool sockaddr_storage_sameip(const struct sockaddr_storage &addr, const struct sockaddr_storage &addr2) { +#ifdef SS_DEBUG std::cerr << "sockaddr_storage_sameip()"; std::cerr << std::endl; +#endif if (!sockaddr_storage_samefamily(addr, addr2)) return false; @@ -343,8 +364,10 @@ bool sockaddr_storage_sameip(const struct sockaddr_storage &addr, const struct s bool sockaddr_storage_samenet(const struct sockaddr_storage &addr, const struct sockaddr_storage &addr2) { +#ifdef SS_DEBUG std::cerr << "sockaddr_storage_samenet()"; std::cerr << std::endl; +#endif if (!sockaddr_storage_samefamily(addr, addr2)) return false; @@ -367,8 +390,10 @@ bool sockaddr_storage_samenet(const struct sockaddr_storage &addr, const struct bool sockaddr_storage_samesubnet(const struct sockaddr_storage &addr, const struct sockaddr_storage &addr2) { +#ifdef SS_DEBUG std::cerr << "sockaddr_storage_samesubnet()"; std::cerr << std::endl; +#endif if (!sockaddr_storage_samefamily(addr, addr2)) return false; @@ -463,8 +488,10 @@ std::string sockaddr_storage_porttostring(const struct sockaddr_storage &addr) /********************************* Net Checks ***********************************/ bool sockaddr_storage_isnull(const struct sockaddr_storage &addr) { +#ifdef SS_DEBUG std::cerr << "sockaddr_storage_isnull()"; std::cerr << std::endl; +#endif if (addr.ss_family == 0) return true; @@ -486,8 +513,10 @@ bool sockaddr_storage_isnull(const struct sockaddr_storage &addr) bool sockaddr_storage_isValidNet(const struct sockaddr_storage &addr) { +#ifdef SS_DEBUG std::cerr << "sockaddr_storage_isValidNet()"; std::cerr << std::endl; +#endif switch(addr.ss_family) { @@ -507,8 +536,10 @@ bool sockaddr_storage_isValidNet(const struct sockaddr_storage &addr) bool sockaddr_storage_isLoopbackNet(const struct sockaddr_storage &addr) { +#ifdef SS_DEBUG std::cerr << "sockaddr_storage_isLoopbackNet()"; std::cerr << std::endl; +#endif switch(addr.ss_family) { @@ -529,8 +560,10 @@ bool sockaddr_storage_isLoopbackNet(const struct sockaddr_storage &addr) bool sockaddr_storage_isPrivateNet(const struct sockaddr_storage &addr) { +#ifdef SS_DEBUG std::cerr << "sockaddr_storage_isPrivateNet()"; std::cerr << std::endl; +#endif switch(addr.ss_family) { @@ -551,8 +584,10 @@ bool sockaddr_storage_isPrivateNet(const struct sockaddr_storage &addr) bool sockaddr_storage_isExternalNet(const struct sockaddr_storage &addr) { +#ifdef SS_DEBUG std::cerr << "sockaddr_storage_isExternalNet()"; std::cerr << std::endl; +#endif switch(addr.ss_family) { @@ -608,8 +643,10 @@ const struct sockaddr_in6 *to_const_ipv6_ptr(const struct sockaddr_storage &addr bool sockaddr_storage_ipv4_zeroip(struct sockaddr_storage &addr) { +#ifdef SS_DEBUG std::cerr << "sockaddr_storage_ipv4_zeroip()"; std::cerr << std::endl; +#endif struct sockaddr_in *ipv4_ptr = to_ipv4_ptr(addr); memset(&(ipv4_ptr->sin_addr), 0, sizeof(ipv4_ptr->sin_addr)); @@ -619,8 +656,10 @@ bool sockaddr_storage_ipv4_zeroip(struct sockaddr_storage &addr) bool sockaddr_storage_ipv4_copyip(struct sockaddr_storage &dst, const struct sockaddr_storage &src) { +#ifdef SS_DEBUG std::cerr << "sockaddr_storage_ipv4_copyip()"; std::cerr << std::endl; +#endif struct sockaddr_in *dst_ptr = to_ipv4_ptr(dst); const struct sockaddr_in *src_ptr = to_const_ipv4_ptr(src); @@ -644,8 +683,10 @@ uint16_t sockaddr_storage_ipv4_port(const struct sockaddr_storage &addr) bool sockaddr_storage_ipv4_setport(struct sockaddr_storage &addr, uint16_t port) { +#ifdef SS_DEBUG std::cerr << "sockaddr_storage_ipv4_setport()"; std::cerr << std::endl; +#endif struct sockaddr_in *ipv4_ptr = to_ipv4_ptr(addr); ipv4_ptr->sin_port = htons(port); @@ -700,8 +741,10 @@ bool sockaddr_storage_ipv6_setport(struct sockaddr_storage &addr, uint16_t port) bool sockaddr_storage_ipv4_lessthan(const struct sockaddr_storage &addr, const struct sockaddr_storage &addr2) { +#ifdef SS_DEBUG std::cerr << "sockaddr_storage_ipv4_lessthan()"; std::cerr << std::endl; +#endif const struct sockaddr_in *ptr1 = to_const_ipv4_ptr(addr); const struct sockaddr_in *ptr2 = to_const_ipv4_ptr(addr2); @@ -715,8 +758,10 @@ bool sockaddr_storage_ipv4_lessthan(const struct sockaddr_storage &addr, const s bool sockaddr_storage_ipv4_same(const struct sockaddr_storage &addr, const struct sockaddr_storage &addr2) { +#ifdef SS_DEBUG std::cerr << "sockaddr_storage_ipv4_same()"; std::cerr << std::endl; +#endif const struct sockaddr_in *ptr1 = to_const_ipv4_ptr(addr); const struct sockaddr_in *ptr2 = to_const_ipv4_ptr(addr2); @@ -727,8 +772,10 @@ bool sockaddr_storage_ipv4_same(const struct sockaddr_storage &addr, const struc bool sockaddr_storage_ipv4_sameip(const struct sockaddr_storage &addr, const struct sockaddr_storage &addr2) { +#ifdef SS_DEBUG std::cerr << "sockaddr_storage_ipv4_sameip()"; std::cerr << std::endl; +#endif const struct sockaddr_in *ptr1 = to_const_ipv4_ptr(addr); const struct sockaddr_in *ptr2 = to_const_ipv4_ptr(addr2); @@ -742,8 +789,10 @@ bool sockaddr_storage_ipv4_samenet(const struct sockaddr_storage &addr, const st (void) addr; (void) addr2; +#ifdef SS_DEBUG std::cerr << "sockaddr_storage_ipv4_samenet()"; std::cerr << std::endl; +#endif const struct sockaddr_in *ptr1 = to_const_ipv4_ptr(addr); @@ -756,8 +805,10 @@ bool sockaddr_storage_ipv4_samesubnet(const struct sockaddr_storage &addr, const (void) addr; (void) addr2; +#ifdef SS_DEBUG std::cerr << "sockaddr_storage_ipv4_samesubnet() using pqinetwork::isSameSubnet()"; std::cerr << std::endl; +#endif const struct sockaddr_in *ptr1 = to_const_ipv4_ptr(addr); const struct sockaddr_in *ptr2 = to_const_ipv4_ptr(addr2); @@ -866,8 +917,10 @@ std::string sockaddr_storage_ipv6_iptostring(const struct sockaddr_storage & /* /********************************* Net Checks ***********************************/ bool sockaddr_storage_ipv4_isnull(const struct sockaddr_storage &addr) { +#ifdef SS_DEBUG std::cerr << "sockaddr_storage_ipv4_isnull()"; std::cerr << std::endl; +#endif const struct sockaddr_in *ptr1 = to_const_ipv4_ptr(addr); if (ptr1->sin_family != AF_INET) @@ -883,8 +936,10 @@ bool sockaddr_storage_ipv4_isnull(const struct sockaddr_storage &addr) bool sockaddr_storage_ipv4_isValidNet(const struct sockaddr_storage &addr) { +#ifdef SS_DEBUG std::cerr << "sockaddr_storage_ipv4_isValidNet()"; std::cerr << std::endl; +#endif const struct sockaddr_in *ptr1 = to_const_ipv4_ptr(addr); if (ptr1->sin_family != AF_INET) @@ -897,8 +952,10 @@ bool sockaddr_storage_ipv4_isValidNet(const struct sockaddr_storage &addr) bool sockaddr_storage_ipv4_isLoopbackNet(const struct sockaddr_storage &addr) { +#ifdef SS_DEBUG std::cerr << "sockaddr_storage_ipv4_isLoopbackNet()"; std::cerr << std::endl; +#endif const struct sockaddr_in *ptr1 = to_const_ipv4_ptr(addr); @@ -911,8 +968,10 @@ bool sockaddr_storage_ipv4_isLoopbackNet(const struct sockaddr_storage &addr) bool sockaddr_storage_ipv4_isPrivateNet(const struct sockaddr_storage &addr) { +#ifdef SS_DEBUG std::cerr << "sockaddr_storage_ipv4_isPrivateNet()"; std::cerr << std::endl; +#endif const struct sockaddr_in *ptr1 = to_const_ipv4_ptr(addr); @@ -925,8 +984,10 @@ bool sockaddr_storage_ipv4_isPrivateNet(const struct sockaddr_storage &addr) bool sockaddr_storage_ipv4_isExternalNet(const struct sockaddr_storage &addr) { +#ifdef SS_DEBUG std::cerr << "sockaddr_storage_ipv4_isExternalNet()"; std::cerr << std::endl; +#endif const struct sockaddr_in *ptr1 = to_const_ipv4_ptr(addr); if (ptr1->sin_family != AF_INET) From a455bcc5d23b2138ebc218a5f554fdc3aa26e496 Mon Sep 17 00:00:00 2001 From: drbob Date: Wed, 2 Oct 2013 03:22:43 +0000 Subject: [PATCH 27/83] Increased RRT graph range, for new improved statistics. git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@6788 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- retroshare-gui/src/gui/RttStatistics.cpp | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/retroshare-gui/src/gui/RttStatistics.cpp b/retroshare-gui/src/gui/RttStatistics.cpp index 3aca89989..fce49c6e1 100644 --- a/retroshare-gui/src/gui/RttStatistics.cpp +++ b/retroshare-gui/src/gui/RttStatistics.cpp @@ -323,7 +323,19 @@ void RttStatisticsWidget::updateRttStatistics(const std::map Date: Wed, 2 Oct 2013 19:56:01 +0000 Subject: [PATCH 28/83] - fixed bug (added missing call to addSerialType()) - removed unused RsFileTransferCacheRequestItem and all related functions - fixed bug in turtle router calling members of a deleted item - removed some debug info git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@6789 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/ft/ftserver.cc | 92 ++++++++++++---- libretroshare/src/pqi/p3netmgr.cc | 1 - libretroshare/src/pqi/pqiservice.cc | 1 + libretroshare/src/pqi/pqistreamer.cc | 1 - libretroshare/src/retroshare/rstypes.h | 2 + .../src/serialiser/rsfiletransferitems.cc | 104 +----------------- .../src/serialiser/rsfiletransferitems.h | 21 ---- libretroshare/src/services/p3discovery2.cc | 1 - libretroshare/src/turtle/p3turtle.cc | 14 +-- 9 files changed, 81 insertions(+), 156 deletions(-) diff --git a/libretroshare/src/ft/ftserver.cc b/libretroshare/src/ft/ftserver.cc index 933d99c55..8e3f34b2b 100644 --- a/libretroshare/src/ft/ftserver.cc +++ b/libretroshare/src/ft/ftserver.cc @@ -53,8 +53,8 @@ const int ftserverzone = 29539; #include "serialiser/rsserviceids.h" /*** - * #define SERVER_DEBUG 1 - * #define DEBUG_TICK 1 + * #define SERVER_DEBUG 1 + * #define SERVER_DEBUG_CACHE 1 ***/ static const time_t FILE_TRANSFER_LOW_PRIORITY_TASKS_PERIOD = 5 ; // low priority tasks handling every 5 seconds @@ -70,6 +70,8 @@ ftServer::ftServer(p3PeerMgr *pm, p3LinkMgr *lm) mFtDataplex(NULL), mFtSearch(NULL), srvMutex("ftServer") { mCacheStrapper = new ftCacheStrapper(lm); + + addSerialType(new RsFileTransferSerialiser()) ; } void ftServer::setConfigDirectory(std::string path) @@ -446,15 +448,11 @@ RsTurtleGenericTunnelItem *ftServer::deserialiseItem(void *data,uint32_t size) c #ifdef SERVER_DEBUG std::cerr << "p3turtle: deserialising packet: " << std::endl ; #endif -#ifdef SERVER_DEBUG if ((RS_PKT_VERSION_SERVICE != getRsItemVersion(rstype)) || (RS_SERVICE_TYPE_TURTLE != getRsItemService(rstype))) { -#ifdef SERVER_DEBUG std::cerr << " Wrong type !!" << std::endl ; -#endif return NULL; /* wrong type */ } -#endif switch(getRsItemSubType(rstype)) { @@ -838,10 +836,15 @@ bool ftServer::shareDownloadDirectory(bool share) /**************** Config Interface *****************************/ /***************************************************************/ - /* Key Functions to be overloaded for Full Configuration */ +/* Key Functions to be overloaded for Full Configuration */ RsSerialiser *ftServer::setupSerialiser() { - return NULL; + RsSerialiser *rss = new RsSerialiser ; + rss->addSerialType(new RsFileTransferSerialiser) ; + + //rss->addSerialType(new RsGeneralConfigSerialiser()); + + return rss ; } bool ftServer::saveList(bool &/*cleanup*/, std::list& /*list*/) @@ -868,6 +871,9 @@ bool ftServer::loadConfigMap(std::map &/*configMap*/) /* Client Send */ bool ftServer::sendDataRequest(const std::string& peerId, const std::string& hash, uint64_t size, uint64_t offset, uint32_t chunksize) { +#ifdef SERVER_DEBUG + std::cerr << "ftServer::sendDataRequest() to peer " << peerId << " for hash " << hash << ", offset=" << offset << ", chunk size="<< chunksize << std::endl; +#endif if(mTurtleRouter->isTurtlePeer(peerId)) { RsTurtleFileRequestItem *item = new RsTurtleFileRequestItem ; @@ -879,6 +885,7 @@ bool ftServer::sendDataRequest(const std::string& peerId, const std::string& has } else { + std::cerr << "ftServer::sendDataRequest() " <isTurtlePeer(peerId)) { RsTurtleFileMapRequestItem *item = new RsTurtleFileMapRequestItem ; @@ -928,6 +938,9 @@ bool ftServer::sendChunkMapRequest(const std::string& peerId,const std::string& bool ftServer::sendChunkMap(const std::string& peerId,const std::string& hash,const CompressedChunkMap& map,bool is_client) { +#ifdef SERVER_DEBUG + std::cerr << "ftServer::sendChunkMap() to peer " << peerId << " for hash " << hash << std::endl; +#endif if(mTurtleRouter->isTurtlePeer(peerId)) { RsTurtleFileMapItem *item = new RsTurtleFileMapItem ; @@ -956,6 +969,9 @@ bool ftServer::sendChunkMap(const std::string& peerId,const std::string& hash,co bool ftServer::sendSingleChunkCRCRequest(const std::string& peerId,const std::string& hash,uint32_t chunk_number) { +#ifdef SERVER_DEBUG + std::cerr << "ftServer::sendSingleCRCRequest() to peer " << peerId << " for hash " << hash << ", chunk number=" << chunk_number << std::endl; +#endif if(mTurtleRouter->isTurtlePeer(peerId)) { RsTurtleChunkCrcRequestItem *item = new RsTurtleChunkCrcRequestItem; @@ -984,6 +1000,9 @@ bool ftServer::sendSingleChunkCRCRequest(const std::string& peerId,const std::st bool ftServer::sendSingleChunkCRC(const std::string& peerId,const std::string& hash,uint32_t chunk_number,const Sha1CheckSum& crc) { +#ifdef SERVER_DEBUG + std::cerr << "ftServer::sendSingleCRC() to peer " << peerId << " for hash " << hash << ", chunk number=" << chunk_number << std::endl; +#endif if(mTurtleRouter->isTurtlePeer(peerId)) { RsTurtleChunkCrcItem *item = new RsTurtleChunkCrcItem; @@ -1119,6 +1138,9 @@ void ftServer::receiveTurtleData(RsTurtleGenericTunnelItem *i, case RS_TURTLE_SUBTYPE_FILE_REQUEST: { RsTurtleFileRequestItem *item = dynamic_cast(i) ; +#ifdef SERVER_DEBUG + std::cerr << "ftServer::receiveTurtleData(): received file data request for " << hash << " from peer " << virtual_peer_id << std::endl; +#endif getMultiplexer()->recvDataRequest(virtual_peer_id,hash,0,item->chunk_offset,item->chunk_size) ; } break ; @@ -1126,6 +1148,9 @@ void ftServer::receiveTurtleData(RsTurtleGenericTunnelItem *i, case RS_TURTLE_SUBTYPE_FILE_DATA : { RsTurtleFileDataItem *item = dynamic_cast(i) ; +#ifdef SERVER_DEBUG + std::cerr << "ftServer::receiveTurtleData(): received file data for " << hash << " from peer " << virtual_peer_id << std::endl; +#endif getMultiplexer()->recvData(virtual_peer_id,hash,0,item->chunk_offset,item->chunk_size,item->chunk_data) ; item->chunk_data = NULL ; // this prevents deletion in the destructor of RsFileDataItem, because data will be deleted @@ -1137,6 +1162,9 @@ void ftServer::receiveTurtleData(RsTurtleGenericTunnelItem *i, case RS_TURTLE_SUBTYPE_FILE_MAP : { RsTurtleFileMapItem *item = dynamic_cast(i) ; +#ifdef SERVER_DEBUG + std::cerr << "ftServer::receiveTurtleData(): received chunk map for hash " << hash << " from peer " << virtual_peer_id << std::endl; +#endif getMultiplexer()->recvChunkMap(virtual_peer_id,hash,item->compressed_map,direction == RsTurtleGenericTunnelItem::DIRECTION_CLIENT) ; } break ; @@ -1144,6 +1172,9 @@ void ftServer::receiveTurtleData(RsTurtleGenericTunnelItem *i, case RS_TURTLE_SUBTYPE_FILE_MAP_REQUEST: { //RsTurtleFileMapRequestItem *item = dynamic_cast(i) ; +#ifdef SERVER_DEBUG + std::cerr << "ftServer::receiveTurtleData(): received chunkmap request for hash " << hash << " from peer " << virtual_peer_id << std::endl; +#endif getMultiplexer()->recvChunkMapRequest(virtual_peer_id,hash,direction == RsTurtleGenericTunnelItem::DIRECTION_CLIENT) ; } break ; @@ -1151,6 +1182,9 @@ void ftServer::receiveTurtleData(RsTurtleGenericTunnelItem *i, case RS_TURTLE_SUBTYPE_CHUNK_CRC : { RsTurtleChunkCrcItem *item = dynamic_cast(i) ; +#ifdef SERVER_DEBUG + std::cerr << "ftServer::receiveTurtleData(): received single chunk CRC for hash " << hash << " from peer " << virtual_peer_id << std::endl; +#endif getMultiplexer()->recvSingleChunkCRC(virtual_peer_id,hash,item->chunk_number,item->check_sum) ; } break ; @@ -1158,6 +1192,9 @@ void ftServer::receiveTurtleData(RsTurtleGenericTunnelItem *i, case RS_TURTLE_SUBTYPE_CHUNK_CRC_REQUEST: { RsTurtleChunkCrcRequestItem *item = dynamic_cast(i) ; +#ifdef SERVER_DEBUG + std::cerr << "ftServer::receiveTurtleData(): received single chunk CRC request for hash " << hash << " from peer " << virtual_peer_id << std::endl; +#endif getMultiplexer()->recvSingleChunkCRCRequest(virtual_peer_id,hash,item->chunk_number) ; } break ; @@ -1174,8 +1211,11 @@ int ftServer::tick() { bool moreToTick = false ; - moreToTick = handleIncoming() || moreToTick ; // order is important!! - moreToTick = handleCacheData() || moreToTick ; + if(handleIncoming()) + moreToTick = true; + + if(handleCacheData()) + moreToTick = true; static time_t last_law_priority_tasks_handling_time = 0 ; time_t now = time(NULL) ; @@ -1198,6 +1238,9 @@ bool ftServer::handleCacheData() std::list >::iterator it; int i=0 ; +#ifdef SERVER_DEBUG_CACHE + std::cerr << "handleCacheData() " << std::endl; +#endif mCacheStrapper->getCacheUpdates(cacheUpdates); for(it = cacheUpdates.begin(); it != cacheUpdates.end(); it++) { @@ -1214,7 +1257,7 @@ bool ftServer::handleCacheData() ci -> cacheType = (it->second).cid.type; ci -> cacheSubId = (it->second).cid.subid; -#ifdef SERVER_DEBUG +#ifdef SERVER_DEBUG_CACHE std::string out2 = "Outgoing CacheStrapper Update -> RsCacheItem:\n"; ci -> print_string(out2); std::cerr << out2 << std::endl; @@ -1234,6 +1277,9 @@ int ftServer::handleIncoming() int nhandled = 0 ; RsItem *item = NULL ; +#ifdef SERVER_DEBUG + std::cerr << "ftServer::handleIncoming() " << std::endl; +#endif while(NULL != (item = recvItem())) { @@ -1279,7 +1325,7 @@ int ftServer::handleIncoming() { RsFileTransferChunkMapItem *f = dynamic_cast(item) ; #ifdef SERVER_DEBUG - std::cerr << "ftServer::handleIncoming: received chunkmap for hash " << f->hash << ", client=" << f->is_client << ", map=" << f->compressed_map << std::endl; + std::cerr << "ftServer::handleIncoming: received chunkmap for hash " << f->hash << ", client=" << f->is_client << /*", map=" << f->compressed_map <<*/ std::endl; #endif mFtDataplex->recvChunkMap(f->PeerId(), f->hash,f->compressed_map,f->is_client) ; } @@ -1308,8 +1354,8 @@ int ftServer::handleIncoming() case RS_PKT_SUBTYPE_FT_CACHE_ITEM: { RsFileTransferCacheItem *ci = dynamic_cast(item) ; -#ifdef SERVER_DEBUG - std::cerr << "ftServer::handleIncoming: received cache item hash=" << ci->file.hash << ". from peer " << ci->PeerId() << std::ednl; +#ifdef SERVER_DEBUG_CACHE + std::cerr << "ftServer::handleIncoming: received cache item hash=" << ci->file.hash << ". from peer " << ci->PeerId() << std::endl; #endif /* these go to the CacheStrapper! */ CacheData data; @@ -1325,15 +1371,15 @@ int ftServer::handleIncoming() } break ; - case RS_PKT_SUBTYPE_FT_CACHE_REQUEST: - { - // do nothing - RsFileTransferCacheRequestItem *cr = dynamic_cast(item) ; -#ifdef SERVER_DEBUG - std::cerr << "ftServer::handleIncoming: received cache request from peer " << cr->PeerId() << std::ednl; -#endif - } - break ; +// case RS_PKT_SUBTYPE_FT_CACHE_REQUEST: +// { +// // do nothing +// RsFileTransferCacheRequestItem *cr = dynamic_cast(item) ; +//#ifdef SERVER_DEBUG_CACHE +// std::cerr << "ftServer::handleIncoming: received cache request from peer " << cr->PeerId() << std::endl; +//#endif +// } +// break ; } delete item ; diff --git a/libretroshare/src/pqi/p3netmgr.cc b/libretroshare/src/pqi/p3netmgr.cc index c76b54bdb..a56d165e8 100644 --- a/libretroshare/src/pqi/p3netmgr.cc +++ b/libretroshare/src/pqi/p3netmgr.cc @@ -74,7 +74,6 @@ const uint32_t MIN_TIME_BETWEEN_NET_RESET = 5; * #define NETMGR_DEBUG_STATEBOX 1 ***/ - pqiNetStatus::pqiNetStatus() :mLocalAddrOk(false), mExtAddrOk(false), mExtAddrStableOk(false), mUpnpOk(false), mDhtOk(false), mResetReq(false) diff --git a/libretroshare/src/pqi/pqiservice.cc b/libretroshare/src/pqi/pqiservice.cc index c9301db43..360ba900f 100644 --- a/libretroshare/src/pqi/pqiservice.cc +++ b/libretroshare/src/pqi/pqiservice.cc @@ -70,6 +70,7 @@ int p3ServiceServer::addService(pqiService *ts) it = services.find(ts -> getType()); if (it != services.end()) { + std::cerr << "p3ServiceServer::addService(): Service already added with id " << ts->getType() << "!" << std::endl; // it exists already! return -1; } diff --git a/libretroshare/src/pqi/pqistreamer.cc b/libretroshare/src/pqi/pqistreamer.cc index ca4b533ab..5221db0cc 100644 --- a/libretroshare/src/pqi/pqistreamer.cc +++ b/libretroshare/src/pqi/pqistreamer.cc @@ -45,7 +45,6 @@ const int PQISTREAM_ABS_MAX = 100000000; /* 100 MB/sec (actually per loop) */ #define DEBUG_PQISTREAMER 1 ***/ - #ifdef DEBUG_TRANSFERS #include "util/rsprint.h" #endif diff --git a/libretroshare/src/retroshare/rstypes.h b/libretroshare/src/retroshare/rstypes.h index b8a3ae4ea..5647337db 100644 --- a/libretroshare/src/retroshare/rstypes.h +++ b/libretroshare/src/retroshare/rstypes.h @@ -70,6 +70,8 @@ class Sha1CheckSum std::string toStdString() const ; bool operator==(const Sha1CheckSum& s) const ; + + friend std::ostream& operator<<(std::ostream& out,const Sha1CheckSum& sum) { return out << sum.toStdString() ; } // private: uint32_t fourbytes[5] ; }; diff --git a/libretroshare/src/serialiser/rsfiletransferitems.cc b/libretroshare/src/serialiser/rsfiletransferitems.cc index 32d87f4dd..59565fba4 100644 --- a/libretroshare/src/serialiser/rsfiletransferitems.cc +++ b/libretroshare/src/serialiser/rsfiletransferitems.cc @@ -56,7 +56,6 @@ RsFileTransferItem *RsFileTransferSerialiser::deserialise(void *data, uint32_t * switch(getRsItemSubType(rstype)) { - case RS_PKT_SUBTYPE_FT_CACHE_REQUEST: return deserialise_RsFileTransferCacheRequestItem(data, *pktsize); case RS_PKT_SUBTYPE_FT_CACHE_ITEM: return deserialise_RsFileTransferCacheItem(data, *pktsize); case RS_PKT_SUBTYPE_FT_DATA_REQUEST: return deserialise_RsFileTransferDataRequestItem(data, *pktsize); case RS_PKT_SUBTYPE_FT_DATA: return deserialise_RsFileTransferDataItem(data, *pktsize); @@ -65,6 +64,7 @@ RsFileTransferItem *RsFileTransferSerialiser::deserialise(void *data, uint32_t * case RS_PKT_SUBTYPE_FT_CHUNK_CRC_REQUEST: return deserialise_RsFileTransferSingleChunkCrcRequestItem(data,*pktsize) ; case RS_PKT_SUBTYPE_FT_CHUNK_CRC: return deserialise_RsFileTransferSingleChunkCrcItem(data,*pktsize) ; default: + std::cerr << "RsFileTransferSerialiser::deserialise(): Could not de-serialise item. SubPacket id = " << std::hex << getRsItemSubType(rstype) << " id = " << rstype << std::dec << std::endl; return NULL; } return NULL; @@ -74,17 +74,6 @@ RsFileTransferItem *RsFileTransferSerialiser::deserialise(void *data, uint32_t * /* OUTPUTS */ /**********************************************************************************************/ -std::ostream& RsFileTransferCacheRequestItem::print(std::ostream &out, uint16_t indent) -{ - printRsItemBase(out, "RsFileTransferCacheRequestItem", indent); - uint16_t int_Indent = indent + 2; - printIndent(out, int_Indent); - out << "CacheId: " << cacheType << "/" << cacheSubId << std::endl; - file.print(out, int_Indent); - printRsItemEnd(out, "RsFileTransferCacheRequestItem", indent); - return out; -} - std::ostream& RsFileTransferCacheItem::print(std::ostream &out, uint16_t indent) { printRsItemBase(out, "RsFileTransferCacheItem", indent); @@ -183,14 +172,6 @@ uint32_t RsFileTransferDataItem::serial_size() return s; } -uint32_t RsFileTransferCacheRequestItem::serial_size() -{ - uint32_t s = 8; /* header */ - s += 4; /* type/subid */ - s += file.TlvSize(); - - return s; -} uint32_t RsFileTransferChunkMapRequestItem::serial_size() { uint32_t s = 8; /* header */ @@ -245,13 +226,7 @@ void RsFileTransferDataItem::clear() { fd.TlvClear(); } -void RsFileTransferCacheRequestItem::clear() -{ - cacheType = 0; - cacheSubId = 0; - file.TlvClear(); -} - + /**********************************************************************************************/ /* SERIALISATION */ /**********************************************************************************************/ @@ -372,29 +347,6 @@ bool RsFileTransferChunkMapItem::serialise(void *data, uint32_t& pktsize) return ok; } -/* serialise the data to the buffer */ -bool RsFileTransferCacheRequestItem::serialise(void *data, uint32_t& pktsize) -{ - uint32_t tlvsize,offset=0; - bool ok = true; - - if(!serialise_header(data,pktsize,tlvsize,offset)) - return false ; - - /* add mandatory parts first */ - ok &= setRawUInt16(data, tlvsize, &offset, cacheType); - ok &= setRawUInt16(data, tlvsize, &offset, cacheSubId); - ok &= file.SetTlv(data, tlvsize, &offset); - - if (offset != tlvsize) - { - ok = false; - std::cerr << "RsFileItemSerialiser::serialiseReq() Size Error! " << std::endl; - } - - return ok; -} - /* serialise the data to the buffer */ bool RsFileTransferDataItem::serialise(void *data, uint32_t& pktsize) { @@ -482,58 +434,6 @@ bool RsFileTransferCacheItem::serialise(void *data, uint32_t& pktsize) /* DESERIALISATION */ /**********************************************************************************************/ -RsFileTransferItem *RsFileTransferSerialiser::deserialise_RsFileTransferCacheRequestItem(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_FILE_TRANSFER != getRsItemType(rstype) || RS_PKT_SUBTYPE_FT_CACHE_REQUEST != getRsItemSubType(rstype)) - { - std::cerr << "RsFileTransferSerialiser::deserialise_RsFileTransferCacheRequest(): wong subtype!" << std::endl; - return NULL; /* wrong type */ - } - - if (pktsize < rssize) /* check size */ - { - std::cerr << "RsFileTransferSerialiser::deserialise_RsFileTransferCacheRequest(): size inconsistency!" << std::endl; - return NULL; /* not enough data */ - } - - bool ok = true; - - /* ready to load */ - RsFileTransferCacheRequestItem *item = new RsFileTransferCacheRequestItem(); - item->clear(); - - /* skip the header */ - offset += 8; - - /* get mandatory parts first */ - ok &= getRawUInt16(data, rssize, &offset, &(item->cacheType)); - ok &= getRawUInt16(data, rssize, &offset, &(item->cacheSubId)); - ok &= item->file.GetTlv(data, rssize, &offset); - - if (offset != rssize) - { - /* error */ - delete item; - return NULL; - } - - if (!ok) - { - delete item; - return NULL; - } - - return item; -} - - RsFileTransferItem *RsFileTransferSerialiser::deserialise_RsFileTransferCacheItem(void *data, uint32_t pktsize) { /* get the type and size */ diff --git a/libretroshare/src/serialiser/rsfiletransferitems.h b/libretroshare/src/serialiser/rsfiletransferitems.h index 96697b1e3..1451cb959 100644 --- a/libretroshare/src/serialiser/rsfiletransferitems.h +++ b/libretroshare/src/serialiser/rsfiletransferitems.h @@ -194,26 +194,6 @@ class RsFileTransferSingleChunkCrcItem: public RsFileTransferItem Sha1CheckSum check_sum ; // CRC32 map of the file. }; -class RsFileTransferCacheRequestItem: public RsFileTransferItem -{ - public: - RsFileTransferCacheRequestItem() :RsFileTransferItem(RS_PKT_SUBTYPE_FT_CACHE_REQUEST) - { - setPriorityLevel(QOS_PRIORITY_RS_CACHE_REQUEST); - } - virtual ~RsFileTransferCacheRequestItem() {} - virtual bool serialise(void *data,uint32_t& size) ; - virtual uint32_t serial_size() ; - virtual void clear(); - std::ostream &print(std::ostream &out, uint16_t indent = 0); - - // private part - // - uint16_t cacheType; - uint16_t cacheSubId; - RsTlvFileItem file; /* file information */ -}; - class RsFileTransferCacheItem: public RsFileTransferItem { public: @@ -256,7 +236,6 @@ class RsFileTransferSerialiser: public RsSerialType virtual RsFileTransferItem *deserialise(void *data, uint32_t *size); private: - RsFileTransferItem *deserialise_RsFileTransferCacheRequestItem(void *data, uint32_t pktsize); RsFileTransferItem *deserialise_RsFileTransferCacheItem(void *data, uint32_t pktsize); RsFileTransferItem *deserialise_RsFileTransferChunkMapRequestItem(void *data, uint32_t pktsize); RsFileTransferItem *deserialise_RsFileTransferChunkMapItem(void *data, uint32_t pktsize); diff --git a/libretroshare/src/services/p3discovery2.cc b/libretroshare/src/services/p3discovery2.cc index 0fb722fd8..39981a7d1 100644 --- a/libretroshare/src/services/p3discovery2.cc +++ b/libretroshare/src/services/p3discovery2.cc @@ -36,7 +36,6 @@ RsDisc *rsDisc = NULL; * #define P3DISC_DEBUG 1 ****/ - bool populateContactInfo(const peerState &detail, RsDiscContactItem *pkt) { pkt->clear(); diff --git a/libretroshare/src/turtle/p3turtle.cc b/libretroshare/src/turtle/p3turtle.cc index abd2baa84..34c61a868 100644 --- a/libretroshare/src/turtle/p3turtle.cc +++ b/libretroshare/src/turtle/p3turtle.cc @@ -23,8 +23,6 @@ * */ -//#define P3TURTLE_DEBUG - #include #include #include @@ -1103,7 +1101,7 @@ bool p3turtle::getTunnelServiceInfo(TurtleTunnelId tunnel_id,std::string& vpid,s if(it2 == _local_tunnels.end()) { #ifdef P3TURTLE_DEBUG - std::cerr << "p3turtle: unknown tunnel id " << (void*)item->tunnelId() << std::endl ; + std::cerr << "p3turtle: unknown tunnel id " << (void*)tunnel_id << std::endl ; #endif return false; } @@ -1450,6 +1448,8 @@ void p3turtle::handleTunnelRequest(RsTurtleOpenTunnelItem *item) res_item->tunnel_id = item->partial_tunnel_id ^ generatePersonalFilePrint(item->file_hash,false) ; res_item->PeerId(item->PeerId()) ; + TurtleTunnelId t_id = res_item->tunnel_id ; + sendItem(res_item) ; // Note in the tunnels list that we have an ending tunnel here. @@ -1461,11 +1461,11 @@ void p3turtle::handleTunnelRequest(RsTurtleOpenTunnelItem *item) tt.transfered_bytes = 0 ; tt.speed_Bps = 0.0f ; - _local_tunnels[res_item->tunnel_id] = tt ; + _local_tunnels[t_id] = tt ; // We add a virtual peer for that tunnel+hash combination. // - locked_addDistantPeer(item->file_hash,res_item->tunnel_id) ; + locked_addDistantPeer(item->file_hash,t_id) ; // Store some info string about the tunnel. // @@ -1473,7 +1473,7 @@ void p3turtle::handleTunnelRequest(RsTurtleOpenTunnelItem *item) // Notify the client service that there's a new virtual peer id available as a client. // - service->addVirtualPeer(item->file_hash,_local_tunnels[res_item->tunnel_id].vpid,RsTurtleGenericTunnelItem::DIRECTION_CLIENT) ; + service->addVirtualPeer(item->file_hash,_local_tunnels[t_id].vpid,RsTurtleGenericTunnelItem::DIRECTION_CLIENT) ; // We return straight, because when something is found, there's no need to digg a tunnel further. // @@ -2093,7 +2093,7 @@ void p3turtle::dumpState() //std::cerr << ", last_req=" << (void*)it->second.last_request << ", time_stamp = " << it->second.time_stamp << "(" << now-it->second.time_stamp << " secs ago)" << std::endl ; } std::cerr << " Active outgoing file hashes: " << _outgoing_file_hashes.size() << std::endl ; - for(std::map::const_iterator it(_outgoing_file_hashes.begin());it!=_outgoing_file_hashes.end();++it) + for(std::map::const_iterator it(_outgoing_file_hashes.begin());it!=_outgoing_file_hashes.end();++it) std::cerr << " hash=0x" << it->first << std::endl ; std::cerr << " Local tunnels:" << std::endl ; From f961dc90668a55fe6420a1a8adce279caf24f2fd Mon Sep 17 00:00:00 2001 From: csoler Date: Wed, 2 Oct 2013 20:09:42 +0000 Subject: [PATCH 29/83] enabled display serialisation errors in p3service git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@6790 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/services/p3service.cc | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/libretroshare/src/services/p3service.cc b/libretroshare/src/services/p3service.cc index 9254f9f8d..eaa01ae02 100644 --- a/libretroshare/src/services/p3service.cc +++ b/libretroshare/src/services/p3service.cc @@ -155,10 +155,8 @@ int p3FastService::sendItem(RsItem *si) uint32_t size = rsSerialiser->size(si); if (!size) { -#ifdef SERV_DEBUG std::cerr << "p3Service::send() ERROR size == 0"; std::cerr << std::endl; -#endif /* can't convert! */ delete si; @@ -168,20 +166,18 @@ int p3FastService::sendItem(RsItem *si) RsRawItem *raw = new RsRawItem(si->PacketId(), size); if (!rsSerialiser->serialise(si, raw->getRawData(), &size)) { -#ifdef SERV_DEBUG std::cerr << "p3Service::send() ERROR serialise failed"; std::cerr << std::endl; -#endif + delete raw; raw = NULL; } if ((raw) && (size != raw->getRawLength())) { -#ifdef SERV_DEBUG std::cerr << "p3Service::send() ERROR serialise size mismatch"; std::cerr << std::endl; -#endif + delete raw; raw = NULL; } From 2466c01e35a51e35039b3356b6eae7157c49f988 Mon Sep 17 00:00:00 2001 From: csoler Date: Wed, 2 Oct 2013 20:28:42 +0000 Subject: [PATCH 30/83] enabled checksum code in rscertificate. Shoudl make the transfer of certs more safe git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@6791 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/pgp/rscertificate.cc | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/libretroshare/src/pgp/rscertificate.cc b/libretroshare/src/pgp/rscertificate.cc index 7af451bd5..a8cef7f7e 100644 --- a/libretroshare/src/pgp/rscertificate.cc +++ b/libretroshare/src/pgp/rscertificate.cc @@ -10,8 +10,6 @@ //#define DEBUG_RSCERTIFICATE -//#define V_06_USE_CHECKSUM - static const std::string PGP_CERTIFICATE_START ( "-----BEGIN PGP PUBLIC KEY BLOCK-----" ); static const std::string PGP_CERTIFICATE_END ( "-----END PGP PUBLIC KEY BLOCK-----" ); static const std::string EXTERNAL_IP_BEGIN_SECTION ( "--EXT--" ); @@ -93,7 +91,7 @@ std::string RsCertificate::toStdString() const addPacket( CERTIFICATE_PTAG_NAME_SECTION , (unsigned char *)location_name.c_str() ,location_name.length() , buf, p, BS ) ; addPacket( CERTIFICATE_PTAG_SSLID_SECTION , location_id.toByteArray() ,location_id.SIZE_IN_BYTES, buf, p, BS ) ; } -#ifdef V_06_USE_CHECKSUM + uint32_t computed_crc = PGPKeyManagement::compute24bitsCRC(buf,p) ; // handle endian issues. @@ -103,7 +101,7 @@ std::string RsCertificate::toStdString() const mem[2] = (computed_crc >> 16) & 0xff ; addPacket( CERTIFICATE_PTAG_CHECKSUM_SECTION,mem,3,buf,p,BS) ; -#endif + std::string out_string ; Radix64::encode((char *)buf, p, out_string) ; @@ -333,13 +331,12 @@ bool RsCertificate::initFromString(const std::string& instr,uint32_t& err_code) total_s += s ; } -#ifdef V_06_USE_CHECKSUM + if(!checksum_check_passed) { err_code = CERTIFICATE_PARSING_ERROR_MISSING_CHECKSUM ; return false ; } -#endif if(total_s != size) std::cerr << "(EE) Certificate contains trailing characters. Weird." << std::endl; From 90b4a20e5d251014cb5c18ff5312b25ce11519fb Mon Sep 17 00:00:00 2001 From: drbob Date: Thu, 3 Oct 2013 13:15:10 +0000 Subject: [PATCH 31/83] updated VoIP to use new Fast packet sending. git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@6792 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- plugins/VOIP/gui/SpeexProcessor.h | 2 +- plugins/VOIP/services/p3vors.cc | 60 ++++++++++++++++--------------- plugins/VOIP/services/p3vors.h | 3 +- 3 files changed, 34 insertions(+), 31 deletions(-) diff --git a/plugins/VOIP/gui/SpeexProcessor.h b/plugins/VOIP/gui/SpeexProcessor.h index 13171f60c..2ebb9869e 100644 --- a/plugins/VOIP/gui/SpeexProcessor.h +++ b/plugins/VOIP/gui/SpeexProcessor.h @@ -22,7 +22,7 @@ #define SAMPLING_RATE 16000 //must be the same as the speex setted mode (speex_wb_mode) #define FRAME_SIZE 320 //must be the same as the speex setted mode (speex_wb_mode) -#define ECHOTAILSIZE 25 +#define ECHOTAILSIZE 10 class SpeexBits; diff --git a/plugins/VOIP/services/p3vors.cc b/plugins/VOIP/services/p3vors.cc index 4071f8db4..b5579b803 100644 --- a/plugins/VOIP/services/p3vors.cc +++ b/plugins/VOIP/services/p3vors.cc @@ -168,7 +168,7 @@ int p3VoRS::tick() std::cerr << "ticking p3VoRS" << std::endl; #endif - processIncoming(); + //processIncoming(); sendPackets(); return 0; @@ -393,44 +393,46 @@ bool p3VoRS::getIncomingData(const std::string& peer_id,std::vectorPacketSubType()) { - bool keep = false ; + case RS_PKT_SUBTYPE_VOIP_PING: + handlePing(dynamic_cast(item)); + break; - switch(item->PacketSubType()) - { - case RS_PKT_SUBTYPE_VOIP_PING: handlePing(dynamic_cast(item)); - break; + case RS_PKT_SUBTYPE_VOIP_PONG: + handlePong(dynamic_cast(item)); + break; - case RS_PKT_SUBTYPE_VOIP_PONG: handlePong(dynamic_cast(item)); - break; + case RS_PKT_SUBTYPE_VOIP_PROTOCOL: + handleProtocol(dynamic_cast(item)) ; + break ; - case RS_PKT_SUBTYPE_VOIP_PROTOCOL: handleProtocol(dynamic_cast(item)) ; - break ; - - case RS_PKT_SUBTYPE_VOIP_DATA: handleData(dynamic_cast(item)); - keep = true ; - break; + case RS_PKT_SUBTYPE_VOIP_DATA: + handleData(dynamic_cast(item)); + keep = true ; + break; #if 0 /* THESE ARE ALL FUTURISTIC DATA TYPES */ - case RS_BANDWIDTH_PING_ITEM: handleBandwidthPing(item); - break; + case RS_BANDWIDTH_PING_ITEM: + handleBandwidthPing(item); + break; - case RS_BANDWIDTH_PONG_ITEM: handleBandwidthPong(item); - break; + case RS_BANDWIDTH_PONG_ITEM: + handleBandwidthPong(item); + break; #endif - default: - break; - } - - /* clean up */ - if(!keep) - delete item; + default: + break; } + + /* clean up */ + if(!keep) + delete item; return true ; } diff --git a/plugins/VOIP/services/p3vors.h b/plugins/VOIP/services/p3vors.h index 79bcf6179..740596da9 100644 --- a/plugins/VOIP/services/p3vors.h +++ b/plugins/VOIP/services/p3vors.h @@ -99,6 +99,7 @@ class p3VoRS: public RsPQIService, public RsVoip */ virtual int tick(); virtual int status(); + virtual bool recvItem(RsItem *item); /*************** pqiMonitor callback ***********************/ //virtual void statusChange(const std::list &plist); @@ -130,7 +131,7 @@ class p3VoRS: public RsPQIService, public RsVoip private: int sendPackets(); void sendPingMeasurements(); - int processIncoming(); + //int processIncoming(); int handlePing(RsVoipPingItem *item); int handlePong(RsVoipPongItem *item); From 420fadb5c3430db6ea106f80e262b8f9e22f6081 Mon Sep 17 00:00:00 2001 From: drbob Date: Thu, 3 Oct 2013 13:16:51 +0000 Subject: [PATCH 32/83] updated nogui for latest V0.6 changes. git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@6793 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- retroshare-nogui/src/retroshare-nogui.pro | 2 +- retroshare-nogui/src/rpc/proto/rpcprotopeers.cc | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/retroshare-nogui/src/retroshare-nogui.pro b/retroshare-nogui/src/retroshare-nogui.pro index 846f64114..0330c2602 100644 --- a/retroshare-nogui/src/retroshare-nogui.pro +++ b/retroshare-nogui/src/retroshare-nogui.pro @@ -7,7 +7,7 @@ CONFIG -= qt xml gui # if you are linking against the libretroshare with gxs. # this option links against the required sqlite library. -#CONFIG += gxs +CONFIG += gxs #CONFIG += debug debug { diff --git a/retroshare-nogui/src/rpc/proto/rpcprotopeers.cc b/retroshare-nogui/src/rpc/proto/rpcprotopeers.cc index f1cc7f10d..9e507da55 100644 --- a/retroshare-nogui/src/rpc/proto/rpcprotopeers.cc +++ b/retroshare-nogui/src/rpc/proto/rpcprotopeers.cc @@ -515,7 +515,7 @@ bool load_person_details(std::string pgp_id, rsctrl::core::Person *person, else { std::list common_friends; - rsDisc->getDiscGPGFriends(pgp_id, common_friends); + rsDisc->getDiscPgpFriends(pgp_id, common_friends); int size = common_friends.size(); if (size) { From 695e417fd5d06d77247a48206ad440783e14f4e3 Mon Sep 17 00:00:00 2001 From: csoler Date: Thu, 3 Oct 2013 21:41:34 +0000 Subject: [PATCH 33/83] changed std::wstring for std::string+utf8 in chat, and messages git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@6795 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/pqi/p3historymgr.cc | 3 +- libretroshare/src/retroshare/rsmsgs.h | 18 ++++---- libretroshare/src/rsserver/p3msgs.cc | 6 +-- libretroshare/src/rsserver/p3msgs.h | 6 +-- .../src/serialiser/rshistoryitems.cc | 4 +- libretroshare/src/serialiser/rsmsgitems.cc | 24 +++++------ libretroshare/src/serialiser/rsmsgitems.h | 40 +++++++++--------- libretroshare/src/serialiser/rstlvfileitem.cc | 20 ++++----- libretroshare/src/serialiser/rstlvtypes.h | 4 +- libretroshare/src/services/p3chatservice.cc | 31 +++++++------- libretroshare/src/services/p3chatservice.h | 6 +-- libretroshare/src/services/p3msgservice.cc | 41 +++++++++---------- libretroshare/src/services/p3msgservice.h | 2 +- retroshare-gui/src/gui/FriendsDialog.cpp | 4 +- retroshare-gui/src/gui/MessagesDialog.cpp | 4 +- .../src/gui/chat/ChatLobbyDialog.cpp | 2 +- retroshare-gui/src/gui/chat/ChatWidget.cpp | 4 +- .../src/gui/chat/PopupChatDialog.cpp | 6 +-- retroshare-gui/src/gui/feeds/ChatMsgItem.cpp | 4 +- retroshare-gui/src/gui/feeds/MsgItem.cpp | 4 +- retroshare-gui/src/gui/feeds/PeerItem.cpp | 4 +- retroshare-gui/src/gui/feeds/SecurityItem.cpp | 4 +- .../src/gui/msgs/MessageComposer.cpp | 22 +++++----- retroshare-gui/src/gui/msgs/MessageWidget.cpp | 4 +- 24 files changed, 132 insertions(+), 135 deletions(-) diff --git a/libretroshare/src/pqi/p3historymgr.cc b/libretroshare/src/pqi/p3historymgr.cc index 01d365b4b..f967297d9 100644 --- a/libretroshare/src/pqi/p3historymgr.cc +++ b/libretroshare/src/pqi/p3historymgr.cc @@ -87,7 +87,8 @@ void p3HistoryMgr::addMessage(bool incoming, const std::string &chatPeerId, cons item->saveToDisc = false; } - librs::util::ConvertUtf16ToUtf8(chatItem->message, item->message); + item->message = chatItem->message ; + //librs::util::ConvertUtf16ToUtf8(chatItem->message, item->message); std::map >::iterator mit = mMessages.find(item->chatPeerId); if (mit != mMessages.end()) { diff --git a/libretroshare/src/retroshare/rsmsgs.h b/libretroshare/src/retroshare/rsmsgs.h index e2c195984..8a8d459c3 100644 --- a/libretroshare/src/retroshare/rsmsgs.h +++ b/libretroshare/src/retroshare/rsmsgs.h @@ -98,11 +98,11 @@ class MessageInfo std::list msgcc; std::list msgbcc; - std::wstring title; - std::wstring msg; + std::string title; + std::string msg; - std::wstring attach_title; - std::wstring attach_comment; + std::string attach_title; + std::string attach_comment; std::list files; std::map encryption_keys ; // for concerned ids only the public pgp key id to encrypt the message with. int size; /* total of files */ @@ -121,7 +121,7 @@ class MsgInfoSummary uint32_t msgflags; - std::wstring title; + std::string title; int count; /* file count */ time_t ts; @@ -170,7 +170,7 @@ class ChatInfo unsigned int chatflags; uint32_t sendTime; uint32_t recvTime; - std::wstring msg; + std::string msg; }; class ChatLobbyInvite @@ -254,7 +254,7 @@ virtual void getMessageCount(unsigned int *pnInbox, unsigned int *pnInboxNew, un virtual bool decryptMessage(const std::string& mId) = 0 ; virtual bool MessageSend(MessageInfo &info) = 0; -virtual bool SystemMessage(const std::wstring &title, const std::wstring &message, uint32_t systemFlag) = 0; +virtual bool SystemMessage(const std::string &title, const std::string &message, uint32_t systemFlag) = 0; virtual bool MessageToDraft(MessageInfo &info, const std::string &msgParentId) = 0; virtual bool MessageToTrash(const std::string &mid, bool bTrash) = 0; virtual bool getMsgParentId(const std::string &msgId, std::string &msgParentId) = 0; @@ -288,8 +288,8 @@ virtual bool getDistantMessageHash(const std::string& pgp_id, std::string& hash) /****************************************/ /* Chat */ /****************************************/ -virtual bool sendPublicChat(const std::wstring& msg) = 0; -virtual bool sendPrivateChat(const std::string& id, const std::wstring& msg) = 0; +virtual bool sendPublicChat(const std::string& msg) = 0; +virtual bool sendPrivateChat(const std::string& id, const std::string& msg) = 0; virtual int getPublicChatQueueCount() = 0; virtual bool getPublicChatQueue(std::list &chats) = 0; virtual int getPrivateChatQueueCount(bool incoming) = 0; diff --git a/libretroshare/src/rsserver/p3msgs.cc b/libretroshare/src/rsserver/p3msgs.cc index 58613ac26..3346a1964 100644 --- a/libretroshare/src/rsserver/p3msgs.cc +++ b/libretroshare/src/rsserver/p3msgs.cc @@ -121,7 +121,7 @@ bool p3Msgs::getDistantMessageHash(const std::string& pgp_id,std::string& hash) return mMsgSrv->getDistantMessageHash(pgp_id,hash); } -bool p3Msgs::SystemMessage(const std::wstring &title, const std::wstring &message, uint32_t systemFlag) +bool p3Msgs::SystemMessage(const std::string &title, const std::string &message, uint32_t systemFlag) { return mMsgSrv->SystemMessage(title, message, systemFlag); } @@ -207,13 +207,13 @@ bool p3Msgs::resetMessageStandardTagTypes(MsgTagType& tags) /****************************************/ /****************************************/ -bool p3Msgs::sendPublicChat(const std::wstring& msg) +bool p3Msgs::sendPublicChat(const std::string& msg) { /* send a message to all for now */ return mChatSrv -> sendPublicChat(msg); } -bool p3Msgs::sendPrivateChat(const std::string& id, const std::wstring& msg) +bool p3Msgs::sendPrivateChat(const std::string& id, const std::string& msg) { /* send a message to peer */ return mChatSrv -> sendPrivateChat(id, msg); diff --git a/libretroshare/src/rsserver/p3msgs.h b/libretroshare/src/rsserver/p3msgs.h index c42888a4e..371992dea 100644 --- a/libretroshare/src/rsserver/p3msgs.h +++ b/libretroshare/src/rsserver/p3msgs.h @@ -59,7 +59,7 @@ class p3Msgs: public RsMsgs virtual bool MessageSend(MessageInfo &info); virtual bool decryptMessage(const std::string& mid); - virtual bool SystemMessage(const std::wstring &title, const std::wstring &message, uint32_t systemFlag); + virtual bool SystemMessage(const std::string &title, const std::string &message, uint32_t systemFlag); virtual bool MessageToDraft(MessageInfo &info, const std::string &msgParentId); virtual bool MessageToTrash(const std::string &mid, bool bTrash); virtual bool MessageDelete(const std::string &mid); @@ -120,13 +120,13 @@ class p3Msgs: public RsMsgs /*! * public chat sent to all peers */ - virtual bool sendPublicChat(const std::wstring& msg); + virtual bool sendPublicChat(const std::string& msg); /*! * chat is sent to specifc peer * @param id peer to send chat msg to */ - virtual bool sendPrivateChat(const std::string& id, const std::wstring& msg); + virtual bool sendPrivateChat(const std::string& id, const std::string& msg); /*! * returns the count of messages in public or private queue diff --git a/libretroshare/src/serialiser/rshistoryitems.cc b/libretroshare/src/serialiser/rshistoryitems.cc index 0cb270ad3..023fdc81c 100644 --- a/libretroshare/src/serialiser/rshistoryitems.cc +++ b/libretroshare/src/serialiser/rshistoryitems.cc @@ -147,7 +147,7 @@ bool RsHistorySerialiser::serialiseHistoryMsgItem(RsHistoryMsgItem* item, void* ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_NAME, item->peerName); ok &= setRawUInt32(data, tlvsize, &offset, item->sendTime); ok &= setRawUInt32(data, tlvsize, &offset, item->recvTime); - ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_WSTR_MSG, item->message); + ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_MSG, item->message); if (offset != tlvsize) { @@ -202,7 +202,7 @@ RsHistoryMsgItem *RsHistorySerialiser::deserialiseHistoryMsgItem(void *data, uin ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_NAME, item->peerName); ok &= getRawUInt32(data, rssize, &offset, &(item->sendTime)); ok &= getRawUInt32(data, rssize, &offset, &(item->recvTime)); - ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_WSTR_MSG, item->message); + ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_MSG, item->message); if (offset != rssize) { diff --git a/libretroshare/src/serialiser/rsmsgitems.cc b/libretroshare/src/serialiser/rsmsgitems.cc index 5e0c5131b..706ed8f8f 100644 --- a/libretroshare/src/serialiser/rsmsgitems.cc +++ b/libretroshare/src/serialiser/rsmsgitems.cc @@ -303,7 +303,7 @@ uint32_t RsChatMsgItem::serial_size() uint32_t s = 8; /* header */ s += 4; /* chatFlags */ s += 4; /* sendTime */ - s += GetTlvWideStringSize(message); + s += GetTlvStringSize(message); return s; } @@ -418,7 +418,7 @@ uint32_t RsPrivateChatMsgConfigItem::serial_size() s += 4; /* chatFlags */ s += 4; /* configFlags */ s += 4; /* sendTime */ - s += GetTlvWideStringSize(message); + s += GetTlvStringSize(message); s += 4; /* recvTime */ return s; @@ -498,7 +498,7 @@ bool RsChatMsgItem::serialise(void *data, uint32_t& pktsize) /* add mandatory parts first */ ok &= setRawUInt32(data, tlvsize, &offset, chatFlags); ok &= setRawUInt32(data, tlvsize, &offset, sendTime); - ok &= SetTlvWideString(data, tlvsize, &offset, TLV_TYPE_WSTR_MSG, message); + ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_MSG, message); #ifdef CHAT_DEBUG std::cerr << "Serialized the following message:" << std::endl; std::cerr << "========== BEGIN MESSAGE =========" << std::endl; @@ -806,7 +806,7 @@ bool RsPrivateChatMsgConfigItem::serialise(void *data, uint32_t& pktsize) ok &= setRawUInt32(data, tlvsize, &offset, chatFlags); ok &= setRawUInt32(data, tlvsize, &offset, configFlags); ok &= setRawUInt32(data, tlvsize, &offset, sendTime); - ok &= SetTlvWideString(data, tlvsize, &offset, TLV_TYPE_WSTR_MSG, message); + ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_MSG, message); ok &= setRawUInt32(data, tlvsize, &offset, recvTime); if (offset != tlvsize) @@ -989,7 +989,7 @@ RsChatMsgItem::RsChatMsgItem(void *data,uint32_t /*size*/,uint8_t subtype) /* get mandatory parts first */ ok &= getRawUInt32(data, rssize, &offset, &chatFlags); ok &= getRawUInt32(data, rssize, &offset, &sendTime); - ok &= GetTlvWideString(data, rssize, &offset, TLV_TYPE_WSTR_MSG, message); + ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_MSG, message); #ifdef CHAT_DEBUG std::cerr << "Building new chat msg item." << std::endl ; @@ -1227,7 +1227,7 @@ RsPrivateChatMsgConfigItem::RsPrivateChatMsgConfigItem(void *data,uint32_t /*siz ok &= getRawUInt32(data, rssize, &offset, &chatFlags); ok &= getRawUInt32(data, rssize, &offset, &configFlags); ok &= getRawUInt32(data, rssize, &offset, &sendTime); - ok &= GetTlvWideString(data, rssize, &offset, TLV_TYPE_WSTR_MSG, message); + ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_MSG, message); ok &= getRawUInt32(data, rssize, &offset, &recvTime); #ifdef CHAT_DEBUG @@ -1500,8 +1500,8 @@ uint32_t RsMsgItem::serial_size(bool m_bConfiguration) s += 4; /* sendTime */ s += 4; /* recvTime */ - s += GetTlvWideStringSize(subject); - s += GetTlvWideStringSize(message); + s += GetTlvStringSize(subject); + s += GetTlvStringSize(message); s += msgto.TlvSize(); s += msgcc.TlvSize(); @@ -1544,8 +1544,8 @@ bool RsMsgItem::serialise(void *data, uint32_t& pktsize,bool config) ok &= setRawUInt32(data, tlvsize, &offset, sendTime); ok &= setRawUInt32(data, tlvsize, &offset, recvTime); - ok &= SetTlvWideString(data,tlvsize,&offset,TLV_TYPE_WSTR_SUBJECT,subject); - ok &= SetTlvWideString(data, tlvsize, &offset, TLV_TYPE_WSTR_MSG, message); + ok &= SetTlvString(data,tlvsize,&offset,TLV_TYPE_STR_SUBJECT,subject); + ok &= SetTlvString(data, tlvsize, &offset, TLV_TYPE_STR_MSG, message); ok &= msgto.SetTlv(data, tlvsize, &offset); ok &= msgcc.SetTlv(data, tlvsize, &offset); @@ -1601,8 +1601,8 @@ RsMsgItem *RsMsgSerialiser::deserialiseMsgItem(void *data, uint32_t *pktsize) ok &= getRawUInt32(data, rssize, &offset, &(item->sendTime)); ok &= getRawUInt32(data, rssize, &offset, &(item->recvTime)); - ok &= GetTlvWideString(data,rssize,&offset,TLV_TYPE_WSTR_SUBJECT,item->subject); - ok &= GetTlvWideString(data, rssize, &offset, TLV_TYPE_WSTR_MSG, item->message); + ok &= GetTlvString(data,rssize,&offset,TLV_TYPE_STR_SUBJECT,item->subject); + ok &= GetTlvString(data, rssize, &offset, TLV_TYPE_STR_MSG, item->message); ok &= item->msgto.GetTlv(data, rssize, &offset); ok &= item->msgcc.GetTlv(data, rssize, &offset); ok &= item->msgbcc.GetTlv(data, rssize, &offset); diff --git a/libretroshare/src/serialiser/rsmsgitems.h b/libretroshare/src/serialiser/rsmsgitems.h index 7c9704c1f..0ab2c7519 100644 --- a/libretroshare/src/serialiser/rsmsgitems.h +++ b/libretroshare/src/serialiser/rsmsgitems.h @@ -50,24 +50,24 @@ const uint32_t RS_CHAT_FLAG_ACK_DISTANT_CONNECTION = 0x0800; const uint32_t RS_CHATMSG_CONFIGFLAG_INCOMING = 0x0001; -const uint8_t RS_PKT_SUBTYPE_CHAT_AVATAR = 0x03 ; -const uint8_t RS_PKT_SUBTYPE_CHAT_STATUS = 0x04 ; -const uint8_t RS_PKT_SUBTYPE_PRIVATECHATMSG_CONFIG = 0x05 ; -const uint8_t RS_PKT_SUBTYPE_CHAT_LOBBY_MSG_DEPRECATED= 0x06 ; // don't use ! Deprecated -const uint8_t RS_PKT_SUBTYPE_CHAT_LOBBY_INVITE_DEPREC = 0x07 ; // don't use ! Deprecated -const uint8_t RS_PKT_SUBTYPE_CHAT_LOBBY_ACCEPT = 0x08 ; -const uint8_t RS_PKT_SUBTYPE_CHAT_LOBBY_CHALLENGE = 0x09 ; -const uint8_t RS_PKT_SUBTYPE_CHAT_LOBBY_UNSUBSCRIBE = 0x0A ; -const uint8_t RS_PKT_SUBTYPE_CHAT_LOBBY_EVENT_DEPREC = 0x0B ; // don't use ! Deprecated -const uint8_t RS_PKT_SUBTYPE_CHAT_LOBBY_MSG = 0x0C ; -const uint8_t RS_PKT_SUBTYPE_CHAT_LOBBY_LIST_REQUEST = 0x0D ; +const uint8_t RS_PKT_SUBTYPE_CHAT_AVATAR = 0x03 ; +const uint8_t RS_PKT_SUBTYPE_CHAT_STATUS = 0x04 ; +const uint8_t RS_PKT_SUBTYPE_PRIVATECHATMSG_CONFIG = 0x05 ; +const uint8_t RS_PKT_SUBTYPE_CHAT_LOBBY_MSG_DEPRECATED = 0x06 ; // don't use ! Deprecated +const uint8_t RS_PKT_SUBTYPE_CHAT_LOBBY_INVITE_DEPREC = 0x07 ; // don't use ! Deprecated +const uint8_t RS_PKT_SUBTYPE_CHAT_LOBBY_ACCEPT = 0x08 ; +const uint8_t RS_PKT_SUBTYPE_CHAT_LOBBY_CHALLENGE = 0x09 ; +const uint8_t RS_PKT_SUBTYPE_CHAT_LOBBY_UNSUBSCRIBE = 0x0A ; +const uint8_t RS_PKT_SUBTYPE_CHAT_LOBBY_EVENT_DEPREC = 0x0B ; // don't use ! Deprecated +const uint8_t RS_PKT_SUBTYPE_CHAT_LOBBY_MSG = 0x0C ; +const uint8_t RS_PKT_SUBTYPE_CHAT_LOBBY_LIST_REQUEST = 0x0D ; const uint8_t RS_PKT_SUBTYPE_CHAT_LOBBY_LIST_deprecated = 0x0E ; // to be removed -const uint8_t RS_PKT_SUBTYPE_CHAT_LOBBY_INVITE = 0x0F ; -const uint8_t RS_PKT_SUBTYPE_CHAT_LOBBY_EVENT = 0x10 ; +const uint8_t RS_PKT_SUBTYPE_CHAT_LOBBY_INVITE = 0x0F ; +const uint8_t RS_PKT_SUBTYPE_CHAT_LOBBY_EVENT = 0x10 ; const uint8_t RS_PKT_SUBTYPE_CHAT_LOBBY_LIST_deprecated2 = 0x11 ; // to be removed (deprecated since 02 Dec. 2012) -const uint8_t RS_PKT_SUBTYPE_CHAT_LOBBY_LIST = 0x12 ; -const uint8_t RS_PKT_SUBTYPE_DISTANT_INVITE_CONFIG = 0x13 ; -const uint8_t RS_PKT_SUBTYPE_CHAT_LOBBY_CONFIG = 0x15 ; +const uint8_t RS_PKT_SUBTYPE_CHAT_LOBBY_LIST = 0x12 ; +const uint8_t RS_PKT_SUBTYPE_DISTANT_INVITE_CONFIG = 0x13 ; +const uint8_t RS_PKT_SUBTYPE_CHAT_LOBBY_CONFIG = 0x15 ; // for defining tags themselves and msg tags const uint8_t RS_PKT_SUBTYPE_MSG_TAG_TYPE = 0x03; @@ -117,7 +117,7 @@ class RsChatMsgItem: public RsChatItem uint32_t chatFlags; uint32_t sendTime; - std::wstring message; + std::string message; /* not serialised */ uint32_t recvTime; }; @@ -316,7 +316,7 @@ class RsPrivateChatMsgConfigItem: public RsChatItem uint32_t chatFlags; uint32_t configFlags; uint32_t sendTime; - std::wstring message; + std::string message; uint32_t recvTime; }; class RsPrivateChatDistantInviteConfigItem: public RsChatItem @@ -475,8 +475,8 @@ class RsMsgItem: public RsMessageItem uint32_t sendTime; uint32_t recvTime; - std::wstring subject; - std::wstring message; + std::string subject; + std::string message; RsTlvPeerIdSet msgto; RsTlvPeerIdSet msgcc; diff --git a/libretroshare/src/serialiser/rstlvfileitem.cc b/libretroshare/src/serialiser/rstlvfileitem.cc index 644bdb856..939830e57 100644 --- a/libretroshare/src/serialiser/rstlvfileitem.cc +++ b/libretroshare/src/serialiser/rstlvfileitem.cc @@ -417,9 +417,9 @@ uint32_t RsTlvFileSet::TlvSize() /* now add comment and title length of this tlv object */ if (title.length() > 0) - s += GetTlvWideStringSize(title); + s += GetTlvStringSize(title); if (comment.length() > 0) - s += GetTlvWideStringSize(comment); + s += GetTlvStringSize(comment); return s; } @@ -454,9 +454,9 @@ bool RsTlvFileSet::SetTlv(void *data, uint32_t size, uint32_t *offset) /* se /* now optional ones */ if (title.length() > 0) - ok &= SetTlvWideString(data, tlvend, offset, TLV_TYPE_WSTR_TITLE, title); + ok &= SetTlvString(data, tlvend, offset, TLV_TYPE_STR_TITLE, title); if (comment.length() > 0) - ok &= SetTlvWideString(data, tlvend, offset, TLV_TYPE_WSTR_COMMENT, comment); + ok &= SetTlvString(data, tlvend, offset, TLV_TYPE_STR_COMMENT, comment); return ok; @@ -500,15 +500,15 @@ bool RsTlvFileSet::GetTlv(void *data, uint32_t size, uint32_t *offset) items.push_back(newitem); } } - else if (tlvsubtype == TLV_TYPE_WSTR_TITLE) + else if (tlvsubtype == TLV_TYPE_STR_TITLE) { - ok &= GetTlvWideString(data, tlvend, offset, - TLV_TYPE_WSTR_TITLE, title); + ok &= GetTlvString(data, tlvend, offset, + TLV_TYPE_STR_TITLE, title); } - else if (tlvsubtype == TLV_TYPE_WSTR_COMMENT) + else if (tlvsubtype == TLV_TYPE_STR_COMMENT) { - ok &= GetTlvWideString(data, tlvend, offset, - TLV_TYPE_WSTR_COMMENT, comment); + ok &= GetTlvString(data, tlvend, offset, + TLV_TYPE_STR_COMMENT, comment); } else { diff --git a/libretroshare/src/serialiser/rstlvtypes.h b/libretroshare/src/serialiser/rstlvtypes.h index 4fd45bd4a..7b6f582b9 100644 --- a/libretroshare/src/serialiser/rstlvtypes.h +++ b/libretroshare/src/serialiser/rstlvtypes.h @@ -187,8 +187,8 @@ virtual bool GetTlv(void *data, uint32_t size, uint32_t *offset); /* deseria virtual std::ostream &print(std::ostream &out, uint16_t indent); std::list items; /// Mandatory - std::wstring title; /// Optional: title of file set - std::wstring comment; /// Optional: comments for file + std::string title; /// Optional: title of file set + std::string comment; /// Optional: comments for file }; diff --git a/libretroshare/src/services/p3chatservice.cc b/libretroshare/src/services/p3chatservice.cc index be71584f3..ef409e266 100644 --- a/libretroshare/src/services/p3chatservice.cc +++ b/libretroshare/src/services/p3chatservice.cc @@ -141,7 +141,7 @@ int p3ChatService::status() /***************** Chat Stuff **********************/ -int p3ChatService::sendPublicChat(const std::wstring &msg) +int p3ChatService::sendPublicChat(const std::string &msg) { /* go through all the peers */ @@ -460,7 +460,7 @@ bool p3ChatService::isOnline(const std::string& id) return true ; } -bool p3ChatService::sendPrivateChat(const std::string &id, const std::wstring &msg) +bool p3ChatService::sendPrivateChat(const std::string &id, const std::string &msg) { // look into ID. Is it a peer, or a chat lobby? @@ -643,7 +643,7 @@ bool p3ChatService::locked_checkAndRebuildPartialMessage(RsChatLobbyMsgItem *ci) #ifdef CHAT_DEBUG std::cerr << " Message is complete ! Re-forming it and returning true." << std::endl; #endif - std::wstring msg ; + std::string msg ; uint32_t flags = 0 ; for(uint32_t i=0;isecond.size();++i) @@ -998,20 +998,18 @@ bool p3ChatService::checkForMessageSecurity(RsChatMsgItem *ci) // https://en.wikipedia.org/wiki/Billion_laughs // This should be done for all incoming HTML messages (also in forums // etc.) so this should be a function in some other file. - wchar_t tmp[10]; - mbstowcs(tmp, "message.find(tmp) != std::string::npos) + if (ci->message.find("message << std::endl; - std::wcout << "**********" << std::endl; - std::wcout << "********** entity attack by " << ci->PeerId().c_str() << std::endl; - std::wcout << "**********" << std::endl; + std::cout << "handleRecvChatMsgItem: " << ci->message << std::endl; + std::cout << "**********" << std::endl; + std::cout << "********** entity attack by " << ci->PeerId().c_str() << std::endl; + std::cout << "**********" << std::endl; - ci->message = L"**** This message has been removed because it breaks security rules.****" ; + ci->message = "**** This message has been removed because it breaks security rules.****" ; return false; } // For a future whitelist: @@ -1146,8 +1144,9 @@ bool p3ChatService::handleRecvChatMsgItem(RsChatMsgItem *ci) ci->chatFlags |= RS_CHAT_FLAG_AVATAR_AVAILABLE ; } - std::string message; - librs::util::ConvertUtf16ToUtf8(ci->message, message); + std::string message = ci->message; + //librs::util::ConvertUtf16ToUtf8(ci->message, message); + if (ci->chatFlags & RS_CHAT_FLAG_PRIVATE) { /* notify private chat message */ getPqiNotify()->AddPopupMessage(popupChatFlag, ci->PeerId(), name, message); @@ -1691,7 +1690,7 @@ void p3ChatService::sendAvatarJpegData(const std::string& peer_id) RsChatAvatarItem *ci = makeOwnAvatarItem(); ci->PeerId(peer_id); - // take avatar, and embed it into a std::wstring. + // take avatar, and embed it into a std::string. // #ifdef CHAT_DEBUG std::cerr << "p3ChatService::sending avatar image to peer" << peer_id << ", image size = " << ci->image_size << std::endl ; @@ -2142,7 +2141,7 @@ void p3ChatService::locked_initLobbyBouncableObject(const ChatLobbyId& lobby_id, item.nick = lobby.nick_name ; } -bool p3ChatService::sendLobbyChat(const std::string &id, const std::wstring& msg, const ChatLobbyId& lobby_id) +bool p3ChatService::sendLobbyChat(const std::string &id, const std::string& msg, const ChatLobbyId& lobby_id) { #ifdef CHAT_DEBUG std::cerr << "Sending chat lobby message to lobby " << std::hex << lobby_id << std::dec << std::endl; @@ -2461,7 +2460,7 @@ bool p3ChatService::acceptLobbyInvite(const ChatLobbyId& lobby_id) item->lobby_id = entry.lobby_id ; item->msg_id = 0 ; item->nick = "Lobby management" ; - item->message = std::wstring(L"Welcome to chat lobby") ; + item->message = std::string("Welcome to chat lobby") ; item->PeerId(entry.virtual_peer_id) ; item->chatFlags = RS_CHAT_FLAG_PRIVATE | RS_CHAT_FLAG_LOBBY ; diff --git a/libretroshare/src/services/p3chatservice.h b/libretroshare/src/services/p3chatservice.h index d48f157a8..010ba1b8d 100644 --- a/libretroshare/src/services/p3chatservice.h +++ b/libretroshare/src/services/p3chatservice.h @@ -70,14 +70,14 @@ class p3ChatService: public p3Service, public p3Config, public pqiMonitor, publi /*! * public chat sent to all peers */ - int sendPublicChat(const std::wstring &msg); + int sendPublicChat(const std::string &msg); /********* RsMsgs ***********/ /*! * chat is sent to specifc peer * @param id peer to send chat msg to */ - bool sendPrivateChat(const std::string &id, const std::wstring &msg); + bool sendPrivateChat(const std::string &id, const std::string &msg); /*! * can be used to send 'immediate' status msgs, these status updates are meant for immediate use by peer (not saved by rs) @@ -244,7 +244,7 @@ class p3ChatService: public p3Service, public p3Config, public pqiMonitor, publi /// receive and handle chat lobby item bool recvLobbyChat(RsChatLobbyMsgItem*,const std::string& src_peer_id) ; - bool sendLobbyChat(const std::string &id, const std::wstring&, const ChatLobbyId&) ; + bool sendLobbyChat(const std::string &id, const std::string&, const ChatLobbyId&) ; void handleRecvLobbyInvite(RsChatLobbyInviteItem*) ; void checkAndRedirectMsgToLobby(RsChatMsgItem*) ; void handleConnectionChallenge(RsChatLobbyConnectChallengeItem *item) ; diff --git a/libretroshare/src/services/p3msgservice.cc b/libretroshare/src/services/p3msgservice.cc index a3ae97627..e66971a78 100644 --- a/libretroshare/src/services/p3msgservice.cc +++ b/libretroshare/src/services/p3msgservice.cc @@ -138,14 +138,10 @@ void p3MsgService::processMsg(RsMsgItem *mi, bool incoming) pqiNotify *notify = getPqiNotify(); if (notify) { - std::string title, message; - librs::util::ConvertUtf16ToUtf8(mi->subject, title); - librs::util::ConvertUtf16ToUtf8(mi->message, message); - if(mi->msgFlags & RS_MSG_FLAGS_ENCRYPTED) - notify->AddPopupMessage(RS_POPUP_ENCRYPTED_MSG, mi->PeerId(), title, message); + notify->AddPopupMessage(RS_POPUP_ENCRYPTED_MSG, mi->PeerId(), mi->subject, mi->message); else - notify->AddPopupMessage(RS_POPUP_MSG, mi->PeerId(), title, message); + notify->AddPopupMessage(RS_POPUP_MSG, mi->PeerId(), mi->subject, mi->message); std::string out; rs_sprintf(out, "%lu", mi->msgId); @@ -669,12 +665,12 @@ void p3MsgService::loadWelcomeMsg() msg -> recvTime = time(NULL); msg -> msgFlags = RS_MSG_FLAGS_NEW; - msg -> subject = L"Welcome to Retroshare"; + msg -> subject = "Welcome to Retroshare"; - msg -> message = L"Send and receive messages with your friends...\n"; - msg -> message += L"These can hold recommendations from your local shared files.\n\n"; - msg -> message += L"Add recommendations through the Local Files Dialog.\n\n"; - msg -> message += L"Enjoy."; + msg -> message = "Send and receive messages with your friends...\n"; + msg -> message += "These can hold recommendations from your local shared files.\n\n"; + msg -> message += "Add recommendations through the Local Files Dialog.\n\n"; + msg -> message += "Enjoy."; msg -> msgId = getNewUniqueMsgId(); @@ -1072,7 +1068,7 @@ bool p3MsgService::MessageSend(MessageInfo &info) return true; } -bool p3MsgService::SystemMessage(const std::wstring &title, const std::wstring &message, uint32_t systemFlag) +bool p3MsgService::SystemMessage(const std::string &title, const std::string &message, uint32_t systemFlag) { if ((systemFlag & RS_MSG_SYSTEM) == 0) { /* no flag specified */ @@ -1829,22 +1825,21 @@ bool p3MsgService::encryptMessage(const std::string& pgp_id,RsMsgItem *item) #endif // Now turn the binary encrypted chunk into a readable radix string. // +#ifdef DEBUG_DISTANT_MSG + std::cerr << " Converting to radix64" << std::endl; +#endif std::string armoured_data ; Radix64::encode((char *)encrypted_data,encrypted_size,armoured_data) ; delete[] encrypted_data ; - std::wstring encrypted_msg ; - -#ifdef DEBUG_DISTANT_MSG - std::cerr << " Converting to radix64" << std::endl; -#endif - if(!librs::util::ConvertUtf8ToUtf16(armoured_data,encrypted_msg)) - return false; + //std::wstring encrypted_msg = armoured_data; + //if(!librs::util::ConvertUtf8ToUtf16(armoured_data,encrypted_msg)) + // return false; // wipe the item clean and replace the message by the encrypted data. - item->message = encrypted_msg ; - item->subject = L"" ; + item->message = armoured_data ; + item->subject = "" ; item->msgcc.ids.clear() ; item->msgbcc.ids.clear() ; item->msgto.ids.clear() ; @@ -1870,11 +1865,13 @@ bool p3MsgService::decryptMessage(const std::string& mId) std::map::iterator mit = imsg.find(msgId); - if(mit == imsg.end() || !librs::util::ConvertUtf16ToUtf8(mit->second->message,encrypted_string)) + if(mit == imsg.end()) { std::cerr << "Can't find this message in msg list. Id=" << mId << std::endl; return false; } + + encrypted_string = mit->second->message ; } char *encrypted_data ; diff --git a/libretroshare/src/services/p3msgservice.h b/libretroshare/src/services/p3msgservice.h index 81ebbae2d..6e1ac98f8 100644 --- a/libretroshare/src/services/p3msgservice.h +++ b/libretroshare/src/services/p3msgservice.h @@ -66,7 +66,7 @@ bool getMsgParentId(const std::string &msgId, std::string &msgParentId); bool setMsgParentId(uint32_t msgId, uint32_t msgParentId); bool MessageSend(MessageInfo &info); -bool SystemMessage(const std::wstring &title, const std::wstring &message, uint32_t systemFlag); +bool SystemMessage(const std::string &title, const std::string &message, uint32_t systemFlag); bool MessageToDraft(MessageInfo &info, const std::string &msgParentId); bool MessageToTrash(const std::string &mid, bool bTrash); diff --git a/retroshare-gui/src/gui/FriendsDialog.cpp b/retroshare-gui/src/gui/FriendsDialog.cpp index 9ea095d12..0ded05914 100644 --- a/retroshare-gui/src/gui/FriendsDialog.cpp +++ b/retroshare-gui/src/gui/FriendsDialog.cpp @@ -500,7 +500,7 @@ void FriendsDialog::insertChat() QDateTime sendTime = QDateTime::fromTime_t(it->sendTime); QDateTime recvTime = QDateTime::fromTime_t(it->recvTime); QString name = QString::fromUtf8(rsPeers->getPeerName(it->rsid).c_str()); - QString msg = QString::fromStdWString(it->msg); + QString msg = QString::fromUtf8(it->msg.c_str()); #ifdef FRIENDS_DEBUG std::cerr << "FriendsDialog::insertChat(): " << msg.toStdString() << std::endl; @@ -571,7 +571,7 @@ void FriendsDialog::sendMsg() QString text; RsHtml::optimizeHtml(lineWidget, text); - std::wstring message = text.toStdWString(); + std::string message = text.toUtf8().constData(); #ifdef FRIENDS_DEBUG std::string msg(message.begin(), message.end()); diff --git a/retroshare-gui/src/gui/MessagesDialog.cpp b/retroshare-gui/src/gui/MessagesDialog.cpp index 63a7fa38c..9c37d0e1b 100644 --- a/retroshare-gui/src/gui/MessagesDialog.cpp +++ b/retroshare-gui/src/gui/MessagesDialog.cpp @@ -1138,7 +1138,7 @@ void MessagesDialog::insertMessages() if(it->msgflags & RS_MSG_ENCRYPTED) text = tr("Encrypted message. Right-click to decrypt it.") ; else - text = QString::fromStdWString(it->title); + text = QString::fromStdString(it->title); item[COLUMN_SUBJECT]->setText(text); item[COLUMN_SUBJECT]->setData(text + dateString, ROLE_SORT); @@ -1206,7 +1206,7 @@ void MessagesDialog::insertMessages() if (gotInfo || rsMsgs->getMessage(it->msgId, msgInfo)) { gotInfo = true; QTextDocument doc; - doc.setHtml(QString::fromStdWString(msgInfo.msg)); + doc.setHtml(QString::fromStdString(msgInfo.msg)); item[COLUMN_CONTENT]->setText(doc.toPlainText().replace(QString("\n"), QString(" "))); } else { std::cerr << "MessagesDialog::insertMsgTxtAndFiles() Couldn't find Msg" << std::endl; diff --git a/retroshare-gui/src/gui/chat/ChatLobbyDialog.cpp b/retroshare-gui/src/gui/chat/ChatLobbyDialog.cpp index 8a872f455..f20837476 100644 --- a/retroshare-gui/src/gui/chat/ChatLobbyDialog.cpp +++ b/retroshare-gui/src/gui/chat/ChatLobbyDialog.cpp @@ -284,7 +284,7 @@ void ChatLobbyDialog::addIncomingChatMsg(const ChatInfo& info) { QDateTime sendTime = QDateTime::fromTime_t(info.sendTime); QDateTime recvTime = QDateTime::fromTime_t(info.recvTime); - QString message = QString::fromStdWString(info.msg); + QString message = QString::fromUtf8(info.msg.c_str()); QString name = QString::fromUtf8(info.peer_nickname.c_str()); QString rsid = QString::fromUtf8(info.rsid.c_str()); diff --git a/retroshare-gui/src/gui/chat/ChatWidget.cpp b/retroshare-gui/src/gui/chat/ChatWidget.cpp index 3fff5a757..ce21026e3 100644 --- a/retroshare-gui/src/gui/chat/ChatWidget.cpp +++ b/retroshare-gui/src/gui/chat/ChatWidget.cpp @@ -711,7 +711,7 @@ void ChatWidget::sendChat() QString text; RsHtml::optimizeHtml(chatWidget, text); - std::wstring msg = text.toStdWString(); + std::string msg = text.toUtf8().constData(); if (msg.empty()) { // nothing to send @@ -724,7 +724,7 @@ void ChatWidget::sendChat() if (rsMsgs->sendPrivateChat(peerId, msg)) { QDateTime currentTime = QDateTime::currentDateTime(); - addChatMsg(false, name, currentTime, currentTime, QString::fromStdWString(msg), TYPE_NORMAL); + addChatMsg(false, name, currentTime, currentTime, text, TYPE_NORMAL); } chatWidget->clear(); diff --git a/retroshare-gui/src/gui/chat/PopupChatDialog.cpp b/retroshare-gui/src/gui/chat/PopupChatDialog.cpp index 668f9c158..4066ef5cc 100644 --- a/retroshare-gui/src/gui/chat/PopupChatDialog.cpp +++ b/retroshare-gui/src/gui/chat/PopupChatDialog.cpp @@ -134,7 +134,7 @@ void PopupChatDialog::addIncomingChatMsg(const ChatInfo& info) if (cw) { QDateTime sendTime = QDateTime::fromTime_t(info.sendTime); QDateTime recvTime = QDateTime::fromTime_t(info.recvTime); - QString message = QString::fromStdWString(info.msg); + QString message = QString::fromUtf8(info.msg.c_str()); QString name = getPeerName(info.rsid) ; cw->addChatMsg(true, name, sendTime, recvTime, message, ChatWidget::TYPE_NORMAL); @@ -176,7 +176,7 @@ void PopupChatDialog::onChatChanged(int list, int type) QDateTime sendTime = QDateTime::fromTime_t(it->sendTime); QDateTime recvTime = QDateTime::fromTime_t(it->recvTime); - QString message = QString::fromStdWString(it->msg); + QString message = QString::fromUtf8(it->msg.c_str()); ui.chatWidget->addChatMsg(false, name, sendTime, recvTime, message, ChatWidget::TYPE_OFFLINE); } @@ -195,7 +195,7 @@ void PopupChatDialog::onChatChanged(int list, int type) for(it = savedOfflineChat.begin(); it != savedOfflineChat.end(); ++it) { QDateTime sendTime = QDateTime::fromTime_t(it->sendTime); QDateTime recvTime = QDateTime::fromTime_t(it->recvTime); - QString message = QString::fromStdWString(it->msg); + QString message = QString::fromUtf8(it->msg.c_str()); ui.chatWidget->addChatMsg(false, name, sendTime, recvTime, message, ChatWidget::TYPE_NORMAL); } diff --git a/retroshare-gui/src/gui/feeds/ChatMsgItem.cpp b/retroshare-gui/src/gui/feeds/ChatMsgItem.cpp index cbbe24674..98d075b32 100644 --- a/retroshare-gui/src/gui/feeds/ChatMsgItem.cpp +++ b/retroshare-gui/src/gui/feeds/ChatMsgItem.cpp @@ -243,8 +243,8 @@ void ChatMsgItem::sendMessage() /* construct a message */ MessageInfo mi; - mi.title = tr("Quick Message").toStdWString(); - mi.msg = quickmsgText->toHtml().toStdWString(); + mi.title = tr("Quick Message").toUtf8().constData(); + mi.msg = quickmsgText->toHtml().toUtf8().constData(); mi.msgto.push_back(mPeerId); rsMsgs->MessageSend(mi); diff --git a/retroshare-gui/src/gui/feeds/MsgItem.cpp b/retroshare-gui/src/gui/feeds/MsgItem.cpp index 096403c87..0e23812b6 100644 --- a/retroshare-gui/src/gui/feeds/MsgItem.cpp +++ b/retroshare-gui/src/gui/feeds/MsgItem.cpp @@ -127,12 +127,12 @@ void MsgItem::updateItemStatic() title += srcName; titleLabel->setText(title); - subjectLabel->setText(QString::fromStdWString(mi.title)); + subjectLabel->setText(QString::fromUtf8(mi.title.c_str())); if(mi.msgflags & RS_MSG_ENCRYPTED) msgLabel->setText(RsHtml().formatText(NULL, tr("[Encrypted message]"), RSHTML_FORMATTEXT_EMBED_SMILEYS | RSHTML_FORMATTEXT_EMBED_LINKS)); else - msgLabel->setText(RsHtml().formatText(NULL, QString::fromStdWString(mi.msg), RSHTML_FORMATTEXT_EMBED_SMILEYS | RSHTML_FORMATTEXT_EMBED_LINKS)); + msgLabel->setText(RsHtml().formatText(NULL, QString::fromUtf8(mi.msg.c_str()), RSHTML_FORMATTEXT_EMBED_SMILEYS | RSHTML_FORMATTEXT_EMBED_LINKS)); std::list::iterator it; for(it = mi.files.begin(); it != mi.files.end(); it++) diff --git a/retroshare-gui/src/gui/feeds/PeerItem.cpp b/retroshare-gui/src/gui/feeds/PeerItem.cpp index 5df812e15..feadc489a 100644 --- a/retroshare-gui/src/gui/feeds/PeerItem.cpp +++ b/retroshare-gui/src/gui/feeds/PeerItem.cpp @@ -312,8 +312,8 @@ void PeerItem::sendMessage() /* construct a message */ MessageInfo mi; - mi.title = tr("Quick Message").toStdWString(); - mi.msg = quickmsgText->toHtml().toStdWString(); + mi.title = tr("Quick Message").toUtf8().constData(); + mi.msg = quickmsgText->toHtml().toUtf8().constData(); mi.msgto.push_back(mPeerId); rsMsgs->MessageSend(mi); diff --git a/retroshare-gui/src/gui/feeds/SecurityItem.cpp b/retroshare-gui/src/gui/feeds/SecurityItem.cpp index bc062177d..52887d8ca 100644 --- a/retroshare-gui/src/gui/feeds/SecurityItem.cpp +++ b/retroshare-gui/src/gui/feeds/SecurityItem.cpp @@ -407,8 +407,8 @@ void SecurityItem::sendMessage() /* construct a message */ MessageInfo mi; - mi.title = tr("Quick Message").toStdWString(); - mi.msg = quickmsgText->toHtml().toStdWString(); + mi.title = tr("Quick Message").toUtf8().constData(); + mi.msg = quickmsgText->toHtml().toUtf8().constData(); mi.msgto.push_back(mGpgId); rsMsgs->MessageSend(mi); diff --git a/retroshare-gui/src/gui/msgs/MessageComposer.cpp b/retroshare-gui/src/gui/msgs/MessageComposer.cpp index cd9758a14..a0ba87360 100644 --- a/retroshare-gui/src/gui/msgs/MessageComposer.cpp +++ b/retroshare-gui/src/gui/msgs/MessageComposer.cpp @@ -512,14 +512,14 @@ void MessageComposer::sendConnectAttemptMsg(const std::string &gpgId, const std: if ((it->msgflags & RS_MSG_USER_REQUEST) == 0) { continue; } - if (it->title == title.toStdWString()) { + if (it->title == title.toUtf8().constData()) { return; } } /* create a message */ QString msgText = tr("Hi %1,

%2 wants to be friends with you on RetroShare.

Respond now:
%3

Thanks,
The RetroShare Team").arg(QString::fromUtf8(rsPeers->getGPGName(rsPeers->getGPGOwnId()).c_str()), sslName, link.toHtml()); - rsMsgs->SystemMessage(title.toStdWString(), msgText.toStdWString(), RS_MSG_USER_REQUEST); + rsMsgs->SystemMessage(title.toUtf8().constData(), msgText.toUtf8().constData(), RS_MSG_USER_REQUEST); } void MessageComposer::closeEvent (QCloseEvent * event) @@ -889,8 +889,8 @@ MessageComposer *MessageComposer::newMsg(const std::string &msgId /* = ""*/) // needed to send system flags with reply msgComposer->msgFlags = (msgInfo.msgflags & RS_MSG_SYSTEM); - msgComposer->setTitleText(QString::fromStdWString(msgInfo.title)); - msgComposer->setMsgText(QString::fromStdWString(msgInfo.msg)); + msgComposer->setTitleText(QString::fromUtf8(msgInfo.title.c_str())); + msgComposer->setMsgText(QString::fromUtf8(msgInfo.msg.c_str())); msgComposer->setFileList(msgInfo.files); // get existing groups @@ -975,7 +975,7 @@ QString MessageComposer::buildReplyHeader(const MessageInfo &msgInfo) } header += QString("
%1: %2
").arg(tr("Sent"), DateTime::formatLongDateTime(msgInfo.ts)); - header += QString("%1: %2
").arg(tr("Subject"), QString::fromStdWString(msgInfo.title)); + header += QString("%1: %2
").arg(tr("Subject"), QString::fromUtf8(msgInfo.title.c_str())); header += "
"; header += tr("On %1, %2 wrote:").arg(DateTime::formatDateTime(msgInfo.ts), from); @@ -1034,8 +1034,8 @@ MessageComposer *MessageComposer::replyMsg(const std::string &msgId, bool all) /* fill it in */ - msgComposer->setTitleText(QString::fromStdWString(msgInfo.title), REPLY); - msgComposer->setQuotedMsg(QString::fromStdWString(msgInfo.msg), buildReplyHeader(msgInfo)); + msgComposer->setTitleText(QString::fromUtf8(msgInfo.title.c_str()), REPLY); + msgComposer->setQuotedMsg(QString::fromUtf8(msgInfo.msg.c_str()), buildReplyHeader(msgInfo)); msgComposer->addRecipient(MessageComposer::TO, msgInfo.srcId, false); @@ -1078,8 +1078,8 @@ MessageComposer *MessageComposer::forwardMsg(const std::string &msgId) /* fill it in */ - msgComposer->setTitleText(QString::fromStdWString(msgInfo.title), FORWARD); - msgComposer->setQuotedMsg(QString::fromStdWString(msgInfo.msg), buildReplyHeader(msgInfo)); + msgComposer->setTitleText(QString::fromUtf8(msgInfo.title.c_str()), FORWARD); + msgComposer->setQuotedMsg(QString::fromUtf8(msgInfo.msg.c_str()), buildReplyHeader(msgInfo)); std::list& files_info = msgInfo.files; @@ -1151,13 +1151,13 @@ bool MessageComposer::sendMessage_internal(bool bDraftbox) /* construct a message */ MessageInfo mi; - mi.title = misc::removeNewLine(ui.titleEdit->text()).toStdWString(); + mi.title = misc::removeNewLine(ui.titleEdit->text()).toUtf8().constData(); // needed to send system flags with reply mi.msgflags = msgFlags; QString text; RsHtml::optimizeHtml(ui.msgText, text); - mi.msg = text.toStdWString(); + mi.msg = text.toUtf8().constData(); /* check for existing title */ if (bDraftbox == false && mi.title.empty()) { diff --git a/retroshare-gui/src/gui/msgs/MessageWidget.cpp b/retroshare-gui/src/gui/msgs/MessageWidget.cpp index 6e646a382..21e1b6af1 100644 --- a/retroshare-gui/src/gui/msgs/MessageWidget.cpp +++ b/retroshare-gui/src/gui/msgs/MessageWidget.cpp @@ -554,9 +554,9 @@ void MessageWidget::fill(const std::string &msgId) ui.fromText->setToolTip(PeerDefs::rsidFromId(srcId)); } - ui.subjectText->setText(QString::fromStdWString(msgInfo.title)); + ui.subjectText->setText(QString::fromUtf8(msgInfo.title.c_str())); - text = RsHtmlMsg(msgInfo.msgflags).formatText(ui.msgText->document(), QString::fromStdWString(msgInfo.msg), RSHTML_FORMATTEXT_EMBED_SMILEYS | RSHTML_FORMATTEXT_EMBED_LINKS | RSHTML_FORMATTEXT_REPLACE_LINKS); + text = RsHtmlMsg(msgInfo.msgflags).formatText(ui.msgText->document(), QString::fromUtf8(msgInfo.msg.c_str()), RSHTML_FORMATTEXT_EMBED_SMILEYS | RSHTML_FORMATTEXT_EMBED_LINKS | RSHTML_FORMATTEXT_REPLACE_LINKS); ui.msgText->setHtml(text); ui.filesText->setText(QString("(%1 %2)").arg(msgInfo.count).arg(msgInfo.count == 1 ? tr("File") : tr("Files"))); From fcb441cbd7055a8376d52d244ccf789ee432857e Mon Sep 17 00:00:00 2001 From: csoler Date: Fri, 4 Oct 2013 18:49:02 +0000 Subject: [PATCH 34/83] fixed utf8/wstring calls git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@6799 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- .../src/rpc/proto/rpcprotochat.cc | 22 ++++--------------- 1 file changed, 4 insertions(+), 18 deletions(-) diff --git a/retroshare-nogui/src/rpc/proto/rpcprotochat.cc b/retroshare-nogui/src/rpc/proto/rpcprotochat.cc index 1298206e5..388685c5d 100644 --- a/retroshare-nogui/src/rpc/proto/rpcprotochat.cc +++ b/retroshare-nogui/src/rpc/proto/rpcprotochat.cc @@ -1001,8 +1001,7 @@ int RpcProtoChat::processReqSendMessage(uint32_t chan_id, uint32_t /*msg_id*/, u // Send the message. bool priv_or_lobby = true; std::string chat_id; - std::wstring chat_msg; - convertUTF8toWString(req.msg().msg(), chat_msg); + std::string chat_msg = req.msg().msg() ; std::cerr << "Chat Message is: " << req.msg().msg(); std::cerr << std::endl; @@ -1146,9 +1145,7 @@ int RpcProtoChat::locked_checkForEvents(uint32_t event, const std::listpeer_nickname; std::cerr << std::endl; { - std::string msg_utf8; - librs::util::ConvertUtf16ToUtf8(it->msg, msg_utf8); - std::cerr << " Msg: " << msg_utf8; + std::cerr << " Msg: " << it->msg ; std::cerr << std::endl; } @@ -1222,9 +1219,7 @@ int RpcProtoChat::locked_checkForEvents(uint32_t event, const std::listpeer_nickname; std::cerr << std::endl; { - std::string msg_utf8; - librs::util::ConvertUtf16ToUtf8(it->msg, msg_utf8); - std::cerr << " Msg: " << msg_utf8; + std::cerr << " Msg: " << it->msg; std::cerr << std::endl; } /* must send to all registered clients */ @@ -1427,16 +1422,7 @@ bool createQueuedEventSendMsg(const ChatInfo &chatinfo, rsctrl::chat::ChatType c msg->set_chat_flags(chatinfo.chatflags); msg->set_send_time(chatinfo.sendTime); msg->set_recv_time(chatinfo.recvTime); - - std::string msg_utf8; - if (!convertWStringToUTF8(chatinfo.msg, msg_utf8)) - { - std::cerr << "RpcProtoChat::createQueuedEventSendMsg() ERROR Converting Msg"; - std::cerr << std::endl; - return false; - } - - msg->set_msg(msg_utf8); + msg->set_msg(chatinfo.msg); /* DONE - Generate Reply */ std::string outmsg; From 9d4033b0430d32a186c44dbdaf93ccc921048058 Mon Sep 17 00:00:00 2001 From: csoler Date: Fri, 4 Oct 2013 21:00:31 +0000 Subject: [PATCH 35/83] fixed unused variable warning git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@6802 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/pgp/pgphandler.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libretroshare/src/pgp/pgphandler.cc b/libretroshare/src/pgp/pgphandler.cc index 1ae09fe23..f3add34de 100644 --- a/libretroshare/src/pgp/pgphandler.cc +++ b/libretroshare/src/pgp/pgphandler.cc @@ -1721,8 +1721,8 @@ bool PGPHandler::locked_syncPublicKeyring() bool PGPHandler::locked_syncTrustDatabase() { struct stat64 buf ; - std::wstring wfullname; #ifdef WINDOWS_SYS + std::wstring wfullname; librs::util::ConvertUtf8ToUtf16(_trustdb_path, wfullname); if(-1 == _wstati64(wfullname.c_str(), &buf)) #else From 9470e5562a2866f709d5f40cb091e021e58674c5 Mon Sep 17 00:00:00 2001 From: chrisparker126 Date: Sat, 5 Oct 2013 11:36:31 +0000 Subject: [PATCH 36/83] Added update capability to forums ui Added timestamp check for group update in nxs decided to add control variable to allow meta changes in updates rather than none git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.5-gxs_finale@6803 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/gxs/rsgenexchange.cc | 29 ++++++++- libretroshare/src/gxs/rsgenexchange.h | 27 ++++++-- libretroshare/src/gxs/rsgxsnetservice.cc | 9 ++- libretroshare/src/gxs/rsgxsutil.h | 10 +++ libretroshare/src/retroshare/rsgxsforums.h | 8 +++ .../src/retroshare/rsgxsifacetypes.h | 64 ++++++++++++++++++- libretroshare/src/services/p3gxsforums.cc | 14 ++++ libretroshare/src/services/p3gxsforums.h | 7 ++ retroshare-gui/src/gui/gxs/GxsGroupDialog.cpp | 53 ++++++++++++--- retroshare-gui/src/gui/gxs/GxsGroupDialog.h | 1 + .../src/gui/gxschannels/GxsChannelDialog.cpp | 1 + .../src/gui/gxsforums/GxsForumGroupDialog.cpp | 7 ++ 12 files changed, 208 insertions(+), 22 deletions(-) diff --git a/libretroshare/src/gxs/rsgenexchange.cc b/libretroshare/src/gxs/rsgenexchange.cc index 5b4baff0d..db29576ca 100644 --- a/libretroshare/src/gxs/rsgenexchange.cc +++ b/libretroshare/src/gxs/rsgenexchange.cc @@ -1370,11 +1370,11 @@ void RsGenExchange::publishGroup(uint32_t& token, RsGxsGrpItem *grpItem) } -void RsGenExchange::updateGroup(uint32_t& token, RsGxsGrpItem* grpItem) +void RsGenExchange::updateGroup(uint32_t& token, RsGxsGroupUpdateMeta& updateMeta, RsGxsGrpItem* grpItem) { RsStackMutex stack(mGenMtx); token = mDataAccess->generatePublicToken(); - mGroupUpdatePublish.push_back(GroupUpdatePublish(grpItem, token)); + mGroupUpdatePublish.push_back(GroupUpdatePublish(grpItem, updateMeta, token)); #ifdef GEN_EXCH_DEBUG std::cerr << "RsGenExchange::updateGroup() token: " << token; @@ -1828,7 +1828,9 @@ void RsGenExchange::processGroupUpdatePublish() const RsGxsGroupId& groupId = gup.grpItem->meta.mGroupId; RsGxsGrpMetaData* meta = grpMeta[groupId]; - GxsGrpPendingSign ggps(ggps.mItem, ggps.mToken); + gup.grpItem->meta = *meta; + assignMetaUpdates(gup.grpItem->meta, gup.mUpdateMeta); + GxsGrpPendingSign ggps(gup.grpItem, ggps.mToken); bool split = splitKeys(meta->keys, ggps.mPrivateKeys, ggps.mPublicKeys); @@ -1849,6 +1851,27 @@ void RsGenExchange::processGroupUpdatePublish() mGroupUpdatePublish.clear(); } +void RsGenExchange::assignMetaUpdates(RsGroupMetaData& meta, const RsGxsGroupUpdateMeta metaUpdate) const +{ + const RsGxsGroupUpdateMeta::GxsMetaUpdate* updates; + RsGxsGroupUpdateMeta::GxsMetaUpdate::const_iterator mit = updates->begin(); + for(; mit != updates->end(); mit++) + { + const UpdateItem* item = mit->second; + RsGxsGroupUpdateMeta::UpdateType utype = mit->first; + + if(utype == RsGxsGroupUpdateMeta::NAME) + { + const StringUpdateItem* sitem = NULL; + + if((sitem = dynamic_cast(item)) != NULL) + { + meta.mGroupName = sitem->getUpdate(); + } + } + } +} + bool RsGenExchange::splitKeys(const RsTlvSecurityKeySet& keySet, RsTlvSecurityKeySet& privateKeySet, RsTlvSecurityKeySet& publicKeySet) { diff --git a/libretroshare/src/gxs/rsgenexchange.h b/libretroshare/src/gxs/rsgenexchange.h index b7dc6e966..054c19ce6 100644 --- a/libretroshare/src/gxs/rsgenexchange.h +++ b/libretroshare/src/gxs/rsgenexchange.h @@ -527,12 +527,12 @@ protected: /*! * Updates an existing group item \n - * This will induce a related change message \n - * Ownership of item passes to this rsgenexchange \n - * @param token - * @param grpItem - */ - void updateGroup(uint32_t& token, RsGxsGrpItem* grpItem); + * This will induce a related change message \n + * Ownership of item passes to this rsgenexchange \n + * @param token + * @param grpItem + */ + void updateGroup(uint32_t& token, RsGxsGroupUpdateMeta& updateMeta, RsGxsGrpItem* grpItem); public: /*! @@ -762,7 +762,20 @@ private: */ bool updateValid(RsGxsGrpMetaData& oldGrp, RsNxsGrp& newGrp) const; - bool splitKeys(const RsTlvSecurityKeySet& keySet, RsTlvSecurityKeySet& privateKeySet, RsTlvSecurityKeySet& publicKeySet); + /*! + * convenience function for splitting key sets into private and public + * @param keySet The keys set to split into a private and public set + * @param privateKeySet contains the publish and admin private keys + * @param publicKeySet contains the publish and admin public keys + * @return false, if 2 private and public keys are not found in keySet + */ + bool splitKeys(const RsTlvSecurityKeySet& keySet, RsTlvSecurityKeySet& privateKeySet, + RsTlvSecurityKeySet& publicKeySet); + + /*! + * Convenience function for assigning the meta update items to the actual group meta + */ + void assignMetaUpdates(RsGroupMetaData& meta, const RsGxsGroupUpdateMeta metaUpdate) const; private: diff --git a/libretroshare/src/gxs/rsgxsnetservice.cc b/libretroshare/src/gxs/rsgxsnetservice.cc index 6465d4332..c0e4c712d 100644 --- a/libretroshare/src/gxs/rsgxsnetservice.cc +++ b/libretroshare/src/gxs/rsgxsnetservice.cc @@ -1366,6 +1366,7 @@ void RsGxsNetService::locked_genReqGrpTransaction(NxsTransaction* tr) } std::map grpMetaMap; + std::map::const_iterator metaIter; mDataStore->retrieveGxsGrpMetaData(grpMetaMap); // now do compare and add loop @@ -1380,8 +1381,14 @@ void RsGxsNetService::locked_genReqGrpTransaction(NxsTransaction* tr) { RsNxsSyncGrpItem*& grpSyncItem = *llit; const std::string& grpId = grpSyncItem->grpId; + metaIter = grpMetaMap.find(grpId); + bool haveItem = metaIter != grpMetaMap.end(); + bool latestItem = false; - if(grpMetaMap.find(grpId) == grpMetaMap.end()){ + if(!haveItem) + latestItem = grpSyncItem->publishTs > metaIter->second->mPublishTs; + + if(haveItem && latestItem){ // determine if you need to check reputation bool checkRep = !grpSyncItem->authorId.empty(); diff --git a/libretroshare/src/gxs/rsgxsutil.h b/libretroshare/src/gxs/rsgxsutil.h index f6b367f4a..9e11b5e41 100644 --- a/libretroshare/src/gxs/rsgxsutil.h +++ b/libretroshare/src/gxs/rsgxsutil.h @@ -139,4 +139,14 @@ public: bool validUpdate; }; +class GroupUpdatePublish +{ +public: + GroupUpdatePublish(RsGxsGrpItem* item, RsGxsGroupUpdateMeta updateMeta, uint32_t token) + : grpItem(item), mToken(token), mUpdateMeta(updateMeta) {} + RsGxsGrpItem* grpItem; + RsGxsGroupUpdateMeta mUpdateMeta; + uint32_t mToken; +}; + #endif /* GXSUTIL_H_ */ diff --git a/libretroshare/src/retroshare/rsgxsforums.h b/libretroshare/src/retroshare/rsgxsforums.h index de97618c0..956ac2ab5 100644 --- a/libretroshare/src/retroshare/rsgxsforums.h +++ b/libretroshare/src/retroshare/rsgxsforums.h @@ -84,6 +84,14 @@ virtual void setMessageReadStatus(uint32_t& token, const RsGxsGrpMsgIdPair& msgI virtual bool createGroup(uint32_t &token, RsGxsForumGroup &group) = 0; virtual bool createMsg(uint32_t &token, RsGxsForumMsg &msg) = 0; +/*! + * To update forum group with new information + * @param token the token used to check completion status of update + * @param group group to be updated, groupId element must be set or will be rejected + * @return false groupId not set, true if set and accepted (still check token for completion) + */ +virtual bool updateGroup(uint32_t &token, RsGxsGroupUpdateMeta&, RsGxsForumGroup &group); + }; diff --git a/libretroshare/src/retroshare/rsgxsifacetypes.h b/libretroshare/src/retroshare/rsgxsifacetypes.h index d4a4f4df3..a6dacd329 100644 --- a/libretroshare/src/retroshare/rsgxsifacetypes.h +++ b/libretroshare/src/retroshare/rsgxsifacetypes.h @@ -128,7 +128,6 @@ public: class GxsGroupStatistic { public: - /// number of message RsGxsGroupId mGrpId; uint32_t mNumMsgs; @@ -147,4 +146,67 @@ public: uint32_t mSizeStore; }; +class UpdateItem +{ +public: + virtual ~UpdateItem() { } +}; + +class StringUpdateItem : public UpdateItem +{ +public: + StringUpdateItem(const std::string update) : mUpdate(update) {} + const std::string& getUpdate() const { return mUpdate; } + +private: + std::string mUpdate; +}; + +class RsGxsGroupUpdateMeta +{ +public: + + // expand as support is added for other utypes + enum UpdateType { DESCRIPTION, NAME }; + + RsGxsGroupUpdateMeta(const std::string& groupId); + ~RsGxsGroupUpdateMeta() + { + GxsMetaUpdate::iterator mit = mUpdates.begin(); + for(; mit != mUpdates.end(); mit++) + delete mit->second; + } + + typedef std::map GxsMetaUpdate; + + /*! + * Only one item of a utype can exist + * @param utype the type of meta update + * @param item update item containing the change value + */ + void setMetaUpdate(UpdateType utype, UpdateItem* item) + { + GxsMetaUpdate::iterator mit; + if ((mit = mUpdates.find(utype)) != mUpdates.end()) + mUpdates[utype] = item; + else + delete mUpdates[utype]; + } + + /*! + * @param utype update type to remove + * @return false if update did not exist, true if update successfully removed + */ + bool removeUpdateType(UpdateType utype){ return mUpdates.erase(utype) == 1; } + + const GxsMetaUpdate* getUpdate() { return &mUpdates; } + + const std::string& getGroupId() { return mGroupId; } + +private: + + GxsMetaUpdate mUpdates; + std::string mGroupId; +}; + #endif /* RSGXSIFACETYPES_H_ */ diff --git a/libretroshare/src/services/p3gxsforums.cc b/libretroshare/src/services/p3gxsforums.cc index 6010ddc3d..1e8fd1a65 100644 --- a/libretroshare/src/services/p3gxsforums.cc +++ b/libretroshare/src/services/p3gxsforums.cc @@ -215,6 +215,20 @@ bool p3GxsForums::createGroup(uint32_t &token, RsGxsForumGroup &group) return true; } +bool p3GxsForums::updateGroup(uint32_t &token, RsGxsGroupUpdateMeta& meta, RsGxsForumGroup &group) +{ + std::cerr << "p3GxsForums::createGroup()" << std::endl; + + if(group.mMeta.mGroupId.empty()) + return false; + + RsGxsForumGroupItem* grpItem = new RsGxsForumGroupItem(); + grpItem->mGroup = group; + grpItem->meta = group.mMeta; + + RsGenExchange::updateGroup(token, meta, grpItem); + return true; +} bool p3GxsForums::createMsg(uint32_t &token, RsGxsForumMsg &msg) { diff --git a/libretroshare/src/services/p3gxsforums.h b/libretroshare/src/services/p3gxsforums.h index 6287a10f8..cc2311539 100644 --- a/libretroshare/src/services/p3gxsforums.h +++ b/libretroshare/src/services/p3gxsforums.h @@ -74,6 +74,13 @@ virtual void setMessageReadStatus(uint32_t& token, const RsGxsGrpMsgIdPair& msgI virtual bool createGroup(uint32_t &token, RsGxsForumGroup &group); virtual bool createMsg(uint32_t &token, RsGxsForumMsg &msg); +/*! + * To update forum group with new information + * @param token the token used to check completion status of update + * @param group group to be updated, groupId element must be set or will be rejected + * @return false groupId not set, true if set and accepted (still check token for completion) + */ +virtual bool updateGroup(uint32_t &token, RsGxsGroupUpdateMeta& meta, RsGxsForumGroup &group); private: diff --git a/retroshare-gui/src/gui/gxs/GxsGroupDialog.cpp b/retroshare-gui/src/gui/gxs/GxsGroupDialog.cpp index 2ecc06db4..81f314718 100644 --- a/retroshare-gui/src/gui/gxs/GxsGroupDialog.cpp +++ b/retroshare-gui/src/gui/gxs/GxsGroupDialog.cpp @@ -148,13 +148,13 @@ void GxsGroupDialog::initMode() { ui.buttonBox->setStandardButtons(QDialogButtonBox::Close); } - break; -//TODO -// case MODE_EDIT: -// { -// ui.createButton->setText(tr("Submit Changes")); -// } -// break; + break; + case MODE_EDIT: + { + ui.buttonBox->setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); + ui.buttonBox->button(QDialogButtonBox::Ok)->setText(tr("Submit Group Changes")); + } + break; } } @@ -320,14 +320,47 @@ void GxsGroupDialog::submitGroup() break; case MODE_EDIT: - { - /* TEMP: just close if down */ - cancelDialog(); + { + + editGroup(); } break; } } +void GxsGroupDialog::editGroup() +{ + std::cerr << "GxsGroupDialog::editGroup()" << std::endl; + + QString name = misc::removeNewLine(ui.groupName->text()); + uint32_t flags = GXS_SERV::FLAG_PRIVACY_PUBLIC; + + if(name.isEmpty()) + { + /* error message */ + QMessageBox::warning(this, "RetroShare", tr("Please add a Name"), QMessageBox::Ok, QMessageBox::Ok); + return; //Don't add a empty name!! + } + + uint32_t token; + RsGroupMetaData meta; + + // Fill in the MetaData as best we can. + meta.mGroupName = std::string(name.toUtf8()); + + meta.mGroupFlags = flags; + meta.mSignFlags = getGroupSignFlags(); + + if (service_CreateGroup(token, meta)) + { + // get the Queue to handle response. + if(mTokenQueue != NULL) + mTokenQueue->queueRequest(token, TOKENREQ_GROUPINFO, RS_TOKREQ_ANSTYPE_ACK, GXSGROUP_NEWGROUPID); + } + + close(); +} + void GxsGroupDialog::createGroup() { std::cerr << "GxsGroupDialog::createGroup()"; diff --git a/retroshare-gui/src/gui/gxs/GxsGroupDialog.h b/retroshare-gui/src/gui/gxs/GxsGroupDialog.h index f8cf39cec..5f71ee364 100644 --- a/retroshare-gui/src/gui/gxs/GxsGroupDialog.h +++ b/retroshare-gui/src/gui/gxs/GxsGroupDialog.h @@ -202,6 +202,7 @@ private: void setupVisibility(); void clearForm(); void createGroup(); + void editGroup(); void sendShareList(std::string forumId); void loadNewGroupId(const uint32_t &token); diff --git a/retroshare-gui/src/gui/gxschannels/GxsChannelDialog.cpp b/retroshare-gui/src/gui/gxschannels/GxsChannelDialog.cpp index a35e7a522..8ab57794e 100644 --- a/retroshare-gui/src/gui/gxschannels/GxsChannelDialog.cpp +++ b/retroshare-gui/src/gui/gxschannels/GxsChannelDialog.cpp @@ -23,6 +23,7 @@ #include #include +#include #include "GxsChannelDialog.h" #include "gui/feeds/GxsChannelPostItem.h" diff --git a/retroshare-gui/src/gui/gxsforums/GxsForumGroupDialog.cpp b/retroshare-gui/src/gui/gxsforums/GxsForumGroupDialog.cpp index 36351363b..47edec932 100644 --- a/retroshare-gui/src/gui/gxsforums/GxsForumGroupDialog.cpp +++ b/retroshare-gui/src/gui/gxsforums/GxsForumGroupDialog.cpp @@ -52,6 +52,13 @@ const uint32_t ForumCreateDefaultsFlags = ( GXS_GROUP_DEFAULTS_DISTRIB_PUBLIC GXS_GROUP_DEFAULTS_COMMENTS_NO | 0); + +const uint32_t ForumEditEnabledFlags = ( GXS_GROUP_FLAGS_ICON | + GXS_GROUP_FLAGS_DESCRIPTION | + 0); + +const uint32_t ForumEditDefaultsFlags = 0; + GxsForumGroupDialog::GxsForumGroupDialog(TokenQueue *tokenQueue, QWidget *parent) :GxsGroupDialog(tokenQueue, ForumCreateEnabledFlags, ForumCreateDefaultsFlags, parent) { From 18944404cc7eb7396a5b2535db48963714962e93 Mon Sep 17 00:00:00 2001 From: chrisparker126 Date: Sat, 5 Oct 2013 12:03:31 +0000 Subject: [PATCH 37/83] make update function pure virtual in interface git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.5-gxs_finale@6804 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/retroshare/rsgxsforums.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libretroshare/src/retroshare/rsgxsforums.h b/libretroshare/src/retroshare/rsgxsforums.h index 956ac2ab5..1ae6fd9e0 100644 --- a/libretroshare/src/retroshare/rsgxsforums.h +++ b/libretroshare/src/retroshare/rsgxsforums.h @@ -90,7 +90,7 @@ virtual bool createMsg(uint32_t &token, RsGxsForumMsg &msg) = 0; * @param group group to be updated, groupId element must be set or will be rejected * @return false groupId not set, true if set and accepted (still check token for completion) */ -virtual bool updateGroup(uint32_t &token, RsGxsGroupUpdateMeta&, RsGxsForumGroup &group); +virtual bool updateGroup(uint32_t &token, RsGxsGroupUpdateMeta&, RsGxsForumGroup &group) = 0; }; From 120a27d9c713808a5d81852eda4686ccc4bea390 Mon Sep 17 00:00:00 2001 From: csoler Date: Sun, 6 Oct 2013 20:12:34 +0000 Subject: [PATCH 38/83] - added RsCompress with memory compression methods based on ZLib (already linked) - added test code for RsCompress methods - used compression to compress file lists so as to reduce bandwidth usage git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@6809 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/dbase/findex.cc | 112 ++++++--- libretroshare/src/libretroshare.pro | 2 + libretroshare/src/tests/util/Makefile | 6 +- libretroshare/src/tests/util/compress_test.cc | 217 ++++++++++++++++++ retroshare-gui/src/gui/MessagesDialog.cpp | 4 +- 5 files changed, 306 insertions(+), 35 deletions(-) create mode 100644 libretroshare/src/tests/util/compress_test.cc diff --git a/libretroshare/src/dbase/findex.cc b/libretroshare/src/dbase/findex.cc index 9fb7c63ab..f3ba81bde 100644 --- a/libretroshare/src/dbase/findex.cc +++ b/libretroshare/src/dbase/findex.cc @@ -26,6 +26,7 @@ #include "retroshare/rsexpr.h" #include "util/rsdir.h" #include "util/rsstring.h" +#include "util/rscompress.h" #include #include @@ -746,9 +747,10 @@ int FileIndex::printFileIndex(std::string &out) return 1; } -int FileIndex::loadIndex(const std::string& filename, const std::string& expectedHash, uint64_t /*size*/) +int FileIndex::loadIndex(const std::string& filename, const std::string& expectedHash, uint64_t size) { - std::ifstream file (filename.c_str(), std::ifstream::binary); + FILE *file = RsDirUtil::rs_fopen(filename.c_str(),"rb") ; + if (!file) { #ifdef FI_DEBUG @@ -759,28 +761,36 @@ int FileIndex::loadIndex(const std::string& filename, const std::string& expecte } /* load file into memory, close file */ - char ibuf[512]; - std::string s; - while(!file.eof()) - { - file.read(ibuf, 512); - s.append(ibuf, file.gcount()); - } - file.close(); + uint8_t *compressed_data = new uint8_t[size] ; - /* calculate hash */ - unsigned char sha_buf[SHA_DIGEST_LENGTH]; - SHA_CTX *sha_ctx = new SHA_CTX; - SHA1_Init(sha_ctx); - SHA1_Update(sha_ctx, s.c_str(), s.length()); - SHA1_Final(&sha_buf[0], sha_ctx); - delete sha_ctx; - - std::string tmpout; - for(int i = 0; i < SHA_DIGEST_LENGTH; i++) + if(compressed_data == NULL) { - rs_sprintf_append(tmpout, "%02x", (unsigned int) (sha_buf[i])); + std::cerr << "FileIndex::loadIndex(): can't allocate memory for " << size << " bytes." << std::endl; + return 0 ; } + int bytesread = 0 ; + if(size != (bytesread = fread(compressed_data,1,size,file))) + { + std::cerr << "FileIndex::loadIndex(): can't read " << size << " bytes from file " << filename << ". Only " << bytesread << " actually read." << std::endl; + return 0 ; + } + fclose(file) ; + + std::string tmpout = RsDirUtil::sha1sum((unsigned char *)(compressed_data),size).toStdString() ; + +// /* calculate hash */ +// unsigned char sha_buf[SHA_DIGEST_LENGTH]; +// SHA_CTX *sha_ctx = new SHA_CTX; +// SHA1_Init(sha_ctx); +// SHA1_Update(sha_ctx, s.c_str(), s.length()); +// SHA1_Final(&sha_buf[0], sha_ctx); +// delete sha_ctx; +// +// std::string tmpout; +// for(int i = 0; i < SHA_DIGEST_LENGTH; i++) +// { +// rs_sprintf_append(tmpout, "%02x", (unsigned int) (sha_buf[i])); +// } if (expectedHash != "" && expectedHash != tmpout) { @@ -791,6 +801,21 @@ int FileIndex::loadIndex(const std::string& filename, const std::string& expecte #endif return 0; } + // now uncompress the string + // + + uint8_t *uncompressed_data = NULL ; + unsigned int uncompressed_data_size = 0 ; + + if(!RsCompress::uncompress_memory_chunk(compressed_data,size,uncompressed_data,uncompressed_data_size)) + { + std::cerr << "FileIndex::loadIndex() Decompression failed! Fileindex can't be read." << std::endl; + return 0 ; + } + std::string s((char *)uncompressed_data,uncompressed_data_size) ; + + delete[] compressed_data ; + free(uncompressed_data) ; #define FIND_NEXT(s,start,end,c) end = s.find(c, start); if (end == std::string::npos) end = s.length(); @@ -966,7 +991,6 @@ int FileIndex::saveIndex(const std::string& filename, std::string &fileHash, uin std::string s; size = 0 ; - fileHash = "" ; /* print version and header */ s += "# FileIndex version 0.1\n"; @@ -1003,18 +1027,37 @@ int FileIndex::saveIndex(const std::string& filename, std::string &fileHash, uin /* signal to pop directory from stack in loadIndex() */ s += "-\n"; - /* calculate sha1 hash */ - SHA_CTX *sha_ctx = new SHA_CTX; - SHA1_Init(sha_ctx); - SHA1_Update(sha_ctx, s.c_str(), s.length()); - SHA1_Final(&sha_buf[0], sha_ctx); - delete sha_ctx; + // now compress the data. + + std::cerr << "FileIndex::saveIndex(): compressign data." << std::endl; - for(int i = 0; i < SHA_DIGEST_LENGTH; i++) + uint8_t *compressed_data = NULL ; + uint32_t compressed_data_size = 0 ; + + if(!RsCompress::compress_memory_chunk((unsigned char *)s.c_str(),s.length(),compressed_data,compressed_data_size)) { - rs_sprintf_append(fileHash, "%02x", (unsigned int) (sha_buf[i])); + std::cerr << "(EE) ERROR in file list compression ! file list can't be saved" << std::endl; + return false ; } + fileHash = RsDirUtil::sha1sum((unsigned char *)compressed_data,compressed_data_size).toStdString() ; + + std::cerr << " old size = " << s.length() << std::endl; + std::cerr << " new size = " << compressed_data_size << std::endl; + std::cerr << " hash = " << fileHash << std::endl; + +// /* calculate sha1 hash */ +// SHA_CTX *sha_ctx = new SHA_CTX; +// SHA1_Init(sha_ctx); +// SHA1_Update(sha_ctx, s.c_str(), s.length()); +// SHA1_Final(&sha_buf[0], sha_ctx); +// delete sha_ctx; +// +// for(int i = 0; i < SHA_DIGEST_LENGTH; i++) +// { +// rs_sprintf_append(fileHash, "%02x", (unsigned int) (sha_buf[i])); +// } + /* finally, save to file */ FILE *file = RsDirUtil::rs_fopen(filenametmp.c_str(), "wb"); @@ -1023,9 +1066,16 @@ int FileIndex::saveIndex(const std::string& filename, std::string &fileHash, uin std::cerr << "FileIndex::saveIndex error opening file for writting: " << filename << ". Giving up." << std::endl; return 0; } - fprintf(file,"%s",s.c_str()) ; + int outwritten ; + + if(compressed_data_size != (outwritten=fwrite(compressed_data,1,compressed_data_size,file))) + { + std::cerr << "FileIndex::saveIndex error. File not entirely written. Only " << outwritten << " bytes wrote out of " << compressed_data_size << " check for disk full, or disk quotas." << std::endl; + return 0; + } fclose(file); + free(compressed_data) ; // Use a temp file name so that the file is never half saved. // diff --git a/libretroshare/src/libretroshare.pro b/libretroshare/src/libretroshare.pro index d4058dc10..e3911f177 100644 --- a/libretroshare/src/libretroshare.pro +++ b/libretroshare/src/libretroshare.pro @@ -408,6 +408,7 @@ HEADERS += turtle/p3turtle.h \ HEADERS += util/folderiterator.h \ util/rsdebug.h \ + util/rscompress.h \ util/smallobject.h \ util/rsdir.h \ util/rsdiscspace.h \ @@ -542,6 +543,7 @@ SOURCES += turtle/p3turtle.cc \ SOURCES += util/folderiterator.cc \ util/rsdebug.cc \ + util/rscompress.cc \ util/smallobject.cc \ util/rsdir.cc \ util/rsdiscspace.cc \ diff --git a/libretroshare/src/tests/util/Makefile b/libretroshare/src/tests/util/Makefile index 9be844a06..8ec44d149 100644 --- a/libretroshare/src/tests/util/Makefile +++ b/libretroshare/src/tests/util/Makefile @@ -9,13 +9,15 @@ OPS_TOP_DIR = ../../../../openpgpsdk/src include $(RS_TOP_DIR)/tests/scripts/config.mk ############################################################### -TESTOBJ = dirtest.o sha1_test.o aes_test.o dchat_decrypt.o -TESTS = dirtest sha1_test aes_test dchat_decrypt +TESTOBJ = dirtest.o compress_test.o sha1_test.o aes_test.o dchat_decrypt.o +TESTS = dirtest sha1_test aes_test compress_test dchat_decrypt all: tests sha1_test: sha1_test.o $(CC) $(CFLAGS) -o sha1_test sha1_test.o $(LIBS) +compress_test: compress_test.o + $(CC) $(CFLAGS) -o compress_test compress_test.o $(LIBS) dirtest: dirtest.o $(CC) $(CFLAGS) -o dirtest dirtest.o $(LIBS) dirtest: aes_test.o diff --git a/libretroshare/src/tests/util/compress_test.cc b/libretroshare/src/tests/util/compress_test.cc new file mode 100644 index 000000000..07e24b2eb --- /dev/null +++ b/libretroshare/src/tests/util/compress_test.cc @@ -0,0 +1,217 @@ + +/* + * "$Id: compress.cc,v 1.1 2007-02-19 20:08:30 rmf24 Exp $" + * + * RetroShare C++ Interface. + * + * Copyright 2012-2012 by Cyril Soler + * + * 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 "util/rscompress.h" +#include "util/rsdir.h" +#include "util/utest.h" +#include "util/argstream.h" + +#include +#include +#include +#include + +void printHelp(int argc,char *argv[]) +{ + std::cerr << argv[0] << ": tests AES encryption/decryption functions." << std::endl; + std::cerr << "Usage: " << argv[0] << std::endl ; +} + +bool compareStrings(const std::string& s1,const std::string& s2) +{ + uint32_t L = std::min(s1.length(),s2.length()) ; + + for(int i=0;i>4) ] ; + std::cerr << outh[ data[j] & 0xf ] ; + } +} + +INITTEST() ; + +int main(int argc,char *argv[]) +{ + std::string inputfile ; + argstream as(argc,argv) ; + + as >> help() ; + + as.defaultErrorHandling() ; + + std::cerr << "Testing RsCompress" << std::endl; + + std::string source_string = "This is a very secret string, but ultimately it will always be decyphered \ + ar cqs libretroshare.a temp/linux-g++-64/obj/p3bitdht.o \ + temp/linux-g++-64/obj/p3bitdht_interface.o \ + temp/linux-g++-64/obj/p3bitdht_peers.o \ + temp/linux-g++-64/obj/p3bitdht_peernet.o \ + temp/linux-g++-64/obj/p3bitdht_relay.o \ + temp/linux-g++-64/obj/connectstatebox.o temp/linux-g++-64/obj/udppeer.o \ + temp/linux-g++-64/obj/tcppacket.o temp/linux-g++-64/obj/tcpstream.o \ + temp/linux-g++-64/obj/tou.o temp/linux-g++-64/obj/bss_tou.o \ + temp/linux-g++-64/obj/udpstunner.o temp/linux-g++-64/obj/udprelay.o \ + temp/linux-g++-64/obj/cachestrapper.o temp/linux-g++-64/obj/fimonitor.o \ + temp/linux-g++-64/obj/findex.o temp/linux-g++-64/obj/fistore.o \ + temp/linux-g++-64/obj/rsexpr.o temp/linux-g++-64/obj/ftchunkmap.o \ + temp/linux-g++-64/obj/ftcontroller.o \ + temp/linux-g++-64/obj/ftdatamultiplex.o temp/linux-g++-64/obj/ftdbase.o \ + temp/linux-g++-64/obj/ftextralist.o temp/linux-g++-64/obj/ftfilecreator.o \ + temp/linux-g++-64/obj/ftfileprovider.o \ + temp/linux-g++-64/obj/ftfilesearch.o temp/linux-g++-64/obj/ftserver.o \ + temp/linux-g++-64/obj/fttransfermodule.o \ + temp/linux-g++-64/obj/ftturtlefiletransferitem.o \ + temp/linux-g++-64/obj/authgpg.o temp/linux-g++-64/obj/authssl.o \ + temp/linux-g++-64/obj/pgphandler.o temp/linux-g++-64/obj/pgpkeyutil.o \ + temp/linux-g++-64/obj/rscertificate.o temp/linux-g++-64/obj/p3cfgmgr.o \ + temp/linux-g++-64/obj/p3peermgr.o temp/linux-g++-64/obj/p3linkmgr.o \ + temp/linux-g++-64/obj/p3netmgr.o temp/linux-g++-64/obj/p3notify.o \ + temp/linux-g++-64/obj/pqiqos.o temp/linux-g++-64/obj/pqiarchive.o \ + temp/linux-g++-64/obj/pqibin.o temp/linux-g++-64/obj/pqihandler.o \ + temp/linux-g++-64/obj/p3historymgr.o temp/linux-g++-64/obj/pqiipset.o \ + temp/linux-g++-64/obj/pqiloopback.o temp/linux-g++-64/obj/pqimonitor.o \ + temp/linux-g++-64/obj/pqinetwork.o temp/linux-g++-64/obj/pqiperson.o \ + temp/linux-g++-64/obj/pqipersongrp.o temp/linux-g++-64/obj/pqisecurity.o \ + temp/linux-g++-64/obj/pqiservice.o temp/linux-g++-64/obj/pqissl.o \ + temp/linux-g++-64/obj/pqissllistener.o \ + temp/linux-g++-64/obj/pqisslpersongrp.o temp/linux-g++-64/obj/pqissludp.o \ + temp/linux-g++-64/obj/pqisslproxy.o temp/linux-g++-64/obj/pqistore.o \ + temp/linux-g++-64/obj/pqistreamer.o \ + temp/linux-g++-64/obj/pqithreadstreamer.o \ + temp/linux-g++-64/obj/pqiqosstreamer.o temp/linux-g++-64/obj/sslfns.o \ + temp/linux-g++-64/obj/pqinetstatebox.o \ + temp/linux-g++-64/obj/p3face-config.o temp/linux-g++-64/obj/p3face-msgs.o \ + temp/linux-g++-64/obj/p3face-server.o temp/linux-g++-64/obj/p3history.o \ + temp/linux-g++-64/obj/p3msgs.o temp/linux-g++-64/obj/p3peers.o \ + temp/linux-g++-64/obj/p3status.o temp/linux-g++-64/obj/rsinit.o \ + temp/linux-g++-64/obj/rsloginhandler.o temp/linux-g++-64/obj/rstypes.o \ + temp/linux-g++-64/obj/p3serverconfig.o \ + temp/linux-g++-64/obj/pluginmanager.o temp/linux-g++-64/obj/dlfcn_win32.o \ + temp/linux-g++-64/obj/rspluginitems.o \ + temp/linux-g++-64/obj/rsbaseserial.o \ + temp/linux-g++-64/obj/rsfiletransferitems.o \ + temp/linux-g++-64/obj/rsserviceserialiser.o \ + temp/linux-g++-64/obj/rsconfigitems.o \ + temp/linux-g++-64/obj/rshistoryitems.o temp/linux-g++-64/obj/rsmsgitems.o \ + temp/linux-g++-64/obj/rsserial.o temp/linux-g++-64/obj/rsstatusitems.o \ + temp/linux-g++-64/obj/rstlvaddrs.o temp/linux-g++-64/obj/rstlvbase.o \ + temp/linux-g++-64/obj/rstlvfileitem.o temp/linux-g++-64/obj/rstlvimage.o \ + temp/linux-g++-64/obj/rstlvkeys.o temp/linux-g++-64/obj/rstlvkvwide.o \ + temp/linux-g++-64/obj/rstlvtypes.o temp/linux-g++-64/obj/rstlvutil.o \ + temp/linux-g++-64/obj/rstlvdsdv.o temp/linux-g++-64/obj/rsdsdvitems.o \ + temp/linux-g++-64/obj/rstlvbanlist.o \ + temp/linux-g++-64/obj/rsbanlistitems.o \ + temp/linux-g++-64/obj/rsbwctrlitems.o \ + temp/linux-g++-64/obj/rsdiscovery2items.o \ + temp/linux-g++-64/obj/rsheartbeatitems.o \ + temp/linux-g++-64/obj/rsrttitems.o temp/linux-g++-64/obj/p3chatservice.o \ + temp/linux-g++-64/obj/p3msgservice.o temp/linux-g++-64/obj/p3service.o \ + temp/linux-g++-64/obj/p3statusservice.o temp/linux-g++-64/obj/p3dsdv.o \ + temp/linux-g++-64/obj/p3banlist.o temp/linux-g++-64/obj/p3bwctrl.o \ + temp/linux-g++-64/obj/p3discovery2.o temp/linux-g++-64/obj/p3heartbeat.o \ + temp/linux-g++-64/obj/p3rtt.o temp/linux-g++-64/obj/p3turtle.o \ + temp/linux-g++-64/obj/rsturtleitem.o \ + temp/linux-g++-64/obj/folderiterator.o temp/linux-g++-64/obj/rsdebug.o \ + temp/linux-g++-64/obj/rscompress.o temp/linux-g++-64/obj/smallobject.o \ + temp/linux-g++-64/obj/rsdir.o temp/linux-g++-64/obj/rsdiscspace.o \ + temp/linux-g++-64/obj/rsnet.o temp/linux-g++-64/obj/rsnet_ss.o \ + temp/linux-g++-64/obj/extaddrfinder.o temp/linux-g++-64/obj/dnsresolver.o \ + temp/linux-g++-64/obj/rsprint.o temp/linux-g++-64/obj/rsstring.o \ + temp/linux-g++-64/obj/rsthreads.o temp/linux-g++-64/obj/rsversion.o \ + temp/linux-g++-64/obj/rswin.o temp/linux-g++-64/obj/rsaes.o \ + temp/linux-g++-64/obj/rsrandom.o temp/linux-g++-64/obj/rstickevent.o \ + temp/linux-g++-64/obj/UPnPBase.o \ + temp/linux-g++-64/obj/upnphandler_linux.o \ + temp/linux-g++-64/obj/rsnxsitems.o temp/linux-g++-64/obj/rsdataservice.o \ + temp/linux-g++-64/obj/rsgenexchange.o \ + temp/linux-g++-64/obj/rsgxsnetservice.o temp/linux-g++-64/obj/rsgxsdata.o \ + temp/linux-g++-64/obj/rsgxsitems.o \ + temp/linux-g++-64/obj/rsgxsdataaccess.o temp/linux-g++-64/obj/retrodb.o \ + temp/linux-g++-64/obj/contentvalue.o temp/linux-g++-64/obj/rsdbbind.o \ + temp/linux-g++-64/obj/gxssecurity.o temp/linux-g++-64/obj/gxstokenqueue.o \ + temp/linux-g++-64/obj/rsgxsnetutils.o temp/linux-g++-64/obj/rsgxsutil.o \ + temp/linux-g++-64/obj/p3idservice.o temp/linux-g++-64/obj/rsgxsiditems.o \ + temp/linux-g++-64/obj/p3gxscircles.o \ + temp/linux-g++-64/obj/rsgxscircleitems.o \ + temp/linux-g++-64/obj/p3gxsforums.o \ + temp/linux-g++-64/obj/rsgxsforumitems.o \ + temp/linux-g++-64/obj/p3gxschannels.o temp/linux-g++-64/obj/p3gxscommon.o \ + temp/linux-g++-64/obj/rsgxscommentitems.o \ + temp/linux-g++-64/obj/rsgxschannelitems.o temp/linux-g++-64/obj/p3wiki.o \ + temp/linux-g++-64/obj/rswikiitems.o temp/linux-g++-64/obj/p3wire.o \ + temp/linux-g++-64/obj/rswireitems.o temp/linux-g++-64/obj/p3posted.o \ + temp/linux-g++-64/obj/rsposteditems.o \ + temp/linux-g++-64/obj/p3photoservice.o \ + temp/linux-g++-64/obj/rsphotoitems.o" ; + + std::cerr << "Input string: length=" << source_string.length() << std::endl; + std::cerr << "Input string: hash =" << RsDirUtil::sha1sum((uint8_t*)source_string.c_str(),source_string.length()).toStdString() << std::endl; + + uint8_t *output_data ; + uint32_t output_length ; + + CHECK(RsCompress::compress_memory_chunk((uint8_t*)source_string.c_str(),source_string.length(),output_data,output_length)) ; + + std::cerr << "Compressed data: " << std::endl; + std::cerr << " Length = " << output_length << std::endl; + std::cerr << " hash = " << RsDirUtil::sha1sum(output_data,output_length).toStdString() << std::endl; + + std::cerr << "Uncompressing..." << std::endl; + + uint8_t *decomp_output_data=NULL ; + uint32_t decomp_output_length=0 ; + + CHECK(RsCompress::uncompress_memory_chunk(output_data,output_length,decomp_output_data,decomp_output_length)) ; + + std::cerr << "Decompressed data: size=" << decomp_output_length << std::endl; + std::cerr << "Decompressed data: hash=" << RsDirUtil::sha1sum(decomp_output_data,decomp_output_length).toStdString() << std::endl; + + std::string decompress_string((char *)decomp_output_data,decomp_output_length) ; + CHECK(compareStrings(decompress_string, source_string)) ; + + free(decomp_output_data) ; + free(output_data) ; + + FINALREPORT("RSCompress") ; + return TESTRESULT() ; +} + diff --git a/retroshare-gui/src/gui/MessagesDialog.cpp b/retroshare-gui/src/gui/MessagesDialog.cpp index 9c37d0e1b..d37b18f15 100644 --- a/retroshare-gui/src/gui/MessagesDialog.cpp +++ b/retroshare-gui/src/gui/MessagesDialog.cpp @@ -1138,7 +1138,7 @@ void MessagesDialog::insertMessages() if(it->msgflags & RS_MSG_ENCRYPTED) text = tr("Encrypted message. Right-click to decrypt it.") ; else - text = QString::fromStdString(it->title); + text = QString::fromUtf8(it->title.c_str()); item[COLUMN_SUBJECT]->setText(text); item[COLUMN_SUBJECT]->setData(text + dateString, ROLE_SORT); @@ -1206,7 +1206,7 @@ void MessagesDialog::insertMessages() if (gotInfo || rsMsgs->getMessage(it->msgId, msgInfo)) { gotInfo = true; QTextDocument doc; - doc.setHtml(QString::fromStdString(msgInfo.msg)); + doc.setHtml(QString::fromUtf8(msgInfo.msg.c_str())); item[COLUMN_CONTENT]->setText(doc.toPlainText().replace(QString("\n"), QString(" "))); } else { std::cerr << "MessagesDialog::insertMsgTxtAndFiles() Couldn't find Msg" << std::endl; From 4b9378aadda0f3b80deec3ef830ab78f29cba8a8 Mon Sep 17 00:00:00 2001 From: csoler Date: Sun, 6 Oct 2013 20:16:58 +0000 Subject: [PATCH 39/83] adding missing files git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@6810 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/util/rscompress.cc | 190 +++++++++++++++++++++++++++ libretroshare/src/util/rscompress.h | 34 +++++ 2 files changed, 224 insertions(+) create mode 100644 libretroshare/src/util/rscompress.cc create mode 100644 libretroshare/src/util/rscompress.h diff --git a/libretroshare/src/util/rscompress.cc b/libretroshare/src/util/rscompress.cc new file mode 100644 index 000000000..1d62b4c2a --- /dev/null +++ b/libretroshare/src/util/rscompress.cc @@ -0,0 +1,190 @@ +/* + * libretroshare/src/utils: rscompress.cc + * + * Basic memory chunk compression, based on openpgp-sdk + * + * Copyright 2013 by Cyril Soler + * + * 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 "csoler@users.sourceforge.net". + * + */ + +#include +#include +#include +#include +#include +#include "rscompress.h" +#include "zlib.h" + +// 16K buffer size. +// +static const unsigned int CHUNK = 16384u ; + +bool RsCompress::compress_memory_chunk(const uint8_t *input_mem,const uint32_t input_size,uint8_t *& output_mem,uint32_t& output_size) +{ + + uint32_t remaining_input = input_size ; + uint32_t output_offset = 0 ; + uint32_t input_offset = 0 ; + output_size = 1024 ; + output_mem = (uint8_t*)malloc(output_size) ; + + int ret, flush; + unsigned have; + int level = 9 ; + z_stream strm; + unsigned char in[CHUNK]; + unsigned char out[CHUNK]; + /* allocate deflate state */ + strm.zalloc = Z_NULL; + strm.zfree = Z_NULL; + strm.opaque = Z_NULL; + + ret = deflateInit(&strm, level); + if (ret != Z_OK) + return false; + + /* compress until end of file */ + do + { + uint32_t available_in = std::min(CHUNK,remaining_input) ; + memcpy(in,input_mem+input_offset,available_in) ; + strm.avail_in = available_in ; + remaining_input -= available_in ; + input_offset += available_in ; + + flush = /*feof(source)*/ remaining_input ? Z_NO_FLUSH: Z_FINISH ; + strm.next_in = in; + + /* run deflate() on input until output buffer not full, finish + compression if all of source has been read in */ + do + { + strm.avail_out = CHUNK; + strm.next_out = out; + ret = deflate(&strm, flush); /* no bad return value */ + assert(ret != Z_STREAM_ERROR); /* state not clobbered */ + have = CHUNK - strm.avail_out; + + if(output_size < have+output_offset) + { + //std::cerr << "Growing outputbuffer from " << output_size << " to " << have+output_offset << std::endl; + output_mem = (uint8_t*)realloc(output_mem,have+output_offset) ; + output_size = have+output_offset ; + } + + memcpy(output_mem+output_offset,out,have) ; + output_offset += have ; + + //std::cerr << "Copying " << have << " bytes to output. New offset=" << output_offset << std::endl; + } while (strm.avail_out == 0); + assert(strm.avail_in == 0); /* all input will be used */ + + /* done when last data in file processed */ + } while (flush != Z_FINISH); + assert(ret == Z_STREAM_END); /* stream will be complete */ + + /* clean up and return */ + (void)deflateEnd(&strm); + + output_size = output_offset ; + + return true ; +} + +bool RsCompress::uncompress_memory_chunk(const uint8_t *input_mem,const uint32_t input_size,uint8_t *& output_mem,uint32_t& output_size) +{ + uint32_t remaining_input = input_size ; + output_size = input_size ; + uint32_t output_offset = 0 ; + uint32_t input_offset = 0 ; + output_mem = (uint8_t*)malloc(output_size) ; + + int ret; + unsigned have; + z_stream strm; + unsigned char in[CHUNK]; + unsigned char out[CHUNK]; + + /* allocate inflate state */ + strm.zalloc = Z_NULL; + strm.zfree = Z_NULL; + strm.opaque = Z_NULL; + strm.avail_in = 0; + strm.next_in = Z_NULL; + ret = inflateInit(&strm); + if (ret != Z_OK) + return ret; + + /* decompress until deflate stream ends or end of file */ + do + { + uint32_t available_in = std::min(CHUNK,remaining_input) ; + memcpy(in,input_mem,available_in) ; + strm.avail_in = available_in ; + remaining_input -= available_in ; + input_offset += available_in ; + + if (strm.avail_in == 0) + break; + + strm.next_in = in; + /* run inflate() on input until output buffer not full */ + do { + strm.avail_out = CHUNK; + strm.next_out = out; + + ret = inflate(&strm, Z_NO_FLUSH); + assert(ret != Z_STREAM_ERROR); /* state not clobbered */ + switch (ret) { + case Z_NEED_DICT: + ret = Z_DATA_ERROR; /* and fall through */ + case Z_DATA_ERROR: + case Z_MEM_ERROR: + (void)inflateEnd(&strm); + return ret; + } + + + have = CHUNK - strm.avail_out; + + if(output_size < have+output_offset) + { + output_mem = (uint8_t*)realloc(output_mem,have+output_offset) ; + output_size = have+output_offset ; + } + + memcpy(output_mem+output_offset,out,have) ; + output_offset += have ; + + } while (strm.avail_out == 0); + /* done when inflate() says it's done */ + } while (ret != Z_STREAM_END); + + /* clean up and return */ + (void)inflateEnd(&strm); + + output_size = output_offset ; + return ret == Z_STREAM_END ; +} + + + + + + diff --git a/libretroshare/src/util/rscompress.h b/libretroshare/src/util/rscompress.h new file mode 100644 index 000000000..0d11c3f47 --- /dev/null +++ b/libretroshare/src/util/rscompress.h @@ -0,0 +1,34 @@ +/* + * libretroshare/src/utils: rscompress.h + * + * Basic memory chunk compression, based on openpgp-sdk + * + * Copyright 2013 by Cyril Soler + * + * 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 "csoler@users.sourceforge.net". + * + */ + +#pragma once + +class RsCompress +{ + public: + static bool compress_memory_chunk(const uint8_t *input_mem,const uint32_t input_size,uint8_t *& output_mem,uint32_t& output_size) ; + static bool uncompress_memory_chunk(const uint8_t *input_mem,const uint32_t input_size,uint8_t *& output_mem,uint32_t& output_size) ; +}; + From 25d721b6fe4a6d75100d57a1e7280d551b03bac9 Mon Sep 17 00:00:00 2001 From: chrisparker126 Date: Sun, 6 Oct 2013 21:07:31 +0000 Subject: [PATCH 40/83] Code change to test group edit - can modify group names and content now Group edit code fixes git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.5-gxs_finale@6811 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/gxs/gxssecurity.cc | 4 +- libretroshare/src/gxs/gxssecurity.h | 4 +- libretroshare/src/gxs/rsgenexchange.cc | 114 +++++++++++++----- libretroshare/src/gxs/rsgenexchange.h | 20 +-- .../src/retroshare/rsgxsifacetypes.h | 23 +--- libretroshare/src/services/p3gxsforums.cc | 5 +- retroshare-gui/src/gui/gxs/GxsGroupDialog.cpp | 11 +- retroshare-gui/src/gui/gxs/GxsGroupDialog.h | 14 ++- .../src/gui/gxsforums/GxsForumGroupDialog.cpp | 11 +- .../src/gui/gxsforums/GxsForumGroupDialog.h | 1 + 10 files changed, 133 insertions(+), 74 deletions(-) diff --git a/libretroshare/src/gxs/gxssecurity.cc b/libretroshare/src/gxs/gxssecurity.cc index ea820e1b4..f32e9f150 100644 --- a/libretroshare/src/gxs/gxssecurity.cc +++ b/libretroshare/src/gxs/gxssecurity.cc @@ -38,7 +38,7 @@ GxsSecurity::~GxsSecurity() { } -RSA *GxsSecurity::extractPublicKey(RsTlvSecurityKey& key) +RSA *GxsSecurity::extractPublicKey(const RsTlvSecurityKey& key) { const unsigned char *keyptr = (const unsigned char *) key.keyData.bin_data; long keylen = key.keyData.bin_len; @@ -489,7 +489,7 @@ void GxsSecurity::setRSAPrivateKey(RsTlvSecurityKey & key, RSA *rsa_priv) key.keyId = keyId; } -RSA *GxsSecurity::extractPrivateKey(RsTlvSecurityKey & key) +RSA *GxsSecurity::extractPrivateKey(const RsTlvSecurityKey & key) { const unsigned char *keyptr = (const unsigned char *) key.keyData.bin_data; long keylen = key.keyData.bin_len; diff --git a/libretroshare/src/gxs/gxssecurity.h b/libretroshare/src/gxs/gxssecurity.h index 2bccf542f..4ebd122f4 100644 --- a/libretroshare/src/gxs/gxssecurity.h +++ b/libretroshare/src/gxs/gxssecurity.h @@ -51,14 +51,14 @@ public: * @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); + static RSA *extractPublicKey(const 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); + static RSA *extractPrivateKey(const RsTlvSecurityKey &key); /*! * stores the rsa public key in a RsTlvSecurityKey diff --git a/libretroshare/src/gxs/rsgenexchange.cc b/libretroshare/src/gxs/rsgenexchange.cc index db29576ca..db4a4c214 100644 --- a/libretroshare/src/gxs/rsgenexchange.cc +++ b/libretroshare/src/gxs/rsgenexchange.cc @@ -118,6 +118,8 @@ void RsGenExchange::tick() publishMsgs(); + processGroupUpdatePublish(); + processRecvdData(); if(!mNotifications.empty()) @@ -278,6 +280,54 @@ void RsGenExchange::generateGroupKeys(RsTlvSecurityKeySet& privatekeySet, } } +void RsGenExchange::generatePublicFromPrivateKeys(const RsTlvSecurityKeySet &privatekeySet, + RsTlvSecurityKeySet &publickeySet) +{ + + // actually just copy settings of one key except mark its key flags public + + typedef std::map keyMap; + const keyMap& allKeys = privatekeySet.keys; + keyMap::const_iterator cit = allKeys.begin(); + bool adminFound = false, publishFound = false; + for(; cit != allKeys.end(); cit++) + { + const RsTlvSecurityKey& privKey = cit->second; + if(privKey.keyFlags & RSTLV_KEY_TYPE_FULL) + { + RsTlvSecurityKey pubKey; + + pubKey = privKey; + + RSA *rsaPrivKey = NULL, *rsaPubKey = NULL; + + rsaPrivKey = GxsSecurity::extractPrivateKey(privKey); + + if(rsaPrivKey) + rsaPubKey = RSAPublicKey_dup(rsaPrivKey); + + if(rsaPrivKey && rsaPubKey) + { + GxsSecurity::setRSAPublicKey(pubKey, rsaPubKey); + + if(pubKey.keyFlags & RSTLV_KEY_DISTRIB_ADMIN) + pubKey.keyFlags = RSTLV_KEY_DISTRIB_ADMIN | RSTLV_KEY_TYPE_PUBLIC_ONLY; + + if(pubKey.keyFlags & RSTLV_KEY_DISTRIB_PRIVATE) + pubKey.keyFlags = RSTLV_KEY_DISTRIB_PRIVATE | RSTLV_KEY_TYPE_PUBLIC_ONLY; + + publickeySet.keys.insert(std::make_pair(pubKey.keyId, pubKey)); + } + + if(rsaPrivKey) + RSA_free(rsaPrivKey); + + if(rsaPubKey) + RSA_free(rsaPubKey); + } + } +} + uint8_t RsGenExchange::createGroup(RsNxsGrp *grp, RsTlvSecurityKeySet& privateKeySet, RsTlvSecurityKeySet& publicKeySet) { std::cerr << "RsGenExchange::createGroup()"; @@ -1818,6 +1868,9 @@ void RsGenExchange::processGroupUpdatePublish() grpMeta.insert(std::make_pair(groupId, (RsGxsGrpMetaData*)(NULL))); } + if(grpMeta.empty()) + return; + mDataStore->retrieveGxsGrpMetaData(grpMeta); // now @@ -1832,20 +1885,23 @@ void RsGenExchange::processGroupUpdatePublish() assignMetaUpdates(gup.grpItem->meta, gup.mUpdateMeta); GxsGrpPendingSign ggps(gup.grpItem, ggps.mToken); - bool split = splitKeys(meta->keys, ggps.mPrivateKeys, ggps.mPublicKeys); + bool publishAndAdminPrivatePresent = checkKeys(meta->keys); - if(split) + if(publishAndAdminPrivatePresent) { - ggps.mHaveKeys = true; - ggps.mStartTS = time(NULL); - ggps.mLastAttemptTS = 0; - mGrpsToPublish.push_back(ggps); + ggps.mPrivateKeys = meta->keys; + generatePublicFromPrivateKeys(ggps.mPrivateKeys, ggps.mPublicKeys); + ggps.mHaveKeys = true; + ggps.mStartTS = time(NULL); + ggps.mLastAttemptTS = 0; + ggps.mIsUpdate = true; + mGrpsToPublish.push_back(ggps); }else { - delete gup.grpItem; - mDataAccess->updatePublicRequestStatus(gup.mToken, RsTokenService::GXS_REQUEST_V2_STATUS_FAILED); + delete gup.grpItem; + mDataAccess->updatePublicRequestStatus(gup.mToken, RsTokenService::GXS_REQUEST_V2_STATUS_FAILED); } - + delete meta; } mGroupUpdatePublish.clear(); @@ -1853,43 +1909,39 @@ void RsGenExchange::processGroupUpdatePublish() void RsGenExchange::assignMetaUpdates(RsGroupMetaData& meta, const RsGxsGroupUpdateMeta metaUpdate) const { - const RsGxsGroupUpdateMeta::GxsMetaUpdate* updates; + const RsGxsGroupUpdateMeta::GxsMetaUpdate* updates = metaUpdate.getUpdates(); RsGxsGroupUpdateMeta::GxsMetaUpdate::const_iterator mit = updates->begin(); for(; mit != updates->end(); mit++) { - const UpdateItem* item = mit->second; - RsGxsGroupUpdateMeta::UpdateType utype = mit->first; - if(utype == RsGxsGroupUpdateMeta::NAME) - { - const StringUpdateItem* sitem = NULL; - - if((sitem = dynamic_cast(item)) != NULL) - { - meta.mGroupName = sitem->getUpdate(); - } - } + if(mit->first == RsGxsGroupUpdateMeta::NAME) + meta.mGroupName = mit->second; } } -bool RsGenExchange::splitKeys(const RsTlvSecurityKeySet& keySet, RsTlvSecurityKeySet& privateKeySet, RsTlvSecurityKeySet& publicKeySet) +bool RsGenExchange::checkKeys(const RsTlvSecurityKeySet& keySet) { typedef std::map keyMap; const keyMap& allKeys = keySet.keys; keyMap::const_iterator cit = allKeys.begin(); - + bool adminFound = false, publishFound = false; for(; cit != allKeys.end(); cit++) { - const RsTlvSecurityKey& key = cit->second; - if(key.keyFlags & RSTLV_KEY_TYPE_PUBLIC_ONLY) - publicKeySet.keys.insert(std::make_pair(key.keyId, key)); - else if(key.keyFlags & RSTLV_KEY_TYPE_FULL) - privateKeySet.keys.insert(std::make_pair(key.keyId, key)); + const RsTlvSecurityKey& key = cit->second; + if(key.keyFlags & RSTLV_KEY_TYPE_FULL) + { + if(key.keyFlags & RSTLV_KEY_DISTRIB_ADMIN) + adminFound = true; + + if(key.keyFlags & RSTLV_KEY_DISTRIB_PRIVATE) + publishFound = true; + + } } // user must have both private and public parts of publish and admin keys - return (privateKeySet.keys.size() == 2) && (publicKeySet.keys.size() == 2); + return adminFound && publishFound; } void RsGenExchange::publishGrps() @@ -1962,10 +2014,6 @@ void RsGenExchange::publishGrps() // get group id from private admin key id grpItem->meta.mGroupId = grp->grpId = privAdminKey.keyId; - // what!? this will remove the private keys! - privatekeySet.keys.insert(publicKeySet.keys.begin(), - publicKeySet.keys.end()); - ServiceCreate_Return ret = service_CreateGroup(grpItem, privatekeySet); diff --git a/libretroshare/src/gxs/rsgenexchange.h b/libretroshare/src/gxs/rsgenexchange.h index 054c19ce6..b495d7922 100644 --- a/libretroshare/src/gxs/rsgenexchange.h +++ b/libretroshare/src/gxs/rsgenexchange.h @@ -712,11 +712,20 @@ private: /*! * Generate a set of keys that can define a GXS group * @param privatekeySet contains private generated keys - * @param privatekeySet contains public generated keys (counterpart of private) + * @param publickeySet contains public generated keys (counterpart of private) * @param genPublicKeys should publish key pair also be generated */ void generateGroupKeys(RsTlvSecurityKeySet& privatekeySet, RsTlvSecurityKeySet& publickeySet, bool genPublishKeys); + /*! + * Generate public set of keys from their private counterparts + * No keys will be generated if one fails + * @param privatekeySet contains private generated keys + * @param publickeySet contains public generated keys (counterpart of private) + * @return false if key gen failed for a key set + */ + void generatePublicFromPrivateKeys(const RsTlvSecurityKeySet& privatekeySet, RsTlvSecurityKeySet& publickeySet); + /*! * Attempts to validate msg signatures * @param msg message to be validated @@ -763,14 +772,11 @@ private: bool updateValid(RsGxsGrpMetaData& oldGrp, RsNxsGrp& newGrp) const; /*! - * convenience function for splitting key sets into private and public + * convenience function for checking private publish and admin keys are present * @param keySet The keys set to split into a private and public set - * @param privateKeySet contains the publish and admin private keys - * @param publicKeySet contains the publish and admin public keys - * @return false, if 2 private and public keys are not found in keySet + * @return false, if private admin and publish keys cannot be found, true otherwise */ - bool splitKeys(const RsTlvSecurityKeySet& keySet, RsTlvSecurityKeySet& privateKeySet, - RsTlvSecurityKeySet& publicKeySet); + bool checkKeys(const RsTlvSecurityKeySet& keySet); /*! * Convenience function for assigning the meta update items to the actual group meta diff --git a/libretroshare/src/retroshare/rsgxsifacetypes.h b/libretroshare/src/retroshare/rsgxsifacetypes.h index a6dacd329..f2181e363 100644 --- a/libretroshare/src/retroshare/rsgxsifacetypes.h +++ b/libretroshare/src/retroshare/rsgxsifacetypes.h @@ -169,28 +169,18 @@ public: // expand as support is added for other utypes enum UpdateType { DESCRIPTION, NAME }; - RsGxsGroupUpdateMeta(const std::string& groupId); - ~RsGxsGroupUpdateMeta() - { - GxsMetaUpdate::iterator mit = mUpdates.begin(); - for(; mit != mUpdates.end(); mit++) - delete mit->second; - } + RsGxsGroupUpdateMeta(const std::string& groupId) : mGroupId(groupId) {} - typedef std::map GxsMetaUpdate; + typedef std::map GxsMetaUpdate; /*! * Only one item of a utype can exist * @param utype the type of meta update * @param item update item containing the change value */ - void setMetaUpdate(UpdateType utype, UpdateItem* item) + void setMetaUpdate(UpdateType utype, const std::string& update) { - GxsMetaUpdate::iterator mit; - if ((mit = mUpdates.find(utype)) != mUpdates.end()) - mUpdates[utype] = item; - else - delete mUpdates[utype]; + mUpdates[utype] = update; } /*! @@ -199,9 +189,8 @@ public: */ bool removeUpdateType(UpdateType utype){ return mUpdates.erase(utype) == 1; } - const GxsMetaUpdate* getUpdate() { return &mUpdates; } - - const std::string& getGroupId() { return mGroupId; } + const GxsMetaUpdate* getUpdates() const { return &mUpdates; } + const std::string& getGroupId() const { return mGroupId; } private: diff --git a/libretroshare/src/services/p3gxsforums.cc b/libretroshare/src/services/p3gxsforums.cc index 1e8fd1a65..7b7766bd2 100644 --- a/libretroshare/src/services/p3gxsforums.cc +++ b/libretroshare/src/services/p3gxsforums.cc @@ -219,12 +219,13 @@ bool p3GxsForums::updateGroup(uint32_t &token, RsGxsGroupUpdateMeta& meta, RsGxs { std::cerr << "p3GxsForums::createGroup()" << std::endl; - if(group.mMeta.mGroupId.empty()) + if(meta.getGroupId().empty()) return false; RsGxsForumGroupItem* grpItem = new RsGxsForumGroupItem(); grpItem->mGroup = group; - grpItem->meta = group.mMeta; + grpItem->meta = group.mMeta; + grpItem->meta.mGroupId = meta.getGroupId(); RsGenExchange::updateGroup(token, meta, grpItem); return true; diff --git a/retroshare-gui/src/gui/gxs/GxsGroupDialog.cpp b/retroshare-gui/src/gui/gxs/GxsGroupDialog.cpp index 81f314718..d3f93cc24 100644 --- a/retroshare-gui/src/gui/gxs/GxsGroupDialog.cpp +++ b/retroshare-gui/src/gui/gxs/GxsGroupDialog.cpp @@ -343,15 +343,10 @@ void GxsGroupDialog::editGroup() } uint32_t token; - RsGroupMetaData meta; + RsGxsGroupUpdateMeta updateMeta(mGrpMeta.mGroupId); + updateMeta.setMetaUpdate(RsGxsGroupUpdateMeta::NAME, std::string(name.toUtf8())); - // Fill in the MetaData as best we can. - meta.mGroupName = std::string(name.toUtf8()); - - meta.mGroupFlags = flags; - meta.mSignFlags = getGroupSignFlags(); - - if (service_CreateGroup(token, meta)) + if (service_EditGroup(token, updateMeta)) { // get the Queue to handle response. if(mTokenQueue != NULL) diff --git a/retroshare-gui/src/gui/gxs/GxsGroupDialog.h b/retroshare-gui/src/gui/gxs/GxsGroupDialog.h index 5f71ee364..35db177d0 100644 --- a/retroshare-gui/src/gui/gxs/GxsGroupDialog.h +++ b/retroshare-gui/src/gui/gxs/GxsGroupDialog.h @@ -163,13 +163,21 @@ protected: void setUiText(UiType uiType, const QString &text); /*! - * Main purpose is to help tansfer meta data to service - * + * It is up to the service to do the actual group creation + * Service can also modify initial meta going into group * @param token This should be set to the token retrieved * @param meta The deriving GXS service should set their grp meta to this value */ virtual bool service_CreateGroup(uint32_t &token, const RsGroupMetaData &meta) = 0; + /*! + * It is up to the service to do the actual group editing + * TODO: make pure virtual + * @param token This should be set to the token retrieved + * @param meta The deriving GXS service should set their grp meta to this value + */ + virtual bool service_EditGroup(uint32_t &token, RsGxsGroupUpdateMeta &updateMeta) {} + /*! * This returns a group logo from the ui \n * Should be calleld by deriving service @@ -216,6 +224,8 @@ private: uint32_t mReadonlyFlags; uint32_t mDefaultsFlags; + protected: + /** Qt Designer generated object */ Ui::GxsGroupDialog ui; }; diff --git a/retroshare-gui/src/gui/gxsforums/GxsForumGroupDialog.cpp b/retroshare-gui/src/gui/gxsforums/GxsForumGroupDialog.cpp index 47edec932..77d0611ac 100644 --- a/retroshare-gui/src/gui/gxsforums/GxsForumGroupDialog.cpp +++ b/retroshare-gui/src/gui/gxsforums/GxsForumGroupDialog.cpp @@ -95,8 +95,17 @@ bool GxsForumGroupDialog::service_CreateGroup(uint32_t &token, const RsGroupMeta // Specific Function. RsGxsForumGroup grp; grp.mMeta = meta; - //grp.mDescription = std::string(desc.toUtf8()); + grp.mDescription = std::string(ui.groupDesc->toPlainText().toUtf8()); rsGxsForums->createGroup(token, grp); return true; } + +bool GxsForumGroupDialog::service_EditGroup(uint32_t &token, RsGxsGroupUpdateMeta &updateMeta) +{ + RsGxsForumGroup grp; + grp.mDescription = std::string(ui.groupDesc->toPlainText().toUtf8()); + + rsGxsForums->updateGroup(token, updateMeta, grp); + return true; +} diff --git a/retroshare-gui/src/gui/gxsforums/GxsForumGroupDialog.h b/retroshare-gui/src/gui/gxsforums/GxsForumGroupDialog.h index 96d431319..777139efb 100644 --- a/retroshare-gui/src/gui/gxsforums/GxsForumGroupDialog.h +++ b/retroshare-gui/src/gui/gxsforums/GxsForumGroupDialog.h @@ -37,6 +37,7 @@ protected: virtual void initUi(); virtual QPixmap serviceImage(); virtual bool service_CreateGroup(uint32_t &token, const RsGroupMetaData &meta); + virtual bool service_EditGroup(uint32_t &token, RsGxsGroupUpdateMeta &updateMeta); }; #endif From fc1b7fcb5ceb085814aa1ac6d1de8e3b10685736 Mon Sep 17 00:00:00 2001 From: chrisparker126 Date: Sun, 13 Oct 2013 21:49:17 +0000 Subject: [PATCH 41/83] more debugging of group update - did not correctly perform sync - admin signature validation was being skipped! - still niggly issue with admin signature validation git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.5-gxs_finale@6829 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/gxs/rsdataservice.cc | 5 ++--- libretroshare/src/gxs/rsgenexchange.cc | 25 ++++++++++++++++++++---- libretroshare/src/gxs/rsgxsnetservice.cc | 7 +++---- 3 files changed, 26 insertions(+), 11 deletions(-) diff --git a/libretroshare/src/gxs/rsdataservice.cc b/libretroshare/src/gxs/rsdataservice.cc index a334d090f..9b7769ed8 100644 --- a/libretroshare/src/gxs/rsdataservice.cc +++ b/libretroshare/src/gxs/rsdataservice.cc @@ -663,9 +663,8 @@ int RsDataService::updateGroup(std::map &grp) if(!validSize(grpPtr)) continue; std::string grpFile = mServiceDir + "/" + grpPtr->grpId; - std::fstream ostrm(grpFile.c_str(), std::ios::binary | std::ios::app | std::ios::trunc); - ostrm.seekg(0, std::ios::end); // go to end to append - uint32_t offset = ostrm.tellg(); // get fill offset + std::fstream ostrm(grpFile.c_str(), std::ios::binary | std::ios::trunc); + uint32_t offset = 0; // get file offset /*! * STORE file offset, file length, file name, diff --git a/libretroshare/src/gxs/rsgenexchange.cc b/libretroshare/src/gxs/rsgenexchange.cc index db4a4c214..da9a6d080 100644 --- a/libretroshare/src/gxs/rsgenexchange.cc +++ b/libretroshare/src/gxs/rsgenexchange.cc @@ -316,6 +316,8 @@ void RsGenExchange::generatePublicFromPrivateKeys(const RsTlvSecurityKeySet &pri if(pubKey.keyFlags & RSTLV_KEY_DISTRIB_PRIVATE) pubKey.keyFlags = RSTLV_KEY_DISTRIB_PRIVATE | RSTLV_KEY_TYPE_PUBLIC_ONLY; + pubKey.endTS = pubKey.startTS + 60 * 60 * 24 * 365 * 5; /* approx 5 years */ + publickeySet.keys.insert(std::make_pair(pubKey.keyId, pubKey)); } @@ -2384,14 +2386,14 @@ void RsGenExchange::processRecvdGroups() meta->mGroupStatus = GXS_SERV::GXS_GRP_STATUS_UNPROCESSED | GXS_SERV::GXS_GRP_STATUS_UNREAD; meta->mSubscribeFlags = GXS_SERV::GROUP_SUBSCRIBE_NOT_SUBSCRIBED; - if(meta->mCircleType == GXS_CIRCLE_TYPE_YOUREYESONLY) - meta->mOriginator = grp->PeerId(); - computeHash(grp->grp, meta->mHash); // now check if group already existss if(std::find(existingGrpIds.begin(), existingGrpIds.end(), grp->grpId) == existingGrpIds.end()) { + if(meta->mCircleType == GXS_CIRCLE_TYPE_YOUREYESONLY) + meta->mOriginator = grp->PeerId(); + grps.insert(std::make_pair(grp, meta)); grpIds.push_back(grp->grpId); } @@ -2455,6 +2457,9 @@ void RsGenExchange::processRecvdGroups() void RsGenExchange::performUpdateValidation() { + + RsStackMutex stack(mGenMtx); + #ifdef GXS_GENX_DEBUG std::cerr << "RsGenExchange::performUpdateValidation() " << std::endl; #endif @@ -2492,7 +2497,19 @@ void RsGenExchange::performUpdateValidation() for(; vit != mGroupUpdates.end(); vit++) { GroupUpdate& gu = *vit; - grps.insert(std::make_pair(gu.newGrp, gu.newGrp->metaData)); + + if(gu.validUpdate) + { + if(gu.newGrp->metaData->mCircleType == GXS_CIRCLE_TYPE_YOUREYESONLY) + gu.newGrp->metaData->mOriginator = gu.newGrp->PeerId(); + + grps.insert(std::make_pair(gu.newGrp, gu.newGrp->metaData)); + } + else + { + delete gu.newGrp; + } + delete gu.oldGrpMeta; } diff --git a/libretroshare/src/gxs/rsgxsnetservice.cc b/libretroshare/src/gxs/rsgxsnetservice.cc index c0e4c712d..c1690e96a 100644 --- a/libretroshare/src/gxs/rsgxsnetservice.cc +++ b/libretroshare/src/gxs/rsgxsnetservice.cc @@ -1383,12 +1383,11 @@ void RsGxsNetService::locked_genReqGrpTransaction(NxsTransaction* tr) const std::string& grpId = grpSyncItem->grpId; metaIter = grpMetaMap.find(grpId); bool haveItem = metaIter != grpMetaMap.end(); - bool latestItem = false; + bool latestVersion = false; - if(!haveItem) - latestItem = grpSyncItem->publishTs > metaIter->second->mPublishTs; + latestVersion = grpSyncItem->publishTs > metaIter->second->mPublishTs; - if(haveItem && latestItem){ + if(!haveItem || (haveItem && latestVersion) ){ // determine if you need to check reputation bool checkRep = !grpSyncItem->authorId.empty(); From 19d7faa572b8fb03a55293f86cde040227c27196 Mon Sep 17 00:00:00 2001 From: chrisparker126 Date: Mon, 14 Oct 2013 22:03:11 +0000 Subject: [PATCH 42/83] finally found group signature bug, was aliasing signature in validateGrp call (perfect example of why one should use const)! git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.5-gxs_finale@6831 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/gxs/rsgenexchange.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libretroshare/src/gxs/rsgenexchange.cc b/libretroshare/src/gxs/rsgenexchange.cc index da9a6d080..54899fe0e 100644 --- a/libretroshare/src/gxs/rsgenexchange.cc +++ b/libretroshare/src/gxs/rsgenexchange.cc @@ -2532,7 +2532,7 @@ bool RsGenExchange::updateValid(RsGxsGrpMetaData& oldGrpMeta, RsNxsGrp& newGrp) return false; } - RsTlvKeySignature& adminSign = mit->second; + RsTlvKeySignature adminSign = mit->second; std::map& keys = oldGrpMeta.keys.keys; std::map::iterator keyMit = keys.find(oldGrpMeta.mGroupId); From fc588614478762128b469d85f942d167c5bcbf43 Mon Sep 17 00:00:00 2001 From: drbob Date: Sun, 20 Oct 2013 09:43:30 +0000 Subject: [PATCH 43/83] Added RecognTags. - items are described in serialiser. - util functions in util/rsrecogn.cc are used to manipulate it. - these are attached to GxsIds, with new interface fns. - Associated Signing Code is in a separate program. Other Tweaks. - Added RsMemCache::erase() - Added RsTlvStringSetRef - Fix for rsturtleitem (already added to trunk). - Formatting and debugging. Status: There is a bug in RsGenExchange::updateGroup which prevents full testing, The basic generation, parsing and validation functions have been tested and are ok. The processing as part of p3IdService still needs to be fully debugged. git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.5-gxs_finale@6854 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/libretroshare.pro | 6 +- .../src/retroshare/rsgxsifacetypes.h | 2 +- libretroshare/src/retroshare/rsidentity.h | 45 + libretroshare/src/serialiser/rsgxsiditems.cc | 20 + libretroshare/src/serialiser/rsgxsitems.cc | 3 +- .../src/serialiser/rsgxsrecognitems.cc | 600 ++++++++++++ .../src/serialiser/rsgxsrecognitems.h | 152 +++ libretroshare/src/serialiser/rsserviceids.h | 2 + libretroshare/src/serialiser/rstlvbase.h | 1 + libretroshare/src/serialiser/rstlvtypes.cc | 159 +++ libretroshare/src/serialiser/rstlvtypes.h | 16 + libretroshare/src/services/p3gxsforums.cc | 2 +- libretroshare/src/services/p3idservice.cc | 921 ++++++++++++++++-- libretroshare/src/services/p3idservice.h | 69 +- libretroshare/src/services/p3posted.cc | 1 - libretroshare/src/turtle/rsturtleitem.cc | 4 +- libretroshare/src/util/rsmemcache.h | 42 + libretroshare/src/util/rsrecogn.cc | 640 ++++++++++++ libretroshare/src/util/rsrecogn.h | 61 ++ 19 files changed, 2645 insertions(+), 101 deletions(-) create mode 100644 libretroshare/src/serialiser/rsgxsrecognitems.cc create mode 100644 libretroshare/src/serialiser/rsgxsrecognitems.h create mode 100644 libretroshare/src/util/rsrecogn.cc create mode 100644 libretroshare/src/util/rsrecogn.h diff --git a/libretroshare/src/libretroshare.pro b/libretroshare/src/libretroshare.pro index de0cfed2a..42fc6e8f8 100644 --- a/libretroshare/src/libretroshare.pro +++ b/libretroshare/src/libretroshare.pro @@ -7,7 +7,7 @@ CONFIG += test_voip #GXS Stuff. # This should be disabled for releases until further notice. -#CONFIG += gxs debug +CONFIG += gxs debug # Beware: All data of the stripped services are lost DEFINES *= PQI_DISABLE_TUNNEL @@ -387,6 +387,7 @@ HEADERS += serialiser/rsbaseitems.h \ serialiser/rstlvbanlist.h \ serialiser/rsbanlistitems.h \ serialiser/rsbwctrlitems.h \ + serialiser/rsgxsrecognitems.h \ serialiser/rstunnelitems.h HEADERS += services/p3channels.h \ @@ -430,6 +431,7 @@ HEADERS += util/folderiterator.h \ util/pugiconfig.h \ util/rsmemcache.h \ util/rstickevent.h \ + util/rsrecogn.h \ SOURCES += dbase/cachestrapper.cc \ dbase/fimonitor.cc \ @@ -529,6 +531,7 @@ SOURCES += serialiser/rsbaseitems.cc \ serialiser/rstlvbanlist.cc \ serialiser/rsbanlistitems.cc \ serialiser/rsbwctrlitems.cc \ + serialiser/rsgxsrecognitems.cc \ serialiser/rstunnelitems.cc SOURCES += services/p3channels.cc \ @@ -571,6 +574,7 @@ SOURCES += util/folderiterator.cc \ util/rsaes.cc \ util/rsrandom.cc \ util/rstickevent.cc \ + util/rsrecogn.cc \ upnp_miniupnpc { diff --git a/libretroshare/src/retroshare/rsgxsifacetypes.h b/libretroshare/src/retroshare/rsgxsifacetypes.h index f2181e363..830df9f52 100644 --- a/libretroshare/src/retroshare/rsgxsifacetypes.h +++ b/libretroshare/src/retroshare/rsgxsifacetypes.h @@ -47,7 +47,7 @@ public: mGroupStatus = 0; mCircleType = 0; - //mPublishTs = 0; + mPublishTs = 0; } void operator =(const RsGxsGrpMetaData& rGxsMeta); diff --git a/libretroshare/src/retroshare/rsidentity.h b/libretroshare/src/retroshare/rsidentity.h index 4b78f0a38..a1891e6ac 100644 --- a/libretroshare/src/retroshare/rsidentity.h +++ b/libretroshare/src/retroshare/rsidentity.h @@ -55,6 +55,8 @@ extern RsIdentity *rsIdentity; #define RSID_RELATION_OTHER 0x0008 #define RSID_RELATION_UNKNOWN 0x0010 +#define RSRECOGN_MAX_TAGINFO 5 + std::string rsIdTypeToString(uint32_t idtype); class RsGxsIdGroup @@ -82,6 +84,9 @@ class RsGxsIdGroup std::string mPgpIdHash; std::string mPgpIdSign; // Need a signature as proof - otherwise anyone could add others Hashes. + // Recognition Strings. MAX# defined above. + std::list mRecognTags; + // Not Serialised - for GUI's benefit. bool mPgpKnown; std::string mPgpId; @@ -163,6 +168,36 @@ class RsIdOpinion typedef std::string RsGxsId; // TMP. => +class RsRecognTag +{ + public: + RsRecognTag(uint16_t tc, uint16_t tt, bool v) + :tag_class(tc), tag_type(tt), valid(v) { return; } + uint16_t tag_class; + uint16_t tag_type; + bool valid; +}; + + +class RsRecognTagDetails +{ + public: + RsRecognTagDetails() + :valid_from(0), valid_to(0), tag_class(0), tag_type(0), + is_valid(false), is_pending(false) { return; } + + time_t valid_from; + time_t valid_to; + uint16_t tag_class; + uint16_t tag_type; + + std::string signer; + + bool is_valid; + bool is_pending; +}; + + class RsIdentityDetails { public: @@ -181,6 +216,9 @@ class RsIdentityDetails bool mPgpKnown; std::string mPgpId; + // Recogn details. + std::list mRecognTags; + // reputation details. double mOpinion; double mReputation; @@ -230,6 +268,13 @@ virtual bool getOwnIds(std::list &ownIds) = 0; virtual bool submitOpinion(uint32_t& token, RsIdOpinion &opinion) = 0; virtual bool createIdentity(uint32_t& token, RsIdentityParameters ¶ms) = 0; +virtual bool updateIdentity(uint32_t& token, RsGxsIdGroup &group) = 0; + +virtual bool parseRecognTag(const RsGxsId &id, const std::string &nickname, + const std::string &tag, RsRecognTagDetails &details) = 0; +virtual bool getRecognTagRequest(const RsGxsId &id, const std::string &comment, + uint16_t tag_class, uint16_t tag_type, std::string &tag) = 0; + // Specific RsIdentity Functions.... /* Specific Service Data */ /* We expose these initially for testing / GUI purposes. diff --git a/libretroshare/src/serialiser/rsgxsiditems.cc b/libretroshare/src/serialiser/rsgxsiditems.cc index e22055b7a..7853afeaf 100644 --- a/libretroshare/src/serialiser/rsgxsiditems.cc +++ b/libretroshare/src/serialiser/rsgxsiditems.cc @@ -122,20 +122,30 @@ void RsGxsIdGroupItem::clear() group.mPgpIdHash.clear(); group.mPgpIdSign.clear(); + group.mRecognTags.clear(); + group.mPgpKnown = false; group.mPgpId.clear(); } + std::ostream& RsGxsIdGroupItem::print(std::ostream& out, uint16_t indent) { printRsItemBase(out, "RsGxsIdGroupItem", indent); uint16_t int_Indent = indent + 2; + printIndent(out, int_Indent); + out << "MetaData: " << meta << std::endl; printIndent(out, int_Indent); out << "PgpIdHash: " << group.mPgpIdHash << std::endl; printIndent(out, int_Indent); out << "PgpIdSign: " << group.mPgpIdSign << std::endl; + printIndent(out, int_Indent); + out << "RecognTags:" << std::endl; + + RsTlvStringSetRef set(TLV_TYPE_RECOGNSET, group.mRecognTags); + set.print(out, int_Indent + 2); printRsItemEnd(out ,"RsGxsIdGroupItem", indent); return out; @@ -151,6 +161,9 @@ uint32_t RsGxsIdSerialiser::sizeGxsIdGroupItem(RsGxsIdGroupItem *item) s += GetTlvStringSize(group.mPgpIdHash); s += GetTlvStringSize(group.mPgpIdSign); + RsTlvStringSetRef set(TLV_TYPE_RECOGNSET, item->group.mRecognTags); + s += set.TlvSize(); + return s; } @@ -181,6 +194,9 @@ bool RsGxsIdSerialiser::serialiseGxsIdGroupItem(RsGxsIdGroupItem *item, void *da /* GxsIdGroupItem */ ok &= SetTlvString(data, tlvsize, &offset, 1, item->group.mPgpIdHash); ok &= SetTlvString(data, tlvsize, &offset, 1, item->group.mPgpIdSign); + + RsTlvStringSetRef set(TLV_TYPE_RECOGNSET, item->group.mRecognTags); + ok &= set.SetTlv(data, tlvsize, &offset); if(offset != tlvsize) { @@ -238,6 +254,10 @@ RsGxsIdGroupItem* RsGxsIdSerialiser::deserialiseGxsIdGroupItem(void *data, uint3 ok &= GetTlvString(data, rssize, &offset, 1, item->group.mPgpIdHash); ok &= GetTlvString(data, rssize, &offset, 1, item->group.mPgpIdSign); + + RsTlvStringSetRef set(TLV_TYPE_RECOGNSET, item->group.mRecognTags); + ok &= set.GetTlv(data, rssize, &offset); + if (offset != rssize) { diff --git a/libretroshare/src/serialiser/rsgxsitems.cc b/libretroshare/src/serialiser/rsgxsitems.cc index 6cc57e90c..e1acdf0fd 100644 --- a/libretroshare/src/serialiser/rsgxsitems.cc +++ b/libretroshare/src/serialiser/rsgxsitems.cc @@ -52,7 +52,8 @@ std::ostream &operator<<(std::ostream &out, const RsGroupMetaData &meta) { - out << "[ GroupId: " << meta.mGroupId << " Name: " << meta.mGroupName << " ]"; + out << "[ GroupId: " << meta.mGroupId << " Name: " << meta.mGroupName; + out << " PublishTs: " << meta.mPublishTs << " ]"; return out; } diff --git a/libretroshare/src/serialiser/rsgxsrecognitems.cc b/libretroshare/src/serialiser/rsgxsrecognitems.cc new file mode 100644 index 000000000..89b4576aa --- /dev/null +++ b/libretroshare/src/serialiser/rsgxsrecognitems.cc @@ -0,0 +1,600 @@ +/* + * libretroshare/src/serialiser: rsgxsrecogitems.cc + * + * RetroShare Serialiser. + * + * Copyright 2013-2013 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.1 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/rsgxsrecognitems.h" + +/*** +#define RSSERIAL_DEBUG 1 +***/ + +#include + +/*************************************************************************/ + +RsGxsRecognReqItem::~RsGxsRecognReqItem() +{ + return; +} + +void RsGxsRecognReqItem::clear() +{ + issued_at = 0; + period = 0; + tag_class = 0; + tag_type = 0; + + identity.clear(); + nickname.clear(); + comment.clear(); + + sign.TlvClear(); + +} + +std::ostream &RsGxsRecognReqItem::print(std::ostream &out, uint16_t indent) +{ + printRsItemBase(out, "RsGxsRecognReqItem", indent); + uint16_t int_Indent = indent + 2; + + printIndent(out, int_Indent); + out << "issued_at: " << issued_at << std::endl; + + printIndent(out, int_Indent); + out << "period: " << period << std::endl; + + printIndent(out, int_Indent); + out << "tag_class: " << tag_class << std::endl; + + printIndent(out, int_Indent); + out << "tag_type: " << tag_type << std::endl; + + printIndent(out, int_Indent); + out << "identity: " << identity << std::endl; + + printIndent(out, int_Indent); + out << "nickname: " << nickname << std::endl; + + printIndent(out, int_Indent); + out << "comment: " << comment << std::endl; + + printIndent(out, int_Indent); + out << "signature: " << std::endl; + sign.print(out, int_Indent + 2); + + printRsItemEnd(out, "RsGxsRecognReqItem", indent); + return out; +} + + +uint32_t RsGxsRecognSerialiser::sizeReq(RsGxsRecognReqItem *item) +{ + uint32_t s = 8; /* header */ + s += 4; // issued_at; + s += 4; // period; + s += 2; // tag_class; + s += 2; // tag_type; + s += GetTlvStringSize(item->identity); + s += GetTlvStringSize(item->nickname); + s += GetTlvStringSize(item->comment); + s += item->sign.TlvSize(); + + return s; +} + +/* serialise the data to the buffer */ +bool RsGxsRecognSerialiser::serialiseReq(RsGxsRecognReqItem *item, void *data, uint32_t *pktsize) +{ + uint32_t tlvsize = sizeReq(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 << "RsGxsRecognSerialiser::serialiseReq() Header: " << ok << std::endl; + std::cerr << "RsGxsRecognSerialiser::serialiseReq() Size: " << tlvsize << std::endl; +#endif + + /* skip the header */ + offset += 8; + + /* add mandatory parts first */ + ok &= setRawUInt32(data, tlvsize, &offset, item->issued_at); + ok &= setRawUInt32(data, tlvsize, &offset, item->period); + ok &= setRawUInt16(data, tlvsize, &offset, item->tag_class); + ok &= setRawUInt16(data, tlvsize, &offset, item->tag_type); + + ok &= SetTlvString(data, tlvsize, &offset, 1, item->identity); + ok &= SetTlvString(data, tlvsize, &offset, 1, item->nickname); + ok &= SetTlvString(data, tlvsize, &offset, 1, item->comment); + ok &= item->sign.SetTlv(data, tlvsize, &offset); + + + if (offset != tlvsize) + { + ok = false; +#ifdef RSSERIAL_DEBUG + std::cerr << "RsGxsRecognSerialiser::serialiseReq() Size Error! " << std::endl; +#endif + } + + return ok; +} + +RsGxsRecognReqItem *RsGxsRecognSerialiser::deserialiseReq(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_GXS_RECOGN != getRsItemService(rstype)) || + (RS_PKT_SUBTYPE_RECOGN_REQ != 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 */ + RsGxsRecognReqItem *item = new RsGxsRecognReqItem(); + item->clear(); + + /* skip the header */ + offset += 8; + + /* add mandatory parts first */ + ok &= getRawUInt32(data, tlvsize, &offset, &(item->issued_at)); + ok &= getRawUInt32(data, tlvsize, &offset, &(item->period)); + ok &= getRawUInt16(data, tlvsize, &offset, &(item->tag_class)); + ok &= getRawUInt16(data, tlvsize, &offset, &(item->tag_type)); + + ok &= GetTlvString(data, tlvsize, &offset, 1, item->identity); + ok &= GetTlvString(data, tlvsize, &offset, 1, item->nickname); + ok &= GetTlvString(data, tlvsize, &offset, 1, item->comment); + ok &= item->sign.GetTlv(data, tlvsize, &offset); + + + if (offset != tlvsize) + { + /* error */ + delete item; + return NULL; + } + + if (!ok) + { + delete item; + return NULL; + } + + return item; +} + +/*************************************************************************/ + +RsGxsRecognTagItem::~RsGxsRecognTagItem() +{ + return; +} + +void RsGxsRecognTagItem::clear() +{ + valid_from = 0; + valid_to = 0; + + tag_class = 0; + tag_type = 0; + + identity.clear(); + nickname.clear(); + + sign.TlvClear(); +} + +std::ostream &RsGxsRecognTagItem::print(std::ostream &out, uint16_t indent) +{ + printRsItemBase(out, "RsGxsRecognTagItem", indent); + uint16_t int_Indent = indent + 2; + + printIndent(out, int_Indent); + out << "valid_from: " << valid_from << std::endl; + + printIndent(out, int_Indent); + out << "valid_to: " << valid_to << std::endl; + + printIndent(out, int_Indent); + out << "tag_class: " << tag_class << std::endl; + + printIndent(out, int_Indent); + out << "tag_type: " << tag_type << std::endl; + + printIndent(out, int_Indent); + out << "identity: " << identity << std::endl; + + printIndent(out, int_Indent); + out << "nickname: " << nickname << std::endl; + + printIndent(out, int_Indent); + out << "signature: " << std::endl; + sign.print(out, int_Indent + 2); + + printRsItemEnd(out, "RsGxsRecognTagItem", indent); + return out; +} + + +uint32_t RsGxsRecognSerialiser::sizeTag(RsGxsRecognTagItem *item) +{ + uint32_t s = 8; /* header */ + s += 4; // valid_from; + s += 4; // valid_to; + s += 2; // tag_class; + s += 2; // tag_type; + + s += GetTlvStringSize(item->identity); + s += GetTlvStringSize(item->nickname); + + s += item->sign.TlvSize(); + + return s; +} + +/* serialise the data to the buffer */ +bool RsGxsRecognSerialiser::serialiseTag(RsGxsRecognTagItem *item, void *data, uint32_t *pktsize) +{ + uint32_t tlvsize = sizeTag(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 << "RsGxsRecognSerialiser::serialiseTag() Header: " << ok << std::endl; + std::cerr << "RsGxsRecognSerialiser::serialiseTag() Size: " << tlvsize << std::endl; +#endif + + /* skip the header */ + offset += 8; + + /* add mandatory parts first */ + ok &= setRawUInt32(data, tlvsize, &offset, item->valid_from); + ok &= setRawUInt32(data, tlvsize, &offset, item->valid_to); + + ok &= setRawUInt16(data, tlvsize, &offset, item->tag_class); + ok &= setRawUInt16(data, tlvsize, &offset, item->tag_type); + + ok &= SetTlvString(data, tlvsize, &offset, 1, item->identity); + ok &= SetTlvString(data, tlvsize, &offset, 1, item->nickname); + ok &= item->sign.SetTlv(data, tlvsize, &offset); + + + if (offset != tlvsize) + { + ok = false; +#ifdef RSSERIAL_DEBUG + std::cerr << "RsGxsRecognSerialiser::serialiseTag() Size Error! " << std::endl; +#endif + } + + return ok; +} + +RsGxsRecognTagItem *RsGxsRecognSerialiser::deserialiseTag(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_GXS_RECOGN != getRsItemService(rstype)) || + (RS_PKT_SUBTYPE_RECOGN_TAG != 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 */ + RsGxsRecognTagItem *item = new RsGxsRecognTagItem(); + item->clear(); + + /* skip the header */ + offset += 8; + + /* add mandatory parts first */ + ok &= getRawUInt32(data, tlvsize, &offset, &(item->valid_from)); + ok &= getRawUInt32(data, tlvsize, &offset, &(item->valid_to)); + + ok &= getRawUInt16(data, tlvsize, &offset, &(item->tag_class)); + ok &= getRawUInt16(data, tlvsize, &offset, &(item->tag_type)); + + ok &= GetTlvString(data, tlvsize, &offset, 1, item->identity); + ok &= GetTlvString(data, tlvsize, &offset, 1, item->nickname); + ok &= item->sign.GetTlv(data, tlvsize, &offset); + + + if (offset != tlvsize) + { + /* error */ + delete item; + return NULL; + } + + if (!ok) + { + delete item; + return NULL; + } + + return item; +} + +/*************************************************************************/ + +RsGxsRecognSignerItem::~RsGxsRecognSignerItem() +{ + return; +} + +void RsGxsRecognSignerItem::clear() +{ + signing_classes.TlvClear(); + key.TlvClear(); + sign.TlvClear(); +} + +std::ostream &RsGxsRecognSignerItem::print(std::ostream &out, uint16_t indent) +{ + printRsItemBase(out, "RsGxsRecognSignerItem", indent); + uint16_t int_Indent = indent + 2; + + printIndent(out, int_Indent); + out << "signing_classes: " << std::endl; + signing_classes.print(out, int_Indent + 2); + + printIndent(out, int_Indent); + out << "key: " << std::endl; + key.print(out, int_Indent + 2); + + printIndent(out, int_Indent); + out << "signature: " << std::endl; + sign.print(out, int_Indent + 2); + + + printRsItemEnd(out, "RsGxsRecognSignerItem", indent); + return out; +} + + + + +uint32_t RsGxsRecognSerialiser::sizeSigner(RsGxsRecognSignerItem *item) +{ + uint32_t s = 8; /* header */ + s += item->signing_classes.TlvSize(); + s += item->key.TlvSize(); + s += item->sign.TlvSize(); + + return s; +} + +/* serialise the data to the buffer */ +bool RsGxsRecognSerialiser::serialiseSigner(RsGxsRecognSignerItem *item, void *data, uint32_t *pktsize) +{ + uint32_t tlvsize = sizeSigner(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 << "RsGxsRecognSerialiser::serialiseSigner() Header: " << ok << std::endl; + std::cerr << "RsGxsRecognSerialiser::serialiseSigner() Size: " << tlvsize << std::endl; +#endif + + /* skip the header */ + offset += 8; + + /* add mandatory parts first */ + ok &= item->signing_classes.SetTlv(data, tlvsize, &offset); + ok &= item->key.SetTlv(data, tlvsize, &offset); + ok &= item->sign.SetTlv(data, tlvsize, &offset); + + if (offset != tlvsize) + { + ok = false; +#ifdef RSSERIAL_DEBUG + std::cerr << "RsGxsRecognSerialiser::serialiseSigner() Size Error! " << std::endl; +#endif + } + + return ok; +} + +RsGxsRecognSignerItem *RsGxsRecognSerialiser::deserialiseSigner(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_GXS_RECOGN != getRsItemService(rstype)) || + (RS_PKT_SUBTYPE_RECOGN_SIGNER != 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 */ + RsGxsRecognSignerItem *item = new RsGxsRecognSignerItem(); + item->clear(); + + /* skip the header */ + offset += 8; + + /* add mandatory parts first */ + ok &= item->signing_classes.GetTlv(data, tlvsize, &offset); + ok &= item->key.GetTlv(data, tlvsize, &offset); + ok &= item->sign.GetTlv(data, tlvsize, &offset); + + if (offset != tlvsize) + { + /* error */ + delete item; + return NULL; + } + + if (!ok) + { + delete item; + return NULL; + } + + return item; +} + + +/*************************************************************************/ + +uint32_t RsGxsRecognSerialiser::size(RsItem *i) +{ + RsGxsRecognReqItem *rqi; + RsGxsRecognTagItem *rti; + RsGxsRecognSignerItem *rsi; + + if (NULL != (rqi = dynamic_cast(i))) + { + return sizeReq(rqi); + } + if (NULL != (rti = dynamic_cast(i))) + { + return sizeTag(rti); + } + if (NULL != (rsi = dynamic_cast(i))) + { + return sizeSigner(rsi); + } + return 0; +} + +bool RsGxsRecognSerialiser::serialise(RsItem *i, void *data, uint32_t *pktsize) +{ + RsGxsRecognReqItem *rri; + RsGxsRecognTagItem *rti; + RsGxsRecognSignerItem *rsi; + + if (NULL != (rri = dynamic_cast(i))) + { + return serialiseReq(rri, data, pktsize); + } + if (NULL != (rti = dynamic_cast(i))) + { + return serialiseTag(rti, data, pktsize); + } + if (NULL != (rsi = dynamic_cast(i))) + { + return serialiseSigner(rsi, data, pktsize); + } + return false; +} + +RsItem *RsGxsRecognSerialiser::deserialise(void *data, uint32_t *pktsize) +{ + /* get the type and size */ + uint32_t rstype = getRsItemId(data); + + if ((RS_PKT_VERSION_SERVICE != getRsItemVersion(rstype)) || + (RS_SERVICE_TYPE_GXS_RECOGN != getRsItemService(rstype))) + { + return NULL; /* wrong type */ + } + + switch(getRsItemSubType(rstype)) + { + case RS_PKT_SUBTYPE_RECOGN_REQ: + return deserialiseReq(data, pktsize); + break; + case RS_PKT_SUBTYPE_RECOGN_TAG: + return deserialiseTag(data, pktsize); + break; + case RS_PKT_SUBTYPE_RECOGN_SIGNER: + return deserialiseSigner(data, pktsize); + break; + default: + return NULL; + break; + } +} + +/*************************************************************************/ + + + diff --git a/libretroshare/src/serialiser/rsgxsrecognitems.h b/libretroshare/src/serialiser/rsgxsrecognitems.h new file mode 100644 index 000000000..fdbc9cfc2 --- /dev/null +++ b/libretroshare/src/serialiser/rsgxsrecognitems.h @@ -0,0 +1,152 @@ +#ifndef RS_GXS_RECOG_ITEMS_H +#define RS_GXS_RECOG_ITEMS_H + +/* + * libretroshare/src/serialiser: rsgxsrecogitems.h + * + * RetroShare Serialiser. + * + * Copyright 2013-2013 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.1 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" + +/**************************************************************************/ + +#define RS_PKT_SUBTYPE_RECOGN_REQ 0x01 +#define RS_PKT_SUBTYPE_RECOGN_TAG 0x02 +#define RS_PKT_SUBTYPE_RECOGN_SIGNER 0x03 + + +class RsGxsRecognReqItem: public RsItem +{ + public: + RsGxsRecognReqItem() + :RsItem(RS_PKT_VERSION_SERVICE, RS_SERVICE_TYPE_GXS_RECOGN, + RS_PKT_SUBTYPE_RECOGN_REQ) + { + setPriorityLevel(QOS_PRIORITY_DEFAULT); + return; + } +virtual ~RsGxsRecognReqItem(); +virtual void clear(); +std::ostream &print(std::ostream &out, uint16_t indent = 0); + + + uint32_t issued_at; + uint32_t period; + uint16_t tag_class; + uint16_t tag_type; + + std::string identity; + std::string nickname; + std::string comment; + + RsTlvKeySignature sign; +}; + + +class RsGxsRecognTagItem: public RsItem +{ + public: + RsGxsRecognTagItem() + :RsItem(RS_PKT_VERSION_SERVICE, RS_SERVICE_TYPE_GXS_RECOGN, + RS_PKT_SUBTYPE_RECOGN_TAG) + { + setPriorityLevel(QOS_PRIORITY_DEFAULT); + return; + } +virtual ~RsGxsRecognTagItem(); +virtual void clear(); +std::ostream &print(std::ostream &out, uint16_t indent = 0); + + uint32_t valid_from; + uint32_t valid_to; + uint16_t tag_class; + uint16_t tag_type; + + std::string identity; + std::string nickname; + + RsTlvKeySignature sign; +}; + + +class RsGxsRecognSignerItem: public RsItem +{ + public: + RsGxsRecognSignerItem() + :RsItem(RS_PKT_VERSION_SERVICE, RS_SERVICE_TYPE_GXS_RECOGN, + RS_PKT_SUBTYPE_RECOGN_SIGNER) + { + setPriorityLevel(QOS_PRIORITY_DEFAULT); + return; + } +virtual ~RsGxsRecognSignerItem(); +virtual void clear(); +std::ostream &print(std::ostream &out, uint16_t indent = 0); + + RsTlvServiceIdSet signing_classes; + RsTlvSecurityKey key; // has from->to, and flags. + RsTlvKeySignature sign; +}; + + +class RsGxsRecognSerialiser: public RsSerialType +{ + public: + RsGxsRecognSerialiser() + :RsSerialType(RS_PKT_VERSION_SERVICE, RS_SERVICE_TYPE_GXS_RECOGN) + { return; } +virtual ~RsGxsRecognSerialiser() + { 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 sizeReq(RsGxsRecognReqItem *); +virtual bool serialiseReq(RsGxsRecognReqItem *item, void *data, uint32_t *size); +virtual RsGxsRecognReqItem *deserialiseReq(void *data, uint32_t *size); + +virtual uint32_t sizeTag(RsGxsRecognTagItem *); +virtual bool serialiseTag(RsGxsRecognTagItem *item, void *data, uint32_t *size); +virtual RsGxsRecognTagItem *deserialiseTag(void *data, uint32_t *size); + +virtual uint32_t sizeSigner(RsGxsRecognSignerItem *); +virtual bool serialiseSigner(RsGxsRecognSignerItem *item, void *data, uint32_t *size); +virtual RsGxsRecognSignerItem *deserialiseSigner(void *data, uint32_t *size); + +}; + +/**************************************************************************/ + +#endif /* RS_GXS_RECOGN_ITEMS_H */ + + diff --git a/libretroshare/src/serialiser/rsserviceids.h b/libretroshare/src/serialiser/rsserviceids.h index 8095ed575..efa22dc32 100644 --- a/libretroshare/src/serialiser/rsserviceids.h +++ b/libretroshare/src/serialiser/rsserviceids.h @@ -149,6 +149,8 @@ const uint16_t RS_SERVICE_GXSV3_TYPE_POSTED = 0xf326; const uint16_t RS_SERVICE_GXSV3_TYPE_CHANNELS = 0xf327; const uint16_t RS_SERVICE_GXSV3_TYPE_GXSCIRCLE = 0xf328; +const uint16_t RS_SERVICE_TYPE_GXS_RECOGN = 0xf331; + /***************** IDS ALLOCATED FOR PLUGINS ******************/ const uint16_t RS_SERVICE_TYPE_PLUGIN_ARADO_TEST_ID1 = 0xf401; diff --git a/libretroshare/src/serialiser/rstlvbase.h b/libretroshare/src/serialiser/rstlvbase.h index 70698df64..613545440 100644 --- a/libretroshare/src/serialiser/rstlvbase.h +++ b/libretroshare/src/serialiser/rstlvbase.h @@ -201,6 +201,7 @@ const uint16_t TLV_TYPE_WKEYVALUESET = 0x1013; const uint16_t TLV_TYPE_STRINGSET = 0x1020; /* dummy non-existant */ const uint16_t TLV_TYPE_PEERSET = 0x1021; const uint16_t TLV_TYPE_HASHSET = 0x1022; +const uint16_t TLV_TYPE_RECOGNSET = 0x1023; const uint16_t TLV_TYPE_SERVICESET = 0x1030; const uint16_t TLV_TYPE_SECURITYKEY = 0x1040; diff --git a/libretroshare/src/serialiser/rstlvtypes.cc b/libretroshare/src/serialiser/rstlvtypes.cc index 6a2fc0579..1c1db3cd8 100644 --- a/libretroshare/src/serialiser/rstlvtypes.cc +++ b/libretroshare/src/serialiser/rstlvtypes.cc @@ -428,6 +428,165 @@ std::ostream &RsTlvStringSet::printHex(std::ostream &out, uint16_t indent) } +/************************************* String Set Ref ************************************/ +/* This is exactly the same as StringSet, but it uses an alternative list. + */ +RsTlvStringSetRef::RsTlvStringSetRef(uint16_t type, std::list &refids) + :mType(type), ids(refids) +{ +} + +void RsTlvStringSetRef::TlvClear() +{ + ids.clear(); + +} + +uint32_t RsTlvStringSetRef::TlvSize() +{ + + uint32_t s = TLV_HEADER_SIZE; /* header */ + + /* determine the total size of ids strings in list */ + + std::list::iterator it; + + for(it = ids.begin(); it != ids.end() ; ++it) + { + if (it->length() > 0) + s += GetTlvStringSize(*it); + } + + return s; +} + + +bool RsTlvStringSetRef::SetTlv(void *data, uint32_t size, uint32_t *offset) /* serialise */ +{ + /* must check sizes */ + uint32_t tlvsize = TlvSize(); + uint32_t tlvend = *offset + tlvsize; + + if (size < tlvend) + return false; /* not enough space */ + + bool ok = true; + + + /* start at data[offset] */ + ok &= SetTlvBase(data, tlvend, offset, mType , tlvsize); + + /* determine the total size of ids strings in list */ + + std::list::iterator it; + + for(it = ids.begin(); it != ids.end() ; ++it) + { + if (it->length() > 0) + ok &= SetTlvString(data, tlvend, offset, TLV_TYPE_STR_GENID, *it); + } + + return ok; + +} + + +bool RsTlvStringSetRef::GetTlv(void *data, uint32_t size, uint32_t *offset) /* serialise */ +{ + if (size < *offset + TLV_HEADER_SIZE) + return false; + + uint16_t tlvtype = GetTlvType( &(((uint8_t *) data)[*offset]) ); + uint32_t tlvsize = GetTlvSize( &(((uint8_t *) data)[*offset]) ); + uint32_t tlvend = *offset + tlvsize; + + + + if (size < tlvend) /* check size */ + return false; /* not enough space */ + + if (tlvtype != mType) /* check type */ + return false; + + bool ok = true; + + /* ready to load */ + TlvClear(); + + /* skip the header */ + (*offset) += TLV_HEADER_SIZE; + + + +/* while there is TLV */ + while((*offset) + 2 < tlvend) + { + /* get the next type */ + uint16_t tlvsubtype = GetTlvType( &(((uint8_t *) data)[*offset]) ); + + if (tlvsubtype == TLV_TYPE_STR_GENID) + { + std::string newIds; + ok &= GetTlvString(data, tlvend, offset, TLV_TYPE_STR_GENID, newIds); + if(ok) + { + ids.push_back(newIds); + + } + } + else + { + /* Step past unknown TLV TYPE */ + ok &= SkipUnknownTlv(data, tlvend, offset); + } + + if (!ok) + { + break; + } + } + + /*************************************************************************** + * NB: extra components could be added (for future expansion of the type). + * or be present (if this code is reading an extended version). + * + * We must chew up the extra characters to conform with TLV specifications + ***************************************************************************/ + if (*offset != tlvend) + { +#ifdef TLV_DEBUG + std::cerr << "RsTlvPeerIdSetRef::GetTlv() Warning extra bytes at end of item"; + std::cerr << std::endl; +#endif + *offset = tlvend; + } + + return ok; +} + +/// print to screen RsTlvStringSet contents +std::ostream &RsTlvStringSetRef::print(std::ostream &out, uint16_t indent) +{ + printBase(out, "RsTlvStringSetRef", indent); + uint16_t int_Indent = indent + 2; + + printIndent(out, int_Indent); + out << "type:" << mType; + out << std::endl; + + std::list::iterator it; + for(it = ids.begin(); it != ids.end() ; ++it) + { + printIndent(out, int_Indent); + out << "id:" << *it; + out << std::endl; + } + + printEnd(out, "RsTlvStringSetRef", indent); + return out; + +} + /************************************* Service Id Set ************************************/ void RsTlvServiceIdSet::TlvClear() diff --git a/libretroshare/src/serialiser/rstlvtypes.h b/libretroshare/src/serialiser/rstlvtypes.h index 4148faa62..9bae52f89 100644 --- a/libretroshare/src/serialiser/rstlvtypes.h +++ b/libretroshare/src/serialiser/rstlvtypes.h @@ -137,6 +137,22 @@ virtual std::ostream &print(std::ostream &out, uint16_t indent); }; +class RsTlvStringSetRef: public RsTlvItem +{ + public: + RsTlvStringSetRef(uint16_t type, std::list &refids); +virtual ~RsTlvStringSetRef() { return; } +virtual uint32_t TlvSize(); +virtual void TlvClear(); +virtual bool SetTlv(void *data, uint32_t size, uint32_t *offset); /* serialise */ +virtual bool GetTlv(void *data, uint32_t size, uint32_t *offset); /* deserialise */ +virtual std::ostream &print(std::ostream &out, uint16_t indent); + + uint16_t mType; + std::list &ids; /* Mandatory */ +}; + + /**** MORE TLV ***** * * File Items/Data. diff --git a/libretroshare/src/services/p3gxsforums.cc b/libretroshare/src/services/p3gxsforums.cc index 7b7766bd2..bdc8472e0 100644 --- a/libretroshare/src/services/p3gxsforums.cc +++ b/libretroshare/src/services/p3gxsforums.cc @@ -217,7 +217,7 @@ bool p3GxsForums::createGroup(uint32_t &token, RsGxsForumGroup &group) bool p3GxsForums::updateGroup(uint32_t &token, RsGxsGroupUpdateMeta& meta, RsGxsForumGroup &group) { - std::cerr << "p3GxsForums::createGroup()" << std::endl; + std::cerr << "p3GxsForums::updateGroup()" << std::endl; if(meta.getGroupId().empty()) return false; diff --git a/libretroshare/src/services/p3idservice.cc b/libretroshare/src/services/p3idservice.cc index 96e0e6569..5864ae32d 100644 --- a/libretroshare/src/services/p3idservice.cc +++ b/libretroshare/src/services/p3idservice.cc @@ -29,6 +29,7 @@ #include "retroshare/rsiface.h" #include "util/rsrandom.h" #include "util/rsstring.h" +#include "util/radix64.h" #include "pqi/authgpg.h" @@ -39,10 +40,13 @@ /**** * #define DEBUG_IDS 1 + * #define DEBUG_RECOGN 1 * #define GXSID_GEN_DUMMY_DATA 1 * #define ENABLE_PGP_SIGNATURES 1 ****/ +#define DEBUG_IDS 1 +#define DEBUG_RECOGN 1 #define ENABLE_PGP_SIGNATURES 1 @@ -76,14 +80,16 @@ RsIdentity *rsIdentity = NULL; #define RSGXSID_MAX_SERVICE_STRING 1024 #define BG_PGPHASH 1 -#define BG_REPUTATION 2 +#define BG_RECOGN 2 +#define BG_REPUTATION 3 #define GXSIDREQ_CACHELOAD 0x0001 #define GXSIDREQ_CACHEOWNIDS 0x0002 #define GXSIDREQ_PGPHASH 0x0010 -#define GXSIDREQ_REPUTATION 0x0020 +#define GXSIDREQ_RECOGN 0x0020 +#define GXSIDREQ_REPUTATION 0x0030 #define GXSIDREQ_CACHETEST 0x1000 @@ -94,7 +100,10 @@ RsIdentity *rsIdentity = NULL; #define GXSID_EVENT_PGPHASH 0x0010 #define GXSID_EVENT_PGPHASH_PROC 0x0011 -#define GXSID_EVENT_REPUTATION 0x0020 +#define GXSID_EVENT_RECOGN 0x0020 +#define GXSID_EVENT_RECOGN_PROC 0x0021 + +#define GXSID_EVENT_REPUTATION 0x0030 #define GXSID_EVENT_CACHETEST 0x1000 @@ -115,6 +124,10 @@ RsIdentity *rsIdentity = NULL; #define PGPHASH_RETRY_PERIOD 11 #define PGPHASH_PROC_PERIOD 1 +#define RECOGN_PERIOD 90 +#define RECOGN_RETRY_PERIOD 17 +#define RECOGN_PROC_PERIOD 1 + #define REPUTATION_PERIOD 60 #define REPUTATION_RETRY_PERIOD 13 #define REPUTATION_PROC_PERIOD 1 @@ -126,14 +139,15 @@ RsIdentity *rsIdentity = NULL; p3IdService::p3IdService(RsGeneralDataService *gds, RsNetworkExchangeService *nes) : RsGxsIdExchange(gds, nes, new RsGxsIdSerialiser(), RS_SERVICE_GXSV2_TYPE_GXSID, idAuthenPolicy()), RsIdentity(this), GxsTokenQueue(this), RsTickEvent(), mIdMtx("p3IdService"), - mPublicKeyCache(DEFAULT_MEM_CACHE_SIZE, "GxsIdPublicKeyCache"), - mPrivateKeyCache(DEFAULT_MEM_CACHE_SIZE, "GxsIdPrivateKeyCache") + mPublicKeyCache(DEFAULT_MEM_CACHE_SIZE, "GxsIdPublicKeyCache"), + mPrivateKeyCache(DEFAULT_MEM_CACHE_SIZE, "GxsIdPrivateKeyCache") { mBgSchedule_Mode = 0; mBgSchedule_Active = false; // Kick off Cache Testing, + Others. RsTickEvent::schedule_in(GXSID_EVENT_PGPHASH, PGPHASH_PERIOD); + RsTickEvent::schedule_in(GXSID_EVENT_RECOGN, RECOGN_PERIOD); RsTickEvent::schedule_in(GXSID_EVENT_REPUTATION, REPUTATION_PERIOD); RsTickEvent::schedule_now(GXSID_EVENT_CACHEOWNIDS); @@ -146,6 +160,7 @@ p3IdService::p3IdService(RsGeneralDataService *gds, RsNetworkExchangeService *ne #endif #endif + loadRecognKeys(); } @@ -300,6 +315,81 @@ bool p3IdService::createIdentity(uint32_t& token, RsIdentityParameters ¶ms) return true; } +bool p3IdService::updateIdentity(uint32_t& token, RsGxsIdGroup &group) +{ + std::cerr << "p3IdService::updateIdentity()"; + std::cerr << std::endl; + + updateGroup(token, group); + + return false; +} + + +bool p3IdService::parseRecognTag(const RsGxsId &id, const std::string &nickname, + const std::string &tag, RsRecognTagDetails &details) +{ + std::cerr << "p3IdService::parseRecognTag()"; + std::cerr << std::endl; + + RsGxsRecognTagItem *tagitem = RsRecogn::extractTag(tag); + if (!tagitem) + { + return false; + } + + bool isPending = false; + bool isValid = recogn_checktag(id, nickname, tagitem, true, isPending); + + details.valid_from = tagitem->valid_from; + details.valid_to = tagitem->valid_to; + details.tag_class = tagitem->tag_class; + details.tag_type = tagitem->tag_type; + details.signer = tagitem->sign.keyId; + + details.is_valid = isValid; + details.is_pending = isPending; + + delete tagitem; + + return true; +} + +bool p3IdService::getRecognTagRequest(const RsGxsId &id, const std::string &comment, uint16_t tag_class, uint16_t tag_type, std::string &tag) +{ + std::cerr << "p3IdService::getRecognTagRequest()"; + std::cerr << std::endl; + + if (!havePrivateKey(id)) + { + std::cerr << "p3IdService::getRecognTagRequest() Dont have private key"; + std::cerr << std::endl; + // attempt to load it. + cache_request_load(id); + return false; + } + + RsTlvSecurityKey key; + std::string nickname; + + { + RsStackMutex stack(mIdMtx); /********** STACK LOCKED MTX ******/ + RsGxsIdCache data; + if (!mPrivateKeyCache.fetch(id, data)) + { + std::cerr << "p3IdService::getRecognTagRequest() Cache failure"; + std::cerr << std::endl; + return false; + } + + key = data.pubkey; + nickname = data.details.mNickname; + } + + return RsRecogn::createTagRequest(key, id, nickname, tag_class, tag_type, comment, tag); +} + + /********************************************************************************/ /******************* RsGixs Interface ***************************************/ @@ -409,6 +499,12 @@ bool p3IdService::getGroupData(const uint32_t &token, std::vector RsGxsIdGroupItem* item = dynamic_cast(*vit); if (item) { +#ifdef DEBUG_IDS + std::cerr << "p3IdService::getGroupData() Item is:"; + std::cerr << std::endl; + item->print(std::cerr); + std::cerr << std::endl; +#endif // DEBUG_IDS RsGxsIdGroup group = item->group; group.mMeta = item->meta; @@ -493,20 +589,64 @@ bool p3IdService::getMsgData(const uint32_t &token, std::vector bool p3IdService::createGroup(uint32_t& token, RsGxsIdGroup &group) { - RsGxsIdGroupItem* item = new RsGxsIdGroupItem(); - item->group = group; - item->meta = group.mMeta; - RsGenExchange::publishGroup(token, item); - return true; + RsGxsIdGroupItem* item = new RsGxsIdGroupItem(); + item->group = group; + item->meta = group.mMeta; + RsGenExchange::publishGroup(token, item); + return true; +} + +bool p3IdService::updateGroup(uint32_t& token, RsGxsIdGroup &group) +{ + RsGxsId id = group.mMeta.mGroupId; + RsGxsIdGroupItem* item = new RsGxsIdGroupItem(); + item->group = group; + item->meta = group.mMeta; + + std::cerr << "p3IdService::updateGroup() Updating RsGxsId: " << id; + std::cerr << std::endl; + + //RsGenExchange::updateGroup(token, item); + + RsGxsGroupUpdateMeta updateMeta(id); + RsGenExchange::updateGroup(token, updateMeta, item); + + // if its in the cache - clear it. + { + RsStackMutex stack(mIdMtx); /********** STACK LOCKED MTX ******/ + if (mPublicKeyCache.erase(id)) + { + std::cerr << "p3IdService::updateGroup() Removed from PublicKeyCache"; + std::cerr << std::endl; + } + else + { + std::cerr << "p3IdService::updateGroup() Not in PublicKeyCache"; + std::cerr << std::endl; + } + + if (mPrivateKeyCache.erase(id)) + { + std::cerr << "p3IdService::updateGroup() Removed from PrivateKeyCache"; + std::cerr << std::endl; + } + else + { + std::cerr << "p3IdService::updateGroup() Not in PrivateKeyCache"; + std::cerr << std::endl; + } + } + + return true; } bool p3IdService::createMsg(uint32_t& token, RsGxsIdOpinion &opinion) { - RsGxsIdOpinionItem* item = new RsGxsIdOpinionItem(); - item->opinion = opinion; - item->meta = opinion.mMeta; - RsGenExchange::publishMsg(token, item); - return true; + RsGxsIdOpinionItem* item = new RsGxsIdOpinionItem(); + item->opinion = opinion; + item->meta = opinion.mMeta; + RsGenExchange::publishMsg(token, item); + return true; } /************************************************************************************/ @@ -558,6 +698,85 @@ std::string SSGxsIdPgp::save() const return output; } + +/* Encoding / Decoding Group Service String stuff + * + * RecognTags. + */ + +bool SSGxsIdRecognTags::load(const std::string &input) +{ + char pgpline[RSGXSID_MAX_SERVICE_STRING]; + int pubTs = 0; + int lastTs = 0; + uint32_t flags = 0; + + if (3 == sscanf(input.c_str(), "F:%u P:%d T:%d", &flags, &pubTs, &lastTs)) + { + publishTs = pubTs; + lastCheckTs = lastTs; + tagFlags = flags; + } + else + { + return false; + } + return true; +} + +std::string SSGxsIdRecognTags::save() const +{ + std::string output; + rs_sprintf(output, "F:%u P:%d T:%d", tagFlags, publishTs, lastCheckTs); + return output; +} + +bool SSGxsIdRecognTags::tagsProcessed() const +{ + return (tagFlags & 0x1000); +} + +bool SSGxsIdRecognTags::tagsPending() const +{ + return (tagFlags & 0x2000); +} + +bool SSGxsIdRecognTags::tagValid(int i) const +{ + uint32_t idx = 0x01 << i; + +#ifdef DEBUG_RECOGN + std::cerr << "SSGxsIdRecognTags::tagValid(" << i << ") idx: " << idx; + std::cerr << " result: " << (tagFlags & idx); + std::cerr << std::endl; +#endif // DEBUG_RECOGN + + return (tagFlags & idx); +} + +void SSGxsIdRecognTags::setTags(bool processed, bool pending, uint32_t flags) +{ + flags &= 0x00ff; // clear top bits; + if (processed) + { + flags |= 0x1000; + } + if (pending) + { + flags |= 0x2000; + } + +#ifdef DEBUG_RECOGN + std::cerr << "SSGxsIdRecognTags::setTags(" << processed << "," << pending << "," << flags << ")"; + std::cerr << " tagFlags: " << tagFlags; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + + tagFlags = flags; +} + + + bool SSGxsIdScore::load(const std::string &input) { return (1 == sscanf(input.c_str(), "%d", &score)); @@ -585,12 +804,13 @@ std::string SSGxsIdCumulator::save() const bool SSGxsIdGroup::load(const std::string &input) { char pgpstr[RSGXSID_MAX_SERVICE_STRING]; + char recognstr[RSGXSID_MAX_SERVICE_STRING]; char scorestr[RSGXSID_MAX_SERVICE_STRING]; char opinionstr[RSGXSID_MAX_SERVICE_STRING]; char repstr[RSGXSID_MAX_SERVICE_STRING]; - // split into two parts. - if (4 != sscanf(input.c_str(), "v1 {P:%[^}]} {Y:%[^}]} {O:%[^}]} {R:%[^}]}", pgpstr, scorestr, opinionstr, repstr)) + // split into parts. + if (5 != sscanf(input.c_str(), "v1 {P:%[^}]} {T:%[^}]} {Y:%[^}]} {O:%[^}]} {R:%[^}]}", pgpstr, recognstr, scorestr, opinionstr, repstr)) { #ifdef DEBUG_IDS std::cerr << "SSGxsIdGroup::load() Failed to extract 4 Parts"; @@ -616,6 +836,22 @@ bool SSGxsIdGroup::load(const std::string &input) ok = false; } + if (recogntags.load(recognstr)) + { +#ifdef DEBUG_RECOGN + std::cerr << "SSGxsIdGroup::load() recognstr: " << recognstr; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + } + else + { +#ifdef DEBUG_RECOGN + std::cerr << "SSGxsIdGroup::load() Invalid recognstr: " << recognstr; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + ok = false; + } + if (score.load(scorestr)) { #ifdef DEBUG_IDS @@ -682,6 +918,10 @@ std::string SSGxsIdGroup::save() const output += pgp.save(); output += "}"; + output += "{T:"; + output += recogntags.save(); + output += "}"; + output += "{Y:"; output += score.save(); output += "}"; @@ -725,11 +965,17 @@ RsGxsIdCache::RsGxsIdCache() return; } -RsGxsIdCache::RsGxsIdCache(const RsGxsIdGroupItem *item, const RsTlvSecurityKey &in_pkey) +RsGxsIdCache::RsGxsIdCache(const RsGxsIdGroupItem *item, const RsTlvSecurityKey &in_pkey, const std::list &tagList) { // Save Keys. pubkey = in_pkey; + // Save Time for ServiceString comparisions. + mPublishTs = item->meta.mPublishTs; + + // Save RecognTags. + mRecognTags = tagList; + // Fill in Details. details.mNickname = item->meta.mGroupName; details.mId = item->meta.mGroupId; @@ -749,6 +995,8 @@ RsGxsIdCache::RsGxsIdCache(const RsGxsIdGroupItem *item, const RsTlvSecurityKey void RsGxsIdCache::updateServiceString(std::string serviceString) { + details.mRecognTags.clear(); + SSGxsIdGroup ssdata; if (ssdata.load(serviceString)) { @@ -765,6 +1013,54 @@ void RsGxsIdCache::updateServiceString(std::string serviceString) } } + + // process RecognTags. + if (ssdata.recogntags.tagsProcessed()) + { +#ifdef DEBUG_RECOGN + std::cerr << "RsGxsIdCache::updateServiceString() updating recogntags"; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + if (ssdata.recogntags.publishTs == mPublishTs) + { + std::list::iterator it; + int i = 0; + for(it = mRecognTags.begin(); it != mRecognTags.end(); it++, i++) + { + if (ssdata.recogntags.tagValid(i) && it->valid) + { +#ifdef DEBUG_RECOGN + std::cerr << "RsGxsIdCache::updateServiceString() Valid Tag: " << it->tag_class << ":" << it->tag_type; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + details.mRecognTags.push_back(*it); + } + else + { +#ifdef DEBUG_RECOGN + std::cerr << "RsGxsIdCache::updateServiceString() Invalid Tag: " << it->tag_class << ":" << it->tag_type; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + } + } + } + else + { +#ifdef DEBUG_RECOGN + std::cerr << "RsGxsIdCache::updateServiceString() recogntags old publishTs"; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + } + + } + else + { +#ifdef DEBUG_RECOGN + std::cerr << "RsGxsIdCache::updateServiceString() recogntags unprocessed"; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + } + details.mOpinion = 0; details.mReputation = ssdata.score.score; } @@ -779,9 +1075,137 @@ void RsGxsIdCache::updateServiceString(std::string serviceString) } +bool p3IdService::recogn_extract_taginfo(const RsGxsIdGroupItem *item, std::list &tagItems) +{ +#ifdef DEBUG_RECOGN + std::cerr << "p3IdService::recogn_extract_taginfo()"; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + + /* process Recogn Tags */ + + std::list::const_iterator rit; + int count = 0; + for(rit = item->group.mRecognTags.begin(); rit != item->group.mRecognTags.end(); rit++) + { + if (++count > RSRECOGN_MAX_TAGINFO) + { +#ifdef DEBUG_RECOGN + std::cerr << "p3IdService::recogn_extract_taginfo() Too many tags."; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + + return true; + } + + RsGxsRecognTagItem *tagitem = RsRecogn::extractTag(*rit); + + if (!tagitem) + { + continue; + } + +#ifdef DEBUG_RECOGN + std::cerr << "p3IdService::recogn_extract_taginfo() Got TagItem: "; + std::cerr << std::endl; + tagitem->print(std::cerr); +#endif // DEBUG_RECOGN + + tagItems.push_back(tagitem); + } + return true; +} +bool p3IdService::cache_process_recogntaginfo(const RsGxsIdGroupItem *item, std::list &tagList) +{ + /* ServiceString decode */ + SSGxsIdGroup ssdata; + bool recognProcess = false; + if (ssdata.load(item->meta.mServiceString)) + { + if (!ssdata.recogntags.tagsProcessed()) + { +#ifdef DEBUG_RECOGN + std::cerr << "p3IdService::cache_process_recogntaginfo() tags not processed"; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + /* we need to reprocess it */ + recognProcess = true; + } + else + { + if (item->meta.mPublishTs != ssdata.recogntags.publishTs) + { +#ifdef DEBUG_RECOGN + std::cerr << "p3IdService::cache_process_recogntaginfo() publishTs old"; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + recognProcess = true; + } + else if (ssdata.recogntags.tagsPending()) + { +#ifdef DEBUG_RECOGN + std::cerr << "p3IdService::cache_process_recogntaginfo() tagsPending"; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + /* reprocess once a day */ + recognProcess = true; + } + } + } + else + { +#ifdef DEBUG_RECOGN + std::cerr << "p3IdService::cache_process_recogntaginfo() ServiceString invalid"; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + recognProcess = true; + } + + std::list tagItems; + std::list::iterator it; + + recogn_extract_taginfo(item, tagItems); + + time_t now = time(NULL); + for(it = tagItems.begin(); it != tagItems.end(); it++) + { + RsRecognTag info((*it)->tag_class, (*it)->tag_type, false); + bool isPending = false; + if (recogn_checktag(item->meta.mGroupId, item->meta.mGroupName, *it, false, isPending)) + { + info.valid = true; + } +#ifdef DEBUG_RECOGN + std::cerr << "p3IdService::cache_process_recogntaginfo() Adding Tag: "; + std::cerr << info.tag_class << ":"; + std::cerr << info.tag_type << ":"; + std::cerr << info.valid; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + + tagList.push_back(info); + delete *it; + } + + + if (recognProcess) + { + RsStackMutex stack(mIdMtx); /********** STACK LOCKED MTX ******/ + mRecognGroupIds.push_back(item->meta.mGroupId); + +#ifdef DEBUG_RECOGN + std::cerr << "p3IdService::cache_process_recogntaginfo() Reprocessing groupId: "; + std::cerr << item->meta.mGroupId; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + + } + + return true; +} bool p3IdService::cache_store(const RsGxsIdGroupItem *item) @@ -793,7 +1217,7 @@ bool p3IdService::cache_store(const RsGxsIdGroupItem *item) //item->print(std::cerr, 0); NEEDS CONST!!!! TODO //std::cerr << std::endl; - /* extract key from keys */ + /* extract key from keys */ RsTlvSecurityKeySet keySet; RsTlvSecurityKey pubkey; RsTlvSecurityKey fullkey; @@ -814,9 +1238,9 @@ bool p3IdService::cache_store(const RsGxsIdGroupItem *item) //std::cerr << "p3IdService::cache_store() KeySet is:"; //keySet.print(std::cerr, 10); - for (kit = keySet.keys.begin(); kit != keySet.keys.end(); kit++) - { - if (kit->second.keyFlags & RSTLV_KEY_DISTRIB_ADMIN) + for (kit = keySet.keys.begin(); kit != keySet.keys.end(); kit++) + { + if (kit->second.keyFlags & RSTLV_KEY_DISTRIB_ADMIN) { #ifdef DEBUG_IDS std::cerr << "p3IdService::cache_store() Found Admin Key"; @@ -824,7 +1248,7 @@ bool p3IdService::cache_store(const RsGxsIdGroupItem *item) #endif // DEBUG_IDS /* save full key - if we have it */ - if (kit->second.keyFlags & RSTLV_KEY_TYPE_FULL) + if (kit->second.keyFlags & RSTLV_KEY_TYPE_FULL) { fullkey = kit->second; full_key_ok = true; @@ -847,16 +1271,20 @@ bool p3IdService::cache_store(const RsGxsIdGroupItem *item) return false; } + // extract tags. + std::list tagList; + cache_process_recogntaginfo(item, tagList); + RsStackMutex stack(mIdMtx); /********** STACK LOCKED MTX ******/ // Create Cache Data. - RsGxsIdCache pubcache(item, pubkey); + RsGxsIdCache pubcache(item, pubkey, tagList); mPublicKeyCache.store(id, pubcache); mPublicKeyCache.resize(); if (full_key_ok) { - RsGxsIdCache fullcache(item, fullkey); + RsGxsIdCache fullcache(item, fullkey, tagList); mPrivateKeyCache.store(id, fullcache); mPrivateKeyCache.resize(); } @@ -932,8 +1360,8 @@ bool p3IdService::cache_start_load() #endif // DEBUG_IDS uint32_t ansType = RS_TOKREQ_ANSTYPE_DATA; - RsTokReqOptions opts; - opts.mReqType = GXS_REQUEST_TYPE_GROUP_DATA; + RsTokReqOptions opts; + opts.mReqType = GXS_REQUEST_TYPE_GROUP_DATA; uint32_t token = 0; RsGenExchange::getTokenService()->requestGroupInfo(token, ansType, opts, groupIds); @@ -1041,8 +1469,8 @@ bool p3IdService::cache_request_ownids() uint32_t ansType = RS_TOKREQ_ANSTYPE_DATA; RsTokReqOptions opts; - opts.mReqType = GXS_REQUEST_TYPE_GROUP_DATA; - //opts.mSubscribeFlags = GXS_SERV::GROUP_SUBSCRIBE_ADMIN; + opts.mReqType = GXS_REQUEST_TYPE_GROUP_DATA; + //opts.mSubscribeFlags = GXS_SERV::GROUP_SUBSCRIBE_ADMIN; uint32_t token = 0; @@ -1132,8 +1560,8 @@ bool p3IdService::cachetest_getlist() #endif // DEBUG_IDS uint32_t ansType = RS_TOKREQ_ANSTYPE_LIST; - RsTokReqOptions opts; - opts.mReqType = GXS_REQUEST_TYPE_GROUP_IDS; + RsTokReqOptions opts; + opts.mReqType = GXS_REQUEST_TYPE_GROUP_IDS; uint32_t token = 0; RsGenExchange::getTokenService()->requestGroupInfo(token, ansType, opts); @@ -1154,11 +1582,11 @@ bool p3IdService::cachetest_handlerequest(uint32_t token) std::list grpIds; bool ok = RsGenExchange::getGroupList(token, grpIds); - if(ok) - { - std::list::iterator vit = grpIds.begin(); - for(; vit != grpIds.end(); vit++) - { + if(ok) + { + std::list::iterator vit = grpIds.begin(); + for(; vit != grpIds.end(); vit++) + { /* 5% chance of checking it! */ if (RSRandom::random_f32() < 0.25) { @@ -1189,7 +1617,7 @@ bool p3IdService::cachetest_handlerequest(uint32_t token) #endif // DEBUG_IDS // success! - seckey.print(std::cerr, 10); + seckey.print(std::cerr, 10); std::cerr << std::endl; @@ -1229,7 +1657,7 @@ bool p3IdService::cachetest_handlerequest(uint32_t token) } } } - } + } else { std::cerr << "p3IdService::cache_load_for_token() ERROR no data"; @@ -1245,13 +1673,13 @@ bool p3IdService::cachetest_handlerequest(uint32_t token) /************************************************************************************/ /* - * We have two background tasks that use the ServiceString: PGPHash & Reputation. + * We have three background tasks that use the ServiceString: PGPHash & Reputation & Recogn * * Only one task can be run at a time - otherwise potential overwrite issues. * So this part coordinates that part of the code. * - * - * + * We are going to have a "fetcher task", which gets all the UNPROCESSED / UPDATED GROUPS. + * and sets the CHECK_PGP, CHECK_RECOGN, etc... this will reduce the "Get All" calls. * */ @@ -1263,7 +1691,7 @@ bool p3IdService::CacheArbitration(uint32_t mode) if (!mBgSchedule_Active) { #ifdef DEBUG_IDS - std::cerr << "p3IdService::CacheArbitration() Okay"; + std::cerr << "p3IdService::CacheArbitration() Okay: mode " << mode; std::cerr << std::endl; #endif // DEBUG_IDS @@ -1273,7 +1701,7 @@ bool p3IdService::CacheArbitration(uint32_t mode) } #ifdef DEBUG_IDS - std::cerr << "p3IdService::CacheArbitration() Is busy..."; + std::cerr << "p3IdService::CacheArbitration() Is busy in mode: " << mBgSchedule_Mode; std::cerr << std::endl; #endif // DEBUG_IDS @@ -1347,6 +1775,13 @@ RsGenExchange::ServiceCreate_Return p3IdService::service_CreateGroup(RsGxsGrpIte return SERVICE_CREATE_FAIL; } +#ifdef DEBUG_IDS + std::cerr << "p3IdService::service_CreateGroup() Item is:"; + std::cerr << std::endl; + item->print(std::cerr); + std::cerr << std::endl; +#endif // DEBUG_IDS + /********************* TEMP HACK UNTIL GXS FILLS IN GROUP_ID *****************/ // find private admin key std::map::iterator mit = keySet.keys.begin(); @@ -1539,11 +1974,9 @@ bool p3IdService::pgphash_start() // Also need to use opts.groupFlags to filter stuff properly to REALID's only. // TODO - //uint32_t ansType = RS_TOKREQ_ANSTYPE_SUMMARY; uint32_t ansType = RS_TOKREQ_ANSTYPE_DATA; - RsTokReqOptions opts; - //opts.mReqType = GXS_REQUEST_TYPE_GROUP_META; - opts.mReqType = GXS_REQUEST_TYPE_GROUP_DATA; + RsTokReqOptions opts; + opts.mReqType = GXS_REQUEST_TYPE_GROUP_DATA; uint32_t token = 0; RsGenExchange::getTokenService()->requestGroupInfo(token, ansType, opts); @@ -1711,29 +2144,6 @@ bool p3IdService::pgphash_process() ssdata.pgp.idKnown = true; ssdata.pgp.pgpId = pgpId.toStdString(); -// SHOULD BE PUSHED TO CACHE! -#if 0 - id.mGpgIdKnown = true; - - id.mGpgId = *it; - id.mGpgName = details.name; - id.mGpgEmail = details.email; - - if (*it == ownId) - { - id.mIdType |= RSID_RELATION_YOURSELF; - } - else if (rsPeers->isGPGAccepted(*it)) - { - id.mIdType |= RSID_RELATION_FRIEND; - } - else - { - id.mIdType |= RSID_RELATION_OTHER; - } - -#endif - } else { @@ -1768,7 +2178,7 @@ bool p3IdService::checkId(const RsGxsIdGroup &grp, PGPIdType &pgpId) std::cerr << std::endl; #endif // DEBUG_IDS - /* some sanity checking... make sure hash is the right size */ + /* some sanity checking... make sure hash is the right size */ #ifdef DEBUG_IDS std::cerr << "p3IdService::checkId() PgpIdHash is: " << grp.mPgpIdHash; @@ -1903,13 +2313,13 @@ void calcPGPHash(const RsGxsId &id, const PGPFingerprintType &pgp, GxsIdPgpHash { unsigned char signature[SHA_DIGEST_LENGTH]; /* hash id + pubkey => pgphash */ - SHA_CTX *sha_ctx = new SHA_CTX; - SHA1_Init(sha_ctx); + SHA_CTX *sha_ctx = new SHA_CTX; + SHA1_Init(sha_ctx); - SHA1_Update(sha_ctx, id.c_str(), id.length()); // TO FIX ONE DAY. - SHA1_Update(sha_ctx, pgp.toByteArray(), pgp.SIZE_IN_BYTES); - SHA1_Final(signature, sha_ctx); - hash = GxsIdPgpHash(signature); + SHA1_Update(sha_ctx, id.c_str(), id.length()); // TO FIX ONE DAY. + SHA1_Update(sha_ctx, pgp.toByteArray(), pgp.SIZE_IN_BYTES); + SHA1_Final(signature, sha_ctx); + hash = GxsIdPgpHash(signature); #ifdef DEBUG_IDS std::cerr << "calcPGPHash():"; @@ -1922,9 +2332,325 @@ void calcPGPHash(const RsGxsId &id, const PGPFingerprintType &pgp, GxsIdPgpHash std::cerr << std::endl; #endif // DEBUG_IDS - delete sha_ctx; + delete sha_ctx; } +/************************************************************************************/ +/************************************************************************************/ +/************************************************************************************/ +/************************************************************************************/ + +/* Task to validate Recogn Tags. + * + * Info to be stored in GroupServiceString + Cache. + **/ + + +bool p3IdService::recogn_start() +{ + if (!CacheArbitration(BG_RECOGN)) + { +#ifdef DEBUG_RECOGN + std::cerr << "p3IdService::recogn_start() Other Events running... Rescheduling"; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + + /* reschedule in a bit */ + RsTickEvent::schedule_in(GXSID_EVENT_RECOGN, RECOGN_RETRY_PERIOD); + return false; + } + + // SCHEDULE NEXT ONE. + RsTickEvent::schedule_in(GXSID_EVENT_RECOGN, RECOGN_PERIOD); + + +#ifdef DEBUG_RECOGN + std::cerr << "p3IdService::recogn_start() making request"; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + + std::list recognList; + { + RsStackMutex stack(mIdMtx); /********** STACK LOCKED MTX ******/ + + recognList = mRecognGroupIds; + mRecognGroupIds.clear(); + } + + if (recognList.empty()) + { +#ifdef DEBUG_RECOGN + std::cerr << "p3IdService::recogn_start() List is Empty, cancelling"; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + + // FINISHED. + CacheArbitrationDone(BG_RECOGN); + return false; + } + + uint32_t ansType = RS_TOKREQ_ANSTYPE_DATA; + RsTokReqOptions opts; + opts.mReqType = GXS_REQUEST_TYPE_GROUP_DATA; + uint32_t token = 0; + + RsGenExchange::getTokenService()->requestGroupInfo(token, ansType, opts, recognList); + GxsTokenQueue::queueRequest(token, GXSIDREQ_RECOGN); + return true; + +} + + +bool p3IdService::recogn_handlerequest(uint32_t token) +{ +#ifdef DEBUG_RECOGN + std::cerr << "p3IdService::recogn_handlerequest(" << token << ")"; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + + std::vector grpData; + bool ok = RsGenExchange::getGroupData(token, grpData); + + if(ok) + { +#ifdef DEBUG_RECOGN + std::cerr << "p3IdService::recogn_request() Have " << grpData.size() << " Groups"; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + + std::vector::iterator vit = grpData.begin(); + + for(; vit != grpData.end(); vit++) + { + RsGxsIdGroupItem* item = dynamic_cast(*vit); + if (item) + { + +#ifdef DEBUG_RECOGN + std::cerr << "p3IdService::recogn_request() Group Id: " << item->meta.mGroupId; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + + RsStackMutex stack(mIdMtx); /********** STACK LOCKED MTX ******/ + mRecognGroupsToProcess.push_back(item); + } + else + { + delete (*vit); + } + } + } + else + { + std::cerr << "p3IdService::recogn_request() getGroupData ERROR"; + std::cerr << std::endl; + } + + // Schedule Processing. + RsTickEvent::schedule_in(GXSID_EVENT_RECOGN_PROC, RECOGN_PROC_PERIOD); + return true; +} + + +bool p3IdService::recogn_process() +{ + /* each time this is called - process one Id from mGroupsToProcess */ + RsGxsIdGroupItem *item; + bool isDone = false; + { + RsStackMutex stack(mIdMtx); /********** STACK LOCKED MTX ******/ + if (!mRecognGroupsToProcess.empty()) + { + item = mRecognGroupsToProcess.front(); + mGroupsToProcess.pop_front(); + +#ifdef DEBUG_RECOGN + std::cerr << "p3IdService::recogn_process() Popped Group: " << item->meta.mGroupId; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + } + else + { + isDone = true; + } + } + + if (isDone) + { +#ifdef DEBUG_RECOGN + std::cerr << "p3IdService::recogn_process() List Empty... Done"; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + // FINISHED. + CacheArbitrationDone(BG_RECOGN); + return true; + } + + + + std::list tagItems; + std::list::iterator it; + + recogn_extract_taginfo(item, tagItems); + + bool isPending = false; + int i = 1; + uint32_t tagValidFlags = 0; + for(it = tagItems.begin(); it != tagItems.end(); it++) + { + bool isTagPending = false; + bool isTagOk = recogn_checktag(item->meta.mGroupId, item->meta.mGroupName, *it, true, isPending); + if (isTagOk) + { + tagValidFlags |= i; + } + else + { + isPending |= isTagPending; + } + + delete *it; + i *= 2; + } + +#ifdef DEBUG_RECOGN + std::cerr << "p3IdService::recogn_process() Tags Checked, saving"; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + + SSGxsIdGroup ssdata; + ssdata.load(item->meta.mServiceString); // attempt load - okay if fails. + + ssdata.recogntags.setTags(true, isPending, tagValidFlags); + ssdata.recogntags.lastCheckTs = time(NULL); + ssdata.recogntags.publishTs = item->meta.mPublishTs; + + /* set new Group ServiceString */ + uint32_t dummyToken = 0; + std::string serviceString = ssdata.save(); + setGroupServiceString(dummyToken, item->meta.mGroupId, serviceString); + + cache_update_if_cached(item->meta.mGroupId, serviceString); + + delete item; + + // Schedule Next Processing. + RsTickEvent::schedule_in(GXSID_EVENT_RECOGN_PROC, RECOGN_PROC_PERIOD); + return false; // as there are more items on the queue to process. +} + + +bool p3IdService::recogn_checktag(const RsGxsId &id, const std::string &nickname, RsGxsRecognTagItem *item, bool doSignCheck, bool &isPending) +{ + +#ifdef DEBUG_RECOGN + std::cerr << "p3IdService::recogn_checktag() groupId: " << id; + std::cerr << std::endl; + std::cerr << "p3IdService::recogn_checktag() nickname: " << nickname; + std::cerr << std::endl; + std::cerr << "p3IdService::recogn_checktag() item: "; + std::cerr << std::endl; + ((RsGxsRecognTagItem *) item)->print(std::cerr); +#endif // DEBUG_RECOGN + + // To check: + // ------------------- + // date range. + // id matches. + // nickname matches. + // signer is valid. + // ------ + // signature is valid. (only if doSignCheck == true) + + time_t now = time(NULL); + isPending = false; + + // check date range. + if ((item->valid_from > now) || (item->valid_to < now)) + { +#ifdef DEBUG_RECOGN + std::cerr << "p3IdService::recogn_checktag() failed timestamp"; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + + return false; + } + + // id match. + if (id != item->identity) + { +#ifdef DEBUG_RECOGN + std::cerr << "p3IdService::recogn_checktag() failed identity"; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + return false; + } + + // nickname match. + if (nickname != item->nickname) + { +#ifdef DEBUG_RECOGN + std::cerr << "p3IdService::recogn_checktag() failed nickname"; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + return false; + } + + + + { + /* check they validity of the Tag */ + RsStackMutex stack(mIdMtx); /********** STACK LOCKED MTX ******/ + + + std::map::iterator it; + it = mRecognSignKeys.find(item->sign.keyId); + if (it == mRecognSignKeys.end()) + { +#ifdef DEBUG_RECOGN + std::cerr << "p3IdService::recogn_checktag() failed to find signkey"; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + + // If OldKey, then we don't want to reprocess. + if (mRecognOldSignKeys.end() != + mRecognOldSignKeys.find(item->sign.keyId)) + { + isPending = true; // need to reprocess later with new key + } + return false; + } + + // Check tag_class is okay for signer. + if (it->second->signing_classes.ids.end() == + std::find(it->second->signing_classes.ids.begin(), it->second->signing_classes.ids.end(), item->tag_class)) + { +#ifdef DEBUG_RECOGN + std::cerr << "p3IdService::recogn_checktag() failed signing_class check"; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + return false; + } + + // ALL Okay, just signature to check. + if (!doSignCheck) + { + return true; + } + + return RsRecogn::validateTagSignature(it->second, item); + } +} + + +void p3IdService::loadRecognKeys() +{ + RsStackMutex stack(mIdMtx); /**** LOCKED MUTEX ****/ + + RsRecogn::loadSigningKeys(mRecognSignKeys); +} + + /************************************************************************************/ /************************************************************************************/ @@ -2003,13 +2729,13 @@ void p3IdService::generateDummy_OwnIds() for(i = 0; i < nIds; i++) { RsGxsIdGroup id; - RsPeerDetails details; + RsPeerDetails details; id.mMeta.mGroupFlags = RSGXSID_GROUPFLAG_REALID; // HACK FOR DUMMY GENERATION. id.mMeta.mAuthorId = ownId; - if (rsPeers->getPeerDetails(ownId, details)) + if (rsPeers->getPeerDetails(ownId, details)) { std::ostringstream out; out << details.name << "_" << i + 1; @@ -2339,7 +3065,7 @@ bool p3IdService::background_checkTokenRequest() uint32_t anstype; time_t ts; - + status = RsGenExchange::getTokenService()->requestStatus(token); //checkRequestStatus(token, status, reqtype, anstype, ts); @@ -2390,7 +3116,7 @@ bool p3IdService::background_requestGroups() } uint32_t ansType = RS_TOKREQ_ANSTYPE_SUMMARY; - RsTokReqOptions opts; + RsTokReqOptions opts; std::list groupIds; /** @@ -2445,7 +3171,7 @@ bool p3IdService::background_requestNewMessages() for(it = modGroupList.begin(); it != modGroupList.end(); it++) { /*** TODO - uint32_t dummyToken = 0; + uint32_t dummyToken = 0; setGroupStatusFlags(dummyToken, it->mGroupId, 0, RSGXS_GROUP_STATUS_NEWMSG); ***/ @@ -2455,7 +3181,7 @@ bool p3IdService::background_requestNewMessages() } uint32_t ansType = RS_TOKREQ_ANSTYPE_SUMMARY; - RsTokReqOptions opts; + RsTokReqOptions opts; token = 0; /* TODO @@ -2501,7 +3227,7 @@ bool p3IdService::background_processNewMessages() * and flag these items as modified - so we rewrite them to the db later. * * If a message is not an original -> store groupId for requiring full analysis later. - */ + */ std::map::iterator mit; @@ -2639,7 +3365,7 @@ bool p3IdService::background_processNewMessages() #endif // DEBUG_IDS /* set Cache */ - uint32_t dummyToken = 0; + uint32_t dummyToken = 0; setGroupServiceString(dummyToken, mit->second.mGroupId, mit->second.mServiceString); } else @@ -2688,7 +3414,7 @@ bool p3IdService::background_FullCalcRequest() /* request the summary info from the parents */ uint32_t ansType = RS_TOKREQ_ANSTYPE_DATA; uint32_t token = 0; - RsTokReqOptions opts; + RsTokReqOptions opts; opts.mOptions = RS_TOKREQOPT_MSG_LATEST; RsGenExchange::getTokenService()->requestMsgInfo(token, ansType, opts, groupIds); @@ -2727,10 +3453,10 @@ bool p3IdService::background_processFullCalc() double rep_sum = 0; double rep_sumsq = 0; - std::vector opinions; - std::vector::iterator vit; + std::vector opinions; + std::vector::iterator vit; - if (!getMsgData(mBgToken, opinions)) + if (!getMsgData(mBgToken, opinions)) { std::cerr << "p3IdService::background_processFullCalc() ERROR Failed to get Opinions"; std::cerr << std::endl; @@ -2739,7 +3465,7 @@ bool p3IdService::background_processFullCalc() } std::string groupId; - for(vit = opinions.begin(); vit != opinions.end(); vit++) + for(vit = opinions.begin(); vit != opinions.end(); vit++) { RsGxsIdOpinion &opinion = *vit; @@ -2878,7 +3604,7 @@ std::ostream &operator<<(std::ostream &out, const RsGxsIdOpinion &opinion) - // Overloaded from GxsTokenQueue for Request callbacks. +// Overloaded from GxsTokenQueue for Request callbacks. void p3IdService::handleResponse(uint32_t token, uint32_t req_type) { #ifdef DEBUG_IDS @@ -2898,6 +3624,9 @@ void p3IdService::handleResponse(uint32_t token, uint32_t req_type) case GXSIDREQ_PGPHASH: pgphash_handlerequest(token); break; + case GXSIDREQ_RECOGN: + recogn_handlerequest(token); + break; case GXSIDREQ_CACHETEST: cachetest_handlerequest(token); break; @@ -2949,6 +3678,14 @@ void p3IdService::handle_event(uint32_t event_type, const std::string &elabel) pgphash_process(); break; + case GXSID_EVENT_RECOGN: + recogn_start(); + break; + + case GXSID_EVENT_RECOGN_PROC: + recogn_process(); + break; + case GXSID_EVENT_DUMMYDATA: generateDummyData(); break; diff --git a/libretroshare/src/services/p3idservice.h b/libretroshare/src/services/p3idservice.h index e9560e8df..a42712ed4 100644 --- a/libretroshare/src/services/p3idservice.h +++ b/libretroshare/src/services/p3idservice.h @@ -38,9 +38,12 @@ #include "util/rsmemcache.h" #include "util/rstickevent.h" +#include "util/rsrecogn.h" #include "pqi/authgpg.h" +#include "serialiser/rsgxsrecognitems.h" + /* * Identity Service * @@ -73,6 +76,27 @@ virtual std::string save() const; std::string pgpId; }; +class SSGxsIdRecognTags: public SSBit +{ + public: + SSGxsIdRecognTags() + :tagFlags(0), publishTs(0), lastCheckTs(0) { return; } + +virtual bool load(const std::string &input); +virtual std::string save() const; + + void setTags(bool processed, bool pending, uint32_t flags); + + bool tagsProcessed() const; // have we processed? + bool tagsPending() const; // should we reprocess? + bool tagValid(int i) const; + + time_t publishTs; + time_t lastCheckTs; + uint32_t tagFlags; +}; + + class SSGxsIdScore: public SSBit { public: @@ -113,11 +137,14 @@ virtual std::string save() const; // pgphash status SSGxsIdPgp pgp; + // recogTags. + SSGxsIdRecognTags recogntags; + // reputation score. SSGxsIdScore score; SSGxsIdCumulator opinion; SSGxsIdCumulator reputation; - + }; #define ID_LOCAL_STATUS_FULL_CALC_FLAG 0x00010000 @@ -133,10 +160,14 @@ class RsGxsIdCache { public: RsGxsIdCache(); - RsGxsIdCache(const RsGxsIdGroupItem *item, const RsTlvSecurityKey &in_pkey); + RsGxsIdCache(const RsGxsIdGroupItem *item, const RsTlvSecurityKey &in_pkey, + const std::list &tagList); void updateServiceString(std::string serviceString); + time_t mPublishTs; + std::list mRecognTags; // Only partially validated. + RsIdentityDetails details; RsTlvSecurityKey pubkey; }; @@ -175,6 +206,7 @@ virtual bool getMsgData(const uint32_t &token, std::vector &opin // These are local - and not exposed via RsIdentity. virtual bool createGroup(uint32_t& token, RsGxsIdGroup &group); +virtual bool updateGroup(uint32_t& token, RsGxsIdGroup &group); virtual bool createMsg(uint32_t& token, RsGxsIdOpinion &opinion); /**************** RsIdentity External Interface. @@ -197,6 +229,13 @@ virtual bool getOwnIds(std::list &ownIds); virtual bool submitOpinion(uint32_t& token, RsIdOpinion &opinion); virtual bool createIdentity(uint32_t& token, RsIdentityParameters ¶ms); +virtual bool updateIdentity(uint32_t& token, RsGxsIdGroup &group); + +virtual bool parseRecognTag(const RsGxsId &id, const std::string &nickname, + const std::string &tag, RsRecognTagDetails &details); +virtual bool getRecognTagRequest(const RsGxsId &id, const std::string &comment, + uint16_t tag_class, uint16_t tag_type, std::string &tag); + /**************** RsGixs Implementation * Notes: @@ -303,6 +342,32 @@ virtual void handle_event(uint32_t event_type, const std::string &elabel); std::map mPgpFingerprintMap; std::list mGroupsToProcess; +/************************************************************************ + * recogn processing. + * + */ + bool recogn_start(); + bool recogn_handlerequest(uint32_t token); + bool recogn_process(); + + // helper functions. + bool recogn_extract_taginfo(const RsGxsIdGroupItem *item, std::list &tagItems); + bool cache_process_recogntaginfo(const RsGxsIdGroupItem *item, std::list &tagList); + + bool recogn_checktag(const RsGxsId &id, const std::string &nickname, RsGxsRecognTagItem *item, bool doSignCheck, bool &isPending); + + void loadRecognKeys(); + + /* MUTEX PROTECTED DATA (mIdMtx - maybe should use a 2nd?) */ + + bool checkRecognSignature_locked(std::string encoded, RSA &key, std::string signature); + bool getRecognKey_locked(std::string signer, RSA &key); + + std::list mRecognGroupIds; + std::list mRecognGroupsToProcess; + std::map mRecognSignKeys; + std::map mRecognOldSignKeys; + /************************************************************************ * Below is the background task for processing opinions => reputations * diff --git a/libretroshare/src/services/p3posted.cc b/libretroshare/src/services/p3posted.cc index b6afe5e2d..46a4220a0 100644 --- a/libretroshare/src/services/p3posted.cc +++ b/libretroshare/src/services/p3posted.cc @@ -40,7 +40,6 @@ /**** * #define POSTED_DEBUG 1 ****/ -#define POSTED_DEBUG 1 RsPosted *rsPosted = NULL; diff --git a/libretroshare/src/turtle/rsturtleitem.cc b/libretroshare/src/turtle/rsturtleitem.cc index 9446e8686..5813fd84e 100644 --- a/libretroshare/src/turtle/rsturtleitem.cc +++ b/libretroshare/src/turtle/rsturtleitem.cc @@ -544,7 +544,7 @@ RsTurtleGenericDataItem::RsTurtleGenericDataItem(void *data,uint32_t pktsize) if(data_bytes != NULL) { - memcpy(data_bytes,data+offset,data_size) ; + memcpy(data_bytes,(void *)((uint8_t *)data+offset),data_size) ; offset += data_size ; } else @@ -585,7 +585,7 @@ bool RsTurtleGenericDataItem::serialize(void *data,uint32_t& pktsize) ok &= setRawUInt32(data, tlvsize, &offset, tunnel_id); ok &= setRawUInt32(data, tlvsize, &offset, data_size); - memcpy(data+offset,data_bytes,data_size) ; + memcpy((void *)((uint8_t *)data+offset),data_bytes,data_size) ; offset += data_size ; if (offset != tlvsize) diff --git a/libretroshare/src/util/rsmemcache.h b/libretroshare/src/util/rsmemcache.h index 5c12e3183..0f5fb966f 100644 --- a/libretroshare/src/util/rsmemcache.h +++ b/libretroshare/src/util/rsmemcache.h @@ -65,6 +65,7 @@ template class RsMemCache bool fetch(const Key &key, Value &data); Value &ref(const Key &key); // like map[] installs empty one if non-existent. bool store(const Key &key, const Value &data); + bool erase(const Key &key); // clean up cache. bool resize(); // should be called periodically to cleanup old entries. @@ -169,6 +170,47 @@ template bool RsMemCache::fetch(const Key &k } +template bool RsMemCache::erase(const Key &key) +{ +#ifdef DEBUG_RSMEMCACHE + std::cerr << "RsMemCache::erase()"; + std::cerr << std::endl; + printStats(std::cerr); +#endif // DEBUG_RSMEMCACHE + + typename std::map::iterator it; + it = mDataMap.find(key); + if (it == mDataMap.end()) + { +#ifdef DEBUG_RSMEMCACHE + std::cerr << "RsMemCache::erase(" << key << ") false"; + std::cerr << std::endl; +#endif // DEBUG_RSMEMCACHE + + mStats_accessmiss++; + return false; + } + +#ifdef DEBUG_RSMEMCACHE + std::cerr << "RsMemCache::erase(" << key << ") OK"; + std::cerr << std::endl; +#endif // DEBUG_RSMEMCACHE + + + /* get timestamps */ + time_t old_ts = it->second.ts; + time_t new_ts = 0; + + // remove from lru. + mDataMap.erase(it); + update_lrumap(key, old_ts, new_ts); + + mStats_access++; + return true; +} + + + template Value &RsMemCache::ref(const Key &key) { #ifdef DEBUG_RSMEMCACHE diff --git a/libretroshare/src/util/rsrecogn.cc b/libretroshare/src/util/rsrecogn.cc new file mode 100644 index 000000000..19c189c6b --- /dev/null +++ b/libretroshare/src/util/rsrecogn.cc @@ -0,0 +1,640 @@ +/* + * libretroshare/src/util: rsrecogn.cc + * + * RetroShare Utilities + * + * Copyright 2013 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.1 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 "pqi/pqi_base.h" + +#include "util/rsrecogn.h" +#include "util/radix64.h" +#include "util/rsstring.h" + +#include "gxs/gxssecurity.h" + +/*** + * #define DEBUG_RECOGN 1 + ***/ + +#define DEBUG_RECOGN 1 + +static std::string RecognKey = "MIICCgKCAgEA4/i2fy+zR27/H8fzphM8mR/Nz+yXjMJTtqKlCvEMQlyk7lKzDbKifNjGSiAXjSv3b9TRgMtje7hfEhs3//Oeu4KsCf6sz17aj2StBF579IdJTSUPDwq6jCsZ6NDEYpG8xz3FVV+Ac8q5Vpr/+jdg23ta09zq4aV8VIdIsroVOmZQqjwPcmQK57iWHd538i/XBtc2rnzbYq5bprnmtAKdx55gXVXDfALa0s6yR0HYvCaWguMEJhMIKWfi/9PEgLgwF9OmRwywc2TU/EdvYJo8fYHLfGk0PnYBuL1oSnn3cwAAef02W2JyCzQ84g30tLSUk+hC1LLi+iYj3x7IRR4q7Rlf/FYv/Q5fvjRtPT9eqM6fKyJ9ZO4NjlrSPFGydNbgABzP6WMhBzFjUkEKS27bGmr8Qxdj3Zp0TvR2IkyM6oM+6YknuM4RndUEgC1ZxtoIhugMjm6HdMQmoaHNK3kXewgQB90HHqzKA/J1gok3NcqL8Yls5g0LHepVHsU4cuaIqQr5yr665ZTLU2oqn1HIdkgydBYYUt6G3eWJKXYRbDhWPthGo/HK+W+iw6cTGWxzlCZS40EU9efxz4mDuhow67jOe704lBP3kiYXu05Y5uspaYnuvrvIwaRWBYapyR9UmKktnY8xJYrZvrcZgCovAbiodTzWeYg37xjFfGgYNI8CAwEAAQ=="; + +#define NUM_RECOGN_SIGN_KEYS 3 +static std::string RecognSigningKeys[NUM_RECOGN_SIGN_KEYS] = +{ + "AvMxAwAAA5YQMAAAABAANAAAAAoAAAABEEAAAAFMAKQAAAAmYjI2ZTUyNGFlZjczYmY3Y2MyMzUwNTc0ZTMyMjcxZWEAAAAAUl8ogFRAXAABEAAAARQwggEKAoIBAQCyblJK73O/fMI1BXTjInHqIWma62Z2r3K7/giT6Xm3k+lyNokvpR+I45XdEvPRmFVZmTU7XT2n3YiPDLe7y2r9fnYiLvBCdu+FBaVv5UQG8nvFGMLKbhdyRpOSBgDc+Y+8plMPn8jqgfNhLROMowmvDJQkJQjlm80d/9wj+VZ+tLiPPo8uOlghqNhdXDGK7HnfeLrJyD8kLEW7+4huaxR8IsLgjzuK8rovGLYCBcnx4TXvtbEeafJBBBt8S/GPeUaB1rxWpVV6fi+oBU6cvjbEqPzSalIrwNPyqlj+1SbL1jGEGEr1XIMzDa96SVsJ0F93lS3H9c8HdvByAifgzbPZAgMBAAEQUAAAAjIApAAAACZlM2Y4YjY3ZjJmYjM0NzZlZmYxZmM3ZjNhNjEzM2M5OQEgAAACBp1w449QGjchVotgHvGWRh18zpsDUHRv8PlRX1vXy8FMstTrnRjaDofFitmpJm8K6F1t/9jviCdB+BCvRzAS4SxER49YCBp04xZfX7c03xdq/e27jYRds2w6YHTiEgNi5v1cyWhrwDcCdefXRnHTH1UOw3jOoWnlnmM6jEsL39XI5fvsog9z8GxcG54APKA7JgiqhgMcrKRwNk74XJAzcjB6FS8xaV2gzpZZLNZ1TU+tJoLSiRqTU8UiAGbAR85lYLT5Ozdd2C+bTQ9f6vltz8bpzicJzxGCIsYtSL44InQsO/Oar9IgZu8QE4pTuunGJhVqEZru7ZN+oV+wXt51n+24SS0sNgNKVUFS74RfvsFi67CrXSWTOI8bVS0Lvv3EMWMdSF9dHGbdCFnp2/wqbW/4Qz7XYF4lcu9gLe4UtIrZ6TkAvBtnSfvTTdXj7kD6oHDjrUCjHPxdhz3BLRbj1wENZsoS3QDl22Ts7dbO8wHjutsS3/zx4DLlADoFlU8p7HJaCdrsq20P4WCeQJb6JbbLpGRAccKAidAPHMxQ4fr3b+GtjxpLJtXaytr4CPSXsCt4TloE9g5yCE6n/2UxQACp8Guh9l2MXmrD7qEGexhYqFB/OG84u3vL+gskmsKXTEqi2SiSmhvzta2p2hGCLCKRQeYbn+4TsIQfgWtYNQvC", + "AvMxAwAAA5YQMAAAABAANAAAAAoAAAACEEAAAAFMAKQAAAAmYjY0OTJkODMzNTI5ZjMxMGM1MmRjMDc3ZjBmZDgyMjcAAAAAUl8ogFRAXAABEAAAARQwggEKAoIBAQC2SS2DNSnzEMUtwHfw/YInm/XLXEUMktyZTmyMWACBbEfmU6aztT3vxz6UHoCBYtKkzKrfDZLvXe0a5TRLMmK+yfl5IzIVUPdqTg6FF3Bx/GXdj4v/ZP6lAuqY5YeI4wPcKldrrIJ9DTUdhZhgdtgDtxGvrXZ8eFjcl9zM+QEykYKMwfnTCixzVOPCCo3q1lJO13NmlhVQDO+f9vvTZsYDCcZHMqlKZWcCEyY1ZpQiCqlsL8wN6tKxMuSQO8EGdH/tNzsGHwCoZq6EEL7SX/pmc2ABjpDQTLixgXwJtCpw8Fwj1xiavsFFbqSLu3SjUCcrMz9f8U5p2ROyv//lWxsXAgMBAAEQUAAAAjIApAAAACZlM2Y4YjY3ZjJmYjM0NzZlZmYxZmM3ZjNhNjEzM2M5OQEgAAACBksDPQ93PdZBGCEnKXcQsdB4yBA9NpImVR81JZdPmWlTwZGAXGJwt4EkBcz+xdey84JDujVtHJUzIL9Ws/Jq5MuXHr0tP5ebah1GCQF2/Ov7sctUk3UPBxeroon7gZQhuzaIJVhl0rzwWriFUbTu7H7g9eaTHMvyfUg+S0Z2p+e0+PdL5rfGOJJZ6+NJCXxxbQ//cF4s0PAzkjAuwDmC+OiUiU5V6fY4XtRMCEI7w+UCj+wQn2Wu1Wc7xVM9uow13rGaLPYkWZ/9v+wNhg0KCsVfKGhkAGGzGyKI9LAppFVTu52pBlRu9Ung7VkhF0JC2aadYKKFl99wCbsGqUYN/gtfgHYCV24LNVah2dAy8CI9UmHdWk1kIwWazbPTYKLfpYCTFxqEqXqo3ijLf0YPsfhIvCQpc5VHAvLJlDm0RFKwzK6N9Zu9s9IvJHzIpaAAHCQJPtYxPwWMdt83njGo9wu1+aVkl5Sb5X8N16AybbnQ7fCBqJruGBM0LHtWVbHEiEygD7OStzyhT5rXKZSQYMA9I2CvK1t7qfDXDM40k8SVQ5CrS9R8x1wqQbe+DqNJ9tMfbUmN0xrO/w2pTl/4edKW30TShW/fr3vCWpVq8gcm3CVFSZUaC4T9wqH96K6KgIPbmg1Hk158pxXYXopEv6ZxR7UTPxKB0O22aIHB6UQ5", + "AvMxAwAAA5YQMAAAABAANAAAAAoAAAABEEAAAAFMAKQAAAAmOTdhNTJkMThjMDBjYWE3YmZlYmQ4NTg0MDJkMzBhY2QAAAAAUl8ogFRAXAABEAAAARQwggEKAoIBAQCXpS0YwAyqe/69hYQC0wrNz7eUHAmJfR5EV7NVFQeOxtTlFwbdvRMK8ZpfqEoRhIPXAYCc9Dv3F7WcmcFer8d50EWhlK7rCQScaRdwL1UmF1dUY8bR8QxhJOUgwmrlzeKOHi2DJ3/9AXm7NJR8XMJgHEQQwi3z/aQsWrwCUA0mk68C8a3vjLtcMj5XBuNXRtGZ9zFjiI9Xt19y0iIKdYpfzOnJTKVETcjH7XPBBbJETWkrEyToHXPjcfhESAbJDOoyfQQbxHMQNE7no7owN08LoWX2kOSGtl2m6JbE2OEdJig83a6U3PDYfYM5LCfsAJEIroYhB3qZJDE98zGC8jihAgMBAAEQUAAAAjIApAAAACZlM2Y4YjY3ZjJmYjM0NzZlZmYxZmM3ZjNhNjEzM2M5OQEgAAACBiwl7oRPJzLlwDd8AzVolFQH1ZS+MWLA4B1eHCjCXSMn+zS0Su6CrpC6/vLwECaKSfNZ8y7T2fNDPJHMLmc1F6jJkdNZq3TZGNRgJx24OF3G5MU6mAH7DBsz7muFto+URTJl9CdJviIyQAn5E+R4Gp531RJdKlbqJl/gWuQMVem+eo3elpVEn8Ckg0yvFaFdhGFTOPyrXOZ6fI0pdCX0SH2q/vAIxGDRzaSYmsR0Y+oYZs0AeRnZD9iEh1v17xnVEdSoLZmZbjlLXXgqhbdXGik6ZoXQg3bTfl5D1j8Tk/d/CXqf0SUKBnIafaNgUeQSMY95M3k3vjPQN7vHdXmg19GnqQmBnGq45qdKI7+0Erfhl4po1z6yVvx9JfIMIDOsKwO3U/As5zbO2BYso0pUP4+gndissfDfqlPRni3orA0tlV6NuLmXi1wkHCu8HQ8WOqEUlWDJNLNpHW5OmgjMFqlIPt7hX5jlc9eXd4oMyaqXm1Tg8Cgbh5DYaT9A7He47+QhqYlPygqK9Fm0ZnH3Yz51cm3p2tRB1JU7qH9h5UqLLKJMBuIx7e9L5ieTfzKmTw6tqpIpHpiR/8bSQlKkw2LxikFy3OXL5obY1t9sWk35BNZQqcqflI6mkPrvGQKwN+co8GjUon5/Y1HSM6ursaJtkD8dz+oXVyWAokkuD7QZ", + + +}; + + + +EVP_PKEY *RsRecogn::loadMasterKey() +{ + /* load master signing key */ + size_t keylen; + char *keyptr; + + Radix64::decode(RecognKey, keyptr, keylen); + + const unsigned char *keyptr2 = (const unsigned char *) keyptr; + long keylen2 = keylen; + + RSA *rsakey = d2i_RSAPublicKey(NULL, &(keyptr2), keylen2); + delete []keyptr; + + if (!rsakey) + { +#ifdef DEBUG_RECOGN + std::cerr << "RsRecogn::loadMasterKeys() failed rsakey load"; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + return NULL; + } + + + EVP_PKEY *signKey = EVP_PKEY_new(); + EVP_PKEY_assign_RSA(signKey, rsakey); + + return signKey; +} + + +bool RsRecogn::loadSigningKeys(std::map &signMap) +{ + + EVP_PKEY *signKey = loadMasterKey(); + RsGxsRecognSerialiser recognSerialiser; + + if (!signKey) + { + std::cerr << "RsRecogn::loadSigningKeys() missing Master Key"; + return false; + } + + + time_t now = time(NULL); + + for(int i = 0; i < NUM_RECOGN_SIGN_KEYS; i++) + { + char *signerbuf; + size_t len; + Radix64::decode(RecognSigningKeys[i], signerbuf, len); + + uint32_t pktsize = len; + RsItem *pktitem = recognSerialiser.deserialise(signerbuf, &pktsize); + RsGxsRecognSignerItem *item = dynamic_cast(pktitem); + + delete []signerbuf; + + if (!item) + { +#ifdef DEBUG_RECOGN + std::cerr << "RsRecogn::loadSigningKeys() failed to deserialise SignerItem"; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + continue; + } + +#ifdef DEBUG_RECOGN + std::cerr << "RsRecogn::loadSigningKeys() SignerItem: "; + std::cerr << std::endl; + item->print(std::cerr); +#endif // DEBUG_RECOGN + + /* check dates */ + if ((item->key.startTS > (unsigned) now) || (item->key.endTS < (unsigned) now)) + { +#ifdef DEBUG_RECOGN + std::cerr << "RsRecogn::loadSigningKeys() failed timestamp"; + std::cerr << std::endl; + std::cerr << "RsRecogn::loadSigningKeys() key.startTS: " << item->key.startTS; + std::cerr << std::endl; + std::cerr << "RsRecogn::loadSigningKeys() now: " << now; + std::cerr << std::endl; + std::cerr << "RsRecogn::loadSigningKeys() key.endTS: " << item->key.endTS; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + delete item; + continue; + } + + /* check signature */ + RsTlvKeySignature signature = item->sign; + item->sign.TlvShallowClear(); + + unsigned int siglen = signature.signData.bin_len; + unsigned char *sigbuf = (unsigned char *) signature.signData.bin_data; + + /* store in */ + uint32_t datalen = recognSerialiser.size(item); + uint8_t *data = (uint8_t *) malloc(datalen); + uint32_t pktlen = datalen; + int signOk = 0; + + if (recognSerialiser.serialise(item, data, &pktlen)) + { + EVP_MD_CTX *mdctx = EVP_MD_CTX_create(); + + EVP_VerifyInit(mdctx, EVP_sha1()); + EVP_VerifyUpdate(mdctx, data, pktlen); + signOk = EVP_VerifyFinal(mdctx, sigbuf, siglen, signKey); + + EVP_MD_CTX_destroy(mdctx); + + item->sign = signature; + signature.TlvShallowClear(); + + if (signOk) + { +#ifdef DEBUG_RECOGN + std::cerr << "RsRecogn::loadSigningKeys() signature ok"; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + std::string signerId = item->key.keyId; + signMap[signerId] = item; + } + } + + if (!signOk) + { +#ifdef DEBUG_RECOGN + std::cerr << "RsRecogn::loadSigningKeys() signature failed"; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + delete item; + } + + free(data); + } + + /* clean up */ + EVP_PKEY_free(signKey); + return true; +} + + + +bool RsRecogn::validateTagSignature(RsGxsRecognSignerItem *signer, RsGxsRecognTagItem *item) +{ + if (item->sign.keyId != signer->key.keyId) + { +#ifdef DEBUG_RECOGN + std::cerr << "RsRecogn::validateTagSignature() keyId mismatch"; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + return false; + } + + const unsigned char *keyptr = (const unsigned char *) signer->key.keyData.bin_data; + long keylen = signer->key.keyData.bin_len; + + /* extract admin key */ + RSA *rsakey = d2i_RSAPublicKey(NULL, &(keyptr), keylen); + if (!rsakey) + { +#ifdef DEBUG_RECOGN + std::cerr << "RsRecogn::validateTagSignature() failed extract signkey"; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + return false; + } + + /* check signature */ + RsTlvKeySignature signature = item->sign; + item->sign.TlvShallowClear(); + + unsigned int siglen = signature.signData.bin_len; + unsigned char *sigbuf = (unsigned char *) signature.signData.bin_data; + + EVP_MD_CTX *mdctx = EVP_MD_CTX_create(); + EVP_PKEY *signKey = EVP_PKEY_new(); + EVP_PKEY_assign_RSA(signKey, rsakey); + + + /* store in */ + RsGxsRecognSerialiser serialiser; + + uint32_t datalen = serialiser.size(item); + uint8_t *data = (uint8_t *) malloc(datalen); + int signOk = 0; + + uint32_t pktlen = datalen; + if (serialiser.serialise(item, data, &pktlen)) + { + + EVP_VerifyInit(mdctx, EVP_sha1()); + EVP_VerifyUpdate(mdctx, data, pktlen); + signOk = EVP_VerifyFinal(mdctx, sigbuf, siglen, signKey); +#ifdef DEBUG_RECOGN + std::cerr << "RsRecogn::validateTagSignature() sign_result: " << signOk; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + } + else + { +#ifdef DEBUG_RECOGN + std::cerr << "RsRecogn::validateTagSignature() failed to serialise"; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + } + + // Clean up. + item->sign = signature; + signature.TlvShallowClear(); + + EVP_MD_CTX_destroy(mdctx); + EVP_PKEY_free(signKey); + + free(data); + + return (signOk == 1); +} + + +bool rsa_sanity_check(RSA *rsa) +{ + std::cerr << "rsa_sanity_check()"; + std::cerr << std::endl; + + if (!rsa) + { + std::cerr << "rsa_sanity_check() RSA == NULL"; + std::cerr << std::endl; + return false; + } + + RSA *pubkey = RSAPublicKey_dup(rsa); + + std::string signId = RsRecogn::getRsaKeyId(rsa); + std::string signId2 = RsRecogn::getRsaKeyId(pubkey); + + bool ok = true; + if (signId != signId2) + { + std::cerr << "rsa_sanity_check() ERROR SignId Failure"; + std::cerr << std::endl; + ok = false; + } + + if (1 != RSA_check_key(rsa)) + { + std::cerr << "rsa_sanity_check() ERROR RSA key is not private"; + std::cerr << std::endl; + ok = false; + } + +#if 0 + if (1 == RSA_check_key(pubkey)) + { + std::cerr << "rsa_sanity_check() ERROR RSA dup key is private"; + std::cerr << std::endl; + ok = false; + } +#endif + + RSA_free(pubkey); + + if (!ok) + { + exit(1); + } + + return true; +} + + + +bool RsRecogn::signTag(EVP_PKEY *signKey, RsGxsRecognTagItem *item) +{ + RsGxsRecognSerialiser serialiser; + + RSA *rsa = EVP_PKEY_get1_RSA(signKey); + std::string signId = getRsaKeyId(rsa); + rsa_sanity_check(rsa); + RSA_free(rsa); + + item->sign.TlvClear(); + + /* write out the item for signing */ + uint32_t len = serialiser.size(item); + char *buf = new char[len]; + if (!serialiser.serialise(item, buf, &len)) + { +#ifdef DEBUG_RECOGN + std::cerr << "RsRecogn::signTag() Failed serialise TagItem:"; + std::cerr << std::endl; + item->print(std::cerr); +#endif // DEBUG_RECOGN + delete []buf; + return false; + } + + /* calc and check signature */ + EVP_MD_CTX *mdctx = EVP_MD_CTX_create(); + + EVP_SignInit(mdctx, EVP_sha1()); + EVP_SignUpdate(mdctx, buf, len); + + unsigned int siglen = EVP_PKEY_size(signKey); + unsigned char sigbuf[siglen]; + EVP_SignFinal(mdctx, sigbuf, &siglen, signKey); + + /* save signature */ + item->sign.signData.setBinData(sigbuf, siglen); + item->sign.keyId = signId; + + /* clean up */ + EVP_MD_CTX_destroy(mdctx); + delete []buf; + + return true; +} + +bool RsRecogn::signSigner(EVP_PKEY *signKey, RsGxsRecognSignerItem *item) +{ + std::cerr << "RsRecogn::signSigner()"; + std::cerr << std::endl; + + RsGxsRecognSerialiser serialiser; + + std::cerr << "RsRecogn::signSigner() Checking Key"; + std::cerr << std::endl; + + RSA *rsa = EVP_PKEY_get1_RSA(signKey); + std::string signId = getRsaKeyId(rsa); + rsa_sanity_check(rsa); + RSA_free(rsa); + + std::cerr << "RsRecogn::signSigner() Key Okay"; + std::cerr << std::endl; + + item->sign.TlvClear(); + + /* write out the item for signing */ + uint32_t len = serialiser.size(item); + char *buf = new char[len]; + if (!serialiser.serialise(item, buf, &len)) + { +#ifdef DEBUG_RECOGN + std::cerr << "RsRecogn::signSigner() Failed serialise SignerItem:"; + std::cerr << std::endl; + item->print(std::cerr); +#endif // DEBUG_RECOGN + delete []buf; + return false; + } + + /* calc and check signature */ + EVP_MD_CTX *mdctx = EVP_MD_CTX_create(); + + EVP_SignInit(mdctx, EVP_sha1()); + EVP_SignUpdate(mdctx, buf, len); + + unsigned int siglen = EVP_PKEY_size(signKey); + unsigned char sigbuf[siglen]; + EVP_SignFinal(mdctx, sigbuf, &siglen, signKey); + + /* save signature */ + item->sign.signData.setBinData(sigbuf, siglen); + item->sign.keyId = signId; + + /* clean up */ + EVP_MD_CTX_destroy(mdctx); + delete []buf; + + return true; +} + + +bool RsRecogn::signTagRequest(EVP_PKEY *signKey, RsGxsRecognReqItem *item) +{ + std::cerr << "RsRecogn::signTagRequest()"; + std::cerr << std::endl; + + RsGxsRecognSerialiser serialiser; + + RSA *rsa = EVP_PKEY_get1_RSA(signKey); + std::string signId = getRsaKeyId(rsa); + rsa_sanity_check(rsa); + RSA_free(rsa); + + item->sign.TlvClear(); + + /* write out the item for signing */ + uint32_t len = serialiser.size(item); + char *buf = new char[len]; + if (!serialiser.serialise(item, buf, &len)) + { +#ifdef DEBUG_RECOGN + std::cerr << "RsRecogn::signTagRequest() Failed serialise Tag Request:"; + std::cerr << std::endl; + item->print(std::cerr); +#endif // DEBUG_RECOGN + delete []buf; + return false; + } + + /* calc and check signature */ + EVP_MD_CTX *mdctx = EVP_MD_CTX_create(); + + EVP_SignInit(mdctx, EVP_sha1()); + EVP_SignUpdate(mdctx, buf, len); + + unsigned int siglen = EVP_PKEY_size(signKey); + unsigned char sigbuf[siglen]; + EVP_SignFinal(mdctx, sigbuf, &siglen, signKey); + + /* save signature */ + item->sign.signData.setBinData(sigbuf, siglen); + item->sign.keyId = signId; + + /* clean up */ + EVP_MD_CTX_destroy(mdctx); + delete []buf; + + return true; +} + + +bool RsRecogn::itemToRadix64(RsItem *item, std::string &radstr) +{ + RsGxsRecognSerialiser serialiser; + + /* write out the item for signing */ + uint32_t len = serialiser.size(item); + char *buf = new char[len]; + if (!serialiser.serialise(item, buf, &len)) + { + return false; + } + + radstr.clear(); + Radix64::encode(buf, len, radstr); + + return true; +} + + +std::string RsRecogn::getRsaKeyId(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; +} + + + +RsGxsRecognTagItem *RsRecogn::extractTag(const std::string &encoded) +{ + // Decode from Radix64 encoded Packet. + size_t buflen; + char *buffer; + uint32_t pktsize; + + Radix64::decode(encoded, buffer, buflen); + pktsize = buflen; + + RsGxsRecognSerialiser serialiser; + RsItem *item = serialiser.deserialise(buffer, &pktsize); + delete []buffer; + + if (!item) + { +#ifdef DEBUG_RECOGN + std::cerr << "RsRecogn::extractTag() ERROR Deserialise failed"; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + return NULL; + } + + RsGxsRecognTagItem *tagitem = dynamic_cast(item); + + if (!tagitem) + { +#ifdef DEBUG_RECOGN + std::cerr << "RsRecogn::extractTag() ERROR Not TagItem, is: "; + std::cerr << std::endl; + item->print(std::cerr); +#endif // DEBUG_RECOGN + delete item; + } + + return tagitem; +} + + +bool RsRecogn::createTagRequest(const RsTlvSecurityKey &key, const std::string &id, const std::string &nickname, uint16_t tag_class, uint16_t tag_type, const std::string &comment, std::string &tag) +{ + RsGxsRecognReqItem *item = new RsGxsRecognReqItem(); + + EVP_PKEY *signKey = EVP_PKEY_new(); + RSA *rsakey = GxsSecurity::extractPrivateKey(key); + if (!rsakey) + { +#ifdef DEBUG_RECOGN + std::cerr << "RsRecogn::createTagRequest() Failed to extract key"; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + return false; + } + + if (!EVP_PKEY_assign_RSA(signKey, rsakey)) + { +#ifdef DEBUG_RECOGN + std::cerr << "RsRecogn::createTagRequest() Failed to assign key"; + std::cerr << std::endl; +#endif // DEBUG_RECOGN + return false; + } + + item->issued_at = time(NULL); + item->period = 365 * 24 * 3600; + item->tag_class = tag_class; + item->tag_type = tag_type; + + item->nickname = nickname; + item->identity = id; + item->comment = comment; + + bool signOk = RsRecogn::signTagRequest(signKey,item); + EVP_PKEY_free(signKey); + + if (!signOk) + { +#ifdef DEBUG_RECOGN + std::cerr << "RsRecogn::createTagRequest() Failed to sign Tag Request:"; + std::cerr << std::endl; + item->print(std::cerr); +#endif // DEBUG_RECOGN + delete item; + return false; + } + + /* write out the item for signing */ + RsGxsRecognSerialiser serialiser; + uint32_t len = serialiser.size(item); + char *buf = new char[len]; + bool serOk = serialiser.serialise(item, buf, &len); + delete item; + + if (serOk) + { + Radix64::encode(buf, len, tag); + } + + delete []buf; + + if (!serOk) + { +#ifdef DEBUG_RECOGN + std::cerr << "RsRecogn::createTagRequest() Failed serialise Tag Request:"; + std::cerr << std::endl; + item->print(std::cerr); +#endif // DEBUG_RECOGN + return false; + } + + return serOk; +} + + diff --git a/libretroshare/src/util/rsrecogn.h b/libretroshare/src/util/rsrecogn.h new file mode 100644 index 000000000..a8df7f25e --- /dev/null +++ b/libretroshare/src/util/rsrecogn.h @@ -0,0 +1,61 @@ + +/* + * libretroshare/src/util: rsrecogn.h + * + * RetroShare Utilities + * + * Copyright 2013 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.1 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 RSUTIL_RECOGN_H +#define RSUTIL_RECOGN_H + +#include +#include +#include +#include + +#include "serialiser/rsgxsrecognitems.h" + +namespace RsRecogn { + +EVP_PKEY * loadMasterKey(); +bool loadSigningKeys(std::map &signMap); +bool validateTagSignature(RsGxsRecognSignerItem *signer, RsGxsRecognTagItem *item); + +bool signTag(EVP_PKEY *signKey, RsGxsRecognTagItem *item); +bool signSigner(EVP_PKEY *signKey, RsGxsRecognSignerItem *item); +bool signTagRequest(EVP_PKEY *signKey, RsGxsRecognReqItem *item); + +bool itemToRadix64(RsItem *item, std::string &radstr); + +std::string getRsaKeyId(RSA *pubkey); + +RsGxsRecognTagItem *extractTag(const std::string &encoded); + +bool createTagRequest(const RsTlvSecurityKey &key, + const std::string &id, const std::string &nickname, + uint16_t tag_class, uint16_t tag_type, + const std::string &comment, std::string &tag); + +} + +#endif From 2ce92da8ad05c010787c0adf1c4f9004c03d1c7c Mon Sep 17 00:00:00 2001 From: drbob Date: Sun, 20 Oct 2013 09:56:12 +0000 Subject: [PATCH 44/83] GUI modifications to incorporate RecognTags. - Enable EditDialog for own Ids. - Addition, parsing and removal of Tags in IdEditDialog. - Display of Tags (only text) in GxsId Label/Chooser/TreewidgetItem .. TODO: - Add icon sets for RecognTags. - display of Tags as Icons. git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.5-gxs_finale@6855 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- retroshare-gui/src/gui/Identity/IdDialog.cpp | 3 +- .../src/gui/Identity/IdEditDialog.cpp | 287 ++++++++++++--- .../src/gui/Identity/IdEditDialog.h | 20 +- .../src/gui/Identity/IdEditDialog.ui | 332 +++++++++++------- retroshare-gui/src/gui/gxs/GxsIdChooser.cpp | 11 + retroshare-gui/src/gui/gxs/GxsIdLabel.cpp | 10 + .../src/gui/gxs/GxsIdTreeWidgetItem.cpp | 11 + retroshare-gui/src/retroshare-gui.pro | 7 +- 8 files changed, 507 insertions(+), 174 deletions(-) diff --git a/retroshare-gui/src/gui/Identity/IdDialog.cpp b/retroshare-gui/src/gui/Identity/IdDialog.cpp index 541615d9e..f1702ac11 100644 --- a/retroshare-gui/src/gui/Identity/IdDialog.cpp +++ b/retroshare-gui/src/gui/Identity/IdDialog.cpp @@ -473,8 +473,7 @@ void IdDialog::insertIdDetails(uint32_t token) mStateHelper->setWidgetEnabled(ui.pushButton_Reputation, false); // No Delete Ids yet! mStateHelper->setWidgetEnabled(ui.pushButton_Delete, /*true*/ false); - // No Editing Ids yet! - mStateHelper->setWidgetEnabled(ui.pushButton_EditId, /*true*/ false); + mStateHelper->setWidgetEnabled(ui.pushButton_EditId, true); } else { diff --git a/retroshare-gui/src/gui/Identity/IdEditDialog.cpp b/retroshare-gui/src/gui/Identity/IdEditDialog.cpp index de204ae84..9593746e4 100644 --- a/retroshare-gui/src/gui/Identity/IdEditDialog.cpp +++ b/retroshare-gui/src/gui/Identity/IdEditDialog.cpp @@ -61,10 +61,19 @@ IdEditDialog::IdEditDialog(QWidget *parent) /* Connect signals */ connect(ui.radioButton_GpgId, SIGNAL(toggled(bool)), this, SLOT(idTypeToggled(bool))); connect(ui.radioButton_Pseudo, SIGNAL(toggled(bool)), this, SLOT(idTypeToggled(bool))); - connect(ui.buttonBox, SIGNAL(accepted()), this, SLOT(updateId())); + connect(ui.buttonBox, SIGNAL(accepted()), this, SLOT(submit())); connect(ui.buttonBox, SIGNAL(rejected()), this, SLOT(close())); + connect(ui.plainTextEdit_Tag, SIGNAL(textChanged()), this, SLOT(checkNewTag())); + connect(ui.pushButton_Tag, SIGNAL(clicked(bool)), this, SLOT(addRecognTag())); + connect(ui.toolButton_Tag1, SIGNAL(clicked(bool)), this, SLOT(rmTag1())); + connect(ui.toolButton_Tag2, SIGNAL(clicked(bool)), this, SLOT(rmTag2())); + connect(ui.toolButton_Tag3, SIGNAL(clicked(bool)), this, SLOT(rmTag3())); + connect(ui.toolButton_Tag4, SIGNAL(clicked(bool)), this, SLOT(rmTag4())); + connect(ui.toolButton_Tag5, SIGNAL(clicked(bool)), this, SLOT(rmTag5())); + mIdQueue = new TokenQueue(rsIdentity->getTokenService(), this); + ui.pushButton_Tag->setEnabled(false); } void IdEditDialog::setupNewId(bool pseudo) @@ -89,6 +98,10 @@ void IdEditDialog::setupNewId(bool pseudo) // force - incase it wasn't triggered. idTypeToggled(true); + + ui.frame_Tags->setHidden(true); + ui.radioButton_GpgId->setEnabled(true); + ui.radioButton_Pseudo->setEnabled(true); } void IdEditDialog::idTypeToggled(bool checked) @@ -144,7 +157,6 @@ void IdEditDialog::loadExistingId(uint32_t token) mStateHelper->setLoading(IDEDITDIALOG_LOADID, false); /* get details from libretroshare */ - RsGxsIdGroup data; std::vector datavector; if (!rsIdentity->getGroupData(token, datavector)) { @@ -166,9 +178,9 @@ void IdEditDialog::loadExistingId(uint32_t token) return; } - data = datavector[0]; + mEditGroup = datavector[0]; - bool realid = (data.mMeta.mGroupFlags & RSGXSID_GROUPFLAG_REALID); + bool realid = (mEditGroup.mMeta.mGroupFlags & RSGXSID_GROUPFLAG_REALID); if (realid) { @@ -178,25 +190,28 @@ void IdEditDialog::loadExistingId(uint32_t token) { ui.radioButton_Pseudo->setChecked(true); } + // these are not editable for existing Id. + ui.radioButton_GpgId->setEnabled(false); + ui.radioButton_Pseudo->setEnabled(false); // DOES THIS TRIGGER ALREADY??? // force - incase it wasn't triggered. idTypeToggled(true); - ui.lineEdit_Nickname->setText(QString::fromUtf8(data.mMeta.mGroupName.c_str())); - ui.lineEdit_KeyId->setText(QString::fromStdString(data.mMeta.mGroupId)); + ui.lineEdit_Nickname->setText(QString::fromUtf8(mEditGroup.mMeta.mGroupName.c_str())); + ui.lineEdit_KeyId->setText(QString::fromStdString(mEditGroup.mMeta.mGroupId)); if (realid) { - ui.lineEdit_GpgHash->setText(QString::fromStdString(data.mPgpIdHash)); + ui.lineEdit_GpgHash->setText(QString::fromStdString(mEditGroup.mPgpIdHash)); - if (data.mPgpKnown) + if (mEditGroup.mPgpKnown) { RsPeerDetails details; - rsPeers->getGPGDetails(data.mPgpId, details); + rsPeers->getGPGDetails(mEditGroup.mPgpId, details); ui.lineEdit_GpgName->setText(QString::fromUtf8(details.name.c_str())); - ui.lineEdit_GpgId->setText(QString::fromStdString(data.mPgpId)); + ui.lineEdit_GpgId->setText(QString::fromStdString(mEditGroup.mPgpId)); } else { @@ -210,53 +225,209 @@ void IdEditDialog::loadExistingId(uint32_t token) ui.lineEdit_GpgId->setText(tr("N/A")); ui.lineEdit_GpgName->setText(tr("N/A")); } + + // RecognTags. + ui.frame_Tags->setHidden(false); + + loadRecognTags(); } -void IdEditDialog::updateId() +#define MAX_RECOGN_TAGS 5 + +void IdEditDialog::checkNewTag() { - RsGxsIdGroup rid; - // Must set, Nickname, KeyId(if existing), mIdType, GpgId. + std::string tag = ui.plainTextEdit_Tag->toPlainText().toStdString(); + std::string id = ui.lineEdit_KeyId->text().toStdString(); + std::string name = ui.lineEdit_Nickname->text().toUtf8().data(); - rid.mMeta.mGroupName = ui.lineEdit_Nickname->text().toUtf8().constData(); + QString desc; + bool ok = tagDetails(id, name, tag, desc); + ui.label_TagCheck->setText(desc); - if (rid.mMeta.mGroupName.size() < 2) + if (mEditGroup.mRecognTags.size() >= MAX_RECOGN_TAGS) { - std::cerr << "IdEditDialog::updateId() Nickname too short"; + ok = false; + } + + ui.pushButton_Tag->setEnabled(ok); +} + +void IdEditDialog::addRecognTag() +{ + std::string tag = ui.plainTextEdit_Tag->toPlainText().toStdString(); + if (mEditGroup.mRecognTags.size() >= MAX_RECOGN_TAGS) + { + std::cerr << "IdEditDialog::addRecognTag() Too many Tags, delete one first"; + std::cerr << std::endl; + } + + mEditGroup.mRecognTags.push_back(tag); + loadRecognTags(); +} + +void IdEditDialog::rmTag1() +{ + rmTag(0); +} + +void IdEditDialog::rmTag2() +{ + rmTag(1); +} + +void IdEditDialog::rmTag3() +{ + rmTag(2); +} + +void IdEditDialog::rmTag4() +{ + rmTag(3); +} + +void IdEditDialog::rmTag5() +{ + rmTag(4); +} + +void IdEditDialog::rmTag(int idx) +{ + std::list::iterator it; + int i = 0; + for(it = mEditGroup.mRecognTags.begin(); it != mEditGroup.mRecognTags.end() && (idx < i); it++, i++) ; + + if (it != mEditGroup.mRecognTags.end()) + { + mEditGroup.mRecognTags.erase(it); + } + loadRecognTags(); +} + +bool IdEditDialog::tagDetails(const std::string &id, const std::string &name, const std::string &tag, QString &desc) +{ + if (tag.empty()) + { + desc += "Empty Tag"; + return false; + } + + /* extract details for each tag */ + RsRecognTagDetails tagDetails; + + bool ok = false; + if (rsIdentity->parseRecognTag(id, name, tag, tagDetails)) + { + desc += QString::number(tagDetails.tag_class); + desc += ":"; + desc += QString::number(tagDetails.tag_type); + + if (tagDetails.is_valid) + { + ok = true; + desc += " Valid"; + } + else + { + desc += " Invalid"; + } + + if (tagDetails.is_pending) + { + ok = true; + desc += " Pending"; + } + } + else + { + desc += "Unparseable"; + } + return ok; +} + + +void IdEditDialog::loadRecognTags() +{ + std::cerr << "IdEditDialog::loadRecognTags()"; + std::cerr << std::endl; + + // delete existing items. + ui.label_Tag1->setHidden(true); + ui.label_Tag2->setHidden(true); + ui.label_Tag3->setHidden(true); + ui.label_Tag4->setHidden(true); + ui.label_Tag5->setHidden(true); + ui.toolButton_Tag1->setHidden(true); + ui.toolButton_Tag2->setHidden(true); + ui.toolButton_Tag3->setHidden(true); + ui.toolButton_Tag4->setHidden(true); + ui.toolButton_Tag5->setHidden(true); + ui.plainTextEdit_Tag->setPlainText(""); + + int i = 0; + std::list::const_iterator it; + for(it = mEditGroup.mRecognTags.begin(); it != mEditGroup.mRecognTags.end(); it++, i++) + { + QString recognTag; + tagDetails(mEditGroup.mMeta.mGroupId, mEditGroup.mMeta.mGroupName, *it, recognTag); + + switch(i) + { + default: + case 0: + ui.label_Tag1->setText(recognTag); + ui.label_Tag1->setHidden(false); + ui.toolButton_Tag1->setHidden(false); + break; + case 1: + ui.label_Tag2->setText(recognTag); + ui.label_Tag2->setHidden(false); + ui.toolButton_Tag2->setHidden(false); + break; + case 2: + ui.label_Tag3->setText(recognTag); + ui.label_Tag3->setHidden(false); + ui.toolButton_Tag3->setHidden(false); + break; + case 3: + ui.label_Tag4->setText(recognTag); + ui.label_Tag4->setHidden(false); + ui.toolButton_Tag4->setHidden(false); + break; + case 4: + ui.label_Tag5->setText(recognTag); + ui.label_Tag5->setHidden(false); + ui.toolButton_Tag5->setHidden(false); + break; + } + } +} + +void IdEditDialog::submit() +{ + if (mIsNew) + { + createId(); + } + else + { + updateId(); + } +} + + +void IdEditDialog::createId() +{ + std::string groupname = ui.lineEdit_Nickname->text().toUtf8().constData(); + + if (groupname.size() < 2) + { + std::cerr << "IdEditDialog::createId() Nickname too short"; std::cerr << std::endl; return; } - //rid.mIdType = RSID_RELATION_YOURSELF; - if (mIsNew) - { - rid.mMeta.mGroupId = ""; - } - else - { - rid.mMeta.mGroupId = ui.lineEdit_KeyId->text().toStdString(); - } - - if (ui.radioButton_GpgId->isChecked()) - { - //rid.mIdType |= RSID_TYPE_REALID; - - //rid.mGpgId = ui.lineEdit_GpgId->text().toStdString(); - rid.mPgpIdHash = ui.lineEdit_GpgHash->text().toStdString(); - //rid.mGpgName = ui.lineEdit_GpgName->text().toUtf8().constData(); - } - else - { - //rid.mIdType |= RSID_TYPE_PSEUDONYM; - - //rid.mGpgId = ""; - rid.mPgpIdHash = ""; - //rid.mGpgName = ""; - //rid.mGpgEmail = ""; - } - - // Can only create Identities for the moment! RsIdentityParameters params; - params.nickname = rid.mMeta.mGroupName; + params.nickname = groupname; params.isPgpLinked = (ui.radioButton_GpgId->isChecked()); uint32_t dummyToken = 0; @@ -265,6 +436,30 @@ void IdEditDialog::updateId() close(); } + +void IdEditDialog::updateId() +{ + /* submit updated details */ + std::string groupname = ui.lineEdit_Nickname->text().toUtf8().constData(); + + if (groupname.size() < 2) + { + std::cerr << "IdEditDialog::updateId() Nickname too short"; + std::cerr << std::endl; + return; + } + + mEditGroup.mMeta.mGroupName = groupname; + + uint32_t dummyToken = 0; + rsIdentity->updateIdentity(dummyToken, mEditGroup); + + close(); +} + + + + void IdEditDialog::loadRequest(const TokenQueue */*queue*/, const TokenRequest &req) { std::cerr << "IdDialog::loadRequest() UserType: " << req.mUserType; diff --git a/retroshare-gui/src/gui/Identity/IdEditDialog.h b/retroshare-gui/src/gui/Identity/IdEditDialog.h index 8ef672710..1703073dc 100644 --- a/retroshare-gui/src/gui/Identity/IdEditDialog.h +++ b/retroshare-gui/src/gui/Identity/IdEditDialog.h @@ -29,6 +29,7 @@ #include #include "util/TokenQueue.h" +#include class UIStateHelper; @@ -46,16 +47,33 @@ public: private slots: void idTypeToggled(bool checked); - void updateId(); + void submit(); + + void addRecognTag(); + void checkNewTag(); + void rmTag1(); + void rmTag2(); + void rmTag3(); + void rmTag4(); + void rmTag5(); private: + void createId(); + void updateId(); void updateIdType(bool pseudo); void loadExistingId(uint32_t token); + void loadRecognTags(); + // extract details. + bool tagDetails(const std::string &id, const std::string &name, const std::string &tag, QString &desc); + void rmTag(int idx); + protected: Ui::IdEditDialog ui; bool mIsNew; UIStateHelper *mStateHelper; + + RsGxsIdGroup mEditGroup; TokenQueue *mIdQueue; }; diff --git a/retroshare-gui/src/gui/Identity/IdEditDialog.ui b/retroshare-gui/src/gui/Identity/IdEditDialog.ui index 2a9dd713b..197ad6dc5 100644 --- a/retroshare-gui/src/gui/Identity/IdEditDialog.ui +++ b/retroshare-gui/src/gui/Identity/IdEditDialog.ui @@ -6,147 +6,233 @@ 0 0 - 557 - 179 + 510 + 595 - - - - - QFormLayout::AllNonFixedFieldsGrow + + + + + QFrame::StyledPanel - - - - Nickname - - - - - - - - - - Key ID - - - - - - - true - - - - - - - PGP Hash - - - - - - - true - - - - - - - PGP Id - - - - - - - true - - - - - - - PGP Name - - - - - - - true - - - - - + + QFrame::Raised + + + + + + + + PGP Associated ID + + + + + + + Pseudonym + + + + + + + + + Nickname + + + + + + + + + + Key ID + + + + + + + true + + + + + + + PGP Hash + + + + + + + true + + + + + + + PGP Id + + + + + + + true + + + + + + + PGP Name + + + + + + + true + + + + + + + + + + QFrame::StyledPanel + + + QFrame::Raised + + + + + + TextLabel + + + + + + + RM + + + + + + + TextLabel + + + + + + + RM + + + + + + + TextLabel + + + + + + + RM + + + + + + + TextLabel + + + + + + + RM + + + + + + + TextLabel + + + + + + + RM + + + + + + + + + + TextLabel + + + + + + + Add + + + + + + + + + + - Qt::Vertical + Qt::Horizontal - 20 - 40 + 328 + 20 - - - - - - - - - PGP Associated ID - - - - - - - Pseudonym - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + - - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - lineEdit_Nickname - lineEdit_KeyId - lineEdit_GpgHash - lineEdit_GpgId - lineEdit_GpgName radioButton_GpgId radioButton_Pseudo buttonBox diff --git a/retroshare-gui/src/gui/gxs/GxsIdChooser.cpp b/retroshare-gui/src/gui/gxs/GxsIdChooser.cpp index 9abfaf25b..a77916079 100644 --- a/retroshare-gui/src/gui/gxs/GxsIdChooser.cpp +++ b/retroshare-gui/src/gui/gxs/GxsIdChooser.cpp @@ -67,6 +67,17 @@ bool GxsIdChooser::MakeIdDesc(const RsGxsId &id, QString &desc) if (found) { desc = QString::fromUtf8(details.mNickname.c_str()); + + std::list::iterator it; + for(it = details.mRecognTags.begin(); it != details.mRecognTags.end(); it++) + { + desc += " ("; + desc += QString::number(it->tag_class); + desc += ":"; + desc += QString::number(it->tag_type); + desc += ")"; + } + if (details.mPgpLinked) { desc += " (PGP) ["; diff --git a/retroshare-gui/src/gui/gxs/GxsIdLabel.cpp b/retroshare-gui/src/gui/gxs/GxsIdLabel.cpp index bae9f798a..12373f212 100644 --- a/retroshare-gui/src/gui/gxs/GxsIdLabel.cpp +++ b/retroshare-gui/src/gui/gxs/GxsIdLabel.cpp @@ -71,6 +71,16 @@ static bool MakeIdDesc(const RsGxsId &id, QString &str) str = QString::fromUtf8(details.mNickname.c_str()); + std::list::iterator it; + for(it = details.mRecognTags.begin(); it != details.mRecognTags.end(); it++) + { + str += " ("; + str += QString::number(it->tag_class); + str += ":"; + str += QString::number(it->tag_type); + str += ")"; + } + bool addCode = true; if (details.mPgpLinked) { diff --git a/retroshare-gui/src/gui/gxs/GxsIdTreeWidgetItem.cpp b/retroshare-gui/src/gui/gxs/GxsIdTreeWidgetItem.cpp index 4b0bc039b..fcba60a52 100644 --- a/retroshare-gui/src/gui/gxs/GxsIdTreeWidgetItem.cpp +++ b/retroshare-gui/src/gui/gxs/GxsIdTreeWidgetItem.cpp @@ -45,6 +45,17 @@ static bool MakeIdDesc(const RsGxsId &id, QString &str) str = QString::fromUtf8(details.mNickname.c_str()); + std::list::iterator it; + for(it = details.mRecognTags.begin(); it != details.mRecognTags.end(); it++) + { + str += " ("; + str += QString::number(it->tag_class); + str += ":"; + str += QString::number(it->tag_type); + str += ")"; + } + + bool addCode = true; if (details.mPgpLinked) { diff --git a/retroshare-gui/src/retroshare-gui.pro b/retroshare-gui/src/retroshare-gui.pro index b4397b355..79b5d37cc 100644 --- a/retroshare-gui/src/retroshare-gui.pro +++ b/retroshare-gui/src/retroshare-gui.pro @@ -2,7 +2,7 @@ CONFIG += qt gui uic qrc resources uitools idle bitdht # Below is for GXS services. # Should be disabled for releases. -#CONFIG += gxs debug +CONFIG += gxs debug gxs { @@ -193,7 +193,10 @@ macx { gxs { LIBS += ../../supportlibs/pegmarkdown/lib/libpegmarkdown.a - LIBS += -lsqlite3 + LIBS += ../../../lib/libsqlcipher.a + #LIBS += ../../../lib/sqlcipher/.libs/libsqlcipher.a + #LIBS += -lsqlite3 + #LIBS += -lsqlcipher } From d31a34bd957cd33af562c1bd1814fc1f58912a1e Mon Sep 17 00:00:00 2001 From: drbob Date: Tue, 22 Oct 2013 03:42:20 +0000 Subject: [PATCH 45/83] hack for testing purposes. git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.5-gxs_finale@6869 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- retroshare-gui/src/gui/Identity/IdEditDialog.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/retroshare-gui/src/gui/Identity/IdEditDialog.cpp b/retroshare-gui/src/gui/Identity/IdEditDialog.cpp index 9593746e4..2518216d3 100644 --- a/retroshare-gui/src/gui/Identity/IdEditDialog.cpp +++ b/retroshare-gui/src/gui/Identity/IdEditDialog.cpp @@ -244,6 +244,13 @@ void IdEditDialog::checkNewTag() bool ok = tagDetails(id, name, tag, desc); ui.label_TagCheck->setText(desc); + // hack to allow add invalid tags (for testing). + if (!tag.empty()) + { + ok = true; + } + + if (mEditGroup.mRecognTags.size() >= MAX_RECOGN_TAGS) { ok = false; From a6f62caef455bd864c1d5b2bfb03f14d83319a8a Mon Sep 17 00:00:00 2001 From: chrisparker126 Date: Tue, 22 Oct 2013 19:56:01 +0000 Subject: [PATCH 46/83] -fixed an update issue with actual group item - simply didn't open grp file in "out" mode on update -made update a bit more sturdy is group not found on update - prevent client can crash librs - updated unit tests for grps and messages - removed data base removal on db reset as cannot rekey db unfortunately (as passphrase (ssl) cannot be kept in the clear in mem) git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.5-gxs_finale@6873 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/gxs/rsdataservice.cc | 67 ++++++++-------- libretroshare/src/gxs/rsgenexchange.cc | 16 +++- .../src/retroshare/rsgxsifacetypes.h | 1 + .../gxs/gen_exchange/genexchange_test.pro | 4 +- .../gxs/gen_exchange/genexchangetester.cpp | 79 ++++++++++--------- .../gxs/gen_exchange/genexchangetester.h | 2 +- .../gen_exchange/genexchangetestservice.cpp | 5 ++ .../gxs/gen_exchange/genexchangetestservice.h | 1 + .../gxs/gen_exchange/gxspublishgrouptest.cc | 69 +++++++++++++++- .../gxs/gen_exchange/gxspublishgrouptest.h | 1 + .../gxs/gen_exchange/gxspublishmsgtest.cc | 8 +- .../gxs/gen_exchange/rsgenexchange_test.cc | 10 +-- 12 files changed, 174 insertions(+), 89 deletions(-) diff --git a/libretroshare/src/gxs/rsdataservice.cc b/libretroshare/src/gxs/rsdataservice.cc index 9b7769ed8..c0f7082a7 100644 --- a/libretroshare/src/gxs/rsdataservice.cc +++ b/libretroshare/src/gxs/rsdataservice.cc @@ -663,7 +663,7 @@ int RsDataService::updateGroup(std::map &grp) if(!validSize(grpPtr)) continue; std::string grpFile = mServiceDir + "/" + grpPtr->grpId; - std::fstream ostrm(grpFile.c_str(), std::ios::binary | std::ios::trunc); + std::ofstream ostrm(grpFile.c_str(), std::ios::binary | std::ios::trunc); uint32_t offset = 0; // get file offset /*! @@ -1058,34 +1058,33 @@ int RsDataService::retrieveGxsGrpMetaData(std::map::iterator mit = grp.begin(); - for(; mit != grp.end(); mit++) - { - const RsGxsGroupId& grpId = mit->first; - RetroCursor* c = mDb->sqlQuery(GRP_TABLE_NAME, grpMetaColumns, "grpId='" + grpId + "'", ""); + for(; mit != grp.end(); mit++) + { + const RsGxsGroupId& grpId = mit->first; + RetroCursor* c = mDb->sqlQuery(GRP_TABLE_NAME, grpMetaColumns, "grpId='" + grpId + "'", ""); - if(c) - { - bool valid = c->moveToFirst(); + if(c) + { + bool valid = c->moveToFirst(); - while(valid) - { - RsGxsGrpMetaData* g = locked_getGrpMeta(*c); + while(valid) + { + RsGxsGrpMetaData* g = locked_getGrpMeta(*c); - if(g) - { - grp[g->mGroupId] = g; - } - valid = c->moveToNext(); - } - delete c; - } + if(g) + { + grp[g->mGroupId] = g; + } + valid = c->moveToNext(); + } + delete c; + } - } + } - } + } return 1; @@ -1104,21 +1103,21 @@ int RsDataService::resetDataStore() std::map::iterator mit = grps.begin(); - - // remove all grp msgs files from service dir - for(; mit != grps.end(); mit++){ - std::string file = mServiceDir + "/" + mit->first; - std::string msgFile = file + "-msgs"; - remove(file.c_str()); // remove group file - remove(msgFile.c_str()); // and remove messages file - delete mit->second; - } { RsStackMutex stack(mDbMutex); - mDb->closeDb(); - } - remove(mDbName.c_str()); // remove db file + // remove all grp msgs files from service dir + for(; mit != grps.end(); mit++){ + std::string file = mServiceDir + "/" + mit->first; + std::string msgFile = file + "-msgs"; + remove(file.c_str()); // remove group file + remove(msgFile.c_str()); // and remove messages file + delete mit->second; + } + + mDb->execSQL("DROP TABLE " + MSG_TABLE_NAME); + mDb->execSQL("DROP TABLE " + GRP_TABLE_NAME); + } // recreate database initialise(); diff --git a/libretroshare/src/gxs/rsgenexchange.cc b/libretroshare/src/gxs/rsgenexchange.cc index 54899fe0e..a41f948af 100644 --- a/libretroshare/src/gxs/rsgenexchange.cc +++ b/libretroshare/src/gxs/rsgenexchange.cc @@ -1881,7 +1881,20 @@ void RsGenExchange::processGroupUpdatePublish() { GroupUpdatePublish& gup = *vit; const RsGxsGroupId& groupId = gup.grpItem->meta.mGroupId; - RsGxsGrpMetaData* meta = grpMeta[groupId]; + std::map::iterator mit = grpMeta.find(groupId); + + RsGxsGrpMetaData* meta = NULL; + if(mit == grpMeta.end()) + { + std::cerr << "Error! could not find meta of old group to update!" << std::endl; + mDataAccess->updatePublicRequestStatus(gup.mToken, RsTokenService::GXS_REQUEST_V2_STATUS_FAILED); + delete gup.grpItem; + continue; + }else + { + meta = mit->second; + } + gup.grpItem->meta = *meta; assignMetaUpdates(gup.grpItem->meta, gup.mUpdateMeta); @@ -1897,6 +1910,7 @@ void RsGenExchange::processGroupUpdatePublish() ggps.mStartTS = time(NULL); ggps.mLastAttemptTS = 0; ggps.mIsUpdate = true; + ggps.mToken = gup.mToken; mGrpsToPublish.push_back(ggps); }else { diff --git a/libretroshare/src/retroshare/rsgxsifacetypes.h b/libretroshare/src/retroshare/rsgxsifacetypes.h index 830df9f52..6f17d3cc5 100644 --- a/libretroshare/src/retroshare/rsgxsifacetypes.h +++ b/libretroshare/src/retroshare/rsgxsifacetypes.h @@ -46,6 +46,7 @@ public: mGroupStatus = 0; mCircleType = 0; + mAuthenFlags = 0; mPublishTs = 0; } diff --git a/libretroshare/src/tests/gxs/gen_exchange/genexchange_test.pro b/libretroshare/src/tests/gxs/gen_exchange/genexchange_test.pro index 2cc6fe806..aa67a28ed 100644 --- a/libretroshare/src/tests/gxs/gen_exchange/genexchange_test.pro +++ b/libretroshare/src/tests/gxs/gen_exchange/genexchange_test.pro @@ -56,7 +56,9 @@ linux-* { LIBS += ../../../lib/libretroshare.a LIBS += ../../../../../libbitdht/src/lib/libbitdht.a LIBS += ../../../../../openpgpsdk/src/lib/libops.a - LIBS += -lssl -lgpgme -lupnp -lixml -lgnome-keyring -lsqlite3 -lbz2 + LIBS += -lssl -lgpgme -lupnp -lixml -lgnome-keyring -lbz2 + # We need a explicit path here, to force using the home version of sqlite3 that really encrypts the database. + LIBS += /home/crispy/Development/retroshare/sqlcipher/sqlcipher/.libs/libsqlite3.a LIBS *= -rdynamic -frtti DEFINES *= HAVE_XSS # for idle time, libx screensaver extensions DEFINES *= UBUNTU diff --git a/libretroshare/src/tests/gxs/gen_exchange/genexchangetester.cpp b/libretroshare/src/tests/gxs/gen_exchange/genexchangetester.cpp index 8eacbbc54..384eba6b3 100644 --- a/libretroshare/src/tests/gxs/gen_exchange/genexchangetester.cpp +++ b/libretroshare/src/tests/gxs/gen_exchange/genexchangetester.cpp @@ -108,7 +108,7 @@ bool GenExchangeTest::pollForMsgAcknowledgement(uint32_t token, now = time(NULL); } return false; -} +} GenExchangeTestService* GenExchangeTest::getTestService() { @@ -155,12 +155,13 @@ void GenExchangeTest::setUp() // would be useful for genexchange services // to have a protected reset button mTestService->start(); -} +} void GenExchangeTest::breakDown() { - mTestService->join(); - clearAllData(); + mDataService->resetDataStore(); + mTestService->join(); + clearAllData(); } bool msgDataSort(const RsDummyMsg* m1, const RsDummyMsg* m2) @@ -189,7 +190,7 @@ bool GenExchangeTest::compareMsgDataMaps() } return ok; -} +} bool GenExchangeTest::compareMsgIdMaps() @@ -205,7 +206,7 @@ bool GenExchangeTest::compareMsgIdMaps() ok &= Comparison, RsGxsMessageId>::comparison(v1, v2); } return ok; -} +} bool GenExchangeTest::compareMsgMetaMaps() @@ -220,19 +221,19 @@ bool GenExchangeTest::compareMsgMetaMaps() ok &= Comparison, RsMsgMetaData>::comparison(v1, v2); } return ok; -} +} bool GenExchangeTest::compareMsgRelateIdsMap() { return false; -} +} bool GenExchangeTest::compareMsgRelatedDataMap() { return false; -} +} bool grpDataSort(const RsDummyGrp* g1, const RsDummyGrp* g2) { @@ -247,7 +248,7 @@ bool GenExchangeTest::compareGrpData() bool ok = Comparison, RsDummyGrp*>::comparison (mGrpDataIn, mGrpDataOut); return ok; -} +} bool operator<(const RsGroupMetaData& l, const RsGroupMetaData& r) { @@ -263,7 +264,7 @@ bool GenExchangeTest::compareGrpMeta() bool ok = Comparison, RsGroupMetaData>::comparison (mGrpMetaDataIn, mGrpMetaDataOut); return ok; -} +} bool GenExchangeTest::compareGrpIds() @@ -289,7 +290,7 @@ void GenExchangeTest::createGrps(uint32_t nGrps, pollForGrpAcknowledgement(token, grpId); groupId.push_back(grpId); } -} +} void GenExchangeTest::init(RsMsgMetaData& msgMetaData) const { @@ -334,7 +335,7 @@ void GenExchangeTest::init(RsDummyGrp& grpItem) const { randString(SHORT_STR, grpItem.grpData); init(grpItem.meta); -} +} void GenExchangeTest::init(RsDummyMsg& msgItem) const @@ -346,72 +347,72 @@ void GenExchangeTest::init(RsDummyMsg& msgItem) const void GenExchangeTest::storeToMsgDataOutMaps(const DummyMsgMap& msgDataOut) { mMsgDataOut.insert(msgDataOut.begin(), msgDataOut.end()); -} +} void GenExchangeTest::storeToMsgIdsOutMaps(const GxsMsgIdResult& msgIdsOut) { mMsgIdsOut.insert(msgIdsOut.begin(), msgIdsOut.end()); -} +} void GenExchangeTest::storeToMsgMetaOutMaps(const GxsMsgMetaMap& msgMetaOut) { mMsgMetaDataOut.insert(msgMetaOut.begin(), msgMetaOut.end()); -} +} void GenExchangeTest::storeToMsgDataInMaps(const DummyMsgMap& msgDataIn) { mMsgDataIn.insert(msgDataIn.begin(), msgDataIn.end()); -} +} void GenExchangeTest::storeToMsgIdsInMaps(const GxsMsgIdResult& msgIdsIn) { mMsgIdsIn.insert(msgIdsIn.begin(), msgIdsIn.end()); -} +} void GenExchangeTest::storeToMsgMetaInMaps(const GxsMsgMetaMap& msgMetaIn) { mMsgMetaDataIn.insert(msgMetaIn.begin(), msgMetaIn.end()); -} +} void GenExchangeTest::storeToGrpIdsOutList( const std::list& grpIdOut) { mGrpIdsOut.insert(mGrpIdsOut.end(), grpIdOut.begin(), grpIdOut.end()); -} +} void GenExchangeTest::storeToGrpMetaOutList( const std::list& grpMetaOut) { mGrpMetaDataOut.insert(mGrpMetaDataOut.end(), grpMetaOut.begin(), grpMetaOut.end()); -} +} void GenExchangeTest::storeToGrpDataOutList( const std::vector& grpDataOut) { mGrpDataOut.insert(mGrpDataOut.end(), grpDataOut.begin(), grpDataOut.end()); -} +} void GenExchangeTest::storeToGrpIdsInList( const std::list& grpIdIn) { mGrpIdsIn.insert(mGrpIdsIn.end(), grpIdIn.begin(), grpIdIn.end()); -} +} void GenExchangeTest::storeToGrpMetaInList( const std::list& grpMetaIn) { mGrpMetaDataIn.insert(mGrpMetaDataIn.end(), grpMetaIn.begin(), grpMetaIn.end()); -} +} void GenExchangeTest::storeToGrpDataInList( @@ -437,14 +438,14 @@ void GenExchangeTest::clearAllData() void GenExchangeTest::clearMsgDataInMap() { mMsgDataIn.clear(); -} +} void GenExchangeTest::clearMsgDataOutMap() { clearMsgDataMap(mMsgDataOut); -} +} void GenExchangeTest::clearMsgDataMap(DummyMsgMap& msgDataMap) const { @@ -459,31 +460,31 @@ void GenExchangeTest::clearMsgDataMap(DummyMsgMap& msgDataMap) const void GenExchangeTest::clearMsgMetaInMap() { mMsgMetaDataIn.clear(); -} +} void GenExchangeTest::clearMsgMetaOutMap() { mMsgMetaDataOut.clear(); -} +} void GenExchangeTest::clearMsgIdInMap() { mMsgIdsIn.clear(); -} +} void GenExchangeTest::clearMsgIdOutMap() { mMsgIdsOut.clear(); -} +} void GenExchangeTest::clearMsgRelatedIdInMap() { mMsgRelatedIdsIn.clear(); -} +} void GenExchangeTest::clearGrpDataInList() @@ -494,38 +495,38 @@ void GenExchangeTest::clearGrpDataInList() void GenExchangeTest::clearGrpDataList(std::vector& grpData) const { deleteResVector(grpData); -} +} void GenExchangeTest::clearGrpDataOutList() { clearGrpDataList(mGrpDataOut); -} +} void GenExchangeTest::clearGrpMetaInList() { mGrpMetaDataIn.clear(); -} +} void GenExchangeTest::clearGrpMetaOutList() { mGrpMetaDataOut.clear(); -} +} void GenExchangeTest::clearGrpIdInList() { mGrpIdsIn.clear(); -} +} void GenExchangeTest::clearGrpIdOutList() { mGrpIdsOut.clear(); -} - +} + bool operator ==(const RsMsgMetaData& lMeta, const RsMsgMetaData& rMeta) { @@ -584,5 +585,5 @@ bool operator ==(const RsDummyMsg& lMsg, const RsDummyMsg& rMsg) bool operator ==(const RsGxsGrpItem& lGrp, const RsGxsGrpItem& rGrp) { return false; -} +} diff --git a/libretroshare/src/tests/gxs/gen_exchange/genexchangetester.h b/libretroshare/src/tests/gxs/gen_exchange/genexchangetester.h index 882a846a2..13bb1cf6e 100644 --- a/libretroshare/src/tests/gxs/gen_exchange/genexchangetester.h +++ b/libretroshare/src/tests/gxs/gen_exchange/genexchangetester.h @@ -258,7 +258,7 @@ private: std::list mGrpMetaDataOut, mGrpMetaDataIn; std::list mGrpIdsOut, mGrpIdsIn; - DummyMsgMap mMsgDataOut, mMsgDataIn; + std::map > mMsgDataOut, mMsgDataIn; GxsMsgMetaMap mMsgMetaDataOut, mMsgMetaDataIn; GxsMsgIdResult mMsgIdsOut, mMsgIdsIn; diff --git a/libretroshare/src/tests/gxs/gen_exchange/genexchangetestservice.cpp b/libretroshare/src/tests/gxs/gen_exchange/genexchangetestservice.cpp index f2b388e71..dd9ba328a 100644 --- a/libretroshare/src/tests/gxs/gen_exchange/genexchangetestservice.cpp +++ b/libretroshare/src/tests/gxs/gen_exchange/genexchangetestservice.cpp @@ -17,6 +17,11 @@ void GenExchangeTestService::publishDummyGrp(uint32_t &token, RsDummyGrp *grp) publishGroup(token, grp); } +void GenExchangeTestService::updateDummyGrp(uint32_t &token, RsGxsGroupUpdateMeta &updateMeta, RsDummyGrp *group) +{ + updateGroup(token, updateMeta, group); +} + void GenExchangeTestService::publishDummyMsg(uint32_t &token, RsDummyMsg *msg) { publishMsg(token, msg); diff --git a/libretroshare/src/tests/gxs/gen_exchange/genexchangetestservice.h b/libretroshare/src/tests/gxs/gen_exchange/genexchangetestservice.h index d0d5e241e..588808eb9 100644 --- a/libretroshare/src/tests/gxs/gen_exchange/genexchangetestservice.h +++ b/libretroshare/src/tests/gxs/gen_exchange/genexchangetestservice.h @@ -15,6 +15,7 @@ public: void notifyChanges(std::vector& changes); void publishDummyGrp(uint32_t& token, RsDummyGrp* grp); + void updateDummyGrp(uint32_t &token, RsGxsGroupUpdateMeta& meta, RsDummyGrp *group); void publishDummyMsg(uint32_t& token, RsDummyMsg* msg); /*! diff --git a/libretroshare/src/tests/gxs/gen_exchange/gxspublishgrouptest.cc b/libretroshare/src/tests/gxs/gen_exchange/gxspublishgrouptest.cc index 7f4555721..2fe0d5fac 100644 --- a/libretroshare/src/tests/gxs/gen_exchange/gxspublishgrouptest.cc +++ b/libretroshare/src/tests/gxs/gen_exchange/gxspublishgrouptest.cc @@ -7,6 +7,7 @@ #include "gxspublishgrouptest.h" #include "util/utest.h" +#include "support.h" #define POLLING_TIME_OUT 5 @@ -169,6 +170,65 @@ bool GxsPublishGroupTest::testGrpIdRetrieval() return ok; } + +bool GxsPublishGroupTest::testUpdateGroup() +{ + setUp(); + + GenExchangeTestService* testService = getTestService(); + RsTokenService* tokenService = getTokenService(); + +// create some random grps to allow msg testing + + RsDummyGrp* dgrp1 = new RsDummyGrp(); + RsDummyGrp* dgrp2 = new RsDummyGrp(); + + RsDummyGrp* dgrp2_copy = new RsDummyGrp(); + + init(*dgrp1); + init(*dgrp2); + + RsTokReqOptions opts; + opts.mReqType = 45000; + uint32_t token; + RsGxsGroupId grpId; + + std::vector groupsPublished; + std::list grpIds; + + std::string name = dgrp1->meta.mGroupName; + *dgrp2 = *dgrp1; + testService->publishDummyGrp(token, dgrp1); + bool ok = pollForGrpAcknowledgement(token, grpId); + + grpIds.push_back(grpId); + RsGxsGroupUpdateMeta updateMeta(grpId); + + updateMeta.setMetaUpdate(RsGxsGroupUpdateMeta::NAME, name); + randString(SHORT_STR, dgrp2->grpData); + dgrp2->meta.mGroupId = grpId; + *dgrp2_copy = *dgrp2; + dgrp2->grpData ="ojfosfjsofjsof"; + testService->updateDummyGrp(token, updateMeta, dgrp2); + ok &= pollForGrpAcknowledgement(token, grpId); + + groupsPublished.push_back(dgrp2_copy); + + opts.mReqType = GXS_REQUEST_TYPE_GROUP_DATA; + + tokenService->requestGroupInfo(token, 0, opts, grpIds); + + pollForToken(token, opts, true); + + + ok &= compareGrpData(); + + breakDown(); + + return ok; + +} + bool GxsPublishGroupTest::testGrpMetaRetrieval() { @@ -229,10 +289,11 @@ bool GxsPublishGroupTest::testGrpMetaRetrieval() } void GxsPublishGroupTest::runTests() { - CHECK(testGrpSubmissionRetrieval()); - CHECK(testGrpIdRetrieval()); - CHECK(testGrpMetaRetrieval()); - CHECK(testSpecificGrpRetrieval()); +// CHECK(testGrpSubmissionRetrieval()); +// CHECK(testGrpIdRetrieval()); +// CHECK(testGrpMetaRetrieval()); + // CHECK(testSpecificGrpRetrieval()); + CHECK(testUpdateGroup()); } diff --git a/libretroshare/src/tests/gxs/gen_exchange/gxspublishgrouptest.h b/libretroshare/src/tests/gxs/gen_exchange/gxspublishgrouptest.h index 9d7f685bc..a0f642828 100644 --- a/libretroshare/src/tests/gxs/gen_exchange/gxspublishgrouptest.h +++ b/libretroshare/src/tests/gxs/gen_exchange/gxspublishgrouptest.h @@ -26,6 +26,7 @@ private: bool testSpecificGrpRetrieval(); bool testGrpIdRetrieval(); bool testGrpMetaRetrieval(); + bool testUpdateGroup(); private: diff --git a/libretroshare/src/tests/gxs/gen_exchange/gxspublishmsgtest.cc b/libretroshare/src/tests/gxs/gen_exchange/gxspublishmsgtest.cc index 16c39c6fa..adfa2026c 100644 --- a/libretroshare/src/tests/gxs/gen_exchange/gxspublishmsgtest.cc +++ b/libretroshare/src/tests/gxs/gen_exchange/gxspublishmsgtest.cc @@ -49,10 +49,10 @@ bool GxsPublishMsgTest::testMsgSubmissionRetrieval() msgOut->meta.mMsgId = msgId.second; DummyMsgMap msgMap; - std::vector msgV; - msgV.push_back(msgOut); - msgMap[msgOut->meta.mGroupId] = msgV; - storeToMsgDataOutMaps(msgMap); + std::vector msgV; + msgV.push_back(msgOut); + msgMap[msgOut->meta.mGroupId] = msgV; + storeToMsgDataOutMaps(msgMap); RsTokReqOptions opts; diff --git a/libretroshare/src/tests/gxs/gen_exchange/rsgenexchange_test.cc b/libretroshare/src/tests/gxs/gen_exchange/rsgenexchange_test.cc index 35afd2563..8b28bad17 100644 --- a/libretroshare/src/tests/gxs/gen_exchange/rsgenexchange_test.cc +++ b/libretroshare/src/tests/gxs/gen_exchange/rsgenexchange_test.cc @@ -30,16 +30,16 @@ INITTEST(); int main() { - RsGeneralDataService* dataStore = new RsDataService("./", "testServiceDb", RS_SERVICE_TYPE_DUMMY, NULL); + RsGeneralDataService* dataStore = new RsDataService("./", "testServiceDb", RS_SERVICE_TYPE_DUMMY, NULL, ""); // we want to use default authentication which is NO authentication :) GenExchangeTestService testService(dataStore, NULL, NULL); - //GxsPublishGroupTest testGrpPublishing(&testService, dataStore); - //testGrpPublishing.runTests(); + GxsPublishGroupTest testGrpPublishing(&testService, dataStore); + testGrpPublishing.runTests(); - GxsPublishMsgTest testMsgPublishing(&testService, dataStore); - testMsgPublishing.runTests(); + //GxsPublishMsgTest testMsgPublishing(&testService, dataStore); + //testMsgPublishing.runTests(); FINALREPORT("RsGenExchangeTest"); From f2884d580f110a9bfa18c8b959f0a97e866a4d98 Mon Sep 17 00:00:00 2001 From: chrisparker126 Date: Tue, 29 Oct 2013 21:29:20 +0000 Subject: [PATCH 47/83] added author pull code -- problem, still need to figure out how to get peer auth req should go to git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.5-gxs_finale@6881 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/gxs/rsgxsnetservice.cc | 39 +++++++++++++++++++++++ libretroshare/src/gxs/rsgxsnetservice.h | 8 +++-- libretroshare/src/gxs/rsnxs.h | 19 ++--------- libretroshare/src/services/p3idservice.cc | 30 ++++++++++++++++- libretroshare/src/services/p3idservice.h | 11 +++++++ 5 files changed, 87 insertions(+), 20 deletions(-) diff --git a/libretroshare/src/gxs/rsgxsnetservice.cc b/libretroshare/src/gxs/rsgxsnetservice.cc index c1690e96a..537fb094c 100644 --- a/libretroshare/src/gxs/rsgxsnetservice.cc +++ b/libretroshare/src/gxs/rsgxsnetservice.cc @@ -766,6 +766,8 @@ void RsGxsNetService::run(){ // vetting of id and circle info runVetting(); + processExplicitGroupRequests(); + } } @@ -2063,3 +2065,40 @@ void RsGxsNetService::setSyncAge(uint32_t age) } +int RsGxsNetService::requestGrp(const std::list& grpId, const std::string& peerId) +{ + RsStackMutex stack(mNxsMutex); + mExplicitRequest[peerId].assign(grpId.begin(), grpId.end()); + return 1; +} + +void RsGxsNetService::processExplicitGroupRequests() +{ + RsStackMutex stack(mNxsMutex); + + std::map >::const_iterator cit = mExplicitRequest.begin(); + + for(; cit != mExplicitRequest.end(); cit++) + { + const std::string& peerId = cit->first; + const std::list& groupIdList = cit->second; + + std::list grpSyncItems; + std::list::const_iterator git = groupIdList.begin(); + uint32_t transN = locked_getTransactionId(); + for(; git != groupIdList.end(); git++) + { + RsNxsSyncGrpItem* item = new RsNxsSyncGrpItem(mServType); + item->grpId = *git; + item->PeerId(peerId); + item->flag = RsNxsSyncGrpItem::FLAG_REQUEST; + item->transactionNumber = transN; + grpSyncItems.push_back(item); + } + + if(!grpSyncItems.empty()) + locked_pushGrpTransactionFromList(grpSyncItems, peerId, transN); + } + + mExplicitRequest.clear(); +} diff --git a/libretroshare/src/gxs/rsgxsnetservice.h b/libretroshare/src/gxs/rsgxsnetservice.h index 6c37d34a0..4cb16a2c3 100644 --- a/libretroshare/src/gxs/rsgxsnetservice.h +++ b/libretroshare/src/gxs/rsgxsnetservice.h @@ -115,7 +115,7 @@ public: * @param msgId the messages to retrieve * @return request token to be redeemed */ - int requestMsg(const std::string& msgId, uint8_t hops){ return 0;} + int requestMsg(const RsGxsGrpMsgIdPair& msgId){ return 0;} /*! * Request for this group is sent through to peers on your network @@ -123,7 +123,7 @@ public: * @param enabled set to false to disable pause, and true otherwise * @return request token to be redeemed */ - int requestGrp(const std::list& grpId, uint8_t hops){ return 0;} + int requestGrp(const std::list& grpId, const std::string& peerId); /* p3Config methods */ @@ -322,6 +322,8 @@ private: bool locked_canReceive(const RsGxsGrpMetaData * const grpMeta, const std::string& peerId); + void processExplicitGroupRequests(); + private: typedef std::vector GrpFragments; @@ -422,6 +424,8 @@ private: // need to be verfied std::vector mPendingResp; std::vector mPendingCircleVets; + + std::map > mExplicitRequest; }; #endif // RSGXSNETSERVICE_H diff --git a/libretroshare/src/gxs/rsnxs.h b/libretroshare/src/gxs/rsnxs.h index 0c201a737..e909994a2 100644 --- a/libretroshare/src/gxs/rsnxs.h +++ b/libretroshare/src/gxs/rsnxs.h @@ -68,21 +68,6 @@ public: */ virtual void setSyncAge(uint32_t age) = 0; - /*! - * Explicitly requests all the groups contained by a peer - * Circumvents polling of peers for message - * @param peerId id of peer - */ - virtual void requestGroupsOfPeer(const std::string& peerId) = 0; - - /*! - * get messages of a peer for a given group id, this circumvents the normal - * polling of peers for messages of given group id - * @param peerId Id of peer - * @param grpId id of group to request messages for - */ - virtual void requestMessagesOfPeer(const std::string& peerId, const std::string& grpId) = 0; - /*! * Initiates a search through the network * This returns messages which contains the search terms set in RsGxsSearch @@ -116,7 +101,7 @@ public: * @param msgId the messages to retrieve * @return request token to be redeemed */ - virtual int requestMsg(const std::string& msgId, uint8_t hops) = 0; + virtual int requestMsg(const RsGxsGrpMsgIdPair& msgId) = 0; /*! * Request for this group is sent through to peers on your network @@ -124,7 +109,7 @@ public: * @param enabled set to false to disable pause, and true otherwise * @return request token to be redeemed */ - virtual int requestGrp(const std::list& grpId, uint8_t hops) = 0; + virtual int requestGrp(const std::list& grpId, const std::string& peerId) = 0; }; diff --git a/libretroshare/src/services/p3idservice.cc b/libretroshare/src/services/p3idservice.cc index 5864ae32d..c63dd524b 100644 --- a/libretroshare/src/services/p3idservice.cc +++ b/libretroshare/src/services/p3idservice.cc @@ -140,7 +140,7 @@ p3IdService::p3IdService(RsGeneralDataService *gds, RsNetworkExchangeService *ne : RsGxsIdExchange(gds, nes, new RsGxsIdSerialiser(), RS_SERVICE_GXSV2_TYPE_GXSID, idAuthenPolicy()), RsIdentity(this), GxsTokenQueue(this), RsTickEvent(), mIdMtx("p3IdService"), mPublicKeyCache(DEFAULT_MEM_CACHE_SIZE, "GxsIdPublicKeyCache"), - mPrivateKeyCache(DEFAULT_MEM_CACHE_SIZE, "GxsIdPrivateKeyCache") + mPrivateKeyCache(DEFAULT_MEM_CACHE_SIZE, "GxsIdPrivateKeyCache"), mNes(nes) { mBgSchedule_Mode = 0; mBgSchedule_Active = false; @@ -1366,6 +1366,9 @@ bool p3IdService::cache_start_load() RsGenExchange::getTokenService()->requestGroupInfo(token, ansType, opts, groupIds); GxsTokenQueue::queueRequest(token, GXSIDREQ_CACHELOAD); + std::set groupIdSet; + groupIdSet.insert(groupIds.begin(), groupIds.end()); + mGroupsToCache.insert(std::make_pair(token, groupIdSet)); } return 1; } @@ -1401,10 +1404,29 @@ bool p3IdService::cache_load_for_token(uint32_t token) std::cerr << std::endl; #endif // DEBUG_IDS + + { + // remove identities that are present + RsStackMutex stack(mIdMtx); + mGroupsToCache[token].erase(item->meta.mGroupId); + } + /* cache the data */ cache_store(item); delete item; } + + { + // now store identities that aren't present + RsStackMutex stack(mIdMtx); + const std::set& groupIdSet = mGroupsToCache[token]; + + if(!groupIdSet.empty()) + mGroupNotPresent[token].assign(groupIdSet.begin(), groupIdSet.end()); + + mGroupsToCache.erase(token); + } + } else { @@ -3601,7 +3623,13 @@ std::ostream &operator<<(std::ostream &out, const RsGxsIdOpinion &opinion) +void p3IdService::checkPeerForIdentities() +{ + RsStackMutex stack(mIdMtx); + // crud, i needed peers instead! + mGroupNotPresent.clear(); +} // Overloaded from GxsTokenQueue for Request callbacks. diff --git a/libretroshare/src/services/p3idservice.h b/libretroshare/src/services/p3idservice.h index a42712ed4..6270ee9e4 100644 --- a/libretroshare/src/services/p3idservice.h +++ b/libretroshare/src/services/p3idservice.h @@ -358,6 +358,12 @@ virtual void handle_event(uint32_t event_type, const std::string &elabel); void loadRecognKeys(); + /************************************************************************ + * for getting identities that are not present + * + */ + void checkPeerForIdentities(); + /* MUTEX PROTECTED DATA (mIdMtx - maybe should use a 2nd?) */ bool checkRecognSignature_locked(std::string encoded, RSA &key, std::string signature); @@ -413,6 +419,11 @@ std::string genRandomId(int len = 20); std::vector mGroupChange; std::vector mMsgChange; + private: + + std::map > mGroupsToCache; + std::map > mGroupNotPresent; + RsNetworkExchangeService* mNes; }; #endif // P3_IDENTITY_SERVICE_HEADER From 812ddef40e5e95b8f2d35c771d4dcb3a2885084e Mon Sep 17 00:00:00 2001 From: drbob Date: Thu, 31 Oct 2013 23:39:05 +0000 Subject: [PATCH 48/83] added missing mutex lock. git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.5-gxs_finale@6885 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/services/p3idservice.cc | 2 ++ 1 file changed, 2 insertions(+) diff --git a/libretroshare/src/services/p3idservice.cc b/libretroshare/src/services/p3idservice.cc index c63dd524b..d86a4fe23 100644 --- a/libretroshare/src/services/p3idservice.cc +++ b/libretroshare/src/services/p3idservice.cc @@ -1368,6 +1368,8 @@ bool p3IdService::cache_start_load() GxsTokenQueue::queueRequest(token, GXSIDREQ_CACHELOAD); std::set groupIdSet; groupIdSet.insert(groupIds.begin(), groupIds.end()); + + RsStackMutex stack(mIdMtx); /********** STACK LOCKED MTX ******/ mGroupsToCache.insert(std::make_pair(token, groupIdSet)); } return 1; From 67c55991d7b418a1938c57f413f448278d9920fc Mon Sep 17 00:00:00 2001 From: chrisparker126 Date: Sun, 3 Nov 2013 23:46:34 +0000 Subject: [PATCH 49/83] decided to continue propagating peer details in - gxsnet now has a ctor option to disable auto group sync git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.5-gxs_finale@6888 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/gxs/rsgenexchange.cc | 2 + libretroshare/src/gxs/rsgxsnetservice.cc | 24 ++++--- libretroshare/src/gxs/rsgxsnetservice.h | 3 +- libretroshare/src/rsserver/rsinit.cc | 4 +- libretroshare/src/services/p3idservice.cc | 87 ++++++++++++++++++----- libretroshare/src/services/p3idservice.h | 11 ++- 6 files changed, 96 insertions(+), 35 deletions(-) diff --git a/libretroshare/src/gxs/rsgenexchange.cc b/libretroshare/src/gxs/rsgenexchange.cc index a41f948af..ffa2a3000 100644 --- a/libretroshare/src/gxs/rsgenexchange.cc +++ b/libretroshare/src/gxs/rsgenexchange.cc @@ -820,6 +820,7 @@ int RsGenExchange::validateMsg(RsNxsMsg *msg, const uint32_t& grpFlag, RsTlvSecu }else { std::list peers; + peers.push_back(msg->PeerId()); mGixs->requestKey(metaData.mAuthorId, peers); return VALIDATE_FAIL_TRY_LATER; } @@ -893,6 +894,7 @@ int RsGenExchange::validateGrp(RsNxsGrp* grp, RsTlvSecurityKeySet& grpKeySet) }else { std::list peers; + peers.push_back(grp->PeerId()); mGixs->requestKey(metaData.mAuthorId, peers); return VALIDATE_FAIL_TRY_LATER; } diff --git a/libretroshare/src/gxs/rsgxsnetservice.cc b/libretroshare/src/gxs/rsgxsnetservice.cc index 537fb094c..afab99ba0 100644 --- a/libretroshare/src/gxs/rsgxsnetservice.cc +++ b/libretroshare/src/gxs/rsgxsnetservice.cc @@ -36,16 +36,16 @@ #define GIXS_CUT_OFF 0 #define SYNC_PERIOD 12 // in microseconds every 10 seconds (1 second for testing) -#define TRANSAC_TIMEOUT 5 // 5 seconds +#define TRANSAC_TIMEOUT 10 // 10 seconds const uint32_t RsGxsNetService::FRAGMENT_SIZE = 150000; RsGxsNetService::RsGxsNetService(uint16_t servType, RsGeneralDataService *gds, - RsNxsNetMgr *netMgr, RsNxsObserver *nxsObs, RsGixsReputation* reputations, RsGcxs* circles) + RsNxsNetMgr *netMgr, RsNxsObserver *nxsObs, RsGixsReputation* reputations, RsGcxs* circles, bool grpAutoSync) : p3Config(servType), p3ThreadedService(servType), mTransactionTimeOut(TRANSAC_TIMEOUT), mServType(servType), mDataStore(gds), mTransactionN(0), mObserver(nxsObs), mNxsMutex("RsGxsNetService"), mNetMgr(netMgr), mSYNC_PERIOD(SYNC_PERIOD), - mSyncTs(0), mReputations(reputations), mCircles(circles) + mSyncTs(0), mReputations(reputations), mCircles(circles), mGrpAutoSync(grpAutoSync) { addSerialType(new RsNxsSerialiser(mServType)); @@ -85,13 +85,16 @@ void RsGxsNetService::syncWithPeers() std::set::iterator sit = peers.begin(); - // for now just grps - for(; sit != peers.end(); sit++) + if(mGrpAutoSync) { - RsNxsSyncGrp *grp = new RsNxsSyncGrp(mServType); - grp->clear(); - grp->PeerId(*sit); - sendItem(grp); + // for now just grps + for(; sit != peers.end(); sit++) + { + RsNxsSyncGrp *grp = new RsNxsSyncGrp(mServType); + grp->clear(); + grp->PeerId(*sit); + sendItem(grp); + } } #ifdef GXS_ENABLE_SYNC_MSGS @@ -773,8 +776,7 @@ void RsGxsNetService::run(){ bool RsGxsNetService::locked_checkTransacTimedOut(NxsTransaction* tr) { - //return tr->mTimeOut < ((uint32_t) time(NULL)); - return false; + return tr->mTimeOut < ((uint32_t) time(NULL)); } void RsGxsNetService::processTransactions(){ diff --git a/libretroshare/src/gxs/rsgxsnetservice.h b/libretroshare/src/gxs/rsgxsnetservice.h index 4cb16a2c3..33d1c9d50 100644 --- a/libretroshare/src/gxs/rsgxsnetservice.h +++ b/libretroshare/src/gxs/rsgxsnetservice.h @@ -73,7 +73,7 @@ public: * arrive */ RsGxsNetService(uint16_t servType, RsGeneralDataService* gds, RsNxsNetMgr* netMgr, - RsNxsObserver* nxsObs = NULL, RsGixsReputation* repuations = NULL, RsGcxs* circles = NULL); + RsNxsObserver* nxsObs = NULL, RsGixsReputation* repuations = NULL, RsGcxs* circles = NULL, bool grpAutoSync = true); virtual ~RsGxsNetService(); @@ -420,6 +420,7 @@ private: RsGcxs* mCircles; RsGixsReputation* mReputations; + bool mGrpAutoSync; // need to be verfied std::vector mPendingResp; diff --git a/libretroshare/src/rsserver/rsinit.cc b/libretroshare/src/rsserver/rsinit.cc index 37e9598f9..e4f58908f 100644 --- a/libretroshare/src/rsserver/rsinit.cc +++ b/libretroshare/src/rsserver/rsinit.cc @@ -2268,7 +2268,8 @@ int RsServer::StartupRetroShare() // create GXS photo service RsGxsNetService* gxsid_ns = new RsGxsNetService( RS_SERVICE_GXSV2_TYPE_GXSID, gxsid_ds, nxsMgr, - mGxsIdService, mGxsIdService, mGxsCircles); + mGxsIdService, mGxsIdService, mGxsCircles, + false); // don't synchronise group automatic (need explicit group request) /**** GxsCircle service ****/ @@ -2653,7 +2654,6 @@ int RsServer::StartupRetroShare() createThread(*gxsforums_ns); createThread(*gxschannels_ns); - #endif // RS_ENABLE_GXS ftserver->StartupThreads(); diff --git a/libretroshare/src/services/p3idservice.cc b/libretroshare/src/services/p3idservice.cc index d86a4fe23..f358cf561 100644 --- a/libretroshare/src/services/p3idservice.cc +++ b/libretroshare/src/services/p3idservice.cc @@ -112,6 +112,7 @@ RsIdentity *rsIdentity = NULL; #define GXSID_EVENT_DUMMY_PGPID 0x2002 #define GXSID_EVENT_DUMMY_UNKNOWN_PGPID 0x2003 #define GXSID_EVENT_DUMMY_PSEUDOID 0x2004 +#define GXSID_EVENT_REQUEST_IDS 0x2005 /* delays */ @@ -411,9 +412,26 @@ bool p3IdService::requestKey(const RsGxsId &id, const std::list &peers) { if (haveKey(id)) return true; + else + { + if(isPendingNetworkRequest(id)) + return true; + } + + return cache_request_load(id); } +bool p3IdService::isPendingNetworkRequest(const RsGxsId& gxsId) const +{ + // if ids has beens confirmed as not physically present return + // immediately, id will be removed from list if found by auto nxs net search + if(mIdsNotPresent.find(gxsId) != mIdsNotPresent.end()) + return true; + + return false; +} + int p3IdService::getKey(const RsGxsId &id, RsTlvSecurityKey &key) { RsStackMutex stack(mIdMtx); /********** STACK LOCKED MTX ******/ @@ -1298,7 +1316,7 @@ bool p3IdService::cache_store(const RsGxsIdGroupItem *item) #define MIN_CYCLE_GAP 2 -bool p3IdService::cache_request_load(const RsGxsId &id) +bool p3IdService::cache_request_load(const RsGxsId &id, const std::list& peers) { #ifdef DEBUG_IDS std::cerr << "p3IdService::cache_request_load(" << id << ")"; @@ -1307,7 +1325,7 @@ bool p3IdService::cache_request_load(const RsGxsId &id) { RsStackMutex stack(mIdMtx); /********** STACK LOCKED MTX ******/ - mCacheLoad_ToCache.push_back(id); + mCacheLoad_ToCache.insert(std::make_pair(id, peers)); } if (RsTickEvent::event_count(GXSID_EVENT_CACHELOAD) > 0) @@ -1339,16 +1357,17 @@ bool p3IdService::cache_start_load() RsStackMutex stack(mIdMtx); /********** STACK LOCKED MTX ******/ /* now we process the modGroupList -> a map so we can use it easily later, and create id list too */ - std::list::iterator it; + std::map >::iterator it; for(it = mCacheLoad_ToCache.begin(); it != mCacheLoad_ToCache.end(); it++) { #ifdef DEBUG_IDS - std::cerr << "p3IdService::cache_start_load() GroupId: " << *it; + std::cerr << "p3IdService::cache_start_load() GroupId: " << it->first; std::cerr << std::endl; #endif // DEBUG_IDS - groupIds.push_back(*it); // might need conversion? + groupIds.push_back(it->first); // might need conversion? } + // mPendingCache.insert(mCacheLoad_ToCache.begin(), mCacheLoad_ToCache.end()); mCacheLoad_ToCache.clear(); } @@ -1365,12 +1384,7 @@ bool p3IdService::cache_start_load() uint32_t token = 0; RsGenExchange::getTokenService()->requestGroupInfo(token, ansType, opts, groupIds); - GxsTokenQueue::queueRequest(token, GXSIDREQ_CACHELOAD); - std::set groupIdSet; - groupIdSet.insert(groupIds.begin(), groupIds.end()); - - RsStackMutex stack(mIdMtx); /********** STACK LOCKED MTX ******/ - mGroupsToCache.insert(std::make_pair(token, groupIdSet)); + GxsTokenQueue::queueRequest(token, GXSIDREQ_CACHELOAD); } return 1; } @@ -1410,7 +1424,7 @@ bool p3IdService::cache_load_for_token(uint32_t token) { // remove identities that are present RsStackMutex stack(mIdMtx); - mGroupsToCache[token].erase(item->meta.mGroupId); + mPendingCache.erase(item->meta.mGroupId); } /* cache the data */ @@ -1420,13 +1434,13 @@ bool p3IdService::cache_load_for_token(uint32_t token) { // now store identities that aren't present + RsStackMutex stack(mIdMtx); - const std::set& groupIdSet = mGroupsToCache[token]; + mIdsNotPresent.insert(mPendingCache.begin(), mPendingCache.end()); + mPendingCache.clear(); - if(!groupIdSet.empty()) - mGroupNotPresent[token].assign(groupIdSet.begin(), groupIdSet.end()); - - mGroupsToCache.erase(token); + if(!mIdsNotPresent.empty()) + schedule_now(GXSID_EVENT_REQUEST_IDS); } } @@ -1440,6 +1454,39 @@ bool p3IdService::cache_load_for_token(uint32_t token) return true; } +void p3IdService::requestIdsFromNet() +{ + RsStackMutex stack(mIdMtx); + + std::map >::const_iterator cit; + std::map > requests; + + // transform to appropriate structure ( > map) to make request to nes + for(cit = mIdsNotPresent.begin(); cit != mIdsNotPresent.end(); cit++) + { + { +#ifdef DEBUG_IDS + std::cerr << "p3IdService::requestIdsFromNet() Id not found, deferring for net request: "; + std::cerr << cit->first; + std::cerr << std::endl; +#endif // DEBUG_IDS + + } + + const std::list& peers = cit->second; + std::list::const_iterator cit2; + for(cit2 = peers.begin(); cit2 != peers.end(); cit2++) + requests[*cit2].push_back(cit->first); + } + + std::map >::const_iterator cit2; + + for(cit2 = requests.begin(); cit2 != requests.end(); cit2++) + mNes->requestGrp(cit2->second, cit2->first); + + mIdsNotPresent.clear(); +} + bool p3IdService::cache_update_if_cached(const RsGxsId &id, std::string serviceString) { /* if these entries are cached - update with new info */ @@ -2483,7 +2530,7 @@ bool p3IdService::recogn_process() bool isDone = false; { RsStackMutex stack(mIdMtx); /********** STACK LOCKED MTX ******/ - if (!mRecognGroupsToProcess.empty()) + if (!mRecognGroupsToProcess.empty() && !mGroupsToProcess.empty()) { item = mRecognGroupsToProcess.front(); mGroupsToProcess.pop_front(); @@ -3735,6 +3782,10 @@ void p3IdService::handle_event(uint32_t event_type, const std::string &elabel) case GXSID_EVENT_DUMMY_PSEUDOID: generateDummy_UnknownPseudo(); break; + case GXSID_EVENT_REQUEST_IDS: + requestIdsFromNet(); + break; + default: /* error */ diff --git a/libretroshare/src/services/p3idservice.h b/libretroshare/src/services/p3idservice.h index 6270ee9e4..f15a0230d 100644 --- a/libretroshare/src/services/p3idservice.h +++ b/libretroshare/src/services/p3idservice.h @@ -284,16 +284,20 @@ virtual void handle_event(uint32_t event_type, const std::string &elabel); */ int cache_tick(); - bool cache_request_load(const RsGxsId &id); + bool cache_request_load(const RsGxsId &id, const std::list& peers = std::list()); bool cache_start_load(); bool cache_load_for_token(uint32_t token); bool cache_store(const RsGxsIdGroupItem *item); bool cache_update_if_cached(const RsGxsId &id, std::string serviceString); + bool isPendingNetworkRequest(const RsGxsId& gxsId) const; + void requestIdsFromNet(); + // Mutex protected. - std::list mCacheLoad_ToCache; + //std::list mCacheLoad_ToCache; + std::map > mCacheLoad_ToCache, mPendingCache; // Switching to RsMemCache for Key Caching. RsMemCache mPublicKeyCache; @@ -421,8 +425,9 @@ std::string genRandomId(int len = 20); private: - std::map > mGroupsToCache; + std::map > mIdsPendingCache; std::map > mGroupNotPresent; + std::map > mIdsNotPresent; RsNetworkExchangeService* mNes; }; From cf8a63888b2ddc062bedf799183aee9067958c40 Mon Sep 17 00:00:00 2001 From: chrisparker126 Date: Mon, 4 Nov 2013 14:09:32 +0000 Subject: [PATCH 50/83] some fixes - id pull now works (Peer A, Peer B test) git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.5-gxs_finale@6889 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/gxs/rsgixs.h | 2 +- libretroshare/src/gxs/rsgxsnetservice.cc | 9 +++++++-- libretroshare/src/gxs/rsgxsnetutils.cc | 10 ++++++---- libretroshare/src/gxs/rsgxsnetutils.h | 2 +- libretroshare/src/rsserver/rsinit.cc | 1 + libretroshare/src/services/p3idservice.cc | 23 +++++++++++++++++++---- libretroshare/src/services/p3idservice.h | 8 +++++++- 7 files changed, 42 insertions(+), 13 deletions(-) diff --git a/libretroshare/src/gxs/rsgixs.h b/libretroshare/src/gxs/rsgixs.h index 304609711..cd3bddf9a 100644 --- a/libretroshare/src/gxs/rsgixs.h +++ b/libretroshare/src/gxs/rsgixs.h @@ -176,7 +176,7 @@ class RsGixsReputation public: // get Reputation. virtual bool haveReputation(const RsGxsId &id) = 0; - virtual bool loadReputation(const RsGxsId &id) = 0; + virtual bool loadReputation(const RsGxsId &id, const std::list& peers) = 0; virtual bool getReputation(const RsGxsId &id, GixsReputation &rep) = 0; }; diff --git a/libretroshare/src/gxs/rsgxsnetservice.cc b/libretroshare/src/gxs/rsgxsnetservice.cc index afab99ba0..872a1777d 100644 --- a/libretroshare/src/gxs/rsgxsnetservice.cc +++ b/libretroshare/src/gxs/rsgxsnetservice.cc @@ -1263,6 +1263,9 @@ void RsGxsNetService::locked_genReqMsgTransaction(NxsTransaction* tr) MsgAuthorV toVet; + std::list peers; + peers.push_back(tr->mTransaction->PeerId()); + for(; llit != msgItemL.end(); llit++) { RsNxsSyncMsgItem*& syncItem = *llit; @@ -1289,7 +1292,7 @@ void RsGxsNetService::locked_genReqMsgTransaction(NxsTransaction* tr) else { // preload for speed - mReputations->loadReputation(syncItem->authorId); + mReputations->loadReputation(syncItem->authorId, peers); MsgAuthEntry entry; entry.mAuthorId = syncItem->authorId; entry.mGrpId = syncItem->grpId; @@ -1380,6 +1383,8 @@ void RsGxsNetService::locked_genReqGrpTransaction(NxsTransaction* tr) uint32_t transN = locked_getTransactionId(); GrpAuthorV toVet; + std::list peers; + peers.push_back(tr->mTransaction->PeerId()); for(; llit != grpItemL.end(); llit++) { @@ -1413,7 +1418,7 @@ void RsGxsNetService::locked_genReqGrpTransaction(NxsTransaction* tr) else { // preload reputation for later - mReputations->loadReputation(grpSyncItem->authorId); + mReputations->loadReputation(grpSyncItem->authorId, peers); GrpAuthEntry entry; entry.mAuthorId = grpSyncItem->authorId; entry.mGrpId = grpSyncItem->grpId; diff --git a/libretroshare/src/gxs/rsgxsnetutils.cc b/libretroshare/src/gxs/rsgxsnetutils.cc index f61ee033c..e5fb94447 100644 --- a/libretroshare/src/gxs/rsgxsnetutils.cc +++ b/libretroshare/src/gxs/rsgxsnetutils.cc @@ -47,14 +47,16 @@ bool AuthorPending::expired() const } bool AuthorPending::getAuthorRep(GixsReputation& rep, - const std::string& authorId) + const std::string& authorId, const std::string& peerId) { if(mRep->haveReputation(authorId)) { return mRep->getReputation(authorId, rep); } - mRep->loadReputation(authorId); + std::list peers; + peers.push_back(peerId); + mRep->loadReputation(authorId, peers); return false; } @@ -94,7 +96,7 @@ bool MsgRespPending::accepted() if(!entry.mPassedVetting) { GixsReputation rep; - if(getAuthorRep(rep, entry.mAuthorId)) + if(getAuthorRep(rep, entry.mAuthorId, mPeerId)) { if(rep.score > mCutOff) { @@ -129,7 +131,7 @@ bool GrpRespPending::accepted() { GixsReputation rep; - if(getAuthorRep(rep, entry.mAuthorId)) + if(getAuthorRep(rep, entry.mAuthorId, mPeerId)) { if(rep.score > mCutOff) { diff --git a/libretroshare/src/gxs/rsgxsnetutils.h b/libretroshare/src/gxs/rsgxsnetutils.h index 1bd70b9b9..b93283aac 100644 --- a/libretroshare/src/gxs/rsgxsnetutils.h +++ b/libretroshare/src/gxs/rsgxsnetutils.h @@ -141,7 +141,7 @@ protected: * @param authorId reputation to get * @return true if successfully retrieve repution */ - bool getAuthorRep(GixsReputation& rep, const std::string& authorId); + bool getAuthorRep(GixsReputation& rep, const std::string& authorId, const std::string& peerId); private: diff --git a/libretroshare/src/rsserver/rsinit.cc b/libretroshare/src/rsserver/rsinit.cc index e4f58908f..3c8f54155 100644 --- a/libretroshare/src/rsserver/rsinit.cc +++ b/libretroshare/src/rsserver/rsinit.cc @@ -2271,6 +2271,7 @@ int RsServer::StartupRetroShare() mGxsIdService, mGxsIdService, mGxsCircles, false); // don't synchronise group automatic (need explicit group request) + mGxsIdService->setNes(gxsid_ns); /**** GxsCircle service ****/ diff --git a/libretroshare/src/services/p3idservice.cc b/libretroshare/src/services/p3idservice.cc index f358cf561..a518b6c19 100644 --- a/libretroshare/src/services/p3idservice.cc +++ b/libretroshare/src/services/p3idservice.cc @@ -164,6 +164,11 @@ p3IdService::p3IdService(RsGeneralDataService *gds, RsNetworkExchangeService *ne loadRecognKeys(); } +void p3IdService::setNes(RsNetworkExchangeService *nes) +{ + RsStackMutex stack(mIdMtx); + mNes = nes; +} uint32_t p3IdService::idAuthenPolicy() { @@ -419,7 +424,7 @@ bool p3IdService::requestKey(const RsGxsId &id, const std::list &peers) } - return cache_request_load(id); + return cache_request_load(id, peers); } bool p3IdService::isPendingNetworkRequest(const RsGxsId& gxsId) const @@ -473,11 +478,18 @@ bool p3IdService::haveReputation(const RsGxsId &id) return haveKey(id); } -bool p3IdService::loadReputation(const RsGxsId &id) +bool p3IdService::loadReputation(const RsGxsId &id, const std::list& peers) { if (haveKey(id)) return true; - return cache_request_load(id); + else + { + if(isPendingNetworkRequest(id)) + return true; + } + + + return cache_request_load(id, peers); } bool p3IdService::getReputation(const RsGxsId &id, GixsReputation &rep) @@ -1367,7 +1379,7 @@ bool p3IdService::cache_start_load() groupIds.push_back(it->first); // might need conversion? } - // mPendingCache.insert(mCacheLoad_ToCache.begin(), mCacheLoad_ToCache.end()); + mPendingCache.insert(mCacheLoad_ToCache.begin(), mCacheLoad_ToCache.end()); mCacheLoad_ToCache.clear(); } @@ -1482,7 +1494,10 @@ void p3IdService::requestIdsFromNet() std::map >::const_iterator cit2; for(cit2 = requests.begin(); cit2 != requests.end(); cit2++) + { + if(mNes) mNes->requestGrp(cit2->second, cit2->first); + } mIdsNotPresent.clear(); } diff --git a/libretroshare/src/services/p3idservice.h b/libretroshare/src/services/p3idservice.h index f15a0230d..8cf81c606 100644 --- a/libretroshare/src/services/p3idservice.h +++ b/libretroshare/src/services/p3idservice.h @@ -196,6 +196,12 @@ static uint32_t idAuthenPolicy(); virtual void service_tick(); // needed for background processing. + /*! + * Design hack, id service must be constructed first as it + * is need for construction of subsequent net services + */ + void setNes(RsNetworkExchangeService* nes); + /* General Interface is provided by RsIdentity / RsGxsIfaceImpl. */ /* Data Specific Interface */ @@ -258,7 +264,7 @@ virtual int getPrivateKey(const RsGxsId &id, RsTlvSecurityKey &key); // get Reputation. virtual bool haveReputation(const RsGxsId &id); -virtual bool loadReputation(const RsGxsId &id); +virtual bool loadReputation(const RsGxsId &id, const std::list& peers); virtual bool getReputation(const RsGxsId &id, GixsReputation &rep); From 6871f9875aca048f68bf426d952d9461a8f2096d Mon Sep 17 00:00:00 2001 From: drbob Date: Tue, 5 Nov 2013 23:33:12 +0000 Subject: [PATCH 51/83] Fixed up bugs in Recogn System - basics work now. - added missing decrement to DataCount in rsmemcache::erase() - added missing note_event_locked() in rstickevent ... can now use previous tick info, - revamped recogn scheduling. on demand rather than periodic. new function recogn_schedule(). - deferred loading of pgpIdList for pgphashes, until we know it will be needed. git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.5-gxs_finale@6893 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/services/p3idservice.cc | 52 +++++++++++++++++++---- libretroshare/src/services/p3idservice.h | 1 + libretroshare/src/util/rsmemcache.h | 7 +++ libretroshare/src/util/rstickevent.cc | 1 + 4 files changed, 52 insertions(+), 9 deletions(-) diff --git a/libretroshare/src/services/p3idservice.cc b/libretroshare/src/services/p3idservice.cc index a518b6c19..9524cb48b 100644 --- a/libretroshare/src/services/p3idservice.cc +++ b/libretroshare/src/services/p3idservice.cc @@ -148,7 +148,6 @@ p3IdService::p3IdService(RsGeneralDataService *gds, RsNetworkExchangeService *ne // Kick off Cache Testing, + Others. RsTickEvent::schedule_in(GXSID_EVENT_PGPHASH, PGPHASH_PERIOD); - RsTickEvent::schedule_in(GXSID_EVENT_RECOGN, RECOGN_PERIOD); RsTickEvent::schedule_in(GXSID_EVENT_REPUTATION, REPUTATION_PERIOD); RsTickEvent::schedule_now(GXSID_EVENT_CACHEOWNIDS); @@ -1232,6 +1231,7 @@ bool p3IdService::cache_process_recogntaginfo(const RsGxsIdGroupItem *item, std: std::cerr << std::endl; #endif // DEBUG_RECOGN + recogn_schedule(); } return true; @@ -2054,8 +2054,6 @@ bool p3IdService::pgphash_start() std::cerr << std::endl; #endif // DEBUG_IDS - getPgpIdList(); - // ACTUALLY only need summary - but have written code for data. // Also need to use opts.groupFlags to filter stuff properly to REALID's only. // TODO @@ -2089,7 +2087,7 @@ bool p3IdService::pgphash_handlerequest(uint32_t token) // We Will do this later! std::vector groups; - std::vector groupsToProcess; + bool groupsToProcess = false; bool ok = getGroupData(token, groups); if(ok) @@ -2162,6 +2160,7 @@ bool p3IdService::pgphash_handlerequest(uint32_t token) RsStackMutex stack(mIdMtx); /********** STACK LOCKED MTX ******/ mGroupsToProcess.push_back(*vit); + groupsToProcess = true; } } else @@ -2170,6 +2169,12 @@ bool p3IdService::pgphash_handlerequest(uint32_t token) std::cerr << std::endl; } + if (groupsToProcess) + { + // update PgpIdList -> if there are groups to process. + getPgpIdList(); + } + // Schedule Processing. RsTickEvent::schedule_in(GXSID_EVENT_PGPHASH_PROC, PGPHASH_PROC_PERIOD); return true; @@ -2431,6 +2436,37 @@ void calcPGPHash(const RsGxsId &id, const PGPFingerprintType &pgp, GxsIdPgpHash * Info to be stored in GroupServiceString + Cache. **/ +bool p3IdService::recogn_schedule() +{ + std::cerr << "p3IdService::recogn_schedule()"; + std::cerr << std::endl; + + int32_t age = 0; + int32_t next_event = 0; + + if (RsTickEvent::event_count(GXSID_EVENT_RECOGN) > 0) + { + std::cerr << "p3IdService::recogn_schedule() Skipping GXSIS_EVENT_RECOGN already scheduled"; + std::cerr << std::endl; + return false; + } + + if (RsTickEvent::prev_event_ago(GXSID_EVENT_RECOGN, age)) + { + std::cerr << "p3IdService::recogn_schedule() previous event " << age << " secs ago"; + std::cerr << std::endl; + + next_event = RECOGN_PERIOD - age; + if (next_event < 0) + { + next_event = 0; + } + } + + RsTickEvent::schedule_in(GXSID_EVENT_RECOGN, next_event); + return true; +} + bool p3IdService::recogn_start() { @@ -2446,9 +2482,7 @@ bool p3IdService::recogn_start() return false; } - // SCHEDULE NEXT ONE. - RsTickEvent::schedule_in(GXSID_EVENT_RECOGN, RECOGN_PERIOD); - + // NEXT EVENT is scheduled via recogn_schedule. #ifdef DEBUG_RECOGN std::cerr << "p3IdService::recogn_start() making request"; @@ -2545,10 +2579,10 @@ bool p3IdService::recogn_process() bool isDone = false; { RsStackMutex stack(mIdMtx); /********** STACK LOCKED MTX ******/ - if (!mRecognGroupsToProcess.empty() && !mGroupsToProcess.empty()) + if (!mRecognGroupsToProcess.empty()) { item = mRecognGroupsToProcess.front(); - mGroupsToProcess.pop_front(); + mRecognGroupsToProcess.pop_front(); #ifdef DEBUG_RECOGN std::cerr << "p3IdService::recogn_process() Popped Group: " << item->meta.mGroupId; diff --git a/libretroshare/src/services/p3idservice.h b/libretroshare/src/services/p3idservice.h index 8cf81c606..48f8ebf9b 100644 --- a/libretroshare/src/services/p3idservice.h +++ b/libretroshare/src/services/p3idservice.h @@ -356,6 +356,7 @@ virtual void handle_event(uint32_t event_type, const std::string &elabel); * recogn processing. * */ + bool recogn_schedule(); bool recogn_start(); bool recogn_handlerequest(uint32_t token); bool recogn_process(); diff --git a/libretroshare/src/util/rsmemcache.h b/libretroshare/src/util/rsmemcache.h index 0f5fb966f..08a4e3a9a 100644 --- a/libretroshare/src/util/rsmemcache.h +++ b/libretroshare/src/util/rsmemcache.h @@ -204,6 +204,7 @@ template bool RsMemCache::erase(const Key &k // remove from lru. mDataMap.erase(it); update_lrumap(key, old_ts, new_ts); + mDataCount--; mStats_access++; return true; @@ -362,6 +363,12 @@ template bool RsMemCache::resize() // ERROR. std::cerr << "RsMemCache::resize() CONSISTENCY ERROR"; std::cerr << std::endl; + std::cerr << "\tmDataMap.size() = " << mDataMap.size(); + std::cerr << std::endl; + std::cerr << "\tmLruMap.size() = " << mLruMap.size(); + std::cerr << std::endl; + std::cerr << "\tmDataCount = " << mDataCount; + std::cerr << std::endl; } if (mDataCount > mMaxSize) diff --git a/libretroshare/src/util/rstickevent.cc b/libretroshare/src/util/rstickevent.cc index 2ebbeec91..69781a4f2 100644 --- a/libretroshare/src/util/rstickevent.cc +++ b/libretroshare/src/util/rstickevent.cc @@ -80,6 +80,7 @@ void RsTickEvent::tick_events() mEvents.erase(it); count_adjust_locked(event_type, -1); + note_event_locked(event_type); } } From 2e886bf443128e5d8b625ca372065917ac7e6a0c Mon Sep 17 00:00:00 2001 From: chrisparker126 Date: Sun, 10 Nov 2013 22:27:50 +0000 Subject: [PATCH 52/83] Add gxs update items for nxs sync optimisation git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.5-gxs_finale@6901 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- .../src/serialiser/rsgxsupdateitems.cc | 348 ++++++++++++++++++ .../src/serialiser/rsgxsupdateitems.h | 105 ++++++ 2 files changed, 453 insertions(+) create mode 100644 libretroshare/src/serialiser/rsgxsupdateitems.cc create mode 100644 libretroshare/src/serialiser/rsgxsupdateitems.h diff --git a/libretroshare/src/serialiser/rsgxsupdateitems.cc b/libretroshare/src/serialiser/rsgxsupdateitems.cc new file mode 100644 index 000000000..f99c7459a --- /dev/null +++ b/libretroshare/src/serialiser/rsgxsupdateitems.cc @@ -0,0 +1,348 @@ +/* + * libretroshare/src/serialiser: rsgxsupdateitems.h + * + * RetroShare Serialiser. + * + * Copyright 2012 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 "rsgxsupdateitems.h" + + + + +RsGxsGrpUpdateItem::RsGxsGrpUpdateItem() { +} + +RsGxsGrpUpdateItem::~RsGxsGrpUpdateItem() { +} + +void RsGxsGrpUpdateItem::clear() +{ + grpUpdateTS = 0; + peerId.clear(); +} + +std::ostream& RsGxsGrpUpdateItem::print(std::ostream& out, uint16_t indent) +{ + +} + +RsGxsMsgUpdateItem::RsGxsMsgUpdateItem() +{ +} + +RsGxsMsgUpdateItem::~RsGxsMsgUpdateItem() { +} + +void RsGxsMsgUpdateItem::clear() +{ + msgUpdateTS.clear(); + peerId.clear(); +} + +std::ostream& RsGxsMsgUpdateItem::print(std::ostream& out, uint16_t indent) +{ +} + +uint32_t RsGxsUpdateSerialiser::size(RsItem* item) +{ + RsGxsMsgUpdateItem* mui = NULL; + RsGxsGrpUpdateItem* gui = NULL; + + if((mui = dynamic_cast(item)) != NULL) + { + return sizeGxsMsgUpdate(mui); + }else if(( gui = dynamic_cast(item)) != NULL){ + return sizeGxsGrpUpdate(gui); + }else + { +#ifdef RSSERIAL_DEBUG + std::cerr << "RsGxsUpdateSerialiser::size(): Could not find appropriate size function" + << std::endl; +#endif + return 0; + } +} + +bool RsGxsUpdateSerialiser::serialise(RsItem* item, void* data, + uint32_t* size) +{ +} + +RsItem* RsGxsUpdateSerialiser::deserialise(void* data, uint32_t* size) +{ + +#ifdef RSSERIAL_DEBUG + std::cerr << "RsNxsSerialiser::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_GXS_MSG_UPDATE: + return deserialGxsMsgUpdate(data, size); + case RS_PKT_SUBTYPE_GXS_GRP_UPDATE: + return deserialGxsGrpUpddate(data, size); + default: + { +#ifdef RSSERIAL_DEBUG + std::cerr << "RsGxsUpdateSerialiser::deserialise() : data has no type" + << std::endl; +#endif + return NULL; + + } + } +} + +uint32_t RsGxsUpdateSerialiser::sizeGxsGrpUpdate(RsGxsGrpUpdateItem* item) +{ + uint32_t s = 8; // header size + s += GetTlvStringSize(item->peerId); + s += 4; + return s; +} + +bool RsGxsUpdateSerialiser::serialiseGxsGrpUpdate(RsGxsGrpUpdateItem* item, + void* data, uint32_t* size) +{ +#ifdef RSSERIAL_DEBUG + std::cerr << "RsGxsUpdateSerialiser::serialiseGxsGrpUpdate()" << std::endl; +#endif + + uint32_t tlvsize = sizeGxsGrpUpdate(item); + uint32_t offset = 0; + + if(*size < tlvsize){ +#ifdef RSSERIAL_DEBUG + std::cerr << "RsGxsUpdateSerialiser::serialiseGxsGrpUpdate() size do not match" << std::endl; +#endif + return false; + } + + *size = tlvsize; + + bool ok = true; + + ok &= setRsItemHeader(data, tlvsize, item->PacketId(), tlvsize); + + /* skip the header */ + offset += 8; + + /* RsNxsSyncm */ + + + ok &= SetTlvString(data, *size, &offset, TLV_TYPE_STR_PEERID, item->peerId); + ok &= setRawUInt32(data, *size, &offset, item->grpUpdateTS); + + if(offset != tlvsize){ +#ifdef RSSERIAL_DEBUG + std::cerr << "RsGxsUpdateSerialiser::serialiseGxsGrpUpdate() FAIL Size Error! " << std::endl; +#endif + ok = false; + } + +#ifdef RSSERIAL_DEBUG + if (!ok) + { + std::cerr << "RsGxsUpdateSerialiser::serialiseGxsGrpUpdate() NOK" << std::endl; + } +#endif + + return ok; +} + +RsGxsGrpUpdateItem* RsGxsUpdateSerialiser::deserialGxsGrpUpddate(void* data, + uint32_t* size) +{ + +} + +uint32_t RsGxsUpdateSerialiser::sizeGxsMsgUpdate(RsGxsMsgUpdateItem* item) +{ + uint32_t s = 8; // header size + s += GetTlvStringSize(item->peerId); + + const std::map& msgUpdateTS = item->msgUpdateTS; + std::map::const_iterator cit = msgUpdateTS.begin(); + + for(; cit != msgUpdateTS.end(); cit++) + { + s += GetTlvStringSize(cit->first); + s += 4; + } + + s += 4; // number of map items + + return s; +} + +bool RsGxsUpdateSerialiser::serialiseGxsMsgUpdate(RsGxsMsgUpdateItem* item, + void* data, uint32_t* size) +{ +#ifdef RSSERIAL_DEBUG + std::cerr << "RsGxsUpdateSerialiser::serialiseGxsMsgUpdate()" << std::endl; +#endif + + uint32_t tlvsize = sizeGxsMsgUpdate(item); + uint32_t offset = 0; + + if(*size < tlvsize){ +#ifdef RSSERIAL_DEBUG + std::cerr << "RsGxsUpdateSerialiser::serialiseGxsMsgUpdate() size do not match" << std::endl; +#endif + return false; + } + + *size = tlvsize; + + bool ok = true; + + ok &= setRsItemHeader(data, tlvsize, item->PacketId(), tlvsize); + + /* skip the header */ + offset += 8; + + /* RsNxsSyncm */ + + + ok &= SetTlvString(data, *size, &offset, TLV_TYPE_STR_PEERID, item->peerId); + + const std::map& msgUpdateTS = item->msgUpdateTS; + std::map::const_iterator cit = msgUpdateTS.begin(); + + uint32_t numItems = msgUpdateTS.size(); + ok &= setRawUInt32(data, *size, &offset, numItems); + + for(; cit != msgUpdateTS.end(); cit++) + { + ok &= SetTlvString(data, *size, &offset, TLV_TYPE_STR_PEERID, cit->first); + ok &= setRawUInt32(data, *size, &offset, cit->second); + } + + if(offset != tlvsize){ +#ifdef RSSERIAL_DEBUG + std::cerr << "RsGxsUpdateSerialiser::serialiseGxsMsgUpdate() FAIL Size Error! " << std::endl; +#endif + ok = false; + } + +#ifdef RSSERIAL_DEBUG + if (!ok) + { + std::cerr << "RsGxsUpdateSerialiser::serialiseGxsMsgUpdate() NOK" << std::endl; + } +#endif + + return ok; +} + +RsGxsMsgUpdateItem* RsGxsUpdateSerialiser::deserialGxsMsgUpdate(void* data, + uint32_t* size) +{ +#ifdef RSSERIAL_DEBUG + std::cerr << "RsGxsUpdateSerialiser::deserialGxsMsgUpdate()" << 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_NXS_SYNC_MSG != getRsItemSubType(rstype))) + { +#ifdef RSSERIAL_DEBUG + std::cerr << "RsGxsUpdateSerialiser::deserialGxsMsgUpdate() FAIL wrong type" << std::endl; +#endif + return NULL; /* wrong type */ + } + + if (*size < rssize) /* check size */ + { +#ifdef RSSERIAL_DEBUG + std::cerr << "RsGxsUpdateSerialiser::deserialGxsMsgUpdate() FAIL wrong size" << std::endl; +#endif + return NULL; /* not enough data */ + } + + /* set the packet length */ + *size = rssize; + + bool ok = true; + + RsGxsMsgUpdateItem* item = new RsGxsMsgUpdateItem(getRsItemService(rstype)); + + /* skip the header */ + offset += 8; + + ok &= GetTlvString(data, *size, &offset, TLV_TYPE_STR_HASH_SHA1, item->peerId); + uint32_t numUpdateItems; + ok &= getRawUInt32(data, *size, &offset, &(numUpdateItems)); + std::map& msgUpdateItem = item->grpUpdateTS; + std::string grpId; + uint32_t updateTS; + for(uint32_t i; i < numUpdateItems; i++) + { + ok &= GetTlvString(data, *size, &offset, TLV_TYPE_STR_GROUPID, grpId); + + if(!ok) + break; + + ok &= getRawUInt32(data, *size, &offset, &(updateTS)); + + if(!ok) + break; + + msgUpdateItem.insert(std::make_pair(grpId, updateTS)); + } + + if (offset != rssize) + { +#ifdef RSSERIAL_DEBUG + std::cerr << "RsGxsUpdateSerialiser::deserialGxsMsgUpdate() FAIL size mismatch" << std::endl; +#endif + /* error */ + delete item; + return NULL; + } + + if (!ok) + { +#ifdef RSSERIAL_DEBUG + std::cerr << "RsGxsUpdateSerialiser::deserialGxsMsgUpdate() NOK" << std::endl; +#endif + delete item; + return NULL; + } + + return item; +} diff --git a/libretroshare/src/serialiser/rsgxsupdateitems.h b/libretroshare/src/serialiser/rsgxsupdateitems.h new file mode 100644 index 000000000..4b16bcb1b --- /dev/null +++ b/libretroshare/src/serialiser/rsgxsupdateitems.h @@ -0,0 +1,105 @@ +#ifndef RSGXSUPDATEITEMS_H_ +#define RSGXSUPDATEITEMS_H_ + +/* + * libretroshare/src/serialiser: rsgxsupdateitems.h + * + * RetroShare Serialiser. + * + * Copyright 2012 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 + +#include "serialiser/rsserviceids.h" +#include "serialiser/rsserial.h" +#include "serialiser/rstlvbase.h" +#include "serialiser/rstlvtypes.h" +#include "serialiser/rstlvkeys.h" +#include "gxs/rsgxsdata.h" + + +const uint8_t RS_PKT_SUBTYPE_GXS_GRP_UPDATE = 0x0001; +const uint8_t RS_PKT_SUBTYPE_GXS_MSG_UPDATE = 0x0002; + +class RsGxsGrpUpdateItem : public RsItem { +public: + RsGxsGrpUpdateItem(); + virtual ~RsGxsGrpUpdateItem(); + + virtual void clear(); + virtual std::ostream &print(std::ostream &out, uint16_t indent); + + std::string peerId; + uint32_t grpUpdateTS; +}; + +class RsGxsMsgUpdateItem : public RsItem +{ +public: + RsGxsMsgUpdateItem(); + virtual ~RsGxsMsgUpdateItem(); + + virtual void clear(); + virtual std::ostream &print(std::ostream &out, uint16_t indent); + + std::string peerId; + std::map msgUpdateTS; +}; + + + +class RsGxsUpdateSerialiser : public RsSerialType +{ +public: + + RsGxsUpdateSerialiser(uint16_t servtype) : + RsSerialType(RS_PKT_VERSION_SERVICE, servtype), SERVICE_TYPE(servtype) { return; } + + virtual ~RsGxsUpdateSerialiser() { return; } + + virtual uint32_t size(RsItem *item); + virtual bool serialise(RsItem *item, void *data, uint32_t *size); + virtual RsItem* deserialise(void *data, uint32_t *size); + +private: + + + /* for RS_PKT_SUBTYPE_GRP_UPDATE_ITEM */ + + virtual uint32_t sizeGxsGrpUpdate(RsGxsGrpUpdateItem* item); + virtual bool serialiseGxsGrpUpdate(RsGxsGrpUpdateItem *item, void *data, uint32_t *size); + virtual RsGxsGrpUpdateItem* deserialGxsGrpUpddate(void *data, uint32_t *size); + + /* for RS_PKT_SUBTYPE_GXS_ */ + + virtual uint32_t sizeGxsMsgUpdate(RsGxsMsgUpdateItem* item); + virtual bool serialiseGxsMsgUpdate(RsGxsMsgUpdateItem *item, void *data, uint32_t *size); + virtual RsGxsMsgUpdateItem* deserialGxsMsgUpdate(void *data, uint32_t *size); + +private: + + const uint16_t SERVICE_TYPE; +}; + + + +#endif /* RSGXSUPDATEITEMS_H_ */ From f74aacd759e04099afa6389e9c332bec1189fb4c Mon Sep 17 00:00:00 2001 From: chrisparker126 Date: Sat, 16 Nov 2013 13:40:04 +0000 Subject: [PATCH 53/83] remaining code for nxs sync optimisation - still needs testing git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.5-gxs_finale@6903 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/gxs/rsgxsnetservice.cc | 246 +++++++++++- libretroshare/src/gxs/rsgxsnetservice.h | 20 + libretroshare/src/libretroshare.pro | 6 +- .../src/serialiser/rsgxsupdateitems.cc | 363 +++++++++++++++++- .../src/serialiser/rsgxsupdateitems.h | 56 ++- libretroshare/src/serialiser/rsnxsitems.cc | 37 +- libretroshare/src/serialiser/rsnxsitems.h | 9 +- 7 files changed, 678 insertions(+), 59 deletions(-) diff --git a/libretroshare/src/gxs/rsgxsnetservice.cc b/libretroshare/src/gxs/rsgxsnetservice.cc index 872a1777d..3485d2863 100644 --- a/libretroshare/src/gxs/rsgxsnetservice.cc +++ b/libretroshare/src/gxs/rsgxsnetservice.cc @@ -90,10 +90,21 @@ void RsGxsNetService::syncWithPeers() // for now just grps for(; sit != peers.end(); sit++) { - RsNxsSyncGrp *grp = new RsNxsSyncGrp(mServType); - grp->clear(); - grp->PeerId(*sit); - sendItem(grp); + + const std::string peerId = *sit; + + ClientGrpMap::const_iterator cit = mClientGrpUpdateMap.find(peerId); + uint32_t updateTS = 0; + if(cit != mClientGrpUpdateMap.end()) + { + const RsGxsGrpUpdateItem *gui = cit->second; + updateTS = gui->grpUpdateTS; + } + RsNxsSyncGrp *grp = new RsNxsSyncGrp(mServType); + grp->clear(); + grp->PeerId(*sit); + grp->updateTS = updateTS; + sendItem(grp); } } @@ -111,7 +122,9 @@ void RsGxsNetService::syncWithPeers() RsGxsGrpMetaData* meta = mit->second; if(meta->mSubscribeFlags & GXS_SERV::GROUP_SUBSCRIBE_SUBSCRIBED ) + { grpIds.push_back(mit->first); + } delete meta; } @@ -125,13 +138,36 @@ void RsGxsNetService::syncWithPeers() std::vector::iterator vit = grpIds.begin(); + // now see if you have an updateTS so optimise whether you need + // to get a new list of peer data + RsGxsMsgUpdateItem* mui = NULL; + + ClientMsgMap::const_iterator cit = mClientMsgUpdateMap.find(*sit); + + if(cit != mClientMsgUpdateMap.end()) + { + mui = cit->second; + } + for(; vit != grpIds.end(); vit++) { - RsNxsSyncMsg* msg = new RsNxsSyncMsg(mServType); - msg->clear(); - msg->PeerId(*sit); - msg->grpId = *vit; - sendItem(msg); + uint32_t updateTS = 0; + if(mui) + { + std::map::const_iterator cit2 = mui->msgUpdateTS.find(*vit); + + if(cit2 != mui->msgUpdateTS.end()) + { + updateTS = cit2->second; + } + } + + RsNxsSyncMsg* msg = new RsNxsSyncMsg(mServType); + msg->clear(); + msg->PeerId(*sit); + msg->grpId = *vit; + msg->updateTS = updateTS; + sendItem(msg); } } #endif @@ -526,20 +562,101 @@ void RsGxsNetService::collateMsgFragments(MsgFragments fragments, std::map& load) +class StoreHere { - return false; +public: + + StoreHere(RsGxsNetService::ClientGrpMap& cgm, RsGxsNetService::ClientMsgMap cmm, + RsGxsNetService::ServerMsgMap& smm, + RsGxsServerGrpUpdateItem*& sgm) : mClientGrpMap(cgm), mClientMsgMap(cmm), + mServerMsgMap(smm), mServerGrpUpdateItem(sgm) + {} + + void operator() (RsItem* item) + { + RsGxsMsgUpdateItem* mui; + RsGxsGrpUpdateItem* gui; + RsGxsServerGrpUpdateItem* gsui; + RsGxsServerMsgUpdateItem* msui; + + if((mui = dynamic_cast(item)) != NULL) + mClientMsgMap.insert(std::make_pair(mui->peerId, mui)); + else if((gui = dynamic_cast(item)) != NULL) + mClientGrpMap.insert(std::make_pair(gui->peerId, gui)); + else if((msui = dynamic_cast(item)) != NULL) + mServerMsgMap.insert(std::make_pair(msui->grpId, msui)); + else if((gsui = dynamic_cast(item)) != NULL) + { + if(mServerGrpUpdateItem) + { + mServerGrpUpdateItem = gsui; + } + else + { +#ifdef NXS_NET_DEBUG + std::cerr << "Error! More than one server group update item exists!" << std::endl; +#endif + delete gsui; + } + } + else + { + std::cerr << "Type not expected!" << std::endl; + } + + } + +private: + + RsGxsNetService::ClientGrpMap& mClientGrpMap; + RsGxsNetService::ClientMsgMap& mClientMsgMap; + RsGxsNetService::ServerMsgMap& mServerMsgMap; + RsGxsServerGrpUpdateItem*& mServerGrpUpdateItem; + +}; + +bool RsGxsNetService::loadList(std::list &load) +{ + std::for_each(load.begin(), load.end(), StoreHere(mClientGrpUpdateMap, mClientMsgUpdateMap, + mServerMsgUpdateMap, mGrpServerUpdateItem)); + return true; } +#include + +template +struct get_second : public std::unary_function +{ + RsItem* operator()(const typename UpdateMap::value_type& value) const + { + return value.second; + } +}; + bool RsGxsNetService::saveList(bool& cleanup, std::list& save) { - return false; + RsStackMutex stack(mNxsMutex); + + // hardcore templates + std::transform(mClientGrpUpdateMap.begin(), mClientGrpUpdateMap.end(), + std::back_inserter(save), get_second()); + + std::transform(mClientMsgUpdateMap.begin(), mClientMsgUpdateMap.end(), + std::back_inserter(save), get_second()); + + std::transform(mServerMsgUpdateMap.begin(), mServerMsgUpdateMap.end(), + std::back_inserter(save), get_second()); + + save.push_back(mGrpServerUpdateItem); } RsSerialiser *RsGxsNetService::setupSerialiser() { - return NULL; + + RsSerialiser *rss = new RsSerialiser; + rss->addSerialType(new RsGxsUpdateSerialiser(mServType)); + + return rss; } void RsGxsNetService::recvNxsItemQueue(){ @@ -1039,25 +1156,53 @@ void RsGxsNetService::locked_processCompletedIncomingTrans(NxsTransaction* tr) // notify listener of grps mObserver->notifyNewGroups(grps); + // now note this as the latest you've received from this peer + std::string peerFrom = tr->mTransaction->PeerId(); + uint32_t updateTS = tr->mTransaction->updateTS; + + ClientGrpMap::iterator it = mClientGrpUpdateMap.find(peerFrom); + + RsGxsGrpUpdateItem* item = NULL; + + if(it != mClientGrpUpdateMap.end()) + { + item = it->second; + }else + { + item = new RsGxsGrpUpdateItem(mServType); + } + + item->grpUpdateTS = updateTS; + item->peerId = peerFrom; + + mClientGrpUpdateMap.insert( + std::make_pair(peerFrom, item)); + + // as a grp list server also note this is the latest item you have + mGrpServerUpdateItem->grpUpdateTS = updateTS; }else if(flag & RsNxsTransac::FLAG_TYPE_MSGS) { std::vector msgs; + std::string grpId; while(tr->mItems.size() > 0) { RsNxsMsg* msg = dynamic_cast(tr->mItems.front()); if(msg) { - tr->mItems.pop_front(); - msgs.push_back(msg); + if(grpId.empty()) + grpId = msg->grpId; + + tr->mItems.pop_front(); + msgs.push_back(msg); } else { #ifdef NXS_NET_DEBUG - std::cerr << "RsGxsNetService::processCompletedTransactions(): item did not caste to msg" - << std::endl; + std::cerr << "RsGxsNetService::processCompletedTransactions(): item did not caste to msg" + << std::endl; #endif } } @@ -1081,6 +1226,10 @@ void RsGxsNetService::locked_processCompletedIncomingTrans(NxsTransaction* tr) // notify listener of msgs mObserver->notifyNewMessages(msgs); + // now note that this is the latest you've received from this peer + // for the grp id + locked_doMsgUpdateWork(tr->mTransaction, grpId); + } }else if(tr->mFlag == NxsTransaction::FLAG_STATE_FAILED){ // don't do anything transaction will simply be cleaned @@ -1088,6 +1237,46 @@ void RsGxsNetService::locked_processCompletedIncomingTrans(NxsTransaction* tr) return; } +void RsGxsNetService::locked_doMsgUpdateWork(const RsNxsTransac *nxsTrans, const std::string &grpId) +{ + + // firts check if peer exists + const std::string& peerFrom = nxsTrans->PeerId(); + + ClientMsgMap::iterator it = mClientMsgUpdateMap.find(peerFrom); + + RsGxsMsgUpdateItem* mui = NULL; + + // now update the peer's entry for this grp id + if(it != mClientMsgUpdateMap.end()) + { + mui = it->second; + } + else + { + mui = new RsGxsMsgUpdateItem(mServType); + mClientMsgUpdateMap.insert(std::make_pair(peerFrom, mui)); + } + + mui->msgUpdateTS[grpId] = nxsTrans->updateTS; + mui->peerId = peerFrom; + + ServerMsgMap::iterator mit = mServerMsgUpdateMap.find(grpId); + RsGxsServerMsgUpdateItem* msui = NULL; + if(mit != mServerMsgUpdateMap.end()) + { + msui = mit->second; + } + else + { + msui = new RsGxsServerMsgUpdateItem(mServType); + mServerMsgUpdateMap.insert(std::make_pair(grpId, msui)); + } + + msui->grpId = grpId; + msui->msgUpdateTS = nxsTrans->updateTS; +} + void RsGxsNetService::locked_processCompletedOutgoingTrans(NxsTransaction* tr) { uint16_t flag = tr->mTransaction->transactFlag; @@ -1128,6 +1317,7 @@ void RsGxsNetService::locked_processCompletedOutgoingTrans(NxsTransaction* tr) std::cerr << "complete Sending Grp Data, transN: " << tr->mTransaction->transactionNumber << std::endl; #endif + }else if(flag & RsNxsTransac::FLAG_TYPE_MSGS) { #ifdef NXS_NET_DEBUG @@ -1169,7 +1359,7 @@ void RsGxsNetService::locked_pushMsgTransactionFromList( newTrans->mTimeOut = time(NULL) + mTransactionTimeOut; // create transaction copy with your id to indicate // its an outgoing transaction - newTrans->mTransaction = new RsNxsTransac(*transac); + newTrans->mTransaction = new RsNxsTransac(*transac); newTrans->mTransaction->PeerId(mOwnId); sendItem(transac); { @@ -1250,7 +1440,7 @@ void RsGxsNetService::locked_genReqMsgTransaction(NxsTransaction* tr) msgIdSet.insert((*vit)->mMsgId); delete(*vit); } - msgMetaV.clear(); + msgMetaV.clear(); // get unique id for this transaction uint32_t transN = locked_getTransactionId(); @@ -1516,6 +1706,7 @@ void RsGxsNetService::locked_genSendGrpsTransaction(NxsTransaction* tr) ntr->transactionNumber = transN; ntr->transactFlag = RsNxsTransac::FLAG_BEGIN_P1 | RsNxsTransac::FLAG_TYPE_GRPS; + ntr->updateTS = time(NULL); ntr->nItems = grps.size(); ntr->PeerId(tr->mTransaction->PeerId()); @@ -1697,6 +1888,7 @@ void RsGxsNetService::locked_genSendMsgsTransaction(NxsTransaction* tr) ntr->transactionNumber = transN; ntr->transactFlag = RsNxsTransac::FLAG_BEGIN_P1 | RsNxsTransac::FLAG_TYPE_MSGS; + ntr->updateTS = time(NULL); ntr->nItems = msgSize; ntr->PeerId(peerId); @@ -1779,6 +1971,10 @@ void RsGxsNetService::handleRecvSyncGroup(RsNxsSyncGrp* item) std::string peer = item->PeerId(); + // don't sync if you have no new updates for this peer + if(item->updateTS >= mGrpServerUpdateItem->grpUpdateTS && item->updateTS != 0) + return; + std::map grp; mDataStore->retrieveGxsGrpMetaData(grp); @@ -1893,6 +2089,16 @@ void RsGxsNetService::handleRecvSyncMessage(RsNxsSyncMsg* item) const std::string& peer = item->PeerId(); + ServerMsgMap::const_iterator cit = mServerMsgUpdateMap.find(item->grpId); + + if(cit != mServerMsgUpdateMap.end()) + { + const RsGxsServerMsgUpdateItem *msui = cit->second; + + if(item->updateTS > msui->msgUpdateTS && item->updateTS != 0) + return; + } + GxsMsgMetaResult metaResult; GxsMsgReq req; diff --git a/libretroshare/src/gxs/rsgxsnetservice.h b/libretroshare/src/gxs/rsgxsnetservice.h index 33d1c9d50..0f7f95774 100644 --- a/libretroshare/src/gxs/rsgxsnetservice.h +++ b/libretroshare/src/gxs/rsgxsnetservice.h @@ -34,6 +34,7 @@ #include "rsnxsobserver.h" #include "pqi/p3linkmgr.h" #include "serialiser/rsnxsitems.h" +#include "serialiser/rsgxsupdateitems.h" #include "rsgxsnetutils.h" #include "pqi/p3cfgmgr.h" #include "rsgixs.h" @@ -323,6 +324,8 @@ private: bool locked_canReceive(const RsGxsGrpMetaData * const grpMeta, const std::string& peerId); void processExplicitGroupRequests(); + + void locked_doMsgUpdateWork(const RsNxsTransac* nxsTrans, const std::string& grpId); private: @@ -427,6 +430,23 @@ private: std::vector mPendingCircleVets; std::map > mExplicitRequest; + + // nxs sync optimisation + // can pull dynamically the latest timestamp for each message + +public: + + typedef std::map ClientMsgMap; + typedef std::map ServerMsgMap; + typedef std::map ClientGrpMap; + +private: + + ClientMsgMap mClientMsgUpdateMap; + ServerMsgMap mServerMsgUpdateMap; + ClientGrpMap mClientGrpUpdateMap; + + RsGxsServerGrpUpdateItem* mGrpServerUpdateItem; }; #endif // RSGXSNETSERVICE_H diff --git a/libretroshare/src/libretroshare.pro b/libretroshare/src/libretroshare.pro index 42fc6e8f8..c3c3ca174 100644 --- a/libretroshare/src/libretroshare.pro +++ b/libretroshare/src/libretroshare.pro @@ -388,7 +388,8 @@ HEADERS += serialiser/rsbaseitems.h \ serialiser/rsbanlistitems.h \ serialiser/rsbwctrlitems.h \ serialiser/rsgxsrecognitems.h \ - serialiser/rstunnelitems.h + serialiser/rstunnelitems.h \ + serialiser/rsgxsupdateitems.h HEADERS += services/p3channels.h \ services/p3chatservice.h \ @@ -532,7 +533,8 @@ SOURCES += serialiser/rsbaseitems.cc \ serialiser/rsbanlistitems.cc \ serialiser/rsbwctrlitems.cc \ serialiser/rsgxsrecognitems.cc \ - serialiser/rstunnelitems.cc + serialiser/rstunnelitems.cc \ + serialiser/rsgxsupdateitems.cc SOURCES += services/p3channels.cc \ services/p3chatservice.cc \ diff --git a/libretroshare/src/serialiser/rsgxsupdateitems.cc b/libretroshare/src/serialiser/rsgxsupdateitems.cc index f99c7459a..fdccdbeae 100644 --- a/libretroshare/src/serialiser/rsgxsupdateitems.cc +++ b/libretroshare/src/serialiser/rsgxsupdateitems.cc @@ -24,15 +24,11 @@ */ #include "rsgxsupdateitems.h" +#include "rsbaseserial.h" -RsGxsGrpUpdateItem::RsGxsGrpUpdateItem() { -} - -RsGxsGrpUpdateItem::~RsGxsGrpUpdateItem() { -} void RsGxsGrpUpdateItem::clear() { @@ -45,12 +41,7 @@ std::ostream& RsGxsGrpUpdateItem::print(std::ostream& out, uint16_t indent) } -RsGxsMsgUpdateItem::RsGxsMsgUpdateItem() -{ -} -RsGxsMsgUpdateItem::~RsGxsMsgUpdateItem() { -} void RsGxsMsgUpdateItem::clear() { @@ -66,12 +57,20 @@ uint32_t RsGxsUpdateSerialiser::size(RsItem* item) { RsGxsMsgUpdateItem* mui = NULL; RsGxsGrpUpdateItem* gui = NULL; + RsGxsServerGrpUpdateItem* gsui = NULL; + RsGxsServerMsgUpdateItem* msui = NULL; if((mui = dynamic_cast(item)) != NULL) { return sizeGxsMsgUpdate(mui); }else if(( gui = dynamic_cast(item)) != NULL){ return sizeGxsGrpUpdate(gui); + }else if((gsui = dynamic_cast(item)) != NULL) + { + return sizeGxsServerGrpUpdate(gsui); + }else if((msui = dynamic_cast(item)) != NULL) + { + return sizeGxsServerMsgUpdate(msui); }else { #ifdef RSSERIAL_DEBUG @@ -85,19 +84,41 @@ uint32_t RsGxsUpdateSerialiser::size(RsItem* item) bool RsGxsUpdateSerialiser::serialise(RsItem* item, void* data, uint32_t* size) { + RsGxsMsgUpdateItem* mui; + RsGxsGrpUpdateItem* gui; + RsGxsServerGrpUpdateItem* gsui; + RsGxsServerMsgUpdateItem* msui; + + if((mui = dynamic_cast(item)) != NULL) + return serialiseGxsMsgUpdate(mui, data, size); + else if((gui = dynamic_cast(item)) != NULL) + return serialiseGxsGrpUpdate(gui, data, size); + else if((msui = dynamic_cast(item)) != NULL) + return serialiseGxsServerMsgUpdate(msui, data, size); + else if((gsui = dynamic_cast(item)) != NULL) + return serialiseGxsServerGrpUpdate(gsui, data, size); + else + { +#ifdef RSSERIAL_DEBUG + std::cerr << "RsGxsUpdateSerialiser::serialise() item does not caste to known type" + << std::endl; +#endif + + return false; + } } RsItem* RsGxsUpdateSerialiser::deserialise(void* data, uint32_t* size) { #ifdef RSSERIAL_DEBUG - std::cerr << "RsNxsSerialiser::deserialise()" << std::endl; + std::cerr << "RsGxsUpdateSerialiser::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))) + (SERVICE_TYPE != getRsItemService(rstype))) { return NULL; /* wrong type */ } @@ -109,6 +130,10 @@ RsItem* RsGxsUpdateSerialiser::deserialise(void* data, uint32_t* size) return deserialGxsMsgUpdate(data, size); case RS_PKT_SUBTYPE_GXS_GRP_UPDATE: return deserialGxsGrpUpddate(data, size); + case RS_PKT_SUBTYPE_GXS_SERVER_GRP_UPDATE: + return deserialGxsServerGrpUpddate(data, size); + case RS_PKT_SUBTYPE_GXS_SERVER_MSG_UPDATE: + return deserialGxsServerMsgUpdate(data, size); default: { #ifdef RSSERIAL_DEBUG @@ -129,6 +154,13 @@ uint32_t RsGxsUpdateSerialiser::sizeGxsGrpUpdate(RsGxsGrpUpdateItem* item) return s; } +uint32_t RsGxsUpdateSerialiser::sizeGxsServerGrpUpdate(RsGxsServerGrpUpdateItem* item) +{ + uint32_t s = 8; // header size + s += 4; // time stamp + return s; +} + bool RsGxsUpdateSerialiser::serialiseGxsGrpUpdate(RsGxsGrpUpdateItem* item, void* data, uint32_t* size) { @@ -155,7 +187,7 @@ bool RsGxsUpdateSerialiser::serialiseGxsGrpUpdate(RsGxsGrpUpdateItem* item, /* skip the header */ offset += 8; - /* RsNxsSyncm */ + /* RsGxsGrpUpdateItem */ ok &= SetTlvString(data, *size, &offset, TLV_TYPE_STR_PEERID, item->peerId); @@ -178,10 +210,182 @@ bool RsGxsUpdateSerialiser::serialiseGxsGrpUpdate(RsGxsGrpUpdateItem* item, return ok; } +bool RsGxsUpdateSerialiser::serialiseGxsServerGrpUpdate(RsGxsServerGrpUpdateItem* item, + void* data, uint32_t* size) +{ +#ifdef RSSERIAL_DEBUG + std::cerr << "RsGxsUpdateSerialiser::serialiseGxsServerGrpUpdate()" << std::endl; +#endif + + uint32_t tlvsize = sizeGxsServerGrpUpdate(item); + uint32_t offset = 0; + + if(*size < tlvsize){ +#ifdef RSSERIAL_DEBUG + std::cerr << "RsGxsUpdateSerialiser::serialiseGxsServerGrpUpdate() size do not match" << std::endl; +#endif + return false; + } + + *size = tlvsize; + + bool ok = true; + + ok &= setRsItemHeader(data, tlvsize, item->PacketId(), tlvsize); + + /* skip the header */ + offset += 8; + + /* RsGxsServerGrpUpdateItem */ + + ok &= setRawUInt32(data, *size, &offset, item->grpUpdateTS); + + if(offset != tlvsize){ +#ifdef RSSERIAL_DEBUG + std::cerr << "RsGxsUpdateSerialiser::serialiseGxsServerGrpUpdate() FAIL Size Error! " << std::endl; +#endif + ok = false; + } + +#ifdef RSSERIAL_DEBUG + if (!ok) + { + std::cerr << "RsGxsUpdateSerialiser::serialiseGxsServerGrpUpdate() NOK" << std::endl; + } +#endif + + return ok; +} + RsGxsGrpUpdateItem* RsGxsUpdateSerialiser::deserialGxsGrpUpddate(void* data, uint32_t* size) { +#ifdef RSSERIAL_DEBUG + std::cerr << "RsGxsUpdateSerialiser::deserialGxsServerGrpUpdate()" << 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_GXS_GRP_UPDATE != getRsItemSubType(rstype))) + { +#ifdef RSSERIAL_DEBUG + std::cerr << "RsGxsUpdateSerialiser::deserialGxsGrpUpdate() FAIL wrong type" << std::endl; +#endif + return NULL; /* wrong type */ + } + + if (*size < rssize) /* check size */ + { +#ifdef RSSERIAL_DEBUG + std::cerr << "RsGxsUpdateSerialiser::deserialGxsGrpUpdate() FAIL wrong size" << std::endl; +#endif + return NULL; /* not enough data */ + } + + /* set the packet length */ + *size = rssize; + + bool ok = true; + + RsGxsGrpUpdateItem* item = new RsGxsGrpUpdateItem(getRsItemService(rstype)); + + /* skip the header */ + offset += 8; + + ok &= getRawUInt32(data, *size, &offset, &(item->grpUpdateTS)); + ok &= GetTlvString(data, *size, &offset, TLV_TYPE_STR_PEERID, item->peerId); + + if (offset != rssize) + { +#ifdef RSSERIAL_DEBUG + std::cerr << "RsGxsUpdateSerialiser::deserialGxxGrpUpdate() FAIL size mismatch" << std::endl; +#endif + /* error */ + delete item; + return NULL; + } + + if (!ok) + { +#ifdef RSSERIAL_DEBUG + std::cerr << "RsGxsUpdateSerialiser::deserialGxsGrpUpdate() NOK" << std::endl; +#endif + delete item; + return NULL; + } + + return item; +} + +RsGxsServerGrpUpdateItem* RsGxsUpdateSerialiser::deserialGxsServerGrpUpddate(void* data, + uint32_t* size) +{ +#ifdef RSSERIAL_DEBUG + std::cerr << "RsGxsUpdateSerialiser::deserialGxsServerGrpUpdate()" << 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_GXS_SERVER_GRP_UPDATE != getRsItemSubType(rstype))) + { +#ifdef RSSERIAL_DEBUG + std::cerr << "RsGxsUpdateSerialiser::deserialGxsServerGrpUpdate() FAIL wrong type" << std::endl; +#endif + return NULL; /* wrong type */ + } + + if (*size < rssize) /* check size */ + { +#ifdef RSSERIAL_DEBUG + std::cerr << "RsGxsUpdateSerialiser::deserialGxsServerGrpUpdate() FAIL wrong size" << std::endl; +#endif + return NULL; /* not enough data */ + } + + /* set the packet length */ + *size = rssize; + + bool ok = true; + + RsGxsServerGrpUpdateItem* item = new RsGxsServerGrpUpdateItem(getRsItemService(rstype)); + + /* skip the header */ + offset += 8; + + ok &= getRawUInt32(data, *size, &offset, &(item->grpUpdateTS)); + + if (offset != rssize) + { +#ifdef RSSERIAL_DEBUG + std::cerr << "RsGxsUpdateSerialiser::deserialGxsServerGrpUpdate() FAIL size mismatch" << std::endl; +#endif + /* error */ + delete item; + return NULL; + } + + if (!ok) + { +#ifdef RSSERIAL_DEBUG + std::cerr << "RsGxsUpdateSerialiser::deserialGxsServerGrpUpdate() NOK" << std::endl; +#endif + delete item; + return NULL; + } + + return item; } uint32_t RsGxsUpdateSerialiser::sizeGxsMsgUpdate(RsGxsMsgUpdateItem* item) @@ -203,6 +407,15 @@ uint32_t RsGxsUpdateSerialiser::sizeGxsMsgUpdate(RsGxsMsgUpdateItem* item) return s; } +uint32_t RsGxsUpdateSerialiser::sizeGxsServerMsgUpdate(RsGxsServerMsgUpdateItem* item) +{ + uint32_t s = 8; // header size + s += GetTlvStringSize(item->grpId); + s += 4; // grp TS + + return s; +} + bool RsGxsUpdateSerialiser::serialiseGxsMsgUpdate(RsGxsMsgUpdateItem* item, void* data, uint32_t* size) { @@ -229,7 +442,7 @@ bool RsGxsUpdateSerialiser::serialiseGxsMsgUpdate(RsGxsMsgUpdateItem* item, /* skip the header */ offset += 8; - /* RsNxsSyncm */ + /* RsGxsMsgUpdateItem */ ok &= SetTlvString(data, *size, &offset, TLV_TYPE_STR_PEERID, item->peerId); @@ -263,6 +476,55 @@ bool RsGxsUpdateSerialiser::serialiseGxsMsgUpdate(RsGxsMsgUpdateItem* item, return ok; } +bool RsGxsUpdateSerialiser::serialiseGxsServerMsgUpdate(RsGxsServerMsgUpdateItem* item, + void* data, uint32_t* size) +{ +#ifdef RSSERIAL_DEBUG + std::cerr << "RsGxsUpdateSerialiser::serialiseGxsServerMsgUpdate()" << std::endl; +#endif + + uint32_t tlvsize = sizeGxsServerMsgUpdate(item); + uint32_t offset = 0; + + if(*size < tlvsize){ +#ifdef RSSERIAL_DEBUG + std::cerr << "RsGxsUpdateSerialiser::serialiseGxsServerMsgUpdate() size do not match" << std::endl; +#endif + return false; + } + + *size = tlvsize; + + bool ok = true; + + ok &= setRsItemHeader(data, tlvsize, item->PacketId(), tlvsize); + + /* skip the header */ + offset += 8; + + /* RsNxsSyncm */ + + + ok &= SetTlvString(data, *size, &offset, TLV_TYPE_STR_GROUPID, item->grpId); + ok &= setRawUInt32(data, *size, &offset, item->msgUpdateTS); + + if(offset != tlvsize){ +#ifdef RSSERIAL_DEBUG + std::cerr << "RsGxsUpdateSerialiser::serialiseGxsServerMsgUpdate() FAIL Size Error! " << std::endl; +#endif + ok = false; + } + +#ifdef RSSERIAL_DEBUG + if (!ok) + { + std::cerr << "RsGxsUpdateSerialiser::serialiseGxsServerMsgUpdate() NOK" << std::endl; + } +#endif + + return ok; +} + RsGxsMsgUpdateItem* RsGxsUpdateSerialiser::deserialGxsMsgUpdate(void* data, uint32_t* size) { @@ -278,7 +540,7 @@ RsGxsMsgUpdateItem* RsGxsUpdateSerialiser::deserialGxsMsgUpdate(void* data, if ((RS_PKT_VERSION_SERVICE != getRsItemVersion(rstype)) || (SERVICE_TYPE != getRsItemService(rstype)) || - (RS_PKT_SUBTYPE_NXS_SYNC_MSG != getRsItemSubType(rstype))) + (RS_PKT_SUBTYPE_GXS_MSG_UPDATE != getRsItemSubType(rstype))) { #ifdef RSSERIAL_DEBUG std::cerr << "RsGxsUpdateSerialiser::deserialGxsMsgUpdate() FAIL wrong type" << std::endl; @@ -304,10 +566,10 @@ RsGxsMsgUpdateItem* RsGxsUpdateSerialiser::deserialGxsMsgUpdate(void* data, /* skip the header */ offset += 8; - ok &= GetTlvString(data, *size, &offset, TLV_TYPE_STR_HASH_SHA1, item->peerId); + ok &= GetTlvString(data, *size, &offset, TLV_TYPE_STR_PEERID, item->peerId); uint32_t numUpdateItems; ok &= getRawUInt32(data, *size, &offset, &(numUpdateItems)); - std::map& msgUpdateItem = item->grpUpdateTS; + std::map& msgUpdateItem = item->msgUpdateTS; std::string grpId; uint32_t updateTS; for(uint32_t i; i < numUpdateItems; i++) @@ -346,3 +608,70 @@ RsGxsMsgUpdateItem* RsGxsUpdateSerialiser::deserialGxsMsgUpdate(void* data, return item; } + +RsGxsServerMsgUpdateItem* RsGxsUpdateSerialiser::deserialGxsServerMsgUpdate(void* data, + uint32_t* size) +{ +#ifdef RSSERIAL_DEBUG + std::cerr << "RsGxsUpdateSerialiser::deserialGxsServerMsgUpdate()" << 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_GXS_SERVER_MSG_UPDATE != getRsItemSubType(rstype))) + { +#ifdef RSSERIAL_DEBUG + std::cerr << "RsGxsUpdateSerialiser::deserialGxsServerMsgUpdate() FAIL wrong type" << std::endl; +#endif + return NULL; /* wrong type */ + } + + if (*size < rssize) /* check size */ + { +#ifdef RSSERIAL_DEBUG + std::cerr << "RsGxsUpdateSerialiser::deserialGxsServerMsgUpdate() FAIL wrong size" << std::endl; +#endif + return NULL; /* not enough data */ + } + + /* set the packet length */ + *size = rssize; + + bool ok = true; + + RsGxsServerMsgUpdateItem* item = new RsGxsServerMsgUpdateItem(getRsItemService(rstype)); + + /* skip the header */ + offset += 8; + + ok &= GetTlvString(data, *size, &offset, TLV_TYPE_STR_GROUPID, item->grpId); + ok &= getRawUInt32(data, *size, &offset, &(item->msgUpdateTS)); + + if (offset != rssize) + { +#ifdef RSSERIAL_DEBUG + std::cerr << "RsGxsUpdateSerialiser::deserialGxsServerMsgUpdate() FAIL size mismatch" << std::endl; +#endif + /* error */ + delete item; + return NULL; + } + + if (!ok) + { +#ifdef RSSERIAL_DEBUG + std::cerr << "RsGxsUpdateSerialiser::deserialGxsServerMsgUpdate() NOK" << std::endl; +#endif + delete item; + return NULL; + } + + return item; +} + diff --git a/libretroshare/src/serialiser/rsgxsupdateitems.h b/libretroshare/src/serialiser/rsgxsupdateitems.h index 4b16bcb1b..bb6e3f9bb 100644 --- a/libretroshare/src/serialiser/rsgxsupdateitems.h +++ b/libretroshare/src/serialiser/rsgxsupdateitems.h @@ -37,13 +37,17 @@ #include "gxs/rsgxsdata.h" -const uint8_t RS_PKT_SUBTYPE_GXS_GRP_UPDATE = 0x0001; -const uint8_t RS_PKT_SUBTYPE_GXS_MSG_UPDATE = 0x0002; +const uint8_t RS_PKT_SUBTYPE_GXS_GRP_UPDATE = 0x0001; +const uint8_t RS_PKT_SUBTYPE_GXS_MSG_UPDATE = 0x0002; +const uint8_t RS_PKT_SUBTYPE_GXS_SERVER_GRP_UPDATE = 0x0004; +const uint8_t RS_PKT_SUBTYPE_GXS_SERVER_MSG_UPDATE = 0x0008; class RsGxsGrpUpdateItem : public RsItem { public: - RsGxsGrpUpdateItem(); - virtual ~RsGxsGrpUpdateItem(); + RsGxsGrpUpdateItem(uint16_t servType) : RsItem(RS_PKT_VERSION_SERVICE, servType, + RS_PKT_SUBTYPE_GXS_GRP_UPDATE) + {} + virtual ~RsGxsGrpUpdateItem() {} virtual void clear(); virtual std::ostream &print(std::ostream &out, uint16_t indent); @@ -52,10 +56,24 @@ public: uint32_t grpUpdateTS; }; +class RsGxsServerGrpUpdateItem : public RsItem { +public: + RsGxsServerGrpUpdateItem(uint16_t servType) : RsItem(RS_PKT_VERSION_SERVICE, servType, + RS_PKT_SUBTYPE_GXS_SERVER_GRP_UPDATE) + {} + virtual ~RsGxsServerGrpUpdateItem(); + + virtual void clear(); + virtual std::ostream &print(std::ostream &out, uint16_t indent); + + uint32_t grpUpdateTS; +}; + class RsGxsMsgUpdateItem : public RsItem { public: - RsGxsMsgUpdateItem(); + RsGxsMsgUpdateItem(uint16_t servType) : RsItem(RS_PKT_VERSION_SERVICE, servType, RS_PKT_SUBTYPE_GXS_MSG_UPDATE) + {} virtual ~RsGxsMsgUpdateItem(); virtual void clear(); @@ -65,6 +83,20 @@ public: std::map msgUpdateTS; }; +class RsGxsServerMsgUpdateItem : public RsItem +{ +public: + RsGxsServerMsgUpdateItem(uint16_t servType) : RsItem(RS_PKT_VERSION_SERVICE, + servType, RS_PKT_SUBTYPE_GXS_SERVER_MSG_UPDATE) + {} + virtual ~RsGxsServerMsgUpdateItem(); + + virtual void clear(); + virtual std::ostream &print(std::ostream &out, uint16_t indent); + + std::string grpId; + uint32_t msgUpdateTS; // the last time this group received a new msg +}; class RsGxsUpdateSerialiser : public RsSerialType @@ -89,12 +121,24 @@ private: virtual bool serialiseGxsGrpUpdate(RsGxsGrpUpdateItem *item, void *data, uint32_t *size); virtual RsGxsGrpUpdateItem* deserialGxsGrpUpddate(void *data, uint32_t *size); - /* for RS_PKT_SUBTYPE_GXS_ */ + /* for RS_PKT_SUBTYPE_GRP_SERVER_UPDATE_ITEM */ + + virtual uint32_t sizeGxsServerGrpUpdate(RsGxsServerGrpUpdateItem* item); + virtual bool serialiseGxsServerGrpUpdate(RsGxsServerGrpUpdateItem *item, void *data, uint32_t *size); + virtual RsGxsServerGrpUpdateItem* deserialGxsServerGrpUpddate(void *data, uint32_t *size); + + /* for RS_PKT_SUBTYPE_GXS_MSG_UPDATE_ITEM */ virtual uint32_t sizeGxsMsgUpdate(RsGxsMsgUpdateItem* item); virtual bool serialiseGxsMsgUpdate(RsGxsMsgUpdateItem *item, void *data, uint32_t *size); virtual RsGxsMsgUpdateItem* deserialGxsMsgUpdate(void *data, uint32_t *size); + /* for RS_PKT_SUBTYPE_GXS_SERVER_UPDATE_ITEM */ + + virtual uint32_t sizeGxsServerMsgUpdate(RsGxsServerMsgUpdateItem* item); + virtual bool serialiseGxsServerMsgUpdate(RsGxsServerMsgUpdateItem *item, void *data, uint32_t *size); + virtual RsGxsServerMsgUpdateItem* deserialGxsServerMsgUpdate(void *data, uint32_t *size); + private: const uint16_t SERVICE_TYPE; diff --git a/libretroshare/src/serialiser/rsnxsitems.cc b/libretroshare/src/serialiser/rsnxsitems.cc index df531ffca..108dba1d0 100644 --- a/libretroshare/src/serialiser/rsnxsitems.cc +++ b/libretroshare/src/serialiser/rsnxsitems.cc @@ -354,8 +354,9 @@ bool RsNxsSerialiser::serialiseNxsSyncGrp(RsNxsSyncGrp *item, void *data, uint32 ok &= setRawUInt32(data, *size, &offset, item->transactionNumber); ok &= setRawUInt8(data, *size, &offset, item->flag); - ok &= setRawUInt32(data, *size, &offset, item->syncAge); + ok &= setRawUInt32(data, *size, &offset, item->createdSince); ok &= SetTlvString(data, *size, &offset, TLV_TYPE_STR_HASH_SHA1, item->syncHash); + ok &= setRawUInt32(data, *size, &offset, item->updateTS); if(offset != tlvsize){ #ifdef RSSERIAL_DEBUG @@ -403,7 +404,7 @@ bool RsNxsSerialiser::serialiseNxsTrans(RsNxsTransac *item, void *data, uint32_t ok &= setRawUInt32(data, *size, &offset, item->transactionNumber); ok &= setRawUInt16(data, *size, &offset, item->transactFlag); ok &= setRawUInt32(data, *size, &offset, item->nItems); - ok &= setRawUInt32(data, *size, &offset, item->timestamp); + ok &= setRawUInt32(data, *size, &offset, item->updateTS); @@ -501,7 +502,7 @@ bool RsNxsSerialiser::serialiseNxsSyncMsg(RsNxsSyncMsg *item, void *data, uint32 ok &= setRawUInt32(data, *size, &offset, item->transactionNumber); ok &= setRawUInt8(data, *size, &offset, item->flag); - ok &= setRawUInt32(data, *size, &offset, item->syncAge); + ok &= setRawUInt32(data, *size, &offset, item->createdSince); ok &= SetTlvString(data, *size, &offset, TLV_TYPE_STR_HASH_SHA1, item->syncHash); ok &= SetTlvString(data, *size, &offset, TLV_TYPE_STR_GROUPID, item->grpId); @@ -710,8 +711,9 @@ RsNxsSyncGrp* RsNxsSerialiser::deserialNxsSyncGrp(void *data, uint32_t *size){ ok &= getRawUInt32(data, *size, &offset, &(item->transactionNumber)); ok &= getRawUInt8(data, *size, &offset, &(item->flag)); - ok &= getRawUInt32(data, *size, &offset, &(item->syncAge)); + ok &= getRawUInt32(data, *size, &offset, &(item->createdSince)); ok &= GetTlvString(data, *size, &offset, TLV_TYPE_STR_HASH_SHA1, item->syncHash); + ok &= getRawUInt32(data, *size, &offset, &(item->updateTS)); if (offset != rssize) { @@ -846,7 +848,7 @@ RsNxsTransac* RsNxsSerialiser::deserialNxsTrans(void *data, uint32_t *size){ ok &= getRawUInt32(data, *size, &offset, &(item->transactionNumber)); ok &= getRawUInt16(data, *size, &offset, &(item->transactFlag)); ok &= getRawUInt32(data, *size, &offset, &(item->nItems)); - ok &= getRawUInt32(data, *size, &offset, &(item->timestamp)); + ok &= getRawUInt32(data, *size, &offset, &(item->updateTS)); if (offset != rssize) { @@ -984,9 +986,10 @@ RsNxsSyncMsg* RsNxsSerialiser::deserialNxsSyncMsg(void *data, uint32_t *size) ok &= getRawUInt32(data, *size, &offset, &(item->transactionNumber)); ok &= getRawUInt8(data, *size, &offset, &(item->flag)); - ok &= getRawUInt32(data, *size, &offset, &(item->syncAge)); + ok &= getRawUInt32(data, *size, &offset, &(item->createdSince)); ok &= GetTlvString(data, *size, &offset, TLV_TYPE_STR_HASH_SHA1, item->syncHash); ok &= GetTlvString(data, *size, &offset, TLV_TYPE_STR_GROUPID, item->grpId); + ok &= getRawUInt32(data, *size, &offset, &(item->updateTS)); if (offset != rssize) { @@ -1057,6 +1060,7 @@ uint32_t RsNxsSerialiser::sizeNxsSyncGrp(RsNxsSyncGrp *item) s += 1; // flag s += 4; // sync age s += GetTlvStringSize(item->syncHash); + s += 4; // updateTS return s; } @@ -1086,6 +1090,7 @@ uint32_t RsNxsSerialiser::sizeNxsSyncMsg(RsNxsSyncMsg *item) s += 4; // age s += GetTlvStringSize(item->grpId); s += GetTlvStringSize(item->syncHash); + s += 4; // updateTS return s; } @@ -1111,7 +1116,7 @@ uint32_t RsNxsSerialiser::sizeNxsTrans(RsNxsTransac *item){ s += 4; // transaction number s += 2; // flag s += 4; // nMsgs - s += 4; // timeout + s += 4; // updateTS return s; } @@ -1141,16 +1146,18 @@ void RsNxsGrp::clear() void RsNxsSyncGrp::clear() { flag = 0; - syncAge = 0; + createdSince = 0; syncHash.clear(); + updateTS = 0; } void RsNxsSyncMsg::clear() { grpId.clear(); flag = 0; - syncAge = 0; + createdSince = 0; syncHash.clear(); + updateTS = 0; } void RsNxsSyncGrpItem::clear() @@ -1172,6 +1179,7 @@ void RsNxsSyncMsgItem::clear() void RsNxsTransac::clear(){ transactFlag = 0; nItems = 0; + updateTS = 0; timestamp = 0; transactionNumber = 0; } @@ -1185,10 +1193,11 @@ std::ostream& RsNxsSyncGrp::print(std::ostream &out, uint16_t indent) printIndent(out , int_Indent); out << "Hash: " << syncHash << std::endl; printIndent(out , int_Indent); - out << "Sync Age: " << syncAge << std::endl; + out << "Sync Age: " << createdSince << std::endl; printIndent(out , int_Indent); out << "flag" << flag << std::endl; - + printIndent(out , int_Indent); + out << "updateTS" << updateTS << std::endl; printRsItemEnd(out ,"RsNxsSyncGrp", indent); @@ -1217,11 +1226,13 @@ std::ostream& RsNxsSyncMsg::print(std::ostream &out, uint16_t indent) printIndent(out , int_Indent); out << "GrpId: " << grpId << std::endl; printIndent(out , int_Indent); - out << "syncAge: " << syncAge << std::endl; + out << "createdSince: " << createdSince << std::endl; printIndent(out , int_Indent); out << "syncHash: " << syncHash << std::endl; printIndent(out , int_Indent); out << "flag: " << flag << std::endl; + printIndent(out , int_Indent); + out << "updateTS: " << updateTS << std::endl; printRsItemEnd(out, "RsNxsSyncMsg", indent); return out; @@ -1316,6 +1327,8 @@ std::ostream& RsNxsTransac::print(std::ostream &out, uint16_t indent){ printIndent(out , int_Indent); out << "timeout: " << timestamp << std::endl; printIndent(out , int_Indent); + out << "updateTS: " << updateTS << std::endl; + printIndent(out , int_Indent); out << "transactionNumber: " << transactionNumber << std::endl; printIndent(out , int_Indent); diff --git a/libretroshare/src/serialiser/rsnxsitems.h b/libretroshare/src/serialiser/rsnxsitems.h index c15b0ce44..b7a6c2fec 100644 --- a/libretroshare/src/serialiser/rsnxsitems.h +++ b/libretroshare/src/serialiser/rsnxsitems.h @@ -100,7 +100,8 @@ public: virtual std::ostream &print(std::ostream &out, uint16_t indent); uint8_t flag; // advises whether to use sync hash - uint32_t syncAge; // how far back to sync data + uint32_t createdSince; // how far back to sync data + uint32_t updateTS; // time of last group update std::string syncHash; // use to determine if changes that have occured since last hash @@ -146,6 +147,9 @@ public: uint16_t transactFlag; uint32_t nItems; + uint32_t updateTS; + + // not serialised uint32_t timestamp; }; @@ -235,7 +239,8 @@ public: std::string grpId; uint8_t flag; - uint32_t syncAge; + uint32_t createdSince; + uint32_t updateTS; // time of last update std::string syncHash; }; From 6cbb3a65f8918b42e2983b73c4d3f574a7073709 Mon Sep 17 00:00:00 2001 From: chrisparker126 Date: Sun, 17 Nov 2013 23:15:39 +0000 Subject: [PATCH 54/83] fixed linker issue, and bad initialisation of pointer bug git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.5-gxs_finale@6904 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/gxs/rsgxsnetservice.cc | 5 +++- .../src/serialiser/rsgxsupdateitems.cc | 27 +++++++++++++++++++ .../src/serialiser/rsgxsupdateitems.h | 6 ++--- 3 files changed, 34 insertions(+), 4 deletions(-) diff --git a/libretroshare/src/gxs/rsgxsnetservice.cc b/libretroshare/src/gxs/rsgxsnetservice.cc index 3485d2863..877d437b4 100644 --- a/libretroshare/src/gxs/rsgxsnetservice.cc +++ b/libretroshare/src/gxs/rsgxsnetservice.cc @@ -45,7 +45,7 @@ RsGxsNetService::RsGxsNetService(uint16_t servType, RsGeneralDataService *gds, : p3Config(servType), p3ThreadedService(servType), mTransactionTimeOut(TRANSAC_TIMEOUT), mServType(servType), mDataStore(gds), mTransactionN(0), mObserver(nxsObs), mNxsMutex("RsGxsNetService"), mNetMgr(netMgr), mSYNC_PERIOD(SYNC_PERIOD), - mSyncTs(0), mReputations(reputations), mCircles(circles), mGrpAutoSync(grpAutoSync) + mSyncTs(0), mReputations(reputations), mCircles(circles), mGrpAutoSync(grpAutoSync), mGrpServerUpdateItem(NULL) { addSerialType(new RsNxsSerialiser(mServType)); @@ -1972,8 +1972,11 @@ void RsGxsNetService::handleRecvSyncGroup(RsNxsSyncGrp* item) std::string peer = item->PeerId(); // don't sync if you have no new updates for this peer + if(mGrpServerUpdateItem) + { if(item->updateTS >= mGrpServerUpdateItem->grpUpdateTS && item->updateTS != 0) return; + } std::map grp; mDataStore->retrieveGxsGrpMetaData(grp); diff --git a/libretroshare/src/serialiser/rsgxsupdateitems.cc b/libretroshare/src/serialiser/rsgxsupdateitems.cc index fdccdbeae..60f637f06 100644 --- a/libretroshare/src/serialiser/rsgxsupdateitems.cc +++ b/libretroshare/src/serialiser/rsgxsupdateitems.cc @@ -51,8 +51,35 @@ void RsGxsMsgUpdateItem::clear() std::ostream& RsGxsMsgUpdateItem::print(std::ostream& out, uint16_t indent) { + } + + +void RsGxsServerMsgUpdateItem::clear() +{ + msgUpdateTS = 0; + grpId.clear(); +} + +std::ostream& RsGxsServerMsgUpdateItem::print(std::ostream& out, uint16_t indent) +{ + +} + + +void RsGxsServerGrpUpdateItem::clear() +{ + grpUpdateTS = 0; +} + +std::ostream& RsGxsServerGrpUpdateItem::print(std::ostream& out, uint16_t indent) +{ + +} + + + uint32_t RsGxsUpdateSerialiser::size(RsItem* item) { RsGxsMsgUpdateItem* mui = NULL; diff --git a/libretroshare/src/serialiser/rsgxsupdateitems.h b/libretroshare/src/serialiser/rsgxsupdateitems.h index bb6e3f9bb..763c51516 100644 --- a/libretroshare/src/serialiser/rsgxsupdateitems.h +++ b/libretroshare/src/serialiser/rsgxsupdateitems.h @@ -61,7 +61,7 @@ public: RsGxsServerGrpUpdateItem(uint16_t servType) : RsItem(RS_PKT_VERSION_SERVICE, servType, RS_PKT_SUBTYPE_GXS_SERVER_GRP_UPDATE) {} - virtual ~RsGxsServerGrpUpdateItem(); + virtual ~RsGxsServerGrpUpdateItem() {} virtual void clear(); virtual std::ostream &print(std::ostream &out, uint16_t indent); @@ -74,7 +74,7 @@ class RsGxsMsgUpdateItem : public RsItem public: RsGxsMsgUpdateItem(uint16_t servType) : RsItem(RS_PKT_VERSION_SERVICE, servType, RS_PKT_SUBTYPE_GXS_MSG_UPDATE) {} - virtual ~RsGxsMsgUpdateItem(); + virtual ~RsGxsMsgUpdateItem() {} virtual void clear(); virtual std::ostream &print(std::ostream &out, uint16_t indent); @@ -89,7 +89,7 @@ public: RsGxsServerMsgUpdateItem(uint16_t servType) : RsItem(RS_PKT_VERSION_SERVICE, servType, RS_PKT_SUBTYPE_GXS_SERVER_MSG_UPDATE) {} - virtual ~RsGxsServerMsgUpdateItem(); + virtual ~RsGxsServerMsgUpdateItem() {} virtual void clear(); virtual std::ostream &print(std::ostream &out, uint16_t indent); From 24839ee2373e09ab25e29f8f7a2f9500621db493 Mon Sep 17 00:00:00 2001 From: chrisparker126 Date: Sat, 23 Nov 2013 23:39:55 +0000 Subject: [PATCH 55/83] decided to use polling and a database trigger to maintain consistentency of last group post for database sync - db reset done, you will lose your current gxs data git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.5-gxs_finale@6906 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/gxs/rsdataservice.cc | 22 +++++- libretroshare/src/gxs/rsgenexchange.cc | 3 + libretroshare/src/gxs/rsgxsdata.cc | 2 + libretroshare/src/gxs/rsgxsdata.h | 6 +- libretroshare/src/gxs/rsgxsnetservice.cc | 94 +++++++++++++++--------- libretroshare/src/gxs/rsgxsnetservice.h | 2 + libretroshare/src/rsserver/rsinit.cc | 2 +- 7 files changed, 92 insertions(+), 39 deletions(-) diff --git a/libretroshare/src/gxs/rsdataservice.cc b/libretroshare/src/gxs/rsdataservice.cc index c0f7082a7..132e366bd 100644 --- a/libretroshare/src/gxs/rsdataservice.cc +++ b/libretroshare/src/gxs/rsdataservice.cc @@ -34,6 +34,8 @@ #define MSG_TABLE_NAME std::string("MESSAGES") #define GRP_TABLE_NAME std::string("GROUPS") +#define GRP_LAST_POST_UPDATE_TRIGGER std::string("LAST_POST_UPDATE") + // generic #define KEY_NXS_FILE std::string("nxsFile") @@ -48,6 +50,7 @@ #define KEY_NXS_META std::string("meta") #define KEY_NXS_SERV_STRING std::string("serv_str") #define KEY_NXS_HASH std::string("hash") +#define KEY_RECV_TS std::string("recv_time_stamp") // grp table columns @@ -111,6 +114,7 @@ #define COL_GRP_INTERN_CIRCLE 18 #define COL_GRP_ORIGINATOR 19 #define COL_GRP_AUTHEN_FLAGS 20 +#define COL_GRP_RECV_TS 21 // msg col numbers @@ -122,6 +126,7 @@ #define COL_THREAD_ID 11 #define COL_MSG_NAME 12 #define COL_MSG_SERV_STRING 13 +#define COL_MSG_RECV_TS 14 // generic meta shared col numbers #define COL_GRP_ID 0 @@ -154,7 +159,7 @@ RsDataService::RsDataService(const std::string &serviceDir, const std::string &d msgMetaColumns.push_back(KEY_SIGN_SET); msgMetaColumns.push_back(KEY_NXS_IDENTITY); msgMetaColumns.push_back(KEY_NXS_HASH); msgMetaColumns.push_back(KEY_MSG_ID); msgMetaColumns.push_back(KEY_ORIG_MSG_ID); msgMetaColumns.push_back(KEY_MSG_STATUS); msgMetaColumns.push_back(KEY_CHILD_TS); msgMetaColumns.push_back(KEY_MSG_PARENT_ID); msgMetaColumns.push_back(KEY_MSG_THREAD_ID); - msgMetaColumns.push_back(KEY_MSG_NAME); msgMetaColumns.push_back(KEY_NXS_SERV_STRING); + msgMetaColumns.push_back(KEY_MSG_NAME); msgMetaColumns.push_back(KEY_NXS_SERV_STRING); msgMetaColumns.push_back(KEY_RECV_TS); // for retrieving actual data msgColumns.push_back(KEY_GRP_ID); msgColumns.push_back(KEY_NXS_FILE); msgColumns.push_back(KEY_NXS_FILE_OFFSET); @@ -168,7 +173,7 @@ RsDataService::RsDataService(const std::string &serviceDir, const std::string &d grpMetaColumns.push_back(KEY_GRP_LAST_POST); grpMetaColumns.push_back(KEY_ORIG_GRP_ID); grpMetaColumns.push_back(KEY_NXS_SERV_STRING); grpMetaColumns.push_back(KEY_GRP_SIGN_FLAGS); grpMetaColumns.push_back(KEY_GRP_CIRCLE_ID); grpMetaColumns.push_back(KEY_GRP_CIRCLE_TYPE); grpMetaColumns.push_back(KEY_GRP_INTERNAL_CIRCLE); grpMetaColumns.push_back(KEY_GRP_ORIGINATOR); - grpMetaColumns.push_back(KEY_GRP_AUTHEN_FLAGS); + grpMetaColumns.push_back(KEY_GRP_AUTHEN_FLAGS); grpMetaColumns.push_back(KEY_RECV_TS); // for retrieving actual grp data grpColumns.push_back(KEY_GRP_ID); grpColumns.push_back(KEY_NXS_FILE); grpColumns.push_back(KEY_NXS_FILE_OFFSET); @@ -212,6 +217,7 @@ void RsDataService::initialise(){ KEY_MSG_NAME + " TEXT," + KEY_NXS_SERV_STRING + " TEXT," + KEY_NXS_HASH + " TEXT," + + KEY_RECV_TS + " INT," + KEY_NXS_FILE_LEN + " INT);"); // create table for grp data @@ -240,8 +246,15 @@ void RsDataService::initialise(){ KEY_GRP_INTERNAL_CIRCLE + " TEXT," + KEY_GRP_ORIGINATOR + " TEXT," + KEY_NXS_HASH + " TEXT," + + KEY_RECV_TS + " INT," + KEY_SIGN_SET + " BLOB);"); + mDb->execSQL("CREATE TRIGGER " + GRP_LAST_POST_UPDATE_TRIGGER + + "UPDATE OF " + KEY_RECV_TS + " ON " + MSG_TABLE_NAME + + std::string("BEGIN ") + + "UPDATE " + GRP_TABLE_NAME + "SET " + KEY_GRP_LAST_POST + "= new." + + KEY_RECV_TS + ";" + + std::string("END;")); } RsGxsGrpMetaData* RsDataService::locked_getGrpMeta(RetroCursor &c) @@ -293,6 +306,7 @@ RsGxsGrpMetaData* RsDataService::locked_getGrpMeta(RetroCursor &c) c.getString(COL_GRP_INTERN_CIRCLE, grpMeta->mInternalCircle); c.getString(COL_GRP_ORIGINATOR, grpMeta->mOriginator); grpMeta->mAuthenFlags = c.getInt32(COL_GRP_AUTHEN_FLAGS); + grpMeta->mRecvTS = c.getInt32(COL_GRP_RECV_TS); if(ok) @@ -379,6 +393,7 @@ RsGxsMsgMetaData* RsDataService::locked_getMsgMeta(RetroCursor &c) c.getString(COL_MSG_NAME, msgMeta->mMsgName); c.getString(COL_MSG_SERV_STRING, msgMeta->mServiceString); c.getString(COL_HASH, msgMeta->mHash); + msgMeta->recvTS = c.getInt32(COL_MSG_RECV_TS); offset = 0; data = (char*)c.getData(COL_SIGN_SET, data_len); @@ -491,6 +506,7 @@ int RsDataService::storeMessage(std::map &msg) cv.put(KEY_GRP_ID, msgMetaPtr->mGroupId); cv.put(KEY_NXS_SERV_STRING, msgMetaPtr->mServiceString); cv.put(KEY_NXS_HASH, msgMetaPtr->mHash); + cv.put(KEY_RECV_TS, (int32_t)msgMetaPtr->recvTS); char signSetData[msgMetaPtr->signSet.TlvSize()]; @@ -598,6 +614,7 @@ int RsDataService::storeGroup(std::map &grp) cv.put(KEY_GRP_ORIGINATOR, grpMetaPtr->mOriginator); cv.put(KEY_GRP_AUTHEN_FLAGS, (int32_t)grpMetaPtr->mAuthenFlags); cv.put(KEY_NXS_HASH, grpMetaPtr->mHash); + cv.put(KEY_RECV_TS, (int32_t)grpMetaPtr->mRecvTS); if(! (grpMetaPtr->mAuthorId.empty()) ){ cv.put(KEY_NXS_IDENTITY, grpMetaPtr->mAuthorId); @@ -1117,6 +1134,7 @@ int RsDataService::resetDataStore() mDb->execSQL("DROP TABLE " + MSG_TABLE_NAME); mDb->execSQL("DROP TABLE " + GRP_TABLE_NAME); + mDb->execSQL("DROP TRIGGER " + GRP_LAST_POST_UPDATE_TRIGGER); } // recreate database diff --git a/libretroshare/src/gxs/rsgenexchange.cc b/libretroshare/src/gxs/rsgenexchange.cc index ffa2a3000..316832b90 100644 --- a/libretroshare/src/gxs/rsgenexchange.cc +++ b/libretroshare/src/gxs/rsgenexchange.cc @@ -1789,6 +1789,7 @@ void RsGenExchange::publishMsgs() msg->metaData->mMsgStatus = GXS_SERV::GXS_MSG_STATUS_UNPROCESSED | GXS_SERV::GXS_MSG_STATUS_UNREAD; msgId = msg->msgId; grpId = msg->grpId; + msg->metaData->recvTS = time(NULL); computeHash(msg->msg, msg->metaData->mHash); mDataAccess->addMsgData(msg); msgChangeMap[grpId].push_back(msgId); @@ -2079,6 +2080,7 @@ void RsGenExchange::publishGrps() { grpId = grp->grpId; computeHash(grp->grp, grp->metaData->mHash); + grp->metaData->mRecvTS = time(NULL); if(ggps.mIsUpdate) mDataAccess->updateGroupData(grp); @@ -2407,6 +2409,7 @@ void RsGenExchange::processRecvdGroups() // now check if group already existss if(std::find(existingGrpIds.begin(), existingGrpIds.end(), grp->grpId) == existingGrpIds.end()) { + meta->mRecvTS = time(NULL); if(meta->mCircleType == GXS_CIRCLE_TYPE_YOUREYESONLY) meta->mOriginator = grp->PeerId(); diff --git a/libretroshare/src/gxs/rsgxsdata.cc b/libretroshare/src/gxs/rsgxsdata.cc index fbccd8af2..5de64b35d 100644 --- a/libretroshare/src/gxs/rsgxsdata.cc +++ b/libretroshare/src/gxs/rsgxsdata.cc @@ -74,6 +74,7 @@ void RsGxsGrpMetaData::clear(){ mOriginator.clear(); mCircleType = 0; mAuthenFlags = 0; + mRecvTS = 0; } @@ -196,6 +197,7 @@ void RsGxsMsgMetaData::clear() mMsgFlags = 0; mMsgStatus = 0; mChildTs = 0; + recvTS = 0; } bool RsGxsMsgMetaData::serialise(void *data, uint32_t *size) diff --git a/libretroshare/src/gxs/rsgxsdata.h b/libretroshare/src/gxs/rsgxsdata.h index 9a94cc8a0..5c17a5cd4 100644 --- a/libretroshare/src/gxs/rsgxsdata.h +++ b/libretroshare/src/gxs/rsgxsdata.h @@ -70,17 +70,16 @@ public: uint32_t mPop; // HOW DO WE DO THIS NOW. uint32_t mMsgCount; // ??? - time_t mLastPost; // ??? + uint32_t mLastPost; // ??? uint32_t mGroupStatus; + uint32_t mRecvTS; std::string mOriginator; std::string mInternalCircle; std::string mHash; }; - - class RsGxsMsgMetaData { public: @@ -114,6 +113,7 @@ public: uint32_t mMsgStatus; time_t mChildTs; + uint32_t recvTS; std::string mHash; bool validated; diff --git a/libretroshare/src/gxs/rsgxsnetservice.cc b/libretroshare/src/gxs/rsgxsnetservice.cc index 877d437b4..1ec276391 100644 --- a/libretroshare/src/gxs/rsgxsnetservice.cc +++ b/libretroshare/src/gxs/rsgxsnetservice.cc @@ -877,6 +877,8 @@ void RsGxsNetService::run(){ Sleep((int) (timeDelta * 1000)); #endif + updateServerSyncTS(); + // process active transactions processTransactions(); @@ -891,6 +893,49 @@ void RsGxsNetService::run(){ } } +void RsGxsNetService::updateServerSyncTS() +{ + RsStackMutex stack(mNxsMutex); + + std::map gxsMap; + + // retrieve all grps and update TS + mDataStore->retrieveGxsGrpMetaData(gxsMap); + std::map::iterator mit = gxsMap.begin(); + + // as a grp list server also note this is the latest item you have + if(mGrpServerUpdateItem == NULL) + { + mGrpServerUpdateItem = new RsGxsServerGrpUpdateItem(mServType); + } + + for(; mit != gxsMap.end(); mit++) + { + const RsGxsGroupId& grpId = mit->first; + RsGxsGrpMetaData* grpMeta = mit->second; + ServerMsgMap::iterator mapIT = mServerMsgUpdateMap.find(grpId); + RsGxsServerMsgUpdateItem* msui = NULL; + + if(mapIT == mServerMsgUpdateMap.end()) + { + msui = new RsGxsServerMsgUpdateItem(mServType); + msui->grpId = grpMeta->mGroupId; + mServerMsgUpdateMap.insert(std::make_pair(msui->grpId, msui)); + }else + { + msui = mapIT->second; + } + + msui->msgUpdateTS = grpMeta->mLastPost; + + // this might be very inefficient with time + if(grpMeta->mRecvTS > mGrpServerUpdateItem->grpUpdateTS) + mGrpServerUpdateItem->grpUpdateTS = grpMeta->mRecvTS; + } + + freeAndClearContainerResource, + RsGxsGrpMetaData*>(gxsMap); +} bool RsGxsNetService::locked_checkTransacTimedOut(NxsTransaction* tr) { return tr->mTimeOut < ((uint32_t) time(NULL)); @@ -1156,30 +1201,27 @@ void RsGxsNetService::locked_processCompletedIncomingTrans(NxsTransaction* tr) // notify listener of grps mObserver->notifyNewGroups(grps); - // now note this as the latest you've received from this peer - std::string peerFrom = tr->mTransaction->PeerId(); - uint32_t updateTS = tr->mTransaction->updateTS; + // now note this as the latest you've received from this peer + std::string peerFrom = tr->mTransaction->PeerId(); + uint32_t updateTS = tr->mTransaction->updateTS; - ClientGrpMap::iterator it = mClientGrpUpdateMap.find(peerFrom); + ClientGrpMap::iterator it = mClientGrpUpdateMap.find(peerFrom); - RsGxsGrpUpdateItem* item = NULL; + RsGxsGrpUpdateItem* item = NULL; - if(it != mClientGrpUpdateMap.end()) - { - item = it->second; - }else - { - item = new RsGxsGrpUpdateItem(mServType); - } + if(it != mClientGrpUpdateMap.end()) + { + item = it->second; + }else + { + item = new RsGxsGrpUpdateItem(mServType); + mClientGrpUpdateMap.insert( + std::make_pair(peerFrom, item)); + } - item->grpUpdateTS = updateTS; - item->peerId = peerFrom; + item->grpUpdateTS = updateTS; + item->peerId = peerFrom; - mClientGrpUpdateMap.insert( - std::make_pair(peerFrom, item)); - - // as a grp list server also note this is the latest item you have - mGrpServerUpdateItem->grpUpdateTS = updateTS; }else if(flag & RsNxsTransac::FLAG_TYPE_MSGS) { @@ -1261,20 +1303,6 @@ void RsGxsNetService::locked_doMsgUpdateWork(const RsNxsTransac *nxsTrans, const mui->msgUpdateTS[grpId] = nxsTrans->updateTS; mui->peerId = peerFrom; - ServerMsgMap::iterator mit = mServerMsgUpdateMap.find(grpId); - RsGxsServerMsgUpdateItem* msui = NULL; - if(mit != mServerMsgUpdateMap.end()) - { - msui = mit->second; - } - else - { - msui = new RsGxsServerMsgUpdateItem(mServType); - mServerMsgUpdateMap.insert(std::make_pair(grpId, msui)); - } - - msui->grpId = grpId; - msui->msgUpdateTS = nxsTrans->updateTS; } void RsGxsNetService::locked_processCompletedOutgoingTrans(NxsTransaction* tr) diff --git a/libretroshare/src/gxs/rsgxsnetservice.h b/libretroshare/src/gxs/rsgxsnetservice.h index 0f7f95774..e1c27df83 100644 --- a/libretroshare/src/gxs/rsgxsnetservice.h +++ b/libretroshare/src/gxs/rsgxsnetservice.h @@ -327,6 +327,8 @@ private: void locked_doMsgUpdateWork(const RsNxsTransac* nxsTrans, const std::string& grpId); + void updateServerSyncTS(); + private: typedef std::vector GrpFragments; diff --git a/libretroshare/src/rsserver/rsinit.cc b/libretroshare/src/rsserver/rsinit.cc index 3c8f54155..6122adc4a 100644 --- a/libretroshare/src/rsserver/rsinit.cc +++ b/libretroshare/src/rsserver/rsinit.cc @@ -2227,7 +2227,7 @@ int RsServer::StartupRetroShare() std::string currGxsDir = RsInitConfig::configDir + "/GXS_phase2"; #ifdef GXS_DEV_TESTNET // Different Directory for testing. - currGxsDir += "_TESTNET5"; + currGxsDir += "_TESTNET6"; #endif bool cleanUpGxsDir = false; From 1cdf329bb1203a86b92ea616f9c81530af7fdadb Mon Sep 17 00:00:00 2001 From: chrisparker126 Date: Sun, 24 Nov 2013 12:37:17 +0000 Subject: [PATCH 56/83] fix for trigger statement, and readjusted algo to use self gen-exchange generated time stamps git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.5-gxs_finale@6907 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/gxs/rsdataservice.cc | 8 +++---- libretroshare/src/gxs/rsgxsnetservice.cc | 30 +++++++++++++++++++++--- 2 files changed, 31 insertions(+), 7 deletions(-) diff --git a/libretroshare/src/gxs/rsdataservice.cc b/libretroshare/src/gxs/rsdataservice.cc index 132e366bd..828fac742 100644 --- a/libretroshare/src/gxs/rsdataservice.cc +++ b/libretroshare/src/gxs/rsdataservice.cc @@ -250,10 +250,10 @@ void RsDataService::initialise(){ KEY_SIGN_SET + " BLOB);"); mDb->execSQL("CREATE TRIGGER " + GRP_LAST_POST_UPDATE_TRIGGER + - "UPDATE OF " + KEY_RECV_TS + " ON " + MSG_TABLE_NAME + - std::string("BEGIN ") + - "UPDATE " + GRP_TABLE_NAME + "SET " + KEY_GRP_LAST_POST + "= new." - + KEY_RECV_TS + ";" + " UPDATE OF " + KEY_RECV_TS + " ON " + MSG_TABLE_NAME + + std::string(" BEGIN ") + + " UPDATE " + GRP_TABLE_NAME + " SET " + KEY_GRP_LAST_POST + "= new." + + KEY_RECV_TS + " WHERE " + KEY_GRP_ID + "=old." + KEY_GRP_ID + ";" + std::string("END;")); } diff --git a/libretroshare/src/gxs/rsgxsnetservice.cc b/libretroshare/src/gxs/rsgxsnetservice.cc index 1ec276391..648d83a8e 100644 --- a/libretroshare/src/gxs/rsgxsnetservice.cc +++ b/libretroshare/src/gxs/rsgxsnetservice.cc @@ -868,6 +868,7 @@ void RsGxsNetService::run(){ double timeDelta = 0.2; + int updateCounter = 0; while(isRunning()){ @@ -877,7 +878,13 @@ void RsGxsNetService::run(){ Sleep((int) (timeDelta * 1000)); #endif - updateServerSyncTS(); + if(updateCounter == 3) + { + updateServerSyncTS(); + updateCounter = 0; + } + else + updateCounter++; // process active transactions processTransactions(); @@ -1729,12 +1736,15 @@ void RsGxsNetService::locked_genSendGrpsTransaction(NxsTransaction* tr) return; } + uint32_t updateTS = 0; + if(mGrpServerUpdateItem) + updateTS = mGrpServerUpdateItem->grpUpdateTS; RsNxsTransac* ntr = new RsNxsTransac(mServType); ntr->transactionNumber = transN; ntr->transactFlag = RsNxsTransac::FLAG_BEGIN_P1 | RsNxsTransac::FLAG_TYPE_GRPS; - ntr->updateTS = time(NULL); + ntr->updateTS = updateTS; ntr->nItems = grps.size(); ntr->PeerId(tr->mTransaction->PeerId()); @@ -1850,12 +1860,17 @@ void RsGxsNetService::locked_genSendMsgsTransaction(NxsTransaction* tr) return; } + std::string grpId = ""; + for(;lit != tr->mItems.end(); lit++) { RsNxsSyncMsgItem* item = dynamic_cast(*lit); if (item) { msgIds[item->grpId].push_back(item->msgId); + + if(grpId.empty()) + grpId = item->grpId; } else { @@ -1912,11 +1927,18 @@ void RsGxsNetService::locked_genSendMsgsTransaction(NxsTransaction* tr) return; } + uint32_t updateTS = 0; + + ServerMsgMap::const_iterator cit = mServerMsgUpdateMap.find(grpId); + + if(cit != mServerMsgUpdateMap.end()) + updateTS = cit->second->msgUpdateTS; + RsNxsTransac* ntr = new RsNxsTransac(mServType); ntr->transactionNumber = transN; ntr->transactFlag = RsNxsTransac::FLAG_BEGIN_P1 | RsNxsTransac::FLAG_TYPE_MSGS; - ntr->updateTS = time(NULL); + ntr->updateTS = updateTS; ntr->nItems = msgSize; ntr->PeerId(peerId); @@ -2003,7 +2025,9 @@ void RsGxsNetService::handleRecvSyncGroup(RsNxsSyncGrp* item) if(mGrpServerUpdateItem) { if(item->updateTS >= mGrpServerUpdateItem->grpUpdateTS && item->updateTS != 0) + { return; + } } std::map grp; From db30ea3ad43750a99e4ee346a9be2a477631baea Mon Sep 17 00:00:00 2001 From: chrisparker126 Date: Sun, 24 Nov 2013 12:38:21 +0000 Subject: [PATCH 57/83] forgot serialiser bad init git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.5-gxs_finale@6908 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/serialiser/rsgxsupdateitems.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/libretroshare/src/serialiser/rsgxsupdateitems.h b/libretroshare/src/serialiser/rsgxsupdateitems.h index 763c51516..77e3b2476 100644 --- a/libretroshare/src/serialiser/rsgxsupdateitems.h +++ b/libretroshare/src/serialiser/rsgxsupdateitems.h @@ -46,7 +46,7 @@ class RsGxsGrpUpdateItem : public RsItem { public: RsGxsGrpUpdateItem(uint16_t servType) : RsItem(RS_PKT_VERSION_SERVICE, servType, RS_PKT_SUBTYPE_GXS_GRP_UPDATE) - {} + {clear();} virtual ~RsGxsGrpUpdateItem() {} virtual void clear(); @@ -60,7 +60,7 @@ class RsGxsServerGrpUpdateItem : public RsItem { public: RsGxsServerGrpUpdateItem(uint16_t servType) : RsItem(RS_PKT_VERSION_SERVICE, servType, RS_PKT_SUBTYPE_GXS_SERVER_GRP_UPDATE) - {} + { clear();} virtual ~RsGxsServerGrpUpdateItem() {} virtual void clear(); @@ -73,7 +73,7 @@ class RsGxsMsgUpdateItem : public RsItem { public: RsGxsMsgUpdateItem(uint16_t servType) : RsItem(RS_PKT_VERSION_SERVICE, servType, RS_PKT_SUBTYPE_GXS_MSG_UPDATE) - {} + { clear();} virtual ~RsGxsMsgUpdateItem() {} virtual void clear(); @@ -88,7 +88,7 @@ class RsGxsServerMsgUpdateItem : public RsItem public: RsGxsServerMsgUpdateItem(uint16_t servType) : RsItem(RS_PKT_VERSION_SERVICE, servType, RS_PKT_SUBTYPE_GXS_SERVER_MSG_UPDATE) - {} + { clear();} virtual ~RsGxsServerMsgUpdateItem() {} virtual void clear(); From 34604577717d8fe3627368bc0ba8142ab7febfe3 Mon Sep 17 00:00:00 2001 From: chrisparker126 Date: Mon, 25 Nov 2013 22:28:17 +0000 Subject: [PATCH 58/83] nxs grp sync optimisation now working - msg still needs a bit of work - bug fix in grp sync found (reputation logic wrong) - bug in nxssyncmsg serialisation from recent work git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.5-gxs_finale@6909 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/gxs/rsgxsnetservice.cc | 56 ++++++++++++++-------- libretroshare/src/gxs/rsgxsnetservice.h | 3 ++ libretroshare/src/serialiser/rsnxsitems.cc | 1 + 3 files changed, 41 insertions(+), 19 deletions(-) diff --git a/libretroshare/src/gxs/rsgxsnetservice.cc b/libretroshare/src/gxs/rsgxsnetservice.cc index 648d83a8e..e7643c7e1 100644 --- a/libretroshare/src/gxs/rsgxsnetservice.cc +++ b/libretroshare/src/gxs/rsgxsnetservice.cc @@ -1503,7 +1503,7 @@ void RsGxsNetService::locked_genReqMsgTransaction(NxsTransaction* tr) GixsReputation rep; mReputations->getReputation(syncItem->authorId, rep); - if(rep.score > GIXS_CUT_OFF) + if(rep.score > GIXS_CUT_OFF || syncItem->authorId.empty()) { RsNxsSyncMsgItem* msgItem = new RsNxsSyncMsgItem(mServType); msgItem->grpId = grpId; @@ -2014,21 +2014,31 @@ void RsGxsNetService::locked_pushGrpRespFromList(std::list& respList locked_addTransaction(tr); } +bool RsGxsNetService::locked_CanReceiveUpdate(const RsNxsSyncGrp *item) +{ + // don't sync if you have no new updates for this peer + if(mGrpServerUpdateItem) + { + if(item->updateTS >= mGrpServerUpdateItem->grpUpdateTS && item->updateTS != 0) + { + return false; + } + } + + return true; +} + void RsGxsNetService::handleRecvSyncGroup(RsNxsSyncGrp* item) { RsStackMutex stack(mNxsMutex); + if(!locked_CanReceiveUpdate(item)) + return; + std::string peer = item->PeerId(); - // don't sync if you have no new updates for this peer - if(mGrpServerUpdateItem) - { - if(item->updateTS >= mGrpServerUpdateItem->grpUpdateTS && item->updateTS != 0) - { - return; - } - } + std::map grp; mDataStore->retrieveGxsGrpMetaData(grp); @@ -2083,6 +2093,8 @@ void RsGxsNetService::handleRecvSyncGroup(RsNxsSyncGrp* item) return; } + + bool RsGxsNetService::canSendGrpId(const std::string& sslId, RsGxsGrpMetaData& grpMeta, std::vector& toVet) { // first do the simple checks @@ -2138,22 +2150,28 @@ bool RsGxsNetService::canSendGrpId(const std::string& sslId, RsGxsGrpMetaData& g return true; } +bool RsGxsNetService::locked_CanReceiveUpdate(const RsNxsSyncMsg *item) +{ + ServerMsgMap::const_iterator cit = mServerMsgUpdateMap.find(item->grpId); + + if(cit != mServerMsgUpdateMap.end()) + { + const RsGxsServerMsgUpdateItem *msui = cit->second; + + if(item->updateTS >= msui->msgUpdateTS && item->updateTS != 0) + return false; + } + return true; +} void RsGxsNetService::handleRecvSyncMessage(RsNxsSyncMsg* item) { RsStackMutex stack(mNxsMutex); + if(!locked_CanReceiveUpdate(item)) + return; + const std::string& peer = item->PeerId(); - ServerMsgMap::const_iterator cit = mServerMsgUpdateMap.find(item->grpId); - - if(cit != mServerMsgUpdateMap.end()) - { - const RsGxsServerMsgUpdateItem *msui = cit->second; - - if(item->updateTS > msui->msgUpdateTS && item->updateTS != 0) - return; - } - GxsMsgMetaResult metaResult; GxsMsgReq req; diff --git a/libretroshare/src/gxs/rsgxsnetservice.h b/libretroshare/src/gxs/rsgxsnetservice.h index e1c27df83..d72773f91 100644 --- a/libretroshare/src/gxs/rsgxsnetservice.h +++ b/libretroshare/src/gxs/rsgxsnetservice.h @@ -329,6 +329,9 @@ private: void updateServerSyncTS(); + bool locked_CanReceiveUpdate(const RsNxsSyncGrp* item); + bool locked_CanReceiveUpdate(const RsNxsSyncMsg* item); + private: typedef std::vector GrpFragments; diff --git a/libretroshare/src/serialiser/rsnxsitems.cc b/libretroshare/src/serialiser/rsnxsitems.cc index 108dba1d0..f855a57c6 100644 --- a/libretroshare/src/serialiser/rsnxsitems.cc +++ b/libretroshare/src/serialiser/rsnxsitems.cc @@ -505,6 +505,7 @@ bool RsNxsSerialiser::serialiseNxsSyncMsg(RsNxsSyncMsg *item, void *data, uint32 ok &= setRawUInt32(data, *size, &offset, item->createdSince); ok &= SetTlvString(data, *size, &offset, TLV_TYPE_STR_HASH_SHA1, item->syncHash); ok &= SetTlvString(data, *size, &offset, TLV_TYPE_STR_GROUPID, item->grpId); + ok &= setRawUInt32(data, *size, &offset, item->updateTS); if(offset != tlvsize){ #ifdef RSSERIAL_DEBUG From e50f0175720969196a8819f7742071ad6b358bb5 Mon Sep 17 00:00:00 2001 From: chrisparker126 Date: Wed, 27 Nov 2013 21:54:05 +0000 Subject: [PATCH 59/83] Fixes of msg sync optimisation - msg sync opt now working git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.5-gxs_finale@6913 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/gxs/rsdataservice.cc | 4 ++-- libretroshare/src/gxs/rsgenexchange.cc | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/libretroshare/src/gxs/rsdataservice.cc b/libretroshare/src/gxs/rsdataservice.cc index 828fac742..4ca2aaa1f 100644 --- a/libretroshare/src/gxs/rsdataservice.cc +++ b/libretroshare/src/gxs/rsdataservice.cc @@ -250,10 +250,10 @@ void RsDataService::initialise(){ KEY_SIGN_SET + " BLOB);"); mDb->execSQL("CREATE TRIGGER " + GRP_LAST_POST_UPDATE_TRIGGER + - " UPDATE OF " + KEY_RECV_TS + " ON " + MSG_TABLE_NAME + + " INSERT ON " + MSG_TABLE_NAME + std::string(" BEGIN ") + " UPDATE " + GRP_TABLE_NAME + " SET " + KEY_GRP_LAST_POST + "= new." - + KEY_RECV_TS + " WHERE " + KEY_GRP_ID + "=old." + KEY_GRP_ID + ";" + + KEY_RECV_TS + " WHERE " + KEY_GRP_ID + "=new." + KEY_GRP_ID + ";" + std::string("END;")); } diff --git a/libretroshare/src/gxs/rsgenexchange.cc b/libretroshare/src/gxs/rsgenexchange.cc index 316832b90..d10740051 100644 --- a/libretroshare/src/gxs/rsgenexchange.cc +++ b/libretroshare/src/gxs/rsgenexchange.cc @@ -2303,6 +2303,7 @@ void RsGenExchange::processRecvdMessages() if(validated_entry != mMsgPendingValidate.end()) mMsgPendingValidate.erase(validated_entry); computeHash(msg->msg, meta->mHash); + meta->recvTS = time(NULL); } } else From 972674173d176fb140f03943a0eac82ac7437589 Mon Sep 17 00:00:00 2001 From: chrisparker126 Date: Mon, 9 Dec 2013 22:24:49 +0000 Subject: [PATCH 60/83] added tests for gxs update items - need to fix to allow saving sync config git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.5-gxs_finale@6936 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- .../tests/serialiser/rsgxsupdateitem_test.cc | 110 ++++++++++++++++++ .../tests/serialiser/rsgxsupdateitem_test.h | 25 ++++ 2 files changed, 135 insertions(+) create mode 100644 libretroshare/src/tests/serialiser/rsgxsupdateitem_test.cc create mode 100644 libretroshare/src/tests/serialiser/rsgxsupdateitem_test.h diff --git a/libretroshare/src/tests/serialiser/rsgxsupdateitem_test.cc b/libretroshare/src/tests/serialiser/rsgxsupdateitem_test.cc new file mode 100644 index 000000000..395e5b7c3 --- /dev/null +++ b/libretroshare/src/tests/serialiser/rsgxsupdateitem_test.cc @@ -0,0 +1,110 @@ +/* + * rsgxsupdateitem_test.cc + * + * Created on: 9 Dec 2013 + * Author: crispy + */ + +#include "support.h" +#include "rsgxsupdateitem_test.h" + +INITTEST(); + +RsSerialType* init_item(RsGxsGrpUpdateItem& i) +{ + i.clear(); + i.grpUpdateTS = rand()%2424; + randString(SHORT_STR, i.peerId); + return new RsGxsUpdateSerialiser(0); +} + +RsSerialType* init_item(RsGxsMsgUpdateItem& i) +{ + i.clear(); + randString(SHORT_STR, i.peerId); + int numUpdates = rand()%123; + + std::string peer; + for(int j=0; j < numUpdates; j++) + { + randString(SHORT_STR, peer); + i.msgUpdateTS.insert(std::make_pair(peer, rand()%45)); + } + + return new RsGxsUpdateSerialiser(0); +} + +RsSerialType* init_item(RsGxsServerGrpUpdateItem& i) +{ + i.clear(); + i.grpUpdateTS = rand()%2424; + + return new RsGxsUpdateSerialiser(0); +} + +RsSerialType* init_item(RsGxsServerMsgUpdateItem& i) +{ + i.clear(); + randString(SHORT_STR, i.grpId); + i.msgUpdateTS = rand()%4252; + return new RsGxsUpdateSerialiser(0); +} + +bool operator ==(const RsGxsGrpUpdateItem& l, const RsGxsGrpUpdateItem& r) +{ + bool ok = l.grpUpdateTS == r.grpUpdateTS; + ok &= l.peerId == r.peerId; + + return ok; +} + +bool operator ==(const RsGxsMsgUpdateItem& l, const RsGxsMsgUpdateItem& r) +{ + bool ok = l.peerId == r.peerId; + + const std::map& lUp = l.msgUpdateTS, rUp = r.msgUpdateTS; + + ok &= lUp.size() == rUp.size(); + + std::map::const_iterator lit = lUp.begin(), rit; + + for(; lit != lUp.end(); lit++) + { + std::string key = lit->first; + if((rit = rUp.find(key)) != rUp.end()) + ok &= lit->second == rit->second; + else + return false; + } + + return ok; +} + +bool operator ==(const RsGxsServerGrpUpdateItem& l, + const RsGxsServerGrpUpdateItem& r) +{ + return l.grpUpdateTS == r.grpUpdateTS; +} + +bool operator ==(const RsGxsServerMsgUpdateItem& l, + const RsGxsServerMsgUpdateItem& r) +{ + bool ok = l.grpId == r.grpId; + ok &= l.msgUpdateTS == r.msgUpdateTS; + return ok; +} + + +int main() +{ + std::cerr << "RsGxsUpdateItem Tests" << std::endl; + + test_RsItem(RS_SERVICE_TYPE_PLUGIN_SIMPLE_FORUM); REPORT("Serialise/Deserialise RsGxsGrpUpdateItem"); + test_RsItem(RS_SERVICE_TYPE_PLUGIN_SIMPLE_FORUM); REPORT("Serialise/Deserialise RsGxsMsgUpdateItem"); + test_RsItem(RS_SERVICE_TYPE_PLUGIN_SIMPLE_FORUM); REPORT("Serialise/Deserialise RsGxsServerGrpUpdateItem"); + test_RsItem(RS_SERVICE_TYPE_PLUGIN_SIMPLE_FORUM); REPORT("Serialise/Deserialise RsGxsServerMsgUpdateItem"); + + FINALREPORT("RsGxsUpdateItem Tests"); + + return TESTRESULT(); +} diff --git a/libretroshare/src/tests/serialiser/rsgxsupdateitem_test.h b/libretroshare/src/tests/serialiser/rsgxsupdateitem_test.h new file mode 100644 index 000000000..57a686241 --- /dev/null +++ b/libretroshare/src/tests/serialiser/rsgxsupdateitem_test.h @@ -0,0 +1,25 @@ +/* + * rsgxsupdateitem_test.h + * + * Created on: 9 Dec 2013 + * Author: crispy + */ + +#ifndef RSGXSUPDATEITEM_TEST_H_ +#define RSGXSUPDATEITEM_TEST_H_ + +#include "serialiser/rsgxsupdateitems.h" +#include "support.h" + + +RsSerialType* init_item(RsGxsGrpUpdateItem& i); +RsSerialType* init_item(RsGxsMsgUpdateItem& i); +RsSerialType* init_item(RsGxsServerGrpUpdateItem& i); +RsSerialType* init_item(RsGxsServerMsgUpdateItem& i); + +bool operator==(const RsGxsGrpUpdateItem& l, const RsGxsGrpUpdateItem& r); +bool operator==(const RsGxsMsgUpdateItem& l, const RsGxsMsgUpdateItem& r); +bool operator==(const RsGxsServerGrpUpdateItem& l, const RsGxsServerGrpUpdateItem& r); +bool operator==(const RsGxsServerMsgUpdateItem& l, const RsGxsServerMsgUpdateItem& r); + +#endif /* RSGXSUPDATEITEM_TEST_H_ */ From dab782fbaa4be31db93e513dc16ca3dd754abbaa Mon Sep 17 00:00:00 2001 From: chrisparker126 Date: Sun, 15 Dec 2013 20:11:39 +0000 Subject: [PATCH 61/83] Fixes for gxsupdate item serialisation - now works git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.5-gxs_finale@6947 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/serialiser/rsgxsupdateitems.cc | 6 +++--- .../src/tests/serialiser/rsgxsupdateitem_test.cc | 8 ++++---- libretroshare/src/tests/serialiser/rsnxsitems_test.cc | 8 ++++---- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/libretroshare/src/serialiser/rsgxsupdateitems.cc b/libretroshare/src/serialiser/rsgxsupdateitems.cc index 60f637f06..26bcff9c3 100644 --- a/libretroshare/src/serialiser/rsgxsupdateitems.cc +++ b/libretroshare/src/serialiser/rsgxsupdateitems.cc @@ -325,8 +325,8 @@ RsGxsGrpUpdateItem* RsGxsUpdateSerialiser::deserialGxsGrpUpddate(void* data, /* skip the header */ offset += 8; - ok &= getRawUInt32(data, *size, &offset, &(item->grpUpdateTS)); ok &= GetTlvString(data, *size, &offset, TLV_TYPE_STR_PEERID, item->peerId); + ok &= getRawUInt32(data, *size, &offset, &(item->grpUpdateTS)); if (offset != rssize) { @@ -482,7 +482,7 @@ bool RsGxsUpdateSerialiser::serialiseGxsMsgUpdate(RsGxsMsgUpdateItem* item, for(; cit != msgUpdateTS.end(); cit++) { - ok &= SetTlvString(data, *size, &offset, TLV_TYPE_STR_PEERID, cit->first); + ok &= SetTlvString(data, *size, &offset, TLV_TYPE_STR_GROUPID, cit->first); ok &= setRawUInt32(data, *size, &offset, cit->second); } @@ -599,7 +599,7 @@ RsGxsMsgUpdateItem* RsGxsUpdateSerialiser::deserialGxsMsgUpdate(void* data, std::map& msgUpdateItem = item->msgUpdateTS; std::string grpId; uint32_t updateTS; - for(uint32_t i; i < numUpdateItems; i++) + for(uint32_t i = 0; i < numUpdateItems; i++) { ok &= GetTlvString(data, *size, &offset, TLV_TYPE_STR_GROUPID, grpId); diff --git a/libretroshare/src/tests/serialiser/rsgxsupdateitem_test.cc b/libretroshare/src/tests/serialiser/rsgxsupdateitem_test.cc index 395e5b7c3..aa858daf7 100644 --- a/libretroshare/src/tests/serialiser/rsgxsupdateitem_test.cc +++ b/libretroshare/src/tests/serialiser/rsgxsupdateitem_test.cc @@ -15,7 +15,7 @@ RsSerialType* init_item(RsGxsGrpUpdateItem& i) i.clear(); i.grpUpdateTS = rand()%2424; randString(SHORT_STR, i.peerId); - return new RsGxsUpdateSerialiser(0); + return new RsGxsUpdateSerialiser(RS_SERVICE_TYPE_PLUGIN_SIMPLE_FORUM); } RsSerialType* init_item(RsGxsMsgUpdateItem& i) @@ -31,7 +31,7 @@ RsSerialType* init_item(RsGxsMsgUpdateItem& i) i.msgUpdateTS.insert(std::make_pair(peer, rand()%45)); } - return new RsGxsUpdateSerialiser(0); + return new RsGxsUpdateSerialiser(RS_SERVICE_TYPE_PLUGIN_SIMPLE_FORUM); } RsSerialType* init_item(RsGxsServerGrpUpdateItem& i) @@ -39,7 +39,7 @@ RsSerialType* init_item(RsGxsServerGrpUpdateItem& i) i.clear(); i.grpUpdateTS = rand()%2424; - return new RsGxsUpdateSerialiser(0); + return new RsGxsUpdateSerialiser(RS_SERVICE_TYPE_PLUGIN_SIMPLE_FORUM); } RsSerialType* init_item(RsGxsServerMsgUpdateItem& i) @@ -47,7 +47,7 @@ RsSerialType* init_item(RsGxsServerMsgUpdateItem& i) i.clear(); randString(SHORT_STR, i.grpId); i.msgUpdateTS = rand()%4252; - return new RsGxsUpdateSerialiser(0); + return new RsGxsUpdateSerialiser(RS_SERVICE_TYPE_PLUGIN_SIMPLE_FORUM); } bool operator ==(const RsGxsGrpUpdateItem& l, const RsGxsGrpUpdateItem& r) diff --git a/libretroshare/src/tests/serialiser/rsnxsitems_test.cc b/libretroshare/src/tests/serialiser/rsnxsitems_test.cc index 16cc020a9..b2dab65e9 100644 --- a/libretroshare/src/tests/serialiser/rsnxsitems_test.cc +++ b/libretroshare/src/tests/serialiser/rsnxsitems_test.cc @@ -39,7 +39,7 @@ RsSerialType* init_item(RsNxsSyncGrp& rsg) { rsg.clear(); rsg.flag = RsNxsSyncGrp::FLAG_USE_SYNC_HASH; - rsg.syncAge = rand()%2423; + rsg.createdSince = rand()%2423; randString(3124,rsg.syncHash); return new RsNxsSerialiser(RS_SERVICE_TYPE_PLUGIN_SIMPLE_FORUM); @@ -50,7 +50,7 @@ RsSerialType* init_item(RsNxsSyncMsg& rsgm) rsgm.clear(); rsgm.flag = RsNxsSyncMsg::FLAG_USE_SYNC_HASH; - rsgm.syncAge = rand()%24232; + rsgm.createdSince = rand()%24232; rsgm.transactionNumber = rand()%23; randString(SHORT_STR, rsgm.grpId); randString(SHORT_STR, rsgm.syncHash); @@ -120,7 +120,7 @@ bool operator==(const RsNxsSyncGrp& l, const RsNxsSyncGrp& r) if(l.syncHash != r.syncHash) return false; if(l.flag != r.flag) return false; - if(l.syncAge != r.syncAge) return false; + if(l.createdSince != r.createdSince) return false; if(l.transactionNumber != r.transactionNumber) return false; return true; @@ -130,7 +130,7 @@ bool operator==(const RsNxsSyncMsg& l, const RsNxsSyncMsg& r) { if(l.flag != r.flag) return false; - if(l.syncAge != r.syncAge) return false; + if(l.createdSince != r.createdSince) return false; if(l.syncHash != r.syncHash) return false; if(l.grpId != r.grpId) return false; if(l.transactionNumber != r.transactionNumber) return false; From cc7569e3966dd431a7230b42c45168e6b91d5e9f Mon Sep 17 00:00:00 2001 From: chrisparker126 Date: Fri, 20 Dec 2013 14:48:32 +0000 Subject: [PATCH 62/83] - enabled config saving of sync information - additional fixes for sync reloading - confirmed sync now working with A B test git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.5-gxs_finale@6951 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/gxs/rsgxsnetservice.cc | 32 +++++++++++++++++++++--- libretroshare/src/rsserver/rsinit.cc | 13 ++++++++++ 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/libretroshare/src/gxs/rsgxsnetservice.cc b/libretroshare/src/gxs/rsgxsnetservice.cc index e7643c7e1..00fd02422 100644 --- a/libretroshare/src/gxs/rsgxsnetservice.cc +++ b/libretroshare/src/gxs/rsgxsnetservice.cc @@ -566,7 +566,7 @@ class StoreHere { public: - StoreHere(RsGxsNetService::ClientGrpMap& cgm, RsGxsNetService::ClientMsgMap cmm, + StoreHere(RsGxsNetService::ClientGrpMap& cgm, RsGxsNetService::ClientMsgMap& cmm, RsGxsNetService::ServerMsgMap& smm, RsGxsServerGrpUpdateItem*& sgm) : mClientGrpMap(cgm), mClientMsgMap(cmm), mServerMsgMap(smm), mServerGrpUpdateItem(sgm) @@ -587,7 +587,7 @@ public: mServerMsgMap.insert(std::make_pair(msui->grpId, msui)); else if((gsui = dynamic_cast(item)) != NULL) { - if(mServerGrpUpdateItem) + if(mServerGrpUpdateItem == NULL) { mServerGrpUpdateItem = gsui; } @@ -619,6 +619,7 @@ bool RsGxsNetService::loadList(std::list &load) { std::for_each(load.begin(), load.end(), StoreHere(mClientGrpUpdateMap, mClientMsgUpdateMap, mServerMsgUpdateMap, mGrpServerUpdateItem)); + return true; } @@ -648,6 +649,9 @@ bool RsGxsNetService::saveList(bool& cleanup, std::list& save) std::back_inserter(save), get_second()); save.push_back(mGrpServerUpdateItem); + + cleanup = false; + return true; } RsSerialiser *RsGxsNetService::setupSerialiser() @@ -916,6 +920,8 @@ void RsGxsNetService::updateServerSyncTS() mGrpServerUpdateItem = new RsGxsServerGrpUpdateItem(mServType); } + bool change = false; + for(; mit != gxsMap.end(); mit++) { const RsGxsGroupId& grpId = mit->first; @@ -933,15 +939,27 @@ void RsGxsNetService::updateServerSyncTS() msui = mapIT->second; } - msui->msgUpdateTS = grpMeta->mLastPost; + if(grpMeta->mLastPost > msui->msgUpdateTS ) + { + change = true; + msui->msgUpdateTS = grpMeta->mLastPost; + } // this might be very inefficient with time if(grpMeta->mRecvTS > mGrpServerUpdateItem->grpUpdateTS) + { mGrpServerUpdateItem->grpUpdateTS = grpMeta->mRecvTS; + change = true; + } } + // actual change in config settings, then save configuration + if(change) + IndicateConfigChanged(); + freeAndClearContainerResource, RsGxsGrpMetaData*>(gxsMap); + } bool RsGxsNetService::locked_checkTransacTimedOut(NxsTransaction* tr) { @@ -1229,6 +1247,8 @@ void RsGxsNetService::locked_processCompletedIncomingTrans(NxsTransaction* tr) item->grpUpdateTS = updateTS; item->peerId = peerFrom; + IndicateConfigChanged(); + }else if(flag & RsNxsTransac::FLAG_TYPE_MSGS) { @@ -1310,6 +1330,7 @@ void RsGxsNetService::locked_doMsgUpdateWork(const RsNxsTransac *nxsTrans, const mui->msgUpdateTS[grpId] = nxsTrans->updateTS; mui->peerId = peerFrom; + IndicateConfigChanged(); } void RsGxsNetService::locked_processCompletedOutgoingTrans(NxsTransaction* tr) @@ -2159,7 +2180,12 @@ bool RsGxsNetService::locked_CanReceiveUpdate(const RsNxsSyncMsg *item) const RsGxsServerMsgUpdateItem *msui = cit->second; if(item->updateTS >= msui->msgUpdateTS && item->updateTS != 0) + { +#ifdef NXS_NET_DEBUG + std::cerr << "RsGxsNetService::locked_CanReceiveUpdate(): Msgs up to date" << std::endl; +#endif return false; + } } return true; } diff --git a/libretroshare/src/rsserver/rsinit.cc b/libretroshare/src/rsserver/rsinit.cc index 6122adc4a..c5e797f1a 100644 --- a/libretroshare/src/rsserver/rsinit.cc +++ b/libretroshare/src/rsserver/rsinit.cc @@ -2502,6 +2502,19 @@ int RsServer::StartupRetroShare() mConfigMgr->addConfiguration("bitdht.cfg", mBitDht); #endif +#ifdef RS_ENABLE_GXS + + mConfigMgr->addConfiguration("identity.cfg", gxsid_ns); + mConfigMgr->addConfiguration("gxsforums.cfg", gxsforums_ns); + mConfigMgr->addConfiguration("gxschannels.cfg", gxschannels_ns); + mConfigMgr->addConfiguration("gxscircles.cfg", gxscircles_ns); + mConfigMgr->addConfiguration("posted.cfg", posted_ns); + mConfigMgr->addConfiguration("wire.cfg", wire_ns); + mConfigMgr->addConfiguration("wiki.cfg", wiki_ns); + mConfigMgr->addConfiguration("photo.cfg", photo_ns); + +#endif + mPluginsManager->addConfigurations(mConfigMgr) ; ftserver->addConfiguration(mConfigMgr); From 8aca56bc4f764f840d9c6d72466d82fff02ca7bd Mon Sep 17 00:00:00 2001 From: chrisparker126 Date: Sat, 21 Dec 2013 19:27:48 +0000 Subject: [PATCH 63/83] merge fix git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@6954 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/serialiser/rstlvbase.h | 1 + 1 file changed, 1 insertion(+) diff --git a/libretroshare/src/serialiser/rstlvbase.h b/libretroshare/src/serialiser/rstlvbase.h index 0f1ecb97c..f57dabf3e 100644 --- a/libretroshare/src/serialiser/rstlvbase.h +++ b/libretroshare/src/serialiser/rstlvbase.h @@ -211,6 +211,7 @@ const uint16_t TLV_TYPE_PEERSET = 0x1021; const uint16_t TLV_TYPE_HASHSET = 0x1022; const uint16_t TLV_TYPE_PGPIDSET = 0x1023; +const uint16_t TLV_TYPE_RECOGNSET = 0x1024; const uint16_t TLV_TYPE_SERVICESET = 0x1030; From 9d78ad89420a8e6cf5325102a9c6cda7c2be2938 Mon Sep 17 00:00:00 2001 From: defnax Date: Wed, 25 Dec 2013 17:16:17 +0000 Subject: [PATCH 64/83] renaming strings git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@6962 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- retroshare-gui/src/gui/Posted/PostedListDialog.ui | 4 ++-- retroshare-gui/src/gui/unfinished/ApplicationWindow.cpp | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/retroshare-gui/src/gui/Posted/PostedListDialog.ui b/retroshare-gui/src/gui/Posted/PostedListDialog.ui index 917dc9602..bfd409c56 100644 --- a/retroshare-gui/src/gui/Posted/PostedListDialog.ui +++ b/retroshare-gui/src/gui/Posted/PostedListDialog.ui @@ -48,7 +48,7 @@ 0 0 - 605 + 745 332 @@ -83,7 +83,7 @@ - Submit Post + Create Post diff --git a/retroshare-gui/src/gui/unfinished/ApplicationWindow.cpp b/retroshare-gui/src/gui/unfinished/ApplicationWindow.cpp index dbbab898c..8af2f3100 100644 --- a/retroshare-gui/src/gui/unfinished/ApplicationWindow.cpp +++ b/retroshare-gui/src/gui/unfinished/ApplicationWindow.cpp @@ -106,7 +106,7 @@ ApplicationWindow::ApplicationWindow(QWidget* parent, Qt::WFlags flags) #ifdef RS_USE_PHOTOSHARE PhotoShare *photoShare = NULL; ui.stackPages->add(photoShare = new PhotoShare(ui.stackPages), - createPageAction(QIcon(IMAGE_PHOTO), tr("Photo Share"), grp)); + createPageAction(QIcon(IMAGE_PHOTO), tr("Photos"), grp)); #endif PostedDialog *postedDialog = NULL; From 39db508ce73402d491fb6da74a7164d034f1567e Mon Sep 17 00:00:00 2001 From: drbob Date: Sat, 18 Jan 2014 02:32:55 +0000 Subject: [PATCH 65/83] Improvements for V0.6 logins to support hidden nodes. - Separated Acount stuff from rsinit.cc => rsaccounts.cc - Moved Account Directory to HID06_xxxxxxx, or STD06_xxxxx This allows us to check for Hidden immediately And prevents v0.5 accounts being used with 0.6 - Added functions to support Proxy, and Hidden stuff. - Changed Minimum port to 10 to allow port 80 to be used by those who must. git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@7027 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/libretroshare.pro | 4 +- libretroshare/src/pqi/p3peermgr.cc | 78 +- libretroshare/src/pqi/p3peermgr.h | 3 + libretroshare/src/pqi/pqi_base.h | 4 +- libretroshare/src/retroshare/rsinit.h | 106 +- libretroshare/src/retroshare/rspeers.h | 6 + libretroshare/src/rsserver/p3peers.cc | 73 +- libretroshare/src/rsserver/p3peers.h | 4 + libretroshare/src/rsserver/rsaccounts.cc | 1317 ++++++++++++++++++ libretroshare/src/rsserver/rsaccounts.h | 152 ++ libretroshare/src/rsserver/rsinit.cc | 1186 ++-------------- libretroshare/src/rsserver/rsloginhandler.cc | 6 +- libretroshare/src/util/rsdiscspace.cc | 6 +- libretroshare/src/util/rsstring.cc | 13 + libretroshare/src/util/rsstring.h | 2 + 15 files changed, 1783 insertions(+), 1177 deletions(-) create mode 100644 libretroshare/src/rsserver/rsaccounts.cc create mode 100644 libretroshare/src/rsserver/rsaccounts.h diff --git a/libretroshare/src/libretroshare.pro b/libretroshare/src/libretroshare.pro index 80de8c8c0..e4ccd7596 100644 --- a/libretroshare/src/libretroshare.pro +++ b/libretroshare/src/libretroshare.pro @@ -364,6 +364,7 @@ HEADERS += rsserver/p3face.h \ rsserver/p3msgs.h \ rsserver/p3peers.h \ rsserver/p3status.h \ + rsserver/rsaccounts.h \ rsserver/p3serverconfig.h HEADERS += serialiser/rsbaseserial.h \ @@ -391,7 +392,6 @@ HEADERS += serialiser/rsbaseserial.h \ serialiser/rsheartbeatitems.h \ serialiser/rsrttitems.h \ serialiser/rsgxsrecognitems.h \ - serialiser/rstunnelitems.h \ serialiser/rsgxsupdateitems.h HEADERS += services/p3chatservice.h \ @@ -494,6 +494,7 @@ SOURCES += rsserver/p3face-config.cc \ rsserver/p3peers.cc \ rsserver/p3status.cc \ rsserver/rsinit.cc \ + rsserver/rsaccounts.cc \ rsserver/rsloginhandler.cc \ rsserver/rstypes.cc \ rsserver/p3serverconfig.cc @@ -527,7 +528,6 @@ SOURCES += serialiser/rsbaseserial.cc \ serialiser/rsheartbeatitems.cc \ serialiser/rsrttitems.cc \ serialiser/rsgxsrecognitems.cc \ - serialiser/rstunnelitems.cc \ serialiser/rsgxsupdateitems.cc SOURCES += services/p3chatservice.cc \ diff --git a/libretroshare/src/pqi/p3peermgr.cc b/libretroshare/src/pqi/p3peermgr.cc index eb6ead1dc..10ddf5d0a 100644 --- a/libretroshare/src/pqi/p3peermgr.cc +++ b/libretroshare/src/pqi/p3peermgr.cc @@ -103,10 +103,10 @@ std::string textPeerConnectState(peerState &state) } -p3PeerMgrIMPL::p3PeerMgrIMPL( const std::string& ssl_own_id, - const std::string& gpg_own_id, - const std::string& gpg_own_name, - const std::string& ssl_own_location) +p3PeerMgrIMPL::p3PeerMgrIMPL(const std::string& ssl_own_id, + const std::string& gpg_own_id, + const std::string& gpg_own_name, + const std::string& ssl_own_location) :p3Config(CONFIG_TYPE_PEERS), mPeerMtx("p3PeerMgr"), mStatusChanged(false) { @@ -130,11 +130,7 @@ p3PeerMgrIMPL::p3PeerMgrIMPL( const std::string& ssl_own_id, // setup default ProxyServerAddress. sockaddr_storage_clear(mProxyServerAddress); sockaddr_storage_ipv4_aton(mProxyServerAddress, "127.0.0.1"); - sockaddr_storage_ipv4_setport(mProxyServerAddress, 9100); - - //inet_aton("127.0.0.1", &(mProxyServerAddress.sin_addr)); - //mProxyServerAddress.sin_port = htons(9100); - + sockaddr_storage_ipv4_setport(mProxyServerAddress, 9150); } #ifdef PEER_DEBUG @@ -151,17 +147,45 @@ void p3PeerMgrIMPL::setManagers(p3LinkMgrIMPL *linkMgr, p3NetMgrIMPL *netMgr) mNetMgr = netMgr; } + bool p3PeerMgrIMPL::setupHiddenNode(const std::string &hiddenAddress, const uint16_t hiddenPort) { - std::cerr << "p3PeerMgrIMPL::setupHiddenNode()"; - std::cerr << " Address: " << hiddenAddress; - std::cerr << " Port: " << hiddenPort; - std::cerr << std::endl; + { + RsStackMutex stack(mPeerMtx); /****** STACK LOCK MUTEX *******/ + + std::cerr << "p3PeerMgrIMPL::setupHiddenNode()"; + std::cerr << " Address: " << hiddenAddress; + std::cerr << " Port: " << hiddenPort; + std::cerr << std::endl; + + mOwnState.hiddenNode = true; + mOwnState.hiddenPort = hiddenPort; + mOwnState.hiddenDomain = hiddenAddress; + } + + forceHiddenNode(); + return true; +} + + +bool p3PeerMgrIMPL::forceHiddenNode() +{ + { + RsStackMutex stack(mPeerMtx); /****** STACK LOCK MUTEX *******/ + if (RS_NET_MODE_HIDDEN != mOwnState.netMode) + { + std::cerr << "p3PeerMgrIMPL::forceHiddenNode() Required!"; + std::cerr << std::endl; + } + mOwnState.hiddenNode = true; + + // force external address - otherwise its invalid. + sockaddr_storage_clear(mOwnState.serveraddr); + sockaddr_storage_ipv4_aton(mOwnState.serveraddr, "0.0.0.0"); + sockaddr_storage_ipv4_setport(mOwnState.serveraddr, 0); + } setOwnNetworkMode(RS_NET_MODE_HIDDEN); - mOwnState.hiddenNode = true; - mOwnState.hiddenPort = hiddenPort; - mOwnState.hiddenDomain = hiddenAddress; // switch off DHT too. setOwnVisState(mOwnState.vs_disc, RS_VS_DHT_OFF); @@ -170,13 +194,14 @@ bool p3PeerMgrIMPL::setupHiddenNode(const std::string &hiddenAddress, const uint struct sockaddr_storage loopback; sockaddr_storage_clear(loopback); sockaddr_storage_ipv4_aton(loopback, "127.0.0.1"); - sockaddr_storage_ipv4_setport(loopback, hiddenPort); - - //inet_aton("127.0.0.1", &(loopback.sin_addr)); - //loopback.sin_port = htons(hiddenPort); + uint16_t port = sockaddr_storage_port(mOwnState.localaddr); + sockaddr_storage_ipv4_setport(loopback, port); setLocalAddress(AuthSSL::getAuthSSL()->OwnId(), loopback); - + + mNetMgr->setIPServersEnabled(false); + + IndicateConfigChanged(); /**** INDICATE MSG CONFIG CHANGED! *****/ return true; } @@ -357,6 +382,8 @@ bool p3PeerMgrIMPL::setHiddenDomainPort(const std::string &ssl_id, const std::st std::cerr << "p3PeerMgrIMPL::setHiddenDomainPort()"; std::cerr << std::endl; + IndicateConfigChanged(); /**** INDICATE MSG CONFIG CHANGED! *****/ + if (ssl_id == AuthSSL::getAuthSSL()->OwnId()) { mOwnState.hiddenNode = true; @@ -394,6 +421,15 @@ bool p3PeerMgrIMPL::setProxyServerAddress(const struct sockaddr_storage &proxy_a return true; } + +bool p3PeerMgrIMPL::getProxyServerAddress(struct sockaddr_storage &proxy_addr) +{ + RsStackMutex stack(mPeerMtx); /****** STACK LOCK MUTEX *******/ + + proxy_addr = mProxyServerAddress; + return true; +} + bool p3PeerMgrIMPL::getProxyAddress(const std::string &ssl_id, struct sockaddr_storage &proxy_addr, std::string &domain_addr, uint16_t &domain_port) { RsStackMutex stack(mPeerMtx); /****** STACK LOCK MUTEX *******/ diff --git a/libretroshare/src/pqi/p3peermgr.h b/libretroshare/src/pqi/p3peermgr.h index 236f45e03..1ee263496 100644 --- a/libretroshare/src/pqi/p3peermgr.h +++ b/libretroshare/src/pqi/p3peermgr.h @@ -183,6 +183,7 @@ virtual bool getGpgId(const std::string &sslId, std::string &gpgId) = 0; virtual uint32_t getConnectionType(const std::string &sslId) = 0; virtual bool setProxyServerAddress(const struct sockaddr_storage &proxy_addr) = 0; +virtual bool getProxyServerAddress(struct sockaddr_storage &proxy_addr) = 0; virtual bool isHidden() = 0; virtual bool isHiddenPeer(const std::string &ssl_id) = 0; virtual bool getProxyAddress(const std::string &ssl_id, struct sockaddr_storage &proxy_addr, std::string &domain_addr, uint16_t &domain_port) = 0; @@ -281,6 +282,7 @@ virtual bool getGpgId(const std::string &sslId, std::string &gpgId); virtual uint32_t getConnectionType(const std::string &sslId); virtual bool setProxyServerAddress(const struct sockaddr_storage &proxy_addr); +virtual bool getProxyServerAddress(struct sockaddr_storage &proxy_addr); virtual bool isHidden(); virtual bool isHiddenPeer(const std::string &ssl_id); virtual bool getProxyAddress(const std::string &ssl_id, struct sockaddr_storage &proxy_addr, std::string &domain_addr, uint16_t &domain_port); @@ -304,6 +306,7 @@ virtual bool haveOnceConnected(); void setManagers(p3LinkMgrIMPL *linkMgr, p3NetMgrIMPL *netMgr); +bool forceHiddenNode(); bool setupHiddenNode(const std::string &hiddenAddress, const uint16_t hiddenPort); void tick(); diff --git a/libretroshare/src/pqi/pqi_base.h b/libretroshare/src/pqi/pqi_base.h index b2ffcd491..893807cd5 100644 --- a/libretroshare/src/pqi/pqi_base.h +++ b/libretroshare/src/pqi/pqi_base.h @@ -41,7 +41,7 @@ #include "serialiser/rsserial.h" -#define PQI_MIN_PORT 1024 +#define PQI_MIN_PORT 10 // TO ALLOW USERS TO HAVE PORT 80! - was 1024 #define PQI_MAX_PORT 65535 #define PQI_DEFAULT_PORT 7812 @@ -210,7 +210,7 @@ class PQInterface: public RateInterface * Retrieve RsItem from a facility */ virtual RsItem *GetItem() = 0; - virtual bool RecvItem(RsItem *item) { return false; } /* alternative for for GetItem(), when we want to push */ + virtual bool RecvItem(RsItem * /*item*/ ) { return false; } /* alternative for for GetItem(), when we want to push */ /** * also there are tick + person id functions. diff --git a/libretroshare/src/retroshare/rsinit.h b/libretroshare/src/retroshare/rsinit.h index bfde25f8f..329f5d80e 100644 --- a/libretroshare/src/retroshare/rsinit.h +++ b/libretroshare/src/retroshare/rsinit.h @@ -73,69 +73,27 @@ class RsInit static bool isPortable(); static bool isWindowsXP(); - /*! - * Account Details (Combined GPG+SSL Setup) - */ - static bool getPreferedAccountId(std::string &id); - static bool getPGPEngineFileName(std::string &fileName); - static bool getAccountIds(std::list &ids); - static bool getAccountDetails(const std::string &id, std::string &gpgId, std::string &gpgName, std::string &gpgEmail, std::string &sslName); - - static bool ValidateCertificate(std::string &userName) ; - - static bool exportIdentity(const std::string& fname,const std::string& pgp_id) ; - static bool importIdentity(const std::string& fname,std::string& imported_pgp_id,std::string& import_error) ; - - /*! - * Generating GPGme Account - */ - static int GetPGPLogins(std::list &pgpIds); - static int GetPGPLoginDetails(const std::string& id, std::string &name, std::string &email); - static bool GeneratePGPCertificate(const std::string&, const std::string& email, const std::string& passwd, std::string &pgpId, std::string &errString); - - // copies existing gnupg keyrings to the new place of the OpenPGP-SDK version. Returns true on success. - static bool copyGnuPGKeyrings() ; - - /*! * Setup Hidden Location; */ static bool SetHiddenLocation(const std::string& hiddenaddress, uint16_t port); - /*! - * Login GGP - */ - static bool SelectGPGAccount(const std::string& gpgId); - static bool LoadGPGPassword(const std::string& passwd); - - /*! - * Create SSL Certificates - */ - static bool GenerateSSLCertificate(const std::string& name, const std::string& org, const std::string& loc, const std::string& country, const std::string& passwd, std::string &sslId, std::string &errString); - - /*! - * intialises directories for passwords and ssl keys - */ - static bool LoadPassword(const std::string& id, const std::string& passwd) ; + static bool LoadPassword(const std::string& passwd) ; /*! * Final Certificate load. This can be called if: * a) InitRetroshare() returns RS_INIT_HAVE_ACCOUNT -> autoLoad/password Set. - * b) SelectGPGAccount() && LoadPassword() + * b) or LoadPassword() * - * This wrapper is used to lock the profile first before - * finalising the login + * This uses the preferredId from RsAccounts. + * This wrapper also locks the profile before finalising the login */ static int LockAndLoadCertificates(bool autoLoginNT, std::string& lockFilePath); /*! * Post Login Options */ - static std::string RsConfigDirectory(); - static std::string RsConfigKeysDirectory(); - static std::string RsPGPDirectory(); - static std::string RsProfileConfigDirectory(); static bool getStartMinimised() ; static std::string getRetroShareLink(); @@ -144,26 +102,15 @@ class RsInit static void setAutoLogin(bool autoLogin); static bool RsClearAutoLogin() ; - /* used for static install data */ - static std::string getRetroshareDataDirectory(); - - static std::map > unsupported_keys ; private: - /* PreLogin */ - static std::string getHomePath() ; - static bool setupBaseDir(); - - /* Account Details */ - static bool get_configinit(const std::string& dir, std::string &id); - static bool create_configinit(const std::string& dir, const std::string& id); - - static bool setupAccount(const std::string& accountdir); - +#if 0 /* Auto Login */ static bool RsStoreAutoLogin() ; static bool RsTryAutoLogin() ; +#endif +// THESE CAN BE REMOVED FROM THE CLASS TOO. /* Lock/unlock profile directory */ static int LockConfigDirectory(const std::string& accountDir, std::string& lockFilePath); static void UnlockConfigDirectory(); @@ -173,4 +120,43 @@ class RsInit }; + + +/* Seperate Class for dealing with Accounts */ + +namespace RsAccounts +{ + // Directories. + std::string ConfigDirectory(); // aka Base Directory. (normally ~/.retroshare) + std::string DataDirectory(); + std::string PGPDirectory(); + std::string AccountDirectory(); + + // PGP Accounts. + int GetPGPLogins(std::list &pgpIds); + int GetPGPLoginDetails(const std::string& id, std::string &name, std::string &email); + bool GeneratePGPCertificate(const std::string&, const std::string& email, const std::string& passwd, std::string &pgpId, std::string &errString); + + // PGP Support Functions. + bool ExportIdentity(const std::string& fname,const std::string& pgp_id) ; + bool ImportIdentity(const std::string& fname,std::string& imported_pgp_id,std::string& import_error) ; + void GetUnsupportedKeys(std::map > &unsupported_keys); + bool CopyGnuPGKeyrings() ; + + // Rs Accounts + bool SelectAccount(const std::string &id); + + bool GetPreferredAccountId(std::string &id); + bool GetAccountIds(std::list &ids); + bool GetAccountDetails(const std::string &id, + std::string &gpgId, std::string &gpgName, + std::string &gpgEmail, std::string &location); + + bool GenerateSSLCertificate(const std::string& name, const std::string& org, const std::string& loc, const std::string& country, const bool ishiddenloc, const std::string& passwd, std::string &sslId, std::string &errString); + +}; + + + + #endif diff --git a/libretroshare/src/retroshare/rspeers.h b/libretroshare/src/retroshare/rspeers.h index a1a73f9e0..b7140a0f7 100644 --- a/libretroshare/src/retroshare/rspeers.h +++ b/libretroshare/src/retroshare/rspeers.h @@ -214,6 +214,7 @@ class RsPeerDetails bool isHiddenNode; std::string hiddenNodeAddress; + uint16_t hiddenNodePort; // Filled in for Standard Node. std::string localAddr; @@ -322,7 +323,9 @@ class RsPeers /* Network Stuff */ virtual bool connectAttempt(const std::string &ssl_id) = 0; virtual bool setLocation(const std::string &ssl_id, const std::string &location) = 0;//location is shown in the gui to differentiate ssl certs + virtual bool setHiddenNode(const std::string &id, const std::string &hidden_node_address) = 0; + virtual bool setHiddenNode(const std::string &id, const std::string &address, uint16_t port) = 0; virtual bool setLocalAddress(const std::string &ssl_id, const std::string &addr, uint16_t port) = 0; virtual bool setExtAddress( const std::string &ssl_id, const std::string &addr, uint16_t port) = 0; @@ -330,6 +333,9 @@ class RsPeers virtual bool setNetworkMode(const std::string &ssl_id, uint32_t netMode) = 0; virtual bool setVisState(const std::string &ssl_id, uint16_t vs_disc, uint16_t vs_dht) = 0; + virtual bool getProxyServer(std::string &addr, uint16_t &port) = 0; + virtual bool setProxyServer(const std::string &addr, const uint16_t port) = 0; + virtual void getIPServersList(std::list& ip_servers) = 0; virtual void allowServerIPDetermination(bool) = 0; virtual bool getAllowServerIPDetermination() = 0 ; diff --git a/libretroshare/src/rsserver/p3peers.cc b/libretroshare/src/rsserver/p3peers.cc index e4b4207e4..330ef1e6e 100644 --- a/libretroshare/src/rsserver/p3peers.cc +++ b/libretroshare/src/rsserver/p3peers.cc @@ -312,9 +312,10 @@ bool p3Peers::getPeerDetails(const std::string &id, RsPeerDetails &d) if (ps.hiddenNode) { d.isHiddenNode = true; - rs_sprintf(d.hiddenNodeAddress, "%s:%u", ps.hiddenDomain.c_str(), ps.hiddenPort); - d.localAddr = "hidden"; - d.localPort = 0; + d.hiddenNodeAddress = ps.hiddenDomain; + d.hiddenNodePort = ps.hiddenPort; + d.localAddr = sockaddr_storage_iptostring(ps.localaddr); + d.localPort = sockaddr_storage_port(ps.localaddr); d.extAddr = "hidden"; d.extPort = 0; d.dyndns = ""; @@ -323,6 +324,7 @@ bool p3Peers::getPeerDetails(const std::string &id, RsPeerDetails &d) { d.isHiddenNode = false; d.hiddenNodeAddress = ""; + d.hiddenNodePort = 0; d.localAddr = sockaddr_storage_iptostring(ps.localaddr); d.localPort = sockaddr_storage_port(ps.localaddr); @@ -732,6 +734,7 @@ bool p3Peers::setLocation(const std::string &ssl_id, const std::string &locatio return mPeerMgr->setLocation(ssl_id, location); } + bool p3Peers::setHiddenNode(const std::string &id, const std::string &hidden_node_address) { #ifdef P3PEERS_DEBUG @@ -770,6 +773,20 @@ bool p3Peers::setHiddenNode(const std::string &id, const std::string &hidden_no return true; } + +bool p3Peers::setHiddenNode(const std::string &id, const std::string &address, uint16_t port) +{ +#ifdef P3PEERS_DEBUG + std::cerr << "p3Peers::setHiddenNode() " << id << std::endl; +#endif + std::cerr << "p3Peers::setHiddenNode() Domain: " << address << " Port: " << port; + std::cerr << std::endl; + + mPeerMgr->setNetworkMode(id, RS_NET_MODE_HIDDEN); + mPeerMgr->setHiddenDomainPort(id, address, port); + return true; +} + bool p3Peers::setLocalAddress(const std::string &id, const std::string &addr_str, uint16_t port) { #ifdef P3PEERS_DEBUG @@ -864,8 +881,7 @@ bool p3Peers::setNetworkMode(const std::string &id, uint32_t extNetMode) } -bool -p3Peers::setVisState(const std::string &id, uint16_t vs_disc, uint16_t vs_dht) +bool p3Peers::setVisState(const std::string &id, uint16_t vs_disc, uint16_t vs_dht) { #ifdef P3PEERS_DEBUG std::cerr << "p3Peers::setVisState() " << id << std::endl; @@ -876,6 +892,52 @@ p3Peers::setVisState(const std::string &id, uint16_t vs_disc, uint16_t vs_dht) return mPeerMgr->setVisState(id, vs_disc, vs_dht); } +bool p3Peers::getProxyServer(std::string &addr, uint16_t &port) +{ + std::cerr << "p3Peers::getProxyServer()" << std::endl; + + struct sockaddr_storage proxy_addr; + mPeerMgr->getProxyServerAddress(proxy_addr); + addr = sockaddr_storage_iptostring(proxy_addr); + port = sockaddr_storage_port(proxy_addr); + return true; +} + +bool p3Peers::setProxyServer(const std::string &addr_str, const uint16_t port) +{ +#ifdef P3PEERS_DEBUG +#endif + std::cerr << "p3Peers::setProxyServer() " << std::endl; + + struct sockaddr_storage addr; + struct sockaddr_in *addrv4p = (struct sockaddr_in *) &addr; + addrv4p->sin_family = AF_INET; + addrv4p->sin_port = htons(port); + + int ret = 1; +/********************************** WINDOWS/UNIX SPECIFIC PART *******************/ +#ifndef WINDOWS_SYS + if (ret && (0 != inet_aton(addr_str.c_str(), &(addrv4p->sin_addr)))) +#else + addrv4p->sin_addr.s_addr = inet_addr(addr_str.c_str()); + if (ret) +#endif +/********************************** WINDOWS/UNIX SPECIFIC PART *******************/ + { + return mPeerMgr->setProxyServerAddress(addr); + } + else + { + std::cerr << "p3Peers::setProxyServer() Failed to Parse Address" << std::endl; + } + + return false; +} + + + + + //=========================================================================== /* Auth Stuff */ std::string @@ -988,6 +1050,7 @@ bool p3Peers::loadDetailsFromStringCert(const std::string &certstr, RsPeerDetai { pd.isHiddenNode = true; pd.hiddenNodeAddress = cert.hidden_node_string(); + //pd.hiddenNodePort = cert.hidden_node_port(); } else { diff --git a/libretroshare/src/rsserver/p3peers.h b/libretroshare/src/rsserver/p3peers.h index d81e74cfd..e438c3257 100644 --- a/libretroshare/src/rsserver/p3peers.h +++ b/libretroshare/src/rsserver/p3peers.h @@ -85,6 +85,7 @@ virtual bool removeFriendLocation(const std::string &sslId); virtual bool connectAttempt(const std::string &id); virtual bool setLocation(const std::string &ssl_id, const std::string &location);//location is shown in the gui to differentiate ssl certs virtual bool setHiddenNode(const std::string &id, const std::string &hidden_node_address); +virtual bool setHiddenNode(const std::string &id, const std::string &address, uint16_t port); virtual bool setLocalAddress(const std::string &id, const std::string &addr, uint16_t port); virtual bool setExtAddress(const std::string &id, const std::string &addr, uint16_t port); @@ -92,6 +93,9 @@ virtual bool setDynDNS(const std::string &id, const std::string &dyndns); virtual bool setNetworkMode(const std::string &id, uint32_t netMode); virtual bool setVisState(const std::string &id, uint16_t vs_disc, uint16_t vs_dht); +virtual bool getProxyServer(std::string &addr, uint16_t &port); +virtual bool setProxyServer(const std::string &addr, const uint16_t port); + virtual void getIPServersList(std::list& ip_servers) ; virtual void allowServerIPDetermination(bool) ; virtual bool getAllowServerIPDetermination() ; diff --git a/libretroshare/src/rsserver/rsaccounts.cc b/libretroshare/src/rsserver/rsaccounts.cc new file mode 100644 index 000000000..d3306757a --- /dev/null +++ b/libretroshare/src/rsserver/rsaccounts.cc @@ -0,0 +1,1317 @@ +/* + * libretroshare/src/rsserver/rsaccounts.cc + * + * RetroShare C++ Interface. + * + * Copyright 2013-2014 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.1 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". + * + */ + + +/********************************************************************* + * Libretroshare interface declared in rsaccounts.h. + * external interface in rsinit.h RsAccounts namespace. + * + */ + +#include +#include + +#include + +#include + +#include "retroshare/rsinit.h" +#include "rsaccounts.h" + +#include "util/rsdir.h" +#include "util/rsstring.h" +#include "util/folderiterator.h" + +#include "pqi/authssl.h" +#include "pqi/sslfns.h" +#include "pqi/authgpg.h" + + +// Global singleton declaration of data. +RsAccountsDetail rsAccounts; + +/* Uses private class - so must be hidden */ +static bool checkAccount(std::string accountdir, AccountDetails &account,std::map >& unsupported_keys); + +AccountDetails::AccountDetails() +:mIsHiddenLoc(false), mFirstRun(false) +{ + return; +} + +RsAccountsDetail::RsAccountsDetail() +:mAccountsLocked(false) +{ + return; +} + + +bool RsAccountsDetail::loadAccounts() +{ + int failing_accounts ; + + getAvailableAccounts(mAccounts,failing_accounts,mUnsupportedKeys); + + loadPreferredAccount(); + checkPreferredId(); + + if(failing_accounts > 0 && mAccounts.empty()) + return false; + + return true; +} + +bool RsAccountsDetail::lockPreferredAccount() +{ + if (checkPreferredId()) + { + mAccountsLocked = true; + return true; + } + + return false; +} + + +bool RsAccountsDetail::selectAccountByString(const std::string &prefUserString) +{ + std::string lower_case_user_string; + stringToLowerCase(prefUserString, lower_case_user_string) ; + std::string upper_case_user_string; + stringToUpperCase(prefUserString, upper_case_user_string) ; + + std::cerr << "RsAccountsDetail::selectAccountByString(" << prefUserString << ")"; + std::cerr << std::endl; + + if (mAccountsLocked) + { + std::cerr << "RsAccountsDetail::selectAccountByString() ERROR Accounts Locked"; + std::cerr << std::endl; + return false; + } + + + bool pgpNameFound = false; + std::map::const_iterator it; + for(it = mAccounts.begin() ; it!= mAccounts.end() ; it++) + { + std::cerr << "\tChecking account (pgpid = " << it->second.mPgpId; + std::cerr << ", name=" << it->second.mPgpName << ", sslId="; + std::cerr << it->second.mSslId << ")" << std::endl; + + if(prefUserString == it->second.mPgpName || + upper_case_user_string == it->second.mPgpId || + lower_case_user_string == it->second.mSslId) + { + mPreferredId = it->second.mSslId; + pgpNameFound = true; + } + } + return pgpNameFound; +} + + +bool RsAccountsDetail::selectId(const std::string preferredId) +{ + + if (mAccountsLocked) + { + std::cerr << "RsAccountsDetail::selectId() ERROR Accounts Locked"; + std::cerr << std::endl; + return false; + } + + std::map::const_iterator it; + it = mAccounts.find(preferredId); + + if (it != mAccounts.end()) + { + mPreferredId = preferredId; + return true; + } + else + { + return false; + } +} + + +bool RsAccountsDetail::checkPreferredId() +{ + std::map::const_iterator it; + it = mAccounts.find(mPreferredId); + + if (it != mAccounts.end()) + { + return true; + } + else + { + mPreferredId = ""; + return false; + } +} + +// initial configuration bootstrapping... + +const std::string kPathPGPDirectory = "pgp"; +const std::string kPathKeyDirectory = "keys"; + +const std::string kFilenamePreferredAccount = "default_cert.txt"; +const std::string kFilenameKey = "user_pk.pem"; +const std::string kFilenameCert = "user_cert.pem"; + + +/********************************************************************* + * Directories... based on current PreferredId. + */ + +std::string RsAccountsDetail::PathPGPDirectory() +{ + return mBaseDirectory + "/" + kPathPGPDirectory; +} + + +std::string RsAccountsDetail::PathBaseDirectory() +{ + return mBaseDirectory; +} + + +std::string RsAccountsDetail::PathAccountDirectory() +{ + std::string path; + + std::map::const_iterator it; + it = mAccounts.find(mPreferredId); + if (it == mAccounts.end()) + { + return path; + } + + path = mBaseDirectory + "/"; + path += it->second.mAccountDir; + return path; +} + +std::string RsAccountsDetail::PathAccountKeysDirectory() +{ + std::string path = PathAccountDirectory(); + if (path.empty()) + { + return path; + } + + path += "/" + kPathKeyDirectory; + return path; +} + +std::string RsAccountsDetail::PathKeyFile() +{ + std::string path = PathAccountKeysDirectory(); + if (path.empty()) + { + return path; + } + + path += "/" + kFilenameKey; + return path; +} + +std::string RsAccountsDetail::PathCertFile() +{ + std::string path = PathAccountKeysDirectory(); + if (path.empty()) + { + return path; + } + path += "/" + kFilenameCert; + return path; +} + + + +/********************************************************************* + * Setup Base Directories. + * + */ + +bool RsAccountsDetail::setupBaseDirectory(std::string alt_basedir) +{ + if (alt_basedir.empty()) + { + if (!defaultBaseDirectory()) + { + std::cerr << "RsAccounts::setupBaseDirectory() Cannot find defaultBaseDirectory"; + std::cerr << std::endl; + return false; + } + } + else + { + mBaseDirectory = alt_basedir; + } + + if (!RsDirUtil::checkCreateDirectory(mBaseDirectory)) + { + std::cerr << "RsAccounts::setupBaseDirectory() Cannot Create BaseConfig Dir:" << mBaseDirectory; + std::cerr << std::endl; + return false ; + } + return true ; +} + + + + +bool RsAccountsDetail::defaultBaseDirectory() +{ + std::string basedir; + +/******************************** WINDOWS/UNIX SPECIFIC PART ******************/ +#ifndef WINDOWS_SYS + + // unix: homedir + /.retroshare + char *h = getenv("HOME"); + if (h == NULL) + { + std::cerr << "defaultBaseDirectory() Error: "; + std::cerr << "cannot determine $HOME dir" < &ids) +{ + std::map::iterator it; + std::cerr << "getAccountIds:" << std::endl; + + for(it = mAccounts.begin(); it != mAccounts.end(); it++) + { + std::cerr << "SSL Id: " << it->second.mSslId << " PGP Id " << it->second.mPgpId; + std::cerr << " PGP Name: " << it->second.mPgpName; + std::cerr << " PGP Email: " << it->second.mPgpEmail; + std::cerr << " Location: " << it->second.mLocation; + std::cerr << std::endl; + + ids.push_back(it->first); + } + return true; +} + + +bool RsAccountsDetail::getAccountDetails(const std::string &id, + std::string &gpgId, std::string &gpgName, + std::string &gpgEmail, std::string &location) +{ + std::map::iterator it; + it = mAccounts.find(id); + if (it != mAccounts.end()) + { + gpgId = it->second.mPgpId; + gpgName = it->second.mPgpName; + gpgEmail = it->second.mPgpEmail; + location = it->second.mLocation; + return true; + } + return false; +} + +bool RsAccountsDetail::getAccountOptions(bool &ishidden, bool isFirstTimeRun) +{ + std::map::iterator it; + it = mAccounts.find(mPreferredId); + if (it != mAccounts.end()) + { + ishidden = it->second.mIsHiddenLoc; + isFirstTimeRun = it->second.mFirstRun; + return true; + } + return false; +} + + +/* directories with valid certificates in the expected location */ +bool RsAccountsDetail::getAvailableAccounts(std::map &accounts,int& failing_accounts,std::map >& unsupported_keys) +{ + failing_accounts = 0 ; + /* get the directories */ + std::list directories; + std::list::iterator it; + + std::cerr << "RsAccounts::getAvailableAccounts()"; + std::cerr << std::endl; + + /* now iterate through the directory... + * directories - flags as old, + * files checked to see if they have changed. (rehashed) + */ + + /* check for the dir existance */ + librs::util::FolderIterator dirIt(mBaseDirectory); + if (!dirIt.isValid()) + { + std::cerr << "Cannot Open Base Dir - No Available Accounts" << std::endl; + return false ; + } + + struct stat64 buf; + + while (dirIt.readdir()) + { + /* check entry type */ + std::string fname; + dirIt.d_name(fname); + std::string fullname = mBaseDirectory + "/" + fname; +#ifdef FIM_DEBUG + std::cerr << "calling stats on " << fullname <length() != 32 + 6) + { + std::cerr << "getAvailableAccounts() Skipping Invalid sized dir: " << *it << std::endl; + continue; + } + + std::string prefix = (*it).substr(0, 6); + std::string lochex = (*it).substr(6); // rest of string. + + bool hidden_location = false; + bool valid_prefix = false; + if (prefix == "LOC06_") + { + valid_prefix = true; + } + else if (prefix == "HID06_") + { + valid_prefix = true; + hidden_location = true; + } + else + { + std::cerr << "getAvailableAccounts() Skipping Invalid Prefix dir: " << *it << std::endl; + continue; + } + + if(valid_prefix && isHexaString(lochex) && (lochex).length() == 32) + { + std::string accountdir = mBaseDirectory + "/" + *it; +#ifdef GPG_DEBUG + std::cerr << "getAvailableAccounts() Checking: " << *it << std::endl; +#endif + + AccountDetails tmpId; + tmpId.mIsHiddenLoc = hidden_location; + tmpId.mAccountDir = *it; + if (checkAccount(accountdir, tmpId,unsupported_keys)) + { +#ifdef GPG_DEBUG + std::cerr << "getAvailableAccounts() Accepted: " << *it << std::endl; +#endif + + std::map::iterator ait; + ait = accounts.find(tmpId.mSslId); + if (ait != accounts.end()) + { + std::cerr << "getAvailableAccounts() ERROR Duplicate SSLIDs"; + std::cerr << " - only one will be available"; + std::cerr << std::endl; + std::cerr << " ID1 (overridden) : " << ait->first << " Directory: " << ait->second.mAccountDir; + std::cerr << std::endl; + std::cerr << " ID2 (available) : " << tmpId.mSslId << " Directory: " << tmpId.mAccountDir; + std::cerr << std::endl; + + } + + accounts[tmpId.mSslId] = tmpId; + } + else + ++failing_accounts ; + } +#ifdef GPG_DEBUG + else + std::cerr << "Skipped non SSLid directory " << *it << std::endl; +#endif + } + return true; +} + + + +static bool checkAccount(std::string accountdir, AccountDetails &account,std::map >& unsupported_keys) +{ + /* check if the cert/key file exists */ + + // Create the filename. + std::string basename = accountdir + "/"; + basename += kPathKeyDirectory + "/"; + basename += "user"; + + std::string cert_name = basename + "_cert.pem"; + std::string userName, userId; + +#ifdef AUTHSSL_DEBUG + std::cerr << "checkAccount() dir: " << accountdir << std::endl; +#endif + bool ret = false; + + /* check against authmanagers private keys */ + if (LoadCheckX509(cert_name.c_str(), account.mPgpId, account.mLocation, account.mSslId)) + { +#ifdef AUTHSSL_DEBUG + std::cerr << "location: " << account.mLocation << " id: " << account.mSslId << std::endl; + std::cerr << "issuerName: " << account.mPgpId << " id: " << account.mSslId << std::endl; +#endif + + if(! rsAccounts.GetPGPLoginDetails(account.mPgpId, account.mPgpName, account.mPgpEmail)) + return false ; + + if(!AuthGPG::getAuthGPG()->haveSecretKey(account.mPgpId)) + return false ; + + if(!AuthGPG::getAuthGPG()->isKeySupported(account.mPgpId)) + { + std::string keystring = account.mPgpId + " " + account.mPgpName + "<" + account.mPgpEmail ; + unsupported_keys[keystring].push_back("Location: " + account.mLocation + "  (" + account.mSslId + ")") ; + return false ; + } + +#ifdef GPG_DEBUG + std::cerr << "PGPLoginDetails: " << account.mPgpId << " name: " << account.mPgpName; + std::cerr << " email: " << account.mPgpEmail << std::endl; +#endif + ret = true; + } + else + { + std::cerr << "GetIssuerName FAILED!" << std::endl; + ret = false; + } + + return ret; +} + + + + + +/**************************** Access Functions for Init Data **************************/ +/**************************** Private Functions for InitRetroshare ********************/ +/**************************** Private Functions for InitRetroshare ********************/ + + +/*********************************************************** + * This Directory is used to store data and "template" file that Retroshare requires. + * These files will either be copied into Retroshare's configuration directory, + * if they are to be modified. Or used directly, if read-only. + * + * This will initially be used for the DHT bootstrap file. + * + * Please modify the code below to suit your platform! + * + * WINDOWS: + * WINDOWS PORTABLE: + * Linux: + * OSX: + + ***********/ + +#ifdef __APPLE__ + /* needs CoreFoundation Framework */ + #include + //#include + //#include +#endif + +std::string RsAccountsDetail::PathDataDirectory() +{ + std::string dataDirectory; + +/******************************** WINDOWS/UNIX SPECIFIC PART ******************/ +#ifndef WINDOWS_SYS + + #ifdef __APPLE__ + /* NOTE: OSX also qualifies as BSD... so this #ifdef must be before the BSD check. */ + + /* For OSX, applications are Bundled in a directory... + * need to get the path to the executable Bundle. + * + * Code nicely supplied by Qt! + */ + + CFURLRef pluginRef = CFBundleCopyBundleURL(CFBundleGetMainBundle()); + CFStringRef macPath = CFURLCopyFileSystemPath(pluginRef, + kCFURLPOSIXPathStyle); + const char *pathPtr = CFStringGetCStringPtr(macPath, + CFStringGetSystemEncoding()); + dataDirectory = pathPtr; + CFRelease(pluginRef); + CFRelease(macPath); + + dataDirectory += "/Contents/Resources"; + std::cerr << "getRetroshareDataDirectory() OSX: " << dataDirectory; + + #elif (defined(BSD) && (BSD >= 199103)) + /* For BSD, the default is LOCALBASE which will be set + * before compilation via the ports/pkg-src mechanisms. + * For compilation without ports/pkg-src it is set to + * /usr/local (default on Open and Free; Net has /usr/pkg) + */ + dataDirectory = "/usr/local/share/retroshare"; + std::cerr << "getRetroshareDataDirectory() BSD: " << dataDirectory; + + #else + /* For Linux, we have a fixed standard data directory */ + dataDirectory = "/usr/share/RetroShare"; + std::cerr << "getRetroshareDataDirectory() Linux: " << dataDirectory; + + #endif +#else +// if (RsInitConfig::portable) +// { +// /* For Windows Portable, files must be in the data directory */ +// dataDirectory = "Data"; +// std::cerr << "getRetroshareDataDirectory() WINDOWS PORTABLE: " << dataDirectory; +// std::cerr << std::endl; +// } +// else +// { +// /* For Windows: environment variable APPDATA should be suitable */ +// dataDirectory = getenv("APPDATA"); +// dataDirectory += "\\RetroShare"; +// +// std::cerr << "getRetroshareDataDirectory() WINDOWS: " << dataDirectory; +// std::cerr << std::endl; +// } + + /* Use RetroShare's exe dir */ + dataDirectory = "."; +#endif +/******************************** WINDOWS/UNIX SPECIFIC PART ******************/ + + /* Make sure the directory exists, else return emptyString */ + if (!RsDirUtil::checkDirectory(dataDirectory)) + { + std::cerr << "Data Directory not Found: " << dataDirectory << std::endl; + dataDirectory = ""; + } + else + { + std::cerr << "Data Directory Found: " << dataDirectory << std::endl; + } + + return dataDirectory; +} + + + +/*****************************************************************************/ +/*****************************************************************************/ +/************************* Generating Certificates ***************************/ +/*****************************************************************************/ +/*****************************************************************************/ + + + /* Generating GPGme Account */ +int RsAccountsDetail::GetPGPLogins(std::list &pgpIds) { + AuthGPG::getAuthGPG()->availableGPGCertificatesWithPrivateKeys(pgpIds); + return 1; +} + +int RsAccountsDetail::GetPGPLoginDetails(const std::string& id, std::string &name, std::string &email) +{ + #ifdef GPG_DEBUG + std::cerr << "RsInit::GetPGPLoginDetails for \"" << id << "\"" << std::endl; + #endif + + bool ok = true ; + name = AuthGPG::getAuthGPG()->getGPGName(id,&ok); + if(!ok) + return 0 ; + email = AuthGPG::getAuthGPG()->getGPGEmail(id,&ok); + if(!ok) + return 0 ; + + if (name != "") { + return 1; + } else { + return 0; + } +} + + + +/* Before any SSL stuff can be loaded, the correct PGP must be selected / generated: + **/ + +bool RsAccountsDetail::SelectPGPAccount(const std::string& pgpId) +{ + bool retVal = false; + + if (0 < AuthGPG::getAuthGPG() -> GPGInit(pgpId)) + { + retVal = true; + std::cerr << "PGP Auth Success!"; + } + else + std::cerr << "PGP Auth Failed!"; + + std::cerr << " ID: " << pgpId << std::endl; + + return retVal; +} + + +bool RsAccountsDetail::GeneratePGPCertificate(const std::string& name, const std::string& email, const std::string& passwd, std::string &pgpId, std::string &errString) +{ + return AuthGPG::getAuthGPG()->GeneratePGPCertificate(name, email, passwd, pgpId, errString); +} + + // PGP Support Functions. +void RsAccountsDetail::getUnsupportedKeys(std::map > &unsupported_keys) +{ + unsupported_keys = mUnsupportedKeys; + return; +} + +bool RsAccountsDetail::exportIdentity(const std::string& fname,const std::string& id) +{ + return AuthGPG::getAuthGPG()->exportProfile(fname,id); +} + +bool RsAccountsDetail::importIdentity(const std::string& fname,std::string& id,std::string& import_error) +{ + return AuthGPG::getAuthGPG()->importProfile(fname,id,import_error); +} + +bool RsAccountsDetail::copyGnuPGKeyrings() +{ + std::string pgp_dir = PathPGPDirectory() ; + + if(!RsDirUtil::checkCreateDirectory(pgp_dir)) + throw std::runtime_error("Cannot create pgp directory " + pgp_dir) ; + + std::string source_public_keyring; + std::string source_secret_keyring; + +#ifdef WINDOWS_SYS + if (RsInit::isPortable()) + { + source_public_keyring = RsInit::RsConfigDirectory() + "/gnupg/pubring.gpg"; + source_secret_keyring = RsInit::RsConfigDirectory() + "/gnupg/secring.gpg" ; + } else { + source_public_keyring = RsInitConfig::basedir + "/../gnupg/pubring.gpg" ; + source_secret_keyring = RsInitConfig::basedir + "/../gnupg/secring.gpg" ; + } +#else + char *env_gnupghome = getenv("GNUPGHOME") ; + + if(env_gnupghome != NULL) + { + std::cerr << "looking into $GNUPGHOME/" << std::endl; + + source_public_keyring = std::string(env_gnupghome) + "/pubring.gpg" ; + source_secret_keyring = std::string(env_gnupghome) + "/secring.gpg" ; + } + else + { + char *env_homedir = getenv("HOME") ; + + if(env_homedir != NULL) + { + std::cerr << "looking into $HOME/.gnupg/" << std::endl; + std::string home_dir(env_homedir) ; + + // We need a specific part for MacOS and Linux as well + source_public_keyring = home_dir + "/.gnupg/pubring.gpg" ; + source_secret_keyring = home_dir + "/.gnupg/secring.gpg" ; + } + else + return false ; + } +#endif + + if(!RsDirUtil::copyFile(source_public_keyring,pgp_dir + "/retroshare_public_keyring.gpg")) + { + std::cerr << "Cannot copy pub keyring " << source_public_keyring << " to destination file " << pgp_dir + "/retroshare_public_keyring.gpg. If you believe your keyring is in a different place, please make the copy yourself." << std::endl; + return false ; + } + if(!RsDirUtil::copyFile(source_secret_keyring,pgp_dir + "/retroshare_secret_keyring.gpg")) + { + std::cerr << "Cannot copy sec keyring " << source_secret_keyring << " to destination file " << pgp_dir + "/retroshare_secret_keyring.gpg. your keyring is in a different place, please make the copy yourself." << std::endl; + return false ; + } + + return true ; +} + + + + /* Create SSL Certificates */ +bool RsAccountsDetail::GenerateSSLCertificate(const std::string& pgp_id, const std::string& org, const std::string& loc, const std::string& country, const bool ishiddenloc, const std::string& passwd, std::string &sslId, std::string &errString) +{ + /* select the PGP Identity first */ + if (!SelectPGPAccount(pgp_id)) + { + errString = "Invalid PGP Identity"; + return false; + } + + // generate the private_key / certificate. + // save to file. + // + // then load as if they had entered a passwd. + + // check password. + if (passwd.length() < 4) + { + errString = "Password is Unsatisfactory (must be 4+ chars)"; + return false; + } + + int nbits = 2048; + + std::string pgp_name = AuthGPG::getAuthGPG()->getGPGName(pgp_id); + + // Create the filename ..... + // Temporary Directory for creating files.... + std::string tmpdir = "TMPCFG"; + + std::string tmpbase = mBaseDirectory + "/" + tmpdir + "/"; + + if(!setupAccount(tmpbase)) + return false ; + + /* create directory structure */ + std::string keypath = tmpbase + kPathKeyDirectory + "/"; + std::string key_name = keypath + kFilenameKey; + std::string cert_name = keypath + kFilenameCert; + + bool gen_ok = false; + + /* Extra step required for SSL + PGP, user must have selected + * or generated a suitable key so the signing can happen. + */ + + X509_REQ *req = GenerateX509Req( + key_name.c_str(), + passwd.c_str(), + pgp_name.c_str(), + "", //ui -> gen_email -> value(), + org.c_str(), + loc.c_str(), + "", //ui -> gen_state -> value(), + country.c_str(), + nbits, errString); + + if (req == NULL) + { + fprintf(stderr,"RsGenerateCert() Couldn't create Request. Reason: %s\n", errString.c_str()); + return false; + } + + long days = 3000; + X509 *x509 = AuthSSL::getAuthSSL()->SignX509ReqWithGPG(req, days); + + X509_REQ_free(req); + if (x509 == NULL) { + fprintf(stderr,"RsGenerateCert() Couldn't sign ssl certificate. Probably PGP password is wrong.\n"); + return false; + } + + /* save to file */ + if (x509) + { + gen_ok = true; + + /* Print the signed Certificate! */ + BIO *bio_out = NULL; + bio_out = BIO_new(BIO_s_file()); + BIO_set_fp(bio_out,stdout,BIO_NOCLOSE); + + /* Print it out */ + int nmflag = 0; + int reqflag = 0; + + X509_print_ex(bio_out, x509, nmflag, reqflag); + + BIO_flush(bio_out); + BIO_free(bio_out); + + } + else + { + gen_ok = false; + } + + if (gen_ok) + { + /* Save cert to file */ + // open the file. + FILE *out = NULL; + if (NULL == (out = RsDirUtil::rs_fopen(cert_name.c_str(), "w"))) + { + fprintf(stderr,"RsGenerateCert() Couldn't create Cert File"); + fprintf(stderr," : %s\n", cert_name.c_str()); + gen_ok = false; + } + + if (!PEM_write_X509(out,x509)) + { + fprintf(stderr,"RsGenerateCert() Couldn't Save Cert"); + fprintf(stderr," : %s\n", cert_name.c_str()); + gen_ok = false; + } + + fclose(out); + X509_free(x509); + } + + if (!gen_ok) + { + errString = "Generation of Certificate Failed"; + return false; + } + + /* try to load it, and get Id */ + + std::string location; + std::string pgpid_retrieved; + if (LoadCheckX509(cert_name.c_str(), pgpid_retrieved, location, sslId) == 0) { + std::cerr << "RsInit::GenerateSSLCertificate() Cannot check own signature, maybe the files are corrupted." << std::endl; + return false; + } + + /* Move directory to correct id */ + std::string accountdir; + if (ishiddenloc) + { + accountdir = "HID06_" + sslId; + } + else + { + accountdir = "LOC06_" + sslId; + } + + std::string fullAccountDir = mBaseDirectory + "/" + accountdir; + std::string finalbase = fullAccountDir + "/"; + + /* Rename Directory */ + std::cerr << "Mv Config Dir from: " << tmpbase << " to: " << finalbase; + std::cerr << std::endl; + + if (!RsDirUtil::renameFile(tmpbase, finalbase)) + { + std::cerr << "rename FAILED" << std::endl; + } + + AccountDetails newAccount; + + newAccount.mSslId = sslId; + newAccount.mAccountDir = accountdir; + newAccount.mPgpId = pgp_id; + + newAccount.mLocation = loc; + newAccount.mIsHiddenLoc = ishiddenloc; + + newAccount.mFirstRun = true; + + // rest of newAccount pgp filled in checkAccount. + if (!checkAccount(fullAccountDir, newAccount, mUnsupportedKeys)) + { + std::cerr << "RsInit::GenerateSSLCertificate() Cannot check own signature, maybe the files are corrupted." << std::endl; + return false; + } + + mAccounts[newAccount.mSslId] = newAccount; + mPreferredId = newAccount.mSslId; + + std::cerr << "RetroShare has Successfully generated a Certficate/Key" << std::endl; + std::cerr << "\tCert Located: " << cert_name << std::endl; + std::cerr << "\tLocated: " << key_name << std::endl; + + return true; +} + + +/******************* PRIVATE FNS TO HELP with GEN **************/ +bool RsAccountsDetail::setupAccount(const std::string& accountdir) +{ + /* actual config directory isd */ + + std::string subdir1 = accountdir + "/"; + subdir1 += kPathKeyDirectory; + + std::string subdir3 = accountdir + "/"; + subdir3 += "cache"; + + std::string subdir4 = subdir3 + "/"; + std::string subdir5 = subdir3 + "/"; + subdir4 += "local"; + subdir5 += "remote"; + + // fatal if cannot find/create. + std::cerr << "Checking For Directories" << std::endl; + if (!RsDirUtil::checkCreateDirectory(accountdir)) + { + std::cerr << "Cannot Create BaseConfig Dir" << std::endl; + return false ; + } + if (!RsDirUtil::checkCreateDirectory(subdir1)) + { + std::cerr << "Cannot Create Config/Key Dir" << std::endl; + return false ; + } + if (!RsDirUtil::checkCreateDirectory(subdir3)) + { + std::cerr << "Cannot Create Config/Cache Dir" << std::endl; + return false ; + } + if (!RsDirUtil::checkCreateDirectory(subdir4)) + { + std::cerr << "Cannot Create Config/Cache/local Dir" << std::endl; + return false ; + } + if (!RsDirUtil::checkCreateDirectory(subdir5)) + { + std::cerr << "Cannot Create Config/Cache/remote Dir" << std::endl; + return false ; + } + + return true; +} + + + + + + +/***************************** FINAL LOADING OF SETUP *************************/ + +#if 0 + /* Login SSL */ +bool RsInit::LoadPassword(const std::string& id, const std::string& inPwd) +{ + /* select configDir */ + + RsInitConfig::preferredId = id; + + std::map::iterator it = RsInitConfig::accountIds.find(id); + if (it == RsInitConfig::accountIds.end()) + { + std::cerr << "RsInit::LoadPassword() Cannot Locate Identity: " << id; + std::cerr << std::endl; + exit(1); + } + + std::string accountdir = it->second.accountDir; + + RsInitConfig::configDir = RsInitConfig::basedir + "/" + accountdir; + RsInitConfig::passwd = inPwd; + + // if(inPwd != "") + // RsInitConfig::havePasswd = true; + + // Create the filename. + std::string basename = RsInitConfig::configDir + "/"; + basename += configKeyDir + "/"; + basename += "user"; + + RsInitConfig::load_key = basename + "_pk.pem"; + RsInitConfig::load_cert = basename + "_cert.pem"; + + return true; +} +#endif + + + +std::string RsAccountsDetail::getHomePath() +{ + std::string home; +/******************************** WINDOWS/UNIX SPECIFIC PART ******************/ +#ifndef WINDOWS_SYS /* UNIX */ + + home = getenv("HOME"); + +#else /* Windows */ + + char *h2 = getenv("HOMEDRIVE"); + std::cerr << "getHomePath() -> $HOMEDRIVE = " << h2 << std::endl; + char *h3 = getenv("HOMEPATH"); + std::cerr << "getHomePath() -> $HOMEPATH = " << h3 << std::endl; + + if (h2 == NULL) + { + // Might be Win95/98 + // generate default. + home = "C:\\Retro"; + } + else + { + home = h2; + home += h3; + home += "\\Desktop"; + } + + std::cerr << "fltkserver::getHomePath() -> " << home << std::endl; + + // convert to desired format. + home = RsDirUtil::convertPathToUnix(home); +#endif +/******************************** WINDOWS/UNIX SPECIFIC PART ******************/ + return home; +} + + + +/********************************************************************************* + * PUBLIC INTERFACE FUNCTIONS + ********************************************************************************/ + + // Directories. +std::string RsAccounts::ConfigDirectory() { return rsAccounts.PathBaseDirectory(); } +std::string RsAccounts::DataDirectory() { return rsAccounts.PathDataDirectory(); } +std::string RsAccounts::PGPDirectory() { return rsAccounts.PathPGPDirectory(); } +std::string RsAccounts::AccountDirectory() { return rsAccounts.PathAccountDirectory(); } + +// PGP Accounts. +int RsAccounts::GetPGPLogins(std::list &pgpIds) +{ + return rsAccounts.GetPGPLogins(pgpIds); +} + +int RsAccounts::GetPGPLoginDetails(const std::string& id, std::string &name, std::string &email) +{ + return rsAccounts.GetPGPLoginDetails(id, name, email); +} + +bool RsAccounts::GeneratePGPCertificate(const std::string &name, const std::string& email, const std::string& passwd, std::string &pgpId, std::string &errString) +{ + return rsAccounts.GeneratePGPCertificate(name, email, passwd, pgpId, errString); +} + +// PGP Support Functions. +bool RsAccounts::ExportIdentity(const std::string& fname,const std::string& pgp_id) +{ + return rsAccounts.exportIdentity(fname,pgp_id); +} + +bool RsAccounts::ImportIdentity(const std::string& fname,std::string& imported_pgp_id,std::string& import_error) +{ + return rsAccounts.importIdentity(fname,imported_pgp_id,import_error); +} + +void RsAccounts::GetUnsupportedKeys(std::map > &unsupported_keys) +{ + return rsAccounts.getUnsupportedKeys(unsupported_keys); +} + +bool RsAccounts::CopyGnuPGKeyrings() +{ + return rsAccounts.copyGnuPGKeyrings(); +} + +// Rs Accounts +bool RsAccounts::SelectAccount(const std::string &id) +{ + return rsAccounts.selectId(id); +} + +bool RsAccounts::GetPreferredAccountId(std::string &id) +{ + return rsAccounts.getPreferredAccountId(id); +} + +bool RsAccounts::GetAccountIds(std::list &ids) +{ + return rsAccounts.getAccountIds(ids); +} + +bool RsAccounts::GetAccountDetails(const std::string &id, + std::string &pgpId, std::string &pgpName, + std::string &pgpEmail, std::string &location) +{ + return rsAccounts.getAccountDetails(id, pgpId, pgpName, pgpEmail, location); +} + +bool RsAccounts::GenerateSSLCertificate(const std::string& pgp_id, const std::string& org, const std::string& loc, const std::string& country, const bool ishiddenloc, const std::string& passwd, std::string &sslId, std::string &errString) +{ + return rsAccounts.GenerateSSLCertificate(pgp_id, org, loc, country, ishiddenloc, passwd, sslId, errString); +} + +/********************************************************************************* + * END OF: PUBLIC INTERFACE FUNCTIONS + ********************************************************************************/ + diff --git a/libretroshare/src/rsserver/rsaccounts.h b/libretroshare/src/rsserver/rsaccounts.h new file mode 100644 index 000000000..aea820aa6 --- /dev/null +++ b/libretroshare/src/rsserver/rsaccounts.h @@ -0,0 +1,152 @@ +/* + * libretroshare/src/rsserver/rsaccounts.h + * + * RetroShare C++ Interface. + * + * Copyright 2013-2014 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.1 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". + * + */ + + +/********************************************************************* + * Header providing interface for libretroshare access to RsAccounts stuff. + * External access must be through rsinit.g where a RsAccounts namespace + fns + * are available. + * + */ + +#pragma once + +#include +#include +#include + +class AccountDetails +{ + public: + AccountDetails(); + + std::string mSslId; + std::string mAccountDir; + + std::string mPgpId; + std::string mPgpName; + std::string mPgpEmail; + + std::string mLocation; + bool mIsHiddenLoc; + bool mFirstRun; + +}; + +class RsAccountsDetail +{ + public: + RsAccountsDetail(); + + // These functions are externally accessible via RsAccounts namespace. + + + + // These functions are accessible from inside libretroshare. + + bool setupBaseDirectory(std::string alt_basedir); + bool loadAccounts(); + bool lockPreferredAccount(); + + // Paths. + std::string PathDataDirectory(); + std::string PathBaseDirectory(); + + // PGP Path is only dependent on BaseDirectory. + std::string PathPGPDirectory(); + + // Below are dependent on mPreferredId. + std::string PathAccountDirectory(); + std::string PathAccountKeysDirectory(); + std::string PathKeyFile(); + std::string PathCertFile(); + + // PGP Accounts. + + int GetPGPLogins(std::list &pgpIds); + int GetPGPLoginDetails(const std::string& id, std::string &name, std::string &email); + bool GeneratePGPCertificate(const std::string&, const std::string& email, const std::string& passwd, std::string &pgpId, std::string &errString); + + bool SelectPGPAccount(const std::string& pgpId); + + // PGP Support Functions. + bool exportIdentity(const std::string& fname,const std::string& pgp_id) ; + bool importIdentity(const std::string& fname,std::string& imported_pgp_id,std::string& import_error) ; + void getUnsupportedKeys(std::map > &unsupported_keys); + bool copyGnuPGKeyrings() ; + + + // Selecting Rs Account. + bool selectAccountByString(const std::string &prefUserString); + bool selectId(const std::string preferredId); + + // Details of Rs Account. + bool getPreferredAccountId(std::string &id); + bool getAccountDetails(const std::string &id, + std::string &gpgId, std::string &gpgName, + std::string &gpgEmail, std::string &location); + + bool getAccountOptions(bool &ishidden, bool isFirstTimeRun); + + + bool getAccountIds(std::list &ids); + + bool GenerateSSLCertificate(const std::string& gpg_id, + const std::string& org, const std::string& loc, + const std::string& country, const bool ishiddenloc, + const std::string& passwd, std::string &sslId, + std::string &errString); + + // From init file. + bool storePreferredAccount(); + bool loadPreferredAccount(); + + private: + bool checkPreferredId(); + + bool defaultBaseDirectory(); + + std::string getHomePath() ; + + bool getAvailableAccounts(std::map &accounts, + int& failing_accounts, + std::map >& unsupported_keys); + + bool setupAccount(const std::string& accountdir); + + private: + + bool mAccountsLocked; + + std::map mAccounts; + std::string mPreferredId; + std::string mBaseDirectory; + + std::map > mUnsupportedKeys ; +}; + +// Global singleton declaration of data. +extern RsAccountsDetail rsAccounts; + diff --git a/libretroshare/src/rsserver/rsinit.cc b/libretroshare/src/rsserver/rsinit.cc index 6b972691f..3e6309f36 100644 --- a/libretroshare/src/rsserver/rsinit.cc +++ b/libretroshare/src/rsserver/rsinit.cc @@ -43,7 +43,9 @@ #include "util/rsstring.h" #include "retroshare/rsinit.h" #include "plugins/pluginmanager.h" + #include "rsserver/rsloginhandler.h" +#include "rsserver/rsaccounts.h" #include #include @@ -72,45 +74,21 @@ // #define AUTHSSL_DEBUG // #define FIM_DEBUG -class accountId -{ - public: - std::string pgpId; - std::string pgpName; - std::string pgpEmail; - std::string sslId; - std::string location; -}; - -std::map > RsInit::unsupported_keys ; +//std::map > RsInit::unsupported_keys ; class RsInitConfig { public: - /* Directories (SetupBaseDir) */ - static std::string basedir; - static std::string homePath; + static std::string main_executable_hash; + #ifdef WINDOWS_SYS static bool portable; static bool isWindowsXP; #endif - - static std::list accountIds; - static std::string preferedId; - - /* for certificate creation */ - //static std::string gpgPasswd; - static rs_lock_handle_t lockHandle; - /* These fields are needed for login */ - static std::string loginId; - static std::string configDir; - static std::string load_cert; - static std::string load_key; - static std::string passwd; static std::string gxs_passwd; @@ -128,7 +106,7 @@ class RsInitConfig static std::string inet ; /* v0.6 features */ - static bool forceApiUpgrade; + static bool hiddenNodeSet; static std::string hiddenNodeAddress; static uint16_t hiddenNodePort; @@ -138,7 +116,6 @@ class RsInitConfig static int debugLevel; static std::string logfname; - static bool firsttime_run; static bool load_trustedpeer; static std::string load_trustedpeer_file; @@ -151,36 +128,28 @@ class RsInitConfig const int p3facestartupzone = 47238; // initial configuration bootstrapping... -static const std::string configInitFile = "default_cert.txt"; -static const std::string configConfFile = "config.rs"; -static const std::string configCertDir = "friends"; -static const std::string configKeyDir = "keys"; -static const std::string configCaFile = "cacerts.pem"; +//static const std::string configInitFile = "default_cert.txt"; +//static const std::string configConfFile = "config.rs"; +//static const std::string configCertDir = "friends"; +//static const std::string configKeyDir = "keys"; +//static const std::string configCaFile = "cacerts.pem"; +//static const std::string configHelpName = "retro.htm"; + static const std::string configLogFileName = "retro.log"; -static const std::string configHelpName = "retro.htm"; static const int SSLPWD_LEN = 64; -std::list RsInitConfig::accountIds; -std::string RsInitConfig::preferedId; std::string RsInitConfig::main_executable_hash; rs_lock_handle_t RsInitConfig::lockHandle; -std::string RsInitConfig::configDir; -std::string RsInitConfig::load_cert; -std::string RsInitConfig::load_key; - std::string RsInitConfig::passwd; std::string RsInitConfig::gxs_passwd; -//std::string RsInitConfig::gpgPasswd; bool RsInitConfig::autoLogin; /* autoLogin allowed */ bool RsInitConfig::startMinimised; /* Icon or Full Window */ std::string RsInitConfig::RetroShareLink; /* Directories */ -std::string RsInitConfig::basedir; -std::string RsInitConfig::homePath; #ifdef WINDOWS_SYS bool RsInitConfig::portable = false; bool RsInitConfig::isWindowsXP = false; @@ -193,7 +162,7 @@ unsigned short RsInitConfig::port; std::string RsInitConfig::inet; /* v0.6 features */ -bool RsInitConfig::forceApiUpgrade = false; +bool RsInitConfig::hiddenNodeSet = false; std::string RsInitConfig::hiddenNodeAddress; uint16_t RsInitConfig::hiddenNodePort; @@ -203,17 +172,12 @@ bool RsInitConfig::outStderr; int RsInitConfig::debugLevel; std::string RsInitConfig::logfname; -bool RsInitConfig::firsttime_run; bool RsInitConfig::load_trustedpeer; std::string RsInitConfig::load_trustedpeer_file; bool RsInitConfig::udpListenerOnly; -/* Uses private class - so must be hidden */ -static bool getAvailableAccounts(std::list &ids,int& failing_accounts,std::map >& unsupported_keys); -static bool checkAccount(std::string accountdir, accountId &id,std::map >& unsupported_keys); - void RsInit::InitRsConfig() { #ifndef WINDOWS_SYS @@ -224,7 +188,6 @@ void RsInit::InitRsConfig() RsInitConfig::load_trustedpeer = false; - RsInitConfig::firsttime_run = false; RsInitConfig::port = 0 ; RsInitConfig::forceLocalAddr = false; RsInitConfig::haveLogFile = false; @@ -240,7 +203,7 @@ void RsInit::InitRsConfig() RsInitConfig::udpListenerOnly = false; /* setup the homePath (default save location) */ - RsInitConfig::homePath = getHomePath(); +// RsInitConfig::homePath = getHomePath(); #ifdef WINDOWS_SYS // test for portable version @@ -382,8 +345,9 @@ int RsInit::InitRetroShare(int argcIgnored, char **argvIgnored, bool strictCheck #endif /******************************** WINDOWS/UNIX SPECIFIC PART ******************/ - int c; - std::string prefUserString = ""; + int c; + std::string prefUserString = ""; + std::string opt_base_dir; /* getopt info: every availiable option is listed here. if it is followed by a ':' it needs an argument. If it is followed by a '::' the argument is optional. @@ -418,7 +382,7 @@ int RsInit::InitRetroShare(int argcIgnored, char **argvIgnored, bool strictCheck >> parameter('w',"password" ,RsInitConfig::passwd ,"password" ,"Set Login Password." ,false) >> parameter('i',"ip-address" ,RsInitConfig::inet ,"nnn.nnn.nnn.nnn", "Set IP address to use." ,false) >> parameter('p',"port" ,RsInitConfig::port ,"port", "Set listenning port to use." ,false) - >> parameter('c',"base-dir" ,RsInitConfig::basedir ,"directory", "Set base directory." ,false) + >> parameter('c',"base-dir" ,opt_base_dir ,"directory", "Set base directory." ,false) >> parameter('U',"user-id" ,prefUserString ,"ID", "[User Name/GPG id/SSL id] Sets Account to Use, Useful when Autologin is enabled",false) >> parameter('r',"link" ,RsInitConfig::RetroShareLink ,"retroshare://...", "Use a given Retroshare Link" ,false) #ifdef LOCALNET_TESTING @@ -567,12 +531,11 @@ int RsInit::InitRetroShare(int argcIgnored, char **argvIgnored, bool strictCheck AuthSSL::getAuthSSL() -> InitAuth(NULL, NULL, NULL); // first check config directories, and set bootstrap values. - if(!setupBaseDir()) + if(!rsAccounts.setupBaseDirectory(opt_base_dir)) return RS_INIT_BASE_DIR_ERROR ; - get_configinit(RsInitConfig::basedir, RsInitConfig::preferedId); - - std::string pgp_dir = RsPGPDirectory() ; + // Setup PGP stuff. + std::string pgp_dir = rsAccounts.PathPGPDirectory(); if(!RsDirUtil::checkCreateDirectory(pgp_dir)) throw std::runtime_error("Cannot create pgp directory " + pgp_dir) ; @@ -582,74 +545,27 @@ int RsInit::InitRetroShare(int argcIgnored, char **argvIgnored, bool strictCheck pgp_dir + "/retroshare_trustdb.gpg", pgp_dir + "/lock"); - /* Initialize AuthGPG */ - // if (AuthGPG::getAuthGPG()->InitAuth() == false) { - // std::cerr << "AuthGPG::InitAuth failed" << std::endl; - // return RS_INIT_AUTH_FAILED; - // } - - //std::list ids; - std::list::iterator it; - int failing_accounts ; - - getAvailableAccounts(RsInitConfig::accountIds,failing_accounts,unsupported_keys); - - if(failing_accounts > 0 && RsInitConfig::accountIds.empty()) + // load Accounts. + if (!rsAccounts.loadAccounts()) + { return RS_INIT_NO_KEYRING ; + } - // if a different user id has been passed to cmd line check for that instead - - std::string lower_case_user_string; - stringToLowerCase(prefUserString, lower_case_user_string) ; - std::string upper_case_user_string; - stringToUpperCase(prefUserString, upper_case_user_string) ; - - bool pgpNameFound = false; + // choose alternative account. if(prefUserString != "") { - - for(it = RsInitConfig::accountIds.begin() ; it!= RsInitConfig::accountIds.end() ; it++) + if (!rsAccounts.selectAccountByString(prefUserString)) { - std::cerr << "Checking account (gpgid = " << it->pgpId << ", name=" << it->pgpName << ", sslId=" << it->sslId << ")" << std::endl ; - - if(prefUserString == it->pgpName || upper_case_user_string == it->pgpId || lower_case_user_string == it->sslId) - { - RsInitConfig::preferedId = it->sslId; - pgpNameFound = true; - } - } - if(!pgpNameFound){ - std::cerr << "Invalid User name/GPG id/SSL id: not found in list" << std::endl; + std::cerr << "Invalid User name/GPG id/SSL id: not found in list"; + std::cerr << std::endl; return RS_INIT_AUTH_FAILED ; } } + /* check that we have selected someone */ + std::string preferredId; + bool existingUser = rsAccounts.getPreferredAccountId(preferredId); - - /* check that preferedId */ - std::string userName; - std::string userId; - bool existingUser = false; - for(it = RsInitConfig::accountIds.begin(); it != RsInitConfig::accountIds.end(); it++) - { - std::cerr << "Checking Account Id: " << it->sslId << std::endl; - if (RsInitConfig::preferedId == it->sslId) - { - std::cerr << " * Preferred * " << std::endl; - userId = it->sslId; - userName = it->pgpName; - existingUser = true; - break; - } - } - if (!existingUser) - { - std::cerr << "No Existing User" << std::endl; - RsInitConfig::preferedId == ""; - - } - - /* if existing user, and havePasswd .... we can skip the login prompt */ if (existingUser) { if (RsInitConfig::passwd != "") @@ -657,9 +573,7 @@ int RsInit::InitRetroShare(int argcIgnored, char **argvIgnored, bool strictCheck return RS_INIT_HAVE_ACCOUNT; } - RsInit::LoadPassword(RsInitConfig::preferedId, ""); - - if(RsLoginHandler::getSSLPassword(RsInitConfig::preferedId,false,RsInitConfig::passwd)) + if(RsLoginHandler::getSSLPassword(preferredId,false,RsInitConfig::passwd)) { RsInit::setAutoLogin(true); std::cerr << "Autologin has succeeded" << std::endl; @@ -669,515 +583,6 @@ int RsInit::InitRetroShare(int argcIgnored, char **argvIgnored, bool strictCheck return RS_INIT_OK; } -/**************************** Access Functions for Init Data **************************/ - -bool RsInit::exportIdentity(const std::string& fname,const std::string& id) -{ - return AuthGPG::getAuthGPG()->exportProfile(fname,id); -} - -bool RsInit::importIdentity(const std::string& fname,std::string& id,std::string& import_error) -{ - return AuthGPG::getAuthGPG()->importProfile(fname,id,import_error); -} - -bool RsInit::copyGnuPGKeyrings() -{ - std::string pgp_dir = RsPGPDirectory() ; - - if(!RsDirUtil::checkCreateDirectory(pgp_dir)) - throw std::runtime_error("Cannot create pgp directory " + pgp_dir) ; - - std::string source_public_keyring; - std::string source_secret_keyring; - -#ifdef WINDOWS_SYS - if (RsInit::isPortable()) - { - source_public_keyring = RsInit::RsConfigDirectory() + "/gnupg/pubring.gpg"; - source_secret_keyring = RsInit::RsConfigDirectory() + "/gnupg/secring.gpg" ; - } else { - source_public_keyring = RsInitConfig::basedir + "/../gnupg/pubring.gpg" ; - source_secret_keyring = RsInitConfig::basedir + "/../gnupg/secring.gpg" ; - } -#else - char *env_gnupghome = getenv("GNUPGHOME") ; - - if(env_gnupghome != NULL) - { - std::cerr << "looking into $GNUPGHOME/" << std::endl; - - source_public_keyring = std::string(env_gnupghome) + "/pubring.gpg" ; - source_secret_keyring = std::string(env_gnupghome) + "/secring.gpg" ; - } - else - { - char *env_homedir = getenv("HOME") ; - - if(env_homedir != NULL) - { - std::cerr << "looking into $HOME/.gnupg/" << std::endl; - std::string home_dir(env_homedir) ; - - // We need a specific part for MacOS and Linux as well - source_public_keyring = home_dir + "/.gnupg/pubring.gpg" ; - source_secret_keyring = home_dir + "/.gnupg/secring.gpg" ; - } - else - return false ; - } -#endif - - if(!RsDirUtil::copyFile(source_public_keyring,pgp_dir + "/retroshare_public_keyring.gpg")) - { - std::cerr << "Cannot copy pub keyring " << source_public_keyring << " to destination file " << pgp_dir + "/retroshare_public_keyring.gpg. If you believe your keyring is in a different place, please make the copy yourself." << std::endl; - return false ; - } - if(!RsDirUtil::copyFile(source_secret_keyring,pgp_dir + "/retroshare_secret_keyring.gpg")) - { - std::cerr << "Cannot copy sec keyring " << source_secret_keyring << " to destination file " << pgp_dir + "/retroshare_secret_keyring.gpg. your keyring is in a different place, please make the copy yourself." << std::endl; - return false ; - } - - return true ; -} - -bool RsInit::getPreferedAccountId(std::string &id) -{ - id = RsInitConfig::preferedId; - return (RsInitConfig::preferedId != ""); -} - -bool RsInit::getAccountIds(std::list &ids) -{ - std::list::iterator it; - #ifdef AUTHSSL_DEBUG - std::cerr << "getAccountIds:" << std::endl; - #endif - - for(it = RsInitConfig::accountIds.begin(); it != RsInitConfig::accountIds.end(); it++) - { - #ifdef AUTHSSL_DEBUG - std::cerr << "SSL Id: " << it->sslId << " PGP Id " << it->pgpId; - std::cerr << " PGP Name: " << it->pgpName; - std::cerr << " PGP Email: " << it->pgpEmail; - std::cerr << " Location: " << it->location; - std::cerr << std::endl; - #endif - - ids.push_back(it->sslId); - } - return true; -} - - -bool RsInit::getAccountDetails(const std::string &id, - std::string &gpgId, std::string &gpgName, - std::string &gpgEmail, std::string &location) -{ - std::list::iterator it; - for(it = RsInitConfig::accountIds.begin(); it != RsInitConfig::accountIds.end(); it++) - { - if (id == it->sslId) - { - gpgId = it->pgpId; - gpgName = it->pgpName; - gpgEmail = it->pgpEmail; - location = it->location; - return true; - } - } - return false; -} - -/**************************** Access Functions for Init Data **************************/ -/**************************** Private Functions for InitRetroshare ********************/ -/**************************** Private Functions for InitRetroshare ********************/ - - -bool RsInit::setupBaseDir() -{ - // get the default configuration location. - - if (RsInitConfig::basedir == "") - { - // v0.4.x if unix. homedir + /.pqiPGPrc - // v0.5.x if unix. homedir + /.retroshare - -/******************************** WINDOWS/UNIX SPECIFIC PART ******************/ -#ifndef WINDOWS_SYS - char *h = getenv("HOME"); - std::cerr << "retroShare::basedir() -> $HOME = "; - std::cerr << h << std::endl; - if (h == NULL) - { - std::cerr << "load_check_basedir() Fatal Error --"; - std::cerr << std::endl; - std::cerr << "\tcannot determine $HOME dir" < $APPDATA = "; - std::cerr << h << std::endl; - char *h2 = getenv("HOMEDRIVE"); - std::cerr << "retroShare::basedir() -> $HOMEDRIVE = "; - std::cerr << h2 << std::endl; - wchar_t *wh3 = _wgetenv(L"HOMEPATH"); - std::string h3; - librs::util::ConvertUtf16ToUtf8(std::wstring(wh3), h3); - std::cerr << "retroShare::basedir() -> $HOMEPATH = "; - std::cerr << h3 << std::endl; - if (h.empty()) - { - // generating default - std::cerr << "load_check_basedir() getEnv Error --Win95/98?"; - std::cerr << std::endl; - - RsInitConfig::basedir="C:\\Retro"; - - } - else - { - RsInitConfig::basedir = h; - } - - if (!RsDirUtil::checkCreateDirectory(RsInitConfig::basedir)) - { - std::cerr << "Cannot Create BaseConfig Dir" << std::endl; - return false ; - } - RsInitConfig::basedir += "\\RetroShare6"; - } -#endif -/******************************** WINDOWS/UNIX SPECIFIC PART ******************/ - } - - // fatal if cannot find/create. - std::cerr << "Creating Root Retroshare Config Directories" << std::endl; - if (!RsDirUtil::checkCreateDirectory(RsInitConfig::basedir)) - { - std::cerr << "Cannot Create BaseConfig Dir:" << RsInitConfig::basedir << std::endl; - return false ; - } - return true ; -} - - -/*********************************************************** - * This Directory is used to store data and "template" file that Retroshare requires. - * These files will either be copied into Retroshare's configuration directory, - * if they are to be modified. Or used directly, if read-only. - * - * This will initially be used for the DHT bootstrap file. - * - * Please modify the code below to suit your platform! - * - * WINDOWS: - * WINDOWS PORTABLE: - * Linux: - * OSX: - - ***********/ - -#ifdef __APPLE__ - /* needs CoreFoundation Framework */ - #include - //#include - //#include -#endif - -std::string RsInit::getRetroshareDataDirectory() -{ - std::string dataDirectory; - -/******************************** WINDOWS/UNIX SPECIFIC PART ******************/ -#ifndef WINDOWS_SYS - - #ifdef __APPLE__ - /* NOTE: OSX also qualifies as BSD... so this #ifdef must be before the BSD check. */ - - /* For OSX, applications are Bundled in a directory... - * need to get the path to the executable Bundle. - * - * Code nicely supplied by Qt! - */ - - CFURLRef pluginRef = CFBundleCopyBundleURL(CFBundleGetMainBundle()); - CFStringRef macPath = CFURLCopyFileSystemPath(pluginRef, - kCFURLPOSIXPathStyle); - const char *pathPtr = CFStringGetCStringPtr(macPath, - CFStringGetSystemEncoding()); - dataDirectory = pathPtr; - CFRelease(pluginRef); - CFRelease(macPath); - - dataDirectory += "/Contents/Resources"; - std::cerr << "getRetroshareDataDirectory() OSX: " << dataDirectory; - - #elif (defined(BSD) && (BSD >= 199103)) - /* For BSD, the default is LOCALBASE which will be set - * before compilation via the ports/pkg-src mechanisms. - * For compilation without ports/pkg-src it is set to - * /usr/local (default on Open and Free; Net has /usr/pkg) - */ - dataDirectory = "/usr/local/share/retroshare"; - std::cerr << "getRetroshareDataDirectory() BSD: " << dataDirectory; - - #else - /* For Linux, we have a fixed standard data directory */ - dataDirectory = "/usr/share/RetroShare"; - std::cerr << "getRetroshareDataDirectory() Linux: " << dataDirectory; - - #endif -#else -// if (RsInitConfig::portable) -// { -// /* For Windows Portable, files must be in the data directory */ -// dataDirectory = "Data"; -// std::cerr << "getRetroshareDataDirectory() WINDOWS PORTABLE: " << dataDirectory; -// std::cerr << std::endl; -// } -// else -// { -// /* For Windows: environment variable APPDATA should be suitable */ -// dataDirectory = getenv("APPDATA"); -// dataDirectory += "\\RetroShare"; -// -// std::cerr << "getRetroshareDataDirectory() WINDOWS: " << dataDirectory; -// std::cerr << std::endl; -// } - - /* Use RetroShare's exe dir */ - dataDirectory = "."; -#endif -/******************************** WINDOWS/UNIX SPECIFIC PART ******************/ - - /* Make sure the directory exists, else return emptyString */ - if (!RsDirUtil::checkDirectory(dataDirectory)) - { - std::cerr << "Data Directory not Found: " << dataDirectory << std::endl; - dataDirectory = ""; - } - else - { - std::cerr << "Data Directory Found: " << dataDirectory << std::endl; - } - - return dataDirectory; -} - - -static bool isHexaString(const std::string& s) -{ - for(uint32_t i=0;i= 'A' && s[i] <= 'F') || (s[i] >= '0' && s[i] <= '9') || (s[i] >= 'a' && s[i] <= 'f'))) - return false ; - - return true ; -} - -/* directories with valid certificates in the expected location */ -bool getAvailableAccounts(std::list &ids,int& failing_accounts,std::map >& unsupported_keys) -{ - failing_accounts = 0 ; - /* get the directories */ - std::list directories; - std::list::iterator it; - - std::cerr << "getAvailableAccounts()"; - std::cerr << std::endl; - - /* now iterate through the directory... - * directories - flags as old, - * files checked to see if they have changed. (rehashed) - */ - - /* check for the dir existance */ - librs::util::FolderIterator dirIt(RsInitConfig::basedir); - if (!dirIt.isValid()) - { - std::cerr << "Cannot Open Base Dir - No Available Accounts" << std::endl; - return false ; - } - - struct stat64 buf; - - while (dirIt.readdir()) - { - /* check entry type */ - std::string fname; - dirIt.d_name(fname); - std::string fullname = RsInitConfig::basedir + "/" + fname; -#ifdef FIM_DEBUG - std::cerr << "calling stats on " << fullname < >& unsupported_keys) -{ - /* check if the cert/key file exists */ - - std::string subdir1 = accountdir + "/"; - std::string subdir2 = subdir1; - subdir1 += configKeyDir; - subdir2 += configCertDir; - - // Create the filename. - std::string basename = accountdir + "/"; - basename += configKeyDir + "/"; - basename += "user"; - - std::string cert_name = basename + "_cert.pem"; - std::string userName, userId; - -#ifdef AUTHSSL_DEBUG - std::cerr << "checkAccount() dir: " << accountdir << std::endl; -#endif - bool ret = false; - - /* check against authmanagers private keys */ - if (LoadCheckX509(cert_name.c_str(), id.pgpId, id.location, id.sslId)) - { -#ifdef AUTHSSL_DEBUG - std::cerr << "location: " << id.location << " id: " << id.sslId << std::endl; - std::cerr << "issuerName: " << id.pgpId << " id: " << id.sslId << std::endl; -#endif - - if(! RsInit::GetPGPLoginDetails(id.pgpId, id.pgpName, id.pgpEmail)) - return false ; - - if(!AuthGPG::getAuthGPG()->haveSecretKey(id.pgpId)) - return false ; - - if(!AuthGPG::getAuthGPG()->isKeySupported(id.pgpId)) - { - std::string keystring = id.pgpId + " " + id.pgpName + "<" + id.pgpEmail ; - unsupported_keys[keystring].push_back("Location: " + id.location + "  (" + id.sslId + ")") ; - return false ; - } - -#ifdef GPG_DEBUG - std::cerr << "PGPLoginDetails: " << id.pgpId << " name: " << id.pgpName; - std::cerr << " email: " << id.pgpEmail << std::endl; -#endif - ret = true; - } - else - { - std::cerr << "GetIssuerName FAILED!" << std::endl; - ret = false; - } - - return ret; -} - - - - -/*****************************************************************************/ -/*****************************************************************************/ -/************************* Generating Certificates ***************************/ -/*****************************************************************************/ -/*****************************************************************************/ - - - /* Generating GPGme Account */ -int RsInit::GetPGPLogins(std::list &pgpIds) { - AuthGPG::getAuthGPG()->availableGPGCertificatesWithPrivateKeys(pgpIds); - return 1; -} - -int RsInit::GetPGPLoginDetails(const std::string& id, std::string &name, std::string &email) -{ - #ifdef GPG_DEBUG - std::cerr << "RsInit::GetPGPLoginDetails for \"" << id << "\"" << std::endl; - #endif - - bool ok = true ; - name = AuthGPG::getAuthGPG()->getGPGName(id,&ok); - if(!ok) - return 0 ; - email = AuthGPG::getAuthGPG()->getGPGEmail(id,&ok); - if(!ok) - return 0 ; - - if (name != "") { - return 1; - } else { - return 0; - } -} /* * To prevent several running instances from using the same directory @@ -1207,269 +612,14 @@ void RsInit::UnlockConfigDirectory() } -/* Before any SSL stuff can be loaded, the correct PGP must be selected / generated: - **/ - -bool RsInit::SelectGPGAccount(const std::string& gpgId) -{ - bool retVal = false; - - if (0 < AuthGPG::getAuthGPG() -> GPGInit(gpgId)) - { - retVal = true; - std::cerr << "PGP Auth Success!"; - } - else - std::cerr << "PGP Auth Failed!"; - - std::cerr << " ID: " << gpgId << std::endl; - - return retVal; -} - - -bool RsInit::GeneratePGPCertificate(const std::string& name, const std::string& email, const std::string& passwd, std::string &pgpId, std::string &errString) -{ - return AuthGPG::getAuthGPG()->GeneratePGPCertificate(name, email, passwd, pgpId, errString); -} - - - /* Create SSL Certificates */ -bool RsInit::GenerateSSLCertificate(const std::string& gpg_id, const std::string& org, const std::string& loc, const std::string& country, const std::string& passwd, std::string &sslId, std::string &errString) -{ - // generate the private_key / certificate. - // save to file. - // - // then load as if they had entered a passwd. - - // check password. - if (passwd.length() < 4) - { - errString = "Password is Unsatisfactory (must be 4+ chars)"; - return false; - } - - int nbits = 2048; - - std::string name = AuthGPG::getAuthGPG()->getGPGName(gpg_id); - - // Create the filename ..... - // Temporary Directory for creating files.... - std::string tmpdir = "TMPCFG"; - - std::string tmpbase = RsInitConfig::basedir + "/" + tmpdir + "/"; - - if(!RsInit::setupAccount(tmpbase)) - return false ; - - /* create directory structure */ - - std::string basename = tmpbase + configKeyDir + "/"; - basename += "user"; - - std::string key_name = basename + "_pk.pem"; - std::string cert_name = basename + "_cert.pem"; - - bool gen_ok = false; - - /* Extra step required for SSL + PGP, user must have selected - * or generated a suitable key so the signing can happen. - */ - - X509_REQ *req = GenerateX509Req( - key_name.c_str(), - passwd.c_str(), - name.c_str(), - "", //ui -> gen_email -> value(), - org.c_str(), - loc.c_str(), - "", //ui -> gen_state -> value(), - country.c_str(), - nbits, errString); - - if (req == NULL) - { - fprintf(stderr,"RsGenerateCert() Couldn't create Request. Reason: %s\n", errString.c_str()); - return false; - } - - long days = 3000; - X509 *x509 = AuthSSL::getAuthSSL()->SignX509ReqWithGPG(req, days); - - X509_REQ_free(req); - if (x509 == NULL) { - fprintf(stderr,"RsGenerateCert() Couldn't sign ssl certificate. Probably PGP password is wrong.\n"); - return false; - } - - /* save to file */ - if (x509) - { - gen_ok = true; - - /* Print the signed Certificate! */ - BIO *bio_out = NULL; - bio_out = BIO_new(BIO_s_file()); - BIO_set_fp(bio_out,stdout,BIO_NOCLOSE); - - /* Print it out */ - int nmflag = 0; - int reqflag = 0; - - X509_print_ex(bio_out, x509, nmflag, reqflag); - - BIO_flush(bio_out); - BIO_free(bio_out); - - } - else - { - gen_ok = false; - } - - if (gen_ok) - { - /* Save cert to file */ - // open the file. - FILE *out = NULL; - if (NULL == (out = RsDirUtil::rs_fopen(cert_name.c_str(), "w"))) - { - fprintf(stderr,"RsGenerateCert() Couldn't create Cert File"); - fprintf(stderr," : %s\n", cert_name.c_str()); - gen_ok = false; - } - - if (!PEM_write_X509(out,x509)) - { - fprintf(stderr,"RsGenerateCert() Couldn't Save Cert"); - fprintf(stderr," : %s\n", cert_name.c_str()); - gen_ok = false; - } - - fclose(out); - X509_free(x509); - } - - if (!gen_ok) - { - errString = "Generation of Certificate Failed"; - return false; - } - - /* try to load it, and get Id */ - - std::string location; - std::string gpgid; - if (LoadCheckX509(cert_name.c_str(), gpgid, location, sslId) == 0) { - std::cerr << "RsInit::GenerateSSLCertificate() Cannot check own signature, maybe the files are corrupted." << std::endl; - return false; - } - - /* Move directory to correct id */ - std::string finalbase = RsInitConfig::basedir + "/" + sslId + "/"; - /* Rename Directory */ - - std::cerr << "Mv Config Dir from: " << tmpbase << " to: " << finalbase; - std::cerr << std::endl; - - if (!RsDirUtil::renameFile(tmpbase, finalbase)) - { - std::cerr << "rename FAILED" << std::endl; - } - - /* Flag as first time run */ - RsInitConfig::firsttime_run = true; - - std::cerr << "RetroShare has Successfully generated a Certficate/Key" << std::endl; - std::cerr << "\tCert Located: " << cert_name << std::endl; - std::cerr << "\tLocated: " << key_name << std::endl; - - return true; -} - - -/******************* PRIVATE FNS TO HELP with GEN **************/ -bool RsInit::setupAccount(const std::string& accountdir) -{ - /* actual config directory isd */ - - std::string subdir1 = accountdir + "/"; - std::string subdir2 = subdir1; - subdir1 += configKeyDir; - subdir2 += configCertDir; - - std::string subdir3 = accountdir + "/"; - subdir3 += "cache"; - - std::string subdir4 = subdir3 + "/"; - std::string subdir5 = subdir3 + "/"; - subdir4 += "local"; - subdir5 += "remote"; - - // fatal if cannot find/create. - std::cerr << "Checking For Directories" << std::endl; - if (!RsDirUtil::checkCreateDirectory(accountdir)) - { - std::cerr << "Cannot Create BaseConfig Dir" << std::endl; - return false ; - } - if (!RsDirUtil::checkCreateDirectory(subdir1)) - { - std::cerr << "Cannot Create Config/Key Dir" << std::endl; - return false ; - } - if (!RsDirUtil::checkCreateDirectory(subdir2)) - { - std::cerr << "Cannot Create Config/Cert Dir" << std::endl; - return false ; - } - if (!RsDirUtil::checkCreateDirectory(subdir3)) - { - std::cerr << "Cannot Create Config/Cache Dir" << std::endl; - return false ; - } - if (!RsDirUtil::checkCreateDirectory(subdir4)) - { - std::cerr << "Cannot Create Config/Cache/local Dir" << std::endl; - return false ; - } - if (!RsDirUtil::checkCreateDirectory(subdir5)) - { - std::cerr << "Cannot Create Config/Cache/remote Dir" << std::endl; - return false ; - } - - return true; -} - - - - - /***************************** FINAL LOADING OF SETUP *************************/ /* Login SSL */ -bool RsInit::LoadPassword(const std::string& id, const std::string& inPwd) +bool RsInit::LoadPassword(const std::string& inPwd) { - /* select configDir */ - - RsInitConfig::preferedId = id; - RsInitConfig::configDir = RsInitConfig::basedir + "/" + id; RsInitConfig::passwd = inPwd; - - // if(inPwd != "") - // RsInitConfig::havePasswd = true; - - // Create the filename. - std::string basename = RsInitConfig::configDir + "/"; - basename += configKeyDir + "/"; - basename += "user"; - - RsInitConfig::load_key = basename + "_pk.pem"; - RsInitConfig::load_cert = basename + "_cert.pem"; - return true; } @@ -1485,7 +635,30 @@ bool RsInit::LoadPassword(const std::string& id, const std::string& inPwd) */ int RsInit::LockAndLoadCertificates(bool autoLoginNT, std::string& lockFilePath) { - int retVal = LockConfigDirectory(RsInitConfig::configDir, lockFilePath); + if (!rsAccounts.lockPreferredAccount()) + { + return 3; // invalid PreferredAccount. + } + + // Logic that used to be external to RsInit... + std::string accountId; + if (!rsAccounts.getPreferredAccountId(accountId)) + { + return 3; // invalid PreferredAccount; + } + + std::string pgpId, pgpName, pgpEmail, location; + if (!rsAccounts.getAccountDetails(accountId, pgpId, pgpName, pgpEmail, location)) + { + return 3; // invalid PreferredAccount; + } + + if (!rsAccounts.SelectPGPAccount(pgpId)) + { + return 3; // PGP Error. + } + + int retVal = LockConfigDirectory(rsAccounts.PathAccountDirectory(), lockFilePath); if(retVal != 0) return retVal; @@ -1510,13 +683,21 @@ int RsInit::LockAndLoadCertificates(bool autoLoginNT, std::string& lockFilePath */ int RsInit::LoadCertificates(bool autoLoginNT) { - if (RsInitConfig::load_cert == "") + std::string preferredId; + if (!rsAccounts.getPreferredAccountId(preferredId)) + { + std::cerr << "No Account Selected" << std::endl; + return 0; + } + + + if (rsAccounts.PathCertFile() == "") { std::cerr << "RetroShare needs a certificate" << std::endl; return 0; } - if (RsInitConfig::load_key == "") + if (rsAccounts.PathKeyFile() == "") { std::cerr << "RetroShare needs a key" << std::endl; return 0; @@ -1525,20 +706,20 @@ int RsInit::LoadCertificates(bool autoLoginNT) //check if password is already in memory if(RsInitConfig::passwd == "") { - if (RsLoginHandler::getSSLPassword(RsInitConfig::preferedId,true,RsInitConfig::passwd) == false) { + if (RsLoginHandler::getSSLPassword(preferredId,true,RsInitConfig::passwd) == false) { std::cerr << "RsLoginHandler::getSSLPassword() Failed!"; return 0 ; } } else { - if (RsLoginHandler::checkAndStoreSSLPasswdIntoGPGFile(RsInitConfig::preferedId,RsInitConfig::passwd) == false) { + if (RsLoginHandler::checkAndStoreSSLPasswdIntoGPGFile(preferredId,RsInitConfig::passwd) == false) { std::cerr << "RsLoginHandler::checkAndStoreSSLPasswdIntoGPGFile() Failed!"; return 0; } } - std::cerr << "RsInitConfig::load_key.c_str() : " << RsInitConfig::load_key.c_str() << std::endl; + std::cerr << "rsAccounts.PathKeyFile() : " << rsAccounts.PathKeyFile() << std::endl; - if(0 == AuthSSL::getAuthSSL() -> InitAuth(RsInitConfig::load_cert.c_str(), RsInitConfig::load_key.c_str(), RsInitConfig::passwd.c_str())) + if(0 == AuthSSL::getAuthSSL() -> InitAuth(rsAccounts.PathCertFile().c_str(), rsAccounts.PathKeyFile().c_str(), RsInitConfig::passwd.c_str())) { std::cerr << "SSL Auth Failed!"; return 0 ; @@ -1549,7 +730,7 @@ int RsInit::LoadCertificates(bool autoLoginNT) std::cerr << "RetroShare will AutoLogin next time"; std::cerr << std::endl; - RsLoginHandler::enableAutoLogin(RsInitConfig::preferedId,RsInitConfig::passwd); + RsLoginHandler::enableAutoLogin(preferredId,RsInitConfig::passwd); RsInitConfig::autoLogin = true ; } @@ -1559,108 +740,22 @@ int RsInit::LoadCertificates(bool autoLoginNT) // ideally gxs should have its own password RsInitConfig::gxs_passwd = RsInitConfig::passwd; RsInitConfig::passwd = ""; - create_configinit(RsInitConfig::basedir, RsInitConfig::preferedId); - + + rsAccounts.storePreferredAccount(); return 1; } bool RsInit::RsClearAutoLogin() { - return RsLoginHandler::clearAutoLogin(RsInitConfig::preferedId); + std::string preferredId; + if (!rsAccounts.getPreferredAccountId(preferredId)) + { + std::cerr << "RsInit::RsClearAutoLogin() No Account Selected" << std::endl; + return 0; + } + return RsLoginHandler::clearAutoLogin(preferredId); } -bool RsInit::get_configinit(const std::string& dir, std::string &id) -{ - // have a config directories. - - // Check for config file. - std::string initfile = dir + "/"; - initfile += configInitFile; - - // open and read in the lines. - FILE *ifd = RsDirUtil::rs_fopen(initfile.c_str(), "r"); - char path[1024]; - int i; - - if (ifd != NULL) - { - if (NULL != fgets(path, 1024, ifd)) - { - for(i = 0; (path[i] != '\0') && (path[i] != '\n'); i++) {} - path[i] = '\0'; - id = path; - } - fclose(ifd); - return true; - } - - // we have now - // 1) checked or created the config dirs. - // 2) loaded the config_init file - if possible. - return false; -} - -bool RsInit::create_configinit(const std::string& dir, const std::string& id) -{ - // Check for config file. - std::string initfile = dir + "/"; - initfile += configInitFile; - - // open and read in the lines. - FILE *ifd = RsDirUtil::rs_fopen(initfile.c_str(), "w"); - - if (ifd != NULL) - { - fprintf(ifd, "%s\n", id.c_str()); - fclose(ifd); - - std::cerr << "Creating Init File: " << initfile << std::endl; - std::cerr << "\tId: " << id << std::endl; - - return true; - } - std::cerr << "Failed To Create Init File: " << initfile << std::endl; - return false; -} - -std::string RsInit::getHomePath() -{ - std::string home; -/******************************** WINDOWS/UNIX SPECIFIC PART ******************/ -#ifndef WINDOWS_SYS /* UNIX */ - - home = getenv("HOME"); - -#else /* Windows */ - - char *h2 = getenv("HOMEDRIVE"); - std::cerr << "getHomePath() -> $HOMEDRIVE = " << h2 << std::endl; - char *h3 = getenv("HOMEPATH"); - std::cerr << "getHomePath() -> $HOMEPATH = " << h3 << std::endl; - - if (h2 == NULL) - { - // Might be Win95/98 - // generate default. - home = "C:\\Retro"; - } - else - { - home = h2; - home += h3; - home += "\\Desktop"; - } - - std::cerr << "fltkserver::getHomePath() -> " << home << std::endl; - - // convert to FLTK desired format. - home = RsDirUtil::convertPathToUnix(home); -#endif -/******************************** WINDOWS/UNIX SPECIFIC PART ******************/ - return home; -} - -/******************************** WINDOWS/UNIX SPECIFIC PART ******************/ bool RsInit::isPortable() { @@ -1679,26 +774,7 @@ bool RsInit::isWindowsXP() return false; #endif } -std::string RsInit::RsConfigKeysDirectory() -{ - return RsInitConfig::basedir + "/" + RsInitConfig::preferedId + "/" + configKeyDir ; -} -std::string RsInit::RsConfigDirectory() -{ - return RsInitConfig::basedir; -} -std::string RsInit::RsPGPDirectory() -{ - return RsInitConfig::basedir + "/pgp" ; -} - -std::string RsInit::RsProfileConfigDirectory() -{ - std::string dir = RsInitConfig::basedir + "/" + RsInitConfig::preferedId; - //std::cerr << "RsInit::RsProfileConfigDirectory() returning : " << dir << std::endl; - return dir; -} - + bool RsInit::getStartMinimised() { return RsInitConfig::startMinimised; @@ -1725,6 +801,7 @@ void RsInit::setAutoLogin(bool autoLogin){ bool RsInit::SetHiddenLocation(const std::string& hiddenaddress, uint16_t port) { /* parse the bugger (todo) */ + RsInitConfig::hiddenNodeSet = true; RsInitConfig::hiddenNodeAddress = hiddenaddress; RsInitConfig::hiddenNodePort = port; return true; @@ -1897,8 +974,8 @@ int RsServer::StartupRetroShare() std::cerr << "set the debugging to crashMode." << std::endl; if ((!RsInitConfig::haveLogFile) && (!RsInitConfig::outStderr)) { - std::string crashfile = RsInitConfig::basedir + "/"; - crashfile += ownId + "/" + configLogFileName; + std::string crashfile = rsAccounts.PathAccountDirectory(); + crashfile += "/" + configLogFileName; setDebugCrashMode(crashfile.c_str()); } @@ -1912,8 +989,8 @@ int RsServer::StartupRetroShare() // Load up Certificates, and Old Configuration (if present) std::cerr << "Load up Certificates, and Old Configuration (if present)." << std::endl; - std::string emergencySaveDir = RsInitConfig::configDir.c_str(); - std::string emergencyPartialsDir = RsInitConfig::configDir.c_str(); + std::string emergencySaveDir = rsAccounts.PathAccountDirectory(); + std::string emergencyPartialsDir = rsAccounts.PathAccountDirectory(); if (emergencySaveDir != "") { emergencySaveDir += "/"; @@ -1927,53 +1004,13 @@ int RsServer::StartupRetroShare() /**************************************************************************/ std::cerr << "Load Configuration" << std::endl; - mConfigMgr = new p3ConfigMgr(RsInitConfig::configDir); + mConfigMgr = new p3ConfigMgr(rsAccounts.PathAccountDirectory()); mGeneralConfig = new p3GeneralConfig(); - // Add General.cfg, and load - this allows key early options. - mConfigMgr->addConfiguration("general.cfg", mGeneralConfig); - std::string dummy2("dummy"); - mGeneralConfig->loadConfiguration(dummy2); - - // NOTE: if we lose GeneralConfiguration - then RS will fail to start. - // as API_VERSION won't exist. Furthermore HIDDEN node status will be lost. - // We can potentially detect HIDDEN node cofig from "peers.cfg", - // If this is lost too - in real trouble. - -#define RS_API_VERSION_OPT "RS_API" -#define RS_API_VERSION_STRING "0.6.0" - -#define RS_HIDDEN_NODE_OPT "HIDDEN_NODE" -#define RS_HIDDEN_NODE_YES "YES" - - bool forceApiUpgrade = false; - if ((RsInitConfig::firsttime_run) || (forceApiUpgrade)) - { - mGeneralConfig->setSetting(RS_API_VERSION_OPT, RS_API_VERSION_STRING); - } - - bool setupHiddenNode = false; - if (!RsInitConfig::hiddenNodeAddress.empty()) - { - setupHiddenNode = true; - mGeneralConfig->setSetting(RS_HIDDEN_NODE_OPT, RS_HIDDEN_NODE_YES); - } - - // BASIC COMPARISION FOR NOW... can be extended later if needed. - std::string version = mGeneralConfig->getSetting(RS_API_VERSION_OPT); - if (version != RS_API_VERSION_STRING) - { - std::cerr << "Aborting: Old Retroshare Configuration"; - std::cerr << std::endl; - abort(); - } - bool isHiddenNode = false; - if (RS_HIDDEN_NODE_YES == mGeneralConfig->getSetting(RS_HIDDEN_NODE_OPT)) - { - isHiddenNode = true; - std::cerr << "Retroshare: Hidden Node"; - std::cerr << std::endl; - } + // Get configuration options from rsAccounts. + bool isHiddenNode = false; + bool isFirstTimeRun = false; + rsAccounts.getAccountOptions(isHiddenNode, isFirstTimeRun); /**************************************************************************/ /* setup classes / structures */ @@ -2047,7 +1084,7 @@ int RsServer::StartupRetroShare() #define BITDHT_BOOTSTRAP_FILENAME "bdboot.txt" - std::string bootstrapfile = RsInitConfig::configDir.c_str(); + std::string bootstrapfile = rsAccounts.PathAccountDirectory(); if (bootstrapfile != "") { bootstrapfile += "/"; @@ -2063,7 +1100,7 @@ int RsServer::StartupRetroShare() if (!RsDirUtil::checkFile(bootstrapfile,true)) { std::cerr << "DHT bootstrap file not in ConfigDir: " << bootstrapfile << std::endl; - std::string installfile = RsInit::getRetroshareDataDirectory(); + std::string installfile = rsAccounts.PathDataDirectory(); installfile += "/"; installfile += BITDHT_BOOTSTRAP_FILENAME; @@ -2178,7 +1215,7 @@ int RsServer::StartupRetroShare() /****** New Ft Server **** !!! */ ftServer *ftserver = new ftServer(mPeerMgr, mLinkMgr); - ftserver->setConfigDirectory(RsInitConfig::configDir); + ftserver->setConfigDirectory(rsAccounts.PathAccountDirectory()); ftserver->SetupFtServer(&(getNotify())); CacheStrapper *mCacheStrapper = ftserver->getCacheStrapper(); @@ -2195,7 +1232,7 @@ int RsServer::StartupRetroShare() /* create Cache Services */ - std::string config_dir = RsInitConfig::configDir; + std::string config_dir = rsAccounts.PathAccountDirectory(); std::string localcachedir = config_dir + "/cache/local"; std::string remotecachedir = config_dir + "/cache/remote"; @@ -2204,7 +1241,7 @@ int RsServer::StartupRetroShare() #ifndef WINDOWS_SYS plugins_directories.push_back(std::string("/usr/lib/retroshare/extensions/")) ; #endif - plugins_directories.push_back(RsInitConfig::basedir + "/extensions/") ; + plugins_directories.push_back(rsAccounts.PathBaseDirectory() + "/extensions/") ; #ifdef DEBUG_PLUGIN_SYSTEM plugins_directories.push_back(".") ; // this list should be saved/set to some correct value. // possible entries include: /usr/lib/retroshare, ~/.retroshare/extensions/, etc. @@ -2279,7 +1316,7 @@ int RsServer::StartupRetroShare() // the given ssl user id then this directory is cleaned // and deleted std::string priorGxsDir = "./" + mLinkMgr->getOwnId() + "/"; - std::string currGxsDir = RsInitConfig::configDir + "/GXS_phase2"; + std::string currGxsDir = rsAccounts.PathAccountDirectory() + "/GXS_phase2"; #ifdef GXS_DEV_TESTNET // Different Directory for testing. currGxsDir += "_TESTNET6"; @@ -2534,6 +1571,7 @@ int RsServer::StartupRetroShare() mConfigMgr->loadConfiguration(); mConfigMgr->addConfiguration("peers.cfg", mPeerMgr); + mConfigMgr->addConfiguration("general.cfg", mGeneralConfig); mConfigMgr->addConfiguration("cache.cfg", mCacheStrapper); mConfigMgr->addConfiguration("msgs.cfg", msgSrv); mConfigMgr->addConfiguration("chat.cfg", chatSrv); @@ -2610,24 +1648,14 @@ int RsServer::StartupRetroShare() } - if (setupHiddenNode) + if (RsInitConfig::hiddenNodeSet) { mPeerMgr->setupHiddenNode(RsInitConfig::hiddenNodeAddress, RsInitConfig::hiddenNodePort); } - - -#if 0 - /* must load the trusted_peer before setting up the pqipersongrp */ - if (firsttime_run) + else if (isHiddenNode) { - /* at this point we want to load and start the trusted peer -> if selected */ - if (load_trustedpeer) - { - /* sslroot does further checks */ - sslr -> loadInitialTrustedPeer(load_trustedpeer_file); - } + mPeerMgr->forceHiddenNode(); } -#endif mNetMgr -> checkNetAddress(); @@ -2733,17 +1761,13 @@ int RsServer::StartupRetroShare() rsHistory = new p3History(mHistoryMgr); /* put a welcome message in! */ - if (RsInitConfig::firsttime_run) + if (isFirstTimeRun) { msgSrv->loadWelcomeMsg(); ftserver->shareDownloadDirectory(true); mGeneralConfig->saveConfiguration(); } - // load up the help page - std::string helppage = RsInitConfig::basedir + "/"; - helppage += configHelpName; - /* Startup this thread! */ createThread(*this); diff --git a/libretroshare/src/rsserver/rsloginhandler.cc b/libretroshare/src/rsserver/rsloginhandler.cc index ebc018541..6bfb577a2 100644 --- a/libretroshare/src/rsserver/rsloginhandler.cc +++ b/libretroshare/src/rsserver/rsloginhandler.cc @@ -1,9 +1,9 @@ #include #include -#include #include #include "rsloginhandler.h" #include "util/rsdir.h" +#include "rsaccounts.h" #if defined(UBUNTU) || defined(__FreeBSD__) || defined(__OpenBSD__) #include @@ -689,11 +689,11 @@ bool RsLoginHandler::getSSLPasswdFromGPGFile(const std::string& ssl_id,std::stri std::string RsLoginHandler::getSSLPasswdFileName(const std::string& /*ssl_id*/) { - return RsInit::RsConfigKeysDirectory() + "/" + "ssl_passphrase.pgp"; + return rsAccounts.PathAccountKeysDirectory() + "/" + "ssl_passphrase.pgp"; } std::string RsLoginHandler::getAutologinFileName(const std::string& /*ssl_id*/) { - return RsInit::RsConfigKeysDirectory() + "/" + "help.dta" ; + return rsAccounts.PathAccountKeysDirectory() + "/" + "help.dta" ; } diff --git a/libretroshare/src/util/rsdiscspace.cc b/libretroshare/src/util/rsdiscspace.cc index f2ebad099..d5e4d98d8 100644 --- a/libretroshare/src/util/rsdiscspace.cc +++ b/libretroshare/src/util/rsdiscspace.cc @@ -27,7 +27,7 @@ #include #include "retroshare/rsfiles.h" #include "retroshare/rsiface.h" -#include "retroshare/rsinit.h" +#include "rsserver/rsaccounts.h" #include "rsdiscspace.h" #include #ifndef WIN32 @@ -157,13 +157,13 @@ bool RsDiscSpace::checkForDiscSpace(RsDiscSpace::DiscLocation loc) #endif break ; - case RS_CONFIG_DIRECTORY: rs = crossSystemDiskStats(RsInit::RsConfigDirectory().c_str(),free_blocks,block_size) ; + case RS_CONFIG_DIRECTORY: rs = crossSystemDiskStats(rsAccounts.PathAccountDirectory().c_str(),free_blocks,block_size) ; #ifdef DEBUG_RSDISCSPACE std::cerr << " path = " << RsInit::RsConfigDirectory() << std::endl ; #endif break ; - case RS_PGP_DIRECTORY: rs = crossSystemDiskStats(RsInit::RsPGPDirectory().c_str(),free_blocks,block_size) ; + case RS_PGP_DIRECTORY: rs = crossSystemDiskStats(rsAccounts.PathPGPDirectory().c_str(),free_blocks,block_size) ; #ifdef DEBUG_RSDISCSPACE std::cerr << " path = " << RsInit::RsPGPDirectory() << std::endl ; #endif diff --git a/libretroshare/src/util/rsstring.cc b/libretroshare/src/util/rsstring.cc index fb3d6e31c..be3ab9154 100644 --- a/libretroshare/src/util/rsstring.cc +++ b/libretroshare/src/util/rsstring.cc @@ -304,3 +304,16 @@ void stringToLowerCase(const std::string& s, std::string &lower) if(lower[i] > 64 && lower[i] < 91) lower[i] += 97-65 ; } + + + +bool isHexaString(const std::string& s) +{ + for(uint32_t i=0;i= 'A' && s[i] <= 'F') || (s[i] >= '0' && s[i] <= '9') || (s[i] >= 'a' && s[i] <= 'f'))) + return false ; + + return true ; +} + + diff --git a/libretroshare/src/util/rsstring.h b/libretroshare/src/util/rsstring.h index be26fe54d..0e9df964f 100644 --- a/libretroshare/src/util/rsstring.h +++ b/libretroshare/src/util/rsstring.h @@ -48,4 +48,6 @@ int rs_sprintf_append(std::string &str, const char *fmt, ...); void stringToUpperCase(const std::string& s, std::string &upper); void stringToLowerCase(const std::string& s, std::string &lower); +bool isHexaString(const std::string& s); + #endif // RSSTRING_H_ From bbe3ee8d2fb1ce2878dc84da4f99aef392cd1ff9 Mon Sep 17 00:00:00 2001 From: drbob Date: Sat, 18 Jan 2014 02:35:06 +0000 Subject: [PATCH 66/83] - Switched to new RsAccounts interface. - Reworked ServerPage to support HiddenNode configuration. git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@7028 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- retroshare-gui/src/gui/GenCertDialog.cpp | 24 +- retroshare-gui/src/gui/StartDialog.cpp | 8 +- retroshare-gui/src/gui/chat/ChatStyle.cpp | 2 +- .../src/gui/profile/ProfileManager.cpp | 10 +- .../src/gui/settings/RsharePeerSettings.cpp | 2 +- .../src/gui/settings/ServerPage.cpp | 249 +++++++++++++++++- retroshare-gui/src/gui/settings/ServerPage.h | 9 + retroshare-gui/src/gui/settings/ServerPage.ui | 35 ++- retroshare-gui/src/gui/settings/rsettings.cpp | 4 +- retroshare-gui/src/lang/languagesupport.cpp | 2 +- retroshare-gui/src/main.cpp | 15 +- retroshare-gui/src/rshare.cpp | 19 +- retroshare-gui/src/rshare.h | 2 +- 13 files changed, 329 insertions(+), 52 deletions(-) diff --git a/retroshare-gui/src/gui/GenCertDialog.cpp b/retroshare-gui/src/gui/GenCertDialog.cpp index 70f3fb6be..2b32001eb 100644 --- a/retroshare-gui/src/gui/GenCertDialog.cpp +++ b/retroshare-gui/src/gui/GenCertDialog.cpp @@ -72,12 +72,12 @@ void GenCertDialog::init() std::list::iterator it; bool foundGPGKeys = false; if (!mOnlyGenerateIdentity) { - if (RsInit::GetPGPLogins(pgpIds)) { + if (RsAccounts::GetPGPLogins(pgpIds)) { for(it = pgpIds.begin(); it != pgpIds.end(); it++) { QVariant userData(QString::fromStdString(*it)); std::string name, email; - RsInit::GetPGPLoginDetails(*it, name, email); + RsAccounts::GetPGPLoginDetails(*it, name, email); std::cerr << "Adding PGPUser: " << name << " id: " << *it << std::endl; QString gid = QString::fromStdString(*it).right(8) ; ui.genPGPuser->addItem(QString::fromUtf8(name.c_str()) + " <" + QString::fromUtf8(email.c_str()) + "> (" + gid + ")", userData); @@ -187,7 +187,7 @@ void GenCertDialog::exportIdentity() QVariant data = ui.genPGPuser->itemData(ui.genPGPuser->currentIndex()); std::string gpg_id = data.toString().toStdString() ; - if(RsInit::exportIdentity(fname.toStdString(),gpg_id)) + if(RsAccounts::ExportIdentity(fname.toStdString(),gpg_id)) QMessageBox::information(this,tr("Identity saved"),tr("Your identity was successfully saved\nIt is encrypted\n\nYou can now copy it to another computer\nand use the import button to load it")) ; else QMessageBox::information(this,tr("Identity not saved"),tr("Your identity was not saved. An error occurred.")) ; @@ -203,7 +203,7 @@ void GenCertDialog::importIdentity() std::string gpg_id ; std::string err_string ; - if(!RsInit::importIdentity(fname.toStdString(),gpg_id,err_string)) + if(!RsAccounts::ImportIdentity(fname.toStdString(),gpg_id,err_string)) { QMessageBox::information(this,tr("Identity not loaded"),tr("Your identity was not loaded properly:")+" \n "+QString::fromStdString(err_string)) ; return ; @@ -212,7 +212,7 @@ void GenCertDialog::importIdentity() { std::string name,email ; - RsInit::GetPGPLoginDetails(gpg_id, name, email); + RsAccounts::GetPGPLoginDetails(gpg_id, name, email); std::cerr << "Adding PGPUser: " << name << " id: " << gpg_id << std::endl; QMessageBox::information(this,tr("New identity imported"),tr("Your identity was imported successfully:")+" \n"+"\nName :"+QString::fromStdString(name)+"\nemail: " + QString::fromStdString(email)+"\nKey ID: "+QString::fromStdString(gpg_id)+"\n\n"+tr("You can use it now to create a new location.")) ; @@ -226,6 +226,7 @@ void GenCertDialog::genPerson() /* Check the data from the GUI. */ std::string genLoc = ui.location_input->text().toUtf8().constData(); std::string PGPId; + bool isHiddenLoc = false; if (ui.hidden_checkbox->isChecked()) { @@ -240,6 +241,7 @@ void GenCertDialog::genPerson() QMessageBox::Ok); return; } + isHiddenLoc = true; } if (!genNewGPGKey) { @@ -297,7 +299,7 @@ void GenCertDialog::genPerson() while(QAbstractEventDispatcher::instance()->processEvents(QEventLoop::AllEvents)) ; std::string email_str = "" ; - RsInit::GeneratePGPCertificate(ui.name_input->text().toUtf8().constData(), email_str.c_str(), ui.password_input->text().toUtf8().constData(), PGPId, err_string); + RsAccounts::GeneratePGPCertificate(ui.name_input->text().toUtf8().constData(), email_str.c_str(), ui.password_input->text().toUtf8().constData(), PGPId, err_string); setCursor(Qt::ArrowCursor) ; } @@ -305,19 +307,19 @@ void GenCertDialog::genPerson() //generate a random ssl password std::string sslPasswd = RSRandom::random_alphaNumericString(RsInit::getSslPwdLen()) ; - /* Initialise the PGP user first */ - RsInit::SelectGPGAccount(PGPId); + /* GenerateSSLCertificate - selects the PGP Account */ + //RsInit::SelectGPGAccount(PGPId); std::string sslId; std::cerr << "GenCertDialog::genPerson() Generating SSL cert with gpg id : " << PGPId << std::endl; std::string err; - bool okGen = RsInit::GenerateSSLCertificate(PGPId, "", genLoc, "", sslPasswd, sslId, err); + bool okGen = RsAccounts::GenerateSSLCertificate(PGPId, "", genLoc, "", isHiddenLoc, sslPasswd, sslId, err); if (okGen) { /* complete the process */ - RsInit::LoadPassword(sslId, sslPasswd); - if (Rshare::loadCertificate(sslId, false, PGPId)) { + RsInit::LoadPassword(sslPasswd); + if (Rshare::loadCertificate(sslId, false)) { accept(); } } diff --git a/retroshare-gui/src/gui/StartDialog.cpp b/retroshare-gui/src/gui/StartDialog.cpp index e6bf9af9a..8a1e2dc67 100644 --- a/retroshare-gui/src/gui/StartDialog.cpp +++ b/retroshare-gui/src/gui/StartDialog.cpp @@ -48,17 +48,17 @@ StartDialog::StartDialog(QWidget *parent) std::list accountIds; std::list::iterator it; std::string preferedId; - RsInit::getPreferedAccountId(preferedId); + RsAccounts::GetPreferredAccountId(preferedId); int pidx = -1; int i; - if (RsInit::getAccountIds(accountIds)) + if (RsAccounts::GetAccountIds(accountIds)) { for(it = accountIds.begin(), i = 0; it != accountIds.end(); it++, i++) { const QVariant & userData = QVariant(QString::fromStdString(*it)); std::string gpgid, name, email, location; - RsInit::getAccountDetails(*it, gpgid, name, email, location); + RsAccounts::GetAccountDetails(*it, gpgid, name, email, location); QString accountName = QString::fromUtf8(name.c_str()) + " (" + QString::fromStdString(gpgid).right(8) + ") - " + QString::fromUtf8(location.c_str()); ui.loadName->addItem(accountName, userData); @@ -97,8 +97,6 @@ void StartDialog::loadPerson() QVariant data = ui.loadName->itemData(pgpidx); accountId = (data.toString()).toStdString(); - RsInit::LoadPassword(accountId, ""); - if (Rshare::loadCertificate(accountId, ui.autologin_checkbox->isChecked())) { accept(); } diff --git a/retroshare-gui/src/gui/chat/ChatStyle.cpp b/retroshare-gui/src/gui/chat/ChatStyle.cpp index 7a5b7c2d5..9b97d30cf 100644 --- a/retroshare-gui/src/gui/chat/ChatStyle.cpp +++ b/retroshare-gui/src/gui/chat/ChatStyle.cpp @@ -145,7 +145,7 @@ void ChatStyle::styleChanged(int styleType) static QString getBaseDir() { // application path - QString baseDir = QString::fromUtf8(RsInit::RsConfigDirectory().c_str()); + QString baseDir = QString::fromUtf8(RsAccounts::ConfigDirectory().c_str()); #ifdef WIN32 if (RsInit::isPortable ()) { diff --git a/retroshare-gui/src/gui/profile/ProfileManager.cpp b/retroshare-gui/src/gui/profile/ProfileManager.cpp index dfa956d2e..2f542d28a 100644 --- a/retroshare-gui/src/gui/profile/ProfileManager.cpp +++ b/retroshare-gui/src/gui/profile/ProfileManager.cpp @@ -99,10 +99,10 @@ void ProfileManager::fillIdentities() std::list pgpIds; std::list::iterator it; - if (RsInit::GetPGPLogins(pgpIds)) { + if (RsAccounts::GetPGPLogins(pgpIds)) { for (it = pgpIds.begin(); it != pgpIds.end(); it++) { std::string name, email; - RsInit::GetPGPLoginDetails(*it, name, email); + RsAccounts::GetPGPLoginDetails(*it, name, email); std::cerr << "Adding PGPUser: " << name << " id: " << *it << std::endl; QString gid = QString::fromStdString(*it); @@ -138,7 +138,7 @@ void ProfileManager::exportIdentity() fname += ".asc"; } - if (RsInit::exportIdentity(fname.toUtf8().constData(), gpgId)) + if (RsAccounts::ExportIdentity(fname.toUtf8().constData(), gpgId)) QMessageBox::information(this, tr("Identity saved"), tr("Your identity was successfully saved\nIt is encrypted\n\nYou can now copy it to another computer\nand use the import button to load it")); else QMessageBox::information(this, tr("Identity not saved"), tr("Your identity was not saved. An error occurred.")); @@ -154,7 +154,7 @@ void ProfileManager::importIdentity() std::string gpg_id ; std::string err_string ; - if(!RsInit::importIdentity(fname.toUtf8().constData(),gpg_id,err_string)) + if(!RsAccounts::ImportIdentity(fname.toUtf8().constData(),gpg_id,err_string)) { QMessageBox::information(this,tr("Identity not loaded"),tr("Your identity was not loaded properly:")+" \n "+QString::fromStdString(err_string)) ; return ; @@ -163,7 +163,7 @@ void ProfileManager::importIdentity() { std::string name,email ; - RsInit::GetPGPLoginDetails(gpg_id, name, email); + RsAccounts::GetPGPLoginDetails(gpg_id, name, email); std::cerr << "Adding PGPUser: " << name << " id: " << gpg_id << std::endl; QMessageBox::information(this,tr("New identity imported"),tr("Your identity was imported successfully:")+" \n"+"\nName :"+QString::fromStdString(name)+"\nemail: " + QString::fromStdString(email)+"\nKey ID: "+QString::fromStdString(gpg_id)+"\n\n"+tr("You can use it now to create a new location.")) ; diff --git a/retroshare-gui/src/gui/settings/RsharePeerSettings.cpp b/retroshare-gui/src/gui/settings/RsharePeerSettings.cpp index 33d2c0279..3318d9506 100644 --- a/retroshare-gui/src/gui/settings/RsharePeerSettings.cpp +++ b/retroshare-gui/src/gui/settings/RsharePeerSettings.cpp @@ -36,7 +36,7 @@ #include "gui/style/RSStyle.h" /** The file in which all settings of he peers will read and written. */ -#define SETTINGS_FILE (QString::fromUtf8(RsInit::RsProfileConfigDirectory().c_str()) + "/RSPeers.conf") +#define SETTINGS_FILE (QString::fromUtf8(RsAccounts::ConfigDirectory().c_str()) + "/RSPeers.conf") /* clean dead id's after these days */ #define DAYS_TO_CLEAN 7 diff --git a/retroshare-gui/src/gui/settings/ServerPage.cpp b/retroshare-gui/src/gui/settings/ServerPage.cpp index edeaada4b..752887f3e 100755 --- a/retroshare-gui/src/gui/settings/ServerPage.cpp +++ b/retroshare-gui/src/gui/settings/ServerPage.cpp @@ -35,7 +35,7 @@ #include ServerPage::ServerPage(QWidget * parent, Qt::WFlags flags) - : ConfigPage(parent, flags) + : ConfigPage(parent, flags), mIsHiddenNode(false) { /* Invoke the Qt Designer generated object setup routine */ ui.setupUi(this); @@ -84,10 +84,14 @@ ServerPage::ServerPage(QWidget * parent, Qt::WFlags flags) ui.tabWidget->widget(2)->layout()->addItem(verticalSpacer) ; ui.tabWidget->widget(2)->layout()->update() ; + ui.torPort->setVisible(false); /* Hide platform specific features */ #ifdef Q_WS_WIN #endif + + std::cerr << "ServerPage::ServerPage() called"; + std::cerr << std::endl; } void ServerPage::showRoutingInfo() @@ -135,6 +139,8 @@ ServerPage::save(QString &/*errmsg*/) /** Loads the settings for this page */ void ServerPage::load() { + std::cerr << "ServerPage::load() called"; + std::cerr << std::endl; /* load up configuration from rsPeers */ RsPeerDetails detail; @@ -143,6 +149,13 @@ void ServerPage::load() return; } + mIsHiddenNode = (detail.netMode == RS_NETMODE_HIDDEN); + if (mIsHiddenNode) + { + loadHiddenNode(); + return; + } + /* set net mode */ int netIndex = 0; switch(detail.netMode) @@ -236,12 +249,21 @@ void ServerPage::toggleTurtleRouting(bool b) /** Loads the settings for this page */ void ServerPage::updateStatus() { + std::cerr << "ServerPage::updateStatusd() called"; + std::cerr << std::endl; + if(RsAutoUpdatePage::eventsLocked()) return ; if(!isVisible()) return ; + if (mIsHiddenNode) + { + updateStatusHiddenNode(); + return; + } + /* load up configuration from rsPeers */ RsPeerDetails detail; if (!rsPeers->getPeerDetails(rsPeers->getOwnId(), detail)) @@ -315,6 +337,12 @@ void ServerPage::saveAddresses() bool saveAddr = false; + if (mIsHiddenNode) + { + saveAddressesHiddenNode(); + return; + } + RsPeerDetails detail; std::string ownId = rsPeers->getOwnId(); @@ -327,6 +355,9 @@ void ServerPage::saveAddresses() uint32_t netMode = 0; switch(netIndex) { + case 3: + netMode = RS_NETMODE_HIDDEN; + break; case 2: netMode = RS_NETMODE_EXT; break; @@ -384,3 +415,219 @@ void ServerPage::saveAddresses() load(); } + +/***********************************************************************************/ +/***********************************************************************************/ +/******* ALTERNATIVE VERSION IF HIDDEN NODE ***************************************/ +/***********************************************************************************/ +/***********************************************************************************/ + +/** Loads the settings for this page */ +void ServerPage::loadHiddenNode() +{ + std::cerr << "ServerPage::loadHiddenNode() called"; + std::cerr << std::endl; + + /* load up configuration from rsPeers */ + RsPeerDetails detail; + if (!rsPeers->getPeerDetails(rsPeers->getOwnId(), detail)) + { + return; + } + + /* At this point we want to force the Configuration Page to look different + * We will be called multiple times - so cannot just delete bad items. + * + * We want: + * NETMODE: HiddenNode FIXED. + * Disc/DHT: Discovery / No Discovery. + * Local Address: 127.0.0.1, Port: Listening Port. (listening port changable) + * External Address ==> TOR Address: 17621376587.onion + PORT. + * + * Known / Previous IPs: empty / removed. + * Ask about IP: Disabled. + */ + + // FIXED. + ui.netModeComboBox->setCurrentIndex(3); + ui.netModeComboBox->setEnabled(false); + + // CHANGE OPTIONS ON + ui.discComboBox->removeItem(3); + ui.discComboBox->removeItem(2); + ui.discComboBox->removeItem(1); + ui.discComboBox->removeItem(0); + ui.discComboBox->insertItem (0, tr("Discovery On (recommended)")); + ui.discComboBox->insertItem (1, tr("Discovery Off")); + + int netIndex = 1; // OFF. + if (detail.vs_disc != RS_VS_DISC_OFF) + { + netIndex = 0; // DISC ON; + } + ui.discComboBox->setCurrentIndex(netIndex); + + // Download Rates - Stay the same as before. + int dlrate = 0; + int ulrate = 0; + rsConfig->GetMaxDataRates(dlrate, ulrate); + ui.totalDownloadRate->setValue(dlrate); + ui.totalUploadRate->setValue(ulrate); + + // Addresses. + ui.localAddress->setEnabled(false); + ui.localPort -> setEnabled(true); + ui.extAddress -> setEnabled(true); + ui.extPort -> setEnabled(true); + + /* Addresses must be set here - otherwise can't edit it */ + /* set local address */ + ui.localAddress->setText(QString::fromStdString(detail.localAddr)); + ui.localPort -> setValue(detail.localPort); + /* set the server address */ + + + ui.label_extAddress->setText(tr("TOR Onion Address")); + ui.extAddress->setText(QString::fromStdString(detail.hiddenNodeAddress)); + ui.extPort -> setValue(detail.hiddenNodePort); + + /* set DynDNS */ + ui.label_dynDNS -> setText("TOR Server Port"); + + std::string proxyaddr; + uint16_t proxyport; + rsPeers->getProxyServer(proxyaddr, proxyport); + + ui.dynDNS -> setText(QString::fromStdString(proxyaddr)); + ui.torPort -> setVisible(true); + ui.torPort -> setValue(proxyport); + + ui.showDiscStatusBar->setChecked(Settings->getStatusBarFlags() & STATUSBAR_DISC); + + ui._max_tr_up_per_sec_SB->setValue(rsTurtle->getMaxTRForwardRate()) ; + ui._turtle_enabled_CB->setChecked(rsTurtle->enabled()) ; + + // show what we have in ipAddresses. (should be nothing!) + ui.ipAddressList->clear(); + for(std::list::const_iterator it(detail.ipAddressList.begin());it!=detail.ipAddressList.end();++it) + ui.ipAddressList->addItem(QString::fromStdString(*it)); + + ui.iconlabel_upnp->setPixmap(QPixmap(":/images/ledoff1.png")); + ui.iconlabel_netLimited->setPixmap(QPixmap(":/images/ledoff1.png")); + ui.iconlabel_ext->setPixmap(QPixmap(":/images/ledoff1.png")); + + ui.allowIpDeterminationCB->setChecked(false); + ui.allowIpDeterminationCB->setEnabled(false); + ui.IPServersLV->setEnabled(false); +} + +/** Loads the settings for this page */ +void ServerPage::updateStatusHiddenNode() +{ + std::cerr << "ServerPage::updateStatusHiddenNode() called"; + std::cerr << std::endl; + +// THIS IS DISABLED FOR NOW. +#if 0 + + /* load up configuration from rsPeers */ + RsPeerDetails detail; + if (!rsPeers->getPeerDetails(rsPeers->getOwnId(), detail)) + return; + + /* only update if can't edit */ + if (!ui.localPort->isEnabled()) + { + /* set local address */ + ui.localPort -> setValue(detail.localPort); + ui.extPort -> setValue(detail.extPort); + } + + /* set local address */ + ui.localAddress->setText(QString::fromStdString(detail.localAddr)); + /* set the server address */ + ui.extAddress->setText(QString::fromStdString(detail.extAddr)); + + + // Now update network bits. + RsConfigNetStatus net_status; + rsConfig->getConfigNetStatus(net_status); + + /******* Network Status Tab *******/ + + if(net_status.netUpnpOk) + ui.iconlabel_upnp->setPixmap(QPixmap(":/images/ledon1.png")); + else + ui.iconlabel_upnp->setPixmap(QPixmap(":/images/ledoff1.png")); + + if (net_status.netLocalOk) + ui.iconlabel_netLimited->setPixmap(QPixmap(":/images/ledon1.png")); + else + ui.iconlabel_netLimited->setPixmap(QPixmap(":/images/ledoff1.png")); + + if (net_status.netExtAddressOk) + ui.iconlabel_ext->setPixmap(QPixmap(":/images/ledon1.png")); + else + ui.iconlabel_ext->setPixmap(QPixmap(":/images/ledoff1.png")); + +#endif + +} + +void ServerPage::saveAddressesHiddenNode() +{ + RsPeerDetails detail; + std::string ownId = rsPeers->getOwnId(); + + if (!rsPeers->getPeerDetails(ownId, detail)) + return; + + // NETMODE IS UNCHANGABLE + uint16_t vs_disc = 0; + uint16_t vs_dht = 0; + /* Check if vis has changed */ + switch(ui.discComboBox->currentIndex()) + { + default: + case 0: + vs_disc = RS_VS_DISC_FULL; + vs_dht = RS_VS_DHT_OFF; + break; + case 1: + vs_disc = RS_VS_DISC_OFF; + vs_dht = RS_VS_DHT_OFF; + break; + } + + if ((vs_disc != detail.vs_disc) || (vs_dht != detail.vs_dht)) + rsPeers->setVisState(ownId, vs_disc, vs_dht); + + // Work out what we do with addresses! + //rsPeers->setLocalAddress(ownId, ui.localAddress->text().toStdString(), ui.localPort->value()); + //rsPeers->setExtAddress(ownId, ui.extAddress->text().toStdString(), ui.extPort->value()); + + std::string hiddenAddr = ui.extAddress->text().toStdString(); + uint16_t hiddenPort = ui.extPort->value(); + if ((hiddenAddr != detail.hiddenNodeAddress) || (hiddenPort != detail.hiddenNodePort)) + { + rsPeers->setHiddenNode(ownId, hiddenAddr, hiddenPort); + } + + + // HANDLE PROXY SERVER. + std::string orig_proxyaddr; + uint16_t orig_proxyport; + rsPeers->getProxyServer(orig_proxyaddr, orig_proxyport); + + std::string new_proxyaddr = ui.dynDNS -> text().toStdString(); + uint16_t new_proxyport = ui.torPort -> value(); + + if ((new_proxyaddr != orig_proxyaddr) || (new_proxyport != orig_proxyport)) + { + rsPeers->setProxyServer(new_proxyaddr, new_proxyport); + } + + rsConfig->SetMaxDataRates( ui.totalDownloadRate->value(), ui.totalUploadRate->value() ); + load(); +} + diff --git a/retroshare-gui/src/gui/settings/ServerPage.h b/retroshare-gui/src/gui/settings/ServerPage.h index df474e251..a7b019b0c 100755 --- a/retroshare-gui/src/gui/settings/ServerPage.h +++ b/retroshare-gui/src/gui/settings/ServerPage.h @@ -56,9 +56,18 @@ private slots: void toggleTurtleRouting(bool) ; private: + + // Alternative Versions for HiddenNode Mode. + void loadHiddenNode(); + void updateStatusHiddenNode(); + void saveAddressesHiddenNode(); + + Ui::ServerPage ui; TurtleRouterDialog *_routing_info_page ; + + bool mIsHiddenNode; }; #endif // !SERVERPAGE_H diff --git a/retroshare-gui/src/gui/settings/ServerPage.ui b/retroshare-gui/src/gui/settings/ServerPage.ui index c3ddbdd4a..00250ebf3 100755 --- a/retroshare-gui/src/gui/settings/ServerPage.ui +++ b/retroshare-gui/src/gui/settings/ServerPage.ui @@ -126,14 +126,14 @@ peers still need to trust each other to allow connection. - + External Address - + Dynamic DNS @@ -159,10 +159,10 @@ peers still need to trust each other to allow connection. - Acceptable ports range from 1024 to 65535. Ports below 1024 are reserved by your system. + Acceptable ports range from 10 to 65535. Normally Ports below 1024 are reserved by your system. - 1024 + 10 65535 @@ -185,10 +185,10 @@ peers still need to trust each other to allow connection. - Acceptable ports range from 1024 to 65535. Ports below 1024 are reserved by your system. + Acceptable ports range from 10 to 65535. Normally ports below 1024 are reserved by your system. - 1024 + 10 65535 @@ -201,6 +201,29 @@ peers still need to trust each other to allow connection.
+ + + + The Port that TOR is listening to for outgoing connections. Normally 9100 or 9150 + + + 1024 + + + 65535 + + + 9100 + + + + + + + Port: + + + diff --git a/retroshare-gui/src/gui/settings/rsettings.cpp b/retroshare-gui/src/gui/settings/rsettings.cpp index bec614976..3bc84a206 100644 --- a/retroshare-gui/src/gui/settings/rsettings.cpp +++ b/retroshare-gui/src/gui/settings/rsettings.cpp @@ -27,14 +27,14 @@ #include /** The file in which all settings will read and written. */ -#define SETTINGS_FILE (QString::fromUtf8(RsInit::RsProfileConfigDirectory().c_str()) + "/RetroShare.conf") +#define SETTINGS_FILE (QString::fromUtf8(RsAccounts::AccountDirectory().c_str()) + "/RetroShare.conf") /** Constructor */ RSettings::RSettings(const QString settingsGroup) : QSettings(SETTINGS_FILE, QSettings::IniFormat) { std::string sPreferedId; - m_bValid = RsInit::getPreferedAccountId(sPreferedId); + m_bValid = RsAccounts::GetPreferredAccountId(sPreferedId); if (!settingsGroup.isEmpty()) beginGroup(settingsGroup); diff --git a/retroshare-gui/src/lang/languagesupport.cpp b/retroshare-gui/src/lang/languagesupport.cpp index aea4f50e1..cee03da07 100644 --- a/retroshare-gui/src/lang/languagesupport.cpp +++ b/retroshare-gui/src/lang/languagesupport.cpp @@ -31,7 +31,7 @@ static QMap translatorPlugins; -#define EXTERNAL_TRANSLATION_DIR QString::fromUtf8(RsInit::getRetroshareDataDirectory().c_str()) +#define EXTERNAL_TRANSLATION_DIR QString::fromUtf8(RsAccounts::DataDirectory().c_str()) /** Initializes the list of available languages. */ QMap diff --git a/retroshare-gui/src/main.cpp b/retroshare-gui/src/main.cpp index 80213f834..5ea4730b8 100644 --- a/retroshare-gui/src/main.cpp +++ b/retroshare-gui/src/main.cpp @@ -59,14 +59,17 @@ static void displayWarningAboutDSAKeys() { - if(RsInit::unsupported_keys.empty()) + std::map > unsupported_keys; + RsAccounts::GetUnsupportedKeys(unsupported_keys); + + if(unsupported_keys.empty()) return ; QMessageBox msgBox; QString txt = QObject::tr("You appear to have locations associated to DSA keys:"); txt += "
    " ; - for(std::map >::const_iterator it(RsInit::unsupported_keys.begin());it!=RsInit::unsupported_keys.end();++it) + for(std::map >::const_iterator it(unsupported_keys.begin());it!=unsupported_keys.end();++it) { txt += "
  • " + QString::fromStdString(it->first) ; txt += "
      " ; @@ -134,7 +137,7 @@ int main(int argc, char *argv[]) return 0 ; if(ret == QMessageBox::Ok) { - if(!RsInit::copyGnuPGKeyrings()) + if(!RsAccounts::CopyGnuPGKeyrings()) return 0 ; initResult = RsInit::InitRetroShare(argc, argv); @@ -180,7 +183,7 @@ int main(int argc, char *argv[]) /* Setup The GUI Stuff */ Rshare rshare(args, argc, argv, - QString::fromUtf8(RsInit::RsConfigDirectory().c_str())); + QString::fromUtf8(RsAccounts::ConfigDirectory().c_str())); std::string url = RsInit::getRetroShareLink(); if (!url.empty()) { @@ -202,7 +205,7 @@ int main(int argc, char *argv[]) /* check for existing Certificate */ bool genCert = false; std::list accountIds; - if (RsInit::getAccountIds(accountIds) && (accountIds.size() > 0)) + if (RsAccounts::GetAccountIds(accountIds) && (accountIds.size() > 0)) { StartDialog sd; if (sd.exec() == QDialog::Rejected) { @@ -234,7 +237,7 @@ int main(int argc, char *argv[]) splashScreen.showMessage(rshare.translate("SplashScreen", "Load profile"), Qt::AlignHCenter | Qt::AlignBottom); std::string preferredId; - RsInit::getPreferedAccountId(preferredId); + RsAccounts::GetPreferredAccountId(preferredId); // true: note auto-login is active Rshare::loadCertificate(preferredId, true); diff --git a/retroshare-gui/src/rshare.cpp b/retroshare-gui/src/rshare.cpp index 6427d6ef4..499a5de87 100644 --- a/retroshare-gui/src/rshare.cpp +++ b/retroshare-gui/src/rshare.cpp @@ -456,9 +456,9 @@ void Rshare::loadStyleSheet(const QString &sheetName) file.setFileName(":/qss/stylesheet/" + sheetName.mid(1) + ".qss"); } else { /* external stylesheet */ - file.setFileName(QString::fromUtf8(RsInit::RsConfigDirectory().c_str()) + "/qss/" + sheetName + ".qss"); + file.setFileName(QString::fromUtf8(RsAccounts::ConfigDirectory().c_str()) + "/qss/" + sheetName + ".qss"); if (!file.exists()) { - file.setFileName(QString::fromUtf8(RsInit::getRetroshareDataDirectory().c_str()) + "/qss/" + sheetName + ".qss"); + file.setFileName(QString::fromUtf8(RsAccounts::DataDirectory().c_str()) + "/qss/" + sheetName + ".qss"); } } if (file.open(QFile::ReadOnly)) { @@ -488,14 +488,14 @@ void Rshare::getAvailableStyleSheets(QMap &styleSheets) styleSheets.insert(QString("%1 (%2)").arg(name, tr("built-in")), ":" + name); } } - fileInfoList = QDir(QString::fromUtf8(RsInit::RsConfigDirectory().c_str()) + "/qss/").entryInfoList(QStringList("*.qss")); + fileInfoList = QDir(QString::fromUtf8(RsAccounts::ConfigDirectory().c_str()) + "/qss/").entryInfoList(QStringList("*.qss")); foreach (fileInfo, fileInfoList) { if (fileInfo.isFile()) { QString name = fileInfo.baseName(); styleSheets.insert(name, name); } } - fileInfoList = QDir(QString::fromUtf8(RsInit::getRetroshareDataDirectory().c_str()) + "/qss/").entryInfoList(QStringList("*.qss")); + fileInfoList = QDir(QString::fromUtf8(RsAccounts::DataDirectory().c_str()) + "/qss/").entryInfoList(QStringList("*.qss")); foreach (fileInfo, fileInfoList) { if (fileInfo.isFile()) { QString name = fileInfo.baseName(); @@ -613,15 +613,10 @@ void Rshare::blinkTimer() } } -bool Rshare::loadCertificate(const std::string &accountId, bool autoLogin, std::string gpgId) +bool Rshare::loadCertificate(const std::string &accountId, bool autoLogin) { - if (gpgId.empty()) { - std::string gpgName, gpgEmail, sslName; - if (!RsInit::getAccountDetails(accountId, gpgId, gpgName, gpgEmail, sslName)) { - return false; - } - } - if (!RsInit::SelectGPGAccount(gpgId)) { + if (!RsAccounts::SelectAccount(accountId)) + { return false; } diff --git a/retroshare-gui/src/rshare.h b/retroshare-gui/src/rshare.h index bcc956ef9..8a80042ce 100644 --- a/retroshare-gui/src/rshare.h +++ b/retroshare-gui/src/rshare.h @@ -89,7 +89,7 @@ public: /** Recalculates matching stylesheet for widget **/ static void refreshStyleSheet(QWidget *widget, bool processChildren); - static bool loadCertificate(const std::string &accountId, bool autoLogin, std::string gpgId = ""); + static bool loadCertificate(const std::string &accountId, bool autoLogin); /** * Update Language, Style and StyleSheet. From 12e7d739413f6d9e83388f0ebd53c984054ac812 Mon Sep 17 00:00:00 2001 From: drbob Date: Sat, 18 Jan 2014 04:40:39 +0000 Subject: [PATCH 67/83] Added ProxyServer to configuration. git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@7029 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/pqi/p3peermgr.cc | 89 ++++++++++++++++++++++++------ 1 file changed, 71 insertions(+), 18 deletions(-) diff --git a/libretroshare/src/pqi/p3peermgr.cc b/libretroshare/src/pqi/p3peermgr.cc index 10ddf5d0a..331d974b2 100644 --- a/libretroshare/src/pqi/p3peermgr.cc +++ b/libretroshare/src/pqi/p3peermgr.cc @@ -73,6 +73,13 @@ const uint32_t PEER_IP_CONNECT_STATE_MAX_LIST_SIZE = 4; #define MAX_AVAIL_PERIOD 230 //times a peer stay in available state when not connected #define MIN_RETRY_PERIOD 140 +static const std::string kConfigDefaultProxyServerIpAddr = "127.0.0.1"; +static const uint16_t kConfigDefaultProxyServerPort = 9050; // standard port. + +static const std::string kConfigKeyExtIpFinder = "USE_EXTR_IP_FINDER"; +static const std::string kConfigKeyProxyServerIpAddr = "PROXY_SERVER_IPADDR"; +static const std::string kConfigKeyProxyServerPort = "PROXY_SERVER_PORT"; + void printConnectState(std::ostream &out, peerState &peer); peerState::peerState() @@ -129,8 +136,10 @@ p3PeerMgrIMPL::p3PeerMgrIMPL(const std::string& ssl_own_id, // setup default ProxyServerAddress. sockaddr_storage_clear(mProxyServerAddress); - sockaddr_storage_ipv4_aton(mProxyServerAddress, "127.0.0.1"); - sockaddr_storage_ipv4_setport(mProxyServerAddress, 9150); + sockaddr_storage_ipv4_aton(mProxyServerAddress, + kConfigDefaultProxyServerIpAddr.c_str()); + sockaddr_storage_ipv4_setport(mProxyServerAddress, + kConfigDefaultProxyServerPort); } #ifdef PEER_DEBUG @@ -417,7 +426,11 @@ bool p3PeerMgrIMPL::setProxyServerAddress(const struct sockaddr_storage &proxy_a { RsStackMutex stack(mPeerMtx); /****** STACK LOCK MUTEX *******/ - mProxyServerAddress = proxy_addr; + if (!sockaddr_storage_same(mProxyServerAddress,proxy_addr)) + { + IndicateConfigChanged(); /**** INDICATE MSG CONFIG CHANGED! *****/ + mProxyServerAddress = proxy_addr; + } return true; } @@ -1483,6 +1496,10 @@ bool p3PeerMgrIMPL::saveList(bool &cleanup, std::list& saveData) cleanup = false; bool useExtAddrFinder = mNetMgr->getIPServersEnabled(); + // Store Proxy Server. + struct sockaddr_storage proxy_addr; + getProxyServerAddress(proxy_addr); + mPeerMtx.lock(); /****** MUTEX LOCKED *******/ RsPeerNetItem *item = new RsPeerNetItem(); @@ -1586,23 +1603,25 @@ bool p3PeerMgrIMPL::saveList(bool &cleanup, std::list& saveData) RsConfigKeyValueSet *vitem = new RsConfigKeyValueSet ; RsTlvKeyValue kv; - kv.key = "USE_EXTR_IP_FINDER" ; + kv.key = kConfigKeyExtIpFinder; kv.value = (useExtAddrFinder)?"TRUE":"FALSE" ; vitem->tlvkvs.pairs.push_back(kv) ; -#ifdef PEER_DEBUG - std::cout << "Pushing item for use_extr_addr_finder = " << useExtAddrFinder << std::endl ; -#endif + + std::cerr << "Saving proxyServerAddress: " << sockaddr_storage_tostring(proxy_addr); + std::cerr << std::endl; + + kv.key = kConfigKeyProxyServerIpAddr; + kv.value = sockaddr_storage_iptostring(proxy_addr); + vitem->tlvkvs.pairs.push_back(kv) ; + + kv.key = kConfigKeyProxyServerPort; + kv.value = sockaddr_storage_porttostring(proxy_addr); + vitem->tlvkvs.pairs.push_back(kv) ; + saveData.push_back(vitem); saveCleanupList.push_back(vitem); - // Now save config for network digging strategies - - RsConfigKeyValueSet *vitem2 = new RsConfigKeyValueSet ; - - saveData.push_back(vitem2); - saveCleanupList.push_back(vitem2); - /* save groups */ std::list::iterator groupIt; @@ -1633,7 +1652,9 @@ bool p3PeerMgrIMPL::loadList(std::list& load) // DEFAULTS. bool useExtAddrFinder = true; - + std::string proxyIpAddress = kConfigDefaultProxyServerIpAddr; + uint16_t proxyPort = kConfigDefaultProxyServerPort; + if (load.size() == 0) { std::cerr << "p3PeerMgrIMPL::loadList() list is empty, it may be a configuration problem." << std::endl; return false; @@ -1714,11 +1735,26 @@ bool p3PeerMgrIMPL::loadList(std::list& load) std::cerr << std::endl; #endif std::list::iterator kit; - for(kit = vitem->tlvkvs.pairs.begin(); kit != vitem->tlvkvs.pairs.end(); kit++) { - if(kit->key == "USE_EXTR_IP_FINDER") { + for(kit = vitem->tlvkvs.pairs.begin(); kit != vitem->tlvkvs.pairs.end(); kit++) + { + if (kit->key == kConfigKeyExtIpFinder) + { useExtAddrFinder = (kit->value == "TRUE"); std::cerr << "setting use_extr_addr_finder to " << useExtAddrFinder << std::endl ; } + else if (kit->key == kConfigKeyProxyServerIpAddr) + { + proxyIpAddress = kit->value; + std::cerr << "Loaded proxyIpAddress: " << proxyIpAddress; + std::cerr << std::endl ; + + } + else if (kit->key == kConfigKeyProxyServerPort) + { + proxyPort = atoi(kit->value.c_str()); + std::cerr << "Loaded proxyPort: " << proxyPort; + std::cerr << std::endl ; + } } delete(*it); @@ -1815,8 +1851,25 @@ bool p3PeerMgrIMPL::loadList(std::list& load) } } + // If we are hidden - don't want ExtAddrFinder - ever! + if (isHidden()) + { + useExtAddrFinder = false; + } + mNetMgr->setIPServersEnabled(useExtAddrFinder); - + + // Configure Proxy Server. + struct sockaddr_storage proxy_addr; + sockaddr_storage_clear(proxy_addr); + sockaddr_storage_ipv4_aton(proxy_addr, proxyIpAddress.c_str()); + sockaddr_storage_ipv4_setport(proxy_addr, proxyPort); + + if (sockaddr_storage_isValidNet(proxy_addr)) + { + setProxyServerAddress(proxy_addr); + } + return true; } From ee09c3ce9c02f0021398dd5adabcaca8dfe7e3d9 Mon Sep 17 00:00:00 2001 From: drbob Date: Sat, 18 Jan 2014 05:05:35 +0000 Subject: [PATCH 68/83] Allow Local Address to be saved and modified in hidden mode. git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@7030 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/pqi/p3peermgr.cc | 3 ++- retroshare-gui/src/gui/settings/ServerPage.cpp | 7 ++++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/libretroshare/src/pqi/p3peermgr.cc b/libretroshare/src/pqi/p3peermgr.cc index 331d974b2..9c30aef2f 100644 --- a/libretroshare/src/pqi/p3peermgr.cc +++ b/libretroshare/src/pqi/p3peermgr.cc @@ -1701,7 +1701,8 @@ bool p3PeerMgrIMPL::loadList(std::list& load) if (pitem->netMode == RS_NET_MODE_HIDDEN) { - /* set only the hidden stuff */ + /* set only the hidden stuff & localAddress */ + setLocalAddress(pitem->pid, pitem->localAddrV4.addr); setHiddenDomainPort(pitem->pid, pitem->domain_addr, pitem->domain_port); } diff --git a/retroshare-gui/src/gui/settings/ServerPage.cpp b/retroshare-gui/src/gui/settings/ServerPage.cpp index 752887f3e..335827c27 100755 --- a/retroshare-gui/src/gui/settings/ServerPage.cpp +++ b/retroshare-gui/src/gui/settings/ServerPage.cpp @@ -603,9 +603,14 @@ void ServerPage::saveAddressesHiddenNode() rsPeers->setVisState(ownId, vs_disc, vs_dht); // Work out what we do with addresses! - //rsPeers->setLocalAddress(ownId, ui.localAddress->text().toStdString(), ui.localPort->value()); //rsPeers->setExtAddress(ownId, ui.extAddress->text().toStdString(), ui.extPort->value()); + if (detail.localPort != ui.localPort->value()) + { + // Set Local Address - force to 127.0.0.1 + rsPeers->setLocalAddress(ownId, "127.0.0.1", ui.localPort->value()); + } + std::string hiddenAddr = ui.extAddress->text().toStdString(); uint16_t hiddenPort = ui.extPort->value(); if ((hiddenAddr != detail.hiddenNodeAddress) || (hiddenPort != detail.hiddenNodePort)) From b741503803a18e6d23f87dadda382a603b0aeeb4 Mon Sep 17 00:00:00 2001 From: drbob Date: Sat, 18 Jan 2014 05:27:54 +0000 Subject: [PATCH 69/83] Added port to hidden address. git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@7031 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/pgp/rscertificate.cc | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/libretroshare/src/pgp/rscertificate.cc b/libretroshare/src/pgp/rscertificate.cc index a8cef7f7e..136f67a89 100644 --- a/libretroshare/src/pgp/rscertificate.cc +++ b/libretroshare/src/pgp/rscertificate.cc @@ -7,6 +7,7 @@ #include #include #include "rscertificate.h" +#include "util/rsstring.h" //#define DEBUG_RSCERTIFICATE @@ -154,7 +155,8 @@ RsCertificate::RsCertificate(const RsPeerDetails& Detail, const unsigned char *b if (Detail.isHiddenNode) { hidden_node = true; - hidden_node_address = Detail.hiddenNodeAddress; + hidden_node_address = Detail.hiddenNodeAddress; + rs_sprintf_append(hidden_node_address, ":%u", Detail.hiddenNodePort); memset(ipv4_internal_ip_and_port,0,6) ; memset(ipv4_external_ip_and_port,0,6) ; From 8c8baae0449b85b42c077b50de56e1b8e0d487a3 Mon Sep 17 00:00:00 2001 From: drbob Date: Sat, 18 Jan 2014 05:42:44 +0000 Subject: [PATCH 70/83] fixed bad parse of addresses in certificate. git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@7032 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/pgp/rscertificate.cc | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/libretroshare/src/pgp/rscertificate.cc b/libretroshare/src/pgp/rscertificate.cc index 136f67a89..7fad53836 100644 --- a/libretroshare/src/pgp/rscertificate.cc +++ b/libretroshare/src/pgp/rscertificate.cc @@ -167,8 +167,28 @@ RsCertificate::RsCertificate(const RsPeerDetails& Detail, const unsigned char *b hidden_node = false; hidden_node_address = ""; - scan_ip(Detail.localAddr,Detail.localPort,ipv4_internal_ip_and_port) ; - scan_ip(Detail.extAddr,Detail.extPort,ipv4_external_ip_and_port) ; + try + { + scan_ip(Detail.localAddr,Detail.localPort,ipv4_internal_ip_and_port) ; + } + catch(...) + { + std::cerr << "RsCertificate::Invalid LocalAddress"; + std::cerr << std::endl; + memset(ipv4_internal_ip_and_port,0,6) ; + } + + + try + { + scan_ip(Detail.extAddr,Detail.extPort,ipv4_external_ip_and_port) ; + } + catch(...) + { + std::cerr << "RsCertificate::Invalid ExternalAddress"; + std::cerr << std::endl; + memset(ipv4_external_ip_and_port,0,6) ; + } dns_name = Detail.dyndns ; } From affdd49001f0aeb30e791ab24b46170216d12d4a Mon Sep 17 00:00:00 2001 From: csoler Date: Sat, 18 Jan 2014 16:53:19 +0000 Subject: [PATCH 71/83] made cert of versions 0.5 and 0.6 incompatible. Removed old cert format parse/display git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@7033 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/pgp/rscertificate.cc | 41 +++++++++++++++---- libretroshare/src/retroshare/rspeers.h | 1 + .../src/gui/connect/ConnectFriendWizard.cpp | 6 ++- .../src/gui/settings/CryptoPage.cpp | 3 ++ 4 files changed, 41 insertions(+), 10 deletions(-) diff --git a/libretroshare/src/pgp/rscertificate.cc b/libretroshare/src/pgp/rscertificate.cc index 7fad53836..e5707d1c8 100644 --- a/libretroshare/src/pgp/rscertificate.cc +++ b/libretroshare/src/pgp/rscertificate.cc @@ -9,7 +9,7 @@ #include "rscertificate.h" #include "util/rsstring.h" -//#define DEBUG_RSCERTIFICATE +#define DEBUG_RSCERTIFICATE static const std::string PGP_CERTIFICATE_START ( "-----BEGIN PGP PUBLIC KEY BLOCK-----" ); static const std::string PGP_CERTIFICATE_END ( "-----END PGP PUBLIC KEY BLOCK-----" ); @@ -27,6 +27,9 @@ static const uint8_t CERTIFICATE_PTAG_SSLID_SECTION = 0x05 ; static const uint8_t CERTIFICATE_PTAG_NAME_SECTION = 0x06 ; static const uint8_t CERTIFICATE_PTAG_CHECKSUM_SECTION = 0x07 ; static const uint8_t CERTIFICATE_PTAG_HIDDENNODE_SECTION = 0x08 ; +static const uint8_t CERTIFICATE_PTAG_VERSION_SECTION = 0x09 ; + +static const uint8_t CERTIFICATE_VERSION_06 = 0x06 ; static bool is_acceptable_radix64Char(char c) { @@ -74,7 +77,8 @@ std::string RsCertificate::toStdString() const size_t p = 0 ; unsigned char *buf = new unsigned char[BS] ; - addPacket( CERTIFICATE_PTAG_PGP_SECTION , binary_pgp_key , binary_pgp_key_size , buf, p, BS ) ; + addPacket( CERTIFICATE_PTAG_VERSION_SECTION, &CERTIFICATE_VERSION_06 , 1 , buf, p, BS ) ; + addPacket( CERTIFICATE_PTAG_PGP_SECTION , binary_pgp_key , binary_pgp_key_size , buf, p, BS ) ; if(!only_pgp) { @@ -132,7 +136,7 @@ RsCertificate::RsCertificate(const std::string& str) { uint32_t err_code ; - if(!initFromString(str,err_code) && !initFromString_oldFormat(str,err_code)) + if(!initFromString(str,err_code)) // && !initFromString_oldFormat(str,err_code)) throw err_code ; } @@ -252,6 +256,7 @@ bool RsCertificate::initFromString(const std::string& instr,uint32_t& err_code) unsigned char *buf = (unsigned char *)bf ; size_t total_s = 0 ; only_pgp = true ; + uint8_t certificate_version = 0x00 ; while(total_s < size) { @@ -272,8 +277,13 @@ bool RsCertificate::initFromString(const std::string& instr,uint32_t& err_code) #ifdef DEBUG_RSCERTIFICATE std::cerr << "Packet parse: read ptag " << (int)ptag << ", size " << s << ", total_s = " << total_s << ", expected total = " << size << std::endl; #endif + switch(ptag) { + case CERTIFICATE_PTAG_VERSION_SECTION: certificate_version = buf[0] ; + buf = &buf[s] ; + break ; + case CERTIFICATE_PTAG_PGP_SECTION: binary_pgp_key = new unsigned char[s] ; memcpy(binary_pgp_key,buf,s) ; binary_pgp_key_size = s ; @@ -360,6 +370,15 @@ bool RsCertificate::initFromString(const std::string& instr,uint32_t& err_code) return false ; } + if(certificate_version != CERTIFICATE_VERSION_06) + { + err_code = CERTIFICATE_PARSING_ERROR_WRONG_VERSION ; + return false ; + } +#ifdef DEBUG_RSCERTIFICATE + std::cerr << "Certificate is version " << (int)certificate_version << std::endl; +#endif + if(total_s != size) std::cerr << "(EE) Certificate contains trailing characters. Weird." << std::endl; @@ -416,11 +435,11 @@ unsigned short RsCertificate::loc_port_us() const bool RsCertificate::cleanCertificate(const std::string& input,std::string& output,Format& format,int& error_code) { - if(cleanCertificate_oldFormat(input,output,error_code)) - { - format = RS_CERTIFICATE_OLD_FORMAT ; - return true ; - } +// if(cleanCertificate_oldFormat(input,output,error_code)) +// { +// format = RS_CERTIFICATE_OLD_FORMAT ; +// return true ; +// } if(cleanCertificate(input,output,error_code)) { @@ -843,6 +862,10 @@ bool RsCertificate::cleanCertificate_oldFormat(const std::string& certstr,std::s std::string RsCertificate::toStdString_oldFormat() const { + return std::string() ; + + // not supported anymore. + // std::string res ; res += PGPKeyManagement::makeArmouredKey(binary_pgp_key,binary_pgp_key_size,pgp_version) ; @@ -891,6 +914,8 @@ std::string RsCertificate::toStdString_oldFormat() const bool RsCertificate::initFromString_oldFormat(const std::string& certstr,uint32_t& /*err_code*/) { + return false ; // this format is not supported anymore. + //parse the text to get ip address try { diff --git a/libretroshare/src/retroshare/rspeers.h b/libretroshare/src/retroshare/rspeers.h index b7140a0f7..f4ed8dc33 100644 --- a/libretroshare/src/retroshare/rspeers.h +++ b/libretroshare/src/retroshare/rspeers.h @@ -112,6 +112,7 @@ const uint32_t CERTIFICATE_PARSING_ERROR_INVALID_CHECKSUM_SECTION = 0x15 ; const uint32_t CERTIFICATE_PARSING_ERROR_CHECKSUM_ERROR = 0x16 ; const uint32_t CERTIFICATE_PARSING_ERROR_UNKNOWN_SECTION_PTAG = 0x17 ; const uint32_t CERTIFICATE_PARSING_ERROR_MISSING_CHECKSUM = 0x18 ; +const uint32_t CERTIFICATE_PARSING_ERROR_WRONG_VERSION = 0x19 ; const uint32_t PGP_KEYRING_REMOVAL_ERROR_NO_ERROR = 0x20 ; const uint32_t PGP_KEYRING_REMOVAL_ERROR_CANT_REMOVE_SECRET_KEYS = 0x21 ; diff --git a/retroshare-gui/src/gui/connect/ConnectFriendWizard.cpp b/retroshare-gui/src/gui/connect/ConnectFriendWizard.cpp index 211be996f..6219950eb 100755 --- a/retroshare-gui/src/gui/connect/ConnectFriendWizard.cpp +++ b/retroshare-gui/src/gui/connect/ConnectFriendWizard.cpp @@ -108,6 +108,7 @@ QString ConnectFriendWizard::getErrorString(uint32_t error_code) case CERTIFICATE_PARSING_ERROR_INVALID_LOCAL_IP: return tr("Invalid local IP.") ; case CERTIFICATE_PARSING_ERROR_INVALID_CHECKSUM_SECTION: return tr("Invalid checksum section.") ; case CERTIFICATE_PARSING_ERROR_CHECKSUM_ERROR: return tr("Checksum mismatch. Certificate is corrupted.") ; + case CERTIFICATE_PARSING_ERROR_WRONG_VERSION: return tr("Certificate has wrong version number. Remember that v0.6 and v0.5 networks are incompatible.") ; case CERTIFICATE_PARSING_ERROR_UNKNOWN_SECTION_PTAG: return tr("Unknown section type found (Certificate might be corrupted).") ; case CERTIFICATE_PARSING_ERROR_MISSING_CHECKSUM: return tr("Missing checksum.") ; @@ -194,9 +195,10 @@ void ConnectFriendWizard::initializePage(int id) cleanfriendCertTimer->setInterval(1000); // 1 second connect(cleanfriendCertTimer, SIGNAL(timeout()), this, SLOT(cleanFriendCert())); - ui->userCertOldFormatButton->setChecked(true); + ui->userCertOldFormatButton->setChecked(false); + ui->userCertOldFormatButton->hide() ; - toggleFormatState(false); + toggleFormatState(true); toggleSignatureState(false); updateOwnCert(); diff --git a/retroshare-gui/src/gui/settings/CryptoPage.cpp b/retroshare-gui/src/gui/settings/CryptoPage.cpp index c988099f7..c9fa14fc4 100755 --- a/retroshare-gui/src/gui/settings/CryptoPage.cpp +++ b/retroshare-gui/src/gui/settings/CryptoPage.cpp @@ -49,6 +49,9 @@ CryptoPage::CryptoPage(QWidget * parent, Qt::WFlags flags) connect(ui._copyLink_PB, SIGNAL(clicked()), this, SLOT(copyRSLink())); connect(ui._useOldFormat_CB, SIGNAL(toggled(bool)), this, SLOT(load())); + ui._useOldFormat_CB->setEnabled(false) ; + ui._useOldFormat_CB->setChecked(false) ; + // hide profile manager as it causes bugs when generating a new profile. //ui.profile_Button->hide() ; From d39c5c028a96043f138e0c9b27ad0170c04358f1 Mon Sep 17 00:00:00 2001 From: drbob Date: Sat, 18 Jan 2014 23:29:22 +0000 Subject: [PATCH 72/83] fixed up hidden addresses and removed whitespace from onion address. git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@7036 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/pqi/p3peermgr.cc | 17 +++- libretroshare/src/rsserver/p3peers.cc | 77 ++++++++++++------- .../src/gui/connect/ConnectFriendWizard.cpp | 2 +- 3 files changed, 66 insertions(+), 30 deletions(-) diff --git a/libretroshare/src/pqi/p3peermgr.cc b/libretroshare/src/pqi/p3peermgr.cc index 9c30aef2f..a297069da 100644 --- a/libretroshare/src/pqi/p3peermgr.cc +++ b/libretroshare/src/pqi/p3peermgr.cc @@ -391,12 +391,25 @@ bool p3PeerMgrIMPL::setHiddenDomainPort(const std::string &ssl_id, const std::st std::cerr << "p3PeerMgrIMPL::setHiddenDomainPort()"; std::cerr << std::endl; + std::string domain = domain_addr; + // trim whitespace! + size_t pos = domain.find_last_not_of(" \t\n"); + if (std::string::npos != pos) + { + domain = domain.substr(0, pos + 1); + } + pos = domain.find_first_not_of(" \t\n"); + if (std::string::npos != pos) + { + domain = domain.substr(pos); + } + IndicateConfigChanged(); /**** INDICATE MSG CONFIG CHANGED! *****/ if (ssl_id == AuthSSL::getAuthSSL()->OwnId()) { mOwnState.hiddenNode = true; - mOwnState.hiddenDomain = domain_addr; + mOwnState.hiddenDomain = domain; mOwnState.hiddenPort = domain_port; std::cerr << "p3PeerMgrIMPL::setHiddenDomainPort() Set own State"; std::cerr << std::endl; @@ -413,7 +426,7 @@ bool p3PeerMgrIMPL::setHiddenDomainPort(const std::string &ssl_id, const std::st return false; } - it->second.hiddenDomain = domain_addr; + it->second.hiddenDomain = domain; it->second.hiddenPort = domain_port; it->second.hiddenNode = true; std::cerr << "p3PeerMgrIMPL::setHiddenDomainPort() Set Peers State"; diff --git a/libretroshare/src/rsserver/p3peers.cc b/libretroshare/src/rsserver/p3peers.cc index 330ef1e6e..97bbcf3fd 100644 --- a/libretroshare/src/rsserver/p3peers.cc +++ b/libretroshare/src/rsserver/p3peers.cc @@ -735,41 +735,58 @@ bool p3Peers::setLocation(const std::string &ssl_id, const std::string &locatio } +bool splitAddressString(const std::string &addr, std::string &domain, uint16_t &port) +{ + std::cerr << "splitAddressString() Input: " << addr << std::endl; + + size_t cpos = addr.rfind(':'); + if (cpos == std::string::npos) + { + std::cerr << "splitAddressString Failed to parse (:)"; + std::cerr << std::endl; + return false; + } + + int lenport = addr.length() - (cpos + 1); // +1 to skip over : char. + if (lenport <= 0) + { + std::cerr << "splitAddressString() Missing Port "; + std::cerr << std::endl; + return false; + } + + domain = addr.substr(0, cpos); + std::string portstr = addr.substr(cpos + 1, std::string::npos); + int portint = atoi(portstr.c_str()); + + if ((portint < 0) || (portint > 65535)) + { + std::cerr << "splitAddressString() Invalid Port"; + std::cerr << std::endl; + return false; + } + port = portint; + + std::cerr << "splitAddressString() Domain: " << domain << " Port: " << port; + std::cerr << std::endl; + return true; +} + + bool p3Peers::setHiddenNode(const std::string &id, const std::string &hidden_node_address) { #ifdef P3PEERS_DEBUG std::cerr << "p3Peers::setHiddenNode() " << id << std::endl; #endif - size_t cpos = hidden_node_address.rfind(':'); - if (cpos == std::string::npos) + std::string domain; + uint16_t port; + if (!splitAddressString(hidden_node_address, domain, port)) { - std::cerr << "p3Peers::setHiddenNode() Failed to parse (:) " << hidden_node_address << std::endl; return false; } - - int lenport = hidden_node_address.length() - (cpos + 1); // +1 to skip over : char. - if (lenport <= 0) - { - std::cerr << "p3Peers::setHiddenNode() Missing Port: " << hidden_node_address << std::endl; - return false; - } - - std::string domain = hidden_node_address.substr(0, cpos); - std::string port = hidden_node_address.substr(cpos + 1, std::string::npos); - int portint = atoi(port.c_str()); - - if ((portint < 0) || (portint > 65535)) - { - std::cerr << "p3Peers::setHiddenNode() Invalid Port: " << hidden_node_address << std::endl; - return false; - } - - std::cerr << "p3Peers::setHiddenNode() Domain: " << domain << " Port: " << portint; - std::cerr << std::endl; - mPeerMgr->setNetworkMode(id, RS_NET_MODE_HIDDEN); - mPeerMgr->setHiddenDomainPort(id, domain, (uint16_t) portint); + mPeerMgr->setHiddenDomainPort(id, domain, port); return true; } @@ -1049,8 +1066,14 @@ bool p3Peers::loadDetailsFromStringCert(const std::string &certstr, RsPeerDetai if (!cert.hidden_node_string().empty()) { pd.isHiddenNode = true; - pd.hiddenNodeAddress = cert.hidden_node_string(); - //pd.hiddenNodePort = cert.hidden_node_port(); + + std::string domain; + uint16_t port; + if (splitAddressString(cert.hidden_node_string(), domain, port)) + { + pd.hiddenNodeAddress = domain; + pd.hiddenNodePort = port; + } } else { diff --git a/retroshare-gui/src/gui/connect/ConnectFriendWizard.cpp b/retroshare-gui/src/gui/connect/ConnectFriendWizard.cpp index 6219950eb..0f5cd379f 100755 --- a/retroshare-gui/src/gui/connect/ConnectFriendWizard.cpp +++ b/retroshare-gui/src/gui/connect/ConnectFriendWizard.cpp @@ -631,7 +631,7 @@ void ConnectFriendWizard::accept() if (peerDetails.isHiddenNode) { std::cerr << "ConnectFriendWizard::accept() : setting hidden node." << std::endl; - rsPeers->setHiddenNode(peerDetails.id, peerDetails.hiddenNodeAddress); + rsPeers->setHiddenNode(peerDetails.id, peerDetails.hiddenNodeAddress, peerDetails.hiddenNodePort); } else { From 6526dd6c4bd21ad4451eecfff6b5b41c81046cd9 Mon Sep 17 00:00:00 2001 From: drbob Date: Sun, 19 Jan 2014 06:25:49 +0000 Subject: [PATCH 73/83] Tweaked linkmgr to allow loopback connections. This allows STD -> HIDDEN connections! git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@7037 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/pqi/p3linkmgr.cc | 14 +++++++++++++- libretroshare/src/pqi/pqisslpersongrp.cc | 3 ++- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/libretroshare/src/pqi/p3linkmgr.cc b/libretroshare/src/pqi/p3linkmgr.cc index 1557b0498..c18030b75 100644 --- a/libretroshare/src/pqi/p3linkmgr.cc +++ b/libretroshare/src/pqi/p3linkmgr.cc @@ -1709,7 +1709,7 @@ bool p3LinkMgrIMPL::locked_CheckPotentialAddr(const struct sockaddr_storage &ad } bool isValid = sockaddr_storage_isValidNet(addr); - // bool isLoopback = sockaddr_storage_isLoopbackNet(addr); + bool isLoopback = sockaddr_storage_isLoopbackNet(addr); // bool isPrivate = sockaddr_storage_isPrivateNet(addr); bool isExternal = sockaddr_storage_isExternalNet(addr); @@ -1753,6 +1753,18 @@ bool p3LinkMgrIMPL::locked_CheckPotentialAddr(const struct sockaddr_storage &ad } + /* if loopback, then okay - probably proxy connection (or local testing). + */ + if (isLoopback) + { +#ifdef LINKMGR_DEBUG + std::cerr << "p3LinkMgrIMPL::locked_CheckPotentialAddr() ACCEPTING - LOOPBACK"; + std::cerr << std::endl; +#endif + return true; + } + + /* get here, it is private or loopback * - can only connect to these addresses if we are on the same subnet. - check net against our local address. diff --git a/libretroshare/src/pqi/pqisslpersongrp.cc b/libretroshare/src/pqi/pqisslpersongrp.cc index a0fdb6733..12f654fbd 100644 --- a/libretroshare/src/pqi/pqisslpersongrp.cc +++ b/libretroshare/src/pqi/pqisslpersongrp.cc @@ -76,7 +76,8 @@ pqiperson * pqisslpersongrp::locked_createPerson(std::string id, pqilistener *li pqiperson *pqip = new pqiperson(id, this); // If using proxy, then only create a proxy item, otherwise can use any. - if (mPeerMgr->isHiddenPeer(id)) + // If we are a hidden node - then all connections should be via proxy. + if (mPeerMgr->isHiddenPeer(id) || mPeerMgr->isHidden()) { std::cerr << "pqisslpersongrp::locked_createPerson() Is Hidden Peer!"; std::cerr << std::endl; From 45bd72203e5ef12410cc0488149efad215d7e9d4 Mon Sep 17 00:00:00 2001 From: drbob Date: Sun, 19 Jan 2014 06:27:02 +0000 Subject: [PATCH 74/83] Added TOR Configuration page. Allows STD Nodes to configure Proxy too. Moved most of hidden node parameters to this page. git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@7038 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- .../src/gui/settings/ServerPage.cpp | 92 ++++-- retroshare-gui/src/gui/settings/ServerPage.ui | 296 ++++++++++++++++-- 2 files changed, 331 insertions(+), 57 deletions(-) diff --git a/retroshare-gui/src/gui/settings/ServerPage.cpp b/retroshare-gui/src/gui/settings/ServerPage.cpp index 335827c27..49d496c6e 100755 --- a/retroshare-gui/src/gui/settings/ServerPage.cpp +++ b/retroshare-gui/src/gui/settings/ServerPage.cpp @@ -84,7 +84,8 @@ ServerPage::ServerPage(QWidget * parent, Qt::WFlags flags) ui.tabWidget->widget(2)->layout()->addItem(verticalSpacer) ; ui.tabWidget->widget(2)->layout()->update() ; - ui.torPort->setVisible(false); + ui.torpage_incoming->setVisible(false); + /* Hide platform specific features */ #ifdef Q_WS_WIN @@ -236,6 +237,13 @@ void ServerPage::load() ui.ipAddressList->clear(); for(std::list::const_iterator it(detail.ipAddressList.begin());it!=detail.ipAddressList.end();++it) ui.ipAddressList->addItem(QString::fromStdString(*it)); + + /* TOR PAGE SETTINGS - only Proxy (outgoing) */ + std::string proxyaddr; + uint16_t proxyport; + rsPeers->getProxyServer(proxyaddr, proxyport); + ui.torpage_proxyAddress -> setText(QString::fromStdString(proxyaddr)); + ui.torpage_proxyPort -> setValue(proxyport); } void ServerPage::toggleTurtleRouting(bool b) @@ -412,6 +420,19 @@ void ServerPage::saveAddresses() rsPeers->setDynDNS(ownId, ui.dynDNS->text().toStdString()); rsConfig->SetMaxDataRates( ui.totalDownloadRate->value(), ui.totalUploadRate->value() ); + // HANDLE PROXY SERVER. + std::string orig_proxyaddr; + uint16_t orig_proxyport; + rsPeers->getProxyServer(orig_proxyaddr, orig_proxyport); + + std::string new_proxyaddr = ui.torpage_proxyAddress -> text().toStdString(); + uint16_t new_proxyport = ui.torpage_proxyPort -> value(); + + if ((new_proxyaddr != orig_proxyaddr) || (new_proxyport != orig_proxyport)) + { + rsPeers->setProxyServer(new_proxyaddr, new_proxyport); + } + load(); } @@ -476,9 +497,13 @@ void ServerPage::loadHiddenNode() // Addresses. ui.localAddress->setEnabled(false); - ui.localPort -> setEnabled(true); - ui.extAddress -> setEnabled(true); - ui.extPort -> setEnabled(true); + ui.localPort -> setEnabled(false); + ui.extAddress -> setEnabled(false); + ui.extPort -> setVisible(false); + ui.label_dynDNS->setVisible(false); + ui.dynDNS ->setVisible(false); + + ui.torpage_incoming->setVisible(true); /* Addresses must be set here - otherwise can't edit it */ /* set local address */ @@ -486,21 +511,7 @@ void ServerPage::loadHiddenNode() ui.localPort -> setValue(detail.localPort); /* set the server address */ - - ui.label_extAddress->setText(tr("TOR Onion Address")); - ui.extAddress->setText(QString::fromStdString(detail.hiddenNodeAddress)); - ui.extPort -> setValue(detail.hiddenNodePort); - - /* set DynDNS */ - ui.label_dynDNS -> setText("TOR Server Port"); - - std::string proxyaddr; - uint16_t proxyport; - rsPeers->getProxyServer(proxyaddr, proxyport); - - ui.dynDNS -> setText(QString::fromStdString(proxyaddr)); - ui.torPort -> setVisible(true); - ui.torPort -> setValue(proxyport); + ui.extAddress->setText(tr("Hidden - See TOR Config")); ui.showDiscStatusBar->setChecked(Settings->getStatusBarFlags() & STATUSBAR_DISC); @@ -519,6 +530,33 @@ void ServerPage::loadHiddenNode() ui.allowIpDeterminationCB->setChecked(false); ui.allowIpDeterminationCB->setEnabled(false); ui.IPServersLV->setEnabled(false); + + /* TOR PAGE SETTINGS */ + + /* set local address */ + ui.torpage_localAddress->setEnabled(false); + ui.torpage_localAddress->setText(QString::fromStdString(detail.localAddr)); + ui.torpage_localPort -> setValue(detail.localPort); + + /* set the server address */ + ui.torpage_onionAddress->setText(QString::fromStdString(detail.hiddenNodeAddress)); + ui.torpage_onionPort -> setValue(detail.hiddenNodePort); + + std::string proxyaddr; + uint16_t proxyport; + rsPeers->getProxyServer(proxyaddr, proxyport); + ui.torpage_proxyAddress -> setText(QString::fromStdString(proxyaddr)); + ui.torpage_proxyPort -> setValue(proxyport); + + QString expected = "HiddenServiceDir \n"; + expected += "HiddenServicePort "; + expected += QString::number(detail.hiddenNodePort); + expected += " "; + expected += QString::fromStdString(detail.localAddr); + expected += ":"; + expected += QString::number(detail.localPort); + + ui.torpage_configuration->setPlainText(expected); } /** Loads the settings for this page */ @@ -602,30 +640,26 @@ void ServerPage::saveAddressesHiddenNode() if ((vs_disc != detail.vs_disc) || (vs_dht != detail.vs_dht)) rsPeers->setVisState(ownId, vs_disc, vs_dht); - // Work out what we do with addresses! - //rsPeers->setExtAddress(ownId, ui.extAddress->text().toStdString(), ui.extPort->value()); - - if (detail.localPort != ui.localPort->value()) + if (detail.localPort != ui.torpage_localPort->value()) { // Set Local Address - force to 127.0.0.1 - rsPeers->setLocalAddress(ownId, "127.0.0.1", ui.localPort->value()); + rsPeers->setLocalAddress(ownId, "127.0.0.1", ui.torpage_localPort->value()); } - std::string hiddenAddr = ui.extAddress->text().toStdString(); - uint16_t hiddenPort = ui.extPort->value(); + std::string hiddenAddr = ui.torpage_onionAddress->text().toStdString(); + uint16_t hiddenPort = ui.torpage_onionPort->value(); if ((hiddenAddr != detail.hiddenNodeAddress) || (hiddenPort != detail.hiddenNodePort)) { rsPeers->setHiddenNode(ownId, hiddenAddr, hiddenPort); } - // HANDLE PROXY SERVER. std::string orig_proxyaddr; uint16_t orig_proxyport; rsPeers->getProxyServer(orig_proxyaddr, orig_proxyport); - std::string new_proxyaddr = ui.dynDNS -> text().toStdString(); - uint16_t new_proxyport = ui.torPort -> value(); + std::string new_proxyaddr = ui.torpage_proxyAddress -> text().toStdString(); + uint16_t new_proxyport = ui.torpage_proxyPort -> value(); if ((new_proxyaddr != orig_proxyaddr) || (new_proxyport != orig_proxyport)) { diff --git a/retroshare-gui/src/gui/settings/ServerPage.ui b/retroshare-gui/src/gui/settings/ServerPage.ui index 00250ebf3..c75bb19ae 100755 --- a/retroshare-gui/src/gui/settings/ServerPage.ui +++ b/retroshare-gui/src/gui/settings/ServerPage.ui @@ -6,18 +6,18 @@ 0 0 - 632 - 683 + 602 + 535 6 - + - 0 + 3 @@ -201,29 +201,6 @@ peers still need to trust each other to allow connection. - - - - The Port that TOR is listening to for outgoing connections. Normally 9100 or 9150 - - - 1024 - - - 65535 - - - 9100 - - - - - - - Port: - - - @@ -568,6 +545,270 @@ The default value is 20. + + + TOR Configuration + + + + + + Outgoing TOR Connections + + + + + + + + + + TOR Socks Proxy + + + + + + + + + + 10 + + + 65535 + + + + + + + + + + + + 16 + 16 + + + + + + + :/images/ledoff1.png + + + + + + + Outgoing Okay + + + + + + + + + + + + 16777215 + 100 + + + + Qt::ScrollBarAlwaysOff + + + true + + + TOR Socks Proxy default: 127.0.01:9050. Set in torrc config and update here. + +You can connect to Hidden Nodes, even if you +are running a standard Node, so why not setup TOR? + + + + + + + + + + + 0 + 0 + + + + Incoming TOR Connections + + + + + + + + Local Address + + + + + + + + + + 10 + + + 65535 + + + + + + + + + + 16 + 16 + + + + + + + :/images/ledoff1.png + + + + + + + Incoming Okay + + + + + + + + + Onion Address + + + + + + + + + + 10 + + + 65535 + + + + + + + + + + + Expected torrc Port Configuration: + + + + + + + + 0 + 0 + + + + + 0 + 10 + + + + + 16777215 + 50 + + + + Qt::ScrollBarAlwaysOff + + + true + + + HiddenServiceDir </your/path/to/hidden/directory/service> +HiddenServicePort 9191 127.0.0.1:9191 + + + + + + + + + + 0 + 0 + + + + + 16777215 + 100 + + + + true + + + To Receive Connections, you must first setup a TOR Hidden Service. +See TOR documentation for HOWTO details. + +Once this is done, paste the Onion Address in the box above. +This is your external address on the TOR network. +Finally make sure that the Ports match the TOR configuration. + +If you have issues connecting over TOR check the TOR logs too. + + + + + + + + + + Qt::Vertical + + + + 20 + 18 + + + + + + @@ -575,7 +816,6 @@ The default value is 20. netModeComboBox discComboBox - tabWidget localAddress localPort extAddress From 06a582564d4b20a7186335e7a828b83b1ffa0b8b Mon Sep 17 00:00:00 2001 From: drbob Date: Sun, 19 Jan 2014 11:35:31 +0000 Subject: [PATCH 75/83] Fixes for failed Proxy Connection Attempts: - create Timeout Fn so it can be called by classes derived from pqissl. - set HIDDEN timeout to 30 seconds. - add reset_locked() calls on errors in pqisslproxy. git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@7039 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/pqi/p3linkmgr.h | 2 ++ libretroshare/src/pqi/pqipersongrp.cc | 3 ++- libretroshare/src/pqi/pqissl.cc | 25 ++++++++++++++++++------- libretroshare/src/pqi/pqissl.h | 3 +++ libretroshare/src/pqi/pqisslproxy.cc | 13 ++++++++++--- libretroshare/src/pqi/pqissludp.cc | 12 +----------- 6 files changed, 36 insertions(+), 22 deletions(-) diff --git a/libretroshare/src/pqi/p3linkmgr.h b/libretroshare/src/pqi/p3linkmgr.h index a4513ea83..ea294c1dd 100644 --- a/libretroshare/src/pqi/p3linkmgr.h +++ b/libretroshare/src/pqi/p3linkmgr.h @@ -51,7 +51,9 @@ const uint32_t RS_NET_CONN_TCP_HIDDEN = 0x0008; const uint32_t RS_NET_CONN_UDP_DHT_SYNC = 0x0010; const uint32_t RS_NET_CONN_UDP_PEER_SYNC = 0x0020; /* coming soon */ +// These are set in pqipersongroup. const uint32_t RS_TCP_STD_TIMEOUT_PERIOD = 5; /* 5 seconds! */ +const uint32_t RS_TCP_HIDDEN_TIMEOUT_PERIOD = 30; /* 30 seconds! */ const uint32_t RS_UDP_STD_TIMEOUT_PERIOD = 80; /* 80 secs, allows UDP TTL to get to 40! - Plenty of time (30+80) = 110 secs */ class peerAddrInfo diff --git a/libretroshare/src/pqi/pqipersongrp.cc b/libretroshare/src/pqi/pqipersongrp.cc index e3128c6ed..9dc994b9e 100644 --- a/libretroshare/src/pqi/pqipersongrp.cc +++ b/libretroshare/src/pqi/pqipersongrp.cc @@ -620,12 +620,13 @@ int pqipersongrp::connectPeer(std::string id if (type == RS_NET_CONN_TCP_HIDDEN) { ptype = PQI_CONNECT_HIDDEN_TCP; + timeout = RS_TCP_HIDDEN_TIMEOUT_PERIOD; } else { ptype = PQI_CONNECT_TCP; + timeout = RS_TCP_STD_TIMEOUT_PERIOD; } - timeout = RS_TCP_STD_TIMEOUT_PERIOD; #ifdef PGRP_DEBUG std::cerr << " pqipersongrp::connectPeer() connecting with TCP: Timeout :" << timeout; std::cerr << std::endl; diff --git a/libretroshare/src/pqi/pqissl.cc b/libretroshare/src/pqi/pqissl.cc index 32fefbffa..aebe05550 100644 --- a/libretroshare/src/pqi/pqissl.cc +++ b/libretroshare/src/pqi/pqissl.cc @@ -823,13 +823,8 @@ int pqissl::Initiate_Connection() * */ -int pqissl::Basic_Connection_Complete() +bool pqissl::CheckConnectionTimeout() { -#ifdef PQISSL_LOG_DEBUG - rslog(RSL_DEBUG_BASIC, pqisslzone, - "pqissl::Basic_Connection_Complete()..."); -#endif - /* new TimeOut code. */ if (time(NULL) > mTimeoutTS) { @@ -841,10 +836,26 @@ int pqissl::Basic_Connection_Complete() rslog(RSL_ALERT, pqisslzone, "pqissl::Basic_Connection_Complete() -> calling reset()"); reset_locked(); + return true; + } + return false; +} + + + +int pqissl::Basic_Connection_Complete() +{ +#ifdef PQISSL_LOG_DEBUG + rslog(RSL_DEBUG_BASIC, pqisslzone, + "pqissl::Basic_Connection_Complete()..."); +#endif + + if (CheckConnectionTimeout()) + { + // calls reset. return -1; } - if (waiting != WAITING_SOCK_CONNECT) { rslog(RSL_ALERT, pqisslzone, diff --git a/libretroshare/src/pqi/pqissl.h b/libretroshare/src/pqi/pqissl.h index de8813cd9..915e71173 100644 --- a/libretroshare/src/pqi/pqissl.h +++ b/libretroshare/src/pqi/pqissl.h @@ -165,6 +165,9 @@ int Authorise_SSL_Connection(); int Extract_Failed_SSL_Certificate(); // try to get cert anyway. + // check connection timeout. +bool CheckConnectionTimeout(); + //protected internal fns that are overloaded for udp case. virtual int net_internal_close(int fd); diff --git a/libretroshare/src/pqi/pqisslproxy.cc b/libretroshare/src/pqi/pqisslproxy.cc index 45c9d4c19..e8bcea8bf 100755 --- a/libretroshare/src/pqi/pqisslproxy.cc +++ b/libretroshare/src/pqi/pqisslproxy.cc @@ -96,6 +96,12 @@ int pqisslproxy::Basic_Connection_Complete() std::cerr << std::endl; #endif + if (CheckConnectionTimeout()) + { + // calls reset. + return -1; + } + int ret = 0; switch(mProxyState) { @@ -127,6 +133,7 @@ int pqisslproxy::Basic_Connection_Complete() std::cerr << std::endl; #endif + reset_locked(); return -1; } @@ -134,10 +141,10 @@ int pqisslproxy::Basic_Connection_Complete() { #ifdef PROXY_DEBUG - std::cerr << "pqisslproxy::Basic_Connection_Complete() FAILED(2)"; - std::cerr << std::endl; + std::cerr << "pqisslproxy::Basic_Connection_Complete() FAILED(2)"; + std::cerr << std::endl; #endif - + reset_locked(); return -1; // FAILURE. } diff --git a/libretroshare/src/pqi/pqissludp.cc b/libretroshare/src/pqi/pqissludp.cc index fef91d8db..bc8f750b3 100644 --- a/libretroshare/src/pqi/pqissludp.cc +++ b/libretroshare/src/pqi/pqissludp.cc @@ -351,21 +351,11 @@ int pqissludp::Basic_Connection_Complete() rslog(RSL_DEBUG_BASIC, pqissludpzone, "pqissludp::Basic_Connection_Complete()..."); - - if (time(NULL) > mTimeoutTS) + if (CheckConnectionTimeout()) { - std::string out = "pqissludp::Basic_Connection_Complete() Connection Timed Out. Peer: " + PeerId(); - rs_sprintf_append(out, " Period: %lu", mConnectTimeout); - - rslog(RSL_WARNING, pqissludpzone, out); - - /* as sockfd is valid, this should close it all up */ - - reset_locked(); return -1; } - if (waiting != WAITING_SOCK_CONNECT) { rslog(RSL_DEBUG_BASIC, pqissludpzone, From efd1447a84df19c37dd482f3a92039e3c06f4492 Mon Sep 17 00:00:00 2001 From: csoler Date: Sun, 19 Jan 2014 14:42:16 +0000 Subject: [PATCH 76/83] removed code for old certificate format. git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@7041 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/pgp/rscertificate.cc | 579 +----------------- libretroshare/src/pgp/rscertificate.h | 4 - libretroshare/src/retroshare/rspeers.h | 4 +- libretroshare/src/rsserver/p3peers.cc | 11 +- libretroshare/src/rsserver/p3peers.h | 4 +- .../src/gui/connect/ConfCertDialog.cpp | 2 +- .../src/gui/connect/ConnectFriendWizard.cpp | 2 +- .../src/gui/settings/CryptoPage.cpp | 2 +- 8 files changed, 13 insertions(+), 595 deletions(-) diff --git a/libretroshare/src/pgp/rscertificate.cc b/libretroshare/src/pgp/rscertificate.cc index e5707d1c8..547c0bc20 100644 --- a/libretroshare/src/pgp/rscertificate.cc +++ b/libretroshare/src/pgp/rscertificate.cc @@ -136,7 +136,7 @@ RsCertificate::RsCertificate(const std::string& str) { uint32_t err_code ; - if(!initFromString(str,err_code)) // && !initFromString_oldFormat(str,err_code)) + if(!initFromString(str,err_code)) throw err_code ; } @@ -435,12 +435,6 @@ unsigned short RsCertificate::loc_port_us() const bool RsCertificate::cleanCertificate(const std::string& input,std::string& output,Format& format,int& error_code) { -// if(cleanCertificate_oldFormat(input,output,error_code)) -// { -// format = RS_CERTIFICATE_OLD_FORMAT ; -// return true ; -// } - if(cleanCertificate(input,output,error_code)) { format = RS_CERTIFICATE_RADIX ; @@ -494,576 +488,7 @@ bool RsCertificate::cleanCertificate(const std::string& instr,std::string& str,i return true ; } -// All the code below should be removed when in 0.6. Certificates will only use the new format. -// -bool RsCertificate::cleanCertificate_oldFormat(const std::string& certstr,std::string& cleanCertificate,int& error_code) -{ - error_code = RS_PEER_CERT_CLEANING_CODE_UNKOWN_ERROR ; // default - const std::string& badCertificate(certstr) ; - - std::string pgpend("-----END PGP PUBLIC KEY BLOCK-----"); - - size_t pos = certstr.find(pgpend); - std::string peer_info ; - std::string cert ; - - if (pos != std::string::npos) - { - pos += pgpend.length(); - cert = certstr.substr(0, pos); - if (pos + 1 < certstr.length()) - peer_info = certstr.substr(pos + 1); - } - else - { - error_code = RS_PEER_CERT_CLEANING_CODE_NO_END_TAG ; - return false ; - } - - if(cert.empty()) - return false ; - - /* - Buffer for storing the cleaned certificate. In certain cases the - cleanCertificate can be larger than the badCertificate - */ - cleanCertificate = ""; - //The entire certificate begin tag - const char * beginCertTag="-----BEGIN"; - //The entire certificate end tag - const char * endCertTag="-----END"; - //Tag containing dots. The common part of both start and end tags - const char * commonTag="-----"; - //Only BEGIN part of the begin tag - const char * beginTag="BEGIN"; - //Only END part of the end tag - const char * endTag="END"; - //The start index of the ----- part of the certificate begin tag - size_t beginCertStartIdx1=0; - //The start index of the BEGIN part of the certificate begin tag - size_t beginCertStartIdx2=0; - //The start index of the end part(-----) of the certificate begin tag. The begin tag ends with -----. Example -----BEGIN XPGP CERTIFICATE----- - size_t beginCertEndIdx=0; - //The start index of the ----- part of the certificate end tag - size_t endCertStartIdx1=0; - //The start index of the END part of the certificate end tag - size_t endCertStartIdx2=0; - //The start index of the end part(-----) of the certificate end tag. The begin tag ends with -----. Example -----BEGIN XPGP CERTIFICATE----- - size_t endCertEndIdx=0; - //The length of the bad certificate. - size_t lengthOfCert=certstr.length(); - //The current index value in the bad certificate - size_t currBadCertIdx=0; - //Temporary index value - size_t tmpIdx=0; - //Boolean flag showing if the begin tag or the end tag has been found - bool found=false; - /* - Calculating the value of the beginCertStartIdx1 and beginCertStartIdx2. Here - we first locate the occurance of ----- and then the location of BEGIN. Next - we check if there are any non space or non new-line characters between their - occureance. If there are any other characters between the two(----- and - BEGIN), other than space and new line then it means that it is the - certificate begin tag. Here we take care of the fact that we may have - introduced some spaces and newlines in the begin tag by mistake. This takes - care of the spaces and newlines between ----- and BEGIN. - */ - - while(found==false && (beginCertStartIdx1=certstr.find(commonTag,tmpIdx))!=std::string::npos) - { - beginCertStartIdx2=certstr.find(beginTag,beginCertStartIdx1+strlen(commonTag)); - tmpIdx=beginCertStartIdx1+strlen(commonTag); - if(beginCertStartIdx2!=std::string::npos) - { - found=true; - for(size_t i=beginCertStartIdx1+strlen(commonTag);i tag"< tag"< tag"<=lengthOfCert) - { - std::cerr<<"Certificate corrupted beyond repair: No <------END > tag"< header; - header.push_back("Version"); - header.push_back("Comment"); - header.push_back("MessageID"); - header.push_back("Hash"); - header.push_back("Charset"); - - for (std::list::iterator headerIt = header.begin (); headerIt != header.end(); headerIt++) - { - if (badCertificate.substr(currBadCertIdx, (*headerIt).length()) == *headerIt) - { - cleanCertificate += badCertificate.substr(currBadCertIdx, (*headerIt).length()); - currBadCertIdx += (*headerIt).length(); - while(currBadCertIdx=endCertStartIdx1) - { - std::cerr<<"Certificate corrupted beyond repair: No checksum, or no newline after first tag"<GetRetroshareInvite(detail.id,ui._shouldAddSignatures_CB->isChecked(),ui._useOldFormat_CB->isChecked()) ; // this needs to be a SSL id + std::string invite = rsPeers->GetRetroshareInvite(detail.id,ui._shouldAddSignatures_CB->isChecked()) ; // this needs to be a SSL id ui.userCertificateText->setReadOnly(true); ui.userCertificateText->setMinimumHeight(200); diff --git a/retroshare-gui/src/gui/connect/ConnectFriendWizard.cpp b/retroshare-gui/src/gui/connect/ConnectFriendWizard.cpp index 0f5cd379f..09332788a 100755 --- a/retroshare-gui/src/gui/connect/ConnectFriendWizard.cpp +++ b/retroshare-gui/src/gui/connect/ConnectFriendWizard.cpp @@ -668,7 +668,7 @@ void ConnectFriendWizard::accept() void ConnectFriendWizard::updateOwnCert() { - std::string invite = rsPeers->GetRetroshareInvite(ui->userCertIncludeSignaturesButton->isChecked(),ui->userCertOldFormatButton->isChecked()); + std::string invite = rsPeers->GetRetroshareInvite(ui->userCertIncludeSignaturesButton->isChecked()); std::cerr << "TextPage() getting Invite: " << invite << std::endl; diff --git a/retroshare-gui/src/gui/settings/CryptoPage.cpp b/retroshare-gui/src/gui/settings/CryptoPage.cpp index c9fa14fc4..4b9b4235a 100755 --- a/retroshare-gui/src/gui/settings/CryptoPage.cpp +++ b/retroshare-gui/src/gui/settings/CryptoPage.cpp @@ -112,7 +112,7 @@ void CryptoPage::load() { /* Loads ouer default Puplickey */ - ui.certplainTextEdit->setPlainText(QString::fromUtf8(rsPeers->GetRetroshareInvite(ui._includeSignatures_CB->isChecked(),ui._useOldFormat_CB->isChecked()).c_str())); + ui.certplainTextEdit->setPlainText(QString::fromUtf8(rsPeers->GetRetroshareInvite(ui._includeSignatures_CB->isChecked()).c_str())); } void CryptoPage::copyRSLink() From f3afc128ee8318aec7628a453bdbdb7ccc70e6da Mon Sep 17 00:00:00 2001 From: chrisparker126 Date: Sun, 19 Jan 2014 23:38:48 +0000 Subject: [PATCH 77/83] Chozabu patch - New db created for parent group id field, you will all previous gxs data - posted now support sub post topics git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@7042 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/gxs/rsdataservice.cc | 11 +- libretroshare/src/gxs/rsgenexchange.cc | 1 + libretroshare/src/gxs/rsgxsdata.cc | 6 + libretroshare/src/gxs/rsgxsdata.h | 1 + libretroshare/src/pqi/pqissludp.cc | 1 + libretroshare/src/pqi/pqithreadstreamer.cc | 1 + .../src/retroshare/rsgxsifacetypes.h | 1 + libretroshare/src/rsserver/rsinit.cc | 2 +- libretroshare/src/serialiser/rsgxsitems.cc | 7 +- .../src/gui/Posted/PostedListDialog.cpp | 62 +++--- .../src/gui/Posted/PostedListDialog.h | 6 +- .../src/gui/common/GroupTreeWidget.cpp | 206 ++++++++++++------ .../src/gui/common/GroupTreeWidget.h | 8 +- retroshare-gui/src/gui/gxs/GxsGroupDialog.cpp | 56 ++--- retroshare-gui/src/gui/gxs/GxsGroupDialog.h | 19 +- retroshare-gui/src/gui/gxs/GxsGroupDialog.ui | 44 +++- 16 files changed, 257 insertions(+), 175 deletions(-) diff --git a/libretroshare/src/gxs/rsdataservice.cc b/libretroshare/src/gxs/rsdataservice.cc index 4ca2aaa1f..08f788218 100644 --- a/libretroshare/src/gxs/rsdataservice.cc +++ b/libretroshare/src/gxs/rsdataservice.cc @@ -44,6 +44,7 @@ #define KEY_NXS_IDENTITY std::string("identity") #define KEY_GRP_ID std::string("grpId") #define KEY_ORIG_GRP_ID std::string("origGrpId") +#define KEY_PARENT_GRP_ID std::string("parentGrpId") #define KEY_SIGN_SET std::string("signSet") #define KEY_TIME_STAMP std::string("timeStamp") #define KEY_NXS_FLAGS std::string("flags") @@ -114,7 +115,8 @@ #define COL_GRP_INTERN_CIRCLE 18 #define COL_GRP_ORIGINATOR 19 #define COL_GRP_AUTHEN_FLAGS 20 -#define COL_GRP_RECV_TS 21 +#define COL_PARENT_GRP_ID 21 +#define COL_GRP_RECV_TS 22 // msg col numbers @@ -173,7 +175,8 @@ RsDataService::RsDataService(const std::string &serviceDir, const std::string &d grpMetaColumns.push_back(KEY_GRP_LAST_POST); grpMetaColumns.push_back(KEY_ORIG_GRP_ID); grpMetaColumns.push_back(KEY_NXS_SERV_STRING); grpMetaColumns.push_back(KEY_GRP_SIGN_FLAGS); grpMetaColumns.push_back(KEY_GRP_CIRCLE_ID); grpMetaColumns.push_back(KEY_GRP_CIRCLE_TYPE); grpMetaColumns.push_back(KEY_GRP_INTERNAL_CIRCLE); grpMetaColumns.push_back(KEY_GRP_ORIGINATOR); - grpMetaColumns.push_back(KEY_GRP_AUTHEN_FLAGS); grpMetaColumns.push_back(KEY_RECV_TS); + grpMetaColumns.push_back(KEY_GRP_AUTHEN_FLAGS); grpMetaColumns.push_back(KEY_PARENT_GRP_ID); grpMetaColumns.push_back(KEY_RECV_TS); + // for retrieving actual grp data grpColumns.push_back(KEY_GRP_ID); grpColumns.push_back(KEY_NXS_FILE); grpColumns.push_back(KEY_NXS_FILE_OFFSET); @@ -247,6 +250,7 @@ void RsDataService::initialise(){ KEY_GRP_ORIGINATOR + " TEXT," + KEY_NXS_HASH + " TEXT," + KEY_RECV_TS + " INT," + + KEY_PARENT_GRP_ID + " TEXT," + KEY_SIGN_SET + " BLOB);"); mDb->execSQL("CREATE TRIGGER " + GRP_LAST_POST_UPDATE_TRIGGER + @@ -309,6 +313,8 @@ RsGxsGrpMetaData* RsDataService::locked_getGrpMeta(RetroCursor &c) grpMeta->mRecvTS = c.getInt32(COL_GRP_RECV_TS); + c.getString(COL_PARENT_GRP_ID, grpMeta->mParentGrpId); + if(ok) return grpMeta; else @@ -613,6 +619,7 @@ int RsDataService::storeGroup(std::map &grp) cv.put(KEY_GRP_INTERNAL_CIRCLE, grpMetaPtr->mInternalCircle); cv.put(KEY_GRP_ORIGINATOR, grpMetaPtr->mOriginator); cv.put(KEY_GRP_AUTHEN_FLAGS, (int32_t)grpMetaPtr->mAuthenFlags); + cv.put(KEY_PARENT_GRP_ID, grpMetaPtr->mParentGrpId); cv.put(KEY_NXS_HASH, grpMetaPtr->mHash); cv.put(KEY_RECV_TS, (int32_t)grpMetaPtr->mRecvTS); diff --git a/libretroshare/src/gxs/rsgenexchange.cc b/libretroshare/src/gxs/rsgenexchange.cc index df367a5aa..0c1f80e5e 100644 --- a/libretroshare/src/gxs/rsgenexchange.cc +++ b/libretroshare/src/gxs/rsgenexchange.cc @@ -2051,6 +2051,7 @@ void RsGenExchange::publishGrps() { grp->metaData = new RsGxsGrpMetaData(); grpItem->meta.mPublishTs = time(NULL); + //grpItem->meta.mParentGrpId = std::string("empty"); *(grp->metaData) = grpItem->meta; // TODO: change when publish key optimisation added (public groups don't have publish key diff --git a/libretroshare/src/gxs/rsgxsdata.cc b/libretroshare/src/gxs/rsgxsdata.cc index 5de64b35d..45f4db18f 100644 --- a/libretroshare/src/gxs/rsgxsdata.cc +++ b/libretroshare/src/gxs/rsgxsdata.cc @@ -49,6 +49,7 @@ uint32_t RsGxsGrpMetaData::serial_size() s += 4; // for mCircleType s += GetTlvStringSize(mCircleId); s += 4; // mAuthenFlag + s += GetTlvStringSize(mParentGrpId); return s; } @@ -74,6 +75,7 @@ void RsGxsGrpMetaData::clear(){ mOriginator.clear(); mCircleType = 0; mAuthenFlags = 0; + mParentGrpId.clear(); mRecvTS = 0; } @@ -104,6 +106,7 @@ bool RsGxsGrpMetaData::serialise(void *data, uint32_t &pktsize) ok &= SetTlvString(data, tlvsize, &offset, 0, mGroupId); ok &= SetTlvString(data, tlvsize, &offset, 0, mOrigGrpId); + ok &= SetTlvString(data, tlvsize, &offset, 0, mParentGrpId); ok &= SetTlvString(data, tlvsize, &offset, 0, mGroupName); ok &= setRawUInt32(data, tlvsize, &offset, mGroupFlags); ok &= setRawUInt32(data, tlvsize, &offset, mPublishTs); @@ -134,6 +137,7 @@ bool RsGxsGrpMetaData::deserialise(void *data, uint32_t &pktsize) ok &= GetTlvString(data, pktsize, &offset, 0, mGroupId); ok &= GetTlvString(data, pktsize, &offset, 0, mOrigGrpId); + ok &= GetTlvString(data, pktsize, &offset, 0, mParentGrpId); ok &= GetTlvString(data, pktsize, &offset, 0, mGroupName); ok &= getRawUInt32(data, pktsize, &offset, &mGroupFlags); ok &= getRawUInt32(data, pktsize, &offset, &mPublishTs); @@ -286,6 +290,8 @@ void RsGxsGrpMetaData::operator =(const RsGroupMetaData& rMeta) this->mInternalCircle = rMeta.mInternalCircle; this->mOriginator = rMeta.mOriginator; this->mAuthenFlags = rMeta.mAuthenFlags; + //std::cout << "rMeta.mParentGrpId= " <mParentGrpId = rMeta.mParentGrpId; } void RsGxsMsgMetaData::operator =(const RsMsgMetaData& rMeta) diff --git a/libretroshare/src/gxs/rsgxsdata.h b/libretroshare/src/gxs/rsgxsdata.h index 5c17a5cd4..6fe905a9a 100644 --- a/libretroshare/src/gxs/rsgxsdata.h +++ b/libretroshare/src/gxs/rsgxsdata.h @@ -63,6 +63,7 @@ public: std::string mServiceString; uint32_t mAuthenFlags; + RsGxsGroupId mParentGrpId; // BELOW HERE IS LOCAL DATA, THAT IS NOT FROM MSG. diff --git a/libretroshare/src/pqi/pqissludp.cc b/libretroshare/src/pqi/pqissludp.cc index bc8f750b3..c65fb550d 100644 --- a/libretroshare/src/pqi/pqissludp.cc +++ b/libretroshare/src/pqi/pqissludp.cc @@ -38,6 +38,7 @@ #include "util/rsstring.h" #include "pqi/p3linkmgr.h" +#include const int pqissludpzone = 3144; diff --git a/libretroshare/src/pqi/pqithreadstreamer.cc b/libretroshare/src/pqi/pqithreadstreamer.cc index 196059665..b9507b135 100644 --- a/libretroshare/src/pqi/pqithreadstreamer.cc +++ b/libretroshare/src/pqi/pqithreadstreamer.cc @@ -25,6 +25,7 @@ #include "pqi/pqithreadstreamer.h" +#include #define DEFAULT_STREAMER_TIMEOUT 10000 // 10 ms. #define DEFAULT_STREAMER_SLEEP 1000 // 1 ms. diff --git a/libretroshare/src/retroshare/rsgxsifacetypes.h b/libretroshare/src/retroshare/rsgxsifacetypes.h index 6f17d3cc5..6f8bdda89 100644 --- a/libretroshare/src/retroshare/rsgxsifacetypes.h +++ b/libretroshare/src/retroshare/rsgxsifacetypes.h @@ -65,6 +65,7 @@ public: std::string mCircleId; uint32_t mCircleType; uint32_t mAuthenFlags; + std::string mParentGrpId; // BELOW HERE IS LOCAL DATA, THAT IS NOT FROM MSG. diff --git a/libretroshare/src/rsserver/rsinit.cc b/libretroshare/src/rsserver/rsinit.cc index 3e6309f36..a25cbee0c 100644 --- a/libretroshare/src/rsserver/rsinit.cc +++ b/libretroshare/src/rsserver/rsinit.cc @@ -1319,7 +1319,7 @@ int RsServer::StartupRetroShare() std::string currGxsDir = rsAccounts.PathAccountDirectory() + "/GXS_phase2"; #ifdef GXS_DEV_TESTNET // Different Directory for testing. - currGxsDir += "_TESTNET6"; + currGxsDir += "_TESTNET7"; #endif bool cleanUpGxsDir = false; diff --git a/libretroshare/src/serialiser/rsgxsitems.cc b/libretroshare/src/serialiser/rsgxsitems.cc index e1acdf0fd..164e2d754 100644 --- a/libretroshare/src/serialiser/rsgxsitems.cc +++ b/libretroshare/src/serialiser/rsgxsitems.cc @@ -47,13 +47,16 @@ this->mInternalCircle = rGxsMeta.mInternalCircle; this->mOriginator = rGxsMeta.mOriginator; this->mAuthenFlags = rGxsMeta.mAuthenFlags; + // std::cout << "rGxsMeta.mParentGrpId= " <mParentGrpId= " <mParentGrpId<<"\n"; + this->mParentGrpId = rGxsMeta.mParentGrpId; } std::ostream &operator<<(std::ostream &out, const RsGroupMetaData &meta) { - out << "[ GroupId: " << meta.mGroupId << " Name: " << meta.mGroupName; - out << " PublishTs: " << meta.mPublishTs << " ]"; + out << "[ GroupId: " << meta.mGroupId << " Name: " << meta.mGroupName << " ]"; return out; } diff --git a/retroshare-gui/src/gui/Posted/PostedListDialog.cpp b/retroshare-gui/src/gui/Posted/PostedListDialog.cpp index 55c0b5bcd..0575c01ea 100644 --- a/retroshare-gui/src/gui/Posted/PostedListDialog.cpp +++ b/retroshare-gui/src/gui/Posted/PostedListDialog.cpp @@ -86,8 +86,8 @@ PostedListDialog::PostedListDialog(QWidget *parent) /* create posted tree */ yourTopics = ui.groupTreeWidget->addCategoryItem(tr("My Topics"), QIcon(IMAGE_FOLDER), true); subscribedTopics = ui.groupTreeWidget->addCategoryItem(tr("Subscribed Topics"), QIcon(IMAGE_FOLDERRED), true); - popularTopics = ui.groupTreeWidget->addCategoryItem(tr("Popular Topics"), QIcon(IMAGE_FOLDERGREEN), false); - otherTopics = ui.groupTreeWidget->addCategoryItem(tr("Other Topics"), QIcon(IMAGE_FOLDERYELLOW), false); + allTopics = ui.groupTreeWidget->addCategoryItem(tr("All Topics"), QIcon(IMAGE_FOLDERGREEN), false); + //otherTopics = ui.groupTreeWidget->addCategoryItem(tr("Other Topics"), QIcon(IMAGE_FOLDERYELLOW), false); ui.hotSortButton->setChecked(true); @@ -181,6 +181,8 @@ void PostedListDialog::groupListCustomPopupMenu(QPoint /*point*/) action->setEnabled(!isSubscribed); action = contextMnu.addAction(QIcon(IMAGE_MESSAGE), tr("Unsubscribe"), this, SLOT(unsubscribeTopic())); action->setEnabled(isSubscribed); + action = contextMnu.addAction(QIcon(IMAGE_FOLDERGREEN), tr("New Child-Group"), this, SLOT(newSubTopic())); + action->setEnabled(isSubscribed); contextMnu.exec(QCursor::pos()); } @@ -361,6 +363,23 @@ void PostedListDialog::newTopic() PostedGroupDialog cf (mPostedQueue, this); cf.exec (); } +void PostedListDialog::newSubTopic() +{ + std::cerr << "mCurrTopicId: " << mCurrTopicId << std::endl; + PostedGroupDialog cf (mPostedQueue, this); + cf.setParentLabel(mCurrTopicId.c_str()); + cf.exec (); +/* + if (mCurrTopicId.empty()) { + return; + } + RsPostedGroup grp; + grp.mMeta.mParentGroupId = mCurrTopicId; + + PostedGroupDialog cf (grp, this); + GxsForumGroupDialog cf(grp, GxsGroupDialog::MODE_SHOW, this); + cf.exec ();*/ +} void PostedListDialog::showGroupDetails() { @@ -923,17 +942,16 @@ void PostedListDialog::groupInfoToGroupItemInfo(const RsGroupMetaData &groupInfo groupItemInfo.popularity = groupInfo.mPop; groupItemInfo.lastpost = QDateTime::fromTime_t(groupInfo.mLastPost); groupItemInfo.subscribeFlags = groupInfo.mSubscribeFlags; + groupItemInfo.parentId = QString::fromStdString(groupInfo.mParentGrpId); } -void PostedListDialog::insertGroupData(const std::list &groupList) +void PostedListDialog::insertGroupData( std::list &groupList) { std::list::const_iterator it; QList adminList; QList subList; - QList popList; - QList otherList; - std::multimap popMap; + QList completeList; for (it = groupList.begin(); it != groupList.end(); it++) { @@ -943,6 +961,8 @@ void PostedListDialog::insertGroupData(const std::list &groupLi GroupItemInfo groupItemInfo; groupInfoToGroupItemInfo(*it, groupItemInfo); + completeList.push_back(groupItemInfo); + if (IS_GROUP_SUBSCRIBED(flags)) { if (IS_GROUP_ADMIN(flags) || IS_GROUP_PUBLISHER(flags)) @@ -954,40 +974,12 @@ void PostedListDialog::insertGroupData(const std::list &groupLi subList.push_back(groupItemInfo); } } - else - { - popMap.insert(std::make_pair(it->mPop, groupItemInfo)); - } - } - - /* iterate backwards through popMap - take the top 5 or 10% of list */ - uint32_t popCount = 5; - if (popCount < popMap.size() / 10) - { - popCount = popMap.size() / 10; - } - - uint32_t i = 0; - uint32_t popLimit = 0; - std::multimap::reverse_iterator rit; - for(rit = popMap.rbegin(); ((rit != popMap.rend()) && (i < popCount)); rit++, i++) ; - if (rit != popMap.rend()) { - popLimit = rit->first; - } - - for (rit = popMap.rbegin(); rit != popMap.rend(); rit++) { - if (rit->second.popularity < (int) popLimit) { - otherList.append(rit->second); - } else { - popList.append(rit->second); - } } /* now we can add them in as a tree! */ ui.groupTreeWidget->fillGroupItems(yourTopics, adminList); ui.groupTreeWidget->fillGroupItems(subscribedTopics, subList); - ui.groupTreeWidget->fillGroupItems(popularTopics, popList); - ui.groupTreeWidget->fillGroupItems(otherTopics, otherList); + ui.groupTreeWidget->fillGroupItems(allTopics, completeList); } /**************************************************************************************/ diff --git a/retroshare-gui/src/gui/Posted/PostedListDialog.h b/retroshare-gui/src/gui/Posted/PostedListDialog.h index 5cbefea97..d0eea6070 100644 --- a/retroshare-gui/src/gui/Posted/PostedListDialog.h +++ b/retroshare-gui/src/gui/Posted/PostedListDialog.h @@ -66,6 +66,7 @@ private slots: void changedTopic(const QString &id); void newTopic(); + void newSubTopic(); void showGroupDetails(); void newPost(); @@ -126,7 +127,7 @@ private: void updateDisplayedItems(const std::vector& msgIds); void updateCurrentDisplayComplete(const uint32_t& token); - void insertGroupData(const std::list &groupList); + void insertGroupData(std::list &groupList); void groupInfoToGroupItemInfo(const RsGroupMetaData &groupInfo, GroupItemInfo &groupItemInfo); void loadRequest(const TokenQueue *queue, const TokenRequest &req); @@ -134,8 +135,7 @@ private: private: QTreeWidgetItem *yourTopics; QTreeWidgetItem *subscribedTopics; - QTreeWidgetItem *popularTopics; - QTreeWidgetItem *otherTopics; + QTreeWidgetItem *allTopics; int mSortMethod; int mLastSortMethod; diff --git a/retroshare-gui/src/gui/common/GroupTreeWidget.cpp b/retroshare-gui/src/gui/common/GroupTreeWidget.cpp index 2e13ddddf..4a3576afc 100644 --- a/retroshare-gui/src/gui/common/GroupTreeWidget.cpp +++ b/retroshare-gui/src/gui/common/GroupTreeWidget.cpp @@ -21,6 +21,8 @@ #include #include +#include +#include #include "GroupTreeWidget.h" #include "ui_GroupTreeWidget.h" @@ -31,6 +33,7 @@ #include "RSTreeWidgetItem.h" #include +#include #define COLUMN_NAME 0 #define COLUMN_POPULARITY 1 @@ -45,6 +48,7 @@ #define ROLE_SEARCH_SCORE Qt::UserRole + 5 #define ROLE_SUBSCRIBE_FLAGS Qt::UserRole + 6 #define ROLE_COLOR Qt::UserRole + 7 +#define ROLE_PARENT_ID Qt::UserRole + 8 #define FILTER_NAME_INDEX 0 #define FILTER_DESC_INDEX 1 @@ -299,6 +303,38 @@ QString GroupTreeWidget::itemId(QTreeWidgetItem *item) return item->data(COLUMN_DATA, ROLE_ID).toString(); } +QTreeWidgetItem* GroupTreeWidget::recursiveIdSearch(QTreeWidgetItem *currentItem, const QString &id){ + int childCount = currentItem->childCount(); + for (int child = 0; child < childCount; child++) { + QTreeWidgetItem *childItem = currentItem->child(child); + if (childItem->data(COLUMN_DATA, ROLE_ID).toString() == id) { + /* Found child */ + return childItem; + } + QTreeWidgetItem* recur = recursiveIdSearch(childItem, id); + if(recur) return recur; + } + return NULL; +} + +void GroupTreeWidget::checkOrphans(QList &orphanList, QTreeWidgetItem *justInserted){ + + if(orphanList.length()==0)return; + QString newID = justInserted->data(COLUMN_DATA, ROLE_ID).toString(); + + QList oList = orphanList; + QMutableListIterator i(oList); + while (i.hasNext()) { + QTreeWidgetItem *orphan = i.next(); + QString parentID = orphan->data(COLUMN_DATA, ROLE_PARENT_ID).toString(); + if (parentID.compare(newID)==0){ + justInserted->addChild(orphan); + i.remove(); + checkOrphans(orphanList,orphan); + } + } +} + void GroupTreeWidget::fillGroupItems(QTreeWidgetItem *categoryItem, const QList &itemList) { if (categoryItem == NULL) { @@ -307,28 +343,32 @@ void GroupTreeWidget::fillGroupItems(QTreeWidgetItem *categoryItem, const QList< QString filterText = ui->filterLineEdit->text(); + QList orphans; + /* Iterate all items */ QList::const_iterator it; for (it = itemList.begin(); it != itemList.end(); it++) { const GroupItemInfo &itemInfo = *it; - QTreeWidgetItem *item = NULL; - - /* Search exisiting item */ - int childCount = categoryItem->childCount(); - for (int child = 0; child < childCount; child++) { - QTreeWidgetItem *childItem = categoryItem->child(child); - if (childItem->data(COLUMN_DATA, ROLE_ID).toString() == itemInfo.id) { - /* Found child */ - item = childItem; - break; - } - } + QTreeWidgetItem *item = recursiveIdSearch(categoryItem, itemInfo.id); if (item == NULL) { item = new RSTreeWidgetItem(compareRole); item->setData(COLUMN_DATA, ROLE_ID, itemInfo.id); - categoryItem->addChild(item); + item->setData(COLUMN_DATA, ROLE_PARENT_ID, itemInfo.parentId); + + if(itemInfo.parentId.length()<10){ + categoryItem->addChild(item); + checkOrphans(orphans,item); + }else{ + QTreeWidgetItem *parentItem = recursiveIdSearch(categoryItem, itemInfo.parentId); + if(parentItem){ + parentItem->addChild(item); + checkOrphans(orphans,item); + }else{ + orphans.append(item); + } + } } item->setText(COLUMN_NAME, itemInfo.name); @@ -371,6 +411,16 @@ void GroupTreeWidget::fillGroupItems(QTreeWidgetItem *categoryItem, const QList< calculateScore(item, filterText); } + /* Add remaning topics whose parents are unknown */ + QMutableListIterator i(orphans); + while (i.hasNext()) { + QTreeWidgetItem *orphan = i.next(); + categoryItem->addChild(orphan); + std::cerr << "adding orphan\n"<< orphan->data(COLUMN_DATA, ROLE_PARENT_ID).toString().toStdString() <<"\n"; + std::cerr << orphan->data(COLUMN_DATA, ROLE_ID).toString().toStdString() <<"\n"; + std::cerr << "\n"; + } + /* Remove all items not in list */ int child = 0; int childCount = categoryItem->childCount(); @@ -391,7 +441,7 @@ void GroupTreeWidget::fillGroupItems(QTreeWidgetItem *categoryItem, const QList< } } - resort(categoryItem); + resort(categoryItem, NULL); } void GroupTreeWidget::setUnreadCount(QTreeWidgetItem *item, int unreadCount) @@ -466,88 +516,104 @@ int GroupTreeWidget::subscribeFlags(const QString &id) return item->data(COLUMN_DATA, ROLE_SUBSCRIBE_FLAGS).toInt(); } -void GroupTreeWidget::calculateScore(QTreeWidgetItem *item, const QString &filterText) +int GroupTreeWidget::calculateScore(QTreeWidgetItem *item, const QString &filterText) { - if (item) { - /* Calculate one item */ - int score; - if (filterText.isEmpty()) { - score = 0; + + int score = 0; + if (!item) return score; + + /* Calculate one item */ + if (filterText.isEmpty()) { + score = 0; + item->setHidden(false); + int count = item->childCount(); + for (int nIndex = 0; nIndex < count; ++nIndex) { + calculateScore(item->child(nIndex), filterText); + } + } else { + QString scoreString; + + switch (ui->filterLineEdit->currentFilter()) { + case FILTER_NAME_INDEX: + scoreString = item->data(COLUMN_DATA, ROLE_NAME).toString(); + break; + case FILTER_DESC_INDEX: + scoreString = item->data(COLUMN_DATA, ROLE_DESCRIPTION).toString(); + break; + } + + score = scoreString.count(filterText, Qt::CaseInsensitive); + + int count = item->childCount(); + for (int nIndex = 0; nIndex < count; ++nIndex) { + score += calculateScore(item->child(nIndex), filterText); + } + + if (score) { item->setHidden(false); } else { - QString scoreString; - - switch (ui->filterLineEdit->currentFilter()) { - case FILTER_NAME_INDEX: - scoreString = item->data(COLUMN_DATA, ROLE_NAME).toString(); - break; - case FILTER_DESC_INDEX: - scoreString = item->data(COLUMN_DATA, ROLE_DESCRIPTION).toString(); - break; - } - - score = scoreString.count(filterText, Qt::CaseInsensitive); - - if (score) { - item->setHidden(false); - } else { - item->setHidden(true); - } + item->setHidden(true); } - - item->setData(COLUMN_DATA, ROLE_SEARCH_SCORE, -score); // negative for correct sorting - - return; } + item->setData(COLUMN_DATA, ROLE_SEARCH_SCORE, -score); // negative for correct sorting + + return score; + +} + +void GroupTreeWidget::calculateScores(const QString &filterText) +{ /* Find out which has given word in it */ QTreeWidgetItemIterator itemIterator(ui->treeWidget); - QTreeWidgetItem *item; - while ((item = *itemIterator) != NULL) { - itemIterator++; - if (item->data(COLUMN_DATA, ROLE_ID).toString().isEmpty()) { - continue; + int count = ui->treeWidget->topLevelItemCount(); + for (int child = 0; child < count; child++) { + QTreeWidgetItem *catitem = ui->treeWidget->topLevelItem(child); + int icount = catitem->childCount(); + for (int nIndex = 0; nIndex < icount; ++nIndex) { + calculateScore(catitem->child(nIndex), filterText); } - - calculateScore(item, filterText); } } void GroupTreeWidget::filterChanged() { /* Recalculate score */ - calculateScore(NULL, ui->filterLineEdit->text()); + calculateScores(ui->filterLineEdit->text()); - resort(NULL); + sort(); } -void GroupTreeWidget::resort(QTreeWidgetItem *categoryItem) +void GroupTreeWidget::resort(QTreeWidgetItem *categoryItem, Qt::SortOrder *order) { - Qt::SortOrder order = (actionSortAscending == NULL || actionSortAscending->isChecked()) ? Qt::AscendingOrder : Qt::DescendingOrder; + if(order == NULL){ + Qt::SortOrder so = (actionSortAscending == NULL || actionSortAscending->isChecked()) ? Qt::AscendingOrder : Qt::DescendingOrder; + order = &so; - if (ui->filterLineEdit->text().isEmpty() == false) { - compareRole->setRole(COLUMN_DATA, ROLE_SEARCH_SCORE); - compareRole->addRole(COLUMN_DATA, ROLE_LASTPOST); - } else if (actionSortByName && actionSortByName->isChecked()) { - compareRole->setRole(COLUMN_DATA, ROLE_NAME); - } else if (actionSortByPopularity && actionSortByPopularity->isChecked()) { - compareRole->setRole(COLUMN_DATA, ROLE_POPULARITY); - } else if (actionSortByLastPost && actionSortByLastPost->isChecked()) { - compareRole->setRole(COLUMN_DATA, ROLE_LASTPOST); + if (ui->filterLineEdit->text().isEmpty() == false) { + compareRole->setRole(COLUMN_DATA, ROLE_SEARCH_SCORE); + compareRole->addRole(COLUMN_DATA, ROLE_LASTPOST); + } else if (actionSortByName && actionSortByName->isChecked()) { + compareRole->setRole(COLUMN_DATA, ROLE_NAME); + } else if (actionSortByPopularity && actionSortByPopularity->isChecked()) { + compareRole->setRole(COLUMN_DATA, ROLE_POPULARITY); + } else if (actionSortByLastPost && actionSortByLastPost->isChecked()) { + compareRole->setRole(COLUMN_DATA, ROLE_LASTPOST); + } } - if (categoryItem) { - categoryItem->sortChildren(COLUMN_DATA, order); - } else { - int count = ui->treeWidget->topLevelItemCount(); - for (int child = 0; child < count; child++) { - ui->treeWidget->topLevelItem(child)->sortChildren(COLUMN_DATA, order); - } + categoryItem->sortChildren(COLUMN_DATA, *order); + int count = categoryItem->childCount(); + for (int child = 0; child < count; child++) { + resort(categoryItem->child(child), order); } } void GroupTreeWidget::sort() { - resort(NULL); + int count = ui->treeWidget->topLevelItemCount(); + for (int child = 0; child < count; child++) { + resort(ui->treeWidget->topLevelItem(child), NULL); + } } diff --git a/retroshare-gui/src/gui/common/GroupTreeWidget.h b/retroshare-gui/src/gui/common/GroupTreeWidget.h index dd7326ac3..4e222fd22 100644 --- a/retroshare-gui/src/gui/common/GroupTreeWidget.h +++ b/retroshare-gui/src/gui/common/GroupTreeWidget.h @@ -55,6 +55,7 @@ public: QString id; QString name; QString description; + QString parentId; int popularity; QDateTime lastpost; QIcon icon; @@ -85,6 +86,8 @@ public: QString itemId(QTreeWidgetItem *item); // Fill items of a group void fillGroupItems(QTreeWidgetItem *categoryItem, const QList &itemList); + QTreeWidgetItem *recursiveIdSearch(QTreeWidgetItem *currentItem, const QString &id); + void checkOrphans(QList &orphanList, QTreeWidgetItem *justInserted); // Set the unread count of an item void setUnreadCount(QTreeWidgetItem *item, int unreadCount); @@ -120,8 +123,9 @@ private slots: private: // Initialize the display menu for sorting void initDisplayMenu(QToolButton *toolButton); - void calculateScore(QTreeWidgetItem *item, const QString &filterText); - void resort(QTreeWidgetItem *categoryItem); + int calculateScore(QTreeWidgetItem *item, const QString &filterText); + void calculateScores(const QString &filterText); + void resort(QTreeWidgetItem *categoryItem, Qt::SortOrder *order); void updateColors(); private: diff --git a/retroshare-gui/src/gui/gxs/GxsGroupDialog.cpp b/retroshare-gui/src/gui/gxs/GxsGroupDialog.cpp index d3f93cc24..dbd07bedc 100644 --- a/retroshare-gui/src/gui/gxs/GxsGroupDialog.cpp +++ b/retroshare-gui/src/gui/gxs/GxsGroupDialog.cpp @@ -94,6 +94,8 @@ void GxsGroupDialog::init() this->resize(this->size().width() - ui.contactsdockWidget->size().width(), this->size().height()); } + ui.parentGroupBox->setVisible(false); + /* initialize key share list */ ui.keyShareList->setHeaderText(tr("Contacts:")); ui.keyShareList->setModus(FriendSelectionWidget::MODUS_CHECK); @@ -148,13 +150,13 @@ void GxsGroupDialog::initMode() { ui.buttonBox->setStandardButtons(QDialogButtonBox::Close); } - break; - case MODE_EDIT: - { - ui.buttonBox->setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); - ui.buttonBox->button(QDialogButtonBox::Ok)->setText(tr("Submit Group Changes")); - } - break; + break; +//TODO +// case MODE_EDIT: +// { +// ui.createButton->setText(tr("Submit Changes")); +// } +// break; } } @@ -320,40 +322,17 @@ void GxsGroupDialog::submitGroup() break; case MODE_EDIT: - { - - editGroup(); + { + /* TEMP: just close if down */ + cancelDialog(); } break; } } -void GxsGroupDialog::editGroup() -{ - std::cerr << "GxsGroupDialog::editGroup()" << std::endl; - - QString name = misc::removeNewLine(ui.groupName->text()); - uint32_t flags = GXS_SERV::FLAG_PRIVACY_PUBLIC; - - if(name.isEmpty()) - { - /* error message */ - QMessageBox::warning(this, "RetroShare", tr("Please add a Name"), QMessageBox::Ok, QMessageBox::Ok); - return; //Don't add a empty name!! - } - - uint32_t token; - RsGxsGroupUpdateMeta updateMeta(mGrpMeta.mGroupId); - updateMeta.setMetaUpdate(RsGxsGroupUpdateMeta::NAME, std::string(name.toUtf8())); - - if (service_EditGroup(token, updateMeta)) - { - // get the Queue to handle response. - if(mTokenQueue != NULL) - mTokenQueue->queueRequest(token, TOKENREQ_GROUPINFO, RS_TOKREQ_ANSTYPE_ACK, GXSGROUP_NEWGROUPID); - } - - close(); +void GxsGroupDialog::setParentLabel(QString parentId){ + ui.parentGroupBox->setVisible(true); + ui.parentLabel->setText(parentId); } void GxsGroupDialog::createGroup() @@ -361,7 +340,8 @@ void GxsGroupDialog::createGroup() std::cerr << "GxsGroupDialog::createGroup()"; std::cerr << std::endl; - QString name = misc::removeNewLine(ui.groupName->text()); + QString name = misc::removeNewLine(ui.groupName->text()); + QString parentGroupId = misc::removeNewLine(ui.parentLabel->text()); uint32_t flags = GXS_SERV::FLAG_PRIVACY_PUBLIC; if(name.isEmpty()) @@ -376,6 +356,8 @@ void GxsGroupDialog::createGroup() // Fill in the MetaData as best we can. meta.mGroupName = std::string(name.toUtf8()); + if(parentGroupId.length()>10) + meta.mParentGrpId = parentGroupId.toStdString(); meta.mGroupFlags = flags; meta.mSignFlags = getGroupSignFlags(); diff --git a/retroshare-gui/src/gui/gxs/GxsGroupDialog.h b/retroshare-gui/src/gui/gxs/GxsGroupDialog.h index 35db177d0..8356d8715 100644 --- a/retroshare-gui/src/gui/gxs/GxsGroupDialog.h +++ b/retroshare-gui/src/gui/gxs/GxsGroupDialog.h @@ -143,6 +143,7 @@ public: uint32_t mode() { return mMode; } + void setParentLabel(QString parentId); private: void newGroup(); void init(); @@ -155,6 +156,8 @@ protected slots: void addGroupLogo(); protected: + /** Qt Designer generated object */ + Ui::GxsGroupDialog ui; virtual void showEvent(QShowEvent*); virtual void initUi() = 0; @@ -163,21 +166,13 @@ protected: void setUiText(UiType uiType, const QString &text); /*! - * It is up to the service to do the actual group creation - * Service can also modify initial meta going into group + * Main purpose is to help tansfer meta data to service + * * @param token This should be set to the token retrieved * @param meta The deriving GXS service should set their grp meta to this value */ virtual bool service_CreateGroup(uint32_t &token, const RsGroupMetaData &meta) = 0; - /*! - * It is up to the service to do the actual group editing - * TODO: make pure virtual - * @param token This should be set to the token retrieved - * @param meta The deriving GXS service should set their grp meta to this value - */ - virtual bool service_EditGroup(uint32_t &token, RsGxsGroupUpdateMeta &updateMeta) {} - /*! * This returns a group logo from the ui \n * Should be calleld by deriving service @@ -210,7 +205,6 @@ private: void setupVisibility(); void clearForm(); void createGroup(); - void editGroup(); void sendShareList(std::string forumId); void loadNewGroupId(const uint32_t &token); @@ -224,10 +218,7 @@ private: uint32_t mReadonlyFlags; uint32_t mDefaultsFlags; - protected: - /** Qt Designer generated object */ - Ui::GxsGroupDialog ui; }; #endif diff --git a/retroshare-gui/src/gui/gxs/GxsGroupDialog.ui b/retroshare-gui/src/gui/gxs/GxsGroupDialog.ui index 632dc6027..1ee1514ae 100644 --- a/retroshare-gui/src/gui/gxs/GxsGroupDialog.ui +++ b/retroshare-gui/src/gui/gxs/GxsGroupDialog.ui @@ -7,7 +7,7 @@ 0 0 695 - 448 + 518 @@ -156,7 +156,7 @@ - + true @@ -257,7 +257,7 @@ - + Message Distribution @@ -323,7 +323,7 @@ - + Publish Signatures @@ -366,7 +366,7 @@ - + Personal Signatures @@ -402,7 +402,7 @@ - + Comments @@ -431,7 +431,7 @@ - + QFrame::StyledPanel @@ -441,13 +441,40 @@ - + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + + + Parent: + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + None + + + + + + + + @@ -479,7 +506,6 @@ - From 46518ebf51c87b924a5f702243732eeafd94f610 Mon Sep 17 00:00:00 2001 From: drbob Date: Mon, 20 Jan 2014 07:29:54 +0000 Subject: [PATCH 78/83] revert GUI part of svn commit 7042 git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@7043 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- .../src/gui/Posted/PostedListDialog.cpp | 62 +++--- .../src/gui/Posted/PostedListDialog.h | 6 +- .../src/gui/common/GroupTreeWidget.cpp | 206 ++++++------------ .../src/gui/common/GroupTreeWidget.h | 8 +- retroshare-gui/src/gui/gxs/GxsGroupDialog.cpp | 56 +++-- retroshare-gui/src/gui/gxs/GxsGroupDialog.h | 19 +- retroshare-gui/src/gui/gxs/GxsGroupDialog.ui | 44 +--- 7 files changed, 170 insertions(+), 231 deletions(-) diff --git a/retroshare-gui/src/gui/Posted/PostedListDialog.cpp b/retroshare-gui/src/gui/Posted/PostedListDialog.cpp index 0575c01ea..55c0b5bcd 100644 --- a/retroshare-gui/src/gui/Posted/PostedListDialog.cpp +++ b/retroshare-gui/src/gui/Posted/PostedListDialog.cpp @@ -86,8 +86,8 @@ PostedListDialog::PostedListDialog(QWidget *parent) /* create posted tree */ yourTopics = ui.groupTreeWidget->addCategoryItem(tr("My Topics"), QIcon(IMAGE_FOLDER), true); subscribedTopics = ui.groupTreeWidget->addCategoryItem(tr("Subscribed Topics"), QIcon(IMAGE_FOLDERRED), true); - allTopics = ui.groupTreeWidget->addCategoryItem(tr("All Topics"), QIcon(IMAGE_FOLDERGREEN), false); - //otherTopics = ui.groupTreeWidget->addCategoryItem(tr("Other Topics"), QIcon(IMAGE_FOLDERYELLOW), false); + popularTopics = ui.groupTreeWidget->addCategoryItem(tr("Popular Topics"), QIcon(IMAGE_FOLDERGREEN), false); + otherTopics = ui.groupTreeWidget->addCategoryItem(tr("Other Topics"), QIcon(IMAGE_FOLDERYELLOW), false); ui.hotSortButton->setChecked(true); @@ -181,8 +181,6 @@ void PostedListDialog::groupListCustomPopupMenu(QPoint /*point*/) action->setEnabled(!isSubscribed); action = contextMnu.addAction(QIcon(IMAGE_MESSAGE), tr("Unsubscribe"), this, SLOT(unsubscribeTopic())); action->setEnabled(isSubscribed); - action = contextMnu.addAction(QIcon(IMAGE_FOLDERGREEN), tr("New Child-Group"), this, SLOT(newSubTopic())); - action->setEnabled(isSubscribed); contextMnu.exec(QCursor::pos()); } @@ -363,23 +361,6 @@ void PostedListDialog::newTopic() PostedGroupDialog cf (mPostedQueue, this); cf.exec (); } -void PostedListDialog::newSubTopic() -{ - std::cerr << "mCurrTopicId: " << mCurrTopicId << std::endl; - PostedGroupDialog cf (mPostedQueue, this); - cf.setParentLabel(mCurrTopicId.c_str()); - cf.exec (); -/* - if (mCurrTopicId.empty()) { - return; - } - RsPostedGroup grp; - grp.mMeta.mParentGroupId = mCurrTopicId; - - PostedGroupDialog cf (grp, this); - GxsForumGroupDialog cf(grp, GxsGroupDialog::MODE_SHOW, this); - cf.exec ();*/ -} void PostedListDialog::showGroupDetails() { @@ -942,16 +923,17 @@ void PostedListDialog::groupInfoToGroupItemInfo(const RsGroupMetaData &groupInfo groupItemInfo.popularity = groupInfo.mPop; groupItemInfo.lastpost = QDateTime::fromTime_t(groupInfo.mLastPost); groupItemInfo.subscribeFlags = groupInfo.mSubscribeFlags; - groupItemInfo.parentId = QString::fromStdString(groupInfo.mParentGrpId); } -void PostedListDialog::insertGroupData( std::list &groupList) +void PostedListDialog::insertGroupData(const std::list &groupList) { std::list::const_iterator it; QList adminList; QList subList; - QList completeList; + QList popList; + QList otherList; + std::multimap popMap; for (it = groupList.begin(); it != groupList.end(); it++) { @@ -961,8 +943,6 @@ void PostedListDialog::insertGroupData( std::list &groupList) GroupItemInfo groupItemInfo; groupInfoToGroupItemInfo(*it, groupItemInfo); - completeList.push_back(groupItemInfo); - if (IS_GROUP_SUBSCRIBED(flags)) { if (IS_GROUP_ADMIN(flags) || IS_GROUP_PUBLISHER(flags)) @@ -974,12 +954,40 @@ void PostedListDialog::insertGroupData( std::list &groupList) subList.push_back(groupItemInfo); } } + else + { + popMap.insert(std::make_pair(it->mPop, groupItemInfo)); + } + } + + /* iterate backwards through popMap - take the top 5 or 10% of list */ + uint32_t popCount = 5; + if (popCount < popMap.size() / 10) + { + popCount = popMap.size() / 10; + } + + uint32_t i = 0; + uint32_t popLimit = 0; + std::multimap::reverse_iterator rit; + for(rit = popMap.rbegin(); ((rit != popMap.rend()) && (i < popCount)); rit++, i++) ; + if (rit != popMap.rend()) { + popLimit = rit->first; + } + + for (rit = popMap.rbegin(); rit != popMap.rend(); rit++) { + if (rit->second.popularity < (int) popLimit) { + otherList.append(rit->second); + } else { + popList.append(rit->second); + } } /* now we can add them in as a tree! */ ui.groupTreeWidget->fillGroupItems(yourTopics, adminList); ui.groupTreeWidget->fillGroupItems(subscribedTopics, subList); - ui.groupTreeWidget->fillGroupItems(allTopics, completeList); + ui.groupTreeWidget->fillGroupItems(popularTopics, popList); + ui.groupTreeWidget->fillGroupItems(otherTopics, otherList); } /**************************************************************************************/ diff --git a/retroshare-gui/src/gui/Posted/PostedListDialog.h b/retroshare-gui/src/gui/Posted/PostedListDialog.h index d0eea6070..5cbefea97 100644 --- a/retroshare-gui/src/gui/Posted/PostedListDialog.h +++ b/retroshare-gui/src/gui/Posted/PostedListDialog.h @@ -66,7 +66,6 @@ private slots: void changedTopic(const QString &id); void newTopic(); - void newSubTopic(); void showGroupDetails(); void newPost(); @@ -127,7 +126,7 @@ private: void updateDisplayedItems(const std::vector& msgIds); void updateCurrentDisplayComplete(const uint32_t& token); - void insertGroupData(std::list &groupList); + void insertGroupData(const std::list &groupList); void groupInfoToGroupItemInfo(const RsGroupMetaData &groupInfo, GroupItemInfo &groupItemInfo); void loadRequest(const TokenQueue *queue, const TokenRequest &req); @@ -135,7 +134,8 @@ private: private: QTreeWidgetItem *yourTopics; QTreeWidgetItem *subscribedTopics; - QTreeWidgetItem *allTopics; + QTreeWidgetItem *popularTopics; + QTreeWidgetItem *otherTopics; int mSortMethod; int mLastSortMethod; diff --git a/retroshare-gui/src/gui/common/GroupTreeWidget.cpp b/retroshare-gui/src/gui/common/GroupTreeWidget.cpp index 4a3576afc..2e13ddddf 100644 --- a/retroshare-gui/src/gui/common/GroupTreeWidget.cpp +++ b/retroshare-gui/src/gui/common/GroupTreeWidget.cpp @@ -21,8 +21,6 @@ #include #include -#include -#include #include "GroupTreeWidget.h" #include "ui_GroupTreeWidget.h" @@ -33,7 +31,6 @@ #include "RSTreeWidgetItem.h" #include -#include #define COLUMN_NAME 0 #define COLUMN_POPULARITY 1 @@ -48,7 +45,6 @@ #define ROLE_SEARCH_SCORE Qt::UserRole + 5 #define ROLE_SUBSCRIBE_FLAGS Qt::UserRole + 6 #define ROLE_COLOR Qt::UserRole + 7 -#define ROLE_PARENT_ID Qt::UserRole + 8 #define FILTER_NAME_INDEX 0 #define FILTER_DESC_INDEX 1 @@ -303,38 +299,6 @@ QString GroupTreeWidget::itemId(QTreeWidgetItem *item) return item->data(COLUMN_DATA, ROLE_ID).toString(); } -QTreeWidgetItem* GroupTreeWidget::recursiveIdSearch(QTreeWidgetItem *currentItem, const QString &id){ - int childCount = currentItem->childCount(); - for (int child = 0; child < childCount; child++) { - QTreeWidgetItem *childItem = currentItem->child(child); - if (childItem->data(COLUMN_DATA, ROLE_ID).toString() == id) { - /* Found child */ - return childItem; - } - QTreeWidgetItem* recur = recursiveIdSearch(childItem, id); - if(recur) return recur; - } - return NULL; -} - -void GroupTreeWidget::checkOrphans(QList &orphanList, QTreeWidgetItem *justInserted){ - - if(orphanList.length()==0)return; - QString newID = justInserted->data(COLUMN_DATA, ROLE_ID).toString(); - - QList oList = orphanList; - QMutableListIterator i(oList); - while (i.hasNext()) { - QTreeWidgetItem *orphan = i.next(); - QString parentID = orphan->data(COLUMN_DATA, ROLE_PARENT_ID).toString(); - if (parentID.compare(newID)==0){ - justInserted->addChild(orphan); - i.remove(); - checkOrphans(orphanList,orphan); - } - } -} - void GroupTreeWidget::fillGroupItems(QTreeWidgetItem *categoryItem, const QList &itemList) { if (categoryItem == NULL) { @@ -343,32 +307,28 @@ void GroupTreeWidget::fillGroupItems(QTreeWidgetItem *categoryItem, const QList< QString filterText = ui->filterLineEdit->text(); - QList orphans; - /* Iterate all items */ QList::const_iterator it; for (it = itemList.begin(); it != itemList.end(); it++) { const GroupItemInfo &itemInfo = *it; - QTreeWidgetItem *item = recursiveIdSearch(categoryItem, itemInfo.id); + QTreeWidgetItem *item = NULL; + + /* Search exisiting item */ + int childCount = categoryItem->childCount(); + for (int child = 0; child < childCount; child++) { + QTreeWidgetItem *childItem = categoryItem->child(child); + if (childItem->data(COLUMN_DATA, ROLE_ID).toString() == itemInfo.id) { + /* Found child */ + item = childItem; + break; + } + } if (item == NULL) { item = new RSTreeWidgetItem(compareRole); item->setData(COLUMN_DATA, ROLE_ID, itemInfo.id); - item->setData(COLUMN_DATA, ROLE_PARENT_ID, itemInfo.parentId); - - if(itemInfo.parentId.length()<10){ - categoryItem->addChild(item); - checkOrphans(orphans,item); - }else{ - QTreeWidgetItem *parentItem = recursiveIdSearch(categoryItem, itemInfo.parentId); - if(parentItem){ - parentItem->addChild(item); - checkOrphans(orphans,item); - }else{ - orphans.append(item); - } - } + categoryItem->addChild(item); } item->setText(COLUMN_NAME, itemInfo.name); @@ -411,16 +371,6 @@ void GroupTreeWidget::fillGroupItems(QTreeWidgetItem *categoryItem, const QList< calculateScore(item, filterText); } - /* Add remaning topics whose parents are unknown */ - QMutableListIterator i(orphans); - while (i.hasNext()) { - QTreeWidgetItem *orphan = i.next(); - categoryItem->addChild(orphan); - std::cerr << "adding orphan\n"<< orphan->data(COLUMN_DATA, ROLE_PARENT_ID).toString().toStdString() <<"\n"; - std::cerr << orphan->data(COLUMN_DATA, ROLE_ID).toString().toStdString() <<"\n"; - std::cerr << "\n"; - } - /* Remove all items not in list */ int child = 0; int childCount = categoryItem->childCount(); @@ -441,7 +391,7 @@ void GroupTreeWidget::fillGroupItems(QTreeWidgetItem *categoryItem, const QList< } } - resort(categoryItem, NULL); + resort(categoryItem); } void GroupTreeWidget::setUnreadCount(QTreeWidgetItem *item, int unreadCount) @@ -516,104 +466,88 @@ int GroupTreeWidget::subscribeFlags(const QString &id) return item->data(COLUMN_DATA, ROLE_SUBSCRIBE_FLAGS).toInt(); } -int GroupTreeWidget::calculateScore(QTreeWidgetItem *item, const QString &filterText) +void GroupTreeWidget::calculateScore(QTreeWidgetItem *item, const QString &filterText) { - - int score = 0; - if (!item) return score; - - /* Calculate one item */ - if (filterText.isEmpty()) { - score = 0; - item->setHidden(false); - int count = item->childCount(); - for (int nIndex = 0; nIndex < count; ++nIndex) { - calculateScore(item->child(nIndex), filterText); - } - } else { - QString scoreString; - - switch (ui->filterLineEdit->currentFilter()) { - case FILTER_NAME_INDEX: - scoreString = item->data(COLUMN_DATA, ROLE_NAME).toString(); - break; - case FILTER_DESC_INDEX: - scoreString = item->data(COLUMN_DATA, ROLE_DESCRIPTION).toString(); - break; - } - - score = scoreString.count(filterText, Qt::CaseInsensitive); - - int count = item->childCount(); - for (int nIndex = 0; nIndex < count; ++nIndex) { - score += calculateScore(item->child(nIndex), filterText); - } - - if (score) { + if (item) { + /* Calculate one item */ + int score; + if (filterText.isEmpty()) { + score = 0; item->setHidden(false); } else { - item->setHidden(true); + QString scoreString; + + switch (ui->filterLineEdit->currentFilter()) { + case FILTER_NAME_INDEX: + scoreString = item->data(COLUMN_DATA, ROLE_NAME).toString(); + break; + case FILTER_DESC_INDEX: + scoreString = item->data(COLUMN_DATA, ROLE_DESCRIPTION).toString(); + break; + } + + score = scoreString.count(filterText, Qt::CaseInsensitive); + + if (score) { + item->setHidden(false); + } else { + item->setHidden(true); + } } + + item->setData(COLUMN_DATA, ROLE_SEARCH_SCORE, -score); // negative for correct sorting + + return; } - item->setData(COLUMN_DATA, ROLE_SEARCH_SCORE, -score); // negative for correct sorting - - return score; - -} - -void GroupTreeWidget::calculateScores(const QString &filterText) -{ /* Find out which has given word in it */ QTreeWidgetItemIterator itemIterator(ui->treeWidget); + QTreeWidgetItem *item; + while ((item = *itemIterator) != NULL) { + itemIterator++; - int count = ui->treeWidget->topLevelItemCount(); - for (int child = 0; child < count; child++) { - QTreeWidgetItem *catitem = ui->treeWidget->topLevelItem(child); - int icount = catitem->childCount(); - for (int nIndex = 0; nIndex < icount; ++nIndex) { - calculateScore(catitem->child(nIndex), filterText); + if (item->data(COLUMN_DATA, ROLE_ID).toString().isEmpty()) { + continue; } + + calculateScore(item, filterText); } } void GroupTreeWidget::filterChanged() { /* Recalculate score */ - calculateScores(ui->filterLineEdit->text()); + calculateScore(NULL, ui->filterLineEdit->text()); - sort(); + resort(NULL); } -void GroupTreeWidget::resort(QTreeWidgetItem *categoryItem, Qt::SortOrder *order) +void GroupTreeWidget::resort(QTreeWidgetItem *categoryItem) { - if(order == NULL){ - Qt::SortOrder so = (actionSortAscending == NULL || actionSortAscending->isChecked()) ? Qt::AscendingOrder : Qt::DescendingOrder; - order = &so; + Qt::SortOrder order = (actionSortAscending == NULL || actionSortAscending->isChecked()) ? Qt::AscendingOrder : Qt::DescendingOrder; - if (ui->filterLineEdit->text().isEmpty() == false) { - compareRole->setRole(COLUMN_DATA, ROLE_SEARCH_SCORE); - compareRole->addRole(COLUMN_DATA, ROLE_LASTPOST); - } else if (actionSortByName && actionSortByName->isChecked()) { - compareRole->setRole(COLUMN_DATA, ROLE_NAME); - } else if (actionSortByPopularity && actionSortByPopularity->isChecked()) { - compareRole->setRole(COLUMN_DATA, ROLE_POPULARITY); - } else if (actionSortByLastPost && actionSortByLastPost->isChecked()) { - compareRole->setRole(COLUMN_DATA, ROLE_LASTPOST); - } + if (ui->filterLineEdit->text().isEmpty() == false) { + compareRole->setRole(COLUMN_DATA, ROLE_SEARCH_SCORE); + compareRole->addRole(COLUMN_DATA, ROLE_LASTPOST); + } else if (actionSortByName && actionSortByName->isChecked()) { + compareRole->setRole(COLUMN_DATA, ROLE_NAME); + } else if (actionSortByPopularity && actionSortByPopularity->isChecked()) { + compareRole->setRole(COLUMN_DATA, ROLE_POPULARITY); + } else if (actionSortByLastPost && actionSortByLastPost->isChecked()) { + compareRole->setRole(COLUMN_DATA, ROLE_LASTPOST); } - categoryItem->sortChildren(COLUMN_DATA, *order); - int count = categoryItem->childCount(); - for (int child = 0; child < count; child++) { - resort(categoryItem->child(child), order); + if (categoryItem) { + categoryItem->sortChildren(COLUMN_DATA, order); + } else { + int count = ui->treeWidget->topLevelItemCount(); + for (int child = 0; child < count; child++) { + ui->treeWidget->topLevelItem(child)->sortChildren(COLUMN_DATA, order); + } } } void GroupTreeWidget::sort() { - int count = ui->treeWidget->topLevelItemCount(); - for (int child = 0; child < count; child++) { - resort(ui->treeWidget->topLevelItem(child), NULL); - } + resort(NULL); } diff --git a/retroshare-gui/src/gui/common/GroupTreeWidget.h b/retroshare-gui/src/gui/common/GroupTreeWidget.h index 4e222fd22..dd7326ac3 100644 --- a/retroshare-gui/src/gui/common/GroupTreeWidget.h +++ b/retroshare-gui/src/gui/common/GroupTreeWidget.h @@ -55,7 +55,6 @@ public: QString id; QString name; QString description; - QString parentId; int popularity; QDateTime lastpost; QIcon icon; @@ -86,8 +85,6 @@ public: QString itemId(QTreeWidgetItem *item); // Fill items of a group void fillGroupItems(QTreeWidgetItem *categoryItem, const QList &itemList); - QTreeWidgetItem *recursiveIdSearch(QTreeWidgetItem *currentItem, const QString &id); - void checkOrphans(QList &orphanList, QTreeWidgetItem *justInserted); // Set the unread count of an item void setUnreadCount(QTreeWidgetItem *item, int unreadCount); @@ -123,9 +120,8 @@ private slots: private: // Initialize the display menu for sorting void initDisplayMenu(QToolButton *toolButton); - int calculateScore(QTreeWidgetItem *item, const QString &filterText); - void calculateScores(const QString &filterText); - void resort(QTreeWidgetItem *categoryItem, Qt::SortOrder *order); + void calculateScore(QTreeWidgetItem *item, const QString &filterText); + void resort(QTreeWidgetItem *categoryItem); void updateColors(); private: diff --git a/retroshare-gui/src/gui/gxs/GxsGroupDialog.cpp b/retroshare-gui/src/gui/gxs/GxsGroupDialog.cpp index dbd07bedc..d3f93cc24 100644 --- a/retroshare-gui/src/gui/gxs/GxsGroupDialog.cpp +++ b/retroshare-gui/src/gui/gxs/GxsGroupDialog.cpp @@ -94,8 +94,6 @@ void GxsGroupDialog::init() this->resize(this->size().width() - ui.contactsdockWidget->size().width(), this->size().height()); } - ui.parentGroupBox->setVisible(false); - /* initialize key share list */ ui.keyShareList->setHeaderText(tr("Contacts:")); ui.keyShareList->setModus(FriendSelectionWidget::MODUS_CHECK); @@ -150,13 +148,13 @@ void GxsGroupDialog::initMode() { ui.buttonBox->setStandardButtons(QDialogButtonBox::Close); } - break; -//TODO -// case MODE_EDIT: -// { -// ui.createButton->setText(tr("Submit Changes")); -// } -// break; + break; + case MODE_EDIT: + { + ui.buttonBox->setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); + ui.buttonBox->button(QDialogButtonBox::Ok)->setText(tr("Submit Group Changes")); + } + break; } } @@ -322,17 +320,40 @@ void GxsGroupDialog::submitGroup() break; case MODE_EDIT: - { - /* TEMP: just close if down */ - cancelDialog(); + { + + editGroup(); } break; } } -void GxsGroupDialog::setParentLabel(QString parentId){ - ui.parentGroupBox->setVisible(true); - ui.parentLabel->setText(parentId); +void GxsGroupDialog::editGroup() +{ + std::cerr << "GxsGroupDialog::editGroup()" << std::endl; + + QString name = misc::removeNewLine(ui.groupName->text()); + uint32_t flags = GXS_SERV::FLAG_PRIVACY_PUBLIC; + + if(name.isEmpty()) + { + /* error message */ + QMessageBox::warning(this, "RetroShare", tr("Please add a Name"), QMessageBox::Ok, QMessageBox::Ok); + return; //Don't add a empty name!! + } + + uint32_t token; + RsGxsGroupUpdateMeta updateMeta(mGrpMeta.mGroupId); + updateMeta.setMetaUpdate(RsGxsGroupUpdateMeta::NAME, std::string(name.toUtf8())); + + if (service_EditGroup(token, updateMeta)) + { + // get the Queue to handle response. + if(mTokenQueue != NULL) + mTokenQueue->queueRequest(token, TOKENREQ_GROUPINFO, RS_TOKREQ_ANSTYPE_ACK, GXSGROUP_NEWGROUPID); + } + + close(); } void GxsGroupDialog::createGroup() @@ -340,8 +361,7 @@ void GxsGroupDialog::createGroup() std::cerr << "GxsGroupDialog::createGroup()"; std::cerr << std::endl; - QString name = misc::removeNewLine(ui.groupName->text()); - QString parentGroupId = misc::removeNewLine(ui.parentLabel->text()); + QString name = misc::removeNewLine(ui.groupName->text()); uint32_t flags = GXS_SERV::FLAG_PRIVACY_PUBLIC; if(name.isEmpty()) @@ -356,8 +376,6 @@ void GxsGroupDialog::createGroup() // Fill in the MetaData as best we can. meta.mGroupName = std::string(name.toUtf8()); - if(parentGroupId.length()>10) - meta.mParentGrpId = parentGroupId.toStdString(); meta.mGroupFlags = flags; meta.mSignFlags = getGroupSignFlags(); diff --git a/retroshare-gui/src/gui/gxs/GxsGroupDialog.h b/retroshare-gui/src/gui/gxs/GxsGroupDialog.h index 8356d8715..35db177d0 100644 --- a/retroshare-gui/src/gui/gxs/GxsGroupDialog.h +++ b/retroshare-gui/src/gui/gxs/GxsGroupDialog.h @@ -143,7 +143,6 @@ public: uint32_t mode() { return mMode; } - void setParentLabel(QString parentId); private: void newGroup(); void init(); @@ -156,8 +155,6 @@ protected slots: void addGroupLogo(); protected: - /** Qt Designer generated object */ - Ui::GxsGroupDialog ui; virtual void showEvent(QShowEvent*); virtual void initUi() = 0; @@ -166,13 +163,21 @@ protected: void setUiText(UiType uiType, const QString &text); /*! - * Main purpose is to help tansfer meta data to service - * + * It is up to the service to do the actual group creation + * Service can also modify initial meta going into group * @param token This should be set to the token retrieved * @param meta The deriving GXS service should set their grp meta to this value */ virtual bool service_CreateGroup(uint32_t &token, const RsGroupMetaData &meta) = 0; + /*! + * It is up to the service to do the actual group editing + * TODO: make pure virtual + * @param token This should be set to the token retrieved + * @param meta The deriving GXS service should set their grp meta to this value + */ + virtual bool service_EditGroup(uint32_t &token, RsGxsGroupUpdateMeta &updateMeta) {} + /*! * This returns a group logo from the ui \n * Should be calleld by deriving service @@ -205,6 +210,7 @@ private: void setupVisibility(); void clearForm(); void createGroup(); + void editGroup(); void sendShareList(std::string forumId); void loadNewGroupId(const uint32_t &token); @@ -218,7 +224,10 @@ private: uint32_t mReadonlyFlags; uint32_t mDefaultsFlags; + protected: + /** Qt Designer generated object */ + Ui::GxsGroupDialog ui; }; #endif diff --git a/retroshare-gui/src/gui/gxs/GxsGroupDialog.ui b/retroshare-gui/src/gui/gxs/GxsGroupDialog.ui index 1ee1514ae..632dc6027 100644 --- a/retroshare-gui/src/gui/gxs/GxsGroupDialog.ui +++ b/retroshare-gui/src/gui/gxs/GxsGroupDialog.ui @@ -7,7 +7,7 @@ 0 0 695 - 518 + 448 @@ -156,7 +156,7 @@ - + true @@ -257,7 +257,7 @@ - + Message Distribution @@ -323,7 +323,7 @@ - + Publish Signatures @@ -366,7 +366,7 @@ - + Personal Signatures @@ -402,7 +402,7 @@ - + Comments @@ -431,7 +431,7 @@ - + QFrame::StyledPanel @@ -441,40 +441,13 @@ - + QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - - - - Parent: - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - - - - - None - - - - - - - - @@ -506,6 +479,7 @@ + From ae5942733ebf1d83d920e1f11e615c18159953b8 Mon Sep 17 00:00:00 2001 From: drbob Date: Mon, 20 Jan 2014 11:42:27 +0000 Subject: [PATCH 79/83] - Split majority of p3posted into p3postbase.cc - so that it can be reused by other services. - Fixed iterator overflow into rsgxsupdateitems.cc - Fixed Mutex deadlock in pqiperson.cc - Removed old code. - Fixed lots of compile warnings - mainly wrong variable ordering in constructors. git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@7044 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/gxs/rsgxsdataaccess.h | 4 +- libretroshare/src/gxs/rsgxsnetservice.cc | 9 +- libretroshare/src/gxs/rsgxsutil.h | 2 +- libretroshare/src/libretroshare.pro | 6 +- libretroshare/src/pqi/pqiperson.cc | 7 +- libretroshare/src/pqi/pqiperson.h | 2 + libretroshare/src/pqi/pqissl.cc | 9 +- libretroshare/src/pqi/pqithreadstreamer.cc | 2 +- libretroshare/src/retroshare/rsposted.h | 1 - .../src/serialiser/rsgxsupdateitems.cc | 6 +- libretroshare/src/services/p3gxschannels.cc | 2 +- libretroshare/src/services/p3gxscircles.cc | 4 +- libretroshare/src/services/p3gxsforums.cc | 2 +- libretroshare/src/services/p3gxsserviceVEG.cc | 1467 ----------- libretroshare/src/services/p3gxsserviceVEG.h | 191 -- libretroshare/src/services/p3idservice.cc | 7 +- libretroshare/src/services/p3idservice.h | 2 +- libretroshare/src/services/p3postbase.cc | 723 ++++++ libretroshare/src/services/p3postbase.h | 135 ++ libretroshare/src/services/p3posted.cc | 974 +------- libretroshare/src/services/p3posted.h | 148 +- libretroshare/src/services/p3postedVEG.cc | 2148 ----------------- libretroshare/src/services/p3postedVEG.h | 190 -- libretroshare/src/services/p3wiki.cc | 2 +- 24 files changed, 921 insertions(+), 5122 deletions(-) delete mode 100644 libretroshare/src/services/p3gxsserviceVEG.cc delete mode 100644 libretroshare/src/services/p3gxsserviceVEG.h create mode 100644 libretroshare/src/services/p3postbase.cc create mode 100644 libretroshare/src/services/p3postbase.h delete mode 100644 libretroshare/src/services/p3postedVEG.cc delete mode 100644 libretroshare/src/services/p3postedVEG.h diff --git a/libretroshare/src/gxs/rsgxsdataaccess.h b/libretroshare/src/gxs/rsgxsdataaccess.h index 3b0aa8113..1cf439209 100644 --- a/libretroshare/src/gxs/rsgxsdataaccess.h +++ b/libretroshare/src/gxs/rsgxsdataaccess.h @@ -436,11 +436,13 @@ private: private: RsGeneralDataService* mDataStore; + + RsMutex mDataMutex; /* protecting below */ + uint32_t mNextToken; std::map mPublicToken; std::map mRequests; - RsMutex mDataMutex; }; diff --git a/libretroshare/src/gxs/rsgxsnetservice.cc b/libretroshare/src/gxs/rsgxsnetservice.cc index 9f2ffbf3c..6a31a0c27 100644 --- a/libretroshare/src/gxs/rsgxsnetservice.cc +++ b/libretroshare/src/gxs/rsgxsnetservice.cc @@ -1646,10 +1646,13 @@ void RsGxsNetService::locked_genReqGrpTransaction(NxsTransaction* tr) RsNxsSyncGrpItem*& grpSyncItem = *llit; const std::string& grpId = grpSyncItem->grpId; metaIter = grpMetaMap.find(grpId); - bool haveItem = metaIter != grpMetaMap.end(); + bool haveItem = false; bool latestVersion = false; - - latestVersion = grpSyncItem->publishTs > metaIter->second->mPublishTs; + if (metaIter != grpMetaMap.end()) + { + haveItem = true; + latestVersion = grpSyncItem->publishTs > metaIter->second->mPublishTs; + } if(!haveItem || (haveItem && latestVersion) ){ diff --git a/libretroshare/src/gxs/rsgxsutil.h b/libretroshare/src/gxs/rsgxsutil.h index 9e11b5e41..2828ea637 100644 --- a/libretroshare/src/gxs/rsgxsutil.h +++ b/libretroshare/src/gxs/rsgxsutil.h @@ -143,7 +143,7 @@ class GroupUpdatePublish { public: GroupUpdatePublish(RsGxsGrpItem* item, RsGxsGroupUpdateMeta updateMeta, uint32_t token) - : grpItem(item), mToken(token), mUpdateMeta(updateMeta) {} + : grpItem(item), mUpdateMeta(updateMeta), mToken(token) {} RsGxsGrpItem* grpItem; RsGxsGroupUpdateMeta mUpdateMeta; uint32_t mToken; diff --git a/libretroshare/src/libretroshare.pro b/libretroshare/src/libretroshare.pro index e4ccd7596..51cf17d3f 100644 --- a/libretroshare/src/libretroshare.pro +++ b/libretroshare/src/libretroshare.pro @@ -711,11 +711,13 @@ gxs { serialiser/rswireitems.cc \ # Posted Service - HEADERS += services/p3posted.h \ + HEADERS += services/p3postbase.h \ + services/p3posted.h \ retroshare/rsposted.h \ serialiser/rsposteditems.h - SOURCES += services/p3posted.cc \ + SOURCES += services/p3postbase.cc \ + services/p3posted.cc \ serialiser/rsposteditems.cc #Photo Service diff --git a/libretroshare/src/pqi/pqiperson.cc b/libretroshare/src/pqi/pqiperson.cc index 8c45fff1e..45fab8acb 100644 --- a/libretroshare/src/pqi/pqiperson.cc +++ b/libretroshare/src/pqi/pqiperson.cc @@ -151,7 +151,7 @@ int pqiperson::tick() out += " No Heartbeat & No Packets -> assume dead. calling pqissl::reset()"; pqioutput(PQL_WARNING, pqipersonzone, out); - this->reset(); + this->reset_locked(); } } @@ -384,6 +384,11 @@ int pqiperson::reset() { RsStackMutex stack(mPersonMtx); /**** LOCK MUTEX ****/ + return reset_locked(); +} + +int pqiperson::reset_locked() +{ pqioutput(PQL_WARNING, pqipersonzone, "pqiperson::reset() resetting all pqiconnect for Id: " + PeerId()); std::map::iterator it; diff --git a/libretroshare/src/pqi/pqiperson.h b/libretroshare/src/pqi/pqiperson.h index bcb2de6a8..0afe260e3 100644 --- a/libretroshare/src/pqi/pqiperson.h +++ b/libretroshare/src/pqi/pqiperson.h @@ -179,6 +179,8 @@ int handleNotifyEvent_locked(NetInterface *ni, int event, const struct socka RsMutex mPersonMtx; /**** LOCKS below ****/ +int reset_locked(); + void setRateCap_locked(float val_in, float val_out); std::map kids; diff --git a/libretroshare/src/pqi/pqissl.cc b/libretroshare/src/pqi/pqissl.cc index aebe05550..49c8821fe 100644 --- a/libretroshare/src/pqi/pqissl.cc +++ b/libretroshare/src/pqi/pqissl.cc @@ -93,16 +93,15 @@ static const int PQISSL_SSL_CONNECT_TIMEOUT = 30; pqissl::pqissl(pqissllistener *l, PQInterface *parent, p3LinkMgr *lm) :NetBinInterface(parent, parent->PeerId()), + mLinkMgr(lm), pqil(l), mSslMtx("pqissl"), - waiting(WAITING_NOT), active(false), certvalid(false), + active(false), certvalid(false), waiting(WAITING_NOT), sslmode(PQISSL_ACTIVE), ssl_connection(NULL), sockfd(-1), - pqil(l), // no init for remote_addr. - readpkt(NULL), pktlen(0), + readpkt(NULL), pktlen(0), total_len(0), attempt_ts(0), sameLAN(false), n_read_zero(0), mReadZeroTS(0), mConnectDelay(0), mConnectTS(0), - mConnectTimeout(0), mTimeoutTS(0), mLinkMgr(lm) - + mConnectTimeout(0), mTimeoutTS(0) { RsStackMutex stack(mSslMtx); /**** LOCKED MUTEX ****/ diff --git a/libretroshare/src/pqi/pqithreadstreamer.cc b/libretroshare/src/pqi/pqithreadstreamer.cc index b9507b135..43aae789c 100644 --- a/libretroshare/src/pqi/pqithreadstreamer.cc +++ b/libretroshare/src/pqi/pqithreadstreamer.cc @@ -32,7 +32,7 @@ #define DEFAULT_STREAMER_IDLE_SLEEP 1000000 // 1 sec pqithreadstreamer::pqithreadstreamer(PQInterface *parent, RsSerialiser *rss, std::string id, BinInterface *bio_in, int bio_flags_in) -:pqistreamer(rss, id, bio_in, bio_flags_in), mThreadMutex("pqithreadstreamer"), mParent(parent), mTimeout(0) +:pqistreamer(rss, id, bio_in, bio_flags_in), mParent(parent), mThreadMutex("pqithreadstreamer"), mTimeout(0) { mTimeout = DEFAULT_STREAMER_TIMEOUT; mSleepPeriod = DEFAULT_STREAMER_SLEEP; diff --git a/libretroshare/src/retroshare/rsposted.h b/libretroshare/src/retroshare/rsposted.h index 9eb30d248..eeb60c001 100644 --- a/libretroshare/src/retroshare/rsposted.h +++ b/libretroshare/src/retroshare/rsposted.h @@ -82,7 +82,6 @@ class RsPosted : public RsGxsIfaceHelper, public RsGxsCommentService virtual ~RsPosted() { return; } /* Specific Service Data */ - virtual bool getGroupData(const uint32_t &token, std::vector &groups) = 0; virtual bool getPostData(const uint32_t &token, std::vector &posts) = 0; virtual bool getRelatedPosts(const uint32_t &token, std::vector &posts) = 0; diff --git a/libretroshare/src/serialiser/rsgxsupdateitems.cc b/libretroshare/src/serialiser/rsgxsupdateitems.cc index 26bcff9c3..52618720f 100644 --- a/libretroshare/src/serialiser/rsgxsupdateitems.cc +++ b/libretroshare/src/serialiser/rsgxsupdateitems.cc @@ -51,7 +51,7 @@ void RsGxsMsgUpdateItem::clear() std::ostream& RsGxsMsgUpdateItem::print(std::ostream& out, uint16_t indent) { - + return out; } @@ -64,7 +64,7 @@ void RsGxsServerMsgUpdateItem::clear() std::ostream& RsGxsServerMsgUpdateItem::print(std::ostream& out, uint16_t indent) { - + return out; } @@ -75,7 +75,7 @@ void RsGxsServerGrpUpdateItem::clear() std::ostream& RsGxsServerGrpUpdateItem::print(std::ostream& out, uint16_t indent) { - + return out; } diff --git a/libretroshare/src/services/p3gxschannels.cc b/libretroshare/src/services/p3gxschannels.cc index 96fee6a69..e570cbf66 100644 --- a/libretroshare/src/services/p3gxschannels.cc +++ b/libretroshare/src/services/p3gxschannels.cc @@ -1165,7 +1165,7 @@ bool p3GxsChannels::generateVote(uint32_t &token, const RsGxsGroupId &grpId, con uint32_t idx = (uint32_t) (ownIds.size() * RSRandom::random_f32()); uint32_t i = 0; - for(it = ownIds.begin(); (it != ownIds.end()) && (i < idx); it++, i++); + for(it = ownIds.begin(); (it != ownIds.end()) && (i < idx); it++, i++) ; if (it != ownIds.end()) { diff --git a/libretroshare/src/services/p3gxscircles.cc b/libretroshare/src/services/p3gxscircles.cc index 8d9e98f30..f82193a4f 100644 --- a/libretroshare/src/services/p3gxscircles.cc +++ b/libretroshare/src/services/p3gxscircles.cc @@ -1511,7 +1511,7 @@ void p3GxsCircles::generateDummyCircle() int selection = (RSRandom::random_u32() % npgps); std::list::iterator it = mDummyPgpLinkedIds.begin(); - for(int j = 0; (it != mDummyPgpLinkedIds.end()) && (j < selection); j++, it++); + for(int j = 0; (it != mDummyPgpLinkedIds.end()) && (j < selection); j++, it++) ; if (it != mDummyPgpLinkedIds.end()) { idset.insert(*it); @@ -1525,7 +1525,7 @@ void p3GxsCircles::generateDummyCircle() int selection = (RSRandom::random_u32() % mDummyOwnIds.size()); std::list::iterator it = mDummyOwnIds.begin(); mDummyOwnIds.push_back(*it); - for(int j = 0; (it != mDummyOwnIds.end()) && (j < selection); j++, it++); + for(int j = 0; (it != mDummyOwnIds.end()) && (j < selection); j++, it++) ; if (it != mDummyOwnIds.end()) { idset.insert(*it); diff --git a/libretroshare/src/services/p3gxsforums.cc b/libretroshare/src/services/p3gxsforums.cc index bdc8472e0..83493e32e 100644 --- a/libretroshare/src/services/p3gxsforums.cc +++ b/libretroshare/src/services/p3gxsforums.cc @@ -438,7 +438,7 @@ bool p3GxsForums::generateMessage(uint32_t &token, const RsGxsGroupId &grpId, co uint32_t idx = (uint32_t) (ownIds.size() * RSRandom::random_f32()); int i = 0; - for(it = ownIds.begin(); (it != ownIds.end()) && (i < idx); it++, i++); + for(it = ownIds.begin(); (it != ownIds.end()) && (i < idx); it++, i++) ; if (it != ownIds.end()) { diff --git a/libretroshare/src/services/p3gxsserviceVEG.cc b/libretroshare/src/services/p3gxsserviceVEG.cc deleted file mode 100644 index 11ab6e013..000000000 --- a/libretroshare/src/services/p3gxsserviceVEG.cc +++ /dev/null @@ -1,1467 +0,0 @@ -/* - * libretroshare/src/services p3gxsservice.cc - * - * Generic Service Support Class for RetroShare. - * - * Copyright 2012 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/p3gxsserviceVEG.h" - -p3GxsServiceVEG::p3GxsServiceVEG(uint16_t type) - :p3Service(type), mReqMtx("p3GxsService") -{ - mNextToken = 0; - return; -} - -bool p3GxsServiceVEG::generateToken(uint32_t &token) -{ - RsStackMutex stack(mReqMtx); /****** LOCKED *****/ - - token = mNextToken++; - - return true; -} - -bool p3GxsServiceVEG::storeRequest(const uint32_t &token, const uint32_t &ansType, const RsTokReqOptionsVEG &opts, const uint32_t &type, const std::list &ids) -{ - RsStackMutex stack(mReqMtx); /****** LOCKED *****/ - - gxsRequest req; - req.token = token; - req.reqTime = time(NULL); - req.reqType = type; - req.ansType = ansType; - req.Options = opts; - req.status = GXS_REQUEST_STATUS_PENDING; - req.inList = ids; - - mRequests[token] = req; - - return true; -} - - -bool p3GxsServiceVEG::clearRequest(const uint32_t &token) -{ - RsStackMutex stack(mReqMtx); /****** LOCKED *****/ - - std::map::iterator it; - - it = mRequests.find(token); - if (it == mRequests.end()) - { - return false; - } - - mRequests.erase(it); - - return true; -} - -bool p3GxsServiceVEG::updateRequestStatus(const uint32_t &token, const uint32_t &status) -{ - RsStackMutex stack(mReqMtx); /****** LOCKED *****/ - - std::map::iterator it; - - it = mRequests.find(token); - if (it == mRequests.end()) - { - return false; - } - - it->second.status = status; - - return true; -} - -bool p3GxsServiceVEG::updateRequestInList(const uint32_t &token, std::list ids) -{ - RsStackMutex stack(mReqMtx); /****** LOCKED *****/ - - std::map::iterator it; - - it = mRequests.find(token); - if (it == mRequests.end()) - { - return false; - } - - std::list::iterator iit; - for(iit = ids.begin(); iit != ids.end(); iit++) - { - it->second.inList.push_back(*iit); - } - - return true; -} - - -bool p3GxsServiceVEG::updateRequestOutList(const uint32_t &token, std::list ids) -{ - RsStackMutex stack(mReqMtx); /****** LOCKED *****/ - - std::map::iterator it; - - it = mRequests.find(token); - if (it == mRequests.end()) - { - return false; - } - - std::list::iterator iit; - for(iit = ids.begin(); iit != ids.end(); iit++) - { - it->second.outList.push_back(*iit); - } - - return true; -} - -#if 0 -bool p3GxsServiceVEG::updateRequestData(const uint32_t &token, std::map data) -{ - RsStackMutex stack(mReqMtx); /****** LOCKED *****/ - - std::map::iterator it; - - it = mRequests.find(token); - if (it == mRequests.end()) - { - return false; - } - - std::map::iterator dit; - for(dit = data.begin(); dit != data.end(); dit++) - { - it->second.readyData[dit->first] = dit->second; - } - - return true; -} -#endif - -bool p3GxsServiceVEG::checkRequestStatus(const uint32_t &token, uint32_t &status, uint32_t &reqtype, uint32_t &anstype, time_t &ts) -{ - RsStackMutex stack(mReqMtx); /****** LOCKED *****/ - - std::map::iterator it; - - it = mRequests.find(token); - if (it == mRequests.end()) - { - return false; - } - - status = it->second.status; - reqtype = it->second.reqType; - anstype = it->second.ansType; - ts = it->second.reqTime; - - return true; -} - - - // special ones for testing (not in final design) -bool p3GxsServiceVEG::tokenList(std::list &tokens) -{ - RsStackMutex stack(mReqMtx); /****** LOCKED *****/ - - std::map::iterator it; - - for(it = mRequests.begin(); it != mRequests.end(); it++) - { - tokens.push_back(it->first); - } - - return true; -} - -bool p3GxsServiceVEG::popRequestInList(const uint32_t &token, std::string &id) -{ - RsStackMutex stack(mReqMtx); /****** LOCKED *****/ - - std::map::iterator it; - - it = mRequests.find(token); - if (it == mRequests.end()) - { - return false; - } - - if (it->second.inList.size() == 0) - { - return false; - } - - id = it->second.inList.front(); - it->second.inList.pop_front(); - - return true; -} - - -bool p3GxsServiceVEG::popRequestOutList(const uint32_t &token, std::string &id) -{ - RsStackMutex stack(mReqMtx); /****** LOCKED *****/ - - std::map::iterator it; - - it = mRequests.find(token); - if (it == mRequests.end()) - { - return false; - } - - if (it->second.outList.size() == 0) - { - return false; - } - - id = it->second.outList.front(); - it->second.outList.pop_front(); - - return true; -} - - -bool p3GxsServiceVEG::loadRequestOutList(const uint32_t &token, std::list &ids) -{ - RsStackMutex stack(mReqMtx); /****** LOCKED *****/ - - std::map::iterator it; - - it = mRequests.find(token); - if (it == mRequests.end()) - { - return false; - } - - if (it->second.outList.size() == 0) - { - return false; - } - - ids = it->second.outList; - it->second.outList.clear(); - - return true; -} - - -#define MAX_REQUEST_AGE 10 - -bool p3GxsServiceVEG::fakeprocessrequests() - { - std::list::iterator it; - std::list tokens; - - tokenList(tokens); - - time_t now = time(NULL); - for(it = tokens.begin(); it != tokens.end(); it++) - { - uint32_t status; - uint32_t reqtype; - uint32_t anstype; - uint32_t token = *it; - time_t ts; - checkRequestStatus(token, status, reqtype, anstype, ts); - - std::cerr << "p3GxsServiceVEG::fakeprocessrequests() Token: " << token << " Status: " << status << " ReqType: " << reqtype << "Age: " << now - ts << std::endl; - - if (status == GXS_REQUEST_STATUS_PENDING) - { - updateRequestStatus(token, GXS_REQUEST_STATUS_PARTIAL); - } - else if (status == GXS_REQUEST_STATUS_PARTIAL) - { - updateRequestStatus(token, GXS_REQUEST_STATUS_COMPLETE); - } - else if (status == GXS_REQUEST_STATUS_DONE) - { - std::cerr << "p3GxsServiceVEG::fakeprocessrequests() Clearing Done Request Token: " << token; - std::cerr << std::endl; - clearRequest(token); - } - else if (now - ts > MAX_REQUEST_AGE) - { - std::cerr << "p3GxsServiceVEG::fakeprocessrequests() Clearing Old Request Token: " << token; - std::cerr << std::endl; - clearRequest(token); - } - } - - return true; -} - - - -/*********************************************************************************************************/ -/*********************************************************************************************************/ -/*********************************************************************************************************/ -/*********************************************************************************************************/ -/*********************************************************************************************************/ - - -/****** GXS Data Dummy .... Handles generic data storage and access. designed for testing GUIs - * without being dependent on the backend. - * - * - * - * Important to specify the exact behaviour with flags! - * - * - * - ****/ - -GxsDataProxyVEG::GxsDataProxyVEG() - :mDataMtx("GxsDataProxyMtx") -{ - return; -} - - -static bool checkGroupFilter(const RsTokReqOptionsVEG &opts, const RsGroupMetaData &group) -{ - bool statusMatch = false; - if (opts.mStatusMask) - { - // Exact Flags match required. - if ((opts.mStatusMask & opts.mStatusFilter) == (opts.mStatusMask & group.mGroupStatus)) - { - std::cerr << "checkGroupFilter() Accepting Group as StatusMatches: "; - std::cerr << " Mask: " << opts.mStatusMask << " StatusFilter: " << opts.mStatusFilter; - std::cerr << " GroupStatus: " << group.mGroupStatus << " GroupId: " << group.mGroupId; - std::cerr << std::endl; - - statusMatch = true; - } - else - { - std::cerr << "checkGroupFilter() Dropping Group due to !StatusMatch "; - std::cerr << " Mask: " << opts.mStatusMask << " StatusFilter: " << opts.mStatusFilter; - std::cerr << " GroupStatus: " << group.mGroupStatus << " GroupId: " << group.mGroupId; - std::cerr << std::endl; - } - } - else - { - // no status comparision, - statusMatch = true; - } - - bool flagsMatch = false; - if (opts.mFlagsMask) - { - // Exact Flags match required. - if ((opts.mFlagsMask & opts.mFlagsFilter) == (opts.mFlagsMask & group.mGroupFlags)) - { - std::cerr << "checkGroupFilter() Accepting Group as Flags Match: "; - std::cerr << " Mask: " << opts.mFlagsMask << " FlagsFilter: " << opts.mFlagsFilter; - std::cerr << " GroupFlags: " << group.mGroupFlags << " GroupId: " << group.mGroupId; - std::cerr << std::endl; - - flagsMatch = true; - } - else - { - std::cerr << "checkGroupFilter() Dropping Group due to !Flags Match "; - std::cerr << " Mask: " << opts.mFlagsMask << " FlagsFilter: " << opts.mFlagsFilter; - std::cerr << " GroupFlags: " << group.mGroupFlags << " GroupId: " << group.mGroupId; - std::cerr << std::endl; - } - } - else - { - // no status comparision, - flagsMatch = true; - } - - bool subMatch = false; - if (opts.mSubscribeFilter) - { - // Exact Flags match required. - if (opts.mSubscribeFilter & group.mSubscribeFlags) - { - std::cerr << "checkGroupFilter() Accepting Group as SubscribeMatches: "; - std::cerr << " SubscribeFilter: " << opts.mSubscribeFilter; - std::cerr << " GroupSubscribeFlags: " << group.mSubscribeFlags << " GroupId: " << group.mGroupId; - std::cerr << std::endl; - - subMatch = true; - } - else - { - std::cerr << "checkGroupFilter() Dropping Group due to !SubscribeMatch "; - std::cerr << " SubscribeFilter: " << opts.mSubscribeFilter; - std::cerr << " GroupSubscribeFlags: " << group.mSubscribeFlags << " GroupId: " << group.mGroupId; - std::cerr << std::endl; - } - } - else - { - // no subscribe comparision, - subMatch = true; - } - - return (statusMatch && flagsMatch && subMatch); -} - - -static bool checkMsgFilter(const RsTokReqOptionsVEG &opts, const RsMsgMetaData &msg) -{ - bool statusMatch = false; - if (opts.mStatusMask) - { - // Exact Flags match required. - if ((opts.mStatusMask & opts.mStatusFilter) == (opts.mStatusMask & msg.mMsgStatus)) - { - std::cerr << "checkMsgFilter() Accepting Msg as StatusMatches: "; - std::cerr << " Mask: " << opts.mStatusMask << " StatusFilter: " << opts.mStatusFilter; - std::cerr << " MsgStatus: " << msg.mMsgStatus << " MsgId: " << msg.mMsgId; - std::cerr << std::endl; - - statusMatch = true; - } - else - { - std::cerr << "checkMsgFilter() Dropping Msg due to !StatusMatch "; - std::cerr << " Mask: " << opts.mStatusMask << " StatusFilter: " << opts.mStatusFilter; - std::cerr << " MsgStatus: " << msg.mMsgStatus << " MsgId: " << msg.mMsgId; - std::cerr << std::endl; - } - } - else - { - // no status comparision, - statusMatch = true; - } - - bool flagsMatch = false; - if (opts.mFlagsMask) - { - // Exact Flags match required. - if ((opts.mFlagsMask & opts.mFlagsFilter) == (opts.mFlagsMask & msg.mMsgFlags)) - { - std::cerr << "checkMsgFilter() Accepting Msg as Flags Match: "; - std::cerr << " Mask: " << opts.mFlagsMask << " FlagsFilter: " << opts.mFlagsFilter; - std::cerr << " MsgFlags: " << msg.mMsgFlags << " MsgId: " << msg.mMsgId; - std::cerr << std::endl; - - flagsMatch = true; - } - else - { - std::cerr << "checkMsgFilter() Dropping Msg due to !Flags Match "; - std::cerr << " Mask: " << opts.mFlagsMask << " FlagsFilter: " << opts.mFlagsFilter; - std::cerr << " MsgFlags: " << msg.mMsgFlags << " MsgId: " << msg.mMsgId; - std::cerr << std::endl; - } - } - else - { - // no status comparision, - flagsMatch = true; - } - - return (statusMatch && flagsMatch); -} - - -bool GxsDataProxyVEG::filterGroupList(const RsTokReqOptionsVEG &opts, std::list &groupIds) -{ - std::list::iterator it; - for(it = groupIds.begin(); it != groupIds.end(); ) - { - RsStackMutex stack(mDataMtx); /***** LOCKED *****/ - - bool keep = false; - /* find group */ - std::map::iterator mit; - mit = mGroupMetaData.find(*it); - if (mit != mGroupMetaData.end()) - { - keep = checkGroupFilter(opts, mit->second); - } - - if (keep) - { - it++; - } - else - { - it = groupIds.erase(it); - } - } - return true; -} - - -bool GxsDataProxyVEG::filterMsgList(const RsTokReqOptionsVEG &opts, std::list &msgIds) -{ - std::list::iterator it; - for(it = msgIds.begin(); it != msgIds.end(); ) - { - RsStackMutex stack(mDataMtx); /***** LOCKED *****/ - - bool keep = false; - /* find msg */ - std::map::iterator mit; - mit = mMsgMetaData.find(*it); - if (mit != mMsgMetaData.end()) - { - keep = checkMsgFilter(opts, mit->second); - } - - if (keep) - { - it++; - } - else - { - it = msgIds.erase(it); - } - } - return true; -} - - - -bool GxsDataProxyVEG::getGroupList( uint32_t &token, const RsTokReqOptionsVEG &opts, const std::list &groupIds, std::list &outGroupIds) -{ - /* CASEs that this handles ... - * 1) if groupIds is Empty... return all groupIds. - * 2) else copy list. - * - */ - std::cerr << "GxsDataProxyVEG::getGroupList()"; - std::cerr << std::endl; - - if (groupIds.size() == 0) - { - /* grab all the ids */ - RsStackMutex stack(mDataMtx); /***** LOCKED *****/ - - std::map::iterator mit; - for(mit = mGroupMetaData.begin(); mit != mGroupMetaData.end(); mit++) - { - outGroupIds.push_back(mit->first); - } - } - else - { - outGroupIds = groupIds; - } - - filterGroupList(opts, outGroupIds); - - return true; -} - - -bool GxsDataProxyVEG::getMsgList( uint32_t &token, const RsTokReqOptionsVEG &opts, const std::list &groupIds, std::list &outMsgIds) -{ - /* CASEs this handles. - * Input is groupList + Flags. - * 1) No Flags => All Messages in those Groups. - * - */ - std::cerr << "GxsDataProxyVEG::getMsgList()"; - std::cerr << std::endl; - - - bool onlyOrigMsgs = false; - bool onlyLatestMsgs = false; - bool onlyThreadHeadMsgs = false; - - // Can only choose one of these two. - if (opts.mOptions & RS_TOKREQOPT_MSG_ORIGMSG) - { - std::cerr << "GxsDataProxyVEG::getMsgList() MSG_ORIGMSG"; - std::cerr << std::endl; - onlyOrigMsgs = true; - } - else if (opts.mOptions & RS_TOKREQOPT_MSG_LATEST) - { - std::cerr << "GxsDataProxyVEG::getMsgList() MSG_LATEST"; - std::cerr << std::endl; - onlyLatestMsgs = true; - } - - if (opts.mOptions & RS_TOKREQOPT_MSG_THREAD) - { - std::cerr << "GxsDataProxyVEG::getMsgList() MSG_THREAD"; - std::cerr << std::endl; - onlyThreadHeadMsgs = true; - } - - std::list::const_iterator it; - std::map::iterator mit; - - for(it = groupIds.begin(); it != groupIds.end(); it++) - { - if (onlyLatestMsgs) // THIS ONE IS HARD -> LOTS OF COMP. - { - RsStackMutex stack(mDataMtx); /***** LOCKED *****/ - - // RUN THROUGH ALL MSGS... in map origId -> TS. - std::map > origMsgTs; - std::map >::iterator oit; - for(mit = mMsgMetaData.begin(); mit != mMsgMetaData.end(); mit++) - { - if (mit->second.mGroupId != *it) - { - continue; - } - - /* if we are grabbing thread Head... then parentId == empty. */ - if (onlyThreadHeadMsgs) - { - if (!(mit->second.mParentId.empty())) - { - continue; - } - } - - - oit = origMsgTs.find(mit->second.mOrigMsgId); - bool addMsg = false; - if (oit == origMsgTs.end()) - { - std::cerr << "GxsDataProxyVEG::getMsgList() Found New OrigMsgId: "; - std::cerr << mit->second.mOrigMsgId; - std::cerr << " MsgId: " << mit->second.mMsgId; - std::cerr << " TS: " << mit->second.mPublishTs; - std::cerr << std::endl; - - addMsg = true; - } - // check timestamps. - else if (oit->second.second < mit->second.mPublishTs) - { - std::cerr << "GxsDataProxyVEG::getMsgList() Found Later Msg. OrigMsgId: "; - std::cerr << mit->second.mOrigMsgId; - std::cerr << " MsgId: " << mit->second.mMsgId; - std::cerr << " TS: " << mit->second.mPublishTs; - - addMsg = true; - } - - if (addMsg) - { - // add as latest. (overwriting if necessary) - origMsgTs[mit->second.mOrigMsgId] = std::make_pair(mit->second.mMsgId, mit->second.mPublishTs); - } - } - - // Add the discovered Latest Msgs. - for(oit = origMsgTs.begin(); oit != origMsgTs.end(); oit++) - { - outMsgIds.push_back(oit->second.first); - } - - } - else // ALL OTHER CASES. - { - RsStackMutex stack(mDataMtx); /***** LOCKED *****/ - - for(mit = mMsgMetaData.begin(); mit != mMsgMetaData.end(); mit++) - { - if (mit->second.mGroupId == *it) - { - bool add = false; - - /* if we are grabbing thread Head... then parentId == empty. */ - if (onlyThreadHeadMsgs) - { - if (!(mit->second.mParentId.empty())) - { - continue; - } - } - - - if (onlyOrigMsgs) - { - if (mit->second.mMsgId == mit->second.mOrigMsgId) - { - add = true; - } - } - else - { - add = true; - } - - if (add) - { - outMsgIds.push_back(mit->first); - } - } - } - } - } - - filterMsgList(opts, outMsgIds); - - return true; -} - - -bool GxsDataProxyVEG::getMsgRelatedList(uint32_t &token, const RsTokReqOptionsVEG &opts, const std::list &msgIds, std::list &outMsgIds) -{ - /* CASEs this handles. - * Input is msgList + Flags. - * 1) No Flags => just copy msgIds (probably requesting data). - * - */ - - std::cerr << "GxsDataProxyVEG::getMsgRelatedList()"; - std::cerr << std::endl; - - bool onlyLatestMsgs = false; - bool onlyAllVersions = false; - bool onlyChildMsgs = false; - bool onlyThreadMsgs = false; - - if (opts.mOptions & RS_TOKREQOPT_MSG_LATEST) - { - std::cerr << "GxsDataProxyVEG::getMsgRelatedList() MSG_LATEST"; - std::cerr << std::endl; - onlyLatestMsgs = true; - } - else if (opts.mOptions & RS_TOKREQOPT_MSG_VERSIONS) - { - std::cerr << "GxsDataProxyVEG::getMsgRelatedList() MSG_VERSIONS"; - std::cerr << std::endl; - onlyAllVersions = true; - } - - if (opts.mOptions & RS_TOKREQOPT_MSG_PARENT) - { - std::cerr << "GxsDataProxyVEG::getMsgRelatedList() MSG_PARENTS"; - std::cerr << std::endl; - onlyChildMsgs = true; - } - - if (opts.mOptions & RS_TOKREQOPT_MSG_THREAD) - { - std::cerr << "GxsDataProxyVEG::getMsgRelatedList() MSG_THREAD"; - std::cerr << std::endl; - onlyThreadMsgs = true; - } - - if (onlyAllVersions && onlyChildMsgs) - { - std::cerr << "GxsDataProxyVEG::getMsgRelatedList() ERROR Incompatible FLAGS (VERSIONS & PARENT)"; - std::cerr << std::endl; - - return false; - } - - if (onlyAllVersions && onlyThreadMsgs) - { - std::cerr << "GxsDataProxyVEG::getMsgRelatedList() ERROR Incompatible FLAGS (VERSIONS & THREAD)"; - std::cerr << std::endl; - - return false; - } - - if ((!onlyLatestMsgs) && onlyChildMsgs) - { - std::cerr << "GxsDataProxyVEG::getMsgRelatedList() ERROR Incompatible FLAGS (!LATEST & PARENT)"; - std::cerr << std::endl; - - return false; - } - - if ((!onlyLatestMsgs) && onlyThreadMsgs) - { - std::cerr << "GxsDataProxyVEG::getMsgRelatedList() ERROR Incompatible FLAGS (!LATEST & THREAD)"; - std::cerr << std::endl; - - return false; - } - - if (onlyChildMsgs && onlyThreadMsgs) - { - std::cerr << "GxsDataProxyVEG::getMsgRelatedList() ERROR Incompatible FLAGS (PARENT & THREAD)"; - std::cerr << std::endl; - - return false; - } - - - /* FALL BACK OPTION */ - if ((!onlyLatestMsgs) && (!onlyAllVersions) && (!onlyChildMsgs) && (!onlyThreadMsgs)) - { - std::cerr << "GxsDataProxyVEG::getMsgRelatedList() FALLBACK -> NO FLAGS -> JUST COPY"; - std::cerr << std::endl; - /* just copy */ - outMsgIds = msgIds; - filterMsgList(opts, outMsgIds); - - return true; - } - - std::list::const_iterator it; - std::map::iterator mit; - - for(it = msgIds.begin(); it != msgIds.end(); it++) - { - RsStackMutex stack(mDataMtx); /***** LOCKED *****/ - - /* getOriginal Message */ - mit = mMsgMetaData.find(*it); - if (mit == mMsgMetaData.end()) - { - continue; - } - - std::string origMsgId = mit->second.mOrigMsgId; - - if (onlyLatestMsgs) - { - if (onlyChildMsgs || onlyThreadMsgs) - { - // RUN THROUGH ALL MSGS... in map origId -> TS. - std::map > origMsgTs; - std::map >::iterator oit; - for(mit = mMsgMetaData.begin(); mit != mMsgMetaData.end(); mit++) - { - // skip msgs that aren't children. - if (onlyChildMsgs) - { - if (mit->second.mParentId != origMsgId) - { - continue; - } - } - else /* onlyThreadMsgs */ - { - if (mit->second.mThreadId != (*it)) - { - continue; - } - } - - - oit = origMsgTs.find(mit->second.mOrigMsgId); - bool addMsg = false; - if (oit == origMsgTs.end()) - { - std::cerr << "GxsDataProxyVEG::getMsgRelatedList() Found New OrigMsgId: "; - std::cerr << mit->second.mOrigMsgId; - std::cerr << " MsgId: " << mit->second.mMsgId; - std::cerr << " TS: " << mit->second.mPublishTs; - std::cerr << std::endl; - - addMsg = true; - } - // check timestamps. - else if (oit->second.second < mit->second.mPublishTs) - { - std::cerr << "GxsDataProxyVEG::getMsgRelatedList() Found Later Msg. OrigMsgId: "; - std::cerr << mit->second.mOrigMsgId; - std::cerr << " MsgId: " << mit->second.mMsgId; - std::cerr << " TS: " << mit->second.mPublishTs; - - addMsg = true; - } - - if (addMsg) - { - // add as latest. (overwriting if necessary) - origMsgTs[mit->second.mOrigMsgId] = std::make_pair(mit->second.mMsgId, mit->second.mPublishTs); - } - } - - // Add the discovered Latest Msgs. - for(oit = origMsgTs.begin(); oit != origMsgTs.end(); oit++) - { - outMsgIds.push_back(oit->second.first); - } - } - else - { - - /* first guess is potentially better than Orig (can't be worse!) */ - time_t latestTs = mit->second.mPublishTs; - std::string latestMsgId = mit->second.mMsgId; - - for(mit = mMsgMetaData.begin(); mit != mMsgMetaData.end(); mit++) - { - if (mit->second.mOrigMsgId == origMsgId) - { - if (mit->second.mPublishTs > latestTs) - { - latestTs = mit->second.mPublishTs; - latestMsgId = mit->first; - } - } - } - outMsgIds.push_back(latestMsgId); - } - } - else if (onlyAllVersions) - { - for(mit = mMsgMetaData.begin(); mit != mMsgMetaData.end(); mit++) - { - if (mit->second.mOrigMsgId == origMsgId) - { - outMsgIds.push_back(mit->first); - } - } - } - } - - filterMsgList(opts, outMsgIds); - - return true; -} - - -bool GxsDataProxyVEG::createGroup(void *groupData) -{ - RsGroupMetaData meta; - if (convertGroupToMetaData(groupData, meta)) - { - if (!isUniqueGroup(meta.mGroupId)) - { - std::cerr << "GxsDataProxyVEG::createGroup() ERROR GroupId Clashes, discarding"; - std::cerr << std::endl; - return false; - } - - RsStackMutex stack(mDataMtx); /***** LOCKED *****/ - - - /* Set the Group Status Flags */ - meta.mGroupStatus |= (RSGXS_GROUP_STATUS_UPDATED | RSGXS_GROUP_STATUS_NEWGROUP); - - - /* push into maps */ - mGroupData[meta.mGroupId] = groupData; - mGroupMetaData[meta.mGroupId] = meta; - - return true; - } - - std::cerr << "GxsDataProxyVEG::createGroup() ERROR Failed to convert Data"; - std::cerr << std::endl; - return false; -} - - -bool GxsDataProxyVEG::createMsg(void *msgData) -{ - RsMsgMetaData meta; - if (convertMsgToMetaData(msgData, meta)) - { - if (!isUniqueMsg(meta.mMsgId)) - { - std::cerr << "GxsDataProxyVEG::createMsg() ERROR MsgId Clashes, discarding"; - std::cerr << std::endl; - return false; - } - - RsStackMutex stack(mDataMtx); /***** LOCKED *****/ - - - /* find the group */ - std::map::iterator git; - git = mGroupMetaData.find(meta.mGroupId); - if (git == mGroupMetaData.end()) - { - std::cerr << "GxsDataProxyVEG::createMsg() ERROR GroupId Doesn't exist, discarding"; - std::cerr << std::endl; - return false; - } - - /* flag the group as changed */ - git->second.mGroupStatus |= (RSGXS_GROUP_STATUS_UPDATED | RSGXS_GROUP_STATUS_NEWMSG); - - /* Set the Msg Status Flags */ - meta.mMsgStatus |= (RSGXS_MSG_STATUS_UNREAD_BY_USER | RSGXS_MSG_STATUS_UNPROCESSED); - - /* Set the Msg->GroupId Status Flags */ - - /* push into maps */ - mMsgData[meta.mMsgId] = msgData; - mMsgMetaData[meta.mMsgId] = meta; - - return true; - } - - std::cerr << "GxsDataProxyVEG::createMsg() ERROR Failed to convert Data"; - std::cerr << std::endl; - return false; -} - - - // Get Message Status - is retrived via MessageSummary. -bool GxsDataProxyVEG::setMessageStatus(const std::string &msgId,const uint32_t status, const uint32_t statusMask) -{ - RsStackMutex stack(mDataMtx); /***** LOCKED *****/ - - std::map::iterator mit; - mit = mMsgMetaData.find(msgId); - - if (mit == mMsgMetaData.end()) - { - // error. - std::cerr << "GxsDataProxyVEG::getMsgSummary() Error Finding MsgId: " << msgId; - std::cerr << std::endl; - } - else - { - /* tweak status */ - mit->second.mMsgStatus &= ~statusMask; - mit->second.mMsgStatus |= (status & statusMask); - } - - // always return true - as this is supposed to be async operation. - return true; -} - -bool GxsDataProxyVEG::setGroupStatus(const std::string &groupId, const uint32_t status, const uint32_t statusMask) -{ - RsStackMutex stack(mDataMtx); /***** LOCKED *****/ - - std::map::iterator git; - git = mGroupMetaData.find(groupId); - - if (git == mGroupMetaData.end()) - { - // error. - std::cerr << "GxsDataProxyVEG::setGroupStatus() Error Finding GroupId: " << groupId; - std::cerr << std::endl; - } - else - { - /* tweak status */ - git->second.mGroupStatus &= ~statusMask; - git->second.mGroupStatus |= (status & statusMask); - } - - // always return true - as this is supposed to be async operation. - return true; -} - - -bool GxsDataProxyVEG::setGroupSubscribeFlags(const std::string &groupId, uint32_t subscribeFlags, uint32_t subscribeMask) -{ - RsStackMutex stack(mDataMtx); /***** LOCKED *****/ - - std::map::iterator git; - git = mGroupMetaData.find(groupId); - - if (git == mGroupMetaData.end()) - { - // error. - std::cerr << "GxsDataProxyVEG::setGroupSubscribeFlags() Error Finding GroupId: " << groupId; - std::cerr << std::endl; - } - else - { - /* tweak subscribe Flags */ - git->second.mSubscribeFlags &= ~subscribeMask; - git->second.mSubscribeFlags |= (subscribeFlags & subscribeMask); - } - - // always return true - as this is supposed to be async operation. - return true; -} - -bool GxsDataProxyVEG::setMessageServiceString(const std::string &msgId, const std::string &str) -{ - RsStackMutex stack(mDataMtx); /***** LOCKED *****/ - - std::map::iterator mit; - mit = mMsgMetaData.find(msgId); - - if (mit == mMsgMetaData.end()) - { - // error. - std::cerr << "GxsDataProxyVEG::setMessageServiceString() Error Finding MsgId: " << msgId; - std::cerr << std::endl; - } - else - { - mit->second.mServiceString = str; - } - - // always return true - as this is supposed to be async operation. - return true; -} - -bool GxsDataProxyVEG::setGroupServiceString(const std::string &groupId, const std::string &str) -{ - RsStackMutex stack(mDataMtx); /***** LOCKED *****/ - - std::map::iterator git; - git = mGroupMetaData.find(groupId); - - if (git == mGroupMetaData.end()) - { - // error. - std::cerr << "GxsDataProxyVEG::setGroupServiceString() Error Finding GroupId: " << groupId; - std::cerr << std::endl; - } - else - { - git->second.mServiceString = str; - } - - // always return true - as this is supposed to be async operation. - return true; -} - - - /* These Functions must be overloaded to complete the service */ -bool GxsDataProxyVEG::convertGroupToMetaData(void *groupData, RsGroupMetaData &meta) -{ - std::cerr << "GxsDataProxyVEG::convert fn ... please implement!"; - std::cerr << std::endl; - return false; -} - -bool GxsDataProxyVEG::convertMsgToMetaData(void *groupData, RsMsgMetaData &meta) -{ - std::cerr << "GxsDataProxyVEG::convert fn ... please implement!"; - std::cerr << std::endl; - return false; -} - - /* extract Data */ -bool GxsDataProxyVEG::getGroupSummary(const std::string &groupId, RsGroupMetaData &groupSummary) -{ - RsStackMutex stack(mDataMtx); /***** LOCKED *****/ - - std::map::iterator mit; - mit = mGroupMetaData.find(groupId); - - if (mit == mGroupMetaData.end()) - { - // error. - std::cerr << "GxsDataProxyVEG::getGroupMetaData() Error Finding GroupId: " << groupId; - std::cerr << std::endl; - return false; - } - else - { - groupSummary = mit->second; - } - return true; -} - - -bool GxsDataProxyVEG::getMsgSummary(const std::string &msgId, RsMsgMetaData &msgSummary) -{ - RsStackMutex stack(mDataMtx); /***** LOCKED *****/ - - std::map::iterator mit; - mit = mMsgMetaData.find(msgId); - - if (mit == mMsgMetaData.end()) - { - // error. - std::cerr << "GxsDataProxyVEG::getMsgSummary() Error Finding MsgId: " << msgId; - std::cerr << std::endl; - } - else - { - msgSummary = (mit->second); - } - return true; -} - - - /* extract Data */ -bool GxsDataProxyVEG::getGroupSummary(const std::list &groupIds, std::list &groupSummary) -{ - std::list::const_iterator it; - for(it = groupIds.begin(); it != groupIds.end(); it++) - { - RsStackMutex stack(mDataMtx); /***** LOCKED *****/ - - std::map::iterator mit; - mit = mGroupMetaData.find(*it); - - if (mit == mGroupMetaData.end()) - { - // error. - std::cerr << "GxsDataProxyVEG::getGroupMetaData() Error Finding GroupId: " << *it; - std::cerr << std::endl; - } - else - { - groupSummary.push_back(mit->second); - } - } - return true; -} - - -bool GxsDataProxyVEG::getMsgSummary(const std::list &msgIds, std::list &msgSummary) -{ - std::list::const_iterator it; - for(it = msgIds.begin(); it != msgIds.end(); it++) - { - RsStackMutex stack(mDataMtx); /***** LOCKED *****/ - - std::map::iterator mit; - mit = mMsgMetaData.find(*it); - - if (mit == mMsgMetaData.end()) - { - // error. - std::cerr << "GxsDataProxyVEG::getMsgSummary() Error Finding MsgId: " << *it; - std::cerr << std::endl; - } - else - { - msgSummary.push_back(mit->second); - } - } - return true; -} - - -bool GxsDataProxyVEG::getGroupData(const std::string &groupId, void * &groupData) -{ - RsStackMutex stack(mDataMtx); /***** LOCKED *****/ - - std::map::iterator mit; - mit = mGroupData.find(groupId); - - if (mit == mGroupData.end()) - { - // error. - std::cerr << "GxsDataProxyVEG::getGroupData() Error Finding GroupId: " << groupId; - std::cerr << std::endl; - return false; - } - else - { - groupData = mit->second; - } - return true; -} - -bool GxsDataProxyVEG::getMsgData(const std::string &msgId, void * &msgData) -{ - RsStackMutex stack(mDataMtx); /***** LOCKED *****/ - - std::map::iterator mit; - mit = mMsgData.find(msgId); - - if (mit == mMsgData.end()) - { - // error. - std::cerr << "GxsDataProxyVEG::getMsgData() Error Finding MsgId: " << msgId; - std::cerr << std::endl; - return false; - } - else - { - msgData = mit->second; - } - return true; -} - -#if 0 -bool GxsDataProxyVEG::getGroupData(const std::list &groupIds, std::list &groupData) -{ - std::list::const_iterator it; - for(it = groupIds.begin(); it != groupIds.end(); it++) - { - RsStackMutex stack(mDataMtx); /***** LOCKED *****/ - - std::map::iterator mit; - mit = mGroupData.find(*it); - - if (mit == mGroupData.end()) - { - // error. - std::cerr << "GxsDataProxyVEG::getGroupData() Error Finding GroupId: " << *it; - std::cerr << std::endl; - } - else - { - groupData.push_back(mit->second); - } - } - return true; -} - -bool GxsDataProxyVEG::getMsgData(const std::list &msgIds, std::list &msgData) -{ - std::list::const_iterator it; - for(it = msgIds.begin(); it != msgIds.end(); it++) - { - RsStackMutex stack(mDataMtx); /***** LOCKED *****/ - - std::map::iterator mit; - mit = mMsgData.find(*it); - - if (mit == mMsgData.end()) - { - // error. - std::cerr << "GxsDataProxyVEG::getMsgData() Error Finding MsgId: " << *it; - std::cerr << std::endl; - } - else - { - msgData.push_back(mit->second); - } - } - return true; -} -#endif - -bool GxsDataProxyVEG::isUniqueMsg(const std::string &msgId) -{ - RsStackMutex stack(mDataMtx); /***** LOCKED *****/ - - std::map::iterator mit; - mit = mMsgData.find(msgId); - - return (mit == mMsgData.end()); -} - - -bool GxsDataProxyVEG::isUniqueGroup(const std::string &groupId) -{ - RsStackMutex stack(mDataMtx); /***** LOCKED *****/ - - std::map::iterator mit; - mit = mGroupData.find(groupId); - - return (mit == mGroupData.end()); -} - - - -/*********************************************************************************************************/ -/*********************************************************************************************************/ -/*********************************************************************************************************/ -/*********************************************************************************************************/ -/*********************************************************************************************************/ - - -p3GxsDataServiceVEG::p3GxsDataServiceVEG(uint16_t type, GxsDataProxyVEG *proxy) - :p3GxsServiceVEG(type), mProxy(proxy) -{ - return; -} - - - - - -bool p3GxsDataServiceVEG::fakeprocessrequests() -{ - std::list toClear; - std::list::iterator cit; - time_t now = time(NULL); - - { RsStackMutex stack(mReqMtx); /******* LOCKED *******/ - - std::map::iterator it; - - for(it = mRequests.begin(); it != mRequests.end(); it++) - { - //std::cerr << "p3GxsDataServiceVEG::fakeprocessrequests() Token: " << it->second.token << " Status: " << it->second.status << " ReqType: " << it->second.reqType << " Age: " << now - it->second.reqTime << std::endl; - - if (it->second.status == GXS_REQUEST_STATUS_PENDING) - { - std::cerr << "p3GxsDataServiceVEG::fakeprocessrequests() Processing Token: " << it->second.token << " Status: " << it->second.status << " ReqType: " << it->second.reqType << " Age: " << now - it->second.reqTime << std::endl; - it->second.status = GXS_REQUEST_STATUS_PARTIAL; - /* PROCESS REQUEST! */ - switch(it->second.reqType) - { - case GXS_REQUEST_TYPE_GROUPS: - mProxy->getGroupList(it->second.token, it->second.Options, it->second.inList, it->second.outList); - break; - case GXS_REQUEST_TYPE_MSGS: - mProxy->getMsgList(it->second.token, it->second.Options, it->second.inList, it->second.outList); - break; - case GXS_REQUEST_TYPE_MSGRELATED: - mProxy->getMsgRelatedList(it->second.token, it->second.Options, it->second.inList, it->second.outList); - break; - default: - it->second.status = GXS_REQUEST_STATUS_FAILED; - break; - } - } - else if (it->second.status == GXS_REQUEST_STATUS_PARTIAL) - { - it->second.status = GXS_REQUEST_STATUS_COMPLETE; - } - else if (it->second.status == GXS_REQUEST_STATUS_DONE) - { - std::cerr << "p3GxsDataServiceVEG::fakeprocessrequests() Clearing Done Request Token: " << it->second.token; - std::cerr << std::endl; - toClear.push_back(it->second.token); - } - else if (now - it->second.reqTime > MAX_REQUEST_AGE) - { - std::cerr << "p3GxsDataServiceVEG::fakeprocessrequests() Clearing Old Request Token: " << it->second.token; - std::cerr << std::endl; - toClear.push_back(it->second.token); - } - } - - } // END OF MUTEX. - - for(cit = toClear.begin(); cit != toClear.end(); cit++) - { - clearRequest(*cit); - } - - return true; -} - -#if 0 // DISABLED AND MOVED TO GXS CODE. - -//std::ostream &operator<<(std::ostream &out, const RsGroupMetaData &meta) -//{ -// out << "[ GroupId: " << meta.mGroupId << " Name: " << meta.mGroupName << " ]"; -// return out; -//} - -//std::ostream &operator<<(std::ostream &out, const RsMsgMetaData &meta) -//{ -// out << "[ GroupId: " << meta.mGroupId << " MsgId: " << meta.mMsgId; -// out << " Name: " << meta.mMsgName; -// out << " OrigMsgId: " << meta.mOrigMsgId; -// out << " ThreadId: " << meta.mThreadId; -// out << " ParentId: " << meta.mParentId; -// out << " AuthorId: " << meta.mAuthorId; -// out << " Name: " << meta.mMsgName << " ]"; -// return out; -//} - -#endif - diff --git a/libretroshare/src/services/p3gxsserviceVEG.h b/libretroshare/src/services/p3gxsserviceVEG.h deleted file mode 100644 index 096ebdfb0..000000000 --- a/libretroshare/src/services/p3gxsserviceVEG.h +++ /dev/null @@ -1,191 +0,0 @@ -/* - * libretroshare/src/services p3gxsservice.h - * - * Generic Service Support Class for RetroShare. - * - * Copyright 2012 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_GXS_SERVICE_HEADER -#define P3_GXS_SERVICE_HEADER - -#include "services/p3service.h" -#include "retroshare/rsidentityVEG.h" - -/* - * This class provides useful generic support for GXS style services. - * I expect much of this will be incorporated into the base GXS. - * - */ - -#define GXS_REQUEST_STATUS_FAILED 0 -#define GXS_REQUEST_STATUS_PENDING 1 -#define GXS_REQUEST_STATUS_PARTIAL 2 -#define GXS_REQUEST_STATUS_FINISHED_INCOMPLETE 3 -#define GXS_REQUEST_STATUS_COMPLETE 4 -#define GXS_REQUEST_STATUS_DONE 5 // ONCE ALL DATA RETRIEVED. - -#define GXS_REQUEST_TYPE_GROUPS 0x00010000 -#define GXS_REQUEST_TYPE_MSGS 0x00020000 -#define GXS_REQUEST_TYPE_MSGRELATED 0x00040000 - -class gxsRequest -{ - public: - uint32_t token; - uint32_t reqTime; - - uint32_t ansType; - uint32_t reqType; - RsTokReqOptionsVEG Options; - - uint32_t status; - - std::list inList; - std::list outList; - //std::map readyData; -}; - - -class p3GxsServiceVEG: public p3Service -{ - protected: - - p3GxsServiceVEG(uint16_t type); - - public: - -//virtual ~p3Service() { p3Service::~p3Service(); return; } - -bool generateToken(uint32_t &token); -bool storeRequest(const uint32_t &token, const uint32_t &ansType, const RsTokReqOptionsVEG &opts, const uint32_t &type, const std::list &ids); -bool clearRequest(const uint32_t &token); - -bool updateRequestStatus(const uint32_t &token, const uint32_t &status); -bool updateRequestInList(const uint32_t &token, std::list ids); -bool updateRequestOutList(const uint32_t &token, std::list ids); -//bool updateRequestData(const uint32_t &token, std::map data); -bool checkRequestStatus(const uint32_t &token, uint32_t &status, uint32_t &reqtype, uint32_t &anstype, time_t &ts); - - // special ones for testing (not in final design) -bool tokenList(std::list &tokens); -bool popRequestInList(const uint32_t &token, std::string &id); -bool popRequestOutList(const uint32_t &token, std::string &id); -bool loadRequestOutList(const uint32_t &token, std::list &ids); - -virtual bool fakeprocessrequests(); - - protected: - - RsMutex mReqMtx; - - uint32_t mNextToken; - - std::map mRequests; - -}; - - -class GxsDataProxyVEG -{ - public: - - GxsDataProxyVEG(); - -virtual bool getGroupList( uint32_t &token, const RsTokReqOptionsVEG &opts, const std::list &groupIds, std::list &outGroupIds); -virtual bool getMsgList( uint32_t &token, const RsTokReqOptionsVEG &opts, const std::list &groupIds, std::list &outMsgIds); -virtual bool getMsgRelatedList(uint32_t &token, const RsTokReqOptionsVEG &opts, const std::list &msgIds, std::list &outMsgIds); - - - /* This functions return a token - which can be used to retrieve the RsGroupMetaData, later - * This is required, as signatures and keys might have to be generated in the background - * Though at the moment: for this test system it won't change anything? FIXME. - */ -virtual bool createGroup(void *groupData); -virtual bool createMsg(void *msgData); - - /* These Functions must be overloaded to complete the service */ -virtual bool convertGroupToMetaData(void *groupData, RsGroupMetaData &meta); -virtual bool convertMsgToMetaData(void *groupData, RsMsgMetaData &meta); - - /* extract Data */ - bool getGroupSummary(const std::list &groupIds, std::list &groupSummary); - bool getMsgSummary(const std::list &msgIds, std::list &msgSummary); - - bool getGroupSummary(const std::string &groupId, RsGroupMetaData &groupSummary); - bool getMsgSummary(const std::string &msgId, RsMsgMetaData &msgSummary); - - //bool getGroupData(const std::list &groupIds, std::list &groupData); - //bool getMsgData(const std::list &msgIds, std::list &msgData); - bool getGroupData(const std::string &groupId, void * &groupData); - bool getMsgData(const std::string &msgId, void * &msgData); - - bool isUniqueGroup(const std::string &groupId); - bool isUniqueMsg(const std::string &msgId); - - - /* Handle Status & Subscribe Modes */ -// This is removed as redundant - use getGroupList - with OptFlags to find these. -//virtual bool requestGroupsChanged(uint32_t &token); //std::list &groupIds); - - // Get Message Status - is retrived via MessageSummary. - // These operations could have a token, but for the moment we are going to assume - // they are async and always succeed - (or fail silently). -virtual bool setMessageStatus(const std::string &msgId, const uint32_t status, const uint32_t statusMask); -virtual bool setGroupStatus(const std::string &groupId, const uint32_t status, const uint32_t statusMask); -virtual bool setGroupSubscribeFlags(const std::string &groupId, uint32_t subscribeFlags, uint32_t subscribeMask); - -virtual bool setMessageServiceString(const std::string &msgId, const std::string &str); -virtual bool setGroupServiceString(const std::string &grpId, const std::string &str); - - protected: - - bool filterGroupList(const RsTokReqOptionsVEG &opts, std::list &groupIds); - bool filterMsgList(const RsTokReqOptionsVEG &opts, std::list &msgIds); - - - RsMutex mDataMtx; - - std::map mGroupData; - std::map mMsgData; - - std::map mGroupMetaData; - std::map mMsgMetaData; - -}; - - -class p3GxsDataServiceVEG: public p3GxsServiceVEG -{ - public: - - p3GxsDataServiceVEG(uint16_t type, GxsDataProxyVEG *proxy); -virtual bool fakeprocessrequests(); - - - protected: - - GxsDataProxyVEG *mProxy; -}; - - - -#endif // P3_GXS_SERVICE_HEADER - diff --git a/libretroshare/src/services/p3idservice.cc b/libretroshare/src/services/p3idservice.cc index 9524cb48b..5bb445bfd 100644 --- a/libretroshare/src/services/p3idservice.cc +++ b/libretroshare/src/services/p3idservice.cc @@ -139,9 +139,10 @@ RsIdentity *rsIdentity = NULL; p3IdService::p3IdService(RsGeneralDataService *gds, RsNetworkExchangeService *nes) : RsGxsIdExchange(gds, nes, new RsGxsIdSerialiser(), RS_SERVICE_GXSV2_TYPE_GXSID, idAuthenPolicy()), - RsIdentity(this), GxsTokenQueue(this), RsTickEvent(), mIdMtx("p3IdService"), + RsIdentity(this), GxsTokenQueue(this), RsTickEvent(), mPublicKeyCache(DEFAULT_MEM_CACHE_SIZE, "GxsIdPublicKeyCache"), - mPrivateKeyCache(DEFAULT_MEM_CACHE_SIZE, "GxsIdPrivateKeyCache"), mNes(nes) + mPrivateKeyCache(DEFAULT_MEM_CACHE_SIZE, "GxsIdPrivateKeyCache"), + mIdMtx("p3IdService"), mNes(nes) { mBgSchedule_Mode = 0; mBgSchedule_Active = false; @@ -2884,7 +2885,7 @@ void p3IdService::generateDummy_FriendPGP() int idx = RSRandom::random_f32() * (gpgids.size() - 1); it = gpgids.begin(); - for(int j = 0; j < idx; j++, it++); + for(int j = 0; j < idx; j++, it++) ; // HACK FOR DUMMY GENERATION. id.mMeta.mAuthorId = *it; diff --git a/libretroshare/src/services/p3idservice.h b/libretroshare/src/services/p3idservice.h index 48f8ebf9b..ff5dae197 100644 --- a/libretroshare/src/services/p3idservice.h +++ b/libretroshare/src/services/p3idservice.h @@ -91,9 +91,9 @@ virtual std::string save() const; bool tagsPending() const; // should we reprocess? bool tagValid(int i) const; + uint32_t tagFlags; time_t publishTs; time_t lastCheckTs; - uint32_t tagFlags; }; diff --git a/libretroshare/src/services/p3postbase.cc b/libretroshare/src/services/p3postbase.cc new file mode 100644 index 000000000..f277f15da --- /dev/null +++ b/libretroshare/src/services/p3postbase.cc @@ -0,0 +1,723 @@ +/* + * libretroshare/src/services p3posted.cc + * + * Posted interface for RetroShare. + * + * Copyright 2012-2012 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.1 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 "retroshare/rsgxsflags.h" +#include +#include + +#include "services/p3postbase.h" +#include "serialiser/rsgxscommentitems.h" + +// For Dummy Msgs. +#include "util/rsrandom.h" +#include "util/rsstring.h" + +/**** + * #define POSTBASE_DEBUG 1 + ****/ + +#define POSTBASE_BACKGROUND_PROCESSING 0x0002 +#define PROCESSING_START_PERIOD 30 +#define PROCESSING_INC_PERIOD 15 + +#define POSTBASE_ALL_GROUPS 0x0011 +#define POSTBASE_UNPROCESSED_MSGS 0x0012 +#define POSTBASE_ALL_MSGS 0x0013 +#define POSTBASE_BG_POST_META 0x0014 +/********************************************************************************/ +/******************* Startup / Tick ******************************************/ +/********************************************************************************/ + +p3PostBase::p3PostBase(RsGeneralDataService *gds, RsNetworkExchangeService *nes, RsGixs* gixs, + RsSerialType* serviceSerialiser, uint16_t serviceType) + : RsGenExchange(gds, nes, serviceSerialiser, serviceType, gixs, postBaseAuthenPolicy()), GxsTokenQueue(this), RsTickEvent(), mPostBaseMtx("PostBaseMtx") +{ + mBgProcessing = false; + + mCommentService = new p3GxsCommentService(this, serviceType); + RsTickEvent::schedule_in(POSTBASE_BACKGROUND_PROCESSING, PROCESSING_START_PERIOD); +} + + +uint32_t p3PostBase::postBaseAuthenPolicy() +{ + uint32_t policy = 0; + uint32_t flag = 0; + + flag = GXS_SERV::MSG_AUTHEN_ROOT_AUTHOR_SIGN | GXS_SERV::MSG_AUTHEN_CHILD_AUTHOR_SIGN; + RsGenExchange::setAuthenPolicyFlag(flag, policy, RsGenExchange::PUBLIC_GRP_BITS); + + flag |= GXS_SERV::MSG_AUTHEN_ROOT_PUBLISH_SIGN | GXS_SERV::MSG_AUTHEN_CHILD_PUBLISH_SIGN; + RsGenExchange::setAuthenPolicyFlag(flag, policy, RsGenExchange::RESTRICTED_GRP_BITS); + RsGenExchange::setAuthenPolicyFlag(flag, policy, RsGenExchange::PRIVATE_GRP_BITS); + + flag = 0; + RsGenExchange::setAuthenPolicyFlag(flag, policy, RsGenExchange::GRP_OPTION_BITS); + + return policy; +} + +void p3PostBase::notifyChanges(std::vector &changes) +{ + std::cerr << "p3PostBase::notifyChanges()"; + std::cerr << std::endl; + + std::vector changesForGUI; + std::vector::iterator it; + + for(it = changes.begin(); it != changes.end(); it++) + { + RsGxsGroupChange *groupChange = dynamic_cast(*it); + RsGxsMsgChange *msgChange = dynamic_cast(*it); + if (msgChange) + { + std::cerr << "p3PostBase::notifyChanges() Found Message Change Notification"; + std::cerr << std::endl; + + std::map > &msgChangeMap = msgChange->msgChangeMap; + std::map >::iterator mit; + for(mit = msgChangeMap.begin(); mit != msgChangeMap.end(); mit++) + { + std::cerr << "p3PostBase::notifyChanges() Msgs for Group: " << mit->first; + std::cerr << std::endl; + // To start with we are just going to trigger updates on these groups. + // FUTURE OPTIMISATION. + // It could be taken a step further and directly request these msgs for an update. + addGroupForProcessing(mit->first); + } + delete msgChange; + } + + /* pass on Group Changes to GUI */ + if (groupChange) + { + std::cerr << "p3PostBase::notifyChanges() Found Group Change Notification"; + std::cerr << std::endl; + + std::list &groupList = groupChange->mGrpIdList; + std::list::iterator git; + for(git = groupList.begin(); git != groupList.end(); git++) + { + std::cerr << "p3PostBase::notifyChanges() Incoming Group: " << *git; + std::cerr << std::endl; + } + changesForGUI.push_back(groupChange); + } + } + changes.clear(); + receiveHelperChanges(changesForGUI); + + std::cerr << "p3PostBase::notifyChanges() -> receiveChanges()"; + std::cerr << std::endl; +} + +void p3PostBase::service_tick() +{ + RsTickEvent::tick_events(); + GxsTokenQueue::checkRequests(); + + mCommentService->comment_tick(); + + return; +} + +/********************************************************************************************/ +/********************************************************************************************/ + +void p3PostBase::setMessageReadStatus(uint32_t& token, const RsGxsGrpMsgIdPair& msgId, bool read) +{ + uint32_t mask = GXS_SERV::GXS_MSG_STATUS_UNREAD | GXS_SERV::GXS_MSG_STATUS_UNPROCESSED; + uint32_t status = GXS_SERV::GXS_MSG_STATUS_UNREAD; + if (read) + { + status = 0; + } + + setMsgStatusFlags(token, msgId, status, mask); + +} + + + // Overloaded from RsTickEvent for Event callbacks. +void p3PostBase::handle_event(uint32_t event_type, const std::string & /* elabel */) +{ + std::cerr << "p3PostBase::handle_event(" << event_type << ")"; + std::cerr << std::endl; + + // stuff. + switch(event_type) + { + case POSTBASE_BACKGROUND_PROCESSING: + background_tick(); + break; + + default: + /* error */ + std::cerr << "p3PostBase::handle_event() Unknown Event Type: " << event_type; + std::cerr << std::endl; + break; + } +} + + +/********************************************************************************* + * Background Calculations. + * + * Get list of change groups from Notify.... + * this doesn't imclude your own submissions (at this point). + * So they will not be processed until someone else changes something. + * TODO FIX: Must push for that change. + * + * Eventually, we should just be able to get the new messages from Notify, + * and only process them! + */ + +void p3PostBase::background_tick() +{ + +#if 0 + { + RsStackMutex stack(mPostBaseMtx); /********** STACK LOCKED MTX ******/ + if (mBgGroupList.empty()) + { + background_requestAllGroups(); + } + } +#endif + + background_requestUnprocessedGroup(); + + RsTickEvent::schedule_in(POSTBASE_BACKGROUND_PROCESSING, PROCESSING_INC_PERIOD); + +} + +bool p3PostBase::background_requestAllGroups() +{ + std::cerr << "p3PostBase::background_requestAllGroups()"; + std::cerr << std::endl; + + uint32_t ansType = RS_TOKREQ_ANSTYPE_LIST; + RsTokReqOptions opts; + opts.mReqType = GXS_REQUEST_TYPE_GROUP_IDS; + + uint32_t token = 0; + RsGenExchange::getTokenService()->requestGroupInfo(token, ansType, opts); + GxsTokenQueue::queueRequest(token, POSTBASE_ALL_GROUPS); + + return true; +} + + +void p3PostBase::background_loadGroups(const uint32_t &token) +{ + /* get messages */ + std::cerr << "p3PostBase::background_loadGroups()"; + std::cerr << std::endl; + + std::list groupList; + bool ok = RsGenExchange::getGroupList(token, groupList); + + if (!ok) + { + return; + } + + std::list::iterator it; + for(it = groupList.begin(); it != groupList.end(); it++) + { + addGroupForProcessing(*it); + } +} + + +void p3PostBase::addGroupForProcessing(RsGxsGroupId grpId) +{ +#ifdef POSTBASE_DEBUG + std::cerr << "p3PostBase::addGroupForProcessing(" << grpId << ")"; + std::cerr << std::endl; +#endif // POSTBASE_DEBUG + + { + RsStackMutex stack(mPostBaseMtx); /********** STACK LOCKED MTX ******/ + // no point having multiple lookups queued. + if (mBgGroupList.end() == std::find(mBgGroupList.begin(), + mBgGroupList.end(), grpId)) + { + mBgGroupList.push_back(grpId); + } + } +} + + +void p3PostBase::background_requestUnprocessedGroup() +{ +#ifdef POSTBASE_DEBUG + std::cerr << "p3PostBase::background_requestUnprocessedGroup()"; + std::cerr << std::endl; +#endif // POSTBASE_DEBUG + + + RsGxsGroupId grpId; + { + RsStackMutex stack(mPostBaseMtx); /********** STACK LOCKED MTX ******/ + if (mBgProcessing) + { + std::cerr << "p3PostBase::background_requestUnprocessedGroup() Already Active"; + std::cerr << std::endl; + return; + } + if (mBgGroupList.empty()) + { + std::cerr << "p3PostBase::background_requestUnprocessedGroup() No Groups to Process"; + std::cerr << std::endl; + return; + } + + grpId = mBgGroupList.front(); + mBgGroupList.pop_front(); + mBgProcessing = true; + } + + background_requestGroupMsgs(grpId, true); +} + + + + + +void p3PostBase::background_requestGroupMsgs(const RsGxsGroupId &grpId, bool unprocessedOnly) +{ + std::cerr << "p3PostBase::background_requestGroupMsgs() id: " << grpId; + std::cerr << std::endl; + + uint32_t ansType = RS_TOKREQ_ANSTYPE_DATA; + RsTokReqOptions opts; + opts.mReqType = GXS_REQUEST_TYPE_MSG_DATA; + + if (unprocessedOnly) + { + opts.mStatusFilter = GXS_SERV::GXS_MSG_STATUS_UNPROCESSED; + opts.mStatusMask = GXS_SERV::GXS_MSG_STATUS_UNPROCESSED; + } + + std::list grouplist; + grouplist.push_back(grpId); + + uint32_t token = 0; + + RsGenExchange::getTokenService()->requestMsgInfo(token, ansType, opts, grouplist); + + if (unprocessedOnly) + { + GxsTokenQueue::queueRequest(token, POSTBASE_UNPROCESSED_MSGS); + } + else + { + GxsTokenQueue::queueRequest(token, POSTBASE_ALL_MSGS); + } +} + + + + +void p3PostBase::background_loadUnprocessedMsgs(const uint32_t &token) +{ + background_loadMsgs(token, true); +} + + +void p3PostBase::background_loadAllMsgs(const uint32_t &token) +{ + background_loadMsgs(token, false); +} + + +/* This function is generalised to support any collection of messages, across multiple groups */ + +void p3PostBase::background_loadMsgs(const uint32_t &token, bool unprocessed) +{ + /* get messages */ + std::cerr << "p3PostBase::background_loadMsgs()"; + std::cerr << std::endl; + + std::map > msgData; + bool ok = RsGenExchange::getMsgData(token, msgData); + + if (!ok) + { + std::cerr << "p3PostBase::background_loadMsgs() Failed to getMsgData()"; + std::cerr << std::endl; + + /* cleanup */ + background_cleanup(); + return; + + } + + { + RsStackMutex stack(mPostBaseMtx); /********** STACK LOCKED MTX ******/ + mBgStatsMap.clear(); + mBgIncremental = unprocessed; + } + + std::map > postMap; + + // generate vector of changes to push to the GUI. + std::vector changes; + RsGxsMsgChange *msgChanges = new RsGxsMsgChange(RsGxsNotify::TYPE_PROCESSED); + + + RsGxsGroupId groupId; + std::map >::iterator mit; + std::vector::iterator vit; + for (mit = msgData.begin(); mit != msgData.end(); mit++) + { + groupId = mit->first; + for (vit = mit->second.begin(); vit != mit->second.end(); vit++) + { + RsGxsMessageId parentId = (*vit)->meta.mParentId; + RsGxsMessageId threadId = (*vit)->meta.mThreadId; + + + bool inc_counters = false; + uint32_t vote_up_inc = 0; + uint32_t vote_down_inc = 0; + uint32_t comment_inc = 0; + + bool add_voter = false; + RsGxsId voterId; + RsGxsCommentItem *commentItem; + RsGxsVoteItem *voteItem; + + /* THIS Should be handled by UNPROCESSED Filter - but isn't */ + if (!IS_MSG_UNPROCESSED((*vit)->meta.mMsgStatus)) + { + RsStackMutex stack(mPostBaseMtx); /********** STACK LOCKED MTX ******/ + if (mBgIncremental) + { + std::cerr << "p3PostBase::background_loadMsgs() Msg already Processed - Skipping"; + std::cerr << std::endl; + std::cerr << "p3PostBase::background_loadMsgs() ERROR This should not happen"; + std::cerr << std::endl; + delete(*vit); + continue; + } + } + + /* 3 types expected: PostedPost, Comment and Vote */ + if (parentId.empty()) + { + /* we don't care about top-level (Posts) */ + std::cerr << "\tIgnoring TopLevel Item"; + std::cerr << std::endl; + + /* but we need to notify GUI about them */ + msgChanges->msgChangeMap[mit->first].push_back((*vit)->meta.mMsgId); + } + else if (NULL != (commentItem = dynamic_cast(*vit))) + { + /* comment - want all */ + /* Comments are counted by Thread Id */ + std::cerr << "\tProcessing Comment: " << commentItem; + std::cerr << std::endl; + + inc_counters = true; + comment_inc = 1; + } + else if (NULL != (voteItem = dynamic_cast(*vit))) + { + /* vote - only care about direct children */ + if (parentId == threadId) + { + /* Votes are organised by Parent Id, + * ie. you can vote for both Posts and Comments + */ + std::cerr << "\tProcessing Vote: " << voteItem; + std::cerr << std::endl; + + inc_counters = true; + add_voter = true; + voterId = voteItem->meta.mAuthorId; + + if (voteItem->mMsg.mVoteType == GXS_VOTE_UP) + { + vote_up_inc = 1; + } + else + { + vote_down_inc = 1; + } + } + } + else + { + /* unknown! */ + std::cerr << "p3PostBase::background_processNewMessages() ERROR Strange NEW Message:"; + std::cerr << std::endl; + std::cerr << "\t" << (*vit)->meta; + std::cerr << std::endl; + + } + + if (inc_counters) + { + RsStackMutex stack(mPostBaseMtx); /********** STACK LOCKED MTX ******/ + + std::map::iterator sit = mBgStatsMap.find(threadId); + if (sit == mBgStatsMap.end()) + { + // add to map of ones to update. + postMap[groupId].push_back(threadId); + + mBgStatsMap[threadId] = PostStats(0,0,0); + sit = mBgStatsMap.find(threadId); + } + + sit->second.comments += comment_inc; + sit->second.up_votes += vote_up_inc; + sit->second.down_votes += vote_down_inc; + + + if (add_voter) + { + sit->second.voters.push_back(voterId); + } + + std::cerr << "\tThreadId: " << threadId; + std::cerr << " Comment Total: " << sit->second.comments; + std::cerr << " UpVote Total: " << sit->second.up_votes; + std::cerr << " DownVote Total: " << sit->second.down_votes; + std::cerr << std::endl; + } + + /* flag all messages as processed */ + if ((*vit)->meta.mMsgStatus & GXS_SERV::GXS_MSG_STATUS_UNPROCESSED) + { + uint32_t token_a; + RsGxsGrpMsgIdPair msgId = std::make_pair(groupId, (*vit)->meta.mMsgId); + RsGenExchange::setMsgStatusFlags(token_a, msgId, 0, GXS_SERV::GXS_MSG_STATUS_UNPROCESSED); + } + delete(*vit); + } + } + + /* push updates of new Posts */ + if (msgChanges->msgChangeMap.size() > 0) + { + std::cerr << "p3PostBase::background_processNewMessages() -> receiveChanges()"; + std::cerr << std::endl; + + changes.push_back(msgChanges); + receiveHelperChanges(changes); + } + + /* request the summary info from the parents */ + uint32_t token_b; + uint32_t anstype = RS_TOKREQ_ANSTYPE_SUMMARY; + RsTokReqOptions opts; + opts.mReqType = GXS_REQUEST_TYPE_MSG_META; + RsGenExchange::getTokenService()->requestMsgInfo(token_b, anstype, opts, postMap); + + GxsTokenQueue::queueRequest(token_b, POSTBASE_BG_POST_META); + return; +} + + +#define RSGXS_MAX_SERVICE_STRING 1024 +bool encodePostCache(std::string &str, const PostStats &s) +{ + char line[RSGXS_MAX_SERVICE_STRING]; + + snprintf(line, RSGXS_MAX_SERVICE_STRING, "%d %d %d", s.comments, s.up_votes, s.down_votes); + + str = line; + return true; +} + +bool extractPostCache(const std::string &str, PostStats &s) +{ + + uint32_t iupvotes, idownvotes, icomments; + if (3 == sscanf(str.c_str(), "%d %d %d", &icomments, &iupvotes, &idownvotes)) + { + s.comments = icomments; + s.up_votes = iupvotes; + s.down_votes = idownvotes; + return true; + } + return false; +} + + +void p3PostBase::background_updateVoteCounts(const uint32_t &token) +{ + std::cerr << "p3PostBase::background_updateVoteCounts()"; + std::cerr << std::endl; + + GxsMsgMetaMap parentMsgList; + GxsMsgMetaMap::iterator mit; + std::vector::iterator vit; + + bool ok = RsGenExchange::getMsgMeta(token, parentMsgList); + + if (!ok) + { + std::cerr << "p3PostBase::background_updateVoteCounts() ERROR"; + std::cerr << std::endl; + background_cleanup(); + return; + } + + // generate vector of changes to push to the GUI. + std::vector changes; + RsGxsMsgChange *msgChanges = new RsGxsMsgChange(RsGxsNotify::TYPE_PROCESSED); + + for(mit = parentMsgList.begin(); mit != parentMsgList.end(); mit++) + { + for(vit = mit->second.begin(); vit != mit->second.end(); vit++) + { + std::cerr << "p3PostBase::background_updateVoteCounts() Processing Msg(" << mit->first; + std::cerr << ", " << vit->mMsgId << ")"; + std::cerr << std::endl; + + RsStackMutex stack(mPostBaseMtx); /********** STACK LOCKED MTX ******/ + + /* extract current vote count */ + PostStats stats; + if (mBgIncremental) + { + if (!extractPostCache(vit->mServiceString, stats)) + { + if (!(vit->mServiceString.empty())) + { + std::cerr << "p3PostBase::background_updateVoteCounts() Failed to extract Votes"; + std::cerr << std::endl; + std::cerr << "\tFrom String: " << vit->mServiceString; + std::cerr << std::endl; + } + } + } + + /* get increment */ + std::map::iterator it; + it = mBgStatsMap.find(vit->mMsgId); + + if (it != mBgStatsMap.end()) + { + std::cerr << "p3PostBase::background_updateVoteCounts() Adding to msgChangeMap: "; + std::cerr << mit->first << " MsgId: " << vit->mMsgId; + std::cerr << std::endl; + + stats.increment(it->second); + msgChanges->msgChangeMap[mit->first].push_back(vit->mMsgId); + } + else + { + // warning. + std::cerr << "p3PostBase::background_updateVoteCounts() Warning No New Votes found."; + std::cerr << " For MsgId: " << vit->mMsgId; + std::cerr << std::endl; + } + + std::string str; + if (!encodePostCache(str, stats)) + { + std::cerr << "p3PostBase::background_updateVoteCounts() Failed to encode Votes"; + std::cerr << std::endl; + } + else + { + std::cerr << "p3PostBase::background_updateVoteCounts() Encoded String: " << str; + std::cerr << std::endl; + /* store new result */ + uint32_t token_c; + RsGxsGrpMsgIdPair msgId = std::make_pair(vit->mGroupId, vit->mMsgId); + RsGenExchange::setMsgServiceString(token_c, msgId, str); + } + } + } + + if (msgChanges->msgChangeMap.size() > 0) + { + std::cerr << "p3PostBase::background_updateVoteCounts() -> receiveChanges()"; + std::cerr << std::endl; + + changes.push_back(msgChanges); + receiveHelperChanges(changes); + } + + // DONE!. + background_cleanup(); + return; + +} + + +bool p3PostBase::background_cleanup() +{ + std::cerr << "p3PostBase::background_cleanup()"; + std::cerr << std::endl; + + RsStackMutex stack(mPostBaseMtx); /********** STACK LOCKED MTX ******/ + + // Cleanup. + mBgStatsMap.clear(); + mBgProcessing = false; + + return true; +} + + + // Overloaded from GxsTokenQueue for Request callbacks. +void p3PostBase::handleResponse(uint32_t token, uint32_t req_type) +{ + std::cerr << "p3PostBase::handleResponse(" << token << "," << req_type << ")"; + std::cerr << std::endl; + + // stuff. + switch(req_type) + { + case POSTBASE_ALL_GROUPS: + background_loadGroups(token); + break; + case POSTBASE_UNPROCESSED_MSGS: + background_loadUnprocessedMsgs(token); + break; + case POSTBASE_ALL_MSGS: + background_loadAllMsgs(token); + break; + case POSTBASE_BG_POST_META: + background_updateVoteCounts(token); + break; + default: + /* error */ + std::cerr << "p3PostBase::handleResponse() Unknown Request Type: " << req_type; + std::cerr << std::endl; + break; + } +} + diff --git a/libretroshare/src/services/p3postbase.h b/libretroshare/src/services/p3postbase.h new file mode 100644 index 000000000..b5ce1d895 --- /dev/null +++ b/libretroshare/src/services/p3postbase.h @@ -0,0 +1,135 @@ +/* + * libretroshare/src/services: p3postbase.h + * + * GxsChannel interface for RetroShare. + * + * Copyright 2012-2013 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.1 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_POSTBASE_SERVICE_HEADER +#define P3_POSTBASE_SERVICE_HEADER + + +#include "services/p3gxscommon.h" +#include "gxs/rsgenexchange.h" + +#include "util/rstickevent.h" + +#include + +#include +#include +#include + +/* + * + */ + + +class PostStats +{ + public: + PostStats() :up_votes(0), down_votes(0), comments(0) { return; } + PostStats(int up, int down, int c) :up_votes(up), down_votes(down), comments(c) { return; } + + void increment(const PostStats &s) + { + up_votes += s.up_votes; + down_votes += s.down_votes; + comments += s.comments; + return; + } + + int up_votes; + int down_votes; + int comments; + std::list voters; +}; + +bool encodePostCache(std::string &str, const PostStats &s); +bool extractPostCache(const std::string &str, PostStats &s); + + +class p3PostBase: public RsGenExchange, public GxsTokenQueue, public RsTickEvent +{ + public: + + p3PostBase(RsGeneralDataService *gds, RsNetworkExchangeService *nes, RsGixs* gixs, + RsSerialType* serviceSerialiser, uint16_t serviceType); + +virtual void service_tick(); + + // This should be overloaded to call RsGxsIfaceHelper::receiveChanges(). +virtual void receiveHelperChanges(std::vector& changes) = 0; + + protected: + +virtual void notifyChanges(std::vector& changes); + + // Overloaded from GxsTokenQueue for Request callbacks. +virtual void handleResponse(uint32_t token, uint32_t req_type); + + // Overloaded from RsTickEvent. +virtual void handle_event(uint32_t event_type, const std::string &elabel); + + public: + + ////////////////////////////////////////////////////////////////////////////// + +virtual void setMessageReadStatus(uint32_t& token, const RsGxsGrpMsgIdPair& msgId, bool read); + + + protected: + + p3GxsCommentService *mCommentService; + + private: + +static uint32_t postBaseAuthenPolicy(); + + // Background processing. + void background_tick(); + + bool background_requestAllGroups(); + void background_loadGroups(const uint32_t &token); + + void addGroupForProcessing(RsGxsGroupId grpId); + void background_requestUnprocessedGroup(); + + void background_requestGroupMsgs(const RsGxsGroupId &grpId, bool unprocessedOnly); + void background_loadUnprocessedMsgs(const uint32_t &token); + void background_loadAllMsgs(const uint32_t &token); + void background_loadMsgs(const uint32_t &token, bool unprocessed); + + + void background_updateVoteCounts(const uint32_t &token); + bool background_cleanup(); + + + RsMutex mPostBaseMtx; + + bool mBgProcessing; + bool mBgIncremental; + std::list mBgGroupList; + std::map mBgStatsMap; + +}; + +#endif diff --git a/libretroshare/src/services/p3posted.cc b/libretroshare/src/services/p3posted.cc index 08cde19de..e03ba6a70 100644 --- a/libretroshare/src/services/p3posted.cc +++ b/libretroshare/src/services/p3posted.cc @@ -26,146 +26,26 @@ #include "services/p3posted.h" #include "serialiser/rsposteditems.h" -#include - - -#include "retroshare/rsgxsflags.h" -#include #include -// For Dummy Msgs. -#include "util/rsrandom.h" -#include "util/rsstring.h" - /**** * #define POSTED_DEBUG 1 ****/ RsPosted *rsPosted = NULL; -//const uint32_t RsPosted::FLAG_MSGTYPE_POST = 0x0001; -//const uint32_t RsPosted::FLAG_MSGTYPE_MASK = 0x000f; - - -#define POSTED_TESTEVENT_DUMMYDATA 0x0001 -#define DUMMYDATA_PERIOD 60 // long enough for some RsIdentities to be generated. - -#define POSTED_BACKGROUND_PROCESSING 0x0002 -#define PROCESSING_START_PERIOD 30 -#define PROCESSING_INC_PERIOD 15 - -#define POSTED_ALL_GROUPS 0x0011 -#define POSTED_UNPROCESSED_MSGS 0x0012 -#define POSTED_ALL_MSGS 0x0013 -#define POSTED_BG_POST_META 0x0014 /********************************************************************************/ /******************* Startup / Tick ******************************************/ /********************************************************************************/ p3Posted::p3Posted(RsGeneralDataService *gds, RsNetworkExchangeService *nes, RsGixs* gixs) - : RsGenExchange(gds, nes, new RsGxsPostedSerialiser(), RS_SERVICE_GXSV2_TYPE_POSTED, gixs, postedAuthenPolicy()), RsPosted(this), GxsTokenQueue(this), RsTickEvent(), mPostedMtx("PostedMtx") + :p3PostBase(gds, nes, gixs, new RsGxsPostedSerialiser(), RS_SERVICE_GXSV2_TYPE_POSTED), + RsPosted(this) { - mBgProcessing = false; - - // For Dummy Msgs. - mGenActive = false; - mCommentService = new p3GxsCommentService(this, RS_SERVICE_GXSV2_TYPE_POSTED); - - // Test Data disabled in repo. - //RsTickEvent::schedule_in(POSTED_TESTEVENT_DUMMYDATA, DUMMYDATA_PERIOD); - - RsTickEvent::schedule_in(POSTED_BACKGROUND_PROCESSING, PROCESSING_START_PERIOD); -} - - - -uint32_t p3Posted::postedAuthenPolicy() -{ - uint32_t policy = 0; - uint32_t flag = 0; - - flag = GXS_SERV::MSG_AUTHEN_ROOT_AUTHOR_SIGN | GXS_SERV::MSG_AUTHEN_CHILD_AUTHOR_SIGN; - RsGenExchange::setAuthenPolicyFlag(flag, policy, RsGenExchange::PUBLIC_GRP_BITS); - - flag |= GXS_SERV::MSG_AUTHEN_ROOT_PUBLISH_SIGN | GXS_SERV::MSG_AUTHEN_CHILD_PUBLISH_SIGN; - RsGenExchange::setAuthenPolicyFlag(flag, policy, RsGenExchange::RESTRICTED_GRP_BITS); - RsGenExchange::setAuthenPolicyFlag(flag, policy, RsGenExchange::PRIVATE_GRP_BITS); - - flag = 0; - RsGenExchange::setAuthenPolicyFlag(flag, policy, RsGenExchange::GRP_OPTION_BITS); - - return policy; -} - - - - - -void p3Posted::notifyChanges(std::vector &changes) -{ - std::cerr << "p3Posted::notifyChanges()"; - std::cerr << std::endl; - - std::vector changesForGUI; - std::vector::iterator it; - - for(it = changes.begin(); it != changes.end(); it++) - { - RsGxsGroupChange *groupChange = dynamic_cast(*it); - RsGxsMsgChange *msgChange = dynamic_cast(*it); - if (msgChange) - { - std::cerr << "p3Posted::notifyChanges() Found Message Change Notification"; - std::cerr << std::endl; - - std::map > &msgChangeMap = msgChange->msgChangeMap; - std::map >::iterator mit; - for(mit = msgChangeMap.begin(); mit != msgChangeMap.end(); mit++) - { - std::cerr << "p3Posted::notifyChanges() Msgs for Group: " << mit->first; - std::cerr << std::endl; - // To start with we are just going to trigger updates on these groups. - // FUTURE OPTIMISATION. - // It could be taken a step further and directly request these msgs for an update. - addGroupForProcessing(mit->first); - } - delete msgChange; - } - - /* pass on Group Changes to GUI */ - if (groupChange) - { - std::cerr << "p3Posted::notifyChanges() Found Group Change Notification"; - std::cerr << std::endl; - - std::list &groupList = groupChange->mGrpIdList; - std::list::iterator git; - for(git = groupList.begin(); git != groupList.end(); git++) - { - std::cerr << "p3Posted::notifyChanges() Incoming Group: " << *git; - std::cerr << std::endl; - } - changesForGUI.push_back(groupChange); - } - } - changes.clear(); - RsGxsIfaceHelper::receiveChanges(changesForGUI); - - std::cerr << "p3Posted::notifyChanges() -> receiveChanges()"; - std::cerr << std::endl; -} - -void p3Posted::service_tick() -{ - dummy_tick(); - RsTickEvent::tick_events(); - GxsTokenQueue::checkRequests(); - - mCommentService->comment_tick(); - return; } + bool p3Posted::getGroupData(const uint32_t &token, std::vector &groups) { std::vector grpData; @@ -296,7 +176,7 @@ bool RsPostedPost::calculateScores(time_t ref_time) /* so we want to calculate all the scores for this Post. */ PostStats stats; - extractPostedCache(mMeta.mServiceString, stats); + extractPostCache(mMeta.mServiceString, stats); mUpVotes = stats.up_votes; mDownVotes = stats.down_votes; @@ -323,8 +203,6 @@ bool RsPostedPost::calculateScores(time_t ref_time) return true; } - -/********************************************************************************************/ /********************************************************************************************/ /********************************************************************************************/ @@ -354,848 +232,4 @@ bool p3Posted::createPost(uint32_t &token, RsPostedPost &msg) return true; } - /********************************************************************************************/ -/********************************************************************************************/ - -void p3Posted::setMessageReadStatus(uint32_t& token, const RsGxsGrpMsgIdPair& msgId, bool read) -{ - uint32_t mask = GXS_SERV::GXS_MSG_STATUS_UNREAD | GXS_SERV::GXS_MSG_STATUS_UNPROCESSED; - uint32_t status = GXS_SERV::GXS_MSG_STATUS_UNREAD; - if (read) - { - status = 0; - } - - setMsgStatusFlags(token, msgId, status, mask); - -} - - - - - -/********************************************************************************************/ -/********************************************************************************************/ - -/* so we need the same tick idea as wiki for generating dummy channels - */ - -#define MAX_GEN_GROUPS 5 -#define MAX_GEN_MESSAGES 100 - -std::string p3Posted::genRandomId() -{ - std::string randomId; - for(int i = 0; i < 20; i++) - { - randomId += (char) ('a' + (RSRandom::random_u32() % 26)); - } - - return randomId; -} - -bool p3Posted::generateDummyData() -{ - mGenCount = 0; - mGenRefs.resize(MAX_GEN_MESSAGES); - - std::string groupName; - rs_sprintf(groupName, "TestTopic_%d", mGenCount); - - std::cerr << "p3Posted::generateDummyData() Starting off with Group: " << groupName; - std::cerr << std::endl; - - /* create a new group */ - generateGroup(mGenToken, groupName); - - mGenActive = true; - - return true; -} - - -void p3Posted::dummy_tick() -{ - /* check for a new callback */ - - if (mGenActive) - { - std::cerr << "p3Posted::dummyTick() AboutActive"; - std::cerr << std::endl; - - uint32_t status = RsGenExchange::getTokenService()->requestStatus(mGenToken); - if (status != RsTokenService::GXS_REQUEST_V2_STATUS_COMPLETE) - { - std::cerr << "p3Posted::dummy_tick() Status: " << status; - std::cerr << std::endl; - - if (status == RsTokenService::GXS_REQUEST_V2_STATUS_FAILED) - { - std::cerr << "p3Posted::dummy_tick() generateDummyMsgs() FAILED"; - std::cerr << std::endl; - mGenActive = false; - } - return; - } - - if (mGenCount < MAX_GEN_GROUPS) - { - /* get the group Id */ - RsGxsGroupId groupId; - RsGxsMessageId emptyId; - if (!acknowledgeTokenGrp(mGenToken, groupId)) - { - std::cerr << " ERROR "; - std::cerr << std::endl; - mGenActive = false; - return; - } - - std::cerr << "p3Posted::dummy_tick() Acknowledged GroupId: " << groupId; - std::cerr << std::endl; - - PostedDummyRef ref(groupId, emptyId, emptyId); - mGenRefs[mGenCount] = ref; - } - else if (mGenCount < MAX_GEN_MESSAGES) - { - /* get the msg Id, and generate next snapshot */ - RsGxsGrpMsgIdPair msgId; - if (!acknowledgeTokenMsg(mGenToken, msgId)) - { - std::cerr << " ERROR "; - std::cerr << std::endl; - mGenActive = false; - return; - } - - std::cerr << "p3Posted::dummy_tick() Acknowledged "; - std::cerr << std::endl; - - /* store results for later selection */ - - PostedDummyRef ref(msgId.first, mGenThreadId, msgId.second); - mGenRefs[mGenCount] = ref; - } - else - { - std::cerr << "p3Posted::dummy_tick() Finished"; - std::cerr << std::endl; - - /* done */ - mGenActive = false; - return; - } - - mGenCount++; - - if (mGenCount < MAX_GEN_GROUPS) - { - std::string groupName; - rs_sprintf(groupName, "TestTopic_%d", mGenCount); - - std::cerr << "p3Posted::dummy_tick() Generating Group: " << groupName; - std::cerr << std::endl; - - /* create a new group */ - generateGroup(mGenToken, groupName); - } - else - { - /* create a new message */ - uint32_t idx = (uint32_t) (mGenCount * RSRandom::random_f32()); - PostedDummyRef &ref = mGenRefs[idx]; - - RsGxsGroupId grpId = ref.mGroupId; - RsGxsMessageId parentId = ref.mMsgId; - mGenThreadId = ref.mThreadId; - if (mGenThreadId.empty()) - { - mGenThreadId = parentId; - } - - std::cerr << "p3Posted::dummy_tick() Generating Msg ... "; - std::cerr << " GroupId: " << grpId; - std::cerr << " ThreadId: " << mGenThreadId; - std::cerr << " ParentId: " << parentId; - std::cerr << std::endl; - - if (parentId.empty()) - { - generatePost(mGenToken, grpId); - } - else - { - generateComment(mGenToken, grpId, parentId, mGenThreadId); - } - } - } -} - - -bool p3Posted::generatePost(uint32_t &token, const RsGxsGroupId &grpId) -{ - RsPostedPost msg; - - std::string rndId = genRandomId(); - - rs_sprintf(msg.mNotes, "Posted Msg: GroupId: %s, some randomness: %s", - grpId.c_str(), rndId.c_str()); - - msg.mMeta.mMsgName = msg.mNotes; - - msg.mMeta.mGroupId = grpId; - msg.mMeta.mThreadId = ""; - msg.mMeta.mParentId = ""; - - msg.mMeta.mMsgStatus = GXS_SERV::GXS_MSG_STATUS_UNPROCESSED | GXS_SERV::GXS_MSG_STATUS_UNREAD; - - /* chose a random Id to sign with */ - std::list ownIds; - std::list::iterator it; - - rsIdentity->getOwnIds(ownIds); - - uint32_t idx = (uint32_t) (ownIds.size() * RSRandom::random_f32()); - uint32_t i = 0; - for(it = ownIds.begin(); (it != ownIds.end()) && (i < idx); it++, i++) ; - - if (it != ownIds.end()) - { - std::cerr << "p3Posted::generateMessage() Author: " << *it; - std::cerr << std::endl; - msg.mMeta.mAuthorId = *it; - } - else - { - std::cerr << "p3Posted::generateMessage() No Author!"; - std::cerr << std::endl; - } - - createPost(token, msg); - - return true; -} - - -bool p3Posted::generateComment(uint32_t &token, const RsGxsGroupId &grpId, const RsGxsMessageId &parentId, const RsGxsMessageId &threadId) -{ - RsGxsComment msg; - - std::string rndId = genRandomId(); - - rs_sprintf(msg.mComment, "Posted Comment: GroupId: %s, ThreadId: %s, ParentId: %s + some randomness: %s", - grpId.c_str(), threadId.c_str(), parentId.c_str(), rndId.c_str()); - - msg.mMeta.mMsgName = msg.mComment; - - msg.mMeta.mGroupId = grpId; - msg.mMeta.mThreadId = threadId; - msg.mMeta.mParentId = parentId; - - msg.mMeta.mMsgStatus = GXS_SERV::GXS_MSG_STATUS_UNPROCESSED | GXS_SERV::GXS_MSG_STATUS_UNREAD; - - /* chose a random Id to sign with */ - std::list ownIds; - std::list::iterator it; - - rsIdentity->getOwnIds(ownIds); - - uint32_t idx = (uint32_t) (ownIds.size() * RSRandom::random_f32()); - uint32_t i = 0; - for(it = ownIds.begin(); (it != ownIds.end()) && (i < idx); it++, i++) ; - - if (it != ownIds.end()) - { - std::cerr << "p3Posted::generateMessage() Author: " << *it; - std::cerr << std::endl; - msg.mMeta.mAuthorId = *it; - } - else - { - std::cerr << "p3Posted::generateMessage() No Author!"; - std::cerr << std::endl; - } - - createComment(token, msg); - - return true; -} - - -bool p3Posted::generateGroup(uint32_t &token, std::string groupName) -{ - /* generate a new group */ - RsPostedGroup group; - group.mMeta.mGroupName = groupName; - - createGroup(token, group); - - return true; -} - - - // Overloaded from RsTickEvent for Event callbacks. -void p3Posted::handle_event(uint32_t event_type, const std::string & /* elabel */) -{ - std::cerr << "p3Posted::handle_event(" << event_type << ")"; - std::cerr << std::endl; - - // stuff. - switch(event_type) - { - case POSTED_TESTEVENT_DUMMYDATA: - generateDummyData(); - break; - - case POSTED_BACKGROUND_PROCESSING: - background_tick(); - break; - - default: - /* error */ - std::cerr << "p3Posted::handle_event() Unknown Event Type: " << event_type; - std::cerr << std::endl; - break; - } -} - - -/********************************************************************************* - * Background Calculations. - * - * Get list of change groups from Notify.... - * this doesn't imclude your own submissions (at this point). - * So they will not be processed until someone else changes something. - * TODO FIX: Must push for that change. - * - * Eventually, we should just be able to get the new messages from Notify, - * and only process them! - */ - -void p3Posted::background_tick() -{ - -#if 0 - { - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - if (mBgGroupList.empty()) - { - background_requestAllGroups(); - } - } -#endif - - background_requestUnprocessedGroup(); - - RsTickEvent::schedule_in(POSTED_BACKGROUND_PROCESSING, PROCESSING_INC_PERIOD); - -} - -bool p3Posted::background_requestAllGroups() -{ - std::cerr << "p3Posted::background_requestAllGroups()"; - std::cerr << std::endl; - - uint32_t ansType = RS_TOKREQ_ANSTYPE_LIST; - RsTokReqOptions opts; - opts.mReqType = GXS_REQUEST_TYPE_GROUP_IDS; - - uint32_t token = 0; - RsGenExchange::getTokenService()->requestGroupInfo(token, ansType, opts); - GxsTokenQueue::queueRequest(token, POSTED_ALL_GROUPS); - - return true; -} - - -void p3Posted::background_loadGroups(const uint32_t &token) -{ - /* get messages */ - std::cerr << "p3Posted::background_loadGroups()"; - std::cerr << std::endl; - - std::list groupList; - bool ok = RsGenExchange::getGroupList(token, groupList); - - if (!ok) - { - return; - } - - std::list::iterator it; - for(it = groupList.begin(); it != groupList.end(); it++) - { - addGroupForProcessing(*it); - } -} - - -void p3Posted::addGroupForProcessing(RsGxsGroupId grpId) -{ -#ifdef POSTED_DEBUG - std::cerr << "p3Posted::addGroupForProcessing(" << grpId << ")"; - std::cerr << std::endl; -#endif // POSTED_DEBUG - - { - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - // no point having multiple lookups queued. - if (mBgGroupList.end() == std::find(mBgGroupList.begin(), - mBgGroupList.end(), grpId)) - { - mBgGroupList.push_back(grpId); - } - } -} - - -void p3Posted::background_requestUnprocessedGroup() -{ -#ifdef POSTED_DEBUG - std::cerr << "p3Posted::background_requestUnprocessedGroup()"; - std::cerr << std::endl; -#endif // POSTED_DEBUG - - - RsGxsGroupId grpId; - { - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - if (mBgProcessing) - { - std::cerr << "p3Posted::background_requestUnprocessedGroup() Already Active"; - std::cerr << std::endl; - return; - } - if (mBgGroupList.empty()) - { - std::cerr << "p3Posted::background_requestUnprocessedGroup() No Groups to Process"; - std::cerr << std::endl; - return; - } - - grpId = mBgGroupList.front(); - mBgGroupList.pop_front(); - mBgProcessing = true; - } - - background_requestGroupMsgs(grpId, true); -} - - - - - -void p3Posted::background_requestGroupMsgs(const RsGxsGroupId &grpId, bool unprocessedOnly) -{ - std::cerr << "p3Posted::background_requestGroupMsgs() id: " << grpId; - std::cerr << std::endl; - - uint32_t ansType = RS_TOKREQ_ANSTYPE_DATA; - RsTokReqOptions opts; - opts.mReqType = GXS_REQUEST_TYPE_MSG_DATA; - - if (unprocessedOnly) - { - opts.mStatusFilter = GXS_SERV::GXS_MSG_STATUS_UNPROCESSED; - opts.mStatusMask = GXS_SERV::GXS_MSG_STATUS_UNPROCESSED; - } - - std::list grouplist; - grouplist.push_back(grpId); - - uint32_t token = 0; - - RsGenExchange::getTokenService()->requestMsgInfo(token, ansType, opts, grouplist); - - if (unprocessedOnly) - { - GxsTokenQueue::queueRequest(token, POSTED_UNPROCESSED_MSGS); - } - else - { - GxsTokenQueue::queueRequest(token, POSTED_ALL_MSGS); - } -} - - - - -void p3Posted::background_loadUnprocessedMsgs(const uint32_t &token) -{ - background_loadMsgs(token, true); -} - - -void p3Posted::background_loadAllMsgs(const uint32_t &token) -{ - background_loadMsgs(token, false); -} - - -/* This function is generalised to support any collection of messages, across multiple groups */ - -void p3Posted::background_loadMsgs(const uint32_t &token, bool unprocessed) -{ - /* get messages */ - std::cerr << "p3Posted::background_loadMsgs()"; - std::cerr << std::endl; - - std::map > msgData; - bool ok = RsGenExchange::getMsgData(token, msgData); - - if (!ok) - { - std::cerr << "p3Posted::background_loadMsgs() Failed to getMsgData()"; - std::cerr << std::endl; - - /* cleanup */ - background_cleanup(); - return; - - } - - { - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - mBgStatsMap.clear(); - mBgIncremental = unprocessed; - } - - std::map > postMap; - - // generate vector of changes to push to the GUI. - std::vector changes; - RsGxsMsgChange *msgChanges = new RsGxsMsgChange(RsGxsNotify::TYPE_PROCESSED); - - - RsGxsGroupId groupId; - std::map >::iterator mit; - std::vector::iterator vit; - for (mit = msgData.begin(); mit != msgData.end(); mit++) - { - groupId = mit->first; - for (vit = mit->second.begin(); vit != mit->second.end(); vit++) - { - RsGxsMessageId parentId = (*vit)->meta.mParentId; - RsGxsMessageId threadId = (*vit)->meta.mThreadId; - - - bool inc_counters = false; - uint32_t vote_up_inc = 0; - uint32_t vote_down_inc = 0; - uint32_t comment_inc = 0; - - bool add_voter = false; - RsGxsId voterId; - RsGxsCommentItem *commentItem; - RsGxsVoteItem *voteItem; - - /* THIS Should be handled by UNPROCESSED Filter - but isn't */ - if (!IS_MSG_UNPROCESSED((*vit)->meta.mMsgStatus)) - { - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - if (mBgIncremental) - { - std::cerr << "p3Posted::background_loadMsgs() Msg already Processed - Skipping"; - std::cerr << std::endl; - std::cerr << "p3Posted::background_loadMsgs() ERROR This should not happen"; - std::cerr << std::endl; - delete(*vit); - continue; - } - } - - /* 3 types expected: PostedPost, Comment and Vote */ - if (parentId.empty()) - { - /* we don't care about top-level (Posts) */ - std::cerr << "\tIgnoring TopLevel Item"; - std::cerr << std::endl; - - /* but we need to notify GUI about them */ - msgChanges->msgChangeMap[mit->first].push_back((*vit)->meta.mMsgId); - } - else if (NULL != (commentItem = dynamic_cast(*vit))) - { - /* comment - want all */ - /* Comments are counted by Thread Id */ - std::cerr << "\tProcessing Comment: " << commentItem; - std::cerr << std::endl; - - inc_counters = true; - comment_inc = 1; - } - else if (NULL != (voteItem = dynamic_cast(*vit))) - { - /* vote - only care about direct children */ - if (parentId == threadId) - { - /* Votes are organised by Parent Id, - * ie. you can vote for both Posts and Comments - */ - std::cerr << "\tProcessing Vote: " << voteItem; - std::cerr << std::endl; - - inc_counters = true; - add_voter = true; - voterId = voteItem->meta.mAuthorId; - - if (voteItem->mMsg.mVoteType == GXS_VOTE_UP) - { - vote_up_inc = 1; - } - else - { - vote_down_inc = 1; - } - } - } - else - { - /* unknown! */ - std::cerr << "p3Posted::background_processNewMessages() ERROR Strange NEW Message:"; - std::cerr << std::endl; - std::cerr << "\t" << (*vit)->meta; - std::cerr << std::endl; - - } - - if (inc_counters) - { - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - - std::map::iterator sit = mBgStatsMap.find(threadId); - if (sit == mBgStatsMap.end()) - { - // add to map of ones to update. - postMap[groupId].push_back(threadId); - - mBgStatsMap[threadId] = PostStats(0,0,0); - sit = mBgStatsMap.find(threadId); - } - - sit->second.comments += comment_inc; - sit->second.up_votes += vote_up_inc; - sit->second.down_votes += vote_down_inc; - - - if (add_voter) - { - sit->second.voters.push_back(voterId); - } - - std::cerr << "\tThreadId: " << threadId; - std::cerr << " Comment Total: " << sit->second.comments; - std::cerr << " UpVote Total: " << sit->second.up_votes; - std::cerr << " DownVote Total: " << sit->second.down_votes; - std::cerr << std::endl; - } - - /* flag all messages as processed */ - if ((*vit)->meta.mMsgStatus & GXS_SERV::GXS_MSG_STATUS_UNPROCESSED) - { - uint32_t token_a; - RsGxsGrpMsgIdPair msgId = std::make_pair(groupId, (*vit)->meta.mMsgId); - RsGenExchange::setMsgStatusFlags(token_a, msgId, 0, GXS_SERV::GXS_MSG_STATUS_UNPROCESSED); - } - delete(*vit); - } - } - - /* push updates of new Posts */ - if (msgChanges->msgChangeMap.size() > 0) - { - std::cerr << "p3Posted::background_processNewMessages() -> receiveChanges()"; - std::cerr << std::endl; - - changes.push_back(msgChanges); - RsGxsIfaceHelper::receiveChanges(changes); - } - - /* request the summary info from the parents */ - uint32_t token_b; - uint32_t anstype = RS_TOKREQ_ANSTYPE_SUMMARY; - RsTokReqOptions opts; - opts.mReqType = GXS_REQUEST_TYPE_MSG_META; - RsGenExchange::getTokenService()->requestMsgInfo(token_b, anstype, opts, postMap); - - GxsTokenQueue::queueRequest(token_b, POSTED_BG_POST_META); - return; -} - - -#define RSGXS_MAX_SERVICE_STRING 1024 -bool encodePostedCache(std::string &str, const PostStats &s) -{ - char line[RSGXS_MAX_SERVICE_STRING]; - - snprintf(line, RSGXS_MAX_SERVICE_STRING, "%d %d %d", s.comments, s.up_votes, s.down_votes); - - str = line; - return true; -} - -bool extractPostedCache(const std::string &str, PostStats &s) -{ - - uint32_t iupvotes, idownvotes, icomments; - if (3 == sscanf(str.c_str(), "%d %d %d", &icomments, &iupvotes, &idownvotes)) - { - s.comments = icomments; - s.up_votes = iupvotes; - s.down_votes = idownvotes; - return true; - } - return false; -} - - -void p3Posted::background_updateVoteCounts(const uint32_t &token) -{ - std::cerr << "p3Posted::background_updateVoteCounts()"; - std::cerr << std::endl; - - GxsMsgMetaMap parentMsgList; - GxsMsgMetaMap::iterator mit; - std::vector::iterator vit; - - bool ok = RsGenExchange::getMsgMeta(token, parentMsgList); - - if (!ok) - { - std::cerr << "p3Posted::background_updateVoteCounts() ERROR"; - std::cerr << std::endl; - background_cleanup(); - return; - } - - // generate vector of changes to push to the GUI. - std::vector changes; - RsGxsMsgChange *msgChanges = new RsGxsMsgChange(RsGxsNotify::TYPE_PROCESSED); - - for(mit = parentMsgList.begin(); mit != parentMsgList.end(); mit++) - { - for(vit = mit->second.begin(); vit != mit->second.end(); vit++) - { - std::cerr << "p3Posted::background_updateVoteCounts() Processing Msg(" << mit->first; - std::cerr << ", " << vit->mMsgId << ")"; - std::cerr << std::endl; - - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - - /* extract current vote count */ - PostStats stats; - if (mBgIncremental) - { - if (!extractPostedCache(vit->mServiceString, stats)) - { - if (!(vit->mServiceString.empty())) - { - std::cerr << "p3Posted::background_updateVoteCounts() Failed to extract Votes"; - std::cerr << std::endl; - std::cerr << "\tFrom String: " << vit->mServiceString; - std::cerr << std::endl; - } - } - } - - /* get increment */ - std::map::iterator it; - it = mBgStatsMap.find(vit->mMsgId); - - if (it != mBgStatsMap.end()) - { - std::cerr << "p3Posted::background_updateVoteCounts() Adding to msgChangeMap: "; - std::cerr << mit->first << " MsgId: " << vit->mMsgId; - std::cerr << std::endl; - - stats.increment(it->second); - msgChanges->msgChangeMap[mit->first].push_back(vit->mMsgId); - } - else - { - // warning. - std::cerr << "p3Posted::background_updateVoteCounts() Warning No New Votes found."; - std::cerr << " For MsgId: " << vit->mMsgId; - std::cerr << std::endl; - } - - std::string str; - if (!encodePostedCache(str, stats)) - { - std::cerr << "p3Posted::background_updateVoteCounts() Failed to encode Votes"; - std::cerr << std::endl; - } - else - { - std::cerr << "p3Posted::background_updateVoteCounts() Encoded String: " << str; - std::cerr << std::endl; - /* store new result */ - uint32_t token_c; - RsGxsGrpMsgIdPair msgId = std::make_pair(vit->mGroupId, vit->mMsgId); - RsGenExchange::setMsgServiceString(token_c, msgId, str); - } - } - } - - if (msgChanges->msgChangeMap.size() > 0) - { - std::cerr << "p3Posted::background_updateVoteCounts() -> receiveChanges()"; - std::cerr << std::endl; - - changes.push_back(msgChanges); - RsGxsIfaceHelper::receiveChanges(changes); - } - - // DONE!. - background_cleanup(); - return; - -} - - -bool p3Posted::background_cleanup() -{ - std::cerr << "p3Posted::background_cleanup()"; - std::cerr << std::endl; - - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - - // Cleanup. - mBgStatsMap.clear(); - mBgProcessing = false; - - return true; -} - - - // Overloaded from GxsTokenQueue for Request callbacks. -void p3Posted::handleResponse(uint32_t token, uint32_t req_type) -{ - std::cerr << "p3Posted::handleResponse(" << token << "," << req_type << ")"; - std::cerr << std::endl; - - // stuff. - switch(req_type) - { - case POSTED_ALL_GROUPS: - background_loadGroups(token); - break; - case POSTED_UNPROCESSED_MSGS: - background_loadUnprocessedMsgs(token); - break; - case POSTED_ALL_MSGS: - background_loadAllMsgs(token); - break; - case POSTED_BG_POST_META: - background_updateVoteCounts(token); - break; - default: - /* error */ - std::cerr << "p3Posted::handleResponse() Unknown Request Type: " << req_type; - std::cerr << std::endl; - break; - } -} - diff --git a/libretroshare/src/services/p3posted.h b/libretroshare/src/services/p3posted.h index a3bcd4d53..0f82277ec 100644 --- a/libretroshare/src/services/p3posted.h +++ b/libretroshare/src/services/p3posted.h @@ -28,10 +28,7 @@ #include "retroshare/rsposted.h" -#include "services/p3gxscommon.h" -#include "gxs/rsgenexchange.h" - -#include "util/rstickevent.h" +#include "services/p3postbase.h" #include @@ -43,72 +40,41 @@ * */ - -class PostStats -{ - public: - PostStats() :up_votes(0), down_votes(0), comments(0) { return; } - PostStats(int up, int down, int c) :up_votes(up), down_votes(down), comments(c) { return; } - - void increment(const PostStats &s) - { - up_votes += s.up_votes; - down_votes += s.down_votes; - comments += s.comments; - return; - } - - int up_votes; - int down_votes; - int comments; - std::list voters; -}; - -bool encodePostedCache(std::string &str, const PostStats &s); -bool extractPostedCache(const std::string &str, PostStats &s); - - -class p3Posted: public RsGenExchange, public RsPosted, - public GxsTokenQueue, - public RsTickEvent /* only needed for testing - remove after */ +class p3Posted: public p3PostBase, public RsPosted { public: p3Posted(RsGeneralDataService* gds, RsNetworkExchangeService* nes, RsGixs* gixs); -virtual void service_tick(); - protected: - -virtual void notifyChanges(std::vector& changes); - - // Overloaded from GxsTokenQueue for Request callbacks. -virtual void handleResponse(uint32_t token, uint32_t req_type); - - // Overloaded from RsTickEvent. -virtual void handle_event(uint32_t event_type, const std::string &elabel); +virtual void notifyChanges(std::vector& changes) +{ + return p3PostBase::notifyChanges(changes); +} public: +virtual void receiveHelperChanges(std::vector& changes) +{ + return RsGxsIfaceHelper::receiveChanges(changes); +} + + // Posted Specific DataTypes. virtual bool getGroupData(const uint32_t &token, std::vector &groups); virtual bool getPostData(const uint32_t &token, std::vector &posts); - virtual bool getRelatedPosts(const uint32_t &token, std::vector &posts); - ////////////////////////////////////////////////////////////////////////////// - -virtual void setMessageReadStatus(uint32_t& token, const RsGxsGrpMsgIdPair& msgId, bool read); - -//virtual bool setMessageStatus(const std::string &msgId, const uint32_t status, const uint32_t statusMask); -//virtual bool setGroupSubscribeFlags(const std::string &groupId, uint32_t subscribeFlags, uint32_t subscribeMask); - -//virtual bool groupRestoreKeys(const std::string &groupId); -//virtual bool groupShareKeys(const std::string &groupId, std::list& peers); - virtual bool createGroup(uint32_t &token, RsPostedGroup &group); virtual bool createPost(uint32_t &token, RsPostedPost &post); + ////////////////////////////////////////////////////////////////////////////// + // WRAPPERS due to the separate Interface. + +virtual void setMessageReadStatus(uint32_t& token, const RsGxsGrpMsgIdPair& msgId, bool read) + { + return p3PostBase::setMessageReadStatus(token, msgId, read); + } /* Comment service - Provide RsGxsCommentService - redirect to p3GxsCommentService */ @@ -145,82 +111,6 @@ virtual bool acknowledgeVote(const uint32_t& token, std::pair mBgGroupList; - std::map mBgStatsMap; - - - - -// DUMMY DATA, -virtual bool generateDummyData(); - -std::string genRandomId(); - -void dummy_tick(); - -bool generatePost(uint32_t &token, const RsGxsGroupId &grpId); -bool generateComment(uint32_t &token, const RsGxsGroupId &grpId, - const RsGxsMessageId &parentId, const RsGxsMessageId &threadId); -bool generateGroup(uint32_t &token, std::string groupName); - - class PostedDummyRef - { - public: - PostedDummyRef() { return; } - PostedDummyRef(const RsGxsGroupId &grpId, const RsGxsMessageId &threadId, const RsGxsMessageId &msgId) - :mGroupId(grpId), mThreadId(threadId), mMsgId(msgId) { return; } - - RsGxsGroupId mGroupId; - RsGxsMessageId mThreadId; - RsGxsMessageId mMsgId; - }; - - uint32_t mGenToken; - bool mGenActive; - int mGenCount; - std::vector mGenRefs; - RsGxsMessageId mGenThreadId; - - p3GxsCommentService *mCommentService; }; - - - - - - - - #endif diff --git a/libretroshare/src/services/p3postedVEG.cc b/libretroshare/src/services/p3postedVEG.cc deleted file mode 100644 index 63acd3cba..000000000 --- a/libretroshare/src/services/p3postedVEG.cc +++ /dev/null @@ -1,2148 +0,0 @@ -/* - * libretroshare/src/services p3photoservice.cc - * - * Photo Service for RetroShare. - * - * Copyright 2012-2012 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.1 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/p3postedVEG.h" -#include "util/rsrandom.h" -#include -#include -#include - -/**** - * #define POSTED_DEBUG 1 - ****/ - -RsPostedVEG *rsPostedVEG = NULL; - - -/********************************************************************************/ -/******************* Startup / Tick ******************************************/ -/********************************************************************************/ - -p3PostedServiceVEG::p3PostedServiceVEG(uint16_t type) - :p3GxsDataServiceVEG(type, new PostedDataProxy()), mPostedMtx("p3PostedService"), mUpdated(true) -{ - { - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - - mPostedProxy = (PostedDataProxy *) mProxy; - - mViewMode = RSPOSTED_VIEWMODE_HOT; - mViewPeriod = RSPOSTED_PERIOD_WEEK; - mViewStart = 0; - mViewCount = 50; - - mProcessingRanking = false; - mRankingState = 0; - mRankingExternalToken = 0; - mRankingInternalToken = 0; - - mLastBgCheck = 0; - mBgProcessing = 0; - mBgPhase = 0; - mBgToken = 0; - - } - - generateDummyData(); - return; -} - -#define POSTED_BACKGROUND_PERIOD 60 - -int p3PostedServiceVEG::tick() -{ - //std::cerr << "p3PostedServiceVEG::tick()"; - //std::cerr << std::endl; - - fakeprocessrequests(); - - - // Contine Ranking Request. - checkRankingRequest(); - - // Run Background Stuff. - background_checkTokenRequest(); - - /* every minute - run a background check */ - time_t now = time(NULL); - bool doCheck = false; - { - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - if (now - mLastBgCheck > POSTED_BACKGROUND_PERIOD) - { - doCheck = true; - mLastBgCheck = now; - } - } - - if (doCheck) - { - addExtraDummyData(); - background_requestGroups(); - } - - - - // Add in new votes + comments. - return 0; -} - -bool p3PostedServiceVEG::updated() -{ - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - - if (mUpdated) - { - mUpdated = false; - return true; - } - return false; -} - - - - /* Data Requests */ -bool p3PostedServiceVEG::requestGroupInfo( uint32_t &token, uint32_t ansType, const RsTokReqOptionsVEG &opts, const std::list &groupIds) -{ - generateToken(token); - std::cerr << "p3PostedServiceVEG::requestGroupInfo() gets Token: " << token << std::endl; - storeRequest(token, ansType, opts, GXS_REQUEST_TYPE_GROUPS, groupIds); - - return true; -} - -bool p3PostedServiceVEG::requestMsgInfo( uint32_t &token, uint32_t ansType, const RsTokReqOptionsVEG &opts, const std::list &groupIds) -{ - generateToken(token); - std::cerr << "p3PostedServiceVEG::requestMsgInfo() gets Token: " << token << std::endl; - storeRequest(token, ansType, opts, GXS_REQUEST_TYPE_MSGS, groupIds); - - return true; -} - -bool p3PostedServiceVEG::requestMsgRelatedInfo(uint32_t &token, uint32_t ansType, const RsTokReqOptionsVEG &opts, const std::list &msgIds) -{ - generateToken(token); - std::cerr << "p3PostedServiceVEG::requestMsgRelatedInfo() gets Token: " << token << std::endl; - storeRequest(token, ansType, opts, GXS_REQUEST_TYPE_MSGRELATED, msgIds); - - return true; -} - - /* Generic Lists */ -bool p3PostedServiceVEG::getGroupList( const uint32_t &token, std::list &groupIds) -{ - uint32_t status; - uint32_t reqtype; - uint32_t anstype; - time_t ts; - checkRequestStatus(token, status, reqtype, anstype, ts); - - if (anstype != RS_TOKREQ_ANSTYPE_LIST) - { - std::cerr << "p3PostedServiceVEG::getGroupList() ERROR AnsType Wrong" << std::endl; - return false; - } - - if (reqtype != GXS_REQUEST_TYPE_GROUPS) - { - std::cerr << "p3PostedServiceVEG::getGroupList() ERROR ReqType Wrong" << std::endl; - return false; - } - - if (status != GXS_REQUEST_STATUS_COMPLETE) - { - std::cerr << "p3PostedServiceVEG::getGroupList() ERROR Status Incomplete" << std::endl; - return false; - } - - bool ans = loadRequestOutList(token, groupIds); - updateRequestStatus(token, GXS_REQUEST_STATUS_DONE); - - return ans; -} - - - - -bool p3PostedServiceVEG::getMsgList( const uint32_t &token, std::list &msgIds) -{ - uint32_t status; - uint32_t reqtype; - uint32_t anstype; - time_t ts; - checkRequestStatus(token, status, reqtype, anstype, ts); - - if (anstype != RS_TOKREQ_ANSTYPE_LIST) - { - std::cerr << "p3PostedServiceVEG::getMsgList() ERROR AnsType Wrong" << std::endl; - return false; - } - - if ((reqtype != GXS_REQUEST_TYPE_MSGS) && (reqtype != GXS_REQUEST_TYPE_MSGRELATED)) - { - std::cerr << "p3PostedServiceVEG::getMsgList() ERROR ReqType Wrong" << std::endl; - return false; - } - - if (status != GXS_REQUEST_STATUS_COMPLETE) - { - std::cerr << "p3PostedServiceVEG::getMsgList() ERROR Status Incomplete" << std::endl; - return false; - } - - bool ans = loadRequestOutList(token, msgIds); - updateRequestStatus(token, GXS_REQUEST_STATUS_DONE); - - return ans; -} - - - /* Generic Summary */ -bool p3PostedServiceVEG::getGroupSummary( const uint32_t &token, std::list &groupInfo) -{ - uint32_t status; - uint32_t reqtype; - uint32_t anstype; - time_t ts; - checkRequestStatus(token, status, reqtype, anstype, ts); - - if (anstype != RS_TOKREQ_ANSTYPE_SUMMARY) - { - std::cerr << "p3PostedServiceVEG::getGroupSummary() ERROR AnsType Wrong" << std::endl; - return false; - } - - if (reqtype != GXS_REQUEST_TYPE_GROUPS) - { - std::cerr << "p3PostedServiceVEG::getGroupSummary() ERROR ReqType Wrong" << std::endl; - return false; - } - - if (status != GXS_REQUEST_STATUS_COMPLETE) - { - std::cerr << "p3PostedServiceVEG::getGroupSummary() ERROR Status Incomplete" << std::endl; - return false; - } - - std::list groupIds; - bool ans = loadRequestOutList(token, groupIds); - updateRequestStatus(token, GXS_REQUEST_STATUS_DONE); - - /* convert to RsGroupMetaData */ - mProxy->getGroupSummary(groupIds, groupInfo); - - return ans; -} - -bool p3PostedServiceVEG::getMsgSummary( const uint32_t &token, std::list &msgInfo) -{ - uint32_t status; - uint32_t reqtype; - uint32_t anstype; - time_t ts; - checkRequestStatus(token, status, reqtype, anstype, ts); - - if (anstype != RS_TOKREQ_ANSTYPE_SUMMARY) - { - std::cerr << "p3PostedServiceVEG::getMsgSummary() ERROR AnsType Wrong" << std::endl; - return false; - } - - if ((reqtype != GXS_REQUEST_TYPE_MSGS) && (reqtype != GXS_REQUEST_TYPE_MSGRELATED)) - { - std::cerr << "p3PostedServiceVEG::getMsgSummary() ERROR ReqType Wrong" << std::endl; - return false; - } - - if (status != GXS_REQUEST_STATUS_COMPLETE) - { - std::cerr << "p3PostedServiceVEG::getMsgSummary() ERROR Status Incomplete" << std::endl; - return false; - } - - std::list msgIds; - bool ans = loadRequestOutList(token, msgIds); - updateRequestStatus(token, GXS_REQUEST_STATUS_DONE); - - /* convert to RsMsgMetaData */ - mProxy->getMsgSummary(msgIds, msgInfo); - - return ans; -} - - - /* Specific Service Data */ -bool p3PostedServiceVEG::getGroup(const uint32_t &token, RsPostedGroup &group) -{ - std::cerr << "p3PostedServiceVEG::getGroup() Token: " << token; - std::cerr << std::endl; - - uint32_t status; - uint32_t reqtype; - uint32_t anstype; - time_t ts; - checkRequestStatus(token, status, reqtype, anstype, ts); - - - if (anstype != RS_TOKREQ_ANSTYPE_DATA) - { - std::cerr << "p3PostedServiceVEG::getGroup() ERROR AnsType Wrong" << std::endl; - return false; - } - - if (reqtype != GXS_REQUEST_TYPE_GROUPS) - { - std::cerr << "p3PostedServiceVEG::getGroup() ERROR ReqType Wrong" << std::endl; - return false; - } - - if (status != GXS_REQUEST_STATUS_COMPLETE) - { - std::cerr << "p3PostedServiceVEG::getGroup() ERROR Status Incomplete" << std::endl; - return false; - } - - std::string id; - if (!popRequestOutList(token, id)) - { - /* finished */ - updateRequestStatus(token, GXS_REQUEST_STATUS_DONE); - return false; - } - - /* convert to RsPostedGroup */ - bool ans = mPostedProxy->getGroup(id, group); - return ans; -} - - -bool p3PostedServiceVEG::getPost(const uint32_t &token, RsPostedPost &post) -{ - std::cerr << "p3PostedServiceVEG::getPost() Token: " << token; - std::cerr << std::endl; - - uint32_t status; - uint32_t reqtype; - uint32_t anstype; - time_t ts; - checkRequestStatus(token, status, reqtype, anstype, ts); - - - if (anstype != RS_TOKREQ_ANSTYPE_DATA) - { - std::cerr << "p3PostedServiceVEG::getPost() ERROR AnsType Wrong" << std::endl; - return false; - } - - if ((reqtype != GXS_REQUEST_TYPE_MSGS) && (reqtype != GXS_REQUEST_TYPE_MSGRELATED)) - { - std::cerr << "p3PostedServiceVEG::getPost() ERROR ReqType Wrong" << std::endl; - return false; - } - - if (status != GXS_REQUEST_STATUS_COMPLETE) - { - std::cerr << "p3PostedServiceVEG::getPost() ERROR Status Incomplete" << std::endl; - return false; - } - - std::string id; - if (!popRequestOutList(token, id)) - { - /* finished */ - updateRequestStatus(token, GXS_REQUEST_STATUS_DONE); - return false; - } - - /* convert to RsPhotoAlbum */ - bool ans = mPostedProxy->getPost(id, post); - return ans; -} - - -bool p3PostedServiceVEG::getComment(const uint32_t &token, RsPostedComment &comment) -{ - std::cerr << "p3PostedServiceVEG::getComment() Token: " << token; - std::cerr << std::endl; - - uint32_t status; - uint32_t reqtype; - uint32_t anstype; - time_t ts; - checkRequestStatus(token, status, reqtype, anstype, ts); - - - if (anstype != RS_TOKREQ_ANSTYPE_DATA) - { - std::cerr << "p3PostedServiceVEG::getComment() ERROR AnsType Wrong" << std::endl; - return false; - } - - if ((reqtype != GXS_REQUEST_TYPE_MSGS) && (reqtype != GXS_REQUEST_TYPE_MSGRELATED)) - { - std::cerr << "p3PostedServiceVEG::getComment() ERROR ReqType Wrong" << std::endl; - return false; - } - - if (status != GXS_REQUEST_STATUS_COMPLETE) - { - std::cerr << "p3PostedServiceVEG::getComment() ERROR Status Incomplete" << std::endl; - return false; - } - - std::string id; - if (!popRequestOutList(token, id)) - { - /* finished */ - updateRequestStatus(token, GXS_REQUEST_STATUS_DONE); - return false; - } - - /* convert to RsPhotoAlbum */ - bool ans = mPostedProxy->getComment(id, comment); - return ans; -} - - /* Cancel Request */ -bool p3PostedServiceVEG::cancelRequest(const uint32_t &token) -{ - return clearRequest(token); -} - - ////////////////////////////////////////////////////////////////////////////// - - - -bool p3PostedServiceVEG::setMessageStatus(const std::string &msgId, const uint32_t status, const uint32_t statusMask) -{ - return mPostedProxy->setMessageStatus(msgId, status, statusMask); -} - -bool p3PostedServiceVEG::setGroupStatus(const std::string &groupId, const uint32_t status, const uint32_t statusMask) -{ - return mPostedProxy->setGroupStatus(groupId, status, statusMask); -} - -bool p3PostedServiceVEG::setGroupSubscribeFlags(const std::string &groupId, uint32_t subscribeFlags, uint32_t subscribeMask) -{ - return mPostedProxy->setGroupSubscribeFlags(groupId, subscribeFlags, subscribeMask); -} - -bool p3PostedServiceVEG::setMessageServiceString(const std::string &msgId, const std::string &str) -{ - return mPostedProxy->setMessageServiceString(msgId, str); -} - -bool p3PostedServiceVEG::setGroupServiceString(const std::string &grpId, const std::string &str) -{ - return mPostedProxy->setGroupServiceString(grpId, str); -} - - -bool p3PostedServiceVEG::groupRestoreKeys(const std::string &groupId) -{ - return false; -} - -bool p3PostedServiceVEG::groupShareKeys(const std::string &groupId, std::list& peers) -{ - return false; -} - - -bool p3PostedServiceVEG::submitGroup(uint32_t &token, RsPostedGroup &group, bool isNew) -{ - /* check if its a modification or a new album */ - - /* add to database */ - - /* check if its a mod or new photo */ - if (group.mMeta.mGroupId.empty()) - { - /* new photo */ - - /* generate a temp id */ - group.mMeta.mGroupId = genRandomId(); - group.mMeta.mPublishTs = time(NULL); - - std::cerr << "p3PostedServiceVEG::submitGroup() Generated New GroupID: " << group.mMeta.mGroupId; - std::cerr << std::endl; - } - - //group.mModFlags = 0; // These are always cleared. - - { - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - - mUpdated = true; - mPostedProxy->addGroup(group); - } - - // Fake a request to return the GroupMetaData. - generateToken(token); - uint32_t ansType = RS_TOKREQ_ANSTYPE_SUMMARY; - RsTokReqOptionsVEG opts; // NULL is good. - std::list groupIds; - groupIds.push_back(group.mMeta.mGroupId); // It will just return this one. - - std::cerr << "p3PostedServiceVEG::submitGroup() Generating Request Token: " << token << std::endl; - storeRequest(token, ansType, opts, GXS_REQUEST_TYPE_GROUPS, groupIds); - - return true; -} - - -bool p3PostedServiceVEG::submitPost(uint32_t &token, RsPostedPost &post, bool isNew) -{ - if (post.mMeta.mGroupId.empty()) - { - /* new photo */ - std::cerr << "p3PostedServiceVEG::submitPost() Missing GroupID: ERROR"; - std::cerr << std::endl; - return false; - } - - /* generate a new id */ - post.mMeta.mMsgId = genRandomId(); - post.mMeta.mPublishTs = time(NULL); - - if (isNew) - { - /* new (Original Msg) photo */ - post.mMeta.mOrigMsgId = post.mMeta.mMsgId; - std::cerr << "p3PostedServiceVEG::submitPost() New Msg"; - std::cerr << std::endl; - } - else - { - std::cerr << "p3PostedServiceVEG::submitPost() Updated Msg"; - std::cerr << std::endl; - } - - //post.mModFlags = 0; // These are always cleared. - - std::cerr << "p3PostedServiceVEG::submitPost() OrigMsgId: " << post.mMeta.mOrigMsgId; - std::cerr << " MsgId: " << post.mMeta.mMsgId; - std::cerr << std::endl; - - { - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - - mUpdated = true; - mPostedProxy->addPost(post); - } - - // Fake a request to return the MsgMetaData. - generateToken(token); - uint32_t ansType = RS_TOKREQ_ANSTYPE_SUMMARY; - RsTokReqOptionsVEG opts; // NULL is good. - std::list msgIds; - msgIds.push_back(post.mMeta.mMsgId); // It will just return this one. - - std::cerr << "p3PostedServiceVEG::submitPost() Generating Request Token: " << token << std::endl; - storeRequest(token, ansType, opts, GXS_REQUEST_TYPE_MSGRELATED, msgIds); - - return true; -} - - - -bool p3PostedServiceVEG::submitVote(uint32_t &token, RsPostedVote &vote, bool isNew) -{ - if (vote.mMeta.mGroupId.empty()) - { - /* new photo */ - std::cerr << "p3PostedServiceVEG::submitVote() Missing GroupID: ERROR"; - std::cerr << std::endl; - return false; - } - - /* generate a new id */ - vote.mMeta.mMsgId = genRandomId(); - vote.mMeta.mPublishTs = time(NULL); - - if (isNew) - { - /* new (Original Msg) photo */ - vote.mMeta.mOrigMsgId = vote.mMeta.mMsgId; - std::cerr << "p3PostedServiceVEG::submitVote() New Msg"; - std::cerr << std::endl; - } - else - { - std::cerr << "p3PostedServiceVEG::submitVote() Updated Msg"; - std::cerr << std::endl; - } - - //vote.mModFlags = 0; // These are always cleared. - - std::cerr << "p3PostedServiceVEG::submitVote() OrigMsgId: " << vote.mMeta.mOrigMsgId; - std::cerr << " MsgId: " << vote.mMeta.mMsgId; - std::cerr << std::endl; - - { - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - - mUpdated = true; - mPostedProxy->addVote(vote); - } - - // Fake a request to return the MsgMetaData. - generateToken(token); - uint32_t ansType = RS_TOKREQ_ANSTYPE_SUMMARY; - RsTokReqOptionsVEG opts; // NULL is good. - std::list msgIds; - msgIds.push_back(vote.mMeta.mMsgId); // It will just return this one. - - std::cerr << "p3PostedServiceVEG::submitVote() Generating Request Token: " << token << std::endl; - storeRequest(token, ansType, opts, GXS_REQUEST_TYPE_MSGRELATED, msgIds); - - - return true; -} - - -bool p3PostedServiceVEG::submitComment(uint32_t &token, RsPostedComment &comment, bool isNew) -{ - if (comment.mMeta.mGroupId.empty()) - { - /* new photo */ - std::cerr << "p3PostedServiceVEG::submitPost() Missing GroupID: ERROR"; - std::cerr << std::endl; - return false; - } - - /* generate a new id */ - comment.mMeta.mMsgId = genRandomId(); - comment.mMeta.mPublishTs = time(NULL); - - if (isNew) - { - /* new (Original Msg) photo */ - comment.mMeta.mOrigMsgId = comment.mMeta.mMsgId; - std::cerr << "p3PostedServiceVEG::submitComment() New Msg"; - std::cerr << std::endl; - } - else - { - std::cerr << "p3PostedServiceVEG::submitComment() Updated Msg"; - std::cerr << std::endl; - } - - //comment.mModFlags = 0; // These are always cleared. - - std::cerr << "p3PostedServiceVEG::submitComment() OrigMsgId: " << comment.mMeta.mOrigMsgId; - std::cerr << " MsgId: " << comment.mMeta.mMsgId; - std::cerr << std::endl; - - { - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - - mUpdated = true; - mPostedProxy->addComment(comment); - } - - // Fake a request to return the MsgMetaData. - generateToken(token); - uint32_t ansType = RS_TOKREQ_ANSTYPE_SUMMARY; - RsTokReqOptionsVEG opts; // NULL is good. - std::list msgIds; - msgIds.push_back(comment.mMeta.mMsgId); // It will just return this one. - - std::cerr << "p3PostedServiceVEG::submitComment() Generating Request Token: " << token << std::endl; - storeRequest(token, ansType, opts, GXS_REQUEST_TYPE_MSGRELATED, msgIds); - - return true; -} - - - -/********************************************************************************************/ - -bool PostedDataProxy::getGroup(const std::string &id, RsPostedGroup &group) -{ - void *groupData = NULL; - RsGroupMetaData meta; - if (getGroupData(id, groupData) && getGroupSummary(id, meta)) - { - RsPostedGroup *pG = (RsPostedGroup *) groupData; - group = *pG; - - group.mMeta = meta; - - std::cerr << "PostedDataProxy::getGroup() Id: " << id; - std::cerr << " MetaData: " << meta << " DataPointer: " << groupData; - std::cerr << std::endl; - return true; - } - - std::cerr << "PostedDataProxy::getGroup() FAILED Id: " << id; - std::cerr << std::endl; - - return false; -} - - - -bool PostedDataProxy::getPost(const std::string &id, RsPostedPost &post) -{ - void *msgData = NULL; - RsMsgMetaData meta; - if (getMsgData(id, msgData) && getMsgSummary(id, meta)) - { - RsPostedMsg *pM = (RsPostedMsg *) msgData; - - if (pM->postedType == RSPOSTED_MSGTYPE_POST) - { - RsPostedPost *pP = (RsPostedPost *) pM; - post = *pP; - - // update definitive version of the metadata. - post.mMeta = meta; - - std::cerr << "PostedDataProxy::getPost() Id: " << id; - std::cerr << " MetaData: " << meta << " DataPointer: " << msgData; - std::cerr << std::endl; - return true; - } - else - { - std::cerr << "PostedDataProxy::getPost() ERROR NOT POST Id: " << id; - std::cerr << " MetaData: " << meta << " DataPointer: " << msgData; - std::cerr << std::endl; - return false; - } - } - - std::cerr << "PostedDataProxy::getPost() FAILED Id: " << id; - std::cerr << std::endl; - - return false; -} - - - - -bool PostedDataProxy::getVote(const std::string &id, RsPostedVote &vote) -{ - void *msgData = NULL; - RsMsgMetaData meta; - if (getMsgData(id, msgData) && getMsgSummary(id, meta)) - { - RsPostedMsg *pM = (RsPostedMsg *) msgData; - - if (pM->postedType == RSPOSTED_MSGTYPE_VOTE) - { - RsPostedVote *pP = (RsPostedVote *) pM; - vote = *pP; - - // update definitive version of the metadata. - vote.mMeta = meta; - - std::cerr << "PostedDataProxy::getVote() Id: " << id; - std::cerr << " MetaData: " << meta << " DataPointer: " << msgData; - std::cerr << std::endl; - return true; - } - else - { - std::cerr << "PostedDataProxy::getVote() ERROR NOT VOTE Id: " << id; - std::cerr << " MetaData: " << meta << " DataPointer: " << msgData; - std::cerr << std::endl; - return false; - } - } - - std::cerr << "PostedDataProxy::getVote() FAILED Id: " << id; - std::cerr << std::endl; - - return false; -} - - - - -bool PostedDataProxy::getComment(const std::string &id, RsPostedComment &comment) -{ - void *msgData = NULL; - RsMsgMetaData meta; - if (getMsgData(id, msgData) && getMsgSummary(id, meta)) - { - RsPostedMsg *pM = (RsPostedMsg *) msgData; - - if (pM->postedType == RSPOSTED_MSGTYPE_COMMENT) - { - RsPostedComment *pP = (RsPostedComment *) pM; - comment = *pP; - - // update definitive version of the metadata. - comment.mMeta = meta; - - std::cerr << "PostedDataProxy::getComment() Id: " << id; - std::cerr << " MetaData: " << meta << " DataPointer: " << msgData; - std::cerr << std::endl; - return true; - } - else - { - std::cerr << "PostedDataProxy::getComment() ERROR NOT POST Id: " << id; - std::cerr << " MetaData: " << meta << " DataPointer: " << msgData; - std::cerr << std::endl; - return false; - } - } - - std::cerr << "PostedDataProxy::getComment() FAILED Id: " << id; - std::cerr << std::endl; - - return false; -} - - - - -bool PostedDataProxy::addGroup(const RsPostedGroup &group) -{ - // Make duplicate. - RsPostedGroup *pG = new RsPostedGroup(); - *pG = group; - - std::cerr << "PostedDataProxy::addGroup()"; - std::cerr << " MetaData: " << pG->mMeta << " DataPointer: " << pG; - std::cerr << std::endl; - - return createGroup(pG); -} - - -bool PostedDataProxy::addPost(const RsPostedPost &post) -{ - // Make duplicate. - RsPostedPost *pP = new RsPostedPost(); - *pP = post; - - std::cerr << "PostedDataProxy::addPost()"; - std::cerr << " MetaData: " << pP->mMeta << " DataPointer: " << pP; - std::cerr << std::endl; - - return createMsg(pP); -} - - -bool PostedDataProxy::addVote(const RsPostedVote &vote) -{ - // Make duplicate. - RsPostedVote *pP = new RsPostedVote(); - *pP = vote; - - std::cerr << "PostedDataProxy::addVote()"; - std::cerr << " MetaData: " << pP->mMeta << " DataPointer: " << pP; - std::cerr << std::endl; - - return createMsg(pP); -} - - -bool PostedDataProxy::addComment(const RsPostedComment &comment) -{ - // Make duplicate. - RsPostedComment *pP = new RsPostedComment(); - *pP = comment; - - std::cerr << "PostedDataProxy::addComment()"; - std::cerr << " MetaData: " << pP->mMeta << " DataPointer: " << pP; - std::cerr << std::endl; - - return createMsg(pP); -} - - - /* These Functions must be overloaded to complete the service */ -bool PostedDataProxy::convertGroupToMetaData(void *groupData, RsGroupMetaData &meta) -{ - RsPostedGroup *group = (RsPostedGroup *) groupData; - meta = group->mMeta; - - return true; -} - -bool PostedDataProxy::convertMsgToMetaData(void *msgData, RsMsgMetaData &meta) -{ - RsPostedMsg *msg = (RsPostedMsg *) msgData; - meta = msg->mMeta; - - return true; -} - - -/********************************************************************************************/ - -std::string p3PostedServiceVEG::genRandomId() -{ - std::string randomId; - for(int i = 0; i < 20; i++) - { - randomId += (char) ('a' + (RSRandom::random_u32() % 26)); - } - - return randomId; -} - - -/********************************************************************************************/ - -std::ostream &operator<<(std::ostream &out, const RsPostedPost &post) -{ - out << "RsPostedPost [ "; - out << "Title: " << post.mMeta.mMsgName; - out << "]"; - return out; -} - -std::ostream &operator<<(std::ostream &out, const RsPostedVote &vote) -{ - out << "RsPostedVote [ "; - out << "Title: " << vote.mMeta.mMsgName; - out << "]"; - return out; -} - -std::ostream &operator<<(std::ostream &out, const RsPostedComment &comment) -{ - out << "RsPostedComment [ "; - out << "Title: " << comment.mMeta.mMsgName; - out << "]"; - return out; -} - -std::ostream &operator<<(std::ostream &out, const RsPostedGroup &group) -{ - out << "RsPostedGroup [ "; - out << "Title: " << group.mMeta.mGroupName; - out << "]"; - return out; -} - - -/********************************************************************************************/ -/********************************************************************************************/ - -bool p3PostedServiceVEG::generateDummyData() -{ -#define MAX_GROUPS 10 //100 -#define MAX_POSTS 50 //1000 - -#define MAX_BASE_COMMENTS 1000 //10000 -#define MAX_COMMENTS 4000 //10000 - -#define MAX_VOTES 10000 //10000 - - std::list mGroups; - std::list::iterator git; - - std::list mPosts; - std::list::iterator pit; - - std::list mVotes; - std::list::iterator vit; - - std::list mComments; - std::list::iterator cit; - -#define DUMMY_NAME_MAX_LEN 10000 - char name[DUMMY_NAME_MAX_LEN]; - int i, j; - time_t now = time(NULL); - - for(i = 0; i < MAX_GROUPS; i++) - { - /* generate a new forum */ - RsPostedGroup group; - - snprintf(name, DUMMY_NAME_MAX_LEN, "TestTopic_%d", i+1); - - group.mMeta.mGroupId = genRandomId(); - group.mMeta.mGroupName = name; - - group.mMeta.mPublishTs = now - (RSRandom::random_f32() * 100000); - /* key fields to fill in: - * GroupId. - * Name. - * Flags. - * Pop. - */ - - - - /* use probability to decide which are subscribed / own / popularity. - */ - - float rnd = RSRandom::random_f32(); - if (rnd < 0.1) - { - group.mMeta.mSubscribeFlags = RSGXS_GROUP_SUBSCRIBE_ADMIN | RSGXS_GROUP_SUBSCRIBE_SUBSCRIBED; - - } - else if (rnd < 0.3) - { - group.mMeta.mSubscribeFlags = RSGXS_GROUP_SUBSCRIBE_SUBSCRIBED; - } - else - { - group.mMeta.mSubscribeFlags = 0; - } - - group.mMeta.mPop = (int) (RSRandom::random_f32() * 10.0); - mGroups.push_back(group); - - } - - for(i = 0; i < MAX_POSTS; i++) - { - /* generate a base thread */ - - /* rotate the Forum Groups Around, then pick one. - */ - - int rnd = (int) (RSRandom::random_f32() * 10.0); - - for(j = 0; j < rnd; j++) - { - RsPostedGroup head = mGroups.front(); - mGroups.pop_front(); - mGroups.push_back(head); - } - - RsPostedGroup group = mGroups.front(); - - /* now create a new thread */ - - RsPostedPost post; - - snprintf(name, DUMMY_NAME_MAX_LEN, "%s => Post_%d", group.mMeta.mGroupName.c_str(), i+1); - post.mMeta.mMsgName = name; - - post.mMeta.mGroupId = group.mMeta.mGroupId; - post.mMeta.mMsgId = genRandomId(); - post.mMeta.mOrigMsgId = post.mMeta.mMsgId; - post.mMeta.mThreadId = post.mMeta.mMsgId; - post.mMeta.mParentId = ""; - - post.mMeta.mPublishTs = group.mMeta.mPublishTs + (RSRandom::random_f32() * 10000); - if (post.mMeta.mPublishTs > now) - post.mMeta.mPublishTs = now - 1; - - mPosts.push_back(post); - - } - - for(i = 0; i < MAX_BASE_COMMENTS; i++) - { - /* generate a base thread */ - - /* rotate the Forum Groups Around, then pick one. - */ - - int rnd = (int) (RSRandom::random_f32() * 10.0); - - for(j = 0; j < rnd; j++) - { - RsPostedPost head = mPosts.front(); - mPosts.pop_front(); - mPosts.push_back(head); - } - - RsPostedPost parent = mPosts.front(); - - /* now create a new child msg */ - - RsPostedComment comment; - - /* fill in key data - * GroupId - * MsgId - * OrigMsgId - * ThreadId - * ParentId - * PublishTS (take Forum TS + a bit ). - * - * ChildTS ???? - */ - snprintf(name, DUMMY_NAME_MAX_LEN, "%s => Comment_%d", parent.mMeta.mMsgName.c_str(), i+1); - comment.mMeta.mMsgName = name; - //comment.mMsg = name; - - comment.mMeta.mGroupId = parent.mMeta.mGroupId; - comment.mMeta.mMsgId = genRandomId(); - comment.mMeta.mOrigMsgId = comment.mMeta.mMsgId; - comment.mMeta.mThreadId = parent.mMeta.mThreadId; - comment.mMeta.mParentId = parent.mMeta.mOrigMsgId; - - comment.mMeta.mPublishTs = parent.mMeta.mPublishTs + (RSRandom::random_f32() * 10000); - if (comment.mMeta.mPublishTs > now) - comment.mMeta.mPublishTs = now - 1; - - mComments.push_back(comment); - } - - - for(i = 0; i < MAX_COMMENTS; i++) - { - /* generate a base thread */ - - /* rotate the Forum Groups Around, then pick one. - */ - - int rnd = (int) (RSRandom::random_f32() * 10.0); - - for(j = 0; j < rnd; j++) - { - RsPostedComment head = mComments.front(); - mComments.pop_front(); - mComments.push_back(head); - } - - RsPostedComment parent = mComments.front(); - - /* now create a new child msg */ - - RsPostedComment comment; - - /* fill in key data - * GroupId - * MsgId - * OrigMsgId - * ThreadId - * ParentId - * PublishTS (take Forum TS + a bit ). - * - * ChildTS ???? - */ - snprintf(name, DUMMY_NAME_MAX_LEN, "%s => Comment_%d", parent.mMeta.mMsgName.c_str(), i+1); - comment.mMeta.mMsgName = name; - //comment.mMsg = name; - - comment.mMeta.mGroupId = parent.mMeta.mGroupId; - comment.mMeta.mMsgId = genRandomId(); - comment.mMeta.mOrigMsgId = comment.mMeta.mMsgId; - comment.mMeta.mThreadId = parent.mMeta.mThreadId; - comment.mMeta.mParentId = parent.mMeta.mOrigMsgId; - - comment.mMeta.mPublishTs = parent.mMeta.mPublishTs + (RSRandom::random_f32() * 10000); - if (comment.mMeta.mPublishTs > now) - comment.mMeta.mPublishTs = now - 1; - - mComments.push_back(comment); - } - - - for(i = 0; i < MAX_VOTES; i++) - { - /* generate a base thread */ - - /* rotate the Forum Groups Around, then pick one. - */ - - int rnd = (int) (RSRandom::random_f32() * 10.0); - - for(j = 0; j < rnd; j++) - { - RsPostedPost head = mPosts.front(); - mPosts.pop_front(); - mPosts.push_back(head); - } - - RsPostedPost parent = mPosts.front(); - - /* now create a new child msg */ - - RsPostedVote vote; - - snprintf(name, DUMMY_NAME_MAX_LEN, "%s => Vote_%d", parent.mMeta.mMsgName.c_str(), i+1); - vote.mMeta.mMsgName = name; - //vote.mMsg = name; - - vote.mMeta.mGroupId = parent.mMeta.mGroupId; - vote.mMeta.mMsgId = genRandomId(); - vote.mMeta.mOrigMsgId = vote.mMeta.mMsgId; - vote.mMeta.mThreadId = parent.mMeta.mThreadId; - vote.mMeta.mParentId = parent.mMeta.mOrigMsgId; - - vote.mMeta.mPublishTs = parent.mMeta.mPublishTs + (RSRandom::random_f32() * 10000); - if (vote.mMeta.mPublishTs > now) - vote.mMeta.mPublishTs = now - 1; - - mVotes.push_back(vote); - } - - - mUpdated = true; - - /* Then - at the end, we push them all into the Proxy */ - for(git = mGroups.begin(); git != mGroups.end(); git++) - { - /* pushback */ - mPostedProxy->addGroup(*git); - - } - - for(pit = mPosts.begin(); pit != mPosts.end(); pit++) - { - /* pushback */ - mPostedProxy->addPost(*pit); - } - - for(cit = mComments.begin(); cit != mComments.end(); cit++) - { - /* pushback */ -#define COMMENT_FRAC_FOR_LATER (0.70) - if (RSRandom::random_f32() > COMMENT_FRAC_FOR_LATER) - { - mPostedProxy->addComment(*cit); - } - else - { - mDummyLaterComments.push_back(*cit); - } - } - - - for(vit = mVotes.begin(); vit != mVotes.end(); vit++) - { - /* pushback */ - -#define VOTE_FRAC_FOR_LATER (0.70) - if (RSRandom::random_f32() > VOTE_FRAC_FOR_LATER) - { - mPostedProxy->addVote(*vit); - } - else - { - mDummyLaterVotes.push_back(*vit); - } - } - - return true; -} - -#define EXTRA_COMMENT_ADD (20) -#define EXTRA_VOTE_ADD (50) - -bool p3PostedServiceVEG::addExtraDummyData() -{ - std::cerr << "p3PostedServiceVEG::addExtraDummyData()"; - std::cerr << std::endl; - - int i = 0; - - std::list::iterator vit; - std::list::iterator cit; - - for(cit = mDummyLaterComments.begin(); (cit != mDummyLaterComments.end()) && (i < EXTRA_COMMENT_ADD); i++) - { - mPostedProxy->addComment(*cit); - cit = mDummyLaterComments.erase(cit); - } - - i = 0; - for(vit = mDummyLaterVotes.begin(); (vit != mDummyLaterVotes.end()) && (i < EXTRA_VOTE_ADD); i++) - { - mPostedProxy->addVote(*vit); - vit = mDummyLaterVotes.erase(vit); - } - - return true; -} - - - - -/********************************************************************************************/ -/********************************************************************************************/ -/********************************************************************************************/ -/********************************************************************************************/ -/********************************************************************************************/ - - -/* This is the part that will be kept for the final Version. - * we provide a processed view of the data... - * - * start off crude -> then make it efficient. - */ - - - -bool p3PostedServiceVEG::setViewMode(uint32_t mode) -{ - std::cerr << "p3PostedServiceVEG::setViewMode() : " << mode; - std::cerr << std::endl; - - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - - mViewMode = mode; - - return true; -} - -bool p3PostedServiceVEG::setViewPeriod(uint32_t period) -{ - std::cerr << "p3PostedServiceVEG::setViewPeriod() : " << period; - std::cerr << std::endl; - - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - - mViewPeriod = period; - - return true; -} - -bool p3PostedServiceVEG::setViewRange(uint32_t first, uint32_t count) -{ - std::cerr << "p3PostedServiceVEG::setViewRange() : " << first << " +" << count; - std::cerr << std::endl; - - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - - mViewStart = first; - mViewCount = count; - - return true; -} - -float p3PostedServiceVEG::calcPostScore(const RsMsgMetaData &meta) -{ - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - - float score = 0; - uint32_t votes = 0; - uint32_t comments = 0; - time_t now = time(NULL); - time_t age_secs = now - meta.mPublishTs; - // This is a potential problem for gaming the system... post into the future. - // Should fix this by discarding/hiding until ts valid XXX. - if (age_secs < 0) - { - age_secs = 0; - } - - if (!extractPostedCache(meta.mServiceString, votes, comments)) - { - /* no votes/comments yet */ - } - - /* this is dependent on View Mode */ - switch(mViewMode) - { - default: - case RSPOSTED_VIEWMODE_LATEST: - { - score = -age_secs; // - - break; - } - case RSPOSTED_VIEWMODE_TOP: - { - score = votes; - break; - } -// Potentially only -// This is effectively HackerNews Algorithm: which is (p-1)/(t+2)^1.5, where p is votes and t is age in hours. - case RSPOSTED_VIEWMODE_HOT: - { -#define POSTED_AGESHIFT (2.0) -#define POSTED_AGEFACTOR (3600.0) - score = votes / pow(POSTED_AGESHIFT + age_secs / POSTED_AGEFACTOR, 1.5); - break; - } -// Like HOT, but using number of Comments. - case RSPOSTED_VIEWMODE_COMMENTS: - { - score = comments / pow(POSTED_AGESHIFT + age_secs / POSTED_AGEFACTOR, 1.5); - break; - } - } - - return score; -} - -static uint32_t convertPeriodFlagToSeconds(uint32_t periodMode) -{ - float secs = 1; - switch(periodMode) - { - // Fallthrough all of them. - case RSPOSTED_PERIOD_YEAR: - secs *= 12; - case RSPOSTED_PERIOD_MONTH: - secs *= 4.3; // average ~30.4 days = 4.3 weeks. - case RSPOSTED_PERIOD_WEEK: - secs *= 7; - case RSPOSTED_PERIOD_DAY: - secs *= 24; - case RSPOSTED_PERIOD_HOUR: - secs *= 3600; - } - - return (uint32_t) secs; -} - -#define POSTED_RANKINGS_INITIAL_CHECK 1 -#define POSTED_RANKINGS_DATA_REQUEST 2 -#define POSTED_RANKINGS_NODATA 3 -#define POSTED_RANKINGS_DATA_DONE 4 - - /* Poll */ -uint32_t p3PostedServiceVEG::requestStatus(const uint32_t token) -{ - std::cerr << "p3PostedServiceVEG::requestStatus() Token: " << token; - std::cerr << std::endl; - - uint32_t status; - uint32_t reqtype; - uint32_t anstype; - time_t ts; - - uint32_t int_token = token; - - { - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - if ((mProcessingRanking) && (token == mRankingExternalToken)) - { - std::cerr << "p3PostedServiceVEG::requestStatus() is RankingToken"; - std::cerr << std::endl; - - { - switch(mRankingState) - { - case POSTED_RANKINGS_INITIAL_CHECK: - status = GXS_REQUEST_STATUS_PENDING; - std::cerr << "p3PostedServiceVEG::requestStatus() RANKING PENDING"; - std::cerr << std::endl; - return status; - break; - case POSTED_RANKINGS_NODATA: - status = GXS_REQUEST_STATUS_COMPLETE; - std::cerr << "p3PostedServiceVEG::requestStatus() RANKING RETURNED NO DATA"; - std::cerr << std::endl; - return status; - break; - case POSTED_RANKINGS_DATA_REQUEST: - // Switch to real token. - int_token = mRankingInternalToken; - std::cerr << "p3PostedServiceVEG::requestStatus() Flipping to Int Token: " << int_token; - std::cerr << std::endl; - break; - - } - } - } - } - - checkRequestStatus(int_token, status, reqtype, anstype, ts); - - return status; -} - -bool p3PostedServiceVEG::getRankedPost(const uint32_t &token, RsPostedPost &post) -{ - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - if (!mProcessingRanking) - { - - std::cerr << "p3PostedServiceVEG::getRankedPost() ERROR not processing"; - std::cerr << std::endl; - return false; - } - - if (token != mRankingExternalToken) - { - std::cerr << "p3PostedServiceVEG::getRankedPost() ERROR wrong token"; - std::cerr << std::endl; - - return false; - } - - if (mRankingState == POSTED_RANKINGS_NODATA) - { - std::cerr << "p3PostedServiceVEG::getRankedPost() No Data for this request - sorry"; - std::cerr << std::endl; - - /* clean up */ - mProcessingRanking = false; - mRankingExternalToken = 0; - mRankingInternalToken = 0; - mRankingState = POSTED_RANKINGS_DATA_DONE; - - return false; - } - - if (mRankingState != POSTED_RANKINGS_DATA_REQUEST) - { - - std::cerr << "p3PostedServiceVEG::getRankedPost() ERROR wrong state"; - std::cerr << std::endl; - - return false; - - } - - - if (!getPost(mRankingInternalToken, post)) - { - std::cerr << "p3PostedServiceVEG::getRankedPost() End of Posts for this token"; - std::cerr << std::endl; - - /* clean up */ - mProcessingRanking = false; - mRankingExternalToken = 0; - mRankingInternalToken = 0; - mRankingState = POSTED_RANKINGS_DATA_DONE; - - return false; - } - - std::cerr << "p3PostedServiceVEG::getRankedPost() Got Post"; - std::cerr << std::endl; - - return true; -} - - -bool p3PostedServiceVEG::requestRanking(uint32_t &token, std::string groupId) -{ - std::cerr << "p3PostedServiceVEG::requestRanking()"; - std::cerr << std::endl; - { - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - if (mProcessingRanking) - { - std::cerr << "p3PostedServiceVEG::requestRanking() ERROR Request already running - ignoring"; - std::cerr << std::endl; - - return false; - } - } - - generateToken(token); - - { - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - mProcessingRanking = true; - mRankingState = POSTED_RANKINGS_INITIAL_CHECK; - mRankingExternalToken = token; - } - - /* now we request all the posts within the timeframe */ - - uint32_t posttoken; - uint32_t ansType = RS_TOKREQ_ANSTYPE_SUMMARY; - RsTokReqOptionsVEG opts; - - opts.mOptions = RS_TOKREQOPT_MSG_THREAD | RS_TOKREQOPT_MSG_LATEST; - //uint32_t age = convertPeriodFlagToSeconds(mViewPeriod); - - std::list groupIds; - groupIds.push_back(groupId); - - requestMsgInfo(posttoken, ansType, opts, groupIds); - - { - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - std::cerr << "p3PostedServiceVEG::requestRanking() Saved Internal Token: " << posttoken; - std::cerr << std::endl; - mRankingInternalToken = posttoken; - } - return true; -} - -bool p3PostedServiceVEG::checkRankingRequest() -{ - uint32_t token = 0; - { - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - if (!mProcessingRanking) - { - //std::cerr << "p3PostedServiceVEG::checkRankingRequest() Not Processing"; - //std::cerr << std::endl; - return false; - } - - if (mRankingState != POSTED_RANKINGS_INITIAL_CHECK) - { - std::cerr << "p3PostedServiceVEG::checkRankingRequest() Not in Initial Check"; - std::cerr << std::endl; - return false; - } - - /* here it actually running! */ - token = mRankingInternalToken; - - std::cerr << "p3PostedServiceVEG::checkRankingRequest() Running with token: " << token; - std::cerr << std::endl; - } - - - uint32_t status; - uint32_t reqtype; - uint32_t anstype; - time_t ts; - if (checkRequestStatus(token, status, reqtype, anstype, ts)) - { - std::cerr << "p3PostedServiceVEG::checkRankingRequest() checkRequestStatus => OK"; - std::cerr << std::endl; - } - else - { - std::cerr << "p3PostedServiceVEG::checkRankingRequest() checkRequestStatus => ERROR"; - std::cerr << std::endl; - return false; - } - - if (status == GXS_REQUEST_STATUS_COMPLETE) - { - std::cerr << "p3PostedServiceVEG::checkRankingRequest() Init Complete => processPosts"; - std::cerr << std::endl; - - processPosts(); - } - return true; -} - - -bool p3PostedServiceVEG::processPosts() -{ - std::cerr << "p3PostedServiceVEG::processPosts()"; - std::cerr << std::endl; - - uint32_t token = 0; - { - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - if (!mProcessingRanking) - { - std::cerr << "p3PostedServiceVEG::processPosts() ERROR Ranking Request not running"; - std::cerr << std::endl; - - return false; - } - - if (mRankingState != POSTED_RANKINGS_INITIAL_CHECK) - { - std::cerr << "p3PostedServiceVEG::processPosts() ERROR Ranking Request not running"; - std::cerr << std::endl; - - return false; - } - token = mRankingInternalToken; - } - - /* extract the info -> and sort */ - std::list postList; - std::list::const_iterator it; - - if (!getMsgSummary(token, postList)) - { - std::cerr << "p3PostedServiceVEG::processPosts() No Data for Request"; - std::cerr << std::endl; - - /* put it into a state, where the GUI will get to read an empty Queue */ - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - mRankingState = POSTED_RANKINGS_NODATA; - - return false; - } - - std::multimap postMap; - std::multimap::reverse_iterator mit; - - for(it = postList.begin(); it != postList.end(); it++) - { - float score = calcPostScore(*it); - postMap.insert(std::make_pair(score, it->mMsgId)); - } - - /* now grab the N required, and request the data again... - * -> this is what will be passed back to GUI - */ - - std::list msgList; - - { - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - - unsigned int i = 0; - for(mit = postMap.rbegin(); (mit != postMap.rend()) && (i < mViewStart); mit++, i++) - { - std::cerr << "p3PostedServiceVEG::processPosts() Skipping PostId: " << mit->second; - std::cerr << " with score: " << mit->first; - std::cerr << std::endl; - } - - - for(i = 0; (mit != postMap.rend()) && (i < mViewCount); mit++, i++) - { - std::cerr << "p3PostedServiceVEG::processPosts() Adding PostId: " << mit->second; - std::cerr << " with score: " << mit->first; - std::cerr << std::endl; - msgList.push_back(mit->second); - } - } - - token = 0; - uint32_t ansType = RS_TOKREQ_ANSTYPE_DATA; - RsTokReqOptionsVEG opts; - - requestMsgRelatedInfo(token, ansType, opts, msgList); - - { - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - mRankingState = POSTED_RANKINGS_DATA_REQUEST; - mRankingInternalToken = token; - - std::cerr << "p3PostedServiceVEG::processPosts() Second Stage: token: " << token; - std::cerr << std::endl; - } - return true; -} - - - - - - - - -/***** Background Processing **** - * - * Process Each Message - as it arrives. - * - * Update - * - */ - -#define POSTED_BG_REQUEST_GROUPS 1 -#define POSTED_BG_REQUEST_UNPROCESSED 2 -#define POSTED_BG_REQUEST_PARENTS 3 -#define POSTED_BG_PROCESS_VOTES 4 - -bool p3PostedServiceVEG::background_checkTokenRequest() -{ - uint32_t token = 0; - uint32_t phase = 0; - { - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - if (!mBgProcessing) - { - return false; - } - - token = mBgToken; - phase = mBgPhase; - } - - - uint32_t status; - uint32_t reqtype; - uint32_t anstype; - time_t ts; - checkRequestStatus(token, status, reqtype, anstype, ts); - - if (status == GXS_REQUEST_STATUS_COMPLETE) - { - switch(phase) - { - case POSTED_BG_REQUEST_GROUPS: - background_requestNewMessages(); - break; - case POSTED_BG_REQUEST_UNPROCESSED: - background_processNewMessages(); - break; - case POSTED_BG_REQUEST_PARENTS: - background_updateVoteCounts(); - break; - default: - break; - } - } - return true; -} - - -bool p3PostedServiceVEG::background_requestGroups() -{ - std::cerr << "p3PostedServiceVEG::background_requestGroups()"; - std::cerr << std::endl; - - // grab all the subscribed groups. - uint32_t token = 0; - - { - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - - mBgProcessing = true; - mBgPhase = POSTED_BG_REQUEST_GROUPS; - mBgToken = 0; - } - - uint32_t ansType = RS_TOKREQ_ANSTYPE_LIST; - RsTokReqOptionsVEG opts; - std::list groupIds; - - opts.mSubscribeFilter = RSGXS_GROUP_SUBSCRIBE_SUBSCRIBED; - - requestGroupInfo(token, ansType, opts, groupIds); - { - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - mBgToken = token; - } - - return true; -} - - -bool p3PostedServiceVEG::background_requestNewMessages() -{ - std::cerr << "p3PostedServiceVEG::background_requestNewMessages()"; - std::cerr << std::endl; - - std::list groupIds; - uint32_t token = 0; - - { - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - token = mBgToken; - } - - if (!getGroupList(token, groupIds)) - { - std::cerr << "p3PostedServiceVEG::background_requestNewMessages() ERROR No Group List"; - std::cerr << std::endl; - background_cleanup(); - return false; - } - - { - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - mBgPhase = POSTED_BG_REQUEST_UNPROCESSED; - mBgToken = 0; - } - - uint32_t ansType = RS_TOKREQ_ANSTYPE_SUMMARY; - RsTokReqOptionsVEG opts; - token = 0; - - opts.mStatusFilter = RSGXS_MSG_STATUS_UNPROCESSED; - opts.mStatusMask = RSGXS_MSG_STATUS_UNPROCESSED; - - requestMsgInfo(token, ansType, opts, groupIds); - - { - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - mBgToken = token; - } - return true; -} - - -bool p3PostedServiceVEG::background_processNewMessages() -{ - std::cerr << "p3PostedServiceVEG::background_processNewMessages()"; - std::cerr << std::endl; - - std::list newMsgList; - std::list::iterator it; - uint32_t token = 0; - - { - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - token = mBgToken; - } - - if (!getMsgSummary(token, newMsgList)) - { - std::cerr << "p3PostedServiceVEG::background_processNewMessages() ERROR No New Msgs"; - std::cerr << std::endl; - background_cleanup(); - return false; - } - - { - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - mBgPhase = POSTED_BG_REQUEST_PARENTS; - mBgToken = 0; - mBgVoteMap.clear(); - mBgCommentMap.clear(); - } - - /* loop through and sort by parents. - * - grab - */ - - std::list parentList; - - std::map::iterator vit; - - for(it = newMsgList.begin(); it != newMsgList.end(); it++) - { - std::cerr << "Found New MsgId: " << it->mMsgId; - std::cerr << std::endl; - - /* discard threadheads */ - if (it->mParentId.empty()) - { - std::cerr << "\tIgnoring ThreadHead: " << *it; - std::cerr << std::endl; - } - else if (it->mMsgFlags & RSPOSTED_MSGTYPE_COMMENT) - { - /* Comments are counted by Thread Id */ - std::cerr << "\tProcessing Comment: " << *it; - std::cerr << std::endl; - - vit = mBgCommentMap.find(it->mThreadId); - if (vit == mBgCommentMap.end()) - { - mBgCommentMap[it->mThreadId] = 1; - - /* check VoteMap too before adding to parentList */ - if (mBgVoteMap.end() == mBgVoteMap.find(it->mThreadId)) - { - parentList.push_back(it->mThreadId); - } - - std::cerr << "\tThreadId: " << it->mThreadId; - std::cerr << " Comment Total: " << mBgCommentMap[it->mThreadId]; - std::cerr << std::endl; - } - else - { - mBgVoteMap[it->mThreadId]++; - std::cerr << "\tThreadId: " << it->mThreadId; - std::cerr << " Comment Total: " << mBgCommentMap[it->mThreadId]; - std::cerr << std::endl; - } - } - else if (it->mMsgFlags & RSPOSTED_MSGTYPE_VOTE) - { - /* Votes are organised by Parent Id, - * ie. you can vote for both Posts and Comments - */ - std::cerr << "\tProcessing Vote: " << *it; - std::cerr << std::endl; - - vit = mBgVoteMap.find(it->mParentId); - if (vit == mBgVoteMap.end()) - { - mBgVoteMap[it->mParentId] = 1; - - /* check CommentMap too before adding to parentList */ - if (mBgCommentMap.end() == mBgCommentMap.find(it->mParentId)) - { - parentList.push_back(it->mParentId); - } - - std::cerr << "\tParentId: " << it->mParentId; - std::cerr << " Vote Total: " << mBgVoteMap[it->mParentId]; - std::cerr << std::endl; - } - else - { - mBgVoteMap[it->mParentId]++; - std::cerr << "\tParentId: " << it->mParentId; - std::cerr << " Vote Total: " << mBgVoteMap[it->mParentId]; - std::cerr << std::endl; - } - } - else - { - /* unknown! */ - std::cerr << "p3PostedServiceVEG::background_processNewMessages() ERROR Strange NEW Message:"; - std::cerr << std::endl; - std::cerr << "\t" << *it; - std::cerr << std::endl; - - } - - /* flag each new vote as processed */ - setMessageStatus(it->mMsgId, 0, RSGXS_MSG_STATUS_UNPROCESSED); - } - - - /* request the summary info from the parents */ - uint32_t ansType = RS_TOKREQ_ANSTYPE_SUMMARY; - token = 0; - RsTokReqOptionsVEG opts; - requestMsgRelatedInfo(token, ansType, opts, parentList); - - { - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - mBgToken = token; - } - return true; -} - - -bool p3PostedServiceVEG::encodePostedCache(std::string &str, uint32_t votes, uint32_t comments) -{ - char line[RSGXS_MAX_SERVICE_STRING]; - - snprintf(line, RSGXS_MAX_SERVICE_STRING, "%d %d", votes, comments); - - str = line; - return true; -} - -bool p3PostedServiceVEG::extractPostedCache(const std::string &str, uint32_t &votes, uint32_t &comments) -{ - - uint32_t ivotes, icomments; - if (2 == sscanf(str.c_str(), "%d %d", &ivotes, &icomments)) - { - votes = ivotes; - comments = icomments; - return true; - } - - return false; -} - - -bool p3PostedServiceVEG::background_updateVoteCounts() -{ - std::cerr << "p3PostedServiceVEG::background_updateVoteCounts()"; - std::cerr << std::endl; - - std::list parentMsgList; - std::list::iterator it; - - if (!getMsgSummary(mBgToken, parentMsgList)) - { - std::cerr << "p3PostedServiceVEG::background_updateVoteCounts() ERROR"; - std::cerr << std::endl; - background_cleanup(); - return false; - } - - { - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - mBgPhase = POSTED_BG_PROCESS_VOTES; - mBgToken = 0; - } - - for(it = parentMsgList.begin(); it != parentMsgList.end(); it++) - { - /* extract current vote count */ - uint32_t votes = 0; - uint32_t comments = 0; - - if (!extractPostedCache(it->mServiceString, votes, comments)) - { - if (!(it->mServiceString.empty())) - { - std::cerr << "p3PostedServiceVEG::background_updateVoteCounts() Failed to extract Votes"; - std::cerr << std::endl; - std::cerr << "\tFrom String: " << it->mServiceString; - std::cerr << std::endl; - } - } - - /* find increment in votemap */ - { - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - - std::map::iterator vit; - vit = mBgVoteMap.find(it->mMsgId); - if (vit != mBgVoteMap.end()) - { - votes += vit->second; - } - else - { - // warning. - std::cerr << "p3PostedServiceVEG::background_updateVoteCounts() Warning No New Votes found."; - std::cerr << " For MsgId: " << it->mMsgId; - std::cerr << std::endl; - } - - } - - { - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - - std::map::iterator cit; - cit = mBgCommentMap.find(it->mMsgId); - if (cit != mBgCommentMap.end()) - { - comments += cit->second; - } - else - { - // warning. - std::cerr << "p3PostedServiceVEG::background_updateVoteCounts() Warning No New Comments found."; - std::cerr << " For MsgId: " << it->mMsgId; - std::cerr << std::endl; - } - - } - - std::string str; - if (!encodePostedCache(str, votes, comments)) - { - std::cerr << "p3PostedServiceVEG::background_updateVoteCounts() Failed to encode Votes"; - std::cerr << std::endl; - } - else - { - std::cerr << "p3PostedServiceVEG::background_updateVoteCounts() Encoded String: " << str; - std::cerr << std::endl; - /* store new result */ - setMessageServiceString(it->mMsgId, str); - } - } - - // DONE!. - background_cleanup(); - return true; - -} - - -bool p3PostedServiceVEG::background_cleanup() -{ - std::cerr << "p3PostedServiceVEG::background_cleanup()"; - std::cerr << std::endl; - - RsStackMutex stack(mPostedMtx); /********** STACK LOCKED MTX ******/ - - // Cleanup. - mBgVoteMap.clear(); - mBgCommentMap.clear(); - mBgProcessing = false; - mBgToken = 0; - - return true; -} - - diff --git a/libretroshare/src/services/p3postedVEG.h b/libretroshare/src/services/p3postedVEG.h deleted file mode 100644 index f48bee9d0..000000000 --- a/libretroshare/src/services/p3postedVEG.h +++ /dev/null @@ -1,190 +0,0 @@ -/* - * libretroshare/src/services: p3posted.h - * - * 3P/PQI network interface for RetroShare. - * - * Copyright 2012-2012 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_POSTED_SERVICE_VEG_HEADER -#define P3_POSTED_SERVICE_VEG_HEADER - -#include "services/p3gxsserviceVEG.h" -#include "retroshare/rspostedVEG.h" - -#include -#include - -/* - * Posted Service - * - */ - - -class PostedDataProxy: public GxsDataProxyVEG -{ - public: - - bool addGroup(const RsPostedGroup &group); - bool addPost(const RsPostedPost &post); - bool addVote(const RsPostedVote &vote); - bool addComment(const RsPostedComment &comment); - - bool getGroup(const std::string &id, RsPostedGroup &group); - bool getPost(const std::string &id, RsPostedPost &post); - bool getVote(const std::string &id, RsPostedVote &vote); - bool getComment(const std::string &id, RsPostedComment &comment); - - /* These Functions must be overloaded to complete the service */ -virtual bool convertGroupToMetaData(void *groupData, RsGroupMetaData &meta); -virtual bool convertMsgToMetaData(void *groupData, RsMsgMetaData &meta); - -}; - - - -class p3PostedServiceVEG: public p3GxsDataServiceVEG, public RsPostedVEG -{ - public: - - p3PostedServiceVEG(uint16_t type); - -virtual int tick(); - - public: - -// NEW INTERFACE. -/************* Extern Interface *******/ - -virtual bool updated(); - - /* Data Requests */ -virtual bool requestGroupInfo( uint32_t &token, uint32_t ansType, const RsTokReqOptionsVEG &opts, const std::list &groupIds); -virtual bool requestMsgInfo( uint32_t &token, uint32_t ansType, const RsTokReqOptionsVEG &opts, const std::list &groupIds); -virtual bool requestMsgRelatedInfo(uint32_t &token, uint32_t ansType, const RsTokReqOptionsVEG &opts, const std::list &msgIds); - - /* Generic Lists */ -virtual bool getGroupList( const uint32_t &token, std::list &groupIds); -virtual bool getMsgList( const uint32_t &token, std::list &msgIds); - - /* Generic Summary */ -virtual bool getGroupSummary( const uint32_t &token, std::list &groupInfo); -virtual bool getMsgSummary( const uint32_t &token, std::list &msgInfo); - - /* Actual Data -> specific to Interface */ - /* Specific Service Data */ -virtual bool getGroup(const uint32_t &token, RsPostedGroup &group); -virtual bool getPost(const uint32_t &token, RsPostedPost &post); -virtual bool getComment(const uint32_t &token, RsPostedComment &comment); - - - /* Poll */ -virtual uint32_t requestStatus(const uint32_t token); - - /* Cancel Request */ -virtual bool cancelRequest(const uint32_t &token); - - ////////////////////////////////////////////////////////////////////////////// -virtual bool setMessageStatus(const std::string &msgId, const uint32_t status, const uint32_t statusMask); -virtual bool setGroupStatus(const std::string &groupId, const uint32_t status, const uint32_t statusMask); -virtual bool setGroupSubscribeFlags(const std::string &groupId, uint32_t subscribeFlags, uint32_t subscribeMask); -virtual bool setMessageServiceString(const std::string &msgId, const std::string &str); -virtual bool setGroupServiceString(const std::string &grpId, const std::string &str); - -virtual bool groupRestoreKeys(const std::string &groupId); -virtual bool groupShareKeys(const std::string &groupId, std::list& peers); - -virtual bool submitGroup(uint32_t &token, RsPostedGroup &group, bool isNew); -virtual bool submitPost(uint32_t &token, RsPostedPost &post, bool isNew); -virtual bool submitVote(uint32_t &token, RsPostedVote &vote, bool isNew); -virtual bool submitComment(uint32_t &token, RsPostedComment &comment, bool isNew); - - // Extended Interface for Collated Data View. -virtual bool setViewMode(uint32_t mode); -virtual bool setViewPeriod(uint32_t period); -virtual bool setViewRange(uint32_t first, uint32_t count); - -virtual bool requestRanking(uint32_t &token, std::string groupId); -virtual bool getRankedPost(const uint32_t &token, RsPostedPost &post); - - - // These are exposed for GUI usage. -virtual bool encodePostedCache(std::string &str, uint32_t votes, uint32_t comments); -virtual bool extractPostedCache(const std::string &str, uint32_t &votes, uint32_t &comments); -virtual float calcPostScore(const RsMsgMetaData &meta); - - private: - - // -bool checkRankingRequest(); -bool processPosts(); - - // background processing of Votes. - // NB: These should probably be handled by a background thread. - // At the moment they are run from the tick() thread. - -bool background_checkTokenRequest(); -bool background_requestGroups(); -bool background_requestNewMessages(); -bool background_processNewMessages(); - -bool background_updateVoteCounts(); -bool background_cleanup(); - - - -std::string genRandomId(); -bool generateDummyData(); -bool addExtraDummyData(); - - PostedDataProxy *mPostedProxy; - - RsMutex mPostedMtx; - bool mUpdated; - - // Ranking view mode, stored here. - uint32_t mViewMode; - uint32_t mViewPeriod; - uint32_t mViewStart; - uint32_t mViewCount; - - // Processing Ranking stuff. - bool mProcessingRanking; - uint32_t mRankingState; - uint32_t mRankingExternalToken; - uint32_t mRankingInternalToken; - - // background processing - Mutex protected. - time_t mLastBgCheck; - bool mBgProcessing; - uint32_t mBgPhase; - uint32_t mBgToken; - - std::map mBgVoteMap; // ParentId -> Vote Count. - std::map mBgCommentMap; // ThreadId -> Comment Count. - - // extra dummy data. - std::list mDummyLaterVotes; - std::list mDummyLaterComments; - - -}; - -#endif diff --git a/libretroshare/src/services/p3wiki.cc b/libretroshare/src/services/p3wiki.cc index 2390a4254..e20dc4f17 100644 --- a/libretroshare/src/services/p3wiki.cc +++ b/libretroshare/src/services/p3wiki.cc @@ -504,7 +504,7 @@ std::string chooseRandomAuthorId() uint32_t idx = (uint32_t) (ownIds.size() * RSRandom::random_f32()); int i = 0; - for(it = ownIds.begin(); (it != ownIds.end()) && (i < idx); it++, i++); + for(it = ownIds.begin(); (it != ownIds.end()) && (i < idx); it++, i++) ; std::string answer; if (it != ownIds.end()) From bb0d02f3dc78fad9230b9bfe6a94538005e0f394 Mon Sep 17 00:00:00 2001 From: thunder2 Date: Wed, 22 Jan 2014 22:31:42 +0000 Subject: [PATCH 80/83] Fixed compile on Windows. git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@7052 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/rsserver/rsaccounts.cc | 16 +++++++--------- libretroshare/src/util/rsrecogn.cc | 4 ++++ 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/libretroshare/src/rsserver/rsaccounts.cc b/libretroshare/src/rsserver/rsaccounts.cc index d3306757a..71e24bb28 100644 --- a/libretroshare/src/rsserver/rsaccounts.cc +++ b/libretroshare/src/rsserver/rsaccounts.cc @@ -30,6 +30,10 @@ * */ +#ifdef WINDOWS_SYS +#include "util/rswin.h" +#endif // WINDOWS_SYS + #include #include @@ -307,7 +311,7 @@ bool RsAccountsDetail::defaultBaseDirectory() basedir += "/.retroshare6"; #else - if (RsInitConfig::portable) + if (RsInit::isPortable()) { // use directory "Data" in portable version basedir = "Data"; @@ -866,14 +870,8 @@ bool RsAccountsDetail::copyGnuPGKeyrings() std::string source_secret_keyring; #ifdef WINDOWS_SYS - if (RsInit::isPortable()) - { - source_public_keyring = RsInit::RsConfigDirectory() + "/gnupg/pubring.gpg"; - source_secret_keyring = RsInit::RsConfigDirectory() + "/gnupg/secring.gpg" ; - } else { - source_public_keyring = RsInitConfig::basedir + "/../gnupg/pubring.gpg" ; - source_secret_keyring = RsInitConfig::basedir + "/../gnupg/secring.gpg" ; - } + source_public_keyring = mBaseDirectory + "/gnupg/pubring.gpg"; + source_secret_keyring = mBaseDirectory + "/gnupg/secring.gpg" ; #else char *env_gnupghome = getenv("GNUPGHOME") ; diff --git a/libretroshare/src/util/rsrecogn.cc b/libretroshare/src/util/rsrecogn.cc index 19c189c6b..74ca4cae2 100644 --- a/libretroshare/src/util/rsrecogn.cc +++ b/libretroshare/src/util/rsrecogn.cc @@ -23,6 +23,10 @@ * */ +#ifdef WINDOWS_SYS +#include "util/rswin.h" +#endif // WINDOWS_SYS + #include #include From 3b71e8e140a211e98cea084343e7c0b7dffc80ba Mon Sep 17 00:00:00 2001 From: drbob Date: Tue, 28 Jan 2014 07:57:58 +0000 Subject: [PATCH 81/83] Improvements to enable Edit/Show of GxsGroups. NB: The actual update doesn't happen yet - mainly just the display of info. - Fixed up Constructor, and loading of MetaData via TokenService. - Fixed up Enabled / ReadOnly for Show. - Updated children to match new functionality. - Fixed up Show in Circles Dialog too. - removed a few compile errors. git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@7062 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- .../src/gui/Circles/CirclesDialog.cpp | 16 +- .../src/gui/Circles/CreateCircleDialog.cpp | 150 ++++++++--- .../src/gui/Circles/CreateCircleDialog.h | 6 + .../src/gui/Posted/PostedGroupDialog.cpp | 17 +- .../src/gui/Posted/PostedGroupDialog.h | 3 +- .../src/gui/Posted/PostedListDialog.cpp | 4 +- .../src/gui/chat/ChatLobbyDialog.cpp | 4 +- .../src/gui/gxs/GxsCircleChooser.cpp | 17 +- retroshare-gui/src/gui/gxs/GxsCircleChooser.h | 4 +- retroshare-gui/src/gui/gxs/GxsGroupDialog.cpp | 235 ++++++++++++++++-- retroshare-gui/src/gui/gxs/GxsGroupDialog.h | 45 ++-- retroshare-gui/src/gui/gxs/GxsIdChooser.h | 1 + .../src/gui/gxs/WikiGroupDialog.cpp | 76 ++---- retroshare-gui/src/gui/gxs/WikiGroupDialog.h | 3 +- .../gui/gxschannels/GxsChannelGroupDialog.cpp | 22 +- .../gui/gxschannels/GxsChannelGroupDialog.h | 4 +- .../src/gui/gxsforums/GxsForumGroupDialog.cpp | 59 ++++- .../src/gui/gxsforums/GxsForumGroupDialog.h | 5 +- .../src/gui/gxsforums/GxsForumsDialog.cpp | 7 +- 19 files changed, 506 insertions(+), 172 deletions(-) diff --git a/retroshare-gui/src/gui/Circles/CirclesDialog.cpp b/retroshare-gui/src/gui/Circles/CirclesDialog.cpp index e10c8f5fc..886aac99a 100644 --- a/retroshare-gui/src/gui/Circles/CirclesDialog.cpp +++ b/retroshare-gui/src/gui/Circles/CirclesDialog.cpp @@ -65,7 +65,7 @@ CirclesDialog::CirclesDialog(QWidget *parent) mStateHelper->addWidget(CIRCLESDIALOG_GROUPMETA, ui.treeWidget_friends, UISTATE_ACTIVE_ENABLED); mStateHelper->addWidget(CIRCLESDIALOG_GROUPMETA, ui.treeWidget_category, UISTATE_ACTIVE_ENABLED); - mStateHelper->setWidgetEnabled(ui.pushButton_editCircle, false); // not implemented + mStateHelper->setWidgetEnabled(ui.pushButton_editCircle, false); /* Connect signals */ connect(ui.pushButton_extCircle, SIGNAL(clicked()), this, SLOT(createExternalCircle())); @@ -113,12 +113,18 @@ void CirclesDialog::createPersonalCircle() void CirclesDialog::editExistingCircle() { -#if 0 - std::string id; + QTreeWidgetItem *item = ui.treeWidget_membership->currentItem(); + if ((!item) || (!item->parent())) + { + return; + } + + QString coltext = item->text(CIRCLEGROUP_CIRCLE_COL_GROUPID); + std::string id = coltext.toStdString(); + CreateCircleDialog dlg; dlg.editExistingId(id); dlg.exec(); -#endif } void CirclesDialog::reloadAll() @@ -349,6 +355,7 @@ void CirclesDialog::circle_selected() if ((!item) || (!item->parent())) { + mStateHelper->setWidgetEnabled(ui.pushButton_editCircle, false); return; } @@ -377,6 +384,7 @@ void CirclesDialog::circle_selected() { set_tree_background(ui.treeWidget_friends, GRAY_BACKGROUND); } + mStateHelper->setWidgetEnabled(ui.pushButton_editCircle, true); } void CirclesDialog::friend_selected() diff --git a/retroshare-gui/src/gui/Circles/CreateCircleDialog.cpp b/retroshare-gui/src/gui/Circles/CreateCircleDialog.cpp index 5c0908b49..2dfd78f2b 100644 --- a/retroshare-gui/src/gui/Circles/CreateCircleDialog.cpp +++ b/retroshare-gui/src/gui/Circles/CreateCircleDialog.cpp @@ -68,7 +68,7 @@ CreateCircleDialog::CreateCircleDialog() mIsExternalCircle = true; ui.idChooser->loadIds(0,""); - ui.circleComboBox->loadCircles(GXS_CIRCLE_CHOOSER_EXTERNAL); + ui.circleComboBox->loadCircles(GXS_CIRCLE_CHOOSER_EXTERNAL, ""); } CreateCircleDialog::~CreateCircleDialog() @@ -81,22 +81,10 @@ void CreateCircleDialog::editExistingId(std::string circleId) { /* load this circle */ mIsExistingCircle = true; - - /* setup personal or external circle */ - - bool isExternal = false; - if (isExternal) - { - setupForExternalCircle(); - } - else - { - setupForPersonalCircle(); - } - - /* lock stuff they cannot edit */ + requestCircle(circleId); } + void CreateCircleDialog::editNewId(bool isExternal) { /* load this circle */ @@ -164,7 +152,15 @@ void CreateCircleDialog::addMember() } /* check that its not there already */ - QString keyId = item->text(RSCIRCLEID_COL_KEYID); + QString keyId = item->text(RSCIRCLEID_COL_KEYID); + QString idtype = item->text(RSCIRCLEID_COL_IDTYPE); + QString nickname = item->text(RSCIRCLEID_COL_NICKNAME); + + addMember(keyId, idtype, nickname); +} + +void CreateCircleDialog::addMember(const QString& keyId, const QString& idtype, const QString& nickname ) +{ QTreeWidget *tree = ui.treeWidget_membership; int count = tree->topLevelItemCount(); @@ -180,9 +176,9 @@ void CreateCircleDialog::addMember() } QTreeWidgetItem *member = new QTreeWidgetItem(); - member->setText(RSCIRCLEID_COL_NICKNAME, item->text(RSCIRCLEID_COL_NICKNAME)); - member->setText(RSCIRCLEID_COL_KEYID, item->text(RSCIRCLEID_COL_KEYID)); - member->setText(RSCIRCLEID_COL_IDTYPE, item->text(RSCIRCLEID_COL_IDTYPE)); + member->setText(RSCIRCLEID_COL_NICKNAME, nickname); + member->setText(RSCIRCLEID_COL_KEYID, keyId); + member->setText(RSCIRCLEID_COL_IDTYPE, idtype); tree->addTopLevelItem(member); } @@ -337,6 +333,58 @@ void CreateCircleDialog::createCircle() close(); } + +void CreateCircleDialog::updateCircleGUI() +{ + std::cerr << "CreateCircleDialog::updateCircleGUI()"; + std::cerr << std::endl; + + ui.circleName->setText(QString::fromUtf8(mCircleGroup.mMeta.mGroupName.c_str())); + + bool isExternal = true; + switch(mCircleGroup.mMeta.mCircleType) + { + case GXS_CIRCLE_TYPE_LOCAL: + isExternal = false; + break; + case GXS_CIRCLE_TYPE_PUBLIC: + ui.radioButton_Public->setChecked(true); + break; + case GXS_CIRCLE_TYPE_EXT_SELF: + case GXS_CIRCLE_TYPE_EXTERNAL: + if (mCircleGroup.mMeta.mCircleId == mCircleGroup.mMeta.mGroupId) + { + ui.radioButton_Self->setChecked(true); + } + else + { + ui.radioButton_Restricted->setChecked(true); + } + + ui.circleComboBox->loadCircles(GXS_CIRCLE_CHOOSER_EXTERNAL, mCircleGroup.mMeta.mCircleId); + + break; + default: + std::cerr << "CreateCircleDialog::updateCircleGUI() INVALID mCircleType"; + std::cerr << std::endl; + break; + } + + // set preferredId. + ui.idChooser->loadIds(0,mCircleGroup.mMeta.mAuthorId); + + /* setup personal or external circle */ + if (isExternal) + { + setupForExternalCircle(); + } + else + { + setupForPersonalCircle(); + } +} + + void CreateCircleDialog::requestCircle(const RsGxsGroupId &groupId) { RsTokReqOptions opts; @@ -382,7 +430,8 @@ void CreateCircleDialog::loadCircle(uint32_t token) std::cerr << "CreateCircleDialog::loadCircle() Unfinished Loading"; std::cerr << std::endl; - //mCircleGroup = groups[0]; + mCircleGroup = groups[0]; + updateCircleGUI(); } void CreateCircleDialog::getPgpIdentities() @@ -393,24 +442,38 @@ void CreateCircleDialog::getPgpIdentities() QTreeWidget *tree = ui.treeWidget_IdList; tree->clear(); - std::list ids; std::list::iterator it; - rsPeers->getGPGAcceptedList(ids); for(it = ids.begin(); it != ids.end(); it++) { - QTreeWidgetItem *item = new QTreeWidgetItem(); RsPeerDetails details; rsPeers->getGPGDetails(*it, details); - item->setText(RSCIRCLEID_COL_IDTYPE, "PGP Identity"); - item->setText(RSCIRCLEID_COL_NICKNAME, QString::fromUtf8(details.name.c_str())); - item->setText(RSCIRCLEID_COL_KEYID, QString::fromStdString(details.gpg_id)); + QString keyId = QString::fromStdString(details.gpg_id); + QString nickname = QString::fromUtf8(details.name.c_str()); + QString idtype = tr("PGP Identity"); + QTreeWidgetItem *item = new QTreeWidgetItem(); + item->setText(RSCIRCLEID_COL_NICKNAME, nickname); + item->setText(RSCIRCLEID_COL_KEYID, keyId); + item->setText(RSCIRCLEID_COL_IDTYPE, idtype); tree->addTopLevelItem(item); + + // Local Circle. + if (mIsExistingCircle) + { + // check if its in the circle. + std::list::const_iterator it; + it = std::find(mCircleGroup.mLocalFriends.begin(), mCircleGroup.mLocalFriends.end(), details.gpg_id); + if (it != mCircleGroup.mLocalFriends.end()) + { + /* found it */ + addMember(keyId, idtype, nickname); + } + } } } @@ -477,27 +540,44 @@ void CreateCircleDialog::loadIdentities(uint32_t token) continue; } - QTreeWidgetItem *item = new QTreeWidgetItem(); - item->setText(RSCIRCLEID_COL_NICKNAME, QString::fromUtf8(data.mMeta.mGroupName.c_str())); - item->setText(RSCIRCLEID_COL_KEYID, QString::fromStdString(data.mMeta.mGroupId)); + QString keyId = QString::fromStdString(data.mMeta.mGroupId); + QString nickname = QString::fromUtf8(data.mMeta.mGroupName.c_str()); + QString idtype = tr("Anon Id"); + if (data.mMeta.mGroupFlags & RSGXSID_GROUPFLAG_REALID) { if (data.mPgpKnown) { RsPeerDetails details; rsPeers->getGPGDetails(data.mPgpId, details); - item->setText(RSCIRCLEID_COL_IDTYPE, QString::fromUtf8(details.name.c_str())); + idtype = QString::fromUtf8(details.name.c_str()); } else { - item->setText(RSCIRCLEID_COL_IDTYPE, "PGP Linked Id"); + idtype = tr("PGP Linked Id"); } } - else - { - item->setText(RSCIRCLEID_COL_IDTYPE, "Anon Id"); - } + + QTreeWidgetItem *item = new QTreeWidgetItem(); + item->setText(RSCIRCLEID_COL_NICKNAME, nickname); + item->setText(RSCIRCLEID_COL_KEYID, keyId); + item->setText(RSCIRCLEID_COL_IDTYPE, idtype); tree->addTopLevelItem(item); + + // External Circle. + if (mIsExistingCircle) + { + // check if its in the circle. + std::list::const_iterator it; + it = std::find(mCircleGroup.mInvitedMembers.begin(), + mCircleGroup.mInvitedMembers.end(), data.mMeta.mGroupId); + + if (it != mCircleGroup.mInvitedMembers.end()) + { + /* found it */ + addMember(keyId, idtype, nickname); + } + } } } diff --git a/retroshare-gui/src/gui/Circles/CreateCircleDialog.h b/retroshare-gui/src/gui/Circles/CreateCircleDialog.h index f40ae3826..dfe86e90c 100644 --- a/retroshare-gui/src/gui/Circles/CreateCircleDialog.h +++ b/retroshare-gui/src/gui/Circles/CreateCircleDialog.h @@ -54,6 +54,10 @@ private slots: void createCircle(); private: + + void updateCircleGUI(); + void addMember(const QString& keyId, const QString& idtype, const QString& nickname ); + void setupForPersonalCircle(); void setupForExternalCircle(); @@ -70,6 +74,8 @@ private: TokenQueue *mCircleQueue; TokenQueue *mIdQueue; + RsGxsCircleGroup mCircleGroup; // for editting existing Circles. + /** Qt Designer generated object */ Ui::CreateCircleDialog ui; }; diff --git a/retroshare-gui/src/gui/Posted/PostedGroupDialog.cpp b/retroshare-gui/src/gui/Posted/PostedGroupDialog.cpp index 10013dccf..6cf17e686 100644 --- a/retroshare-gui/src/gui/Posted/PostedGroupDialog.cpp +++ b/retroshare-gui/src/gui/Posted/PostedGroupDialog.cpp @@ -26,7 +26,9 @@ #include #include -const uint32_t PostedCreateEnabledFlags = ( // GXS_GROUP_FLAGS_ICON | +const uint32_t PostedCreateEnabledFlags = ( + GXS_GROUP_FLAGS_NAME | + // GXS_GROUP_FLAGS_ICON | GXS_GROUP_FLAGS_DESCRIPTION | GXS_GROUP_FLAGS_DISTRIBUTION | // GXS_GROUP_FLAGS_PUBLISHSIGN | @@ -52,13 +54,16 @@ uint32_t PostedCreateDefaultsFlags = ( GXS_GROUP_DEFAULTS_DISTRIB_PUBLIC | GXS_GROUP_DEFAULTS_COMMENTS_NO | 0); +uint32_t PostedEditEnabledFlags = PostedCreateEnabledFlags; +uint32_t PostedEditDefaultsFlags = PostedCreateDefaultsFlags; + PostedGroupDialog::PostedGroupDialog(TokenQueue *tokenQueue, QWidget *parent) :GxsGroupDialog(tokenQueue, PostedCreateEnabledFlags, PostedCreateDefaultsFlags, parent) { } -PostedGroupDialog::PostedGroupDialog(const RsPostedGroup &group, QWidget *parent) - :GxsGroupDialog(group.mMeta, MODE_SHOW, parent) +PostedGroupDialog::PostedGroupDialog(TokenQueue *tokenExternalQueue, RsTokenService *tokenService, Mode mode, RsGxsGroupId groupId, QWidget *parent) +:GxsGroupDialog(tokenExternalQueue, tokenService, mode, groupId, PostedEditEnabledFlags, PostedEditDefaultsFlags, parent) { } @@ -99,3 +104,9 @@ bool PostedGroupDialog::service_CreateGroup(uint32_t &token, const RsGroupMetaDa return true; } + +bool PostedGroupDialog::service_EditGroup(uint32_t &token, RsGxsGroupUpdateMeta &updateMeta) +{ + return false; +} + diff --git a/retroshare-gui/src/gui/Posted/PostedGroupDialog.h b/retroshare-gui/src/gui/Posted/PostedGroupDialog.h index 632da45fa..293a39fd6 100644 --- a/retroshare-gui/src/gui/Posted/PostedGroupDialog.h +++ b/retroshare-gui/src/gui/Posted/PostedGroupDialog.h @@ -33,12 +33,13 @@ class PostedGroupDialog : public GxsGroupDialog public: PostedGroupDialog(TokenQueue *tokenQueue, QWidget *parent); - PostedGroupDialog(const RsPostedGroup &topic, QWidget *parent); + PostedGroupDialog(TokenQueue *tokenExternalQueue, RsTokenService *tokenService, Mode mode, RsGxsGroupId groupId, QWidget *parent); protected: virtual void initUi(); virtual QPixmap serviceImage(); virtual bool service_CreateGroup(uint32_t &token, const RsGroupMetaData &meta); + virtual bool service_EditGroup(uint32_t &token, RsGxsGroupUpdateMeta &updateMeta); private: RsPostedGroup mTopic; diff --git a/retroshare-gui/src/gui/Posted/PostedListDialog.cpp b/retroshare-gui/src/gui/Posted/PostedListDialog.cpp index 55c0b5bcd..809c04d10 100644 --- a/retroshare-gui/src/gui/Posted/PostedListDialog.cpp +++ b/retroshare-gui/src/gui/Posted/PostedListDialog.cpp @@ -368,8 +368,8 @@ void PostedListDialog::showGroupDetails() { return; } - - PostedGroupDialog cf(mGroups[mCurrTopicId], this); + + PostedGroupDialog cf(mPostedQueue, rsPosted->getTokenService(), GxsGroupDialog::MODE_SHOW, mCurrTopicId, this); cf.exec (); } diff --git a/retroshare-gui/src/gui/chat/ChatLobbyDialog.cpp b/retroshare-gui/src/gui/chat/ChatLobbyDialog.cpp index f20837476..7fd56f068 100644 --- a/retroshare-gui/src/gui/chat/ChatLobbyDialog.cpp +++ b/retroshare-gui/src/gui/chat/ChatLobbyDialog.cpp @@ -331,7 +331,7 @@ void ChatLobbyDialog::updateParticipantsList() std::list::const_iterator it(lInfos.begin()); // Set it to the current ChatLobby - for (; it!=lInfos.end() && (*it).lobby_id != lobbyId; ++it); + for (; it!=lInfos.end() && (*it).lobby_id != lobbyId; ++it) ; if (it != lInfos.end()) { ChatLobbyInfo cliInfo=(*it); @@ -482,7 +482,7 @@ bool ChatLobbyDialog::isNicknameInLobby(const QString &nickname) { std::list::const_iterator it(linfos.begin()); // Set it to the current ChatLobby - for (; it!=linfos.end() && (*it).lobby_id != lobbyId; ++it); + for (; it!=linfos.end() && (*it).lobby_id != lobbyId; ++it) ; if (it != linfos.end()) { for (std::map::const_iterator it2((*it).nick_names.begin()); it2 != (*it).nick_names.end(); ++it2) { diff --git a/retroshare-gui/src/gui/gxs/GxsCircleChooser.cpp b/retroshare-gui/src/gui/gxs/GxsCircleChooser.cpp index 5a0f9a5e1..91e1eb968 100644 --- a/retroshare-gui/src/gui/gxs/GxsCircleChooser.cpp +++ b/retroshare-gui/src/gui/gxs/GxsCircleChooser.cpp @@ -36,9 +36,10 @@ GxsCircleChooser::GxsCircleChooser(QWidget *parent) return; } -void GxsCircleChooser::loadCircles(uint32_t chooserFlags) +void GxsCircleChooser::loadCircles(uint32_t chooserFlags, const RsGxsCircleId &defaultId) { mFlags = chooserFlags; + mDefaultCircleId = defaultId; loadGxsCircles(); } @@ -84,7 +85,9 @@ void GxsCircleChooser::loadGxsCircles() } std::list::iterator it; - for(it = ids.begin(); it != ids.end(); it++) + int i = 0; + int def = -1; + for(it = ids.begin(); it != ids.end(); it++, i++) { /* add to Chooser */ QString str; @@ -97,6 +100,16 @@ void GxsCircleChooser::loadGxsCircles() QString id = QString::fromStdString(*it); addItem(str, id); + + if (mDefaultCircleId == *it) + { + def = i; + } + } + + if (def >= 0) + { + setCurrentIndex(def); } } diff --git a/retroshare-gui/src/gui/gxs/GxsCircleChooser.h b/retroshare-gui/src/gui/gxs/GxsCircleChooser.h index 8bd7efe93..1a5f01fb3 100644 --- a/retroshare-gui/src/gui/gxs/GxsCircleChooser.h +++ b/retroshare-gui/src/gui/gxs/GxsCircleChooser.h @@ -40,12 +40,14 @@ class GxsCircleChooser : public QComboBox public: GxsCircleChooser(QWidget *parent = NULL); - void loadCircles(uint32_t chooserFlags); + void loadCircles(uint32_t chooserFlags, const RsGxsCircleId &defaultId); bool getChosenCircle(RsGxsCircleId &id); private: void loadGxsCircles(); uint32_t mFlags; + + RsGxsCircleId mDefaultCircleId; }; #endif diff --git a/retroshare-gui/src/gui/gxs/GxsGroupDialog.cpp b/retroshare-gui/src/gui/gxs/GxsGroupDialog.cpp index d3f93cc24..6e5d8528a 100644 --- a/retroshare-gui/src/gui/gxs/GxsGroupDialog.cpp +++ b/retroshare-gui/src/gui/gxs/GxsGroupDialog.cpp @@ -51,23 +51,30 @@ #define GXSGROUP_NEWGROUPID 1 #define GXSGROUP_LOADGROUP 2 +#define GXSGROUP_INTERNAL_LOADGROUP 3 /** Constructor */ -GxsGroupDialog::GxsGroupDialog(TokenQueue *tokenQueue, uint32_t enableFlags, uint16_t defaultFlags, QWidget *parent) - : QDialog(parent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint), mTokenQueue(tokenQueue), mMode(MODE_CREATE), mEnabledFlags(enableFlags), mReadonlyFlags(0), mDefaultsFlags(defaultFlags) +GxsGroupDialog::GxsGroupDialog(TokenQueue *tokenExternalQueue, uint32_t enableFlags, uint32_t defaultFlags, QWidget *parent) + : QDialog(parent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint), mTokenService(NULL), mExternalTokenQueue(tokenExternalQueue), mInternalTokenQueue(NULL), mGrpMeta(), mMode(MODE_CREATE), mEnabledFlags(enableFlags), mReadonlyFlags(0), mDefaultsFlags(defaultFlags) { /* Invoke the Qt Designer generated object setup routine */ ui.setupUi(this); + mInternalTokenQueue = NULL; + init(); } -GxsGroupDialog::GxsGroupDialog(const RsGroupMetaData &grpMeta, Mode mode, QWidget *parent) - : QDialog(parent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint), mTokenQueue(NULL), mGrpMeta(grpMeta), mMode(mode), mEnabledFlags(0), mReadonlyFlags(0), mDefaultsFlags(0) +GxsGroupDialog::GxsGroupDialog(TokenQueue *tokenExternalQueue, RsTokenService *tokenService, Mode mode, RsGxsGroupId groupId, uint32_t enableFlags, uint32_t defaultFlags, QWidget *parent) + : QDialog(parent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint), mTokenService(NULL), mExternalTokenQueue(tokenExternalQueue), mInternalTokenQueue(NULL), mGrpMeta(), mMode(mode), mEnabledFlags(enableFlags), mReadonlyFlags(0), mDefaultsFlags(defaultFlags) { /* Invoke the Qt Designer generated object setup routine */ ui.setupUi(this); + mTokenService = tokenService; + mInternalTokenQueue = new TokenQueue(tokenService, this); + mGrpMeta.mGroupId = groupId; + init(); } @@ -102,8 +109,8 @@ void GxsGroupDialog::init() /* Setup Reasonable Defaults */ ui.idChooser->loadIds(0,""); - ui.circleComboBox->loadCircles(GXS_CIRCLE_CHOOSER_EXTERNAL); - ui.localComboBox->loadCircles(GXS_CIRCLE_CHOOSER_PERSONAL); + ui.circleComboBox->loadCircles(GXS_CIRCLE_CHOOSER_EXTERNAL,""); + ui.localComboBox->loadCircles(GXS_CIRCLE_CHOOSER_PERSONAL,""); initMode(); } @@ -134,6 +141,7 @@ void GxsGroupDialog::setUiText(UiType uiType, const QString &text) void GxsGroupDialog::initMode() { + setAllReadonly(); switch (mode()) { case MODE_CREATE: @@ -146,15 +154,18 @@ void GxsGroupDialog::initMode() case MODE_SHOW: { + mReadonlyFlags = 0xffffffff; // Force all to readonly. ui.buttonBox->setStandardButtons(QDialogButtonBox::Close); + requestGroup(mGrpMeta.mGroupId); } - break; - case MODE_EDIT: - { - ui.buttonBox->setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); - ui.buttonBox->button(QDialogButtonBox::Ok)->setText(tr("Submit Group Changes")); - } - break; + break; + case MODE_EDIT: + { + ui.buttonBox->setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); + ui.buttonBox->button(QDialogButtonBox::Ok)->setText(tr("Submit Group Changes")); + requestGroup(mGrpMeta.mGroupId); + } + break; } } @@ -253,6 +264,9 @@ void GxsGroupDialog::setupDefaults() void GxsGroupDialog::setupVisibility() { + { + ui.groupName->setVisible(mEnabledFlags & GXS_GROUP_FLAGS_NAME); + } { ui.groupLogo->setVisible(mEnabledFlags & GXS_GROUP_FLAGS_ICON); ui.addLogoButton->setVisible(mEnabledFlags & GXS_GROUP_FLAGS_ICON); @@ -289,14 +303,112 @@ void GxsGroupDialog::setupVisibility() } +void GxsGroupDialog::setAllReadonly() +{ + uint32_t origReadonlyFlags = mReadonlyFlags; + mReadonlyFlags = 0xffffffff; + + setupReadonly(); + + mReadonlyFlags = origReadonlyFlags; +} + + +void GxsGroupDialog::setupReadonly() +{ + { + ui.groupName->setEnabled(!(mReadonlyFlags & GXS_GROUP_FLAGS_NAME)); + } + { + ui.groupLogo->setEnabled(!(mReadonlyFlags & GXS_GROUP_FLAGS_ICON)); + ui.addLogoButton->setEnabled(!(mReadonlyFlags & GXS_GROUP_FLAGS_ICON)); + } + + { + ui.groupDesc->setEnabled(!(mReadonlyFlags & GXS_GROUP_FLAGS_DESCRIPTION)); + ui.groupDescLabel->setEnabled(!(mReadonlyFlags & GXS_GROUP_FLAGS_DESCRIPTION)); + } + + { + ui.distribGroupBox->setEnabled(!(mReadonlyFlags & GXS_GROUP_FLAGS_DISTRIBUTION)); + } + + { + ui.publishGroupBox->setEnabled(!(mReadonlyFlags & GXS_GROUP_FLAGS_PUBLISHSIGN)); + } + + { + ui.pubKeyShare_cb->setEnabled(!(mReadonlyFlags & GXS_GROUP_FLAGS_SHAREKEYS)); + } + + { + ui.personalGroupBox->setEnabled(!(mReadonlyFlags & GXS_GROUP_FLAGS_PERSONALSIGN)); + } + + { + ui.commentGroupBox->setEnabled(!(mReadonlyFlags & GXS_GROUP_FLAGS_COMMENTS)); + } + + { + ui.extraFrame->setEnabled(!(mReadonlyFlags & GXS_GROUP_FLAGS_EXTRA)); + } +} + + void GxsGroupDialog::newGroup() { setupDefaults(); setupVisibility(); + setupReadonly(); clearForm(); } +void GxsGroupDialog::updateFromExistingMeta() +{ + std::cerr << "void GxsGroupDialog::updateFromExistingMeta()"; + std::cerr << std::endl; + + std::cerr << "void GxsGroupDialog::updateFromExistingMeta() mGrpMeta.mCircleType: "; + std::cerr << mGrpMeta.mCircleType << " Internal: " << mGrpMeta.mInternalCircle; + std::cerr << " External: " << mGrpMeta.mCircleId; + std::cerr << std::endl; + + setupDefaults(); + setupVisibility(); + setupReadonly(); + clearForm(); + + /* setup name */ + ui.groupName->setText(QString::fromUtf8(mGrpMeta.mGroupName.c_str())); + + bool isExternal = true; + switch(mGrpMeta.mCircleType) + { + case GXS_CIRCLE_TYPE_YOUREYESONLY: + ui.typeLocal->setChecked(true); + ui.localComboBox->loadCircles(GXS_CIRCLE_CHOOSER_PERSONAL, mGrpMeta.mInternalCircle); + break; + case GXS_CIRCLE_TYPE_PUBLIC: + ui.typePublic->setChecked(true); + break; + case GXS_CIRCLE_TYPE_EXTERNAL: + ui.typeGroup->setChecked(true); + ui.circleComboBox->loadCircles(GXS_CIRCLE_CHOOSER_EXTERNAL, mGrpMeta.mCircleId); + + break; + default: + std::cerr << "CreateCircleDialog::updateCircleGUI() INVALID mCircleType"; + std::cerr << std::endl; + break; + } + ui.idChooser->loadIds(0, mGrpMeta.mAuthorId); + + + updateCircleOptions(); +} + + void GxsGroupDialog::submitGroup() { std::cerr << "GxsGroupDialog::submitGroup()"; @@ -320,9 +432,9 @@ void GxsGroupDialog::submitGroup() break; case MODE_EDIT: - { + { - editGroup(); + editGroup(); } break; } @@ -337,21 +449,24 @@ void GxsGroupDialog::editGroup() if(name.isEmpty()) { - /* error message */ - QMessageBox::warning(this, "RetroShare", tr("Please add a Name"), QMessageBox::Ok, QMessageBox::Ok); - return; //Don't add a empty name!! + /* error message */ + QMessageBox::warning(this, "RetroShare", tr("Please add a Name"), QMessageBox::Ok, QMessageBox::Ok); + return; //Don't add a empty name!! } + std::cerr << "GxsGroupDialog::editGroup() Unfinished" << std::endl; +#if 0 uint32_t token; RsGxsGroupUpdateMeta updateMeta(mGrpMeta.mGroupId); updateMeta.setMetaUpdate(RsGxsGroupUpdateMeta::NAME, std::string(name.toUtf8())); if (service_EditGroup(token, updateMeta)) { - // get the Queue to handle response. - if(mTokenQueue != NULL) - mTokenQueue->queueRequest(token, TOKENREQ_GROUPINFO, RS_TOKREQ_ANSTYPE_ACK, GXSGROUP_NEWGROUPID); + // get the Queue to handle response. + if(mExternalTokenQueue != NULL) + mExternalTokenQueue->queueRequest(token, TOKENREQ_GROUPINFO, RS_TOKREQ_ANSTYPE_ACK, GXSGROUP_NEWGROUPID); } +#endif close(); } @@ -387,14 +502,18 @@ void GxsGroupDialog::createGroup() return; //Don't add with invalid circle. } + std::cerr << "void GxsGroupDialog::createGroup() meta.mCircleType: "; + std::cerr << meta.mCircleType << " Internal: " << meta.mInternalCircle; + std::cerr << " External: " << meta.mCircleId; + std::cerr << std::endl; ui.idChooser->getChosenId(meta.mAuthorId); if (service_CreateGroup(token, meta)) { // get the Queue to handle response. - if(mTokenQueue != NULL) - mTokenQueue->queueRequest(token, TOKENREQ_GROUPINFO, RS_TOKREQ_ANSTYPE_ACK, GXSGROUP_NEWGROUPID); + if(mExternalTokenQueue != NULL) + mExternalTokenQueue->queueRequest(token, TOKENREQ_GROUPINFO, RS_TOKREQ_ANSTYPE_ACK, GXSGROUP_NEWGROUPID); } close(); @@ -473,7 +592,7 @@ void GxsGroupDialog::updateCircleOptions() { if (ui.typeGroup->isChecked()) { - ui.circleComboBox->setEnabled(true); + ui.circleComboBox->setEnabled(!(mReadonlyFlags & GXS_GROUP_FLAGS_DISTRIBUTION)); ui.circleComboBox->setVisible(true); } else @@ -484,7 +603,7 @@ void GxsGroupDialog::updateCircleOptions() if (ui.typeLocal->isChecked()) { - ui.localComboBox->setEnabled(true); + ui.circleComboBox->setEnabled(!(mReadonlyFlags & GXS_GROUP_FLAGS_DISTRIBUTION)); ui.localComboBox->setVisible(true); } else @@ -585,3 +704,69 @@ void GxsGroupDialog::setShareList() this->resize(this->size().width() - ui.contactsdockWidget->size().width(), this->size().height()); } } + + + +/*********************************************************************************** + Loading Group. + ***********************************************************************************/ + +void GxsGroupDialog::requestGroup(const RsGxsGroupId &groupId) +{ + RsTokReqOptions opts; + opts.mReqType = GXS_REQUEST_TYPE_GROUP_DATA; + + std::list groupIds; + groupIds.push_back(groupId); + + std::cerr << "GxsGroupDialog::requestGroup() Requesting Group Summary(" << groupId << ")"; + std::cerr << std::endl; + + uint32_t token; + mInternalTokenQueue->requestGroupInfo(token, RS_TOKREQ_ANSTYPE_DATA, opts, groupIds, GXSGROUP_INTERNAL_LOADGROUP); +} + + +void GxsGroupDialog::loadGroup(uint32_t token) +{ + std::cerr << "GxsGroupDialog::loadGroup(" << token << ")"; + std::cerr << std::endl; + + if (service_loadGroup(token, mMode, mGrpMeta)) + { + updateFromExistingMeta(); + } +} + +bool GxsGroupDialog::service_loadGroup(uint32_t token, Mode mode, RsGroupMetaData& groupMetaData) +{ + std::cerr << "GxsGroupDialog::service_loadGroup(" << token << ") NOT IMPLEMENTED"; + std::cerr << std::endl; + return false; +} + +void GxsGroupDialog::loadRequest(const TokenQueue *queue, const TokenRequest &req) +{ + std::cerr << "GxsGroupDialog::loadRequest() UserType: " << req.mUserType; + std::cerr << std::endl; + + if (queue == mInternalTokenQueue) + { + /* now switch on req */ + switch(req.mUserType) + { + case GXSGROUP_INTERNAL_LOADGROUP: + loadGroup(req.mToken); + break; + default: + std::cerr << "GxsGroupDialog::loadGroup() UNKNOWN UserType "; + std::cerr << std::endl; + break; + } + } +} + + + + + diff --git a/retroshare-gui/src/gui/gxs/GxsGroupDialog.h b/retroshare-gui/src/gui/gxs/GxsGroupDialog.h index 35db177d0..0083e45e4 100644 --- a/retroshare-gui/src/gui/gxs/GxsGroupDialog.h +++ b/retroshare-gui/src/gui/gxs/GxsGroupDialog.h @@ -55,13 +55,14 @@ public: /*** Group flags affect what is visually enabled that gets input into the grpMeta ***/ -#define GXS_GROUP_FLAGS_ICON 0x00000001 -#define GXS_GROUP_FLAGS_DESCRIPTION 0x00000002 -#define GXS_GROUP_FLAGS_DISTRIBUTION 0x00000004 -#define GXS_GROUP_FLAGS_PUBLISHSIGN 0x00000008 -#define GXS_GROUP_FLAGS_SHAREKEYS 0x00000010 -#define GXS_GROUP_FLAGS_PERSONALSIGN 0x00000020 -#define GXS_GROUP_FLAGS_COMMENTS 0x00000040 +#define GXS_GROUP_FLAGS_NAME 0x00000001 +#define GXS_GROUP_FLAGS_ICON 0x00000002 +#define GXS_GROUP_FLAGS_DESCRIPTION 0x00000004 +#define GXS_GROUP_FLAGS_DISTRIBUTION 0x00000008 +#define GXS_GROUP_FLAGS_PUBLISHSIGN 0x00000010 +#define GXS_GROUP_FLAGS_SHAREKEYS 0x00000020 +#define GXS_GROUP_FLAGS_PERSONALSIGN 0x00000040 +#define GXS_GROUP_FLAGS_COMMENTS 0x00000080 #define GXS_GROUP_FLAGS_EXTRA 0x00000100 @@ -102,7 +103,7 @@ public: * The long term plan is perhap logic structure (i.e. code) will be moved into each GXS \n * service for better customisation of group creation, or perhaps not! */ -class GxsGroupDialog : public QDialog +class GxsGroupDialog : public QDialog, public TokenResponse { Q_OBJECT @@ -131,7 +132,7 @@ public: * @param parent The parent dialog * @param mode */ - GxsGroupDialog(TokenQueue* tokenQueue, uint32_t enableFlags, uint16_t defaultFlags, QWidget *parent = NULL); + GxsGroupDialog(TokenQueue* tokenQueue, uint32_t enableFlags, uint32_t defaultFlags, QWidget *parent = NULL); /*! * Contructs a GxsGroupDialog for display a group or editing @@ -139,10 +140,13 @@ public: * @param mode This determines whether the dialog starts in show or edit mode (Edit not supported yet) * @param parent */ - GxsGroupDialog(const RsGroupMetaData& grpMeta, Mode mode, QWidget *parent = NULL); + GxsGroupDialog(TokenQueue *tokenExternalQueue, RsTokenService *tokenService, Mode mode, RsGxsGroupId groupId, uint32_t enableFlags, uint32_t defaultFlags, QWidget *parent = NULL); uint32_t mode() { return mMode; } + // overloaded from TokenResponse + virtual void loadRequest(const TokenQueue *queue, const TokenRequest &req); + private: void newGroup(); void init(); @@ -172,11 +176,14 @@ protected: /*! * It is up to the service to do the actual group editing - * TODO: make pure virtual * @param token This should be set to the token retrieved * @param meta The deriving GXS service should set their grp meta to this value */ - virtual bool service_EditGroup(uint32_t &token, RsGxsGroupUpdateMeta &updateMeta) {} + virtual bool service_EditGroup(uint32_t &token, RsGxsGroupUpdateMeta &updateMeta) = 0; + + // To be overloaded by users. + // use Token to retrieve from service, fill in metaData. + virtual bool service_loadGroup(uint32_t token, Mode mode, RsGroupMetaData& groupMetaData); /*! * This returns a group logo from the ui \n @@ -206,6 +213,9 @@ private: void setGroupSignFlags(uint32_t signFlags); uint32_t getGroupSignFlags(); + + void setAllReadonly(); + void setupReadonly(); void setupDefaults(); void setupVisibility(); void clearForm(); @@ -214,12 +224,19 @@ private: void sendShareList(std::string forumId); void loadNewGroupId(const uint32_t &token); + // loading existing Groups. + void requestGroup(const RsGxsGroupId &groupId); + void loadGroup(uint32_t token); + void updateFromExistingMeta(); + std::list mShareList; QPixmap picture; - TokenQueue *mTokenQueue; + RsTokenService *mTokenService; + TokenQueue *mExternalTokenQueue; + TokenQueue *mInternalTokenQueue; RsGroupMetaData mGrpMeta; - uint32_t mMode; + Mode mMode; uint32_t mEnabledFlags; uint32_t mReadonlyFlags; uint32_t mDefaultsFlags; diff --git a/retroshare-gui/src/gui/gxs/GxsIdChooser.h b/retroshare-gui/src/gui/gxs/GxsIdChooser.h index 600ad6813..4afb327ba 100644 --- a/retroshare-gui/src/gui/gxs/GxsIdChooser.h +++ b/retroshare-gui/src/gui/gxs/GxsIdChooser.h @@ -39,6 +39,7 @@ public: GxsIdChooser(QWidget *parent = NULL); void loadIds(uint32_t chooserFlags, RsGxsId defId); + bool setChosenId(RsGxsId &id); bool getChosenId(RsGxsId &id); private slots: diff --git a/retroshare-gui/src/gui/gxs/WikiGroupDialog.cpp b/retroshare-gui/src/gui/gxs/WikiGroupDialog.cpp index c688ff662..bbc1fd30c 100644 --- a/retroshare-gui/src/gui/gxs/WikiGroupDialog.cpp +++ b/retroshare-gui/src/gui/gxs/WikiGroupDialog.cpp @@ -26,7 +26,9 @@ #include #include -const uint32_t WikiCreateEnabledFlags = ( // GXS_GROUP_FLAGS_ICON | +const uint32_t WikiCreateEnabledFlags = ( + GXS_GROUP_FLAGS_NAME | + // GXS_GROUP_FLAGS_ICON | GXS_GROUP_FLAGS_DESCRIPTION | GXS_GROUP_FLAGS_DISTRIBUTION | // GXS_GROUP_FLAGS_PUBLISHSIGN | @@ -52,71 +54,17 @@ uint32_t WikiCreateDefaultsFlags = ( GXS_GROUP_DEFAULTS_DISTRIB_PUBLIC | GXS_GROUP_DEFAULTS_COMMENTS_NO | 0); +uint32_t WikiEditDefaultsFlags = WikiCreateDefaultsFlags; +uint32_t WikiEditEnabledFlags = WikiCreateEnabledFlags; WikiGroupDialog::WikiGroupDialog(TokenQueue *tokenQueue, QWidget *parent) :GxsGroupDialog(tokenQueue, WikiCreateEnabledFlags, WikiCreateDefaultsFlags, parent) { - - // To start with we only have open forums - with distribution controls. -#if 0 - uint32_t enabledFlags = ( GXS_GROUP_FLAGS_ICON | - GXS_GROUP_FLAGS_DESCRIPTION | - GXS_GROUP_FLAGS_DISTRIBUTION | - // GXS_GROUP_FLAGS_PUBLISHSIGN | - GXS_GROUP_FLAGS_SHAREKEYS | - // GXS_GROUP_FLAGS_PERSONALSIGN | - // GXS_GROUP_FLAGS_COMMENTS | - 0); - - uint32_t readonlyFlags = 0; - - uint32_t defaultsFlags = ( GXS_GROUP_DEFAULTS_DISTRIB_PUBLIC | - //GXS_GROUP_DEFAULTS_DISTRIB_GROUP | - //GXS_GROUP_DEFAULTS_DISTRIB_LOCAL | - - GXS_GROUP_DEFAULTS_PUBLISH_OPEN | - //GXS_GROUP_DEFAULTS_PUBLISH_THREADS | - //GXS_GROUP_DEFAULTS_PUBLISH_REQUIRED | - //GXS_GROUP_DEFAULTS_PUBLISH_ENCRYPTED | - - //GXS_GROUP_DEFAULTS_PERSONAL_GPG | - GXS_GROUP_DEFAULTS_PERSONAL_REQUIRED | - //GXS_GROUP_DEFAULTS_PERSONAL_IFNOPUB | - - //GXS_GROUP_DEFAULTS_COMMENTS_YES | - GXS_GROUP_DEFAULTS_COMMENTS_NO | - 0); - - //setFlags(enabledFlags, readonlyFlags, defaultsFlags); - setFlags(enabledFlags, defaultsFlags); -#endif - } -WikiGroupDialog::WikiGroupDialog(const RsWikiCollection &collection, QWidget *parent) - :GxsGroupDialog(collection.mMeta, MODE_SHOW, parent) +WikiGroupDialog::WikiGroupDialog(TokenQueue *tokenExternalQueue, RsTokenService *tokenService, Mode mode, RsGxsGroupId groupId, QWidget *parent) +:GxsGroupDialog(tokenExternalQueue, tokenService, mode, groupId, WikiEditEnabledFlags, WikiEditDefaultsFlags, parent) { -#if 0 - - // To start with we only have open forums - with distribution controls. - - uint32_t enabledFlags = ( GXS_GROUP_FLAGS_ICON | - GXS_GROUP_FLAGS_DESCRIPTION | - GXS_GROUP_FLAGS_DISTRIBUTION | - GXS_GROUP_FLAGS_SHAREKEYS | - 0); - - uint32_t readonlyFlags = 0; - - uint32_t defaultsFlags = ( GXS_GROUP_DEFAULTS_DISTRIB_PUBLIC | - GXS_GROUP_DEFAULTS_PUBLISH_OPEN | - GXS_GROUP_DEFAULTS_PERSONAL_REQUIRED | - GXS_GROUP_DEFAULTS_COMMENTS_NO | - 0); - - setFlags(enabledFlags, defaultsFlags); -#endif - } void WikiGroupDialog::initUi() @@ -156,3 +104,13 @@ bool WikiGroupDialog::service_CreateGroup(uint32_t &token, const RsGroupMetaData return true; } + +bool WikiGroupDialog::service_EditGroup(uint32_t &token, RsGxsGroupUpdateMeta &updateMeta) +{ + std::cerr << "WikiGroupDialog::service_EditGroup() UNFINISHED"; + std::cerr << std::endl; + + return false; +} + + diff --git a/retroshare-gui/src/gui/gxs/WikiGroupDialog.h b/retroshare-gui/src/gui/gxs/WikiGroupDialog.h index 4699b2c17..1167d9e06 100644 --- a/retroshare-gui/src/gui/gxs/WikiGroupDialog.h +++ b/retroshare-gui/src/gui/gxs/WikiGroupDialog.h @@ -34,12 +34,13 @@ class WikiGroupDialog : public GxsGroupDialog public: WikiGroupDialog(TokenQueue *tokenQueue, QWidget *parent); - WikiGroupDialog(const RsWikiCollection &collection, QWidget *parent); + WikiGroupDialog(TokenQueue *tokenExternalQueue, RsTokenService *tokenService, Mode mode, RsGxsGroupId groupId, QWidget *parent = NULL); protected: virtual void initUi(); virtual QPixmap serviceImage(); virtual bool service_CreateGroup(uint32_t &token, const RsGroupMetaData &meta); + virtual bool service_EditGroup(uint32_t &token, RsGxsGroupUpdateMeta &updateMeta); private: diff --git a/retroshare-gui/src/gui/gxschannels/GxsChannelGroupDialog.cpp b/retroshare-gui/src/gui/gxschannels/GxsChannelGroupDialog.cpp index 6c60ddf5b..7cfdab075 100644 --- a/retroshare-gui/src/gui/gxschannels/GxsChannelGroupDialog.cpp +++ b/retroshare-gui/src/gui/gxschannels/GxsChannelGroupDialog.cpp @@ -26,7 +26,9 @@ // To start with we only have open forums - with distribution controls. -const uint32_t ChannelCreateEnabledFlags = ( GXS_GROUP_FLAGS_ICON | +const uint32_t ChannelCreateEnabledFlags = ( + GXS_GROUP_FLAGS_NAME | + GXS_GROUP_FLAGS_ICON | GXS_GROUP_FLAGS_DESCRIPTION | GXS_GROUP_FLAGS_DISTRIBUTION | // GXS_GROUP_FLAGS_PUBLISHSIGN | @@ -52,13 +54,16 @@ const uint32_t ChannelCreateDefaultsFlags = ( GXS_GROUP_DEFAULTS_DISTRIB_PUBLIC //GXS_GROUP_DEFAULTS_COMMENTS_NO | 0); +const uint32_t ChannelEditEnabledFlags = ChannelCreateEnabledFlags; +const uint32_t ChannelEditDefaultsFlags = ChannelCreateDefaultsFlags; + GxsChannelGroupDialog::GxsChannelGroupDialog(TokenQueue *tokenQueue, QWidget *parent) :GxsGroupDialog(tokenQueue, ChannelCreateEnabledFlags, ChannelCreateDefaultsFlags, parent) { } -GxsChannelGroupDialog::GxsChannelGroupDialog(const RsGxsChannelGroup &group, Mode mode, QWidget *parent) - :GxsGroupDialog(group.mMeta, mode, parent) +GxsChannelGroupDialog::GxsChannelGroupDialog(TokenQueue *tokenExternalQueue, RsTokenService *tokenService, Mode mode, RsGxsGroupId groupId, uint32_t enableFlags, uint32_t defaultFlags, QWidget *parent) +:GxsGroupDialog(tokenExternalQueue, tokenService, mode, groupId, ChannelEditEnabledFlags, ChannelEditDefaultsFlags, parent) { } @@ -96,3 +101,14 @@ bool GxsChannelGroupDialog::service_CreateGroup(uint32_t &token, const RsGroupMe rsGxsChannels->createGroup(token, grp); return true; } + + + +bool GxsChannelGroupDialog::service_EditGroup(uint32_t &token, RsGxsGroupUpdateMeta &updateMeta) +{ + std::cerr << "GxsChannelGroupDialog::service_EditGroup() UNFINISHED"; + std::cerr << std::endl; + + return false; +} + diff --git a/retroshare-gui/src/gui/gxschannels/GxsChannelGroupDialog.h b/retroshare-gui/src/gui/gxschannels/GxsChannelGroupDialog.h index f1a9d174f..748aae3b8 100644 --- a/retroshare-gui/src/gui/gxschannels/GxsChannelGroupDialog.h +++ b/retroshare-gui/src/gui/gxschannels/GxsChannelGroupDialog.h @@ -31,12 +31,14 @@ class GxsChannelGroupDialog : public GxsGroupDialog public: GxsChannelGroupDialog(TokenQueue *tokenQueue, QWidget *parent); - GxsChannelGroupDialog(const RsGxsChannelGroup &group, Mode mode, QWidget *parent); + GxsChannelGroupDialog(TokenQueue *tokenExternalQueue, RsTokenService *tokenService, Mode mode, RsGxsGroupId groupId, uint32_t enableFlags, uint32_t defaultFlags, QWidget *parent = NULL); protected: virtual void initUi(); virtual QPixmap serviceImage(); virtual bool service_CreateGroup(uint32_t &token, const RsGroupMetaData &meta); + virtual bool service_EditGroup(uint32_t &token, RsGxsGroupUpdateMeta &updateMeta); + }; #endif diff --git a/retroshare-gui/src/gui/gxsforums/GxsForumGroupDialog.cpp b/retroshare-gui/src/gui/gxsforums/GxsForumGroupDialog.cpp index 77d0611ac..e6332cbf7 100644 --- a/retroshare-gui/src/gui/gxsforums/GxsForumGroupDialog.cpp +++ b/retroshare-gui/src/gui/gxsforums/GxsForumGroupDialog.cpp @@ -26,7 +26,9 @@ // To start with we only have open forums - with distribution controls. -const uint32_t ForumCreateEnabledFlags = ( GXS_GROUP_FLAGS_ICON | +const uint32_t ForumCreateEnabledFlags = ( + GXS_GROUP_FLAGS_NAME | + GXS_GROUP_FLAGS_ICON | GXS_GROUP_FLAGS_DESCRIPTION | GXS_GROUP_FLAGS_DISTRIBUTION | // GXS_GROUP_FLAGS_PUBLISHSIGN | @@ -52,20 +54,16 @@ const uint32_t ForumCreateDefaultsFlags = ( GXS_GROUP_DEFAULTS_DISTRIB_PUBLIC GXS_GROUP_DEFAULTS_COMMENTS_NO | 0); - -const uint32_t ForumEditEnabledFlags = ( GXS_GROUP_FLAGS_ICON | - GXS_GROUP_FLAGS_DESCRIPTION | - 0); - -const uint32_t ForumEditDefaultsFlags = 0; +const uint32_t ForumEditEnabledFlags = ForumCreateEnabledFlags; +const uint32_t ForumEditDefaultsFlags = ForumCreateDefaultsFlags; GxsForumGroupDialog::GxsForumGroupDialog(TokenQueue *tokenQueue, QWidget *parent) :GxsGroupDialog(tokenQueue, ForumCreateEnabledFlags, ForumCreateDefaultsFlags, parent) { } -GxsForumGroupDialog::GxsForumGroupDialog(const RsGxsForumGroup &group, Mode mode, QWidget *parent) - :GxsGroupDialog(group.mMeta, mode, parent) +GxsForumGroupDialog::GxsForumGroupDialog(TokenQueue *tokenExternalQueue, RsTokenService *tokenService, Mode mode, RsGxsGroupId groupId, QWidget *parent) +:GxsGroupDialog(tokenExternalQueue, tokenService, mode, groupId, ForumEditEnabledFlags, ForumEditDefaultsFlags, parent) { } @@ -103,9 +101,44 @@ bool GxsForumGroupDialog::service_CreateGroup(uint32_t &token, const RsGroupMeta bool GxsForumGroupDialog::service_EditGroup(uint32_t &token, RsGxsGroupUpdateMeta &updateMeta) { - RsGxsForumGroup grp; - grp.mDescription = std::string(ui.groupDesc->toPlainText().toUtf8()); + std::cerr << "GxsForumGroupDialog::service_EditGroup() UNFINISHED"; + std::cerr << std::endl; - rsGxsForums->updateGroup(token, updateMeta, grp); - return true; + RsGxsForumGroup grp; + grp.mDescription = std::string(ui.groupDesc->toPlainText().toUtf8()); + + rsGxsForums->updateGroup(token, updateMeta, grp); + return true; } + +bool GxsForumGroupDialog::service_loadGroup(uint32_t token, Mode mode, RsGroupMetaData& groupMetaData) +{ + std::cerr << "GxsForumGroupDialog::service_loadGroup(" << token << ")"; + std::cerr << std::endl; + + std::vector groups; + if (!rsGxsForums->getGroupData(token, groups)) + { + std::cerr << "GxsForumGroupDialog::service_loadGroup() Error getting GroupData"; + std::cerr << std::endl; + return false; + } + + if (groups.size() != 1) + { + std::cerr << "GxsForumGroupDialog::service_loadGroup() Error Group.size() != 1"; + std::cerr << std::endl; + return false; + } + + std::cerr << "GxsForumsGroupDialog::service_loadGroup() Unfinished Loading"; + std::cerr << std::endl; + + groupMetaData = groups[0].mMeta; + return true; +} + + + + + diff --git a/retroshare-gui/src/gui/gxsforums/GxsForumGroupDialog.h b/retroshare-gui/src/gui/gxsforums/GxsForumGroupDialog.h index 777139efb..fb00097c0 100644 --- a/retroshare-gui/src/gui/gxsforums/GxsForumGroupDialog.h +++ b/retroshare-gui/src/gui/gxsforums/GxsForumGroupDialog.h @@ -31,13 +31,16 @@ class GxsForumGroupDialog : public GxsGroupDialog public: GxsForumGroupDialog(TokenQueue *tokenQueue, QWidget *parent); - GxsForumGroupDialog(const RsGxsForumGroup &group, Mode mode, QWidget *parent); + GxsForumGroupDialog(TokenQueue *tokenExternalQueue, RsTokenService *tokenService, Mode mode, RsGxsGroupId groupId, QWidget *parent); protected: virtual void initUi(); virtual QPixmap serviceImage(); virtual bool service_CreateGroup(uint32_t &token, const RsGroupMetaData &meta); virtual bool service_EditGroup(uint32_t &token, RsGxsGroupUpdateMeta &updateMeta); + virtual bool service_loadGroup(uint32_t token, Mode mode, RsGroupMetaData& groupMetaData); + + }; #endif diff --git a/retroshare-gui/src/gui/gxsforums/GxsForumsDialog.cpp b/retroshare-gui/src/gui/gxsforums/GxsForumsDialog.cpp index 1d98a5dc6..4062caa81 100644 --- a/retroshare-gui/src/gui/gxsforums/GxsForumsDialog.cpp +++ b/retroshare-gui/src/gui/gxsforums/GxsForumsDialog.cpp @@ -546,10 +546,7 @@ void GxsForumsDialog::showForumDetails() return; } - RsGxsForumGroup grp; - grp.mMeta.mGroupId = mForumId; - - GxsForumGroupDialog cf(grp, GxsGroupDialog::MODE_SHOW, this); + GxsForumGroupDialog cf(mForumQueue, rsGxsForums->getTokenService(), GxsGroupDialog::MODE_SHOW, mForumId, this); cf.exec (); } @@ -562,7 +559,7 @@ void GxsForumsDialog::editForumDetails() RsGxsForumGroup grp; grp.mMeta.mGroupId = mForumId; - GxsForumGroupDialog cf(grp, GxsGroupDialog::MODE_EDIT, this); + GxsForumGroupDialog cf(mForumQueue, rsGxsForums->getTokenService(), GxsGroupDialog::MODE_EDIT, mForumId, this); cf.exec (); } From 82b50d3b46a37a56260d0b6ad567b77184158fbd Mon Sep 17 00:00:00 2001 From: chrisparker126 Date: Tue, 28 Jan 2014 21:47:51 +0000 Subject: [PATCH 82/83] Optimisation - excessive calls to sql SELECT in genexchange and gxsnet, naive algo git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@7068 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/gxs/rsgenexchange.cc | 6 ++++++ libretroshare/src/gxs/rsgxsnetservice.cc | 4 ++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/libretroshare/src/gxs/rsgenexchange.cc b/libretroshare/src/gxs/rsgenexchange.cc index 0c1f80e5e..48778064f 100644 --- a/libretroshare/src/gxs/rsgenexchange.cc +++ b/libretroshare/src/gxs/rsgenexchange.cc @@ -2247,6 +2247,9 @@ void RsGenExchange::processRecvdMessages() } } + if(mReceivedMsgs.empty()) + return; + std::vector::iterator vit = mReceivedMsgs.begin(); GxsMsgReq msgIds; std::map msgs; @@ -2370,6 +2373,9 @@ void RsGenExchange::processRecvdGroups() { RsStackMutex stack(mGenMtx); + if(mReceivedGrps.empty()) + return; + NxsGrpPendValidVect::iterator vit = mReceivedGrps.begin(); std::vector existingGrpIds; std::list grpIds; diff --git a/libretroshare/src/gxs/rsgxsnetservice.cc b/libretroshare/src/gxs/rsgxsnetservice.cc index 6a31a0c27..a15336600 100644 --- a/libretroshare/src/gxs/rsgxsnetservice.cc +++ b/libretroshare/src/gxs/rsgxsnetservice.cc @@ -872,7 +872,7 @@ bool RsGxsNetService::locked_processTransac(RsNxsTransac* item) void RsGxsNetService::run(){ - double timeDelta = 0.2; + double timeDelta = 0.5; int updateCounter = 0; while(isRunning()){ @@ -883,7 +883,7 @@ void RsGxsNetService::run(){ Sleep((int) (timeDelta * 1000)); #endif - if(updateCounter == 3) + if(updateCounter == 20) { updateServerSyncTS(); updateCounter = 0; From 7ca3ed78ae2f0e8526b2427b51127be526f91c02 Mon Sep 17 00:00:00 2001 From: drbob Date: Sat, 1 Feb 2014 03:26:26 +0000 Subject: [PATCH 83/83] fixed up nogui for new rsaccounts stuff. added missing OSX make stuff. git-svn-id: http://svn.code.sf.net/p/retroshare/code/branches/v0.6-initdev@7075 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- retroshare-nogui/src/retroshare-nogui.pro | 17 +++++++++++++++-- retroshare-nogui/src/retroshare.cc | 10 +--------- 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/retroshare-nogui/src/retroshare-nogui.pro b/retroshare-nogui/src/retroshare-nogui.pro index 0330c2602..df689f97a 100644 --- a/retroshare-nogui/src/retroshare-nogui.pro +++ b/retroshare-nogui/src/retroshare-nogui.pro @@ -2,7 +2,7 @@ TEMPLATE = app TARGET = retroshare-nogui CONFIG += bitdht #CONFIG += introserver -CONFIG += sshserver +#CONFIG += sshserver CONFIG -= qt xml gui # if you are linking against the libretroshare with gxs. @@ -106,7 +106,20 @@ macx { # ENABLE THIS OPTION FOR Univeral Binary BUILD. # CONFIG += ppc x86 - LIBS += -Wl,-search_paths_first + LIBS += -Wl,-search_paths_first + + LIBS += ../../libretroshare/src/lib/libretroshare.a + LIBS += ../../openpgpsdk/src/lib/libops.a -lbz2 + LIBS += -lssl -lcrypto -lz + LIBS += ../../../miniupnpc-1.0/libminiupnpc.a + LIBS += -framework CoreFoundation + LIBS += -framework Security + + gxs { + # We need a explicit path here, to force using the home version of sqlite3 that really encrypts the database. + # LIBS += ../../../lib/sqlcipher/.libs/libsqlcipher.a + LIBS += ../../../lib/libsqlcipher.a + } } ##################################### FreeBSD ###################################### diff --git a/retroshare-nogui/src/retroshare.cc b/retroshare-nogui/src/retroshare.cc index 44d8712a7..4c3db5cff 100644 --- a/retroshare-nogui/src/retroshare.cc +++ b/retroshare-nogui/src/retroshare.cc @@ -237,15 +237,7 @@ int main(int argc, char **argv) RsControl *rsServer = createRsControl(*notify); rsicontrol = rsServer ; - std::string preferredId, gpgId, gpgName, gpgEmail, sslName; - RsInit::getPreferedAccountId(preferredId); - - if (RsInit::getAccountDetails(preferredId, gpgId, gpgName, gpgEmail, sslName)) - { - RsInit::SelectGPGAccount(gpgId); - } - - /* Key + Certificate are loaded into libretroshare */ + /* PreferredId => Key + Certificate are loaded into libretroshare */ std::string error_string ; int retVal = RsInit::LockAndLoadCertificates(false,error_string);