From 370d50b41add7f0289ea857ee736e6326ebfca2d Mon Sep 17 00:00:00 2001 From: csoler Date: Wed, 5 Jul 2017 21:36:00 +0200 Subject: [PATCH 01/17] cleaned a bit the code in rsinit.cc --- libretroshare/src/rsserver/rsinit.cc | 414 +++++++++++---------------- 1 file changed, 172 insertions(+), 242 deletions(-) diff --git a/libretroshare/src/rsserver/rsinit.cc b/libretroshare/src/rsserver/rsinit.cc index f6387b070..36572404f 100644 --- a/libretroshare/src/rsserver/rsinit.cc +++ b/libretroshare/src/rsserver/rsinit.cc @@ -270,304 +270,234 @@ bool doPortRestrictions = false; #endif +#ifdef WINDOWS_SYS +#ifdef PTW32_STATIC_LIB +#include +#endif +#endif -/******************************** WINDOWS/UNIX SPECIFIC PART ******************/ -#ifndef WINDOWS_SYS int RsInit::InitRetroShare(int argc, char **argv, bool /* strictCheck */) { -/******************************** WINDOWS/UNIX SPECIFIC PART ******************/ -#else + /******************************** WINDOWS/UNIX SPECIFIC PART ******************/ +#ifdef WINDOWS_SYS + /* THIS IS A HACK TO ALLOW WINDOWS TO ACCEPT COMMANDLINE ARGUMENTS */ - /* for static PThreads under windows... we need to init the library... - */ - #ifdef PTW32_STATIC_LIB - #include - #endif + int argc; + int i; + const int MAX_ARGS = 32; + int j; + char *argv[MAX_ARGS]; + char *wholeline = (char*)GetCommandLine(); + int cmdlen = strlen(wholeline); + // duplicate line, so we can put in spaces.. + char dupline[cmdlen+1]; + strcpy(dupline, wholeline); -int RsInit::InitRetroShare(int argcIgnored, char **argvIgnored, bool strictCheck) -{ - - /* THIS IS A HACK TO ALLOW WINDOWS TO ACCEPT COMMANDLINE ARGUMENTS */ - int argc; - int i; -#ifdef USE_CMD_ARGS - char** argv = argvIgnored; - argc = argcIgnored; -#else - const int MAX_ARGS = 32; - int j; - char *argv[MAX_ARGS]; - char *wholeline = (char*)GetCommandLine(); - int cmdlen = strlen(wholeline); - // duplicate line, so we can put in spaces.. - char dupline[cmdlen+1]; - strcpy(dupline, wholeline); - - /* break wholeline down .... - * NB. This is very simplistic, and will not - * handle multiple spaces, or quotations etc, only for debugging purposes - */ - argv[0] = dupline; - for(i = 1, j = 0; (j + 1 < cmdlen) && (i < MAX_ARGS);) - { - /* find next space. */ - for(;(j + 1 < cmdlen) && (dupline[j] != ' ');j++); - if (j + 1 < cmdlen) - { - dupline[j] = '\0'; - argv[i++] = &(dupline[j+1]); - } - } - argc = i; + /* break wholeline down .... + * NB. This is very simplistic, and will not + * handle multiple spaces, or quotations etc, only for debugging purposes + */ + argv[0] = dupline; + for(i = 1, j = 0; (j + 1 < cmdlen) && (i < MAX_ARGS);) + { + /* find next space. */ + for(;(j + 1 < cmdlen) && (dupline[j] != ' ');j++); + if (j + 1 < cmdlen) + { + dupline[j] = '\0'; + argv[i++] = &(dupline[j+1]); + } + } + argc = i; #endif - for( i=0; ilogfname = "" ; - //rsInitConfig->inet = "" ; + /* 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. + */ + //rsInitConfig->logfname = "" ; + //rsInitConfig->inet = "" ; #ifdef __APPLE__ - /* HACK to avoid stupid OSX Finder behaviour - * remove the commandline arguments - if we detect we are launched from Finder, + /* 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 ((argc >= 2) && (0 == strncmp(argv[1], "-psn", 4))) + { + argc = 1; + } #endif - argstream as(argc,argv) ; + argstream as(argc,argv) ; - as >> option('a',"auto-login" ,rsInitConfig->autoLogin ,"AutoLogin (Windows Only) + StartMinimised") - >> 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." ) + as >> option('a',"auto-login" ,rsInitConfig->autoLogin ,"AutoLogin (Windows Only) + StartMinimised") + >> 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('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" ,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) - // by rshare 'r' "link" "Link" "Open RsLink with protocol retroshare://" - // by rshare 'f' "rsfile" "RsFile" "Open RsFile like RsCollection" + >> parameter('l',"log-file" ,rsInitConfig->logfname ,"logfile" ,"Set Log filename." ,false) + >> parameter('d',"debug-level" ,rsInitConfig->debugLevel ,"level" ,"Set debug level." ,false) + >> 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" ,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) + // by rshare 'r' "link" "Link" "Open RsLink with protocol retroshare://" + // by rshare 'f' "rsfile" "RsFile" "Open RsFile like RsCollection" + #ifdef LOCALNET_TESTING + >> parameter('R',"restrict-port" ,portRestrictions ,"port1-port2","Apply port restriction" ,false) + #endif + >> help('h',"help","Display this Help") ; + + as.defaultErrorHandling(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 - >> parameter('R',"restrict-port" ,portRestrictions ,"port1-port2","Apply port restriction" ,false) -#endif - >> help('h',"help","Display this Help") ; - - as.defaultErrorHandling(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; + if(!portRestrictions.empty()) doPortRestrictions = true; #endif -#ifdef SUSPENDED_CODE -#ifdef LOCALNET_TESTING - while((c = getopt(argc, argv,"hesamui:p:c:w:l:d:U:r:R:")) != -1) -#else - while((c = getopt(argc, argv,"hesamui:p:c:w:l:d:U:r:")) != -1) -#endif - { - switch (c) - { - case 'h': - std::cerr << "Help: " << std::endl; - std::cerr << "The commandline options are for retroshare-nogui, a headless server in a shell, or systems without QT." << std::endl << std::endl; - std::cerr << "-l [logfile] Set the logfilename" << std::endl; - std::cerr << "-w [password] Set the password" << std::endl; - std::cerr << "-i [ip_adress] Set IP Adress to use" << std::endl; - std::cerr << "-p [port] Set the Port to listen on" << std::endl; - std::cerr << "-c [basedir] Set the config basdir" << std::endl; - std::cerr << "-s Output to Stderr" << std::endl; - std::cerr << "-d [debuglevel] Set the debuglevel" << std::endl; - std::cerr << "-a AutoLogin (Windows Only) + StartMinimised" << std::endl; - std::cerr << "-m StartMinimised" << std::endl; - std::cerr << "-u Only listen to UDP" << std::endl; - std::cerr << "-e Use a forwarded external Port" << std::endl ; - std::cerr << "-U [User Name/GPG id/SSL id] Sets Account to Use, Useful when Autologin is enabled." << std::endl; - std::cerr << "-r link Use RetroShare link." << std::endl; -#ifdef LOCALNET_TESTING - std::cerr << "-R Port Restrictions." << std::endl; -#endif - exit(1); - break; - default: - if (strictCheck) { - std::cerr << "Unknown Option!" << std::endl; - std::cerr << "Use '-h' for help." << std::endl; - exit(1); - } - } - } -#endif + setOutputLevel((RsLog::logLvl)rsInitConfig->debugLevel); - setOutputLevel((RsLog::logLvl)rsInitConfig->debugLevel); + // set the debug file. + if (rsInitConfig->haveLogFile) + setDebugFile(rsInitConfig->logfname.c_str()); -// // set the default Debug Level... -// if (rsInitConfig->haveDebugLevel) -// { -// if ((rsInitConfig->debugLevel > 0) && -// (rsInitConfig->debugLevel <= PQL_DEBUG_ALL)) -// { -// std::cerr << "Setting Debug Level to: "; -// std::cerr << rsInitConfig->debugLevel; -// std::cerr << std::endl; -// } -// else -// { -// std::cerr << "Ignoring Invalid Debug Level: "; -// std::cerr << rsInitConfig->debugLevel; -// std::cerr << std::endl; -// } -// } - - // 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. - - uint64_t tmp_size ; + // Hash the main executable. - 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; + uint64_t tmp_size ; - /* At this point we want to. + 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; + + /* 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. */ - /* create singletons */ - AuthSSL::AuthSSLInit(); - AuthSSL::getAuthSSL() -> InitAuth(NULL, NULL, NULL, ""); + /* create singletons */ + AuthSSL::AuthSSLInit(); + AuthSSL::getAuthSSL() -> InitAuth(NULL, NULL, NULL, ""); - rsAccounts = new RsAccountsDetail(); + rsAccounts = new RsAccountsDetail(); - // first check config directories, and set bootstrap values. - if(!rsAccounts->setupBaseDirectory(opt_base_dir)) - return RS_INIT_BASE_DIR_ERROR ; + // first check config directories, and set bootstrap values. + if(!rsAccounts->setupBaseDirectory(opt_base_dir)) + return RS_INIT_BASE_DIR_ERROR ; - // Setup PGP stuff. - std::string pgp_dir = rsAccounts->PathPGPDirectory(); + // Setup PGP stuff. + std::string pgp_dir = rsAccounts->PathPGPDirectory(); - if(!RsDirUtil::checkCreateDirectory(pgp_dir)) - throw std::runtime_error("Cannot create pgp directory " + pgp_dir) ; + if(!RsDirUtil::checkCreateDirectory(pgp_dir)) + throw std::runtime_error("Cannot create pgp directory " + pgp_dir) ; - AuthGPG::init( pgp_dir + "/retroshare_public_keyring.gpg", - pgp_dir + "/retroshare_secret_keyring.gpg", - pgp_dir + "/retroshare_trustdb.gpg", - pgp_dir + "/lock"); + AuthGPG::init( pgp_dir + "/retroshare_public_keyring.gpg", + pgp_dir + "/retroshare_secret_keyring.gpg", + pgp_dir + "/retroshare_trustdb.gpg", + pgp_dir + "/lock"); - // load Accounts. - if (!rsAccounts->loadAccounts()) - { - return RS_INIT_NO_KEYRING ; - } - - // choose alternative account. - if(prefUserString != "") - { - if (!rsAccounts->selectAccountByString(prefUserString)) + // load Accounts. + if (!rsAccounts->loadAccounts()) { - 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 */ - RsPeerId preferredId; - bool existingUser = rsAccounts->getPreferredAccountId(preferredId); - - if (existingUser) - { - if (rsInitConfig->passwd != "") - { - return RS_INIT_HAVE_ACCOUNT; + return RS_INIT_NO_KEYRING ; } - if(RsLoginHandler::getSSLPassword(preferredId,false,rsInitConfig->passwd)) + // choose alternative account. + if(prefUserString != "") { - RsInit::setAutoLogin(true); - std::cerr << "Autologin has succeeded" << std::endl; - return RS_INIT_HAVE_ACCOUNT; + if (!rsAccounts->selectAccountByString(prefUserString)) + { + 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 */ + RsPeerId preferredId; + bool existingUser = rsAccounts->getPreferredAccountId(preferredId); + + if (existingUser) + { + if (rsInitConfig->passwd != "") + { + return RS_INIT_HAVE_ACCOUNT; + } + + if(RsLoginHandler::getSSLPassword(preferredId,false,rsInitConfig->passwd)) + { + RsInit::setAutoLogin(true); + std::cerr << "Autologin has succeeded" << std::endl; + return RS_INIT_HAVE_ACCOUNT; + } + } + return RS_INIT_OK; } - return RS_INIT_OK; -} /* From a778128147a9ae2494dfb97bbaeb564231896360 Mon Sep 17 00:00:00 2001 From: csoler Date: Thu, 6 Jul 2017 20:50:59 +0200 Subject: [PATCH 02/17] fixed multi-digit numbers in terminal account selection --- retroshare-nogui/src/TerminalApiClient.cpp | 93 +++++++++++++++++----- 1 file changed, 71 insertions(+), 22 deletions(-) diff --git a/retroshare-nogui/src/TerminalApiClient.cpp b/retroshare-nogui/src/TerminalApiClient.cpp index 6a08218c1..1e4a6f1c6 100644 --- a/retroshare-nogui/src/TerminalApiClient.cpp +++ b/retroshare-nogui/src/TerminalApiClient.cpp @@ -2,6 +2,8 @@ #include #include +#include +#include #include @@ -96,6 +98,13 @@ TerminalApiClient::~TerminalApiClient() fullstop(); } +struct AccountInfo +{ + std::string name ; + std::string location ; + RsPeerId ssl_id ; +}; + void TerminalApiClient::data_tick() { // values in milliseconds @@ -109,11 +118,14 @@ void TerminalApiClient::data_tick() int last_char = 0; std::string inbuf; bool enter_was_pressed = false; + int account_number_size = 1 ; + int selected_account_number = 0 ; + int account_number_typed = 0 ; StateToken runstate_state_token; std::string runstate; - std::vector accounts; + std::vector accounts; StateToken password_state_token; bool ask_for_password = false; @@ -224,7 +236,6 @@ void TerminalApiClient::data_tick() waitForResponse(id); resps.switchToDeserialisation(); - std::cout << "Type a number to select an account" << std::endl; if(!resps.hasMore()) std::cout << "Error: No Accounts. Use the Qt-GUI or the webinterface to create an account." << std::endl; int i = 0; @@ -234,37 +245,75 @@ void TerminalApiClient::data_tick() std::string id; std::string name; std::string location; + resps.getStreamToMember() << makeKeyValueReference("id", id) << makeKeyValueReference("name", name) << makeKeyValueReference("location", location); - std::cout << "[" << i << "] " << name << "(" << location << ")" << std::endl; - accounts.push_back(id); + + AccountInfo info ; + info.location = location ; + info.name = name ; + info.ssl_id = RsPeerId(id) ; + + accounts.push_back(info); i++; } + + account_number_size = (int)ceil(log(accounts.size())/log(10.0f)) ; + + for(uint32_t i=0;i= '0' && last_char <= '9' - && static_cast(last_char-'0') < accounts.size()) - { - std::string acc = accounts[last_char-'0']; - JsonStream reqs; - JsonStream resps; - Request req(reqs); - std::stringstream ss; - Response resp(resps, ss); + if(!ask_for_password && runstate == "waiting_account_select" && last_char >= '0' && last_char <= '9') + { + std::cout.flush(); + selected_account_number = 10*selected_account_number + last_char - '0' ; + account_number_typed++ ; - req.mPath.push("login"); - req.mPath.push("control"); - reqs << makeKeyValueReference("id", acc); - reqs.switchToDeserialisation(); + if(account_number_typed == account_number_size) + { + if(selected_account_number < accounts.size()) + { + std::cout.flush(); + std::cout << std::endl << "Selected account: " << accounts[selected_account_number].name << " (" << accounts[selected_account_number].location << ") SSL id: " << accounts[selected_account_number].ssl_id << std::endl; - ApiServer::RequestId id = mApiServer->handleRequest(req, resp); - waitForResponse(id); + std::string acc_ssl_id = accounts[selected_account_number].ssl_id.toStdString(); + JsonStream reqs; + JsonStream resps; + Request req(reqs); + std::stringstream ss; + Response resp(resps, ss); - inbuf.clear(); - } + req.mPath.push("login"); + req.mPath.push("control"); + reqs << makeKeyValueReference("id", acc_ssl_id); + reqs.switchToDeserialisation(); + + ApiServer::RequestId id = mApiServer->handleRequest(req, resp); + waitForResponse(id); + + inbuf.clear(); + } + else + { + std::cerr << ": invalid account number (should be between " << std::setw(account_number_size) << std::setfill('0') + << 0 << " and " << std::setw(account_number_size) << std::setfill('0') << accounts.size()-1 << ")" << std::endl; + std::cout << std::endl << "Type account number: " ; + std::cout.flush() ; + } + + account_number_typed = 0 ; + selected_account_number = 0 ; + } + } if(edge && ask_for_password) { From 42bf6b2b6aa5da590f30197547303c6f9353b1b9 Mon Sep 17 00:00:00 2001 From: csoler Date: Thu, 6 Jul 2017 20:57:38 +0200 Subject: [PATCH 03/17] improved display of password request --- retroshare-nogui/src/TerminalApiClient.cpp | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/retroshare-nogui/src/TerminalApiClient.cpp b/retroshare-nogui/src/TerminalApiClient.cpp index 1e4a6f1c6..7a7762b07 100644 --- a/retroshare-nogui/src/TerminalApiClient.cpp +++ b/retroshare-nogui/src/TerminalApiClient.cpp @@ -159,9 +159,15 @@ void TerminalApiClient::data_tick() enter_was_pressed = false; // send echo if(ask_for_password) + { std::cout << "*"; + std::cout.flush(); + } else + { std::cout << (char) last_char; + std::cout.flush(); + } //std::cout << "you pressed key " << (char) last_char << " as integer: " << last_char << std::endl; } @@ -317,7 +323,10 @@ void TerminalApiClient::data_tick() if(edge && ask_for_password) { - std::cout << "Enter the password for key " << key_name << std::endl; + std::cout << std::endl; + std::cout << std::endl; + std::cout << "Enter the password for key " << key_name << " : " ; + std::cout.flush() ; } if(ask_for_password && enter_was_pressed && !inbuf.empty()) From 4f887ff528cb84f142ba3f35887a600db53acce2 Mon Sep 17 00:00:00 2001 From: csoler Date: Sat, 8 Jul 2017 16:47:50 +0200 Subject: [PATCH 04/17] commented out unused line --- openpgpsdk/src/openpgpsdk/packet-parse.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openpgpsdk/src/openpgpsdk/packet-parse.c b/openpgpsdk/src/openpgpsdk/packet-parse.c index a4596a55c..c814bf85e 100644 --- a/openpgpsdk/src/openpgpsdk/packet-parse.c +++ b/openpgpsdk/src/openpgpsdk/packet-parse.c @@ -3247,7 +3247,7 @@ int ops_parse(ops_parse_info_t *pinfo,ops_boolean_t limit_packets) } while (r > 0); return pinfo->errors ? 0 : 1; - return r == -1 ? 0 : 1; + //return r == -1 ? 0 : 1; } /** From b5976e195ec740109539a35fb86ae61ef1c0ed12 Mon Sep 17 00:00:00 2001 From: csoler Date: Sat, 8 Jul 2017 16:48:24 +0200 Subject: [PATCH 05/17] fixed message when passphrase is empty --- libretroshare/src/rsserver/rsloginhandler.cc | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/libretroshare/src/rsserver/rsloginhandler.cc b/libretroshare/src/rsserver/rsloginhandler.cc index 83e04ee96..b6558c991 100644 --- a/libretroshare/src/rsserver/rsloginhandler.cc +++ b/libretroshare/src/rsserver/rsloginhandler.cc @@ -63,12 +63,15 @@ bool RsLoginHandler::getSSLPasswdFromGPGFile(const RsPeerId& ssl_id,std::string& << getSSLPasswdFileName(ssl_id).c_str() << std::endl; std::string plain; - if ( AuthGPG::getAuthGPG()->decryptTextFromFile( - plain, getSSLPasswdFileName(ssl_id)) ) + if ( AuthGPG::getAuthGPG()->decryptTextFromFile( plain, getSSLPasswdFileName(ssl_id)) ) { - std::cerr << "Decrypting went ok !" << std::endl; sslPassword = plain; + if(sslPassword.length() > 0) + std::cerr << "Decrypting went ok !" << std::endl; + else + std::cerr << "Passphrase is empty!" << std::endl; + return sslPassword.length() > 0 ; } else From 7ee527ecbdbc41bd6bc015653c2703d7694c1a0e Mon Sep 17 00:00:00 2001 From: csoler Date: Sat, 8 Jul 2017 17:35:34 +0200 Subject: [PATCH 06/17] removed comments --- libretroshare/src/rsserver/rsaccounts.cc | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/libretroshare/src/rsserver/rsaccounts.cc b/libretroshare/src/rsserver/rsaccounts.cc index 6cec8c570..27b6816c2 100644 --- a/libretroshare/src/rsserver/rsaccounts.cc +++ b/libretroshare/src/rsserver/rsaccounts.cc @@ -453,15 +453,19 @@ bool RsAccountsDetail::getPreferredAccountId(RsPeerId &id) bool RsAccountsDetail::getAccountIds(std::list &ids) { std::map::iterator it; +#ifdef DEBUG_ACCOUNTS std::cerr << "getAccountIds:" << std::endl; +#endif for(it = mAccounts.begin(); it != mAccounts.end(); ++it) { +#ifdef DEBUG_ACCOUNTS 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; +#endif ids.push_back(it->first); } From decbd3514da8f137ae78d5d0a0e66a3f979bfcda Mon Sep 17 00:00:00 2001 From: csoler Date: Sat, 8 Jul 2017 17:38:09 +0200 Subject: [PATCH 07/17] improved the login in the interaction between terminal api client and main --- libresapi/src/api/RsControlModule.cpp | 27 ++-- libresapi/src/api/RsControlModule.h | 6 +- retroshare-nogui/src/TerminalApiClient.cpp | 170 +++++++++++---------- retroshare-nogui/src/TerminalApiClient.h | 19 ++- retroshare-nogui/src/retroshare.cc | 18 ++- 5 files changed, 148 insertions(+), 92 deletions(-) diff --git a/libresapi/src/api/RsControlModule.cpp b/libresapi/src/api/RsControlModule.cpp index eb076086f..b69fa2943 100644 --- a/libresapi/src/api/RsControlModule.cpp +++ b/libresapi/src/api/RsControlModule.cpp @@ -150,24 +150,29 @@ void RsControlModule::run() } // skip account selection if autologin is available - if(initResult != RS_INIT_HAVE_ACCOUNT) - setRunState(WAITING_ACCOUNT_SELECT); + bool wait_for_account_select = (initResult != RS_INIT_HAVE_ACCOUNT); // wait for login request bool auto_login = false; - bool wait_for_account_select = (initResult != RS_INIT_HAVE_ACCOUNT); + + if(wait_for_account_select) + setRunState(WAITING_ACCOUNT_SELECT); + while(wait_for_account_select && !processShouldExit()) { - usleep(5*1000); + usleep(500*1000); RsStackMutex stack(mDataMtx); // ********** LOCKED ********** - wait_for_account_select = mLoadPeerId.isNull(); + + if(!mLoadPeerId.isNull()) + wait_for_account_select = wait_for_account_select && !RsAccounts::SelectAccount(mLoadPeerId); + auto_login = mAutoLoginNextTime; - if(!wait_for_account_select) - { - wait_for_account_select = !RsAccounts::SelectAccount(mLoadPeerId); - if(wait_for_account_select) - setRunState(WAITING_ACCOUNT_SELECT); - } + + //if(!wait_for_account_select) + //{ + // if(wait_for_account_select) + // setRunState(WAITING_ACCOUNT_SELECT); + //} } if(processShouldExit()) diff --git a/libresapi/src/api/RsControlModule.h b/libresapi/src/api/RsControlModule.h index 38d564d9a..e81bb66f1 100644 --- a/libresapi/src/api/RsControlModule.h +++ b/libresapi/src/api/RsControlModule.h @@ -23,6 +23,8 @@ class ApiServer; class RsControlModule: public ResourceRouter, NotifyClient, private RsSingleJobThread { public: + enum RunState { WAITING_INIT, FATAL_ERROR, WAITING_ACCOUNT_SELECT, WAITING_STARTUP, RUNNING_OK, RUNNING_OK_NO_FULL_CONTROL}; + // ApiServer will be called once RS is started, to load additional api modules // full_control: set to true if this module should handle rsinit and login // set to false if rsinit is handled by the Qt gui @@ -32,6 +34,9 @@ public: // returns true if the process should terminate bool processShouldExit(); + // returns the current state of the software booting process + RunState runState() const { return mRunState ; } + // from NotifyClient virtual bool askForPassword(const std::string &title, const std::string& key_details, bool prev_is_bad , std::string& password,bool& canceled) override; virtual bool askForDeferredSelfSignature(const void *data, const uint32_t len, unsigned char *sign, unsigned int *signlen,int& signature_result, std::string reason = "") override; @@ -42,7 +47,6 @@ protected: virtual void run(); private: - enum RunState { WAITING_INIT, FATAL_ERROR, WAITING_ACCOUNT_SELECT, WAITING_STARTUP, RUNNING_OK, RUNNING_OK_NO_FULL_CONTROL}; void handleRunState(Request& req, Response& resp); void handleIdentities(Request& req, Response& resp); void handleLocations(Request& req, Response& resp); diff --git a/retroshare-nogui/src/TerminalApiClient.cpp b/retroshare-nogui/src/TerminalApiClient.cpp index 7a7762b07..a52d51567 100644 --- a/retroshare-nogui/src/TerminalApiClient.cpp +++ b/retroshare-nogui/src/TerminalApiClient.cpp @@ -87,10 +87,8 @@ private: namespace resource_api { -TerminalApiClient::TerminalApiClient(ApiServer *api): - mApiServer(api) +TerminalApiClient::TerminalApiClient(ApiServer *api): mApiServer(api) { - start("resapi terminal"); } TerminalApiClient::~TerminalApiClient() @@ -98,13 +96,6 @@ TerminalApiClient::~TerminalApiClient() fullstop(); } -struct AccountInfo -{ - std::string name ; - std::string location ; - RsPeerId ssl_id ; -}; - void TerminalApiClient::data_tick() { // values in milliseconds @@ -228,44 +219,7 @@ void TerminalApiClient::data_tick() if(!ask_for_password && edge && runstate == "waiting_account_select") { - JsonStream reqs; - JsonStream resps; - Request req(reqs); - std::stringstream ss; - Response resp(resps, ss); - - req.mPath.push("locations"); - req.mPath.push("control"); - reqs.switchToDeserialisation(); - - ApiServer::RequestId id = mApiServer->handleRequest(req, resp); - waitForResponse(id); - - resps.switchToDeserialisation(); - if(!resps.hasMore()) - std::cout << "Error: No Accounts. Use the Qt-GUI or the webinterface to create an account." << std::endl; - int i = 0; - accounts.clear(); - while(resps.hasMore()) - { - std::string id; - std::string name; - std::string location; - - resps.getStreamToMember() - << makeKeyValueReference("id", id) - << makeKeyValueReference("name", name) - << makeKeyValueReference("location", location); - - AccountInfo info ; - info.location = location ; - info.name = name ; - info.ssl_id = RsPeerId(id) ; - - accounts.push_back(info); - i++; - } - + readAvailableAccounts(accounts) ; account_number_size = (int)ceil(log(accounts.size())/log(10.0f)) ; for(uint32_t i=0;ihandleRequest(req, resp); - waitForResponse(id); + sendSelectedAccount(acc_ssl_id) ; inbuf.clear(); } @@ -330,33 +272,107 @@ void TerminalApiClient::data_tick() } if(ask_for_password && enter_was_pressed && !inbuf.empty()) - { - std::cout << "TerminalApiClient: got a password" << std::endl; - JsonStream reqs; - JsonStream resps; - Request req(reqs); - std::stringstream ss; - Response resp(resps, ss); + { + std::cout << "TerminalApiClient: got a password" << std::endl; - req.mPath.push("password"); - req.mPath.push("control"); - reqs << makeKeyValueReference("password", inbuf); - reqs.switchToDeserialisation(); + // Send passwd to api server + sendPassword(inbuf) ; - ApiServer::RequestId id = mApiServer->handleRequest(req, resp); - waitForResponse(id); - - inbuf.clear(); + // clears buffer + inbuf.clear(); } } } -void TerminalApiClient::waitForResponse(ApiServer::RequestId id) +void TerminalApiClient::waitForResponse(ApiServer::RequestId id) const { while(!mApiServer->isRequestDone(id)) usleep(20*1000); } +void TerminalApiClient::sendPassword(const std::string& passwd) const +{ + JsonStream reqs; + JsonStream resps; + Request req(reqs); + std::stringstream ss; + Response resp(resps, ss); + + req.mPath.push("password"); + req.mPath.push("control"); + + std::string pass(passwd) ; + + reqs << makeKeyValueReference("password", pass); + reqs.switchToDeserialisation(); + + ApiServer::RequestId id = mApiServer->handleRequest(req, resp); + waitForResponse(id); +} + +void TerminalApiClient::sendSelectedAccount(const std::string& ssl_id) const +{ + JsonStream reqs; + JsonStream resps; + Request req(reqs); + std::stringstream ss; + Response resp(resps, ss); + + std::string acc_ssl_id(ssl_id) ; + req.mPath.push("login"); + req.mPath.push("control"); + reqs << makeKeyValueReference("id", acc_ssl_id); + reqs.switchToDeserialisation(); + + ApiServer::RequestId id = mApiServer->handleRequest(req, resp); + waitForResponse(id); +} + +void TerminalApiClient::readAvailableAccounts(std::vector& accounts) const +{ + JsonStream reqs; + JsonStream resps; + Request req(reqs); + std::stringstream ss; + Response resp(resps, ss); + + req.mPath.push("locations"); + req.mPath.push("control"); + reqs.switchToDeserialisation(); + + ApiServer::RequestId id = mApiServer->handleRequest(req, resp); + waitForResponse(id); + + resps.switchToDeserialisation(); + + if(!resps.hasMore()) + std::cout << "Error: No Accounts. Use the Qt-GUI or the webinterface to create an account." << std::endl; + + int i = 0; + accounts.clear(); + + while(resps.hasMore()) + { + std::string id; + std::string name; + std::string location; + + resps.getStreamToMember() + << makeKeyValueReference("id", id) + << makeKeyValueReference("name", name) + << makeKeyValueReference("location", location); + + AccountInfo info ; + info.location = location ; + info.name = name ; + info.ssl_id = RsPeerId(id) ; + + accounts.push_back(info); + i++; + } +} + + bool TerminalApiClient::isTokenValid(StateToken runstate_state_token) { JsonStream reqs; diff --git a/retroshare-nogui/src/TerminalApiClient.h b/retroshare-nogui/src/TerminalApiClient.h index bb5265c9d..4f72afb12 100644 --- a/retroshare-nogui/src/TerminalApiClient.h +++ b/retroshare-nogui/src/TerminalApiClient.h @@ -8,7 +8,7 @@ namespace resource_api { // - account selection // - login // - shutdown -class TerminalApiClient: private RsTickingThread{ +class TerminalApiClient: public RsTickingThread{ public: // zero setup: create an instance of this class and destroy it when not needed anymore // no need to call start or stop or something @@ -19,9 +19,24 @@ protected: // from RsThread virtual void data_tick(); /* called once the thread is started. Should be overloaded by subclasses. */ private: - void waitForResponse(ApiServer::RequestId id); + struct AccountInfo + { + std::string name ; + std::string location ; + RsPeerId ssl_id ; + }; + + + void waitForResponse(ApiServer::RequestId id) const; bool isTokenValid(StateToken st); ApiServer* mApiServer; + + // Methods to talk to the ApiServer + + void sendPassword(const std::string& passwd) const; + void sendSelectedAccount(const std::string& ssl_id) const; + void readAvailableAccounts(std::vector& accounts) const; + void getRunningState() const ; }; } // namespace resource_api diff --git a/retroshare-nogui/src/retroshare.cc b/retroshare-nogui/src/retroshare.cc index 011e03873..2e0b5d443 100644 --- a/retroshare-nogui/src/retroshare.cc +++ b/retroshare-nogui/src/retroshare.cc @@ -100,9 +100,25 @@ int main(int argc, char **argv) } resource_api::TerminalApiClient tac(&api); + tac.start(); + while(ctrl_mod.processShouldExit() == false) { - usleep(20*1000); + usleep(200*1000); + + if(!tac.isRunning()) + { + if(!RsInit::isLocationRunning()) + { + std::cerr << "Terminal API client stopped but location not set ! Relaunching." ; + tac.start(); + } + else if(RsInit::isLocationRunning()) + { + std::cerr << "Terminal API client running but location already set ! Stopping it." ; + tac.shutdown(); + } + } } if(httpd) From 5dfbce7e3a507a071107daf963c39aa03cd14ded Mon Sep 17 00:00:00 2001 From: csoler Date: Sun, 9 Jul 2017 21:16:41 +0200 Subject: [PATCH 08/17] fixed Terminal Api Client logic --- libresapi/src/api/RsControlModule.cpp | 49 ++++++- libretroshare/src/pqi/authgpg.cc | 64 ++++----- retroshare-nogui/src/TerminalApiClient.cpp | 151 ++++++++++++++++----- retroshare-nogui/src/TerminalApiClient.h | 4 +- retroshare-nogui/src/retroshare.cc | 20 +-- 5 files changed, 208 insertions(+), 80 deletions(-) diff --git a/libresapi/src/api/RsControlModule.cpp b/libresapi/src/api/RsControlModule.cpp index b69fa2943..1d0cddd65 100644 --- a/libresapi/src/api/RsControlModule.cpp +++ b/libresapi/src/api/RsControlModule.cpp @@ -14,6 +14,8 @@ #include "GetPluginInterfaces.h" +//#define DEBUG_CONTROL_MODULE 1 + namespace resource_api{ RsControlModule::RsControlModule(int argc, char **argv, StateTokenServer* sts, ApiServer *apiserver, bool full_control): @@ -61,6 +63,9 @@ bool RsControlModule::processShouldExit() bool RsControlModule::askForPassword(const std::string &title, const std::string &key_details, bool prev_is_bad, std::string &password, bool& cancelled) { +#ifdef DEBUG_CONTROL_MODULE + std::cerr << "RsControlModule::askForPassword(): current passwd is \"" << mPassword << "\"" << std::endl; +#endif cancelled = false ; { RS_STACK_MUTEX(mDataMtx); // ********** LOCKED ********** @@ -114,7 +119,9 @@ bool RsControlModule::askForPassword(const std::string &title, const std::string void RsControlModule::run() { +#ifdef DEBUG_CONTROL_MODULE std::cerr << "RsControlModule: initialising libretroshare..." << std::endl; +#endif RsInit::InitRsConfig(); int initResult = RsInit::InitRetroShare(argc, argv, true); @@ -125,11 +132,11 @@ void RsControlModule::run() std::stringstream ss; switch (initResult) { case RS_INIT_AUTH_FAILED: - ss << "RsInit::InitRetroShare AuthGPG::InitAuth failed" << std::endl; + ss << "RsControlModule::run() AuthGPG::InitAuth failed" << std::endl; break; default: /* Unexpected return code */ - ss << "RsInit::InitRetroShare unexpected return code " << initResult << std::endl; + ss << "ControlModule::run() unexpected return code " << initResult << std::endl; break; } // FATAL ERROR, we can't recover from this. Just send the message to the user. @@ -141,9 +148,15 @@ void RsControlModule::run() RsControl::earlyInitNotificationSystem(); rsNotify->registerNotifyClient(this); +#ifdef DEBUG_CONTROL_MODULE + std::cerr << "RsControlModule::run() Entering login wait loop." << std::endl; +#endif bool login_ok = false; while(!login_ok) { +#ifdef DEBUG_CONTROL_MODULE + std::cerr << "RsControlModule::run() reseting passwd." << std::endl; +#endif { RsStackMutex stack(mDataMtx); // ********** LOCKED ********** mPassword = ""; @@ -156,15 +169,28 @@ void RsControlModule::run() bool auto_login = false; if(wait_for_account_select) - setRunState(WAITING_ACCOUNT_SELECT); + { +#ifdef DEBUG_CONTROL_MODULE + std::cerr << "RsControlModule::run() wait_for_account_select=true => setting run state to WAITING_ACCOUNT_SELECT." << std::endl; +#endif + setRunState(WAITING_ACCOUNT_SELECT); + } while(wait_for_account_select && !processShouldExit()) { +#ifdef DEBUG_CONTROL_MODULE + std::cerr << "RsControlModule::run() while(wait_for_account_select) mLoadPeerId=" << mLoadPeerId << std::endl; +#endif usleep(500*1000); RsStackMutex stack(mDataMtx); // ********** LOCKED ********** if(!mLoadPeerId.isNull()) + { wait_for_account_select = wait_for_account_select && !RsAccounts::SelectAccount(mLoadPeerId); +#ifdef DEBUG_CONTROL_MODULE + std::cerr << "RsControlModule::run() mLoadPeerId != NULL, account selection result: " << !wait_for_account_select << std::endl; +#endif + } auto_login = mAutoLoginNextTime; @@ -180,6 +206,9 @@ void RsControlModule::run() bool autoLogin = (initResult == RS_INIT_HAVE_ACCOUNT) | auto_login; std::string lockFile; +#ifdef DEBUG_CONTROL_MODULE + std::cerr << "RsControlModule::run() trying to load certificate..." << std::endl; +#endif int retVal = RsInit::LockAndLoadCertificates(autoLogin, lockFile); std::string error_string; @@ -204,16 +233,24 @@ void RsControlModule::run() std::cerr << "RsControlModule::run() LockAndLoadCertificates failed. Unexpected switch value: " << retVal << std::endl; break; } +#ifdef DEBUG_CONTROL_MODULE + std::cerr << "RsControlModule::run() Error string: \"" << error_string << "\"" << std::endl; +#endif { RsStackMutex stack(mDataMtx); // ********** LOCKED ********** mLoadPeerId.clear(); } } +#ifdef DEBUG_CONTROL_MODULE + std::cerr << "RsControlModule::run() login is ok. Starting up..." << std::endl; +#endif { RsStackMutex stack(mDataMtx); // ********** LOCKED ********** mFixedPassword = mPassword; + + std::cerr << "***Reseting mPasswd " << std::endl; mPassword = ""; } @@ -336,13 +373,17 @@ void RsControlModule::handlePassword(Request &req, Response &resp) RsStackMutex stack(mDataMtx); // ********** LOCKED ********** std::string passwd; req.mStream << makeKeyValueReference("password", passwd); - if(passwd != "" && mWantPassword) + if(passwd != "")// && mWantPassword) { // client sends password mPassword = passwd; mWantPassword = false; mStateTokenServer->replaceToken(mStateToken); + + std::cerr << "RsControlModule::handlePassword(): setting mPasswd=\"" << mPassword << "\"" << std::endl; } + else + std::cerr << "RsControlModule::handlePassword(): not setting mPasswd=\"" << mPassword << "\"!!!" << std::endl; resp.mDataStream << makeKeyValueReference("want_password", mWantPassword) diff --git a/libretroshare/src/pqi/authgpg.cc b/libretroshare/src/pqi/authgpg.cc index 1e20d6b85..32b42461a 100644 --- a/libretroshare/src/pqi/authgpg.cc +++ b/libretroshare/src/pqi/authgpg.cc @@ -20,7 +20,7 @@ * USA. * * Please report all bugs and problems to "retroshare@lunamutt.com". - * + * * */ @@ -121,12 +121,12 @@ void AuthGPG::exit() } AuthGPG::AuthGPG(const std::string& path_to_public_keyring,const std::string& path_to_secret_keyring,const std::string& path_to_trustdb,const std::string& pgp_lock_file) - :p3Config(), + :p3Config(), PGPHandler(path_to_public_keyring,path_to_secret_keyring,path_to_trustdb,pgp_lock_file), gpgMtxService("AuthGPG-service"), - gpgMtxEngine("AuthGPG-engine"), + gpgMtxEngine("AuthGPG-engine"), gpgMtxData("AuthGPG-data"), - gpgKeySelected(false) + gpgKeySelected(false) { _force_sync_database = false ; mCount = 0; @@ -231,9 +231,9 @@ void AuthGPG::processServices() } AuthGPGOperationLoadOrSave *loadOrSave = dynamic_cast(operation); - if (loadOrSave) + if (loadOrSave) { - if (loadOrSave->m_load) + if (loadOrSave->m_load) { /* process load operation */ @@ -285,8 +285,8 @@ void AuthGPG::processServices() } service->setGPGOperation(loadOrSave); - } - else + } + else { #ifdef GPG_DEBUG std::cerr << "AuthGPGimpl::processServices() Unknown operation" << std::endl; @@ -313,7 +313,7 @@ bool AuthGPG::parseSignature(const void *sig, unsigned int siglen, RsPgpId& issu return PGPHandler::parseSignature((unsigned char*)sig,siglen,issuer_id) ; } -bool AuthGPG::exportProfile(const std::string& fname,const RsPgpId& exported_id) +bool AuthGPG::exportProfile(const std::string& fname,const RsPgpId& exported_id) { return PGPHandler::exportGPGKeyPair(fname,exported_id) ; } @@ -328,7 +328,7 @@ bool AuthGPG::importProfileFromString(const std::string &data, RsPgpId &gpg_id, return PGPHandler::importGPGKeyPairFromString(data, gpg_id, import_error); } - + bool AuthGPG::active() { RsStackMutex stack(gpgMtxData); /******* LOCKED ******/ @@ -427,7 +427,7 @@ bool AuthGPG::isKeySupported(const RsPgpId& id) const return !(pc->_flags & PGPCertificateInfo::PGP_CERTIFICATE_FLAG_UNSUPPORTED_ALGORITHM) ; } -bool AuthGPG::getGPGDetails(const RsPgpId& pgp_id, RsPeerDetails &d) +bool AuthGPG::getGPGDetails(const RsPgpId& pgp_id, RsPeerDetails &d) { RsStackMutex stack(gpgMtxData); /******* LOCKED ******/ @@ -458,7 +458,7 @@ bool AuthGPG::getGPGDetails(const RsPgpId& pgp_id, RsPeerDetails &d) return true; } -bool AuthGPG::getGPGFilteredList(std::list& list,bool (*filter)(const PGPCertificateInfo&)) +bool AuthGPG::getGPGFilteredList(std::list& list,bool (*filter)(const PGPCertificateInfo&)) { RsStackMutex stack(gpgMtxData); /******* LOCKED ******/ @@ -492,20 +492,20 @@ bool AuthGPG::getGPGSignedList(std::list &ids) // #else // certificate = PGPHandler::SaveCertificateToString(RsPgpId(id),true) ; // #endif -// +// // // #ifdef LIMIT_CERTIFICATE_SIZE // // std::string cleaned_key ; // // if(PGPKeyManagement::createMinimalKey(certificate,cleaned_key)) // // certificate = cleaned_key ; // // #endif -// +// // return certificate.length() > 0 ; // } /***************************************************************** - * Loading and Saving Certificates - this has to + * Loading and Saving Certificates - this has to * be able to handle both openpgp and X509 certificates. - * + * * X509 are passed onto AuthSSL, OpenPGP are passed to gpgme. * */ @@ -515,7 +515,7 @@ bool AuthGPG::getGPGSignedList(std::list &ids) std::string AuthGPG::SaveCertificateToString(const RsPgpId &id,bool include_signatures) { RsStackMutex stack(gpgMtxEngine); /******* LOCKED ******/ - + return PGPHandler::SaveCertificateToString(id,include_signatures) ; } @@ -536,10 +536,10 @@ bool AuthGPG::LoadCertificateFromString(const std::string &str, RsPgpId& gpg_id, /***************************************************************** * Auth...? Signing, Revoke, Trust are all done at * the PGP level.... - * + * * Only Signing of SSL is done at setup. - * Auth should be done... ?? not sure - * maybe + * Auth should be done... ?? not sure + * maybe * */ @@ -596,12 +596,12 @@ bool AuthGPG::TrustCertificate(const RsPgpId& id, int trustlvl) return privateTrustCertificate(id, trustlvl) ; } -bool AuthGPG::encryptDataBin(const RsPgpId& pgp_id,const void *data, unsigned int datalen, unsigned char *sign, unsigned int *signlen) +bool AuthGPG::encryptDataBin(const RsPgpId& pgp_id,const void *data, unsigned int datalen, unsigned char *sign, unsigned int *signlen) { return PGPHandler::encryptDataBin(RsPgpId(pgp_id),data,datalen,sign,signlen) ; } -bool AuthGPG::decryptDataBin(const void *data, unsigned int datalen, unsigned char *sign, unsigned int *signlen) +bool AuthGPG::decryptDataBin(const void *data, unsigned int datalen, unsigned char *sign, unsigned int *signlen) { return PGPHandler::decryptDataBin(mOwnGpgId,data,datalen,sign,signlen) ; } @@ -610,7 +610,7 @@ bool AuthGPG::SignDataBin(const void *data, unsigned int datalen, unsigned char return DoOwnSignature(data, datalen, sign, signlen, reason); } -bool AuthGPG::VerifySignBin(const void *data, uint32_t datalen, unsigned char *sign, unsigned int signlen, const PGPFingerprintType& withfingerprint) +bool AuthGPG::VerifySignBin(const void *data, uint32_t datalen, unsigned char *sign, unsigned int signlen, const PGPFingerprintType& withfingerprint) { return VerifySignature(data, datalen, sign, signlen, withfingerprint); } @@ -639,12 +639,12 @@ int AuthGPG::privateTrustCertificate(const RsPgpId& id, int trustlvl) { RsStackMutex stack(gpgMtxData); /******* LOCKED ******/ - /* The certificate should be in Peers list ??? */ - if(!isGPGAccepted(id)) - { - std::cerr << "Invalid Certificate" << std::endl; + // csoler: Why are we not allowing this when the peer is not in the accepted peers list?? + // The trust level is only a user-defined property that has nothing to + // do with the fact that we allow connections or not. + + if(!isGPGAccepted(id)) return 0; - } int res = PGPHandler::privateTrustCertificate(id,trustlvl) ; _force_sync_database = true ; @@ -667,7 +667,7 @@ bool AuthGPG::saveList(bool& cleanup, std::list& lst) #ifdef GPG_DEBUG std::cerr << "AuthGPG::saveList() called" << std::endl ; #endif - std::list ids ; + std::list ids ; getGPGAcceptedList(ids) ; // needs to be done before the lock RsStackMutex stack(gpgMtxData); /******* LOCKED ******/ @@ -677,7 +677,7 @@ bool AuthGPG::saveList(bool& cleanup, std::list& lst) // Now save config for network digging strategies RsConfigKeyValueSet *vitem = new RsConfigKeyValueSet ; - for (std::list::const_iterator it(ids.begin()); it != ids.end(); ++it) + for (std::list::const_iterator it(ids.begin()); it != ids.end(); ++it) if((*it) != mOwnGpgId) // skip our own id. { RsTlvKeyValue kv; @@ -705,7 +705,7 @@ bool AuthGPG::loadList(std::list& load) for(it = load.begin(); it != load.end(); ++it) { RsConfigKeyValueSet *vitem = dynamic_cast(*it); - if(vitem) + if(vitem) { #ifdef GPG_DEBUG std::cerr << "AuthGPG::loadList() General Variable Config Item:" << std::endl; @@ -715,7 +715,7 @@ bool AuthGPG::loadList(std::list& load) std::list::iterator kit; for(kit = vitem->tlvkvs.pairs.begin(); kit != vitem->tlvkvs.pairs.end(); ++kit) - if (kit->key != mOwnGpgId.toStdString()) + if (kit->key != mOwnGpgId.toStdString()) PGPHandler::setAcceptConnexion(RsPgpId(kit->key), (kit->value == "TRUE")); } delete (*it); diff --git a/retroshare-nogui/src/TerminalApiClient.cpp b/retroshare-nogui/src/TerminalApiClient.cpp index a52d51567..81eebe6b4 100644 --- a/retroshare-nogui/src/TerminalApiClient.cpp +++ b/retroshare-nogui/src/TerminalApiClient.cpp @@ -96,6 +96,23 @@ TerminalApiClient::~TerminalApiClient() fullstop(); } +static std::string readStringFromKeyboard(bool passwd_mode) +{ + int c ; + std::string s; + + while((c=getchar()) != '\n') + { + if(passwd_mode) + putchar('*') ; + else + putchar(c) ; + + s += c ; + } + return s ; +} + void TerminalApiClient::data_tick() { // values in milliseconds @@ -109,6 +126,7 @@ void TerminalApiClient::data_tick() int last_char = 0; std::string inbuf; bool enter_was_pressed = false; + bool prev_is_bad = false ; int account_number_size = 1 ; int selected_account_number = 0 ; int account_number_typed = 0 ; @@ -178,45 +196,63 @@ void TerminalApiClient::data_tick() if(runstate_state_token.isNull()) { edge = true; - JsonStream reqs; - JsonStream resps; - Request req(reqs); - std::stringstream ss; - Response resp(resps, ss); - - req.mPath.push("runstate"); - req.mPath.push("control"); - reqs.switchToDeserialisation(); - - ApiServer::RequestId id = mApiServer->handleRequest(req, resp); - waitForResponse(id); - - resps.switchToDeserialisation(); - resps << makeKeyValueReference("runstate", runstate); - runstate_state_token = resp.mStateToken; - } + readRunState(runstate_state_token,runstate) ; + } if(password_state_token.isNull()) - { + { edge = true; - JsonStream reqs; - JsonStream resps; - Request req(reqs); - std::stringstream ss; - Response resp(resps, ss); + readPasswordState(password_state_token,ask_for_password,key_name,prev_is_bad) ; + } - req.mPath.push("password"); - req.mPath.push("control"); - reqs.switchToDeserialisation(); + if(!ask_for_password && edge && runstate == "waiting_account_select") + { + readAvailableAccounts(accounts) ; + account_number_size = (int)ceil(log(accounts.size())/log(10.0f)) ; - ApiServer::RequestId id = mApiServer->handleRequest(req, resp); - waitForResponse(id); + for(uint32_t i=0;i= accounts.size()) + { + std::cout << std::endl << "Type account number: " ; + std::cout.flush() ; + + std::string s = readStringFromKeyboard(false) ; + + if(sscanf(s.c_str(),"%d",&selected_account_number) != 1) + continue ; + + if(selected_account_number >= accounts.size()) + { + std::cerr << ": invalid account number (should be between " << std::setw(account_number_size) << std::setfill('0') + << 0 << " and " << std::setw(account_number_size) << std::setfill('0') << accounts.size()-1 << ")" << std::endl; + std::cout << std::endl << "Type account number: " ; + std::cout.flush() ; + + selected_account_number = accounts.size(); + } + + std::cout << std::endl << "Selected account: " << accounts[selected_account_number].name << " (" << accounts[selected_account_number].location << ") SSL id: " << accounts[selected_account_number].ssl_id << std::endl; + } + // now ask for passphrase + + std::string prompt = "Enter the password for key " + key_name + " : " ; + std::cout << prompt ; + std::cout.flush(); + std::string passwd = readStringFromKeyboard(true); + + // now we have passwd and account number, so send it to the core. + + std::string acc_ssl_id = accounts[selected_account_number].ssl_id.toStdString(); + + sendPassword(passwd) ; + sendSelectedAccount(acc_ssl_id) ; } +#ifdef OLD_CODE if(!ask_for_password && edge && runstate == "waiting_account_select") { readAvailableAccounts(accounts) ; @@ -278,9 +314,12 @@ void TerminalApiClient::data_tick() // Send passwd to api server sendPassword(inbuf) ; + usleep(1000*1000) ; + // clears buffer inbuf.clear(); } +#endif } } @@ -373,7 +412,7 @@ void TerminalApiClient::readAvailableAccounts(std::vector& accounts } -bool TerminalApiClient::isTokenValid(StateToken runstate_state_token) +bool TerminalApiClient::isTokenValid(StateToken runstate_state_token) const { JsonStream reqs; JsonStream resps; @@ -395,4 +434,50 @@ bool TerminalApiClient::isTokenValid(StateToken runstate_state_token) return true; } +void TerminalApiClient::readPasswordState(StateToken& password_state_token,bool& ask_for_password,std::string& key_name,bool& prev_is_bad) const +{ + JsonStream reqs; + JsonStream resps; + Request req(reqs); + std::stringstream ss; + Response resp(resps, ss); + + req.mPath.push("password"); + req.mPath.push("control"); + reqs.switchToDeserialisation(); + + ApiServer::RequestId id = mApiServer->handleRequest(req, resp); + waitForResponse(id); + + resps.switchToDeserialisation(); + resps << makeKeyValueReference("want_password", ask_for_password); + resps << makeKeyValueReference("key_name", key_name); + resps << makeKeyValueReference("prev_is_bad", prev_is_bad); + password_state_token = resp.mStateToken; + + std::cerr << "****** Passwd state changed: want_passwd=" << ask_for_password << " key_name=" << key_name << " prev_is_bad=" << prev_is_bad << std::endl; +} + +void TerminalApiClient::readRunState(StateToken& runstate_state_token,std::string& runstate) const +{ + JsonStream reqs; + JsonStream resps; + Request req(reqs); + std::stringstream ss; + Response resp(resps, ss); + + req.mPath.push("runstate"); + req.mPath.push("control"); + reqs.switchToDeserialisation(); + + ApiServer::RequestId id = mApiServer->handleRequest(req, resp); + waitForResponse(id); + + resps.switchToDeserialisation(); + resps << makeKeyValueReference("runstate", runstate); + runstate_state_token = resp.mStateToken; + + std::cerr << "****** Run State changed to \"" << runstate << "\"" << std::endl; +} + } // namespace resource_api diff --git a/retroshare-nogui/src/TerminalApiClient.h b/retroshare-nogui/src/TerminalApiClient.h index 4f72afb12..632438124 100644 --- a/retroshare-nogui/src/TerminalApiClient.h +++ b/retroshare-nogui/src/TerminalApiClient.h @@ -28,7 +28,7 @@ private: void waitForResponse(ApiServer::RequestId id) const; - bool isTokenValid(StateToken st); + bool isTokenValid(StateToken st) const; ApiServer* mApiServer; // Methods to talk to the ApiServer @@ -37,6 +37,8 @@ private: void sendSelectedAccount(const std::string& ssl_id) const; void readAvailableAccounts(std::vector& accounts) const; void getRunningState() const ; + void readPasswordState(StateToken& password_state_token,bool& ask_for_password,std::string& key_name,bool& prev_is_bad) const; + void readRunState(StateToken& runstate_state_token, std::__cxx11::string& runstate) const; }; } // namespace resource_api diff --git a/retroshare-nogui/src/retroshare.cc b/retroshare-nogui/src/retroshare.cc index 2e0b5d443..b0273da51 100644 --- a/retroshare-nogui/src/retroshare.cc +++ b/retroshare-nogui/src/retroshare.cc @@ -108,16 +108,16 @@ int main(int argc, char **argv) if(!tac.isRunning()) { - if(!RsInit::isLocationRunning()) - { - std::cerr << "Terminal API client stopped but location not set ! Relaunching." ; - tac.start(); - } - else if(RsInit::isLocationRunning()) - { - std::cerr << "Terminal API client running but location already set ! Stopping it." ; - tac.shutdown(); - } +// if(!RsInit::isLocationRunning()) +// { +// std::cerr << "Terminal API client stopped but location not set ! Relaunching." ; +// tac.start(); +// } +// else if(RsInit::isLocationRunning()) +// { +// std::cerr << "Terminal API client running but location already set ! Stopping it." ; +// tac.shutdown(); +// } } } From 5465e1174fd043d425a7e22b948561af9952464d Mon Sep 17 00:00:00 2001 From: csoler Date: Sun, 9 Jul 2017 21:37:39 +0200 Subject: [PATCH 09/17] fixed debug output --- libresapi/src/api/RsControlModule.cpp | 5 +- retroshare-nogui/src/TerminalApiClient.cpp | 89 +++++----------------- retroshare-nogui/src/retroshare.cc | 17 ++--- 3 files changed, 27 insertions(+), 84 deletions(-) diff --git a/libresapi/src/api/RsControlModule.cpp b/libresapi/src/api/RsControlModule.cpp index 1d0cddd65..1e7f19b38 100644 --- a/libresapi/src/api/RsControlModule.cpp +++ b/libresapi/src/api/RsControlModule.cpp @@ -379,11 +379,14 @@ void RsControlModule::handlePassword(Request &req, Response &resp) mPassword = passwd; mWantPassword = false; mStateTokenServer->replaceToken(mStateToken); - +#ifdef DEBUG_CONTROL_MODULE std::cerr << "RsControlModule::handlePassword(): setting mPasswd=\"" << mPassword << "\"" << std::endl; +#endif } +#ifdef DEBUG_CONTROL_MODULE else std::cerr << "RsControlModule::handlePassword(): not setting mPasswd=\"" << mPassword << "\"!!!" << std::endl; +#endif resp.mDataStream << makeKeyValueReference("want_password", mWantPassword) diff --git a/retroshare-nogui/src/TerminalApiClient.cpp b/retroshare-nogui/src/TerminalApiClient.cpp index 81eebe6b4..cc20c2fb3 100644 --- a/retroshare-nogui/src/TerminalApiClient.cpp +++ b/retroshare-nogui/src/TerminalApiClient.cpp @@ -54,7 +54,7 @@ public: // restore terminal settings tcsetattr(STDIN_FILENO, TCSANOW, &mOldTermSettings); #ifdef TERMINALINPUT_DEBUG - std::cerr << "Terminal restored" << std::endl; + std::cerr << "Terminal killed" << std::endl; #endif #endif } @@ -110,6 +110,7 @@ static std::string readStringFromKeyboard(bool passwd_mode) s += c ; } + putchar('\n'); return s ; } @@ -140,16 +141,21 @@ void TerminalApiClient::data_tick() bool ask_for_password = false; std::string key_name; +#ifdef TO_REMOVE TerminalInput term; +#endif while(!shouldStop()) { // assuming sleep_time >> work_time // so we don't have to check the absolute time, just sleep every cycle usleep(MIN_WAIT_TIME * 1000); - last_io_poll += MIN_WAIT_TIME; + last_event_api_poll += MIN_WAIT_TIME; +#ifdef TO_REMOVE + last_io_poll += MIN_WAIT_TIME; + if(last_io_poll >= IO_POLL_PERIOD) { last_io_poll = 0; @@ -181,6 +187,7 @@ void TerminalApiClient::data_tick() //std::cout << "you pressed key " << (char) last_char << " as integer: " << last_char << std::endl; } } +#endif if(last_event_api_poll >= API_EVENT_POLL_PERIOD) { @@ -192,6 +199,15 @@ void TerminalApiClient::data_tick() password_state_token = StateToken(); } + // If the core has started, we leave. Maybe we should not use this in the future if we want to allow to + // log out and then log in again? + + if(runstate == "running_ok") + { + std::cerr << "Terminating terminal thread because the runstate says that the core is running." << std::endl; + shutdown(); + } + bool edge = false; if(runstate_state_token.isNull()) { @@ -251,75 +267,6 @@ void TerminalApiClient::data_tick() sendPassword(passwd) ; sendSelectedAccount(acc_ssl_id) ; } - -#ifdef OLD_CODE - if(!ask_for_password && edge && runstate == "waiting_account_select") - { - readAvailableAccounts(accounts) ; - account_number_size = (int)ceil(log(accounts.size())/log(10.0f)) ; - - for(uint32_t i=0;i= '0' && last_char <= '9') - { - std::cout.flush(); - selected_account_number = 10*selected_account_number + last_char - '0' ; - account_number_typed++ ; - - if(account_number_typed == account_number_size) - { - if(selected_account_number < accounts.size()) - { - std::cout.flush(); - std::cout << std::endl << "Selected account: " << accounts[selected_account_number].name << " (" << accounts[selected_account_number].location << ") SSL id: " << accounts[selected_account_number].ssl_id << std::endl; - - std::string acc_ssl_id = accounts[selected_account_number].ssl_id.toStdString(); - sendSelectedAccount(acc_ssl_id) ; - - inbuf.clear(); - } - else - { - std::cerr << ": invalid account number (should be between " << std::setw(account_number_size) << std::setfill('0') - << 0 << " and " << std::setw(account_number_size) << std::setfill('0') << accounts.size()-1 << ")" << std::endl; - std::cout << std::endl << "Type account number: " ; - std::cout.flush() ; - } - - account_number_typed = 0 ; - selected_account_number = 0 ; - } - } - - if(edge && ask_for_password) - { - std::cout << std::endl; - std::cout << std::endl; - std::cout << "Enter the password for key " << key_name << " : " ; - std::cout.flush() ; - } - - if(ask_for_password && enter_was_pressed && !inbuf.empty()) - { - std::cout << "TerminalApiClient: got a password" << std::endl; - - // Send passwd to api server - sendPassword(inbuf) ; - - usleep(1000*1000) ; - - // clears buffer - inbuf.clear(); - } -#endif } } diff --git a/retroshare-nogui/src/retroshare.cc b/retroshare-nogui/src/retroshare.cc index b0273da51..ef02bb623 100644 --- a/retroshare-nogui/src/retroshare.cc +++ b/retroshare-nogui/src/retroshare.cc @@ -101,23 +101,16 @@ int main(int argc, char **argv) resource_api::TerminalApiClient tac(&api); tac.start(); + bool already = false ; while(ctrl_mod.processShouldExit() == false) { - usleep(200*1000); + usleep(1000*1000); - if(!tac.isRunning()) + if(!tac.isRunning() && !already) { -// if(!RsInit::isLocationRunning()) -// { -// std::cerr << "Terminal API client stopped but location not set ! Relaunching." ; -// tac.start(); -// } -// else if(RsInit::isLocationRunning()) -// { -// std::cerr << "Terminal API client running but location already set ! Stopping it." ; -// tac.shutdown(); -// } + std::cerr << "Terminal API client terminated." << std::endl; + already = true ; } } From 2c6f11e4ebee43bc336e2b9f9baf484bbb661fac Mon Sep 17 00:00:00 2001 From: csoler Date: Sun, 9 Jul 2017 21:59:02 +0200 Subject: [PATCH 10/17] restored terminal output control class --- retroshare-nogui/src/TerminalApiClient.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/retroshare-nogui/src/TerminalApiClient.cpp b/retroshare-nogui/src/TerminalApiClient.cpp index cc20c2fb3..3c5e55703 100644 --- a/retroshare-nogui/src/TerminalApiClient.cpp +++ b/retroshare-nogui/src/TerminalApiClient.cpp @@ -141,9 +141,8 @@ void TerminalApiClient::data_tick() bool ask_for_password = false; std::string key_name; -#ifdef TO_REMOVE + // This is only used to remove echo from the input and allow us to replace it by what we want. TerminalInput term; -#endif while(!shouldStop()) { @@ -226,7 +225,7 @@ void TerminalApiClient::data_tick() account_number_size = (int)ceil(log(accounts.size())/log(10.0f)) ; for(uint32_t i=0;i Date: Sun, 9 Jul 2017 22:12:01 +0200 Subject: [PATCH 11/17] little improvement to command line help display --- libretroshare/src/rsserver/rsinit.cc | 9 ++++++--- libretroshare/src/util/argstream.h | 14 ++++++++------ 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/libretroshare/src/rsserver/rsinit.cc b/libretroshare/src/rsserver/rsinit.cc index 36572404f..51f82a275 100644 --- a/libretroshare/src/rsserver/rsinit.cc +++ b/libretroshare/src/rsserver/rsinit.cc @@ -89,6 +89,7 @@ // #define GPG_DEBUG // #define AUTHSSL_DEBUG // #define FIM_DEBUG +// #define DEBUG_RSINIT //std::map > RsInit::unsupported_keys ; @@ -311,8 +312,10 @@ int RsInit::InitRetroShare(int argc, char **argv, bool /* strictCheck */) argc = i; #endif +#ifdef DEBUG_RSINIT for(int i=0; i> 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" ,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('U',"user-id" ,prefUserString ,"ID", "[ocation Id] Sets Account to Use, Useful when Autologin is enabled.",false) // by rshare 'r' "link" "Link" "Open RsLink with protocol retroshare://" // by rshare 'f' "rsfile" "RsFile" "Open RsFile like RsCollection" #ifdef LOCALNET_TESTING @@ -365,7 +368,7 @@ int RsInit::InitRetroShare(int argc, char **argv, bool /* strictCheck */) #endif >> help('h',"help","Display this Help") ; - as.defaultErrorHandling(true) ; + as.defaultErrorHandling(true,true) ; if(rsInitConfig->autoLogin) rsInitConfig->startMinimised = true ; if(rsInitConfig->outStderr) rsInitConfig->haveLogFile = false ; @@ -472,7 +475,7 @@ int RsInit::InitRetroShare(int argc, char **argv, bool /* strictCheck */) { if (!rsAccounts->selectAccountByString(prefUserString)) { - std::cerr << "Invalid User name/GPG id/SSL id: not found in list"; + std::cerr << "Invalid User location id: not found in list"; std::cerr << std::endl; return RS_INIT_AUTH_FAILED ; } diff --git a/libretroshare/src/util/argstream.h b/libretroshare/src/util/argstream.h index a628147e0..1d7901fcc 100644 --- a/libretroshare/src/util/argstream.h +++ b/libretroshare/src/util/argstream.h @@ -252,8 +252,8 @@ namespace inline bool helpRequested() const; inline bool isOk() const; inline std::string errorLog() const; - inline std::string usage() const; - inline bool defaultErrorHandling(bool ignoreUnused=false) const; + inline std::string usage(bool skipCommandLine = false) const; + inline bool defaultErrorHandling(bool ignoreUnused=false,bool skipCommandLine=false) const; static inline char uniqueLetter(); protected: void parse(int argc,char** argv); @@ -569,10 +569,12 @@ namespace return helpRequested_; } inline std::string - argstream::usage() const + argstream::usage(bool skipCommandLine) const { std::ostringstream os; - os<<"usage: "<::const_iterator iter = argHelps_.begin();iter != argHelps_.end();++iter) @@ -820,11 +822,11 @@ namespace return s; } inline bool - argstream::defaultErrorHandling(bool ignoreUnused) const + argstream::defaultErrorHandling(bool ignoreUnused,bool skipCommandLine) const { if (helpRequested_) { - std::cout< Date: Tue, 11 Jul 2017 23:32:22 +0200 Subject: [PATCH 12/17] fixed -U option in rs-nogui. Removed debug output that would ruin the terminal interface --- libretroshare/src/pqi/authgpg.cc | 7 ++++++- libretroshare/src/rsserver/rsaccounts.cc | 13 +++++++++++- libretroshare/src/rsserver/rsinit.cc | 21 +++++++++++++------- libretroshare/src/rsserver/rsloginhandler.cc | 7 ++++++- retroshare-nogui/src/TerminalApiClient.cpp | 11 ++++++++++ 5 files changed, 49 insertions(+), 10 deletions(-) diff --git a/libretroshare/src/pqi/authgpg.cc b/libretroshare/src/pqi/authgpg.cc index 32b42461a..b437fb855 100644 --- a/libretroshare/src/pqi/authgpg.cc +++ b/libretroshare/src/pqi/authgpg.cc @@ -46,6 +46,8 @@ #define LIMIT_CERTIFICATE_SIZE 1 #define MAX_CERTIFICATE_SIZE 10000 +//#define DEBUG_AUTHGPG 1 + const time_t STORE_KEY_TIMEOUT = 1 * 60 * 60; //store key is call around every hour AuthGPG *AuthGPG::_instance = NULL ; @@ -88,7 +90,6 @@ bool AuthGPG::encryptTextToFile(const std::string& text,const std::string& outfi std::string pgp_pwd_callback(void * /*hook*/, const char *uid_title, const char *uid_hint, const char * /*passphrase_info*/, int prev_was_bad,bool *cancelled) { -#define GPG_DEBUG2 #ifdef GPG_DEBUG2 fprintf(stderr, "pgp_pwd_callback() called.\n"); #endif @@ -162,7 +163,9 @@ AuthGPG::AuthGPG(const std::string& path_to_public_keyring,const std::string& pa */ int AuthGPG::GPGInit(const RsPgpId &ownId) { +#ifdef DEBUG_AUTHGPG std::cerr << "AuthGPG::GPGInit() called with own gpg id : " << ownId.toStdString() << std::endl; +#endif mOwnGpgId = RsPgpId(ownId); @@ -170,7 +173,9 @@ int AuthGPG::GPGInit(const RsPgpId &ownId) privateTrustCertificate(ownId, 5); updateOwnSignatureFlag(mOwnGpgId) ; +#ifdef DEBUG_AUTHGPG std::cerr << "AuthGPG::GPGInit finished." << std::endl; +#endif return 1; } diff --git a/libretroshare/src/rsserver/rsaccounts.cc b/libretroshare/src/rsserver/rsaccounts.cc index 27b6816c2..236c2af4d 100644 --- a/libretroshare/src/rsserver/rsaccounts.cc +++ b/libretroshare/src/rsserver/rsaccounts.cc @@ -109,6 +109,8 @@ bool RsAccountsDetail::checkAccountDirectory() return setupAccount(PathAccountDirectory()); } +#warning we need to clean that up. Login should only ask for a SSL id, instead of a std::string. + bool RsAccountsDetail::selectAccountByString(const std::string &prefUserString) { if (mAccountsLocked) @@ -137,9 +139,14 @@ bool RsAccountsDetail::selectAccountByString(const std::string &prefUserString) { mPreferredId = it->second.mSslId; pgpNameFound = true; + + std::cerr << "Account selected: " << ssl_id << std::endl; + + return true; } } - return pgpNameFound; + std::cerr << "No suitable candidate found." << std::endl; + return false; } @@ -872,12 +879,16 @@ bool RsAccountsDetail::SelectPGPAccount(const RsPgpId& pgpId) if (0 < AuthGPG::getAuthGPG() -> GPGInit(pgpId)) { retVal = true; +#ifdef DEBUG_ACCOUNTS std::cerr << "PGP Auth Success!"; +#endif } else std::cerr << "PGP Auth Failed!"; +#ifdef DEBUG_ACCOUNTS std::cerr << " ID: " << pgpId << std::endl; +#endif return retVal; } diff --git a/libretroshare/src/rsserver/rsinit.cc b/libretroshare/src/rsserver/rsinit.cc index 51f82a275..5085d7fe6 100644 --- a/libretroshare/src/rsserver/rsinit.cc +++ b/libretroshare/src/rsserver/rsinit.cc @@ -466,21 +466,28 @@ int RsInit::InitRetroShare(int argc, char **argv, bool /* strictCheck */) // load Accounts. if (!rsAccounts->loadAccounts()) - { return RS_INIT_NO_KEYRING ; - } // choose alternative account. if(prefUserString != "") { - if (!rsAccounts->selectAccountByString(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->selectId(ssl_id)) + { + std::cerr << "Auto-selectng account ID " << ssl_id << std::endl; + return RS_INIT_HAVE_ACCOUNT; + } } +#ifdef TO_REMOVE /* check that we have selected someone */ RsPeerId preferredId; bool existingUser = rsAccounts->getPreferredAccountId(preferredId); @@ -488,9 +495,6 @@ int RsInit::InitRetroShare(int argc, char **argv, bool /* strictCheck */) if (existingUser) { if (rsInitConfig->passwd != "") - { - return RS_INIT_HAVE_ACCOUNT; - } if(RsLoginHandler::getSSLPassword(preferredId,false,rsInitConfig->passwd)) { @@ -499,8 +503,9 @@ int RsInit::InitRetroShare(int argc, char **argv, bool /* strictCheck */) return RS_INIT_HAVE_ACCOUNT; } } +#endif return RS_INIT_OK; - } +} /* @@ -638,7 +643,9 @@ int RsInit::LoadCertificates(bool autoLoginNT) if(rsInitConfig->passwd == "") { if (RsLoginHandler::getSSLPassword(preferredId,true,rsInitConfig->passwd) == false) { +#ifdef DEBUG_RSINIT std::cerr << "RsLoginHandler::getSSLPassword() Failed!"; +#endif return 0 ; } } else { diff --git a/libretroshare/src/rsserver/rsloginhandler.cc b/libretroshare/src/rsserver/rsloginhandler.cc index b6558c991..7c031ef45 100644 --- a/libretroshare/src/rsserver/rsloginhandler.cc +++ b/libretroshare/src/rsserver/rsloginhandler.cc @@ -5,6 +5,8 @@ #include "util/rsdir.h" #include "rsaccounts.h" +//#define DEBUG_RSLOGINHANDLER 1 + bool RsLoginHandler::getSSLPassword( const RsPeerId& ssl_id, bool enable_gpg_ask_passwd, std::string& ssl_passwd ) @@ -59,18 +61,21 @@ bool RsLoginHandler::getSSLPasswdFromGPGFile(const RsPeerId& ssl_id,std::string& fclose(sslPassphraseFile); +#ifdef DEBUG_RSLOGINHANDLER std::cerr << "opening sslPassphraseFile : " << getSSLPasswdFileName(ssl_id).c_str() << std::endl; +#endif std::string plain; if ( AuthGPG::getAuthGPG()->decryptTextFromFile( plain, getSSLPasswdFileName(ssl_id)) ) { sslPassword = plain; - +#ifdef DEBUG_RSLOGINHANDLER if(sslPassword.length() > 0) std::cerr << "Decrypting went ok !" << std::endl; else std::cerr << "Passphrase is empty!" << std::endl; +#endif return sslPassword.length() > 0 ; } diff --git a/retroshare-nogui/src/TerminalApiClient.cpp b/retroshare-nogui/src/TerminalApiClient.cpp index 3c5e55703..cdd23cb48 100644 --- a/retroshare-nogui/src/TerminalApiClient.cpp +++ b/retroshare-nogui/src/TerminalApiClient.cpp @@ -266,6 +266,17 @@ void TerminalApiClient::data_tick() sendPassword(passwd) ; sendSelectedAccount(acc_ssl_id) ; } + else if(ask_for_password) + { + std::string prompt = "Enter the password for key " + key_name + " : " ; + std::cout << prompt ; + std::cout.flush(); + std::string passwd = readStringFromKeyboard(true); + + // now we have passwd and account number, so send it to the core. + + sendPassword(passwd) ; + } } } From 4cfdef5ff9e6c820ca82ef2e93a03a083e3b29ea Mon Sep 17 00:00:00 2001 From: csoler Date: Tue, 11 Jul 2017 23:39:04 +0200 Subject: [PATCH 13/17] do not display auto-login option when software is compiled without autologin --- libretroshare/src/rsserver/rsinit.cc | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/libretroshare/src/rsserver/rsinit.cc b/libretroshare/src/rsserver/rsinit.cc index 5085d7fe6..85a5da6f5 100644 --- a/libretroshare/src/rsserver/rsinit.cc +++ b/libretroshare/src/rsserver/rsinit.cc @@ -348,18 +348,21 @@ int RsInit::InitRetroShare(int argc, char **argv, bool /* strictCheck */) argstream as(argc,argv) ; - as >> option('a',"auto-login" ,rsInitConfig->autoLogin ,"AutoLogin (Windows Only) + StartMinimised") + as +#ifdef RS_AUTOLOGIN + >> option('a',"auto-login" ,rsInitConfig->autoLogin ,"AutoLogin (Windows Only) + StartMinimised") +#endif >> 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('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" ,opt_base_dir ,"directory", "Set base directory." ,false) + >> parameter('l',"log-file" ,rsInitConfig->logfname ,"logfile" ,"Set Log filename." ,false) + >> parameter('d',"debug-level" ,rsInitConfig->debugLevel ,"level" ,"Set debug level." ,false) + >> parameter('w',"password" ,rsInitConfig->passwd ,"password" ,"Set Login Password." ,false) + >> parameter('i',"ip-address" ,rsInitConfig->inet ,"nnn.nnn.nnn.nnn", "Force IP address to use (if cannot be detected)." ,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) // by rshare 'r' "link" "Link" "Open RsLink with protocol retroshare://" // by rshare 'f' "rsfile" "RsFile" "Open RsFile like RsCollection" From 1cdb971cf11e417672a4c654ebf7c3098da39e8b Mon Sep 17 00:00:00 2001 From: csoler Date: Tue, 11 Jul 2017 23:47:51 +0200 Subject: [PATCH 14/17] fixed compilation pb due to qtcreator bug --- retroshare-nogui/src/TerminalApiClient.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/retroshare-nogui/src/TerminalApiClient.h b/retroshare-nogui/src/TerminalApiClient.h index 632438124..1fbbb2bed 100644 --- a/retroshare-nogui/src/TerminalApiClient.h +++ b/retroshare-nogui/src/TerminalApiClient.h @@ -38,7 +38,7 @@ private: void readAvailableAccounts(std::vector& accounts) const; void getRunningState() const ; void readPasswordState(StateToken& password_state_token,bool& ask_for_password,std::string& key_name,bool& prev_is_bad) const; - void readRunState(StateToken& runstate_state_token, std::__cxx11::string& runstate) const; + void readRunState(StateToken& runstate_state_token, std::string& runstate) const; }; } // namespace resource_api From 66268c826726be86c887ec339474094cd8172140 Mon Sep 17 00:00:00 2001 From: csoler Date: Wed, 12 Jul 2017 18:48:06 +0200 Subject: [PATCH 15/17] fixed variable shadowing a parameter --- libretroshare/src/rsserver/rsinit.cc | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/libretroshare/src/rsserver/rsinit.cc b/libretroshare/src/rsserver/rsinit.cc index 85a5da6f5..aff871a4b 100644 --- a/libretroshare/src/rsserver/rsinit.cc +++ b/libretroshare/src/rsserver/rsinit.cc @@ -277,7 +277,7 @@ bool doPortRestrictions = false; #endif #endif -int RsInit::InitRetroShare(int argc, char **argv, bool /* strictCheck */) +int RsInit::InitRetroShare(int _argc, char **_argv, bool /* strictCheck */) { /******************************** WINDOWS/UNIX SPECIFIC PART ******************/ #ifdef WINDOWS_SYS @@ -310,6 +310,9 @@ int RsInit::InitRetroShare(int argc, char **argv, bool /* strictCheck */) } } argc = i; +#else + char **argv = _argv ; + int argc = _argc ; #endif #ifdef DEBUG_RSINIT From 00c1a9a7ff0f835e14f6b751a0eec299f90e489b Mon Sep 17 00:00:00 2001 From: csoler Date: Wed, 12 Jul 2017 22:53:35 +0200 Subject: [PATCH 16/17] fixed autologin --- libretroshare/src/rsserver/rsinit.cc | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/libretroshare/src/rsserver/rsinit.cc b/libretroshare/src/rsserver/rsinit.cc index aff871a4b..07a4905eb 100644 --- a/libretroshare/src/rsserver/rsinit.cc +++ b/libretroshare/src/rsserver/rsinit.cc @@ -362,16 +362,20 @@ int RsInit::InitRetroShare(int _argc, char **_argv, bool /* strictCheck */) >> parameter('l',"log-file" ,rsInitConfig->logfname ,"logfile" ,"Set Log filename." ,false) >> parameter('d',"debug-level" ,rsInitConfig->debugLevel ,"level" ,"Set debug level." ,false) +#ifdef TO_REMOVE + // This as removed because it is not used anymore. + >> parameter('w',"password" ,rsInitConfig->passwd ,"password" ,"Set Login Password." ,false) +#endif >> parameter('i',"ip-address" ,rsInitConfig->inet ,"nnn.nnn.nnn.nnn", "Force IP address to use (if cannot be detected)." ,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) // by rshare 'r' "link" "Link" "Open RsLink with protocol retroshare://" // by rshare 'f' "rsfile" "RsFile" "Open RsFile like RsCollection" - #ifdef LOCALNET_TESTING +#ifdef LOCALNET_TESTING >> parameter('R',"restrict-port" ,portRestrictions ,"port1-port2","Apply port restriction" ,false) - #endif +#endif >> help('h',"help","Display this Help") ; as.defaultErrorHandling(true,true) ; From fd452af0883ef749d8da9b6f406e771b80be2371 Mon Sep 17 00:00:00 2001 From: csoler Date: Wed, 12 Jul 2017 23:03:17 +0200 Subject: [PATCH 17/17] removed some debut output that perturbated the passwd command line --- libretroshare/src/rsserver/rsloginhandler.cc | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/libretroshare/src/rsserver/rsloginhandler.cc b/libretroshare/src/rsserver/rsloginhandler.cc index 7c031ef45..453f5442c 100644 --- a/libretroshare/src/rsserver/rsloginhandler.cc +++ b/libretroshare/src/rsserver/rsloginhandler.cc @@ -193,7 +193,9 @@ extern BOOL WINAPI CryptUnprotectData( bool RsLoginHandler::tryAutoLogin(const RsPeerId& ssl_id,std::string& ssl_passwd) { +#ifdef DEBUG_RSLOGINHANDLER std::cerr << "RsTryAutoLogin()" << std::endl; +#endif /******************************** WINDOWS/UNIX SPECIFIC PART ******************/ #ifndef __HAIKU__ @@ -202,7 +204,9 @@ bool RsLoginHandler::tryAutoLogin(const RsPeerId& ssl_id,std::string& ssl_passwd gchar *passwd = NULL; +#ifdef DEBUG_RSLOGINHANDLER std::cerr << "Using attribute: " << ssl_id << std::endl; +#endif if( gnome_keyring_find_password_sync(&my_schema, &passwd,"RetroShare SSL Id",ssl_id.toStdString().c_str(),NULL) == GNOME_KEYRING_RESULT_OK ) { std::cerr << "Got SSL passwd ********************" /*<< passwd*/ << " from gnome keyring" << std::endl; @@ -211,7 +215,9 @@ bool RsLoginHandler::tryAutoLogin(const RsPeerId& ssl_id,std::string& ssl_passwd } else { +#ifdef DEBUG_RSLOGINHANDLER std::cerr << "Could not get passwd from gnome keyring" << std::endl; +#endif return false ; }