Example #1
0
bool CryptoHash::Digest(
    const HashType hashType,
    const String& data,
    OTData& digest)
{
    OTData plaintext(data.Get(), data.GetLength());

    return Digest(hashType, plaintext, digest);
}
Example #2
0
bool CryptoHash::HMAC(
        const CryptoHash::HashType hashType,
        const OTPassword& inputKey,
        const String& inputData,
        OTPassword& outputDigest) const
{
    OTData convertedData(inputData.Get(), inputData.GetLength());

    return HMAC(hashType, inputKey, convertedData, outputDigest);
}
Example #3
0
void CSquirrel::RegisterConstant(String strConstantName, CSquirrelArgument value)
{
	// Push the constant name onto the stack
	sq_pushstring(m_pVM, strConstantName.Get(), -1);

	// Push the constant value onto the stack
	value.push(m_pVM);

	// Create a new slot
	sq_createslot(m_pVM, -3);
}
Example #4
0
void CSquirrel::RegisterFunction(String strFunctionName, SQFUNCTION pfnFunction, int iParameterCount, String strFunctionTemplate)
{
	// Push the function name onto the stack
	sq_pushstring(m_pVM, strFunctionName.Get(), -1);

	// Create a new function
	sq_newclosure(m_pVM, pfnFunction, 0);

	// Set the function parameter template and count
	if(iParameterCount != -1)
	{
		String strTypeMask;

		if(strFunctionTemplate.IsNotEmpty())
			strTypeMask.Format(".%s", strFunctionTemplate.Get());

		sq_setparamscheck(m_pVM, (iParameterCount + 1), strTypeMask.Get());
	}

	// Create a new slot
	sq_createslot(m_pVM, -3);
}
Example #5
0
bool CSquirrel::Load(String strName, String strPath)
{
	// Check if the script exists
	if(!SharedUtility::Exists(strPath.Get()))
		return false;

	// Set the script name
	m_strName = strName;

	// Set the script path
	m_strPath = strPath;

	// Create a squirrel VM with an initial stack size of 1024 bytes (stack will resize as needed)
	m_pVM = sq_open(1024);

	// Register the default error handlers
	sqstd_seterrorhandlers(m_pVM);

	// Set the print function and error function
	sq_setprintfunc(m_pVM, PrintFunction, PrintFunction);

	// Set the compiler error function
	sq_setcompilererrorhandler(m_pVM, CompilerErrorFunction);

	// Set our error handler
	sq_newclosure(m_pVM, PrintErrorFunction, 0);
	sq_seterrorhandler(m_pVM);

	// Push the root table onto the stack
	sq_pushroottable(m_pVM);

#ifdef _SERVER
	// Register the input/output library
	sqstd_register_iolib(m_pVM);
#endif

	// Register the blob library
	sqstd_register_bloblib(m_pVM);

	// Register the math library
	sqstd_register_mathlib(m_pVM);

	// Register the string library
	sqstd_register_stringlib(m_pVM);
	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;
}
bool CClientFileManager::Start(String strName)
{
	if(Exists(strName))
		return false;

	CFileChecksum fileChecksum;
	
	if(!g_pWebserver->FileCopy(strName, bIsScriptManager, fileChecksum))
	{
		CLogFile::Printf("Failed to copy client file %s to web server.\n", strName.Get());
		return false;
	}

	insert(std::pair<String, CFileChecksum>(strName, fileChecksum));
	CBitStream bsSend;
	bsSend.Write(bIsScriptManager);
	bsSend.Write(strName);
	bsSend.Write((char *)&fileChecksum, sizeof(CFileChecksum));
	g_pNetworkManager->RPC(RPC_NewFile, &bsSend, PRIORITY_HIGH, RELIABILITY_RELIABLE_ORDERED, INVALID_ENTITY_ID, true);
	return true;
}
Example #8
0
static void EscapeString(const String &s, std::string *_text) {
  std::string &text = *_text;
  text += "\"";
  for (uoffset_t i = 0; i < s.Length(); i++) {
    char c = s.Get(i);
    switch (c) {
      case '\n': text += "\\n"; break;
      case '\t': text += "\\t"; break;
      case '\r': text += "\\r"; break;
      case '\"': text += "\\\""; break;
      case '\\': text += "\\\\"; break;
      default:
        if (c >= ' ' && c <= '~') {
          text += c;
        } else {
          auto u = static_cast<unsigned char>(c);
          text += "\\x" + IntToStringHex(u);
        }
        break;
    }
  }
  text += "\"";
}
Example #9
0
SQInteger CSquirrel::PrintErrorFunction(SQVM * pVM)
{
	if(sq_gettop(pVM) >= 1)
	{
		const SQChar * szError = NULL;
		sq_getstring(pVM, 2, &szError);
				
		ErrorInfo info;
		info.strError = szError;

		SQStackInfos si;
		SQInteger level = 1; // 1 is to skip this function that is level 0
		const SQChar *name = 0; 
		SQInteger seq = 0;

		while(SQ_SUCCEEDED(sq_stackinfos(pVM, level, &si)))
		{
			const SQChar * fn = _SC("unknown");
			const SQChar * src = _SC("unknown");
			if(si.funcname) fn = si.funcname;
			if(si.source) src = si.source;
			info.callstack.push_back(ErrorCallstackPair(fn, ErrorSourcePair(src, si.line)));
			level++;
		}

		for(level = 0; level < 10; level++)
		{
			seq = 0;

			while((name = sq_getlocal(pVM, level, seq)))
			{
				seq++;
				CSquirrelArgument arg;
				arg.pushFromStack(pVM, -1);
				info.locals.push_back(ErrorLocalPair(name, arg));
				sq_pop(pVM, 1);
			}
		}

		CSquirrel * pScript = CScriptingManager::GetInstance()->Get(pVM);

		if(pScript)
		{
			CSquirrelArguments arguments;
			CSquirrelArguments tempArray;
			CSquirrelArguments callstackTable;
			CSquirrelArguments localsTable;
			arguments.push(info.strError);

			for(ErrorCallstackList::iterator iter = info.callstack.begin(); iter != info.callstack.end(); iter++)
			{
				String strFunction = iter->first;
				String strSource = iter->second.first;
				int iLine = iter->second.second;
				callstackTable.push(strFunction);
				tempArray.reset();
				tempArray.push(strSource);
				tempArray.push(iLine);
				callstackTable.push(tempArray, true);
			}

			arguments.push(callstackTable, false);

			for(ErrorLocalsList::iterator iter = info.locals.begin(); iter != info.locals.end(); iter++)
			{
				String strName = iter->first;
				CSquirrelArgument arg = iter->second;
				localsTable.push(strName);
				localsTable.push(arg);
			}

			arguments.push(localsTable, false);

			if(CEvents::GetInstance()->Call("scriptError", &arguments, pScript).GetInteger() == 1)
			{
				CLogFile::Printf("<Error (%s)>", info.strError.Get());

				CLogFile::Printf("<Callstack>");
				for(ErrorCallstackList::iterator iter = info.callstack.begin(); iter != info.callstack.end(); iter++)
				{
					String strFunction = iter->first;
					String strSource = iter->second.first;
					int iLine = iter->second.second;
					CLogFile::Printf("<%s (%s, %d)>", strFunction.Get(), strSource.Get(), iLine);
				}
				CLogFile::Printf("</Callstack>");

				CLogFile::Printf("<Locals>");
				for(ErrorLocalsList::iterator iter = info.locals.begin(); iter != info.locals.end(); iter++)
				{
					String strName = iter->first;
					CSquirrelArgument arg = iter->second;
					CLogFile::Printf("<%s (%s)>", strName.Get(), arg.GetTypeString().Get());
				}
				CLogFile::Printf("</Locals>");

				CLogFile::Printf("</Error>");
			}
		}
	}

	return 0;
}
Example #10
0
void CBlipManager::SetName(EntityId blipId, String strName)
{
	if(m_bActive[blipId])
		Scripting::ChangeBlipNameFromAscii(m_Blips[blipId].uiBlipIndex, strName.Get());
}
// static
bool LegacySymmetric::Encrypt(
    const LegacySymmetric& theKey,
    const String& strPlaintext,
    String& strOutput,
    const String& pstrDisplay,
    bool bBookends,
    const OTPassword* pAlreadyHavePW)
{
    if (!theKey.IsGenerated()) {
        LogDetail(OT_METHOD)(__FUNCTION__)(
            ": Failure: theKey.IsGenerated() was false. (The calling "
            "code probably should have checked that key already...).")
            .Flush();
        return false;
    }

    if (!strPlaintext.Exists()) {
        LogDetail(OT_METHOD)(__FUNCTION__)(
            ": Plaintext is empty. Please supply. (Failure).")
            .Flush();
        return false;
    }

    // By this point, we know we have a plaintext and a symmetric Key.
    //
    std::unique_ptr<OTPassword> pPassUserInput;

    if (nullptr == pAlreadyHavePW) {
        const char* szDisplay = "Password-protecting a plaintext.";
        const auto strDisplay = String::Factory(
            (!pstrDisplay.Exists()) ? szDisplay : pstrDisplay.Get());

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

    auto ascOutput = Armored::Factory();
    bool bSuccess = false;

    if (nullptr != pPassUserInput)  // Success retrieving the passphrase from
                                    // the user. (Now let's encrypt...)
    {
        OTEnvelope theEnvelope;

        if (theEnvelope.Encrypt(
                strPlaintext,
                const_cast<LegacySymmetric&>(theKey),
                *pPassUserInput) &&
            theEnvelope.GetCiphertext(ascOutput)) {
            bSuccess = true;

            if (bBookends) {
                return ascOutput->WriteArmoredString(
                    strOutput,
                    "SYMMETRIC MSG",  // todo hardcoding.
                    false);           // bEscaped=false
            } else {
                strOutput.Set(ascOutput->Get());
            }
        } else {
            LogDetail(OT_METHOD)(__FUNCTION__)(
                ": Failed trying to encrypt. (Sorry).")
                .Flush();
        }
    } else
        LogDetail(OT_METHOD)(__FUNCTION__)(
            ": Sorry, unable to retrieve passphrase from user. (Failure).")
            .Flush();

    return bSuccess;
}
bool LegacySymmetric::Decrypt(
    const LegacySymmetric& theKey,
    const String& strCiphertext,
    String& strOutput,
    const String& pstrDisplay,
    const OTPassword* pAlreadyHavePW)
{
    if (!theKey.IsGenerated()) {
        LogDetail(OT_METHOD)(__FUNCTION__)(
            ": Failure: theKey.IsGenerated() was false. (The calling "
            "code probably should have checked for that...).")
            .Flush();
        return false;
    }

    auto ascArmor = Armored::Factory();
    const bool bLoadedArmor = Armored::LoadFromString(
        ascArmor, strCiphertext);  // str_bookend="-----BEGIN" by default

    if (!bLoadedArmor || !ascArmor->Exists()) {
        otErr << __FUNCTION__ << ": Failure loading ciphertext envelope:\n\n"
              << strCiphertext << "\n\n";
        return false;
    }

    // By this point, we know we have a ciphertext envelope and a symmetric Key.
    //
    std::unique_ptr<OTPassword> pPassUserInput;

    if (nullptr == pAlreadyHavePW) {
        const char* szDisplay = "Decrypting a password-protected ciphertext.";
        const auto strDisplay = String::Factory(
            (!pstrDisplay.Exists()) ? szDisplay : pstrDisplay.Get());

        pPassUserInput.reset(
            GetPassphraseFromUser(strDisplay));  // bAskTwice=false
                                                 // by default.
    }

    bool bSuccess = false;

    if (pPassUserInput ||  // Success retrieving the passphrase from the
        pAlreadyHavePW)    // user, or passphrase was provided out of scope.
    {
        OTEnvelope theEnvelope(ascArmor);

        if (theEnvelope.Decrypt(
                strOutput,
                theKey,
                pPassUserInput ? *pPassUserInput : *pAlreadyHavePW)) {
            bSuccess = true;
        } else {
            LogDetail(OT_METHOD)(__FUNCTION__)(
                ": Failed trying to decrypt. (Sorry).")
                .Flush();
        }
    } else
        LogDetail(OT_METHOD)(__FUNCTION__)(
            ": Sorry, unable to retrieve passphrase from user. (Failure).")
            .Flush();

    return bSuccess;
}
CMasterList::CMasterList(String strHost, String strVersion, unsigned long ulTimeout, int iServerPort)
{
	m_pHttpClient = new CHttpClient();
	m_pHttpClient->SetRequestTimeout(10000);
	m_pHttpClient->SetHost(strHost);
	m_pHttpClient->SetPort(CSettings::GetInteger("masterlistport"));
	m_ulLastPulse = NULL;
	m_strPostPath.Format(CSettings::GetString("masterlistpath") + "?version=%s&port=%d", strVersion.Get(), iServerPort);
	m_ulTimeout = ulTimeout;
	m_bSentListedMessage = false;
	m_bSentErrorMessage = false;
}
Example #14
0
// return -1 if error, 0 if nothing, and 1 if the node was processed.
int32_t OTOffer::ProcessXMLNode(irr::io::IrrXMLReader*& xml)
{
    int32_t nReturnVal = 0;

    // Here we call the parent class first.
    // If the node is found there, or there is some error,
    // then we just return either way.  But if it comes back
    // as '0', then nothing happened, and we'll continue executing.
    //
    // -- Note you can choose not to call the parent if
    // you don't want to use any of those xml tags.
    // As I do below, in the case of OTAccount.
    // if (nReturnVal = Contract::ProcessXMLNode(xml))
    //    return nReturnVal;

    if (!strcmp("marketOffer", xml->getNodeName())) {
        m_strVersion = xml->getAttributeValue("version");

        String strIsSelling;
        strIsSelling = xml->getAttributeValue("isSelling");
        if (strIsSelling.Compare("true"))
            m_bSelling = true;
        else
            m_bSelling = false;

        m_strContractType.Set((m_bSelling ? "ASK" : "BID"));

        const String strNotaryID(xml->getAttributeValue("notaryID")),
            strInstrumentDefinitionID(
                xml->getAttributeValue("instrumentDefinitionID")),
            strCurrencyTypeID(xml->getAttributeValue("currencyTypeID"));

        const Identifier NOTARY_ID(strNotaryID),
            INSTRUMENT_DEFINITION_ID(strInstrumentDefinitionID),
            CURRENCY_TYPE_ID(strCurrencyTypeID);

        SetNotaryID(NOTARY_ID);
        SetInstrumentDefinitionID(INSTRUMENT_DEFINITION_ID);
        SetCurrencyID(CURRENCY_TYPE_ID);

        const String strScale = xml->getAttributeValue("marketScale");
        const int64_t lScale =
            strScale.Exists() ? strScale.ToLong() : 0; // if it doesn't exist,
                                                       // the 0 here causes the
                                                       // below error to fire.

        if (!isPowerOfTen(lScale)) {
            otOut << "OTOffer::ProcessXMLNode: Failure: marketScale *must* be "
                     "1, or a power of 10. Instead I got: " << lScale << ".\n";
            return (-1);
        }
        else
            SetScale(lScale);

        const String strPriceLimit = xml->getAttributeValue("priceLimit");
        const int64_t lPriceLimit = strPriceLimit.Exists()
                                        ? strPriceLimit.ToLong()
                                        : 0; // if it doesn't exist, the 0 here
                                             // causes the below error to fire.

        // NOTE: Market Orders (new) have a 0 price, so this error condition was
        // changed.
        if (!strPriceLimit.Exists())
        //      if (lPriceLimit < 1)
        {
            otOut << "OTOffer::ProcessXMLNode: Failure: priceLimit *must* be "
                     "provided(" << lPriceLimit << ").\n";
            return (-1);
        }
        else
            SetPriceLimit(lPriceLimit);

        const String strTotal = xml->getAttributeValue("totalAssetsOnOffer");
        const int64_t lTotal =
            strTotal.Exists() ? strTotal.ToLong() : 0; // if it doesn't exist,
                                                       // the 0 here causes the
                                                       // below error to fire.
        if (lTotal < 1) {
            otOut << "OTOffer::ProcessXMLNode: Failure: totalAssetsOnOffer "
                     "*must* be larger than 0. Instead I got: " << lTotal
                  << ".\n";
            return (-1);
        }
        else
            SetTotalAssetsOnOffer(lTotal);

        const String strFinished = xml->getAttributeValue("finishedSoFar");
        const int64_t lFinished = strFinished.Exists()
                                      ? strFinished.ToLong()
                                      : 0; // if it doesn't exist, the 0 here
                                           // causes the below error to fire.
        if (lFinished < 0) {
            otOut << "OTOffer::ProcessXMLNode: Failure: finishedSoFar *must* "
                     "be 0 or larger. Instead I got: " << lFinished << ".\n";
            return (-1);
        }
        else
            SetFinishedSoFar(lFinished);

        const String strMinInc = xml->getAttributeValue("minimumIncrement");
        // if it doesn't exist, the 0 here causes the below error to fire.
        const int64_t lMinInc = strMinInc.Exists() ? strMinInc.ToLong() : 0;

        if ((lMinInc < 1) || (lMinInc > lTotal)) // Minimum increment cannot
                                                 // logically be higher than the
                                                 // total assets on offer...
        {
            otOut << "OTOffer::ProcessXMLNode: Failure: minimumIncrement "
                     "*must* be 1 or larger, \n"
                     "and must also be less than the total assets on offer. "
                     "Instead I got: " << lMinInc << ".\n";
            return (-1);
        }
        else
            SetMinimumIncrement(lMinInc);

        const String strTransNum = xml->getAttributeValue("transactionNum");
        const int64_t lTransNum =
            strTransNum.Exists() ? strTransNum.ToLong() : 0;

        SetTransactionNum(lTransNum);

        const String str_valid_from = xml->getAttributeValue("validFrom");
        const String str_valid_to = xml->getAttributeValue("validTo");

        int64_t tValidFrom =
            str_valid_from.Exists() ? parseTimestamp(str_valid_from.Get()) : 0;
        int64_t tValidTo =
            str_valid_to.Exists() ? parseTimestamp(str_valid_to.Get()) : 0;

        if ((tValidTo < tValidFrom) && (tValidTo != 0)) {
            otOut << "OTOffer::" << __FUNCTION__ << ": Failure: validTo date ("
                  << tValidFrom << ") cannot be earlier than "
                                   "validFrom date (" << tValidTo << ").\n";
            return (-1);
        }

        SetValidFrom(OTTimeGetTimeFromSeconds(tValidFrom));
        SetValidTo(OTTimeGetTimeFromSeconds(tValidTo));

        otLog4 << "\n\nOffer. Transaction Number: " << m_lTransactionNum
               << "\n Valid From: " << tValidFrom << "\n Valid To: " << tValidTo
               << "\n"
                  " InstrumentDefinitionID: " << strInstrumentDefinitionID
               << "\n  CurrencyTypeID: " << strCurrencyTypeID
               << "\n NotaryID: " << strNotaryID
               << "\n"
                  " Price Limit: " << GetPriceLimit()
               << ",  Total Assets on Offer: " << GetTotalAssetsOnOffer()
               << ",  " << (m_bSelling ? "sold" : "bought")
               << " so far: " << GetFinishedSoFar() << "\n "
                                                       " Scale: " << GetScale()
               << ".   Minimum Increment: " << GetMinimumIncrement()
               << ".  This offer is a" << (m_bSelling ? "n ASK" : " BID")
               << ".\n";

        nReturnVal = 1;
    }

    return nReturnVal;
}
Example #15
0
// SET (binary id) FROM ENCODED STRING
void Identifier::SetString(const String& encoded)
{
    return SetString(std::string(encoded.Get()));
}