Storing arbitrary bytes in RocksDB - rocksdb

RocksDB states that it can store arbitrary data but the API only supports std::string types. I want to store std::vector<T> values and it appears if I want to do this then I must convert it into a std::string.
Is there a less brittle way to storing arbitrary types?

I tend to use the following to pack/unpack structures/classes to std::string using a template to automatically adjust to their size.
template <typename T>
std::string Pack(const T* data)
{
std::string d(sizeof(T), L'\0');
memcpy(&d[0], data, d.size());
return d;
}
template <typename T>
std::unique_ptr<T> Unpack(const std::string& data)
{
if (data.size() != sizeof(T))
return nullptr;
auto d = std::make_unique<T>();
memcpy(d.get(), data.data(), data.size());
return d;
}
So the following client code can pack and unpack a structure into the database:
// Test structure
BOB b = {};
b.a = 12;
b.b = 144;
b.c[0] = 's';
b.c[1] = '\0';
// Write to the db
status = pDb->Put(rocksdb::WriteOptions(), key, Pack(&b));
// Read from db with same key
std::string result;
status = pDb->Get(rocksdb::ReadOptions(), key, &result);
std::unique_ptr<BOB> pBob = Unpack<BOB>(result);
if (b.a == pBob->a && b.b == pBob->b && b.c[0] == pBob->c[0])
{
printf("Structure matches!\n");
}
else
{
printf("Structure doesn't match!\n");
}

As a key-value store, RocksDB can store "arbitrary byte array". For your use case, you would need to have some way to serialize your std::vector<T> to a byte array so that it can be put into a std::string. Note that the input std::string does not need to be zero-terminated.

Related

What tools in Qt are there to decode HTML 4 entities?

I have an input QString that has HTML 4 entities, like õ that I’d like to decode. But I can’t find any facilities in Qt to do so. Is there a way to do so in Qt? If possible I’d like to avoid QTextDocument so I don’t have to bring in QtGui.
The HTML 4 entities are listed in this link:
https://www.w3schools.com/charsets/ref_html_entities_4.asp
Out of curiosity, I have looked a bit around.
I found this SO: How can i convert entity character(Escape character) to HTML in QT?. However, it uses QTextDocument (which is part of GUI) what OP wants to prevent.
The doc. of QTextDocument::setHtml() doesn't mention anything specific whether something is used which could be accessed directly (and is even part of the Qt core). Hence, I had a look into source code. I started with QTextDocument::setHtml() on woboq.org and followed the bread crumbs.
Finally, I ended up in qtbase/src/gui/text/qtexthtmlparser.cpp:
QString QTextHtmlParser::parseEntity()
{
const int recover = pos;
int entityLen = 0;
QStringRef entity;
while (pos < len) {
QChar c = txt.at(pos++);
if (c.isSpace() || pos - recover > 9) {
goto error;
}
if (c == QLatin1Char(';'))
break;
++entityLen;
}
if (entityLen) {
entity = QStringRef(&txt, recover, entityLen);
QChar resolved = resolveEntity(entity);
if (!resolved.isNull())
return QString(resolved);
if (entityLen > 1 && entity.at(0) == QLatin1Char('#')) {
entity = entity.mid(1); // removing leading #
int base = 10;
bool ok = false;
if (entity.at(0).toLower() == QLatin1Char('x')) { // hex entity?
entity = entity.mid(1);
base = 16;
}
uint uc = entity.toUInt(&ok, base);
if (ok) {
if (uc >= 0x80 && uc < 0x80 + (sizeof(windowsLatin1ExtendedCharacters)/sizeof(windowsLatin1ExtendedCharacters[0])))
uc = windowsLatin1ExtendedCharacters[uc - 0x80];
QString str;
if (QChar::requiresSurrogates(uc)) {
str += QChar(QChar::highSurrogate(uc));
str += QChar(QChar::lowSurrogate(uc));
} else {
str = QChar(uc);
}
return str;
}
}
}
error:
pos = recover;
return QLatin1String("&");
}
A table of named entities can be found in the same source file:
static const struct QTextHtmlEntity { const char name[9]; quint16 code; } entities[]= {
{ "AElig", 0x00c6 },
{ "AMP", 38 },
...
{ "zwj", 0x200d },
{ "zwnj", 0x200c }
};
Q_STATIC_ASSERT(MAX_ENTITY == sizeof entities / sizeof *entities);
These are bad news for OP:
The API of the QTextHtmlParser is private:
//
// W A R N I N G
// -------------
//
// This file is not part of the Qt API. It exists purely as an
// implementation detail. This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//
and it's part of Qt GUI.
If OP insists to prevent GUI dependencies, the only other chance I see is to duplicate the code (or just to re-implement it from scratch).

How to decrypt data that is encrypted by OpenSSL with RSA_PKCS1_OAEP_PADDING using NCryptDecrypt?

I have difficulty to decrypt data being encrypted using OpenSSL and RSA_PKCS1_OAEP_PADDING padding option.
What I am doing is:
BCRYPT_ALG_HANDLE hCryptAlg = NULL;
BCRYPT_OAEP_PADDING_INFO paddingInfo = { 0 };
DWORD cbDecryptedMessage;
BYTE* pbDecryptedMessage = NULL;
paddingInfo.pszAlgId = BCRYPT_SHA1_ALGORITHM;
// Open an algorithm handle.
BCryptOpenAlgorithmProvider(&hCryptAlg, BCRYPT_RSA_ALGORITHM, NULL, 0);
// Calculate the required buffer
NCryptDecrypt(m_hKeyContextFull, (LPBYTE)pEncrypted, encryptedLenInBytes, &paddingInfo, NULL, cbDecryptedMessage, &outputDataLen, NCRYPT_PAD_OAEP_FLAG | NCRYPT_SILENT_FLAG);
// After required buffer is allocated...
NCryptDecrypt(m_hKeyContextFull, (LPBYTE)pEncrypted, encryptedLenInBytes, &paddingInfo, pbDecryptedMessage, cbDecryptedMessage, &outputDataLen, NCRYPT_PAD_OAEP_FLAG | NCRYPT_SILENT_FLAG);
It fails with NTE_INVALID_PARAMETER (0x80090027). I tried different flags but none of them works.
Note: m_hKeyContextFull has already been retrieved using CryptAcquireCertificatePrivateKey function call:
m_hSystemStore = CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, NULL, CERT_SYSTEM_STORE_LOCAL_MACHINE, m_storeName.c_str());
m_pCertWithKeys = CertFindCertificateInStore(m_hSystemStore, SupportedEncodings, 0, CERT_FIND_SUBJECT_STR, m_certName.c_str(), NULL);
// Obtain the private key from the certificate.
DWORD m_KeyContextSpec = 0;
HCRYPTPROV_OR_NCRYPT_KEY_HANDLE m_hKeyContextFull;
CryptAcquireCertificatePrivateKey(m_pCertWithKeys, CRYPT_ACQUIRE_SILENT_FLAG | CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG, NULL, &m_hKeyContextFull, &m_KeyContextSpec, &m_KeyContextMustBeReleased);
Note: All error checkings have been removed from code for readability.
Is there any idea what am I doing wrong?
Thanks.
I'd start by making paddingInfo valid:
BCRYPT_OAEP_PADDING_INFO paddingInfo;
paddingInfo.pszAlgId = BCRYPT_SHA1_ALGORITHM;
paddingInfo.pbLabel = NULL;
paddingInfo.cbLabel = 0;
The current standard has the empty string label (see RFC 3447).
Moreover, as to pbDecryptedMessage:
If this parameter is NULL, this function will calculate the size needed for the decrypted data and return the size in the location pointed to by the pcbResult parameter.
So it won't decrypt anyway. You need to allocate the buffer first to the right size; a lot of Windows API's work that way: first call it with output buffer NULL and you get back the needed size somehow, in this case in outputDataLen (which you should declare!). Then allocate the outbufbuffer to that size, and call the function again with the fresh buffer, and the correct length in cbDecryptedMessage. After use, free the buffer again of course. But your comment claims to have done so?
Another suspicious fact: You use NCryptDecrypt so the first argument, should
be a hKey of the right type, while m_hKeyContextFull does not seem to have that type. CryptAcquireCertificatePrivateKey will get you an old style key handle.
You cannot mix these different Windows CryptoAPI's.
Maybe look at the NcryptImportKey function, to transfer it.
I'm not familiar with the NCrypt series of interfaces, but we implemented something similar recently in a library using the BCrypt series of interfaces. Here is the function in question, which can be seen in greater context here.
In our case prvblbtyp is LEGACY_RSAPRIVATE_BLOB and prvblbbuf and prvblbblen are described here.
static
int
asymmetric_decrypt(
const wchar_t * const prvblbtyp,
const void * const prvblbbuf, const size_t prvblblen,
const void * const ctbuf, const size_t ctlen,
void ** const ptbuf, size_t * const ptlen)
{
BCRYPT_ALG_HANDLE halg;
int res;
res = INT_MIN;
if (BCryptOpenAlgorithmProvider(
&halg, BCRYPT_RSA_ALGORITHM, NULL, 0) == STATUS_SUCCESS) {
BCRYPT_KEY_HANDLE hkey;
if (BCryptImportKeyPair(
halg,
NULL, prvblbtyp, &hkey,
(void *)prvblbbuf, prvblblen,
0) == STATUS_SUCCESS) {
BCRYPT_OAEP_PADDING_INFO inf;
ULONG len;
inf.pszAlgId = BCRYPT_SHA1_ALGORITHM;
inf.pbLabel = NULL;
inf.cbLabel = 0;
/*
* decrypt first with a NULL output buffer.
* this returns the size necessary for the buffer.
*/
if (BCryptDecrypt(
hkey,
(void *)ctbuf, ctlen,
&inf,
NULL, 0,
NULL, 0, &len,
BCRYPT_PAD_OAEP) == STATUS_SUCCESS) {
void * buf;
/*
* allocate the required buffer
* and decrypt again
*/
res = -ENOMEM;
buf = malloc(len);
if (buf) {
res = INT_MIN;
if (BCryptDecrypt(
hkey,
(void *)ctbuf, ctlen,
&inf,
NULL, 0,
buf, len, &len,
BCRYPT_PAD_OAEP) == STATUS_SUCCESS) {
*ptbuf = buf;
*ptlen = len;
res = 0;
} else {
free(buf);
}
}
}
BCryptDestroyKey(hkey);
}
BCryptCloseAlgorithmProvider(halg, 0);
}
return res;
}

decrypt function at run time and use it QT c++

I'm new to QT and I'm trying to create an encrypted function.
Overall what you do in C / C ++ is:
Take pointer to function
make the function page rwx
Encrypt it (for the example I encrypt and decrypt in the same program)
Decrypt it and run it
A simple code in C will happen roughly like this:
void TestFunction()
{
printf("\nmsgbox test encrypted func\n");
}
// use this as a end label
void FunctionStub() { return; }
void XorBlock(DWORD dwStartAddress, DWORD dwSize)
{
char * addr = (char *)dwStartAddress;
for (int i = 0; i< dwSize; i++)
{
addr[i] ^= 0xff;
}
}
DWORD GetFuncSize(DWORD* Function, DWORD* StubFunction)
{
DWORD dwFunctionSize = 0, dwOldProtect;
DWORD *fnA = NULL, *fnB = NULL;
fnA = (DWORD *)Function;
fnB = (DWORD *)StubFunction;
dwFunctionSize = (fnB - fnA);
VirtualProtect(fnA, dwFunctionSize, PAGE_EXECUTE_READWRITE, &dwOldProtect); // make function page read write execute permission
return dwFunctionSize;
}
int main()
{
DWORD dwFuncSize = GetFuncSize((DWORD*)&TestFunction, (DWORD*)&FunctionStub);
printf("use func");
TestFunction();
XorBlock((DWORD)&TestFunction, dwFuncSize); // XOR encrypt the function
printf("after enc");
//TestFunction(); // If you try to run the encrypted function you will get Access Violation Exception.
XorBlock((DWORD)&TestFunction, dwFuncSize); // XOR decrypt the function
printf("after\n");
TestFunction(); // Fine here
getchar();
}
When I try to run such an example in QT I get a run time error.
Here is the code in QT:
void TestFunction()
{
QMessageBox::information(0, "Test", "msgbox test encrypted func");
}
void FunctionStub() { return; }
void XorBlock(DWORD dwStartAddress, DWORD dwSize)
{
char * addr = (char *)dwStartAddress;
for (int i = 0; i< dwSize; i++)
{
addr[i] ^= 0xff; // here i get seg. fault
}
}
DWORD GetFuncSize(DWORD* Function, DWORD* StubFunction)
{
DWORD dwFunctionSize = 0, dwOldProtect;
DWORD *fnA = NULL, *fnB = NULL;
fnA = (DWORD *)Function;
fnB = (DWORD *)StubFunction;
dwFunctionSize = (fnB - fnA);
VirtualProtect(fnA, dwFunctionSize, PAGE_EXECUTE_READWRITE, &dwOldProtect); // Need to modify our privileges to the memory
QMessageBox::information(0, "Test", "change func to read write execute ");
return dwFunctionSize;
}
void check_enc_function()
{
DWORD dwFuncSize = GetFuncSize((DWORD*)&TestFunction, (DWORD*)&FunctionStub);
QMessageBox::information(0, "Test", "use func");
TestFunction();
XorBlock((DWORD)&TestFunction, dwFuncSize); // XOR encrypt the function -> ### i get seg fault in here ###
QMessageBox::information(0, "Test", "after enc");
TestFunction(); // If you try to run the encrypted function you will get Access Violation Exception.
XorBlock((DWORD)&TestFunction, dwFuncSize); // XOR decrypt the function
QMessageBox::information(0, "Test", "after dec");
TestFunction(); // Fine here
getchar();
}
Why should this happen?
QT is supposed to behave like precision as standard C ++ ...
post Scriptum.
Interestingly in the same matter, what is the most legitimate way to keep an important function encrypted (the reason it is encrypted is DRM)?
Legitimately I mean that anti-viruses will not mistakenly mark me as a virus because I defend myself.
PS2
If I pass an encrypted function over the network (say, I will build a server client schema that the client asks for the function it needs to run from the server and the server sends it to it if it is approved) How can I arrange the symbols so that the function does not collapse?
PS3
How in QT can I turn off the DEP and ASLR defenses? (In my opinion so that I can execute PS 2. I have to cancel them)
Thanks
yoko
The example is undefined behaviour on my system.
The first and main issue in your code is:
void TestFunction() { /* ... */ }
void FunctionStub() { return; }
You assume that the compiler will put FunctionStub after TestFunction without any padding. I compiled your example and FunctionStub in my case was above TestFunction which resulted in a negative dwFunctionSize.
dwFunctionSize = (fnB - fnA);
TestFunction located at # 0xa11d90
FunctionStub located at # 0xa11b50
dwFunctionSize = -0x240
Also in XorBlock
addr[i] ^= 0xff;
Is doing nothing.
I assume you want to write in XorBlock to the memory location to XOR the entire TestFunction.
You could do something like this:
void XorBlock(DWORD dwStartAddress, DWORD dwSize)
{
DWORD dwEndAddress = dwStartAddress + dwSize;
for(DWORD i = dwStartAddress; i < dwEndAddress; i++) {
// ...
}
}
I can't see any Qt-specific in your example. Even if it's Qt function call it's just a call. So I guess you have undefined behaviour in both examples but only second one crashes.
I can't see any reason for compiler and linker to keep function order. For example GCC let you specify the code section for each function. So you can reorder it in executable without reordering in cpp.
I think you need some compiler specific things to make it work.

How to implement clipboard actions for custom mime-types?

I am trying to implement copy/cut/paste in a complex application.
I have a QGraphicsScene that can contain QGraphicsItem subtypes of varied subtypes, fairly complex (with Item as a second parent storing custom properties).
I would copy/cut selected items, and paste them back in place.
I already have implemented it using a local version: a list of items.
void copyItemsActionOld()
{
foreach(QGraphicsItem* qItem, selectedItems())
{
Item* newItem = (dynamic_cast<Item*>(qItem))->createItemCopy();
m_itemClipboard.append(newItem);
}
}
On paste, I make a copy of all items in clipboard and add them to the scene. So simple.....
BUT
I need to implement it using the global system clipboard.
I saw that creating a custom mime type is as simple as calling setData on a QMimeData object, after I make up a format name... (I hope that is true)
static const QString _mimeType("application/myItem");
void copyItemsAction()
{
QMimeData* _mimeData = new QMimeData;
2 QByteArray _itemData = ?????;
_mimeData->setData(_mimeType, _itemData);
QClipboard* _clipboard = QApplication::clipboard();
_clipboard->clear();
_clipboard->setMimeData(_mimeData);
}
void pasteItemsAction()
{
QClipboard* _clipboard = QApplication::clipboard();
const QMimeData* _mimeData = _clipboard->mimeData();
QStringList _formats = _mimeData->formats();
foreach (QString _format, _formats)
{
if (_format == _mimeType)
{
QByteArray _itemData = _mimeData->data(_mimeType);
3 // then do what ? How do I parse it ?
}
}
}
My questions
1) Are the above fragments for copyItemsAction and pasteItemsAction anywhere close to how clipboard actions should work ?
2) How can I put item data in the QByteArray ?
3) How do I parse the data in QByteArray ?
4) Do I need to register the custom mime-type anywhere else ? (other than what I just did in my two functions); and will it be multi-platform ?
I have already implemented save and load functionality for all items. Something like...
void Item::saveItem(QDataStream &outFile)
{
outFile << type;
outFile << width;
outFile << color.name();
}
Can I use this to place the items data in the QByteArray ? (How ?)
I was on the right track, and I kept adding code to my question until I found how to make it work:
static const QString _mimeType("application/myItem");
void copyItemsAction()
{
QByteArray _itemData;
QDataStream outData(&_itemData, QIODevice::WriteOnly);
outData << selectedItems().size();
foreach(QGraphicsItem* qItem, selectedItems())
{
Item* item = dynamic_cast<Item*>(qItem);
item->saveItem(outData);
}
QMimeData* _mimeData = new QMimeData;
_mimeData->setData(_mimeType, _itemData);
_mimeData->setText("My Items");
QClipboard* _clipboard = QApplication::clipboard();
_clipboard->clear();
_clipboard->setMimeData(_mimeData);
}
void pasteItemsAction()
{
QClipboard* _clipboard = QApplication::clipboard();
const QMimeData* _mimeData = _clipboard->mimeData();
QStringList _formats = _mimeData->formats();
foreach (QString _format, _formats)
{
if (_format == _mimeType)
{
QByteArray _itemData = _mimeData->data(_mimeType);
QDataStream inData(&_itemData, QIODevice::ReadOnly);
int itemsSize;
inData >> itemsSize;
for (int i = 0; i < itemsSize; ++i)
{
Item* item = ...
item->loadItem(inData);
}
}
}
}
So, for question 1, yes I was on the right track;
For questions 2 and 3 - I was able to use a QDataStream to serialize info to/from the QByteArray.
If there is a better / more effective / faster way, I would love to know...
For question 4 - it seems that I can use just about any string, if all I want is to copy/paste within a single instance of my application.
It is also true if I want to use it between multiple applications, multiple instances of my application, or for drag-and-drop - on most platforms. (It does not seem to work between multiple applications/instances in the embedded platform I target.)
Caveat - it fails frequently when another clipboard using application is open, in windows.

sqlite3_exec without callback

Is there any way by which I can get the sqlite3_exec() result without through callback?
When I do search I want to get the result directly, most like a return of the function or as OUT param?
Thanks.
I have written some code that allows us to read data from open db (db) according to sql query (zSql) without callback.
Please note, that this code works but might still need some work (for example, I'm not sure if we need to free the text data or not...)
int RunSqlNoCallback(sqlite3 * db, const char * zSql)
{
sqlite3_stmt *stmt = NULL;
int rc = sqlite3_prepare_v2(db, zSql, -1, &stmt, NULL);
if (rc != SQLITE_OK)
return rc;
int rowCount = 0;
rc = sqlite3_step(stmt);
while (rc != SQLITE_DONE && rc != SQLITE_OK)
{
rowCount++;
int colCount = sqlite3_column_count(stmt);
for (int colIndex = 0; colIndex < colCount; colIndex++)
{
int type = sqlite3_column_type(stmt, colIndex);
const char * columnName = sqlite3_column_name(stmt, colIndex);
if (type == SQLITE_INTEGER)
{
int valInt = sqlite3_column_int(stmt, colIndex);
printf("columnName = %s, Integer val = %d", columnName, valInt);
}
else if (type == SQLITE_FLOAT)
{
double valDouble = sqlite3_column_double(stmt, colIndex);
printf("columnName = %s,Double val = %f", columnName, valDouble);
}
else if (type == SQLITE_TEXT)
{
const unsigned char * valChar = sqlite3_column_text(stmt, colIndex);
printf("columnName = %s,Text val = %s", columnName, valChar);
free(valChar);
}
else if (type == SQLITE_BLOB)
{
printf("columnName = %s,BLOB", columnName);
}
else if (type == SQLITE_NULL)
{
printf("columnName = %s,NULL", columnName);
}
}
printf("Line %d, rowCount = %d", rowCount, colCount);
rc = sqlite3_step(stmt);
}
rc = sqlite3_finalize(stmt);
return rc;
}
sqlite3_exec is a convenience wrapper.
If you don't need a callback you should use underlying functions: sqlite3_prepare_v2(), sqlite3_step(), and sqlite3_finalize() directly.
Compile sql query with sqlite3_prepare_v2()
Run sqlite3_step() as many times as necessary to execute the query, use
sqlite3_column_bytes() etc to retrieve the data
Destroy prepared query with sqlite3_finalize()
But it requires more coding and careful error handling.
Calling the callback is how sqlite3_exec is designed to work.
If you want a function that allocates all the memory for the result and returns that, you need a different function, like sqlite3_get_table.
The call back is the mechanism that sqlite3_exec () uses to return one or more results. It looks like its primary use is with a select SQL statement. If the select SQL statement returns multiple rows of results then the call back function specified is called by the sqlite functionality for each row.
I am not sure if you are using C or C++ or some other language however I have a possible solution for you using C with SQLite.
The call back function has as its first argument a void pointer and this can point to pretty much anything. For instance it can point to a struct that contains a pointer to a memory area allocated for the result along with parameters indicating the size of the memory area.
I put an answer to this stackoverflow question, use of sql3_exec, with an example of using a call back that populates a C struct with the results of a select SQL statement. In this example I have a call back that takes one or more row results from a select and transform the results into the data values to put into a C struct. When the sqlite3_exec() function returns, I then process the results from the select using the C struct.
This may be what you are looking for in that you can create your select SQL statement, set up the results struct, call sqlite3_exec() specifying the results struct along with the function pointer to the call back to process the results using the results struct, and when sqlite3_exec() return you have the results of your select. The results of the select will be at the point where you called sqlite3_exec().

Resources