Merge pull request #1624 from csoler/v0.6-RetroshareService

V0.6 retroshare service
This commit is contained in:
csoler 2019-09-09 10:33:18 +02:00 committed by GitHub
commit 4f4b3bfcdb
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
14 changed files with 660 additions and 209 deletions

View file

@ -52,6 +52,8 @@ extern JsonApiServer* jsonApiServer;
*/
struct JsonApiServer : RsSingleJobThread, p3Config
{
static const uint16_t DEFAULT_PORT = 9092 ;
/**
* @brief construct a JsonApiServer instance with given parameters
* @param[in] port listening port fpt the JSON API socket
@ -62,7 +64,7 @@ struct JsonApiServer : RsSingleJobThread, p3Config
* false otherwise, this usually requires user interacion to confirm access
*/
JsonApiServer(
uint16_t port = 9092,
uint16_t port = DEFAULT_PORT,
const std::string& bindAddress = "127.0.0.1",
const std::function<bool(const std::string&)> newAccessRequestCallback = [](const std::string&){return false;} );

View file

@ -480,6 +480,7 @@ HEADERS += turtle/p3turtle.h \
HEADERS += util/folderiterator.h \
util/rsdebug.h \
util/rskbdinput.h \
util/rsmemory.h \
util/smallobject.h \
util/rsdir.h \
@ -626,6 +627,7 @@ SOURCES += turtle/p3turtle.cc \
SOURCES += util/folderiterator.cc \
util/rsdebug.cc \
util/rskbdinput.cc \
util/rsexpr.cc \
util/smallobject.cc \
util/rsdir.cc \

View file

@ -30,6 +30,7 @@
#define RS_INIT_AUTH_FAILED -1 // AuthGPG::InitAuth failed
#define RS_INIT_BASE_DIR_ERROR -2 // AuthGPG::InitAuth failed
#define RS_INIT_NO_KEYRING -3 // Keyring is empty. Need to import it.
#define RS_INIT_NO_EXECUTABLE -4 // executable path hasn't been set in config options
#include <stdint.h>
#include <list>
@ -45,6 +46,38 @@ struct RsLoginHelper;
*/
extern RsLoginHelper* rsLoginHelper;
/**
* @brief The RsInitConfig struct
* This class contains common configuration options, that executables using libretroshare may want to
* set using e.g. commandline options. To be passed to RsInit::InitRetroShare().
*/
struct RsConfigOptions
{
RsConfigOptions();
// required
std::string main_executable_path;/* this should be set to argv[0] */
// Optional. Only change if needed.
bool autoLogin; /* try auto-login */
bool udpListenerOnly; /* only listen to udp */
std::string forcedInetAddress; /* inet address to use.*/
uint16_t forcedPort; /* port to listen to */
bool outStderr;
int debugLevel;
std::string logfname; /* output filename for log */
std::string opModeStr; /* operating mode. Acceptable values: "Full", "NoTurtle", "Gaming", "Minimal" */
std::string optBaseDir; /* base directory where to find profiles, etc */
uint16_t jsonApiPort; /* port to use fo Json API */
std::string jsonApiBindAddress; /* bind address for Json API */
};
/*!
* Initialisation Class (not publicly disclosed to RsIFace)
@ -57,7 +90,7 @@ public:
OK, /// Everything go as expected, no error occurred
ERR_ALREADY_RUNNING, /// Another istance is running already
ERR_CANT_ACQUIRE_LOCK, /// Another istance is already running?
ERR_UNKOWN /// Unkown error, maybe password is wrong?
ERR_UNKNOWN /// Unkown error, maybe password is wrong?
};
/* reorganised RsInit system */
@ -77,12 +110,19 @@ public:
* invalid argument passed and vice versa
* @return RS_INIT_...
*/
static int InitRetroShare(int argc, char **argv, bool strictCheck=true);
static int InitRetroShare(const RsConfigOptions&);
static bool isPortable();
static bool isWindowsXP();
static bool collectEntropy(uint32_t bytes) ;
/*!
* \brief lockFilePath
* \return
* full path for the lock file. Can be used to warn the user about a non deleted lock that would prevent to start.
*/
static std::string lockFilePath();
/*
* Setup Hidden Location;
*/
@ -270,8 +310,10 @@ extern RsAccounts* rsAccounts;
* This helper class have been implemented because there was not reasonable way
* to login in the API that could be exposed via JSON API
*/
struct RsLoginHelper
class RsLoginHelper
{
public:
RsLoginHelper() {}
/**
* @brief Normal way to attempt login
* @jsonapi{development,manualwrapper}
@ -295,7 +337,7 @@ struct RsLoginHelper
RsPeerId mLocationId;
RsPgpId mPgpId;
std::string mLocationName;
std::string mPpgName;
std::string mPgpName;
/// @see RsSerializable::serial_process
void serial_process( RsGenericSerializer::SerializeJob j,

View file

@ -42,6 +42,8 @@
#include "util/folderiterator.h"
#include "util/rsstring.h"
#include "retroshare/rsinit.h"
#include "retroshare/rsnotify.h"
#include "retroshare/rsiface.h"
#include "plugins/pluginmanager.h"
#include "rsserver/rsloginhandler.h"
@ -112,9 +114,29 @@ RsLoginHelper* rsLoginHelper = nullptr;
RsAccounts* rsAccounts = nullptr;
RsConfigOptions::RsConfigOptions()
:
#ifdef RS_JSONAPI
jsonApiPort(JsonApiServer::DEFAULT_PORT),
jsonApiBindAddress("127.0.0.1"),
#endif
autoLogin(false),
forcedPort(0),
udpListenerOnly(false),
outStderr(false),
debugLevel(5)
{
}
struct RsInitConfig
{
RsInitConfig() : jsonApiPort(0), jsonApiBindAddress("127.0.0.1") {}
RsInitConfig()
#ifdef RS_JSONAPI
: jsonApiPort(JsonApiServer::DEFAULT_PORT),
jsonApiBindAddress("127.0.0.1")
#endif
{}
RsFileHash main_executable_hash;
@ -155,6 +177,7 @@ struct RsInitConfig
bool udpListenerOnly;
std::string opModeStr;
std::string optBaseDir;
uint16_t jsonApiPort;
std::string jsonApiBindAddress;
@ -243,14 +266,6 @@ void RsInit::InitRsConfig()
setOutputLevel(RsLog::Warning);
}
/********
* LOCALNET_TESTING - allows port restrictions
*
* #define LOCALNET_TESTING 1
*
********/
#ifdef LOCALNET_TESTING
std::string portRestrictions;
@ -264,165 +279,117 @@ bool doPortRestrictions = false;
#endif
#endif
int RsInit::InitRetroShare(int argc, char **argv, bool /* strictCheck */)
/********
* LOCALNET_TESTING - allows port restrictions
*
* #define LOCALNET_TESTING 1
*
********/
int RsInit::InitRetroShare(const RsConfigOptions& conf)
{
#ifdef DEBUG_RSINIT
for(int i=0; i<argc; i++) printf("%d: %s\n", i, argv[i]);
#endif
rsInitConfig->autoLogin = conf.autoLogin;
rsInitConfig->outStderr = conf.outStderr;
rsInitConfig->logfname = conf.logfname ;
rsInitConfig->inet = conf.forcedInetAddress ;
rsInitConfig->port = conf.forcedPort ;
rsInitConfig->debugLevel = conf.debugLevel;
rsInitConfig->optBaseDir = conf.optBaseDir;
rsInitConfig->jsonApiPort = conf.jsonApiPort;
rsInitConfig->jsonApiBindAddress = conf.jsonApiBindAddress;
#ifdef PTW32_STATIC_LIB
// for static PThreads under windows... we need to init the library...
pthread_win32_process_attach_np();
#endif
std::string prefUserString = "";
std::string opt_base_dir;
#ifdef __APPLE__
// TODO: is this still needed with argstream?
/* HACK to avoid stupid OSX Finder behaviour
* remove the commandline arguments - if we detect we are launched from Finder,
* and we have the unparsable "-psn_0_12332" option.
* this is okay, as you cannot pass commandline arguments via Finder anyway
*/
if ((argc >= 2) && (0 == strncmp(argv[1], "-psn", 4))) argc = 1;
if( rsInitConfig->autoLogin) rsInitConfig->startMinimised = true ;
if( rsInitConfig->outStderr) rsInitConfig->haveLogFile = false ;
if(!rsInitConfig->logfname.empty()) rsInitConfig->haveLogFile = true;
if( rsInitConfig->inet != "127.0.0.1") rsInitConfig->forceLocalAddr = true;
if( rsInitConfig->port != 0) rsInitConfig->forceExtPort = true;
#ifdef LOCALNET_TESTING
if(!portRestrictions.empty()) doPortRestrictions = true;
#endif
setOutputLevel((RsLog::logLvl)rsInitConfig->debugLevel);
argstream as(argc,argv);
as >> option('m',"minimized" ,rsInitConfig->startMinimised ,"Start minimized." )
>> option('s',"stderr" ,rsInitConfig->outStderr ,"output to stderr instead of log file." )
>> option('u',"udp" ,rsInitConfig->udpListenerOnly,"Only listen to UDP." )
>> option('e',"external-port" ,rsInitConfig->forceExtPort ,"Use a forwarded external port." )
>> parameter('l',"log-file" ,rsInitConfig->logfname ,"logfile" ,"Set Log filename." ,false)
>> parameter('d',"debug-level" ,rsInitConfig->debugLevel ,"level" ,"Set debug level." ,false)
>> parameter('i',"ip-address" ,rsInitConfig->inet ,"nnn.nnn.nnn.nnn", "Force IP address to use (if cannot be detected)." ,false)
>> parameter('o',"opmode" ,rsInitConfig->opModeStr ,"opmode" ,"Set Operating mode (Full, NoTurtle, Gaming, Minimal)." ,false)
>> parameter('p',"port" ,rsInitConfig->port ,"port", "Set listenning port to use." ,false)
>> parameter('c',"base-dir" ,opt_base_dir ,"directory", "Set base directory." ,false)
>> parameter('U',"user-id" ,prefUserString ,"ID", "[ocation Id] Sets Account to Use, Useful when Autologin is enabled.",false);
// set the debug file.
if (rsInitConfig->haveLogFile)
setDebugFile(rsInitConfig->logfname.c_str());
#ifdef RS_JSONAPI
as >> parameter(
"jsonApiPort", rsInitConfig->jsonApiPort, "jsonApiPort",
"Enable JSON API on the specified port", false )
>> parameter(
"jsonApiBindAddress", rsInitConfig->jsonApiBindAddress,
"jsonApiBindAddress", "JSON API Bind Address.", false);
#endif // ifdef RS_JSONAPI
#ifdef LOCALNET_TESTING
as >> parameter('R',"restrict-port" ,portRestrictions ,"port1-port2","Apply port restriction" ,false);
#endif // ifdef LOCALNET_TESTING
#ifdef RS_AUTOLOGIN
as >> option('a',"auto-login" ,rsInitConfig->autoLogin ,"AutoLogin (Windows Only) + StartMinimised");
#endif // ifdef RS_AUTOLOGIN
as >> help('h',"help","Display this Help");
as.defaultErrorHandling(true,true);
if(rsInitConfig->autoLogin) rsInitConfig->startMinimised = true ;
if(rsInitConfig->outStderr) rsInitConfig->haveLogFile = false ;
if(!rsInitConfig->logfname.empty()) rsInitConfig->haveLogFile = true;
if(rsInitConfig->inet != "127.0.0.1") rsInitConfig->forceLocalAddr = true;
#ifdef LOCALNET_TESTING
if(!portRestrictions.empty()) doPortRestrictions = true;
#endif
setOutputLevel((RsLog::logLvl)rsInitConfig->debugLevel);
// set the debug file.
if (rsInitConfig->haveLogFile)
setDebugFile(rsInitConfig->logfname.c_str());
/******************************** WINDOWS/UNIX SPECIFIC PART ******************/
/******************************** WINDOWS/UNIX SPECIFIC PART ******************/
#ifndef WINDOWS_SYS
/********************************** WINDOWS/UNIX SPECIFIC PART ******************/
/********************************** WINDOWS/UNIX SPECIFIC PART ******************/
#else
// Windows Networking Init.
WORD wVerReq = MAKEWORD(2,2);
WSADATA wsaData;
// Windows Networking Init.
WORD wVerReq = MAKEWORD(2,2);
WSADATA wsaData;
if (0 != WSAStartup(wVerReq, &wsaData))
{
std::cerr << "Failed to Startup Windows Networking";
std::cerr << std::endl;
}
else
{
std::cerr << "Started Windows Networking";
std::cerr << std::endl;
}
if (0 != WSAStartup(wVerReq, &wsaData))
{
std::cerr << "Failed to Startup Windows Networking";
std::cerr << std::endl;
}
else
{
std::cerr << "Started Windows Networking";
std::cerr << std::endl;
}
#endif
/********************************** WINDOWS/UNIX SPECIFIC PART ******************/
// SWITCH off the SIGPIPE - kills process on Linux.
/******************************** WINDOWS/UNIX SPECIFIC PART ******************/
/********************************** WINDOWS/UNIX SPECIFIC PART ******************/
// SWITCH off the SIGPIPE - kills process on Linux.
/******************************** WINDOWS/UNIX SPECIFIC PART ******************/
#ifndef WINDOWS_SYS
struct sigaction sigact;
sigact.sa_handler = SIG_IGN;
sigact.sa_flags = 0;
struct sigaction sigact;
sigact.sa_handler = SIG_IGN;
sigact.sa_flags = 0;
sigset_t set;
sigemptyset(&set);
//sigaddset(&set, SIGINT); // or whatever other signal
sigact.sa_mask = set;
sigset_t set;
sigemptyset(&set);
//sigaddset(&set, SIGINT); // or whatever other signal
sigact.sa_mask = set;
if (0 == sigaction(SIGPIPE, &sigact, NULL))
{
std::cerr << "RetroShare:: Successfully installed the SIGPIPE Block" << std::endl;
}
else
{
std::cerr << "RetroShare:: Failed to install the SIGPIPE Block" << std::endl;
}
if (0 == sigaction(SIGPIPE, &sigact, NULL))
{
std::cerr << "RetroShare:: Successfully installed the SIGPIPE Block" << std::endl;
}
else
{
std::cerr << "RetroShare:: Failed to install the SIGPIPE Block" << std::endl;
}
#endif
/******************************** WINDOWS/UNIX SPECIFIC PART ******************/
/******************************** WINDOWS/UNIX SPECIFIC PART ******************/
// Hash the main executable.
// Hash the main executable.
uint64_t tmp_size ;
uint64_t tmp_size ;
if(!RsDirUtil::getFileHash(argv[0],rsInitConfig->main_executable_hash,tmp_size,NULL))
std::cerr << "Cannot hash executable! Plugins will not be loaded correctly." << std::endl;
else
std::cerr << "Hashed main executable: " << rsInitConfig->main_executable_hash << std::endl;
if(conf.main_executable_path.empty())
{
std::cerr << "Executable path is unknown. It should normally have been set in passed RsConfigOptions structure" << std::endl;
return 1;
}
if(!RsDirUtil::getFileHash(conf.main_executable_path,rsInitConfig->main_executable_hash,tmp_size,NULL))
std::cerr << "Cannot hash executable! Plugins will not be loaded correctly." << std::endl;
else
std::cerr << "Hashed main executable: " << rsInitConfig->main_executable_hash << std::endl;
/* At this point we want to.
/* At this point we want to.
* 1) Load up Dase Directory.
* 3) Get Prefered Id.
* 2) Get List of Available Accounts.
* 4) Get List of GPG Accounts.
*/
/* Initialize AuthSSL */
AuthSSL::instance().InitAuth(nullptr, nullptr, nullptr, "");
/* Initialize AuthSSL */
AuthSSL::instance().InitAuth(nullptr, nullptr, nullptr, "");
rsLoginHelper = new RsLoginHelper;
rsLoginHelper = new RsLoginHelper;
int error_code ;
int error_code ;
if(!RsAccounts::init(opt_base_dir,error_code))
return error_code ;
if(!RsAccounts::init(rsInitConfig->optBaseDir,error_code))
return error_code ;
// choose alternative account.
if(prefUserString != "")
{
RsPeerId ssl_id(prefUserString);
if(ssl_id.isNull())
{
std::cerr << "Invalid User location id: not found in list";
std::cerr << std::endl;
return RS_INIT_AUTH_FAILED ;
}
if(RsAccounts::SelectAccount(ssl_id))
{
std::cerr << "Auto-selectng account ID " << ssl_id << std::endl;
return RS_INIT_HAVE_ACCOUNT;
}
}
#ifdef RS_AUTOLOGIN
/* check that we have selected someone */
@ -443,9 +410,7 @@ int RsInit::InitRetroShare(int argc, char **argv, bool /* strictCheck */)
#ifdef RS_JSONAPI
if(rsInitConfig->jsonApiPort)
{
jsonApiServer = new JsonApiServer(
rsInitConfig->jsonApiPort,
rsInitConfig->jsonApiBindAddress );
jsonApiServer = new JsonApiServer( rsInitConfig->jsonApiPort, rsInitConfig->jsonApiBindAddress );
jsonApiServer->start("JSON API Server");
}
#endif // ifdef RS_JSONAPI
@ -477,7 +442,7 @@ RsInit::LoadCertificateStatus RsInit::LockConfigDirectory(
case 0: return RsInit::OK;
case 1: return RsInit::ERR_ALREADY_RUNNING;
case 2: return RsInit::ERR_CANT_ACQUIRE_LOCK;
default: return RsInit::ERR_UNKOWN;
default: return RsInit::ERR_UNKNOWN;
}
}
@ -510,27 +475,32 @@ bool RsInit::LoadPassword(const std::string& inPwd)
return true;
}
std::string RsInit::lockFilePath()
{
return RsAccounts::AccountDirectory() + "/lock" ;
}
RsInit::LoadCertificateStatus RsInit::LockAndLoadCertificates(
bool autoLoginNT, std::string& lockFilePath )
{
try
{
if (!RsAccounts::lockPreferredAccount())
throw RsInit::ERR_UNKOWN; // invalid PreferredAccount.
throw RsInit::ERR_UNKNOWN; // invalid PreferredAccount.
// Logic that used to be external to RsInit...
RsPeerId accountId;
if (!RsAccounts::GetPreferredAccountId(accountId))
throw RsInit::ERR_UNKOWN; // invalid PreferredAccount;
throw RsInit::ERR_UNKNOWN; // invalid PreferredAccount;
RsPgpId pgpId;
std::string pgpName, pgpEmail, location;
if(!RsAccounts::GetAccountDetails(accountId, pgpId, pgpName, pgpEmail, location))
throw RsInit::ERR_UNKOWN; // invalid PreferredAccount;
throw RsInit::ERR_UNKNOWN; // invalid PreferredAccount;
if(0 == AuthGPG::getAuthGPG() -> GPGInit(pgpId))
throw RsInit::ERR_UNKOWN; // PGP Error.
throw RsInit::ERR_UNKNOWN; // PGP Error.
LoadCertificateStatus retVal =
LockConfigDirectory(RsAccounts::AccountDirectory(), lockFilePath);
@ -541,7 +511,7 @@ RsInit::LoadCertificateStatus RsInit::LockAndLoadCertificates(
if(LoadCertificates(autoLoginNT) != 1)
{
UnlockConfigDirectory();
throw RsInit::ERR_UNKOWN;
throw RsInit::ERR_UNKNOWN;
}
return RsInit::OK;
@ -1210,7 +1180,8 @@ int RsServer::StartupRetroShare()
plugins_directories.push_back(extensions_dir) ;
if(!RsDirUtil::checkCreateDirectory(extensions_dir))
std::cerr << "(EE) Cannot create extensions directory " + extensions_dir + ". This is not mandatory, but you probably have a permission problem." << std::endl;
std::cerr << "(EE) Cannot create extensions directory " << extensions_dir
<< ". This is not mandatory, but you probably have a permission problem." << std::endl;
#ifdef DEBUG_PLUGIN_SYSTEM
plugins_directories.push_back(".") ; // this list should be saved/set to some correct value.
@ -1909,21 +1880,24 @@ int RsServer::StartupRetroShare()
return 1;
}
RsInit::LoadCertificateStatus RsLoginHelper::attemptLogin(
const RsPeerId& account, const std::string& password)
RsInit::LoadCertificateStatus RsLoginHelper::attemptLogin(const RsPeerId& account, const std::string& password)
{
if(isLoggedIn()) return RsInit::ERR_ALREADY_RUNNING;
if(!rsNotify->cachePgpPassphrase(password)) return RsInit::ERR_UNKOWN;
if(!rsNotify->setDisableAskPassword(true)) return RsInit::ERR_UNKOWN;
if(!RsAccounts::SelectAccount(account)) return RsInit::ERR_UNKOWN;
if(!password.empty())
{
if(!rsNotify->cachePgpPassphrase(password)) return RsInit::ERR_UNKNOWN;
if(!rsNotify->setDisableAskPassword(true)) return RsInit::ERR_UNKNOWN;
}
if(!RsAccounts::SelectAccount(account)) return RsInit::ERR_UNKNOWN;
std::string _ignore_lockFilePath;
RsInit::LoadCertificateStatus ret =
RsInit::LockAndLoadCertificates(false, _ignore_lockFilePath);
if(!rsNotify->setDisableAskPassword(false)) return RsInit::ERR_UNKOWN;
if(!rsNotify->clearPgpPassphrase()) return RsInit::ERR_UNKOWN;
RsInit::LoadCertificateStatus ret = RsInit::LockAndLoadCertificates(false, _ignore_lockFilePath);
if(!rsNotify->setDisableAskPassword(false)) return RsInit::ERR_UNKNOWN;
if(!rsNotify->clearPgpPassphrase()) return RsInit::ERR_UNKNOWN;
if(ret != RsInit::OK) return ret;
if(RsControl::instance()->StartupRetroShare() == 1) return RsInit::OK;
return RsInit::ERR_UNKOWN;
return RsInit::ERR_UNKNOWN;
}
/*static*/ bool RsLoginHelper::collectEntropy(uint32_t bytes)
@ -1939,7 +1913,7 @@ void RsLoginHelper::getLocations(std::vector<RsLoginHelper::Location>& store)
{
Location l; l.mLocationId = locId;
std::string discardPgpMail;
RsAccounts::GetAccountDetails( locId, l.mPgpId, l.mPpgName,
RsAccounts::GetAccountDetails( locId, l.mPgpId, l.mPgpName,
discardPgpMail, l.mLocationName );
store.push_back(l);
}
@ -1957,14 +1931,14 @@ bool RsLoginHelper::createLocation(
return false;
}
if(l.mPgpId.isNull() && l.mPpgName.empty())
if(l.mPgpId.isNull() && l.mPgpName.empty())
{
errorMessage = "Either PGP name or PGP id is needed";
return false;
}
if(l.mPgpId.isNull() && !RsAccounts::GeneratePGPCertificate(
l.mPpgName, "", password, l.mPgpId, 4096, errorMessage) )
l.mPgpName, "", password, l.mPgpId, 4096, errorMessage) )
{
errorMessage = "Failure creating PGP key: " + errorMessage;
return false;
@ -1999,7 +1973,7 @@ void RsLoginHelper::Location::serial_process(
RS_SERIAL_PROCESS(mLocationId);
RS_SERIAL_PROCESS(mPgpId);
RS_SERIAL_PROCESS(mLocationName);
RS_SERIAL_PROCESS(mPpgName);
RS_SERIAL_PROCESS(mPgpName);
}
/*static*/ bool RsAccounts::getCurrentAccountId(RsPeerId& id)

View file

@ -0,0 +1,130 @@
/*******************************************************************************
* libretroshare/src/retroshare/util/rskbdinput.cc *
* *
* Copyright (C) 2019 Cyril Soler <csoler@users.sourceforge.net> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#ifndef __ANDROID__
#include <iostream>
#include <util/rskbdinput.h>
#ifdef WINDOWS_SYS
#include <conio.h>
#include <stdio.h>
#define PASS_MAX 512
namespace RsUtil {
std::string rs_getpass(const std::string& prompt,bool no_echo)
{
static char getpassbuf [PASS_MAX + 1];
size_t i = 0;
int c;
if (!prompt.empty()) {
std::cerr << prompt ;
std::cerr.flush();
}
for (;;) {
c = _getch ();
if (c == '\r') {
getpassbuf [i] = '\0';
break;
}
else if (i < PASS_MAX) {
getpassbuf[i++] = c;
}
if (i >= PASS_MAX) {
getpassbuf [i] = '\0';
break;
}
}
if (!prompt.empty()) {
std::cerr << "\r\n" ;
std::cerr.flush();
}
return std::string(getpassbuf);
}
}
#else
#include <stdio.h>
#include <string>
#include <iostream>
#include <termios.h>
#include <unistd.h>
static int getch()
{
int ch;
struct termios t_old, t_new;
tcgetattr(STDIN_FILENO, &t_old);
t_new = t_old;
t_new.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &t_new);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &t_old);
return ch;
}
namespace RsUtil {
std::string rs_getpass(const std::string& prompt, bool no_echo)
{
const char BACKSPACE=127;
const char RETURN=10;
std::string password;
unsigned char ch=0;
std::cout <<prompt; std::cout.flush();
while((ch=getch())!=RETURN)
{
if(ch==BACKSPACE)
{
if(password.length()!=0)
{
if(no_echo)
std::cout <<"\b \b";
password.resize(password.length()-1);
}
}
else
{
password+=ch;
if(no_echo)
std::cout <<'*';
else
std::cout << ch,std::cout.flush();
}
}
std::cout <<std::endl;
return std::string(password);
}
}
#endif
#endif

View file

@ -0,0 +1,27 @@
/*******************************************************************************
* libretroshare/src/retroshare/util/rskbdinput.h *
* *
* Copyright (C) 2019 Cyril Soler <csoler@users.sourceforge.net> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#include <string>
namespace RsUtil {
std::string rs_getpass(const std::string& prompt,bool no_echo=true) ;
}