bool OTKeypair::SaveAndReloadBothKeysFromTempFile( OTString * pstrOutputCert/*=NULL*/, const OTString * pstrReason/*=NULL*/, OTPassword * pImportPassword/*=NULL*/) { OT_ASSERT(NULL != m_pkeyPrivate); OT_ASSERT(NULL != m_pkeyPublic); // --------------------------------------------------------------- OTString strOutput; const bool bSuccess = this->SaveCertAndPrivateKeyToString(strOutput, pstrReason, pImportPassword); // --------------------------------------- if (bSuccess) { // todo security. Revisit this part during security audit. // const OTString strFilename("temp.nym"); // todo stop hardcoding. Plus this maybe should select a random number too. if (false == OTDB::StorePlainString(strOutput.Get(), OTFolders::Cert().Get(), strFilename.Get())) // temp.nym { OTLog::vError("%s: Failure storing new cert in temp file: %s\n", __FUNCTION__, strFilename.Get()); return false; } // ------------------------------------------ if (false == this->LoadBothKeysFromCertFile(OTFolders::Cert().Get(), strFilename, pstrReason, pImportPassword)) return false; // LoadBothKeysFromCertFile already has error logs, no need to log twice at this point. // ------------------------------------------ if (NULL != pstrOutputCert) pstrOutputCert->Set(strOutput); // Success! } return bSuccess; }
// append a string at the end of the current buffer. void OTString::Concatenate(const OTString & strBuf) { // _WIN32 static char * new_string = NULL; if (NULL == new_string) { new_string = new char[MAX_STRING_LENGTH]; // This only happens once. Static var. OT_ASSERT(NULL != new_string); } new_string[0] = '\0'; // _end _WIN32 if (Exists()) #ifdef _WIN32 { const char * pBuf = strBuf.Get(); sprintf_s(new_string, MAX_STRING_LENGTH, "%s%s", m_strBuffer, pBuf); } #else snprintf(new_string, MAX_STRING_LENGTH, "%s%s", m_strBuffer, strBuf.Get()); #endif else #ifdef _WIN32 {
// *********************************************************************** // // INI FILE // bool GetOTAppDataFolderLocation(OTString strIniFileDefault, OTString & strOTServerDataLocation) { CSimpleIniA ini; SI_Error rc = ini.LoadFile(strIniFileDefault.Get()); if (rc >=0) { { const char * pVal = ini.GetValue("paths", "server_path", SERVER_PATH_DEFAULT); // todo stop hardcoding. if (NULL != pVal) { strOTServerDataLocation.Set(pVal); OTLog::vOutput(0, "Reading ini file (%s). \n Found Server data_folder path: %s \n", strIniFileDefault.Get(), strOTServerDataLocation.Get()); return true; } OTLog::vOutput(0, "Reading ini file (%s) \n", strIniFileDefault.Get()); return false; } } else { OTLog::vOutput(0, "Unable to load ini file (%s) to find data_folder path \n", strIniFileDefault.Get()); return false; } }
int OTLog::Assert(const char * szFilename, int nLinenumber) { if ((NULL != szFilename)) { #ifndef ANDROID // if NOT android std::cerr << "OT_ASSERT in " << szFilename << " at line " << nLinenumber << "\n"; // ----------------------------- // Grab this if we can, too... // OTString strTemp; strTemp.Format("OT_ASSERT in %s at line %d\n", szFilename, nLinenumber); LogToFile(strTemp.Get()); // ----------------------------- #else // if Android OTString strAndroidAssertMsg; strAndroidAssertMsg.Format("\nOT_ASSERT in %s at line %d\n", szFilename, nLinenumber); __android_log_write(ANDROID_LOG_FATAL,"OT Assert", (const char *)strAndroidAssertMsg.Get()); #endif #ifndef _WIN32 print_stacktrace(); #endif } abort(); return -1; }
// Make sure Server Nym is set on this cron object before loading or saving, since it's // used for signing and verifying.. bool OTCron::LoadCron() { static const char * szCronFile = "OT-CRON.crn"; // todo stop hardcoding filenames. OT_ASSERT(NULL != GetServerNym()); // ------------------------------------------------------------------------ bool bFolderExists = OTLog::ConfirmOrCreateFolder(OTLog::CronFolder()); // <path>/cron is where all cronlogs go. if (!bFolderExists) { OTLog::vError("Unable to create or confirm folder \"%s\" in order to load Cron file.\n", OTLog::CronFolder()); return false; } // ------------------------------------------------------------------------ OTString strCronfileLocalPath; strCronfileLocalPath.Format("%s%s%s", OTLog::CronFolder(), OTLog::PathSeparator(), szCronFile); // ------------------------------------------------------------------------ OTString strCronfilePath; strCronfilePath.Format("%s%s%s", OTLog::Path(), OTLog::PathSeparator(), strCronfileLocalPath.Get()); std::ifstream in(strCronfilePath.Get(), std::ios::binary); if (in.fail()) { OTLog::vError("Error opening file in OTCron::LoadCron: %s\n", strCronfilePath.Get()); return false; } std::stringstream buffer; buffer << in.rdbuf(); std::string contents(buffer.str()); OTString strRawFile = contents.c_str(); bool bSuccess = false; if (strRawFile.GetLength()) { bSuccess = LoadContractFromString(strRawFile); if (bSuccess) { bSuccess = VerifySignature(*GetServerNym()); } } return bSuccess; // ------------------------------------------------------------------------ }
OTCronItem * OTCronItem::LoadCronReceipt(const long & lTransactionNum) { // ------------------------------------------------------------------------ bool bFolderExists = OTLog::ConfirmOrCreateFolder(OTLog::CronFolder()); // <path>/cron is where all cronlogs go. if (!bFolderExists) { OTLog::vError("Unable to create or confirm folder \"%s\"\n in order to load Cron Receipt %ld.\n", OTLog::CronFolder(), lTransactionNum); return NULL; } // ------------------------------------------------------------------------ OTString strCronItemLocalPath; strCronItemLocalPath.Format("%s%s%ld.crn", OTLog::CronFolder(), OTLog::PathSeparator(), lTransactionNum); bool bFileExists = OTLog::ConfirmFile(strCronItemLocalPath.Get()); if (!bFileExists) { OTLog::vError("Attempted to load non-existent Cron Record for transaction %ld in folder %s.\n", lTransactionNum, strCronItemLocalPath.Get()); return NULL; } // ------------------------------------------------------------------------ OTString strCronItemPath; strCronItemPath.Format("%s%s%s", OTLog::Path(), OTLog::PathSeparator(), strCronItemLocalPath.Get()); std::ifstream in(strCronItemPath.Get(), std::ios::binary); if (in.fail()) { OTLog::vError("Error opening file in OTCronItem::LoadCronReceipt: %s\n", strCronItemPath.Get()); return NULL; } std::stringstream buffer; buffer << in.rdbuf(); std::string contents(buffer.str()); OTString strRawFile = contents.c_str(); if (strRawFile.GetLength()) return OTCronItem::NewCronItem(strRawFile); return NULL; // ------------------------------------------------------------------------ }
bool OTMint::SaveMint(const char * szAppend/*=NULL*/) { if (!m_strFoldername.Exists()) m_strFoldername.Set(OTLog::MintFolder()); const OTString strServerID(m_ServerID), strAssetTypeID(m_AssetID); if (!m_strFilename.Exists()) { if (NULL != szAppend) m_strFilename.Format("%s%s%s%s", strServerID.Get(), OTLog::PathSeparator(), strAssetTypeID.Get(), szAppend); else m_strFilename.Format("%s%s%s", strServerID.Get(), OTLog::PathSeparator(), strAssetTypeID.Get()); } OTString strFilename; if (NULL != szAppend) strFilename.Format("%s%s", strAssetTypeID.Get(), szAppend); else strFilename = strAssetTypeID.Get(); const char * szFolder1name = OTLog::MintFolder(); const char * szFolder2name = strServerID.Get(); const char * szFilename = strFilename.Get(); // -------------------------------------------------------------------- OTString strRawFile; if (!SaveContractRaw(strRawFile)) { OTLog::vError("Error saving Mintfile (to string):\n%s%s%s%s%s\n", szFolder1name, OTLog::PathSeparator(), szFolder2name, OTLog::PathSeparator(), szFilename); return false; } // -------------------------------------------------------------------- // bool bSaved = OTDB::StorePlainString(strRawFile.Get(), szFolder1name, szFolder2name, szFilename); // <=== SAVING TO DATA STORE. if (!bSaved) { if (NULL != szAppend) OTLog::vError("OTMint::SaveMint: Error writing to file: %s%s%s%s%s%s\n", szFolder1name, OTLog::PathSeparator(), szFolder2name, OTLog::PathSeparator(), szFilename, szAppend); else OTLog::vError("OTMint::SaveMint: Error writing to file: %s%s%s%s%s\n", szFolder1name, OTLog::PathSeparator(), szFolder2name, OTLog::PathSeparator(), szFilename); return false; } // -------------------------------------------------------------------- return true; }
_OT_Lucre_Dumper::_OT_Lucre_Dumper() { #ifdef _WIN32 OTString OpenSSLDumpFilename; // todo security. We shouldn't necessarily be dumping this info to file AT ALL. OpenSSLDumpFilename.Format("%s%s%s",OTLog::Path(),OTLog::PathSeparator,"openssl.dumpfile"); // todo hardcoding. SetDumper(OpenSSLDumpFilename.Get()); // We are only dumping this way currently as a temporary solution to the applink.c openssl thing that can cause crashes in Lucre when withdrawing cash. (Caused by da2ce7 removing Lucre from OT and moving it into a dylib.) m_str_dumpfile = OpenSSLDumpFilename.Get(); #else SetDumper(stderr); #endif }
// ----------------------------------- __ot_server_() : m_pServer(NULL) // INIT { // ----------------------------------------------------------------------- // ----------------------------------------------------------------------- // OTLog class exists on both client and server sides. // #define OT_NO_SIGNAL_HANDLING if you want to turn off OT's signal handling. // #if defined(OT_SIGNAL_HANDLING) OTLog::SetupSignalHandler(); // This is optional! (I, of course, am using it in this test app...) #endif // ----------------------------------------------------------------------- // I instantiate this here (instead of globally) so that I am assured that any globals and other // setup is already done before we instantiate the server object itself. // OT_ASSERT_MSG(NULL == m_pServer, "server main(): ASSERT: NULL == m_pServer."); m_pServer = new OTServer; // // (This .cpp file you are currently reading is a wrapper for OTServer, // which adds the transport layer.) // OT_ASSERT_MSG(NULL != m_pServer, "server main(): ASSERT: Unable to instantiate OT server.\n"); OTString pathUserAppDataPath, pathIniFileLocation; pathUserAppDataPath = GetRoamingAppDataLocation(); pathIniFileLocation.Format("%s%s%s", pathUserAppDataPath.Get(), OTLog::PathSeparator(), SERVER_INI_FILE_DEFAULT); OTString pathOTServerDataLocation; OTLog::vOutput(0, "\nFound ot_init.cfg in: \n %s \nNow checking to see if it contains the OT Server path...", pathIniFileLocation.Get()); // Read the File, If successful use result if (false == GetOTAppDataFolderLocation(pathIniFileLocation, pathOTServerDataLocation)) { OTLog::vOutput(0, "Path not found... Will attempt default!... \n"); // Not successfull will will assume it is in default location: pathOTServerDataLocation.Format("%s%s%s", pathUserAppDataPath.Get(), OTLog::PathSeparator(), SERVER_PATH_DEFAULT); }; OTLog::vOutput(0, " %s \n", pathOTServerDataLocation.Get()); OTLog::SetMainPath(pathOTServerDataLocation.Get()); // <============ SET MAIN PATH OTLog::vOutput(0, "Using server_data path: %s\n", OTLog::Path()); // ----------------------------------------------------------------------- OTCrypto::It()->Init(); // <========== (OpenSSL gets initialized here.) }
// This code reads up the file, discards the bookends, and saves only the gibberish itself. bool OTASCIIArmor::LoadFromFile(const OTString & filename) { std::ifstream fin(filename.Get(), std::ios::binary); if (!fin.is_open()) { OTLog::vError("Error opening file in OTASCIIArmor::LoadFromFile: %s\n", filename.Get()); return false; } return LoadFromifstream(fin); }
const bool OTSettings::LogChange_bool(const OTString & strSection,const OTString & strKey,const bool & bValue ) { if (! strSection.Exists()) { OTLog::vError("%s: Error: %s is Empty!\n", __FUNCTION__, "strSection" ); OT_ASSERT(false); } if (! strKey.Exists()) { OTLog::vError("%s: Error: %s is Empty!\n", __FUNCTION__, "strKey" ); OT_ASSERT(false); } OTString strCategory, strOption; if (!OTLog::StringFill(strCategory,strSection.Get(),12)) return false; if (!OTLog::StringFill(strOption,strKey.Get(),30," to:")) return false; OTLog::vOutput(1, "Setting %s %s %s \n",strCategory.Get(),strOption.Get(),bValue ? "true" : "false"); return true; }
bool OTToken::RecordTokenAsSpent(OTString & theCleartextToken) { OTString strAssetID(GetAssetID()); // ---------------------------------------------------------------------------- // Calculate the filename (a hash of the Lucre cleartext token ID) OTIdentifier theTokenHash; theTokenHash.CalculateDigest(theCleartextToken); // Grab the new hash into a string (for use as a filename) OTString strTokenHash(theTokenHash); OTString strAssetFolder; strAssetFolder.Format("%s.%d", strAssetID.Get(), GetSeries()); // -------------------------------------------------------------------- // See if the spent token file ALREADY EXISTS... bool bTokenIsPresent = OTDB::Exists(OTLog::SpentFolder(), strAssetFolder.Get(), strTokenHash.Get()); // If so, we're trying to record a token that was already recorded... if (bTokenIsPresent) { OTLog::vError("OTToken::RecordTokenAsSpent: Trying to record token as spent," " but it was already recorded: %s%s%s%s%s\n", OTLog::SpentFolder(), OTLog::PathSeparator(), strAssetFolder.Get(), OTLog::PathSeparator(), strTokenHash.Get()); return false; } // ---------------------------------------------------------------------- // FINISHED: // We actually save the token itself into the file, which is named based // on a hash of the Lucre data. // The success of that operation is also now the success of this one. OTString strToken; SaveContract(strToken); bool bSaved = OTDB::StorePlainString(strToken.Get(), OTLog::SpentFolder(), strAssetFolder.Get(), strTokenHash.Get()); if (!bSaved) { OTLog::vError("OTToken::RecordTokenAsSpent: Error saving file: %s%s%s%s%s\n", OTLog::SpentFolder(), OTLog::PathSeparator(), strAssetFolder.Get(), OTLog::PathSeparator(), strTokenHash.Get()); } return bSaved; }
// Lucre step 5: mint verifies token when it is redeemed by merchant. // This function is called by OTToken::VerifyToken. // That's the one you should be calling, most likely, not this one. bool OTMint_Lucre::VerifyToken(OTPseudonym & theNotary, OTString & theCleartextToken, int64_t lDenomination) { bool bReturnValue = false; // OTLog::Error("%s <bank info> <coin>\n", argv[0]); _OT_Lucre_Dumper setDumper; OpenSSL_BIO bioBank = BIO_new(BIO_s_mem()); // input OpenSSL_BIO bioCoin = BIO_new(BIO_s_mem()); // input // --- copy theCleartextToken to bioCoin so lucre can load it BIO_puts(bioCoin, theCleartextToken.Get()); // --- The Mint private info is encrypted in m_mapPrivate[lDenomination]. // So I need to extract that first before I can use it. OTASCIIArmor theArmor; GetPrivate(theArmor, lDenomination); OTEnvelope theEnvelope(theArmor); OTString strContents; // will contain output from opening the envelope. // Decrypt the Envelope into strContents if (theEnvelope.Open(theNotary, strContents)) { // copy strContents to a BIO BIO_puts(bioBank, strContents.Get()); // ---- Now the bank and coin bios are both ready to go... Bank bank(bioBank); Coin coin(bioCoin); if (bank.Verify(coin)) // Here's the boolean output: coin is verified! { bReturnValue = true; // (Done): When a token is redeemed, need to store it in the spent token database. // Right now I can verify the token, but unless I check it against a database, then // even though the signature verifies, it doesn't stop people from redeeming the same // token again and again and again. // // (done): also need to make sure issuer has double-entries for total amount outstanding. // // UPDATE: These are both done now. The Spent Token database is implemented in the transaction server, // (not OTLib proper) and the same server also now keeps a cash account to match all cash withdrawals. // (Meaning, if 10,000 clams total have been withdrawn by various users, then the server actually has // a clam account containing 10,000 clams. As the cash comes in for redemption, the server debits it from // this account again before sending it to its final destination. This way the server tracks total outstanding // amount, as an additional level of security after the blind signature itself.) } } return bReturnValue; }
const bool OTSettings::Set_long(const OTString & strSection, const OTString & strKey, const long & lValue, bool & out_bNewOrUpdate, const OTString & strComment) { if (! strSection.Exists()) { OTLog::vError("%s: Error: %s is Empty!\n", __FUNCTION__, "strSection" ); OT_ASSERT(false); } if (strSection.Compare("")) { OTLog::vError("%s: Error: %s is Blank!\n", __FUNCTION__, "strSection" ); OT_ASSERT(false); } if (! strKey.Exists()) { OTLog::vError("%s: Error: %s is Empty!\n", __FUNCTION__, "strKey" ); OT_ASSERT(false); } if (strKey.Compare("")) { OTLog::vError("%s: Error: %s is Blank!\n", __FUNCTION__, "strKey" ); OT_ASSERT(false); } OTString strValue; strValue.Format("%ld",lValue); const char * const szComment = (strComment.Exists() && !strComment.Compare("")) ? strComment.Get() : NULL; OTString strOldValue, strNewValue; bool bOldKeyExist, bNewKeyExist; // Check if Old Key exists. if(! Check_str(strSection,strKey,strOldValue,bOldKeyExist)) return false; if (bOldKeyExist) { if (strValue.Compare(strOldValue)) { out_bNewOrUpdate = false; return true; } } // Log to Output Setting Change if (! LogChange_str(strSection,strKey,strValue)) return false; // Set New Value SI_Error rc = p_iniSimple -> SetLongValue(strSection.Get(),strKey.Get(),lValue,szComment,false,true); if (0 > rc) return false; // Check if the new value is the same as intended. if (! Check_str(strSection,strKey,strNewValue,bNewKeyExist)) return false; if (bNewKeyExist) { if (strValue.Compare(strNewValue)) { // Success out_bNewOrUpdate = true; return true; } } // If we get here, error! OT_ASSERT(false); return false; }
const bool OTSettings::LogChange_str (const OTString & strSection,const OTString & strKey,const OTString & strValue) { if (! strSection.Exists()) { OTLog::vError("%s: Error: %s is Empty!\n", __FUNCTION__, "strSection" ); OT_ASSERT(false); } if (! strKey.Exists()) { OTLog::vError("%s: Error: %s is Empty!\n", __FUNCTION__, "strKey" ); OT_ASSERT(false); } const char * const szValue = (strValue.Exists() && !strValue.Compare("") ) ? strValue.Get() : "NULL"; OTString strCategory, strOption; if (!OTLog::StringFill(strCategory,strSection.Get(),12)) return false; if (!OTLog::StringFill(strOption,strKey.Get(),30," to:")) return false; OTLog::vOutput(1, "Setting %s %s %s \n",strCategory.Get(),strOption.Get(),szValue); return true; }
// static bool OTKeyring::Gnome_StoreSecret(const OTString& strUser, const OTPassword& thePassword, const std::string& str_display) { OT_ASSERT(strUser.Exists()); OT_ASSERT(thePassword.getMemorySize() > 0); OTData theData(thePassword.getMemory(), thePassword.getMemorySize()); OTASCIIArmor ascData(theData); theData.zeroMemory(); // security reasons. OTString strOutput; const bool bSuccess = ascData.Exists() && ascData.WriteArmoredString(strOutput, "DERIVED KEY"); // There's no // default, to // force you to // enter the right // string. ascData.zeroMemory(); GnomeKeyringResult theResult = GNOME_KEYRING_RESULT_IO_ERROR; if (bSuccess && strOutput.Exists()) { theResult = gnome_keyring_store_password_sync( GNOME_KEYRING_NETWORK_PASSWORD, GNOME_KEYRING_DEFAULT, // GNOME_KEYRING_SESSION, str_display.c_str(), strOutput.Get(), "user", strUser.Get(), "protocol", "opentxs", // todo: hardcoding. nullptr); strOutput.zeroMemory(); bool bResult = false; if (theResult == GNOME_KEYRING_RESULT_OK) bResult = true; else otErr << "OTKeyring::Gnome_StoreSecret: " << "Failure in gnome_keyring_store_password_sync: " << gnome_keyring_result_to_message(theResult) << '\n'; return bResult; } otOut << "OTKeyring::Gnome_StoreSecret: No secret to store.\n"; return false; }
bool OTAccount::DisplayStatistics(OTString & strContents) const { const OTString strAccountID(GetPurportedAccountID()), strServerID(GetPurportedServerID()), strUserID(GetUserID()), strAssetTypeID(m_AcctAssetTypeID); OTString strAcctType; TranslateAccountTypeToString(m_AcctType, strAcctType); strContents.Concatenate( " Asset Account (%s) Name: %s\n" " Last retrieved Balance: %s on date: %s\n" " accountID: %s\n" " userID: %s\n" " serverID: %s\n" " assetTypeID: %s\n" "\n", strAcctType.Get(), m_strName.Get(), m_BalanceAmount.Get(), m_BalanceDate.Get(), strAccountID.Get(), strUserID.Get(), strServerID.Get(), strAssetTypeID.Get()); return true; }
bool OTAccount::SaveAccount() { OTString strID; GetIdentifier(strID); m_strFilename.Format("%s%s%s%s%s", OTLog::Path(), OTLog::PathSeparator(), OTLog::AccountFolder(), OTLog::PathSeparator(), strID.Get()); // the const char * version (used here) expects a filename. // If I passed in the OTString it would try to save to that string instead of opening the file. OTString strTemp(m_strFilename); bool bSaved = SaveContract(strTemp.Get()); if (bSaved) { OTLog::vOutput(2, "Successfully saved account: %s\nFilename: %s\n", m_strFilename.Get(), strTemp.Get()); } else { OTLog::vError("Error saving account: %s\nFilename: %s\n", m_strFilename.Get(), strTemp.Get()); } return bSaved; }
// static bool OTKeyring::IOS_DeleteSecret(const OTString& strUser, const std::string& str_display) { OT_ASSERT(strUser.Exists()); CFStringRef service_name = CFSTR("opentxs"); CFStringRef account_name = CFStringCreateWithCString(nullptr, strUser.Get(), kCFStringEncodingUTF8); const void* keys[] = {kSecClass, kSecAttrService, kSecAttrAccount}; const void* values[] = {kSecClassGenericPassword, service_name, account_name}; CFDictionaryRef query = CFDictionaryCreate(nullptr, keys, values, 3, nullptr, nullptr); OSStatus theError = SecItemDelete(query); CFRelease(query); CFRelease(account_name); if (theError != noErr) { otErr << "OTKeyring::IOS_RetrieveSecret: Error in SecItemDelete.\n"; return false; } return true; }
// static bool OTKeyring::IOS_RetrieveSecret(const OTString& strUser, OTPassword& thePassword, const std::string& str_display) { OT_ASSERT(strUser.Exists()); CFStringRef service_name = CFSTR("opentxs"); CFStringRef account_name = CFStringCreateWithCString(nullptr, strUser.Get(), kCFStringEncodingUTF8); CFDataRef vData = nullptr; const void* keys[] = {kSecClass, kSecAttrService, kSecAttrAccount, kSecReturnData}; const void* values[] = {kSecClassGenericPassword, service_name, account_name, kCFBooleanTrue}; CFDictionaryRef query = CFDictionaryCreate(nullptr, keys, values, 4, nullptr, nullptr); OSStatus theError = SecItemCopyMatching(query, (CFTypeRef*)&vData); CFRelease(query); CFRelease(account_name); if (theError != noErr) { otErr << "OTKeyring::IOS_RetrieveSecret: Error in SecItemCopyMatching.\n"; return false; } thePassword.setMemory(CFDataGetBytePtr(vData), CFDataGetLength(vData)); CFRelease(vData); return true; }
// static bool OTKeyring::IOS_StoreSecret(const OTString& strUser, const OTPassword& thePassword, const std::string& str_display) { OT_ASSERT(strUser.Exists()); OT_ASSERT(thePassword.getMemorySize() > 0); CFStringRef service_name = CFSTR("opentxs"); CFStringRef account_name = CFStringCreateWithCString(nullptr, strUser.Get(), kCFStringEncodingUTF8); CFDataRef vData = CFDataCreateWithBytesNoCopy( nullptr, thePassword.getMemory_uint8(), thePassword.getMemorySize(), kCFAllocatorNull); const void* keys[] = {kSecClass, kSecAttrService, kSecAttrAccount, kSecValueData}; const void* values[] = {kSecClassGenericPassword, service_name, account_name, vData}; CFDictionaryRef item = CFDictionaryCreate(nullptr, keys, values, 4, nullptr, nullptr); OSStatus theError = SecItemAdd(item, nullptr); CFRelease(item); CFRelease(vData); CFRelease(account_name); if (theError != noErr) { otErr << "OTKeyring::IOS_StoreSecret: Error in SecItemAdd.\n"; return false; } return true; }
// static bool OTKeyring::Mac_StoreSecret(const OTString& strUser, const OTPassword& thePassword, const std::string& str_display) { OT_ASSERT(strUser.Exists()); OT_ASSERT(thePassword.getMemorySize() > 0); const std::string service_name = "opentxs"; const std::string account_name = strUser.Get(); OTMacKeychain theKeychain; void* vData = const_cast<void*>(static_cast<const void*>(thePassword.getMemory())); OSStatus theError = theKeychain.AddSecret( nullptr, service_name.size(), service_name.data(), account_name.size(), account_name.data(), thePassword.getMemorySize(), vData, // thePassword.getMemory() nullptr); if (theError != noErr) { otErr << "OTKeyring::Mac_StoreSecret: Error in theKeychain.AddSecret.\n"; return false; } return true; }
// static bool OTKeyring::KWallet_DeleteSecret(const OTString& strUser, const std::string& str_display) { OT_ASSERT(strUser.Exists()); KWallet::Wallet* pWallet = OTKeyring::OpenKWallet(); if (nullptr != pWallet) { const QString qstrKey(strUser.Get()); bool bResult = false; if (pWallet->removeEntry(qstrKey) == 0) // delete the entry bResult = true; else otErr << "OTKeyring::KWallet_DeleteSecret: Failed trying to erase " "secret from KWallet.\n"; return bResult; } otErr << "OTKeyring::KWallet_DeleteSecret: Unable to open kwallet.\n"; return false; }
// --------------------------------------- bool MTRecord::FormatShortMailDescription(std::string & str_output) { OTString strDescription; if (IsMail()) { if (!HasContents()) strDescription.Set("(empty message)"); else { std::string str_contents = GetContents(); if (str_contents.compare(0,8,"Subject:") == 0) { // Make the replacement. str_contents.replace(0, 8, ""); } // ----------------------------------- bool bTruncated = false; if (str_contents.size() > 30) { str_contents.erase(30, std::string::npos); bTruncated = true; } // ----------------------------------- strDescription.Format("\"%s%s\"", OTString::trim(str_contents).c_str(), bTruncated ? "..." : ""); } } // ----------------------------- str_output = strDescription.Get(); // ----------------------------- return (!str_output.empty()); }
bool OTAccount::SaveAccount() { OTString strID; GetIdentifier(strID); return SaveContract(OTFolders::Account().Get(), strID.Get()); }
// if you pass in a master key ID, it will look it up on an existing cached map of master keys. // Otherwise it will use "the" global Master Key (the one used for the Nyms.) // //static OTCachedKey * OTCachedKey::It(OTIdentifier * pIdentifier/*=NULL*/) { // For now we're only allowing a single global instance, unless you pass in an ID, in which case we keep a map. // static OTCachedKey s_theSingleton; // Default is 0 ("you have to type your PW a million times"), but it's overridden in config file. if (NULL == pIdentifier) return &s_theSingleton; // Notice if you pass NULL (no args) then it ALWAYS returns a good pointer here. // ---------------------------------------------------------------- // There is a chance of failure if you pass an ID, since maybe it's not already on the map. // But at least by this point we know FOR SURE that pIdentifier is NOT NULL. // const OTString strIdentifier (*pIdentifier); const std::string str_identifier(strIdentifier.Get()); mapOfCachedKeys::iterator it_keys = s_mapCachedKeys.find(str_identifier); if (s_mapCachedKeys.end() != it_keys) // found it! { OTCachedKey * pMaster = it_keys->second; return pMaster; } // ---------------------------------------------------------------------- // else: We can't instantiate it, since we don't have the corresponding CachedKey, just its // Identifier. We're forced simply to return NULL in this case. // // Therefore you should normally pass in the master key (the same one that you want to cache a copy // of) using the below version of It(). That version creates the copy, if it's not already there. // return NULL; }
bool OTAccount::SaveContractWallet(OTString & strContents) const { const OTString strAccountID(GetPurportedAccountID()), strServerID(GetPurportedServerID()), strUserID(GetUserID()), strAssetTypeID(m_AcctAssetTypeID); OTString strAcctType; TranslateAccountTypeToString(m_AcctType, strAcctType); OTASCIIArmor ascName; if (m_strName.Exists()) // name is in the clear in memory, and base64 in storage. { ascName.SetString(m_strName, false); // linebreaks == false } strContents.Concatenate("<!-- Last retrieved balance: %s on date: %s -->\n" "<!-- Account type: %s --><assetAccount name=\"%s\"\n" " accountID=\"%s\"\n" " userID=\"%s\"\n" " serverID=\"%s\" />\n" "<!-- assetTypeID: %s -->\n\n", m_BalanceAmount.Get(), m_BalanceDate.Get(), strAcctType.Get(), m_strName.Exists() ? ascName.Get() : "", strAccountID.Get(), strUserID.Get(), strServerID.Get(), strAssetTypeID.Get()); return true; }
// static bool OTKeyring::Mac_RetrieveSecret(const OTString& strUser, OTPassword& thePassword, const std::string& str_display) { OT_ASSERT(strUser.Exists()); const std::string service_name = "opentxs"; const std::string account_name = strUser.Get(); uint32_t password_length = 0; void* password_data = nullptr; OTMacKeychain theKeychain; OSStatus theError = theKeychain.FindSecret( nullptr, service_name.size(), service_name.data(), account_name.size(), account_name.data(), &password_length, // output. &password_data, nullptr); if (theError == noErr) { thePassword.setMemory(password_data, password_length); theKeychain.ItemFreeContent(nullptr, password_data); return true; } else otErr << "OTKeyring::Mac_RetrieveSecret: Error in " "theKeychain.FindSecret.\n"; return false; }
bool OTASCIIArmor::WriteArmoredString(OTString & strOutput, const // for "-----BEGIN OT LEDGER-----", str_type would contain "LEDGER" std::string str_type, // There's no default, to force you to enter the right string. bool bEscaped/*=false*/) { const char * szEscape = "- "; OTString strTemp; strTemp.Format("%s%s %s-----\n" // "%s-----BEGIN OT ARMORED %s-----\n" "Version: Open Transactions %s\n" "Comment: http://github.com/FellowTraveler/Open-Transactions/wiki\n\n" // todo hardcoding. "%s" // Should already have a newline at the bottom. "%s%s %s-----\n\n", // "%s-----END OT ARMORED %s-----\n" bEscaped ? szEscape : "", OT_BEGIN_ARMORED, str_type.c_str(), // "%s%s %s-----\n" OTLog::Version(), // "Version: Open Transactions %s\n" /* No variable */ // "Comment: http://github.com/FellowTraveler/Open-Transactions/wiki\n\n", this->Get(), // "%s" <==== CONTENTS OF THIS OBJECT BEING WRITTEN... bEscaped ? szEscape : "", OT_END_ARMORED, str_type.c_str()); // "%s%s %s-----\n" // ----------------------- strOutput.Concatenate("%s", strTemp.Get()); // ----------------------- return true; }
const bool OTPaths::PathExists(const OTString & strPath) { if (!strPath.Exists()) { OTLog::sError("%s: Null: %s passed in!\n", __FUNCTION__, "strPath" ); OT_ASSERT(false); } // remove trailing backslash for stat std::string l_strPath(strPath.Get()); l_strPath = (OTString::replace_chars(l_strPath,"\\",'/')); // all \ to / //std::string l_strPath_stat = l_strPath; std::string l_strPath_stat(""); // remove last / if it exists (for l_strPath_stat) if ('/' == *l_strPath.rbegin()) l_strPath_stat = l_strPath.substr(0, l_strPath.size()-1); else l_strPath_stat = l_strPath; struct stat st; memset(&st, 0, sizeof(st)); if (0 == stat(l_strPath_stat.c_str(), &st)) // good we have at-least on a node { if ('/' != *l_strPath.rbegin()) { long temp_l=0; return FileExists(strPath,temp_l); } else { return FolderExists(strPath); } } return false; }