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_