Exemple #1
0
void SignVerifyMessageDialog::on_verifyMessageButton_VM_clicked()
{
    CBitcoinAddress addr(ui->addressIn_VM->text().toStdString());
    if (!addr.IsValid())
    {
        ui->addressIn_VM->setValid(false);
        ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel_VM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again."));
        return;
    }
    CKeyID keyID;
    if (!addr.GetKeyID(keyID))
    {
        ui->addressIn_VM->setValid(false);
        ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel_VM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again."));
        return;
    }

    bool fInvalid = false;
    std::vector<unsigned char> vchSig = DecodeBase64(ui->signatureIn_VM->text().toStdString().c_str(), &fInvalid);

    if (fInvalid)
    {
        ui->signatureIn_VM->setValid(false);
        ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel_VM->setText(tr("The signature could not be decoded.") + QString(" ") + tr("Please check the signature and try again."));
        return;
    }

    CDataStream ss(SER_GETHASH, 0);
    ss << strMessageMagic;
    ss << ui->messageIn_VM->document()->toPlainText().toStdString();

    CPubKey pubkey;
    if (!pubkey.RecoverCompact(Hash(ss.begin(), ss.end()), vchSig))
    {
        ui->signatureIn_VM->setValid(false);
        ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel_VM->setText(tr("The signature did not match the message digest.") + QString(" ") + tr("Please check the signature and try again."));
        return;
    }

    if (!(CBitcoinAddress(pubkey.GetID()) == addr))
    {
        ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verification failed.") + QString("</nobr>"));
        return;
    }

    ui->statusLabel_VM->setStyleSheet("QLabel { color: green; }");
    ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verified.") + QString("</nobr>"));
}
Exemple #2
0
void HTTPServerHandleAuthHeader(HTTPSession *Heads,int HeaderType, char *Type, char *Data)
{
char *Tempstr=NULL, *Name=NULL, *Value=NULL, *ptr;
char *nonce=NULL, *cnonce=NULL, *request_count=NULL, *qop=NULL, *algo=NULL, *uri=NULL;
int len;

if (strcmp(Type,"Basic")==0)
{
	Tempstr=DecodeBase64(Tempstr, &len, Data);
	ptr=GetToken(Tempstr,":",&Heads->UserName,0);
	Heads->Password=CopyStr(Heads->Password,ptr);
}
else if (strcmp(Type,"Digest")==0)
{
	uri=CopyStr(uri,"");
	algo=CopyStr(algo,"");
	ptr=GetNameValuePair(Data,",","=",&Name,&Value);
	while (ptr)
	{
		if (StrLen(Name) && StrLen(Value))
		{
		StripLeadingWhitespace(Name);
		StripLeadingWhitespace(Value);
		if (strcmp(Name,"username")==0) Heads->UserName=CopyStr(Heads->UserName,Value);
		if (strcmp(Name,"response")==0) Heads->Password=CopyStr(Heads->Password,Value);
		if (strcmp(Name,"nonce")==0) nonce=CopyStr(nonce,Value);
		if (strcmp(Name,"cnonce")==0) cnonce=CopyStr(cnonce,Value);
		if (strcmp(Name,"nc")==0) request_count=CopyStr(request_count,Value);
		if (strcmp(Name,"qop")==0) qop=CopyStr(qop,Value);
		if (strcmp(Name,"uri")==0) uri=CopyStr(uri,Value);
		if (strcmp(Name,"algorithm")==0) algo=CopyStr(algo,Value);
		}
		
	ptr=GetNameValuePair(ptr,",","=",&Name,&Value);
	}

// server nonce (nonce), request counter (nc), client nonce (cnonce), quality of protection code (qop) and HA2 result is calculated. The result is the "response" value provided by the client.

if (StrLen(qop)) Heads->AuthDetails=MCopyStr(Heads->AuthDetails,uri,":",algo,":",nonce,":",request_count,":",cnonce,":",qop, NULL);
else Heads->AuthDetails=CopyStr(Heads->AuthDetails,nonce);

}

DestroyString(qop);
DestroyString(uri);
DestroyString(algo);
DestroyString(Name);
DestroyString(Value);
DestroyString(nonce);
DestroyString(cnonce);
DestroyString(Tempstr);
DestroyString(request_count);
}
Exemple #3
0
static	void
DecodeStringToBinary(
	byte	*p,
	size_t	size,
	char	*str)
{
#ifdef	BINARY_IS_BASE64
	DecodeBase64(p,size,str,strlen(str));
#else
	int		i;

	for	( i = 0 ; i < size ; i ++ , p ++ ) {
		if		(  *str  ==  '\\'  ) {
			str ++;
			switch	(*str) {
			  case	'b':
				*p = '\b';
				str ++;
				break;
			  case	'f':
				*p = '\f';
				str ++;
				break;
			  case	'n':
				*p = '\n';
				str ++;
				break;
			  case	'r':
				*p = '\r';
				str ++;
				break;
			  case	't':
				*p = '\t';
				str ++;
				break;
			  case	'u':
				str ++;
				*p = (unsigned char)HexToInt(str,2);
				str += 2;
				break;
			  default:
				*p = *str;
				str ++;
				break;
			}
		} else {
			*p = *str;
			str ++;
		}
	}
#endif
}
std::string GetBeaconPublicKey(const std::string& cpid, bool bAdvertisingBeacon)
{
    //3-26-2017 - Ensure beacon public key is within 6 months of network age (If advertising, let it be returned as missing after 5 months, to ensure the public key is renewed seamlessly).
    int iMonths = bAdvertisingBeacon ? 5 : 6;
    int64_t iMaxSeconds = 60 * 24 * 30 * iMonths * 60;
    std::string sBeacon = RetrieveBeaconValueWithMaxAge(cpid, iMaxSeconds);
    if (sBeacon.empty()) return "";
    // Beacon data structure: CPID,hashRand,Address,beacon public key: base64 encoded
    std::string sContract = DecodeBase64(sBeacon);
    std::vector<std::string> vContract = split(sContract.c_str(),";");
    if (vContract.size() < 4) return "";
    std::string sBeaconPublicKey = vContract[3];
    return sBeaconPublicKey;
}
Exemple #5
0
/*static*/
std::string I2PSession::GenerateB32AddressFromDestination(const std::string& destination)
{
    std::string canonicalDest = destination;
    for (size_t pos = canonicalDest.find_first_of('-'); pos != std::string::npos; pos = canonicalDest.find_first_of('-', pos))
        canonicalDest[pos] = '+';
    for (size_t pos = canonicalDest.find_first_of('~'); pos != std::string::npos; pos = canonicalDest.find_first_of('~', pos))
        canonicalDest[pos] = '/';
    std::string rawHash = DecodeBase64(canonicalDest);
    uint256 hash;
    SHA256((const unsigned char*)rawHash.c_str(), rawHash.size(), (unsigned char*)&hash);
    std::string result = EncodeBase32(hash.begin(), hash.end() - hash.begin()) + ".b32.i2p";
    for (size_t pos = result.find_first_of('='); pos != std::string::npos; pos = result.find_first_of('=', pos-1))
        result.erase(pos, 1);
    return result;
}
int WXBizMsgCrypt::GenAesKeyFromEncodingKey( const std::string & sEncodingKey, std::string & sAesKey)
{
    if(kEncodingKeySize != sEncodingKey.size())
    {
        return -1;
    }
    
    std::string sBase64 = sEncodingKey + "=";
    int ret = DecodeBase64(sBase64, sAesKey);
    if(0 != ret || kAesKeySize != sAesKey.size())
    {
        return -1;
    }
    
    return 0;
}
Exemple #7
0
bool DecodePSBT(PartiallySignedTransaction& psbt, const std::string& base64_tx, std::string& error)
{
    std::vector<unsigned char> tx_data = DecodeBase64(base64_tx.c_str());
    CDataStream ss_data(tx_data, SER_NETWORK, PROTOCOL_VERSION);
    try {
        ss_data >> psbt;
        if (!ss_data.empty()) {
            error = "extra data after PSBT";
            return false;
        }
    } catch (const std::exception& e) {
        error = e.what();
        return false;
    }
    return true;
}
int DetectBase64DecodeDoMatch(DetectEngineThreadCtx *det_ctx, Signature *s,
                              const SigMatch *sm, uint8_t *payload, uint32_t payload_len)
{
    DetectBase64Decode *data = (DetectBase64Decode *)sm->ctx;
    int decode_len;

#if 0
    printf("Input data:\n");
    PrintRawDataFp(stdout, payload, payload_len);
#endif

    if (data->relative) {
        payload += det_ctx->buffer_offset;
        payload_len -= det_ctx->buffer_offset;
    }

    if (data->offset) {
        if (data->offset >= payload_len) {
            return 0;
        }
        payload = payload + data->offset;
        payload_len -= data->offset;
    }

    decode_len = MIN(payload_len, data->bytes);

#if 0
    printf("Decoding:\n");
    PrintRawDataFp(stdout, payload, decode_len);
#endif

    det_ctx->base64_decoded_len = DecodeBase64(det_ctx->base64_decoded,
                                  payload, decode_len, 0);
    SCLogDebug("Decoded %d bytes from base64 data.",
               det_ctx->base64_decoded_len);
#if 0
    if (det_ctx->base64_decoded_len) {
        printf("Decoded data:\n");
        PrintRawDataFp(stdout, det_ctx->base64_decoded,
                       det_ctx->base64_decoded_len);
    }
#endif

    return det_ctx->base64_decoded_len > 0;
}
void PaymentServerTests::paymentServerTests()
{
    SelectParams(CBaseChainParams::MAIN);
    OptionsModel optionsModel;
    PaymentServer* server = new PaymentServer(NULL, false);
    X509_STORE* caStore = X509_STORE_new();
    X509_STORE_add_cert(caStore, parse_b64der_cert(caCert_BASE64));
    PaymentServer::LoadRootCAs(caStore);
    server->setOptionsModel(&optionsModel);
    server->uiReady();

    // Now feed PaymentRequests to server, and observe signals it produces:
    std::vector<unsigned char> data = DecodeBase64(paymentrequest1_BASE64);
    SendCoinsRecipient r = handleRequest(server, data);
    QString merchant;
    r.paymentRequest.getMerchant(caStore, merchant);
    QCOMPARE(merchant, QString("testmerchant.org"));

    // Version of the above, with an expired certificate:
    data = DecodeBase64(paymentrequest2_BASE64);
    r = handleRequest(server, data);
    r.paymentRequest.getMerchant(caStore, merchant);
    QCOMPARE(merchant, QString(""));

    // Long certificate chain:
    data = DecodeBase64(paymentrequest3_BASE64);
    r = handleRequest(server, data);
    r.paymentRequest.getMerchant(caStore, merchant);
    QCOMPARE(merchant, QString("testmerchant8.org"));

    // Long certificate chain, with an expired certificate in the middle:
    data = DecodeBase64(paymentrequest4_BASE64);
    r = handleRequest(server, data);
    r.paymentRequest.getMerchant(caStore, merchant);
    QCOMPARE(merchant, QString(""));

    // Validly signed, but by a CA not in our root CA list:
    data = DecodeBase64(paymentrequest5_BASE64);
    r = handleRequest(server, data);
    r.paymentRequest.getMerchant(caStore, merchant);
    QCOMPARE(merchant, QString(""));

    // Try again with no root CA's, verifiedMerchant should be empty:
    caStore = X509_STORE_new();
    PaymentServer::LoadRootCAs(caStore);
    data = DecodeBase64(paymentrequest1_BASE64);
    r = handleRequest(server, data);
    r.paymentRequest.getMerchant(caStore, merchant);
    QCOMPARE(merchant, QString(""));

    delete server;
}
Exemple #10
0
//---------------------------------------------------------------------------
// 標準復号化
string DecryptString2(const string& encodedstr,const string &key)
{
	string id=encodedstr.substr(0,9);
	if(id!="!KAWA0001") return("");

	string str=DecodeBase64(encodedstr.substr(9));

	unsigned char k=Kawa0001CalcKey(key);
	if(k!=(unsigned char)str[0]) return("");

	string decodedstr;
	decodedstr.reserve(str.size());
	for(unsigned int i=1,max=str.size();i<max;i++) {
		decodedstr+=str[i]^k;
	}

	return(decodedstr);
}
Exemple #11
0
static bool RPCAuthorized(const std::string& strAuth, std::string& strAuthUsernameOut)
{
    if (strRPCUserColonPass.empty()) // Belt-and-suspenders measure if InitRPCAuthentication was not called
        return false;
    if (strAuth.substr(0, 6) != "Basic ")
        return false;
    std::string strUserPass64 = strAuth.substr(6);
    boost::trim(strUserPass64);
    std::string strUserPass = DecodeBase64(strUserPass64);

    if (strUserPass.find(':') != std::string::npos)
        strAuthUsernameOut = strUserPass.substr(0, strUserPass.find(':'));

    //Check if authorized under single-user field
    if (TimingResistantEqual(strUserPass, strRPCUserColonPass)) {
        return true;
    }
    return multiUserAuthorized(strUserPass);
}
Exemple #12
0
// 参考
// こっちを元にすれば、もうちょっと良いコードになると思うが、うーん・・・。
// (考え中)
string DecryptString(const string& encodedstr)
{
	// long int = 32bit であることに依存したコーディングになってます 
	string str=DecodeBase64(encodedstr.substr(9));

	unsigned cnt = str.size();
	string decodedstr;
	
	char *s = new char[cnt + 4];
	
	str.copy(s, cnt);
	
	for(unsigned int i=0;i<cnt ;i += 4) {
		*(unsigned long *)(s + i) ^= 0xccccccccUL;
	}

	decodedstr.assign(s, cnt);
	delete[] s;
	return(decodedstr);
}
std::string AdvancedDecrypt(std::string boinchash_encrypted)
{
    try{
       std::string pre_encrypted_boinchash = DecodeBase64(boinchash_encrypted);
       std::vector<unsigned char> vchCryptedSecret(pre_encrypted_boinchash.begin(),pre_encrypted_boinchash.end());
       std::vector<unsigned char> vchPlaintext;
       GridDecrypt(vchCryptedSecret,vchPlaintext);
       std::string decrypted = UnsignedVectorToString(vchPlaintext);
       return decrypted;
    } catch (std::exception &e)
    {
        LogPrintf("Error while decrypting %s",boinchash_encrypted);
        return "";
    }
    catch(...)
    {
        LogPrintf("Error while decrypting 2.");
        return "";
    }
}
Exemple #14
0
//---------------------------------------------------------------------------
// 標準復号化
string DecryptString(const string& encodedstr)
{
	string str=DecodeBase64(encodedstr.substr(9));

	unsigned char k=0xcc;
	unsigned int skip=0;

	string id=encodedstr.substr(0,9);
	if(id=="!KAWA0001") {
		k=(unsigned char)str[0];
		skip=1;
	}

	string decodedstr;
	decodedstr.reserve(str.size());
	for(unsigned int i=skip,max=str.size();i<max;i++) {
		decodedstr+=str[i]^k;
	}

	return(decodedstr);
}
Exemple #15
0
bool HTTPAuthorized (const std::map<std::string, std::string>& mapHeaders)
{
    bool const credentialsRequired (! getConfig().RPC_USER.empty() &&
                                    ! getConfig().RPC_PASSWORD.empty());
    if (! credentialsRequired)
        return true;

    auto const it = mapHeaders.find ("authorization");
    if ((it == mapHeaders.end ()) || (it->second.substr (0, 6) != "Basic "))
        return false;

    std::string strUserPass64 = it->second.substr (6);
    boost::trim (strUserPass64);
    std::string strUserPass = DecodeBase64 (strUserPass64);
    std::string::size_type nColon = strUserPass.find (":");

    if (nColon == std::string::npos)
        return false;

    std::string strUser = strUserPass.substr (0, nColon);
    std::string strPassword = strUserPass.substr (nColon + 1);
    return (strUser == getConfig ().RPC_USER) && (strPassword == getConfig ().RPC_PASSWORD);
}
Exemple #16
0
void PaymentServerTests::paymentServerTests()
{
    SelectParams(CBaseChainParams::MAIN);
    OptionsModel optionsModel;
    PaymentServer* server = new PaymentServer(nullptr, false);
    X509_STORE* caStore = X509_STORE_new();
    X509_STORE_add_cert(caStore, parse_b64der_cert(caCert1_BASE64));
    PaymentServer::LoadRootCAs(caStore);
    server->setOptionsModel(&optionsModel);
    server->uiReady();

    std::vector<unsigned char> data;
    SendCoinsRecipient r;
    QString merchant;

    // Now feed PaymentRequests to server, and observe signals it produces

    // This payment request validates directly against the
    // caCert1 certificate authority:
    data = DecodeBase64(paymentrequest1_cert1_BASE64);
    r = handleRequest(server, data);
    r.paymentRequest.getMerchant(caStore, merchant);
    QCOMPARE(merchant, QString("testmerchant.org"));

    // Signed, but expired, merchant cert in the request:
    data = DecodeBase64(paymentrequest2_cert1_BASE64);
    r = handleRequest(server, data);
    r.paymentRequest.getMerchant(caStore, merchant);
    QCOMPARE(merchant, QString(""));

    // 10-long certificate chain, all intermediates valid:
    data = DecodeBase64(paymentrequest3_cert1_BASE64);
    r = handleRequest(server, data);
    r.paymentRequest.getMerchant(caStore, merchant);
    QCOMPARE(merchant, QString("testmerchant8.org"));

    // Long certificate chain, with an expired certificate in the middle:
    data = DecodeBase64(paymentrequest4_cert1_BASE64);
    r = handleRequest(server, data);
    r.paymentRequest.getMerchant(caStore, merchant);
    QCOMPARE(merchant, QString(""));

    // Validly signed, but by a CA not in our root CA list:
    data = DecodeBase64(paymentrequest5_cert1_BASE64);
    r = handleRequest(server, data);
    r.paymentRequest.getMerchant(caStore, merchant);
    QCOMPARE(merchant, QString(""));

    // Try again with no root CA's, verifiedMerchant should be empty:
    caStore = X509_STORE_new();
    PaymentServer::LoadRootCAs(caStore);
    data = DecodeBase64(paymentrequest1_cert1_BASE64);
    r = handleRequest(server, data);
    r.paymentRequest.getMerchant(caStore, merchant);
    QCOMPARE(merchant, QString(""));

    // Load second root certificate
    caStore = X509_STORE_new();
    X509_STORE_add_cert(caStore, parse_b64der_cert(caCert2_BASE64));
    PaymentServer::LoadRootCAs(caStore);

    QByteArray byteArray;

    // For the tests below we just need the payment request data from
    // paymentrequestdata.h parsed + stored in r.paymentRequest.
    //
    // These tests require us to bypass the following normal client execution flow
    // shown below to be able to explicitly just trigger a certain condition!
    //
    // handleRequest()
    // -> PaymentServer::eventFilter()
    //   -> PaymentServer::handleURIOrFile()
    //     -> PaymentServer::readPaymentRequestFromFile()
    //       -> PaymentServer::processPaymentRequest()

    // Contains a testnet paytoaddress, so payment request network doesn't match client network:
    data = DecodeBase64(paymentrequest1_cert2_BASE64);
    byteArray = QByteArray((const char*)data.data(), data.size());
    r.paymentRequest.parse(byteArray);
    // Ensure the request is initialized, because network "main" is default, even for
    // uninitialized payment requests and that will fail our test here.
    QVERIFY(r.paymentRequest.IsInitialized());
    QCOMPARE(PaymentServer::verifyNetwork(r.paymentRequest.getDetails()), false);

    // Expired payment request (expires is set to 1 = 1970-01-01 00:00:01):
    data = DecodeBase64(paymentrequest2_cert2_BASE64);
    byteArray = QByteArray((const char*)data.data(), data.size());
    r.paymentRequest.parse(byteArray);
    // Ensure the request is initialized
    QVERIFY(r.paymentRequest.IsInitialized());
    // compares 1 < GetTime() == false (treated as expired payment request)
    QCOMPARE(PaymentServer::verifyExpired(r.paymentRequest.getDetails()), true);

    // Unexpired payment request (expires is set to 0x7FFFFFFFFFFFFFFF = max. int64_t):
    // 9223372036854775807 (uint64), 9223372036854775807 (int64_t) and -1 (int32_t)
    // -1 is 1969-12-31 23:59:59 (for a 32 bit time values)
    data = DecodeBase64(paymentrequest3_cert2_BASE64);
    byteArray = QByteArray((const char*)data.data(), data.size());
    r.paymentRequest.parse(byteArray);
    // Ensure the request is initialized
    QVERIFY(r.paymentRequest.IsInitialized());
    // compares 9223372036854775807 < GetTime() == false (treated as unexpired payment request)
    QCOMPARE(PaymentServer::verifyExpired(r.paymentRequest.getDetails()), false);

    // Unexpired payment request (expires is set to 0x8000000000000000 > max. int64_t, allowed uint64):
    // 9223372036854775808 (uint64), -9223372036854775808 (int64_t) and 0 (int32_t)
    // 0 is 1970-01-01 00:00:00 (for a 32 bit time values)
    data = DecodeBase64(paymentrequest4_cert2_BASE64);
    byteArray = QByteArray((const char*)data.data(), data.size());
    r.paymentRequest.parse(byteArray);
    // Ensure the request is initialized
    QVERIFY(r.paymentRequest.IsInitialized());
    // compares -9223372036854775808 < GetTime() == true (treated as expired payment request)
    QCOMPARE(PaymentServer::verifyExpired(r.paymentRequest.getDetails()), true);

    // Test BIP70 DoS protection:
    unsigned char randData[BIP70_MAX_PAYMENTREQUEST_SIZE + 1];
    GetRandBytes(randData, sizeof(randData));
    // Write data to a temp file:
    QTemporaryFile tempFile;
    tempFile.open();
    tempFile.write((const char*)randData, sizeof(randData));
    tempFile.close();
    // compares 50001 <= BIP70_MAX_PAYMENTREQUEST_SIZE == false
    QCOMPARE(PaymentServer::verifySize(tempFile.size()), false);

    // Payment request with amount overflow (amount is set to 21000001 BTC):
    data = DecodeBase64(paymentrequest5_cert2_BASE64);
    byteArray = QByteArray((const char*)data.data(), data.size());
    r.paymentRequest.parse(byteArray);
    // Ensure the request is initialized
    QVERIFY(r.paymentRequest.IsInitialized());
    // Extract address and amount from the request
    QList<std::pair<CScript, CAmount> > sendingTos = r.paymentRequest.getPayTo();
    for (const std::pair<CScript, CAmount>& sendingTo : sendingTos) {
        CTxDestination dest;
        if (ExtractDestination(sendingTo.first, dest))
            QCOMPARE(PaymentServer::verifyAmount(sendingTo.second), false);
    }

    delete server;
}
std::string DecodeBase64(const std::string& str)
{
    std::vector<unsigned char> vchRet = DecodeBase64(str.c_str());
    return std::string((const char*)vchRet.data(), vchRet.size());
}
WCHAR *ParseMultipartBody(char *src, char *bond)
{
	char *srcback = _strdup(src);
	size_t sizebond = strlen(bond);
	int numparts = 1;
	int i;
	char *courbond = srcback;
	WCHAR *dest;
	for (;(courbond=strstr(courbond,bond));numparts++,courbond+=sizebond);
	APartDataType *partData = new APartDataType[numparts];
	memset(partData, 0, sizeof(APartDataType)*numparts);
	partData[0].Src = courbond = srcback;
	for (i=1;(courbond=strstr(courbond,bond));i++,courbond+=sizebond){
		*(courbond-2) = 0;
		partData[i].Src = courbond+sizebond;
		while (ENDLINE(partData[i].Src)) partData[i].Src++;
	}
	size_t resultSize=0;
	for (i=0;i<numparts;i++){
		ParseAPart(&partData[i]);
		if (partData[i].body){
			if (partData[i].TransEnc){
				if (!_stricmp(partData[i].TransEnc,"base64")) partData[i].TransEncType=TE_BASE64;
				else if (!_stricmp(partData[i].TransEnc,"quoted-printable"))partData[i].TransEncType=TE_QUOTEDPRINTABLE;
			}
			if (partData[i].ContType){
				char *CharSetStr;
				if(NULL!=(CharSetStr=ExtractFromContentType(partData[i].ContType,"charset=")))
				{
					partData[i].CodePage=GetCharsetFromString(CharSetStr,strlen(CharSetStr));
					delete[] CharSetStr;
				}
			}
			if (partData[i].ContType && !_strnicmp(partData[i].ContType,"text",4)) {
				char *localBody=0;
				switch (partData[i].TransEncType){
					case TE_BASE64:
					{
						int size =partData[i].bodyLen*3/4+5;
						localBody = new char[size+1];
						DecodeBase64(partData[i].body,localBody,size); 
					}break;
					case TE_QUOTEDPRINTABLE:
					{
						int size = partData[i].bodyLen+2;
						localBody = new char[size+1];
						DecodeQuotedPrintable(partData[i].body,localBody,size,FALSE); 
					}break;
				}
				ConvertStringToUnicode(localBody?localBody:partData[i].body,partData[i].CodePage,&partData[i].wBody);
				if (localBody) delete[] localBody;
			} else if(partData[i].ContType && !_strnicmp(partData[i].ContType,"multipart/",10)){
				//Multipart in mulitipart recursive? should be SPAM. Ah well
				char *bondary=NULL;
				if(NULL!=(bondary=ExtractFromContentType(partData[i].ContType,"boundary=")))
				{
					partData[i].wBody = ParseMultipartBody(partData[i].body,bondary);
					delete[] bondary;
				} else goto FailBackRaw; //multipart with no boundary? badly formatted messages.
			} else {
FailBackRaw:
				ConvertStringToUnicode(partData[i].body,partData[i].CodePage,&partData[i].wBody);
			}
			resultSize += wcslen(partData[i].wBody);
		}// if (partData[i].body)
		resultSize += 100+4+3; //cr+nl+100+ 3*bullet
	}
	dest = new WCHAR[resultSize+1];
	size_t destpos = 0;
	for (i=0;i<numparts;i++){
		if (i){ // part before first boudary should not have headers
			char infoline[104]; size_t linesize = 0;
			_snprintf(infoline,100,"%s %d",Translate("Part"),i);
			linesize = strlen(infoline);
			if (partData[i].TransEnc){
				_snprintf(infoline+linesize,100-linesize,"; %s",partData[i].TransEnc);
				linesize = strlen(infoline);
			}
			if (partData[i].ContType){
				char *CharSetStr=strchr(partData[i].ContType,';');
				if (CharSetStr){
					CharSetStr[0]=0;
					_snprintf(infoline+linesize,100-linesize,"; %s",partData[i].ContType);
					linesize = strlen(infoline);
					partData[i].ContType=CharSetStr+1;
					if(NULL!=(CharSetStr=ExtractFromContentType(partData[i].ContType,"charset=")))
					{
						_snprintf(infoline+linesize,100-linesize,"; %s",CharSetStr);
						linesize = strlen(infoline);
						delete[] CharSetStr;
					}
					if(NULL!=(CharSetStr=ExtractFromContentType(partData[i].ContType,"name=")))
					{
						_snprintf(infoline+linesize,100-linesize,"; \"%s\"",CharSetStr);
						linesize = strlen(infoline);
						delete[] CharSetStr;
					}
				} else {
					_snprintf(infoline+linesize,100-linesize,"; %s",partData[i].ContType);
					linesize = strlen(infoline);
				}
			}
			sprintf(infoline+linesize,".\r\n");
			{WCHAR *temp=0;
				dest[destpos] = dest[destpos+1] = dest[destpos+2] = 0x2022; // bullet;
				destpos+=3;
				ConvertStringToUnicode(infoline,CP_ACP,&temp);
				size_t wsize = wcslen(temp);
				wcscpy(&dest[destpos],temp);
				destpos += wsize;
				delete[] temp;
			}
		} // if (i)
		if (partData[i].wBody){
			size_t wsize = wcslen(partData[i].wBody);
			wcscpy(&dest[destpos],partData[i].wBody);
			destpos += wsize;
			delete[] partData[i].wBody;
		}
	}

	free (srcback);
	delete[] partData;
	dest[resultSize] = 0;//just in case
	return dest;
}
void RemoteMinerClient::HandleMessage(const RemoteMinerMessage &message)
{
	json_spirit::Value tval=json_spirit::find_value(message.GetValue().get_obj(),"type");
	if(tval.type()==json_spirit::int_type)
	{
		std::cout << "Got message " << tval.get_int() << " from server." << std::endl;
		if(tval.get_int()==RemoteMinerMessage::MESSAGE_TYPE_SERVERHELLO)
		{
			m_gotserverhello=true;
			tval=json_spirit::find_value(message.GetValue().get_obj(),"metahashrate");
			if(tval.type()==json_spirit::int_type)
			{
				m_minerthreads.SetMetaHashSize(tval.get_int());
				m_metahashsize=tval.get_int();
			}
			tval=json_spirit::find_value(message.GetValue().get_obj(),"serverversion");
			if(tval.type()==json_spirit::str_type)
			{
				std::cout << "Server version " << tval.get_str() << std::endl;
			}
			tval=json_spirit::find_value(message.GetValue().get_obj(),"distributiontype");
			if(tval.type()==json_spirit::str_type)
			{
				std::cout << "Distribution type : " << tval.get_str() << std::endl;
			}
		}
		else if(tval.get_int()==RemoteMinerMessage::MESSAGE_TYPE_SERVERSENDWORK)
		{
			int64 nextblockid=0;
			std::vector<unsigned char> nextblock;
			std::vector<unsigned char> nextmidstate;
			uint256 nexttarget;
			tval=json_spirit::find_value(message.GetValue().get_obj(),"blockid");
			if(tval.type()==json_spirit::int_type)
			{
				nextblockid=tval.get_int();
			}
			tval=json_spirit::find_value(message.GetValue().get_obj(),"block");
			if(tval.type()==json_spirit::str_type)
			{
				DecodeBase64(tval.get_str(),nextblock);
			}
			tval=json_spirit::find_value(message.GetValue().get_obj(),"target");
			if(tval.type()==json_spirit::str_type)
			{
				nexttarget.SetHex(tval.get_str());
			}
			tval=json_spirit::find_value(message.GetValue().get_obj(),"midstate");
			if(tval.type()==json_spirit::str_type)
			{
				DecodeBase64(tval.get_str(),nextmidstate);
			}

			tval=json_spirit::find_value(message.GetValue().get_obj(),"fullblock");
			if(tval.type()==json_spirit::obj_type)
			{
				SaveBlock(tval.get_obj(),"block.txt");
				if(m_address160!=0)
				{
					double amount=0;
					if(FindGenerationAddressInBlock(m_address160,tval.get_obj(),amount))
					{
						std::cout << "Address " << Hash160ToAddress(m_address160) <<  " will receive " << amount << " BTC if this block is solved" << std::endl;
					}
					else
					{
						std::cout << "Address " << Hash160ToAddress(m_address160) << " not found in block being solved" << std::endl;
					}
				}
			}

			m_minerthreads.SetNextBlock(nextblockid,nexttarget,nextblock,nextmidstate);

		}
		else if(tval.get_int()==RemoteMinerMessage::MESSAGE_TYPE_SERVERSTATUS)
		{
			int64 clients=0;
			int64 khashmeta=0;
			int64 khashbest=0;
			int64 clientkhashmeta=0;
			time_t startuptime=0;
			struct tm startuptimetm;
			std::string startuptimestr("");
			int64 blocksgenerated=0;

			tval=json_spirit::find_value(message.GetValue().get_obj(),"clients");
			if(tval.type()==json_spirit::int_type)
			{
				clients=tval.get_int();
			}
			tval=json_spirit::find_value(message.GetValue().get_obj(),"khashmeta");
			if(tval.type()==json_spirit::int_type)
			{
				khashmeta=tval.get_int();
			}
			tval=json_spirit::find_value(message.GetValue().get_obj(),"khashbest");
			if(tval.type()==json_spirit::int_type)
			{
				khashbest=tval.get_int();
			}
			tval=json_spirit::find_value(message.GetValue().get_obj(),"yourkhashmeta");
			if(tval.type()==json_spirit::int_type)
			{
				clientkhashmeta=tval.get_int();
			}
			tval=json_spirit::find_value(message.GetValue().get_obj(),"sessionstartuptime");
			if(tval.type()==json_spirit::int_type)
			{
				startuptime=tval.get_int();
				startuptimetm=*gmtime(&startuptime);
				std::vector<char> buff(128,0);
				int rval=strftime(&buff[0],buff.size()-1,"%Y-%m-%d %H:%M:%S",&startuptimetm);
				buff.resize(rval);
				startuptimestr=std::string(buff.begin(),buff.end());
			}
			tval=json_spirit::find_value(message.GetValue().get_obj(),"sessionblocksgenerated");
			if(tval.type()==json_spirit::int_type)
			{
				blocksgenerated=tval.get_int();
			}
			
			std::cout << std::endl;
			std::cout << GetTimeStr(time(0)) << std::endl;
			std::cout << "Server Status : " << clients << " clients, " << khashmeta << " khash/s" << std::endl;
			std::cout << blocksgenerated << " blocks generated since " << startuptimestr << " UTC" << std::endl;
			std::cout << "Server reports my khash/s as " << clientkhashmeta << std::endl;
		}
	}
	else
	{
		std::cout << "Server sent invalid message.  Disconnecting." << std::endl;
	}
}
Exemple #20
0
extern	Bool
SetValueStringWithLength(
	ValueStruct	*val,
	char		*str,
	size_t		slen,
	char		*codeset)
{
	Bool	rc
	,		fMinus
	,		fPoint;
	size_t	len;
	byte	*p;
	byte	buff[SIZE_NUMBUF+1]
		,	sbuff[SIZE_LONGNAME+1];
	Fixed	from;
	size_t	size;
#ifdef	WITH_I18N
	byte	*q;
	iconv_t	cd;
	size_t	sob
	,		sib;
	char	*istr;
#endif

ENTER_FUNC;
	if		(  val  ==  NULL  ) {
		fprintf(stderr,"no ValueStruct\n");
		rc = FALSE;
	} else
	if		(	(  str   ==  NULL      )
			||	(  *str  ==  CHAR_NIL  ) ) {
		ValueIsNil(val);
		rc = TRUE;
	} else {
		ValueIsNonNil(val);
		switch	(ValueType(val)) {
		  case	GL_TYPE_CHAR:
		  case	GL_TYPE_VARCHAR:
		  case	GL_TYPE_DBCODE:
		  case	GL_TYPE_TEXT:
		  case	GL_TYPE_SYMBOL:
#ifdef	WITH_I18N
			if		(	(  codeset  !=  NULL  )
					&&	(	(  stricmp(codeset,"utf8")   ==  0  )
						||	(  stricmp(codeset,"utf-8")  ==  0  ) ) )	{
				codeset = NULL;
			}
			if		(  codeset  !=  NULL  ) {
				if		(  IS_VALUE_EXPANDABLE(val)  ) {
					len = slen;
				} else {
					len = ValueStringLength(val) < slen ?
						ValueStringLength(val) : slen;
				}
				cd = iconv_open("utf8",codeset);
				while	(TRUE) {
					istr = str;
					sib = len;
					sob = ValueStringSize(val);
					if		(  ( q = ValueString(val) )  !=  NULL  ) {
						memclear(ValueString(val),ValueStringSize(val));
						if		(  iconv(cd,&istr,&sib,(void*)&q,&sob)  ==  0  )	break;
						if		(  errno  ==  E2BIG ) {
							xfree(ValueString(val));
							ValueStringSize(val) *= 2;
						} else
							break;
					} else {
						ValueStringSize(val) = 1;
					}
					ValueString(val) = (byte *)xmalloc(ValueStringSize(val));
				};
				iconv_close(cd);
				*q = 0;
				len = ValueStringSize(val) - sob;
			} else {
#endif
				size = slen + 1;
				len = slen;
				if		(  size  >  ValueStringSize(val)  ) {
					if		(  ValueString(val)  !=  NULL  ) {
						xfree(ValueString(val));
					}
					ValueStringSize(val) = size;
					ValueString(val) = (byte *)xmalloc(size);
				}
				memclear(ValueString(val),ValueStringSize(val));
				strcpy(ValueString(val),str);
#ifdef	WITH_I18N
			}
#endif
			if		(  IS_VALUE_EXPANDABLE(val)  ) {
				ValueStringLength(val) = len;
			}
			rc = TRUE;
			break;
		  case	GL_TYPE_BYTE:
			DecodeStringToBinary(ValueByte(val),ValueByteLength(val),str);
			rc = TRUE;
			break;
		  case	GL_TYPE_BINARY:
#ifdef	BINARY_IS_BASE64
			p = (byte *)xmalloc(strlen(str));
			size = strlen(str);
			size = DecodeBase64(p,size,str,size);
			if		(  ValueByte(val)  !=  NULL  ) {
				xfree(ValueByte(val));
			}
			ValueByteSize(val) = strlen(str);
			ValueByte(val) = p;
#else
			size = 0;
			for	( p = str ; *p != 0 ; ) {
				if		(  *p  ==  '\\'  ) {
					p ++;
					if		(  *p  ==  'u'  ) {
						p += 3;
					} else {
						p ++;
					}
				} else {
					p ++;
				}
				size ++;
			}
			if		(  size  >  ValueByteSize(val)  ) {
				if		(  ValueByte(val)  !=  NULL  ) {
						xfree(ValueByte(val));
				}
				ValueByteSize(val) = size;
				ValueByte(val) = (byte *)xmalloc(size);
			}
			memclear(ValueByte(val),ValueByteSize(val));
			DecodeStringToBinary(ValueByte(val),size,str);
#endif
			ValueByteLength(val) = size;
			rc = TRUE;
			break;
		  case	GL_TYPE_OBJECT:
			ValueObjectId(val) = 0;
			for	( ; slen > 0 ; slen -- )	{
				if		(  isdigit(*str)  )	{
					ValueObjectId(val) = ValueObjectId(val) * 10 + ( *str - '0' );
				}
				str ++;
			}
			if		(  ValueObjectFile(val)  !=  NULL  ) {
				xfree(ValueObjectFile(val));
				ValueObjectFile(val) = NULL;
			}
			rc = TRUE;
			break;
		  case	GL_TYPE_NUMBER:
		  case	GL_TYPE_INT:
		  case	GL_TYPE_FLOAT:
		  case	GL_TYPE_BOOL:
		  case	GL_TYPE_TIMESTAMP:
		  case	GL_TYPE_DATE:
		  case	GL_TYPE_TIME:
#ifdef	WITH_I18N
			if		(  codeset  !=  NULL  ) {
				cd = iconv_open("utf8",codeset);
				istr = str;
				sib = slen;
				sob = SIZE_NUMBUF;
				p = sbuff;
				iconv(cd,&istr,&sib,(void*)&p,&sob);
				iconv_close(cd);
				*p = 0;
				str = sbuff;
			} else {
#endif
				strncpy(sbuff,str,SIZE_NUMBUF);
				str = sbuff;
#ifdef	WITH_I18N
			}
#endif
			switch	(ValueType(val)) {
			  case	GL_TYPE_NUMBER:
				p = buff;
				from.flen = 0;
				from.slen = 0;
				from.sval = buff;
				fPoint = FALSE;
				fMinus = FALSE;
				while	(  *str  !=  0  ) {
					if		(  fPoint  ) {
						from.slen ++;
					}
					if		(  *str  ==  '-'  ) {
						fMinus = TRUE;
					} else
					if	(  isdigit(*str)  ) {
						*p ++ = *str;
						from.flen ++;
					} else
					if		(  *str  ==  '.'  ) {
						fPoint = TRUE;
					}
					str ++;
				}
				*p = 0;
				if		(  fMinus  ) {
					*buff |= 0x40;
				}
				FixedRescale(&ValueFixed(val),&from);
				rc = TRUE;
				break;
			  case	GL_TYPE_INT:
				ValueInteger(val) = StrToInt(str,slen);
				rc = TRUE;
				break;
			  case	GL_TYPE_FLOAT:
				ValueFloat(val) = atof(str);
				rc = TRUE;
				break;
			  case	GL_TYPE_BOOL:
				ValueBool(val) = ( toupper(*str) == 'T' ) ? TRUE : FALSE;
				rc = TRUE;
				break;
			  case	GL_TYPE_TIMESTAMP:
				ValueDateTimeYear(val) = StrToInt(str,4);		str += 4;
				ValueDateTimeMon(val) = StrToInt(str,2) - 1;	str += 2;
				ValueDateTimeMDay(val) = StrToInt(str,2);		str += 2;
				ValueDateTimeHour(val) = StrToInt(str,2);		str += 2;
				ValueDateTimeMin(val) = StrToInt(str,2);		str += 2;
				ValueDateTimeSec(val) = StrToInt(str,2);		str += 2;
				rc = mktime(&ValueDateTime(val)) >= 0 ? TRUE : FALSE;
				break;
			  case	GL_TYPE_DATE:
				ValueDateTimeYear(val) = StrToInt(str,4);		str += 4;
				ValueDateTimeMon(val) = StrToInt(str,2) - 1;	str += 2;
				ValueDateTimeMDay(val) = StrToInt(str,2);		str += 2;
				ValueDateTimeHour(val) = 0;
				ValueDateTimeMin(val) = 0;
				ValueDateTimeSec(val) = 0;
				rc = mktime(&ValueDateTime(val)) >= 0 ? TRUE : FALSE;
				break;
			  case	GL_TYPE_TIME:
				ValueDateTimeYear(val) = 0;
				ValueDateTimeMon(val) = 0;
				ValueDateTimeMDay(val) = 0;
				ValueDateTimeHour(val) = StrToInt(str,2);	str += 2;
				ValueDateTimeMin(val) = StrToInt(str,2);	str += 2;
				ValueDateTimeSec(val) = StrToInt(str,2);	str += 2;
				rc = TRUE;
				break;
			  default:
				rc = TRUE;
				break;
			}
			break;
		  default:
			ValueIsNil(val);
			rc = FALSE;	  
		}
	}
LEAVE_FUNC;
	return	(rc);
}
        void GetSequence(size_t sequenceIndex, std::vector<SequenceDataPtr>& result) override
        {
            const size_t innerSequenceIndex = m_deserializer.m_multiViewCrop ? sequenceIndex / ImageDeserializerBase::NumMultiViewCopies : sequenceIndex;
            const size_t copyId = m_deserializer.m_multiViewCrop ? sequenceIndex % ImageDeserializerBase::NumMultiViewCopies : 0;

            const auto& sequence = m_descriptor.m_sequences[innerSequenceIndex];
            const size_t offset = sequence.m_fileOffsetBytes - m_chunkOffset;

            // Let's parse the string
            char* next_token = nullptr;
            char* token = strtok_s(&m_buffer[0] + offset, "\t", &next_token);
            bool hasSequenceKey = m_deserializer.m_indexer->HasSequenceIds();
            if (hasSequenceKey) // Skip sequence key.
            {
                token = strtok_s(nullptr, "\t", &next_token);
                assert(!std::string(token).empty());
            }

            // Let's get the label.
            if (!token)
                RuntimeError("Empty label value for sequence '%s' in the input file '%ls'", KeyOf(sequence).c_str(), m_deserializer.m_fileName.c_str());

            char* eptr = nullptr;
            errno = 0;
            size_t classId = strtoull(token, &eptr, 10);
            if (token == eptr || errno == ERANGE)
                RuntimeError("Cannot parse label value for sequence '%s' in the input file '%ls'", KeyOf(sequence).c_str(), m_deserializer.m_fileName.c_str());

            size_t labelDimension = m_deserializer.m_labelGenerator->LabelDimension();
            if (classId >= labelDimension)
                RuntimeError(
                    "Image with id '%s' has invalid class id '%" PRIu64 "'. It is exceeding the label dimension of '%" PRIu64,
                    KeyOf(sequence).c_str(), classId, labelDimension);

            // Let's get the image.
            token = strtok_s(nullptr, "\n", &next_token);
            if (!token)
                RuntimeError("Empty image for sequence '%s'", KeyOf(sequence).c_str());

            // Find line end or end of buffer.
            char* endToken = strchr(token, 0);
            if (!endToken)
                RuntimeError("Cannot find the end of the image for sequence '%s' in the input file '%ls'", KeyOf(sequence).c_str(), m_deserializer.m_fileName.c_str());

            // Remove non base64 characters at the end of the string (tabs/spaces)
            while (endToken > token &&  !IsBase64Char(*(endToken - 1)))
                endToken--;

            std::vector<char> decodedImage;
            cv::Mat image;
            if (!DecodeBase64(token, endToken, decodedImage))
            {
                fprintf(stderr, "WARNING: Cannot decode sequence with id %" PRIu64 " in the input file '%ls'\n", sequence.m_key.m_sequence, m_deserializer.m_fileName.c_str());
            }
            else
            {
                image = cv::imdecode(decodedImage, m_deserializer.m_grayscale ? cv::IMREAD_GRAYSCALE : cv::IMREAD_COLOR);
            }

            m_deserializer.PopulateSequenceData(image, classId, copyId, result);
        }
        unsigned char *out = &ret[0];
        
        unsigned value = 0;
        for(std::size_t i=0;i<input.size();i++) {
            unsigned char d = decoding[static_cast<unsigned>(input[i])];
            if(d == 255)
                return ret_type();

            value = (value << 6) | d;
            if(i % 4 == 3) {
                *out++ = value >> 16;
                if(i > 0 && input[i - 1] != '=')
                    *out++ = value >> 8;
                if(input[i] != '=')
                    *out++ = value;
            }
        }
        
        ret.resize(out - &ret[0]);
        return ret;
    }

    void operator >> (const Node& node, Binary& binary)
    {
        std::string scalar;
        node.GetScalar(scalar);
        std::vector<unsigned char> data = DecodeBase64(scalar);
        binary.swap(data);
    }
}