bool Settings::LogChange_str(const String& strSection, const String& strKey,
                               const String& strValue)
{
    if (!strSection.Exists()) {
        otErr << __FUNCTION__ << ": Error: "
              << "strSection"
              << " is Empty!\n";
        OT_FAIL;
    }
    if (!strKey.Exists()) {
        otErr << __FUNCTION__ << ": Error: "
              << "strKey"
              << " is Empty!\n";
        OT_FAIL;
    }

    const char* const szValue = (strValue.Exists() && !strValue.Compare(""))
                                    ? strValue.Get()
                                    : "nullptr";

    String strCategory, strOption;
    if (!Log::StringFill(strCategory, strSection.Get(), 12)) return false;
    if (!Log::StringFill(strOption, strKey.Get(), 30, " to:")) return false;

    otWarn << "Setting " << strCategory << " " << strOption << " " << szValue
           << " \n";
    return true;
}
bool Settings::CheckSetSection(const String& strSection,
                                 const String& strComment,
                                 bool& out_bIsNewSection)
{
    if (!strSection.Exists()) {
        otErr << __FUNCTION__ << ": Error: "
              << "strSection"
              << " is Empty!\n";
        OT_FAIL;
    }
    if (!strComment.Exists()) {
        otErr << __FUNCTION__ << ": Error: "
              << "strComment"
              << " is Empty!\n";
        OT_FAIL;
    }

    const char* const szComment =
        (strComment.Exists() && !strComment.Compare("")) ? strComment.Get()
                                                         : nullptr;

    const int64_t lSectionSize =
        pvt->iniSimple.GetSectionSize(strSection.Get());

    if (1 > lSectionSize) {
        out_bIsNewSection = true;
        SI_Error rc = pvt->iniSimple.SetValue(strSection.Get(), nullptr,
                                              nullptr, szComment, false);
        if (0 > rc) return false;
    }
    else {
        out_bIsNewSection = false;
    }
    return true;
}
Exemple #3
0
// static
bool OTPaths::AppendFile(String& out_strPath, const String& strBasePath,
                         const String& strFileName)
{
    if (!strBasePath.Exists()) {
        otErr << __FUNCTION__ << ": Null: "
              << "strBasePath"
              << " passed in!\n";
        OT_FAIL;
    }
    if (!strFileName.Exists()) {
        otErr << __FUNCTION__ << ": Null: "
              << "strFileName"
              << " passed in!\n";
        OT_FAIL;
    }

    String l_strBasePath_fix(""), l_strFileName_fix("");

    if (!FixPath(strBasePath, l_strBasePath_fix, true)) return false;
    if (!FixPath(strFileName, l_strFileName_fix, false)) return false;

    std::string l_strBasePath(l_strBasePath_fix.Get()),
        l_strFileName(l_strFileName_fix.Get());

    l_strBasePath.append(l_strFileName);

    const String l_strPath(l_strBasePath);

    out_strPath = l_strPath;
    return true;
}
Exemple #4
0
bool OTASCIIArmor::WriteArmoredFile(
    const String& foldername, const String& filename,
    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) const
{
    OT_ASSERT(foldername.Exists());
    OT_ASSERT(filename.Exists());

    String strOutput;

    if (WriteArmoredString(strOutput, str_type, bEscaped) &&
        strOutput.Exists()) {
        // WRITE IT TO THE FILE
        // StorePlainString will attempt to create all the folders leading up to
        // the path
        // for the output file.
        //
        bool bSaved = OTDB::StorePlainString(strOutput.Get(), foldername.Get(),
                                             filename.Get());

        if (!bSaved) {
            otErr << "OTASCIIArmor::WriteArmoredFile"
                  << ": Failed saving to file: %s%s%s\n\n Contents:\n\n"
                  << strOutput << "\n\n",
                foldername.Get(), Log::PathSeparator(), filename.Get();
            return false;
        }

        return true;
    }

    return false;
}
Exemple #5
0
// static
bool OTPaths::Set(OTSettings& config, const String& strSection,
                  const String& strKey, const String& strValue,
                  const bool& bIsRelative, bool& out_bIsNewOrUpdated,
                  const String& strComment)
{
    if (!strSection.Exists()) {
        otErr << __FUNCTION__ << ": Null: "
              << "strSection"
              << " passed in!\n";
        OT_FAIL;
    }
    if (!strKey.Exists()) {
        otErr << __FUNCTION__ << ": Null: "
              << "strKey"
              << " passed in!\n";
        OT_FAIL;
    }

    out_bIsNewOrUpdated = false;

    const bool bPreLoaded(config.IsLoaded());

    if (!bPreLoaded) // we only need to load, if not already loaded.
    {
        config.Reset();
        if (!config.Load()) {
            OT_FAIL;
        }
    }

    bool bBoolIsNew(false);
    String strRelativeKey("");

    strRelativeKey.Format("%s%s", strKey.Get(), OT_CONFIG_ISRELATIVE);

    if (config.Set_bool(strSection, strRelativeKey, bIsRelative, bBoolIsNew,
                        strComment)) {
        bool bStringIsNew = false;
        if (config.Set_str(strSection, strKey, strValue, bStringIsNew)) {
            if (bBoolIsNew && bStringIsNew) // using existing key
            {
                out_bIsNewOrUpdated = true;
            }

            if (!bPreLoaded) {
                if (!config.Save()) {
                    OT_FAIL;
                }
                config.Reset();
            }

            return true;
        }
    }

    // if we get here, there has been a error!
    OT_FAIL;
}
bool Settings::CheckSet_str(const String& strSection, const String& strKey,
                              const String& strDefault, std::string& out_strResult,
                              bool& out_bIsNew, const String& strComment)
{
    if (!strSection.Exists()) {
        otErr << __FUNCTION__ << ": Error: "
              << "strSection"
              << " is Empty!\n";
        OT_FAIL;
    }
    if (!strKey.Exists()) {
        otErr << __FUNCTION__ << ": Error: "
              << "strKey"
              << " is Empty!\n";
        OT_FAIL;
    }

    const char* const szDefault =
        (strDefault.Exists() && !strDefault.Compare("")) ? strDefault.Get()
                                                         : nullptr;

    String strTempResult;
    bool bKeyExist;
    if (!Check_str(strSection, strKey, strTempResult, bKeyExist)) return false;

    if (bKeyExist) {
        // Already have a key, lets use it's value.
        out_bIsNew = false;
        out_strResult = strTempResult.Get();
        return true;
    }
    else {
        bool bNewKeyCheck;
        if (!Set_str(strSection, strKey, strDefault, bNewKeyCheck, strComment))
            return false;

        if (nullptr == szDefault) // The Default is to have no key.
        {
            // Success
            out_bIsNew = false;
            out_strResult = "";
            return true;
        }

        if (bNewKeyCheck) {
            // Success
            out_bIsNew = true;
            out_strResult = strDefault.Get();
            return true;
        }
    }

    // If we get here, error!
    OT_FAIL;
}
bool Settings::Check_bool(const String& strSection, const String& strKey,
                            bool& out_bResult, bool& out_bKeyExist) const
{
    if (!strSection.Exists()) {
        otErr << __FUNCTION__ << ": Error: "
              << "strSection"
              << " is Empty!\n";
        OT_FAIL;
    }
    if (strSection.Compare("")) {
        otErr << __FUNCTION__ << ": Error: "
              << "strSection"
              << " is Blank!\n";
        OT_FAIL;
    }

    if (!strKey.Exists()) {
        otErr << __FUNCTION__ << ": Error: "
              << "strKey"
              << " is Empty!\n";
        OT_FAIL;
    }
    if (strKey.Compare("")) {
        otErr << __FUNCTION__ << ": Error: "
              << "strKey"
              << " is Blank!\n";
        OT_FAIL;
    }

    const char* szVar =
        pvt->iniSimple.GetValue(strSection.Get(), strKey.Get(), nullptr);
    String strVar(szVar);

    if (strVar.Exists() &&
        (strVar.Compare("false") || strVar.Compare("true"))) {
        out_bKeyExist = true;
        if (strVar.Compare("true"))
            out_bResult = true;
        else
            out_bResult = false;
    }
    else {
        out_bKeyExist = false;
        out_bResult = false;
    }

    return true;
}
Exemple #8
0
// static
bool OTPaths::GetHomeFromSystem(String& out_strHomeFolder)
{
#ifdef _WIN32
#ifdef _UNICODE
    TCHAR szPath[MAX_PATH] = L"";
#else
    TCHAR szPath[MAX_PATH] = "";
#endif

    if (SUCCEEDED(SHGetFolderPath(nullptr, CSIDL_APPDATA | CSIDL_FLAG_CREATE,
                                  nullptr, 0, szPath))) {
#ifdef UNICODE
        out_strHomeFolder.Set(utf8util::UTF8FromUTF16(szPath));
#else
        out_strHomeFolder.Set(szPath);
#endif
    }
    else {
        out_strHomeFolder.Set("");
        return false;
    }

#elif defined(__APPLE__)

    String home(getenv("HOME"));
    String library = "";
    AppendFolder(library, home, "Library");
    AppendFolder(out_strHomeFolder, library, "Application Support");

#else
    out_strHomeFolder.Set(getenv("HOME"));
#endif

    return out_strHomeFolder.Exists();
}
bool LegacySymmetric::Decrypt(
    const api::Crypto& crypto,
    const String& strKey,
    String& strCiphertext,
    String& strOutput,
    const String& pstrDisplay,
    const OTPassword* pAlreadyHavePW)
{

    if (!strKey.Exists()) {
        LogDetail(OT_METHOD)(__FUNCTION__)(
            ": Nonexistent: The symmetric key. Please supply. (Failure).")
            .Flush();
        return false;
    }

    implementation::LegacySymmetric theKey(crypto);

    if (!theKey.SerializeFrom(strKey)) {
        LogDetail(OT_METHOD)(__FUNCTION__)(
            ": Failed trying to load symmetric key from "
            "string. (Returning false).")
            .Flush();
        return false;
    }

    // By this point, we know we have a ciphertext envelope and a symmetric Key.
    //
    return Decrypt(
        theKey, strCiphertext, strOutput, pstrDisplay, pAlreadyHavePW);
}
Exemple #10
0
bool String::Contains(const String& strCompare) const
{
    if (nullptr == data_ || !strCompare.Exists()) {
        return false;
    }

    if (strstr(data_, strCompare.Get())) return true;

    return false;
}
Exemple #11
0
// append a string at the end of the current buffer.
void String::Concatenate(const String& strBuf)
{
    std::string str_output;

    if ((length_ > 0) && (nullptr != data_)) str_output += data_;

    if (strBuf.Exists() && (strBuf.GetLength() > 0)) str_output += strBuf.Get();

    Set(str_output.c_str());
}
bool Settings::CheckSet_long(const String& strSection, const String& strKey,
                               const int64_t& lDefault, int64_t& out_lResult,
                               bool& out_bIsNew, const String& strComment)
{
    if (!strSection.Exists()) {
        otErr << __FUNCTION__ << ": Error: "
              << "strSection"
              << " is Empty!\n";
        OT_FAIL;
    }
    if (!strKey.Exists()) {
        otErr << __FUNCTION__ << ": Error: "
              << "strKey"
              << " is Empty!\n";
        OT_FAIL;
    }

    int64_t lTempResult;
    bool bKeyExist;
    if (!Check_long(strSection, strKey, lTempResult, bKeyExist)) return false;

    if (bKeyExist) {
        // Already have a key, lets use it's value.
        out_bIsNew = false;
        out_lResult = lTempResult;
        return true;
    }
    else {
        bool bNewKeyCheck;
        if (!Set_long(strSection, strKey, lDefault, bNewKeyCheck, strComment))
            return false;
        if (bNewKeyCheck) {
            // Success
            out_bIsNew = true;
            out_lResult = lDefault;
            return true;
        }
    }

    // If we get here, error!
    OT_FAIL;
}
bool Settings::Set_bool(const String& strSection, const String& strKey,
                          const bool& bValue, bool& out_bNewOrUpdate,
                          const String& strComment)
{
    if (!strSection.Exists()) {
        otErr << __FUNCTION__ << ": Error: "
              << "strSection"
              << " is Empty!\n";
        OT_FAIL;
    }
    if (!strKey.Exists()) {
        otErr << __FUNCTION__ << ": Error: "
              << "strKey"
              << " is Empty!\n";
        OT_FAIL;
    }
    const String strValue(bValue ? "true" : "false");

    return Set_str(strSection, strKey, strValue, out_bNewOrUpdate, strComment);
}
Exemple #14
0
// static
bool OTKeyring::FlatFile_DeleteSecret(const String& strUser,
                                      const std::string& str_display)
{
    OT_ASSERT(strUser.Exists());

    const std::string str_pw_folder(OTKeyring::FlatFile_GetPasswordFolder());
    if (!str_pw_folder.empty()) {
        String strExactPath;
        strExactPath.Format("%s%s%s", str_pw_folder.c_str(),
                            Log::PathSeparator(), strUser.Get());
        const std::string str_ExactPath(strExactPath.Get());

        std::ofstream ofs(str_ExactPath.c_str(),
                          std::ios::out | std::ios::binary);

        if (ofs.fail()) {
            otErr << __FUNCTION__ << ": Error opening file (to delete it): "
                  << str_ExactPath.c_str() << '\n';
            return false;
        }
        ofs.clear();
        ofs << "(This space intentionally left blank.)\n";

        bool bSuccess = ofs.good() ? true : false;
        ofs.close();
        // Note: I bet you think I should be overwriting the file 7 times here
        // with
        // random data, right? Wrong: YOU need to override OTKeyring and create
        // your
        // own subclass, where you can override DeleteSecret and do that stuff
        // yourself. It's outside of the scope of OT.

        //
        if (remove(str_ExactPath.c_str()) != 0) {
            bSuccess = false;
            otErr << "** (OTKeyring::FlatFile_DeleteSecret) Failed trying to "
                  << "delete file (containing secret):  "
                  << str_ExactPath.c_str() << '\n';
        }
        else {
            bSuccess = true;
            otInfo << "** (OTKeyring::FlatFile_DeleteSecret) Success "
                   << "deleting file: " << str_ExactPath.c_str() << '\n';
        }

        return bSuccess;
    }

    otErr << "OTKeyring::FlatFile_DeleteSecret: Unable to delete any derived "
             "key, since password_folder not provided in config file.\n";

    return false;
}
Exemple #15
0
// this function dosn't change the "strRelativePath" so.  It will only fix the
// strBasePath.
// static
bool OTPaths::RelativeToCanonical(String& out_strCanonicalPath,
                                  const String& strBasePath,
                                  const String& strRelativePath)
{
    if (!strBasePath.Exists()) {
        otErr << __FUNCTION__ << ": Null: "
              << "strBasePath"
              << " passed in!\n";
        OT_FAIL;
    }
    if (!strRelativePath.Exists()) {
        otErr << __FUNCTION__ << ": Null: "
              << "strRelativePath"
              << " passed in!\n";
        OT_FAIL;
    }

    String l_strBasePath_fix("");
    if (!FixPath(strBasePath, l_strBasePath_fix, true)) return false;

    if (strRelativePath.Compare(".")) {
        out_strCanonicalPath = strBasePath;
        return true;
    } // if ".", return base path.

    std::string l_strBasePath(l_strBasePath_fix.Get()),
        l_strRelativePath(strRelativePath.Get());

    l_strBasePath.append(l_strRelativePath);

    String l_strPath(l_strBasePath), l_strCanonicalPath("");

    if (!ToReal(l_strPath, l_strCanonicalPath)) return false;

    out_strCanonicalPath = l_strCanonicalPath;

    return true;
}
Exemple #16
0
bool String::Compare(const String& strCompare) const
{
    if (nullptr == data_ || !strCompare.Exists()) {
        return false;
    }

    char* s1 = data_;
    const char* s2 = strCompare.Get();

    for (; *s1 && *s1 != ' '; s1++, s2++)
        if (*s1 != *s2) return false;

    return true;
}
Exemple #17
0
// This code reads up the file, discards the bookends, and saves only the
// gibberish itself.
bool OTASCIIArmor::LoadFromFile(const String& foldername,
                                const String& filename)
{
    OT_ASSERT(foldername.Exists());
    OT_ASSERT(filename.Exists());

    if (!OTDB::Exists(foldername.Get(), filename.Get())) {
        otErr << "OTASCIIArmor::LoadFromFile: File does not exist: "
              << foldername << "" << Log::PathSeparator() << "" << filename
              << "\n";
        return false;
    }

    String strFileContents(OTDB::QueryPlainString(
        foldername.Get(), filename.Get())); // <=== LOADING FROM DATA STORE.

    if (strFileContents.GetLength() < 2) {
        otErr << "OTASCIIArmor::LoadFromFile: Error reading file: "
              << foldername << Log::PathSeparator() << filename << "\n";
        return false;
    }

    return LoadFromString(strFileContents);
}
bool Settings::Save(const String& strConfigurationFileExactPath)
{
    if (!strConfigurationFileExactPath.Exists()) {
        otErr << __FUNCTION__ << ": Error: "
              << "strConfigurationFileExactPath"
              << " is Empty!\n";
        return false;
    }

    SI_Error rc = pvt->iniSimple.SaveFile(strConfigurationFileExactPath.Get());
    if (0 > rc)
        return false;
    else
        return true;
}
Exemple #19
0
void String::LowLevelSetStr(const String& strBuf)
{
    OT_ASSERT(nullptr == data_); // otherwise memory leak.

    if (strBuf.Exists()) {
        length_ = (MAX_STRING_LENGTH > strBuf.length_)
                      ? strBuf.length_
                      : (MAX_STRING_LENGTH - 1);

        OT_ASSERT_MSG(length_ < (MAX_STRING_LENGTH - 10),
                      "ASSERT: OTString::LowLevelSetStr: Exceeded "
                      "MAX_STRING_LENGTH! (String would not have fully fit "
                      "anyway--it would have been truncated here, potentially "
                      "causing data corruption.)"); // 10 being a buffer.

        data_ = str_dup2(strBuf.data_, length_);
    }
}
Exemple #20
0
// static
bool OTKeyring::FlatFile_RetrieveSecret(const String& strUser,
                                        OTPassword& thePassword,
                                        const std::string& str_display)
{
    OT_ASSERT(strUser.Exists());
    const std::string str_pw_folder(OTKeyring::FlatFile_GetPasswordFolder());
    if (!str_pw_folder.empty()) {
        String strExactPath;
        strExactPath.Format("%s%s%s", str_pw_folder.c_str(),
                            Log::PathSeparator(), strUser.Get());
        const std::string str_ExactPath(strExactPath.Get());

        // Get the password
        //
        OTASCIIArmor ascData;

        if (!ascData.LoadFromExactPath(str_ExactPath))
            otErr << "OTKeyring::FlatFile_RetrieveSecret: "
                  << "Failed trying to decode secret from flat file contents."
                  << "\n";
        else {
            OTData thePayload(ascData);
            ascData.zeroMemory();
            if (thePayload.IsEmpty())
                otErr << __FUNCTION__ << ": Failed trying to decode secret "
                                         "OTData from OTASCIIArmor from "
                                         "flat file contents.\n";
            else {
                thePassword.setMemory(thePayload.GetPointer(),
                                      thePayload.GetSize());
                thePayload.zeroMemory(); // for security.
                return true;
            }
        }
    }

    // Not an error: what if it just hasn't been set there yet?
    //
    otWarn << __FUNCTION__ << ": Unable to retrieve any derived key, since "
                              "password_folder not provided in config file.\n";

    return false;
}
bool Settings::Load(const String& strConfigurationFileExactPath)
{
    if (!strConfigurationFileExactPath.Exists()) {
        otErr << __FUNCTION__ << ": Error: "
              << "strConfigurationFileExactPath"
              << " is Empty!\n";
        return false;
    }

    bool bFolderCreated(false);
    if (!OTPaths::BuildFilePath(strConfigurationFileExactPath,
                                bFolderCreated)) {
        OT_FAIL;
    };

    if (!IsEmpty()) {
        otErr << __FUNCTION__ << ": Bad: "
              << "p_Settings"
              << " is not Empty!\n";
        OT_FAIL;
    }

    int64_t lFilelength;
    if (!OTPaths::FileExists(strConfigurationFileExactPath,
                             lFilelength)) // we don't have a config file, lets
                                           // create a blank one first.
    {
        pvt->iniSimple.Reset(); // clean the config.

        SI_Error rc = pvt->iniSimple.SaveFile(
            strConfigurationFileExactPath.Get()); // save a new file.
        if (0 > rc) return false;                 // error!

        pvt->iniSimple.Reset(); // clean the config (again).
    }

    SI_Error rc = pvt->iniSimple.LoadFile(strConfigurationFileExactPath.Get());
    if (0 > rc)
        return false;
    else
        return true;
}
bool LegacySymmetric::CreateNewKey(
    const api::Crypto& crypto,
    String& strOutput,
    const String& pstrDisplay,
    const OTPassword* pAlreadyHavePW)
{
    std::unique_ptr<OTPassword> pPassUserInput;

    if (nullptr == pAlreadyHavePW) {
        const char* szDisplay = "Creating new symmetric key.";
        const auto strDisplay = String::Factory(
            (!pstrDisplay.Exists()) ? szDisplay : pstrDisplay.Get());

        pPassUserInput.reset(GetPassphraseFromUser(
            strDisplay, true));  // bAskTwice=false by default.
    } else
        pPassUserInput.reset(new OTPassword(*pAlreadyHavePW));

    bool bSuccess = false;

    if (pPassUserInput)  // Success retrieving the passphrase from the
                         // user. (Now let's generate the key...)
    {
        LogDebug(OT_METHOD)(__FUNCTION__)(
            ": Calling LegacySymmetric theKey.GenerateKey()...")
            .Flush();
        implementation::LegacySymmetric theKey(crypto, *pPassUserInput);
        const bool bGenerated = theKey.IsGenerated();

        if (bGenerated && theKey.SerializeTo(strOutput))
            bSuccess = true;
        else
            LogDetail(OT_METHOD)(__FUNCTION__)(
                ": Sorry, unable to generate key. (Failure).")
                .Flush();
    } else
        LogDetail(OT_METHOD)(__FUNCTION__)(
            ": Sorry, unable to retrieve password from user. (Failure).")
            .Flush();

    return bSuccess;
}
Exemple #23
0
// static
bool OTPaths::FixPath(const String& strPath, String& out_strFixedPath,
                      const bool& bIsFolder)
{
    if (!strPath.Exists()) {
        otErr << __FUNCTION__ << ": Null: "
              << "strPath"
              << " passed in!\n";
        OT_FAIL;
    }

    std::string l_strPath(strPath.Get());
    // first change all back-slashes to forward slashes:
    std::string l_strPath_noBackslash(
        String::replace_chars(l_strPath, "\\", '/'));

    // now we make sure we have the correct trailing "/".

    if ('/' == *l_strPath_noBackslash.rbegin()) {
        if (bIsFolder) {
            out_strFixedPath.Set(l_strPath_noBackslash.c_str());
            return true;
        }
        else {
            out_strFixedPath.Set(
                l_strPath_noBackslash.substr(0, l_strPath_noBackslash.size() -
                                                    1).c_str());
            return true;
        }
    }
    else {
        if (bIsFolder) {
            l_strPath_noBackslash += "/";
            out_strFixedPath.Set(l_strPath_noBackslash.c_str());
            return true;
        }
        else {
            out_strFixedPath.Set(l_strPath_noBackslash.c_str());
            return true;
        }
    }
}
Exemple #24
0
bool OTASCIIArmor::SaveTo_ofstream(std::ofstream& fout)
{
    String strOutput;
    std::string str_type("DATA"); // -----BEGIN OT ARMORED DATA-----

    if (WriteArmoredString(strOutput, str_type) && strOutput.Exists()) {
        // WRITE IT TO THE FILE
        //
        fout << strOutput;

        if (fout.fail()) {
            otErr << __FUNCTION__ << ": Failed saving to file.\n Contents:\n\n"
                  << strOutput << "\n\n";
            return false;
        }

        return true;
    }

    return false;
}
Exemple #25
0
// static
bool OTPaths::FileExists(const String& strFilePath, int64_t& nFileLength)
{
    if (!strFilePath.Exists()) {
        otErr << __FUNCTION__ << ": Null: "
              << "strFilePath"
              << " passed in!\n";
        OT_FAIL;
    }

    // remove trailing backslash for stat
    std::string l_strPath(strFilePath.Get());
    l_strPath = (String::replace_chars(l_strPath, "\\", '/')); // all \ to /

    if ('/' != *l_strPath.rbegin()) {
#ifdef _WIN32
        std::string l_strPath_stat = l_strPath;
        struct _stat st_buf;
        memset(&st_buf, 0, sizeof(st_buf));
        char filename[4086]; // not sure about this buffer,
        // on windows paths cannot be longer than 4086,
        // so it should be fine... needs more research.
        strcpy_s(filename, l_strPath_stat.c_str());
        _stat(filename, &st_buf);
#else
        struct stat st_buf;
        memset(&st_buf, 0, sizeof(st_buf));
        stat(l_strPath.c_str(), &st_buf);
#endif

        // check for file
        if (S_ISREG(st_buf.st_mode)) {
            // good we have a file.
            size_t lFileLength = st_buf.st_size;
            nFileLength = static_cast<int64_t>(lFileLength);
            return true;
        }
    }
    return false;
}
Exemple #26
0
// static
bool OTPaths::PathExists(const String& strPath)
{
    if (!strPath.Exists()) {
        otErr << __FUNCTION__ << ": Null: "
              << "strPath"
              << " passed in!\n";
        OT_FAIL;
    }

    // remove trailing backslash for stat
    std::string l_strPath(strPath.Get());
    l_strPath = (String::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()) {
            int64_t temp_l = 0;
            return FileExists(strPath, temp_l);
        }
        else {
            return FolderExists(strPath);
        }
    }
    return false;
}
Exemple #27
0
// static
bool OTPaths::FolderExists(const String& strFolderPath)
{
    if (!strFolderPath.Exists()) {
        otErr << __FUNCTION__ << ": Null: "
              << "strFolderPath"
              << " passed in!\n";
        OT_FAIL;
    }

    // remove trailing backslash for stat
    std::string l_strPath(strFolderPath.Get());
    l_strPath = (String::replace_chars(l_strPath, "\\", '/')); // all \ to /

    if ('/' == *l_strPath.rbegin()) {
#ifdef _WIN32
        std::string l_strPath_stat = l_strPath.substr(0, l_strPath.size() - 1);
        struct _stat st_buf;
        memset(&st_buf, 0, sizeof(st_buf));
        char filename[4086] = ""; // not sure about this buffer,
        // on windows paths cannot be longer than 4086,
        // so it should be fine... needs more research.
        strcpy_s(filename, l_strPath_stat.c_str());
        _stat(filename, &st_buf);
#else
        struct stat st_buf;
        memset(&st_buf, 0, sizeof(st_buf));
        stat(l_strPath.c_str(), &st_buf);
#endif

        if (S_ISDIR(st_buf.st_mode)) {
            // good we have a directory.
            return true;
        }
    }
    return false;
}
Exemple #28
0
// static
bool OTKeyring::FlatFile_StoreSecret(const String& strUser,
                                     const OTPassword& thePassword,
                                     const std::string& str_display)
{
    OT_ASSERT(strUser.Exists());
    OT_ASSERT(thePassword.getMemorySize() > 0);

    const std::string str_pw_folder(OTKeyring::FlatFile_GetPasswordFolder());
    if (!str_pw_folder.empty()) {
        String strExactPath;
        strExactPath.Format("%s%s%s", str_pw_folder.c_str(),
                            Log::PathSeparator(), strUser.Get());
        const std::string str_ExactPath(strExactPath.Get());

        OTData theData(thePassword.getMemory(), thePassword.getMemorySize());
        OTASCIIArmor ascData(theData);
        theData.zeroMemory(); // security reasons.

        // Save the password
        //
        const bool bSaved =
            ascData.Exists() && ascData.SaveToExactPath(str_ExactPath);
        ascData.zeroMemory();

        if (!bSaved)
            otErr << "OTKeyring::FlatFile_StoreSecret: Failed trying to store "
                     "secret.\n";

        return bSaved;
    }

    otErr << "OTKeyring::FlatFile_StoreSecret: Unable to cache derived key, "
             "since password_folder not provided in config file.\n";

    return false;
}
bool Settings::Set_long(const String& strSection, const String& strKey,
                          const int64_t& lValue, bool& out_bNewOrUpdate,
                          const String& strComment)
{
    if (!strSection.Exists()) {
        otErr << __FUNCTION__ << ": Error: "
              << "strSection"
              << " is Empty!\n";
        OT_FAIL;
    }
    if (strSection.Compare("")) {
        otErr << __FUNCTION__ << ": Error: "
              << "strSection"
              << " is Blank!\n";
        OT_FAIL;
    }

    if (!strKey.Exists()) {
        otErr << __FUNCTION__ << ": Error: "
              << "strKey"
              << " is Empty!\n";
        OT_FAIL;
    }
    if (strKey.Compare("")) {
        otErr << __FUNCTION__ << ": Error: "
              << "strKey"
              << " is Blank!\n";
        OT_FAIL;
    }

    String strValue;
    strValue.Format("%" PRId64, lValue);

    const char* const szComment =
        (strComment.Exists() && !strComment.Compare("")) ? strComment.Get()
                                                         : nullptr;

    String 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 = pvt->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_FAIL;
}
bool Settings::Set_str(const String& strSection, const String& strKey,
                         const String& strValue, bool& out_bNewOrUpdate,
                         const String& strComment)
{
    if (!strSection.Exists()) {
        otErr << __FUNCTION__ << ": Error: "
              << "strSection"
              << " is Empty!\n";
        OT_FAIL;
    }
    if (strSection.Compare("")) {
        otErr << __FUNCTION__ << ": Error: "
              << "strSection"
              << " is Blank!\n";
        OT_FAIL;
    }

    if (!strKey.Exists()) {
        otErr << __FUNCTION__ << ": Error: "
              << "strKey"
              << " is Empty!\n";
        OT_FAIL;
    }
    if (strKey.Compare("")) {
        otErr << __FUNCTION__ << ": Error: "
              << "strKey"
              << " is Blank!\n";
        OT_FAIL;
    }

    // if (nullptr == m_strConfigurationFileExactPath){ otErr << "%s: Error:
    // %s is a nullptr!\n", __FUNCTION__, "p_iniSimple"); OT_FAIL; }

    const char* const szValue =
        (strValue.Exists() && !strValue.Compare("")) ? strValue.Get() : nullptr;
    const char* const szComment =
        (strComment.Exists() && !strComment.Compare("")) ? strComment.Get()
                                                         : nullptr;

    String 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 = pvt->iniSimple.SetValue(strSection.Get(), strKey.Get(),
                                          szValue, szComment, true);
    if (0 > rc) return false;

    if (nullptr == szValue) // We set the key's value to null, thus removing it.
    {
        if (bOldKeyExist)
            out_bNewOrUpdate = true;
        else
            out_bNewOrUpdate = false;

        return true;
    }

    // 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_FAIL;
}