1
0
mirror of https://github.com/qTox/qTox.git synced 2024-03-22 14:00:36 +08:00

fix(history): Prevent invalid history access

* When the DB schema was too new we were accessing history anyways. This
has potential to just completely corrupt the DB
* When history was disabled there was a chance we would attempt to write
to history anyways. Added more checks in this area
* Chatform was accessing invalid iterators when there were no displayed
messages. Added a guard for this case
This commit is contained in:
Mick Sayson 2019-09-13 17:38:52 -07:00 committed by Anthony Bilinski
parent 9fa6a4996d
commit e3e6e1d9c4
No known key found for this signature in database
GPG Key ID: 2AA8E0DA1B31FB3C
3 changed files with 81 additions and 28 deletions

View File

@ -195,10 +195,11 @@ bool dbSchema3to4(RawDatabase& db)
/** /**
* @brief Upgrade the db schema * @brief Upgrade the db schema
* @return True if the schema upgrade succeded, false otherwise
* @note On future alterations of the database all you have to do is bump the SCHEMA_VERSION * @note On future alterations of the database all you have to do is bump the SCHEMA_VERSION
* variable and add another case to the switch statement below. Make sure to fall through on each case. * variable and add another case to the switch statement below. Make sure to fall through on each case.
*/ */
void dbSchemaUpgrade(std::shared_ptr<RawDatabase>& db) bool dbSchemaUpgrade(std::shared_ptr<RawDatabase>& db)
{ {
int64_t databaseSchemaVersion; int64_t databaseSchemaVersion;
@ -206,19 +207,17 @@ void dbSchemaUpgrade(std::shared_ptr<RawDatabase>& db)
databaseSchemaVersion = row[0].toLongLong(); databaseSchemaVersion = row[0].toLongLong();
}))) { }))) {
qCritical() << "History failed to read user_version"; qCritical() << "History failed to read user_version";
db.reset(); return false;
return;
} }
if (databaseSchemaVersion > SCHEMA_VERSION) { if (databaseSchemaVersion > SCHEMA_VERSION) {
qWarning().nospace() << "Database version (" << databaseSchemaVersion << qWarning().nospace() << "Database version (" << databaseSchemaVersion <<
") is newer than we currently support (" << SCHEMA_VERSION << "). Please upgrade qTox"; ") is newer than we currently support (" << SCHEMA_VERSION << "). Please upgrade qTox";
// We don't know what future versions have done, we have to disable db access until we re-upgrade // We don't know what future versions have done, we have to disable db access until we re-upgrade
db.reset(); return false;
return;
} else if (databaseSchemaVersion == SCHEMA_VERSION) { } else if (databaseSchemaVersion == SCHEMA_VERSION) {
// No work to do // No work to do
return; return true;
} }
switch (databaseSchemaVersion) { switch (databaseSchemaVersion) {
@ -231,22 +230,19 @@ void dbSchemaUpgrade(std::shared_ptr<RawDatabase>& db)
const bool newDb = isNewDb(db, success); const bool newDb = isNewDb(db, success);
if (!success) { if (!success) {
qCritical() << "Failed to create current db schema"; qCritical() << "Failed to create current db schema";
db.reset(); return false;
return;
} }
if (newDb) { if (newDb) {
if (!createCurrentSchema(*db)) { if (!createCurrentSchema(*db)) {
qCritical() << "Failed to create current db schema"; qCritical() << "Failed to create current db schema";
db.reset(); return false;
return;
} }
qDebug() << "Database created at schema version" << SCHEMA_VERSION; qDebug() << "Database created at schema version" << SCHEMA_VERSION;
break; // new db is the only case where we don't incrementally upgrade through each version break; // new db is the only case where we don't incrementally upgrade through each version
} else { } else {
if (!dbSchema0to1(*db)) { if (!dbSchema0to1(*db)) {
qCritical() << "Failed to upgrade db to schema version 1, aborting"; qCritical() << "Failed to upgrade db to schema version 1, aborting";
db.reset(); return false;
return;
} }
qDebug() << "Database upgraded incrementally to schema version 1"; qDebug() << "Database upgraded incrementally to schema version 1";
} }
@ -255,23 +251,20 @@ void dbSchemaUpgrade(std::shared_ptr<RawDatabase>& db)
case 1: case 1:
if (!dbSchema1to2(*db)) { if (!dbSchema1to2(*db)) {
qCritical() << "Failed to upgrade db to schema version 2, aborting"; qCritical() << "Failed to upgrade db to schema version 2, aborting";
db.reset(); return false;
return;
} }
qDebug() << "Database upgraded incrementally to schema version 2"; qDebug() << "Database upgraded incrementally to schema version 2";
//fallthrough //fallthrough
case 2: case 2:
if (!dbSchema2to3(*db)) { if (!dbSchema2to3(*db)) {
qCritical() << "Failed to upgrade db to schema version 3, aborting"; qCritical() << "Failed to upgrade db to schema version 3, aborting";
db.reset(); return false;
return;
} }
qDebug() << "Database upgraded incrementally to schema version 3"; qDebug() << "Database upgraded incrementally to schema version 3";
case 3: case 3:
if (!dbSchema3to4(*db)) { if (!dbSchema3to4(*db)) {
qCritical() << "Failed to upgrade db to schema version 4, aborting"; qCritical() << "Failed to upgrade db to schema version 4, aborting";
db.reset(); return false;
return;
} }
qDebug() << "Database upgraded incrementally to schema version 4"; qDebug() << "Database upgraded incrementally to schema version 4";
// etc. // etc.
@ -279,6 +272,8 @@ void dbSchemaUpgrade(std::shared_ptr<RawDatabase>& db)
qInfo() << "Database upgrade finished (databaseSchemaVersion" << databaseSchemaVersion qInfo() << "Database upgrade finished (databaseSchemaVersion" << databaseSchemaVersion
<< "->" << SCHEMA_VERSION << ")"; << "->" << SCHEMA_VERSION << ")";
} }
return true;
} }
MessageState getMessageState(bool isPending, bool isBroken) MessageState getMessageState(bool isPending, bool isBroken)
@ -318,18 +313,19 @@ FileDbInsertionData::FileDbInsertionData()
* @brief Prepares the database to work with the history. * @brief Prepares the database to work with the history.
* @param db This database will be prepared for use with the history. * @param db This database will be prepared for use with the history.
*/ */
History::History(std::shared_ptr<RawDatabase> db) History::History(std::shared_ptr<RawDatabase> db_)
: db(db) : db(db_)
{ {
if (!isValid()) { if (!isValid()) {
qWarning() << "Database not open, init failed"; qWarning() << "Database not open, init failed";
return; return;
} }
dbSchemaUpgrade(db); const auto upgradeSucceeded = dbSchemaUpgrade(db);
// dbSchemaUpgrade may have put us in an invalid state // dbSchemaUpgrade may have put us in an invalid state
if (!isValid()) { if (!upgradeSucceeded) {
db.reset();
return; return;
} }
@ -370,6 +366,10 @@ bool History::isValid()
*/ */
bool History::historyExists(const ToxPk& friendPk) bool History::historyExists(const ToxPk& friendPk)
{ {
if (historyAccessBlocked()) {
return false;
}
return !getMessagesForFriend(friendPk, 0, 1).empty(); return !getMessagesForFriend(friendPk, 0, 1).empty();
} }
@ -588,6 +588,10 @@ void History::addNewFileMessage(const QString& friendPk, const QString& fileId,
const QString& fileName, const QString& filePath, int64_t size, const QString& fileName, const QString& filePath, int64_t size,
const QString& sender, const QDateTime& time, QString const& dispName) const QString& sender, const QDateTime& time, QString const& dispName)
{ {
if (historyAccessBlocked()) {
return;
}
// This is an incredibly far from an optimal way of implementing this, // This is an incredibly far from an optimal way of implementing this,
// but given the frequency that people are going to be initiating a file // but given the frequency that people are going to be initiating a file
// transfer we can probably live with it. // transfer we can probably live with it.
@ -644,11 +648,7 @@ void History::addNewMessage(const QString& friendPk, const QString& message, con
const QDateTime& time, bool isDelivered, QString dispName, const QDateTime& time, bool isDelivered, QString dispName,
const std::function<void(RowId)>& insertIdCallback) const std::function<void(RowId)>& insertIdCallback)
{ {
if (!Settings::getInstance().getEnableLogging()) { if (historyAccessBlocked()) {
qWarning() << "Blocked a message from being added to database while history is disabled";
return;
}
if (!isValid()) {
return; return;
} }
@ -659,6 +659,10 @@ void History::addNewMessage(const QString& friendPk, const QString& message, con
void History::setFileFinished(const QString& fileId, bool success, const QString& filePath, void History::setFileFinished(const QString& fileId, bool success, const QString& filePath,
const QByteArray& fileHash) const QByteArray& fileHash)
{ {
if (historyAccessBlocked()) {
return;
}
auto& fileInfo = fileInfos[fileId]; auto& fileInfo = fileInfos[fileId];
if (fileInfo.fileId.get() == -1) { if (fileInfo.fileId.get() == -1) {
fileInfo.finished = true; fileInfo.finished = true;
@ -674,11 +678,19 @@ void History::setFileFinished(const QString& fileId, bool success, const QString
size_t History::getNumMessagesForFriend(const ToxPk& friendPk) size_t History::getNumMessagesForFriend(const ToxPk& friendPk)
{ {
if (historyAccessBlocked()) {
return 0;
}
return getNumMessagesForFriendBeforeDate(friendPk, QDateTime()); return getNumMessagesForFriendBeforeDate(friendPk, QDateTime());
} }
size_t History::getNumMessagesForFriendBeforeDate(const ToxPk& friendPk, const QDateTime& date) size_t History::getNumMessagesForFriendBeforeDate(const ToxPk& friendPk, const QDateTime& date)
{ {
if (historyAccessBlocked()) {
return 0;
}
QString queryText = QString("SELECT COUNT(history.id) " QString queryText = QString("SELECT COUNT(history.id) "
"FROM history " "FROM history "
"JOIN peers chat ON chat_id = chat.id " "JOIN peers chat ON chat_id = chat.id "
@ -704,6 +716,10 @@ size_t History::getNumMessagesForFriendBeforeDate(const ToxPk& friendPk, const Q
QList<History::HistMessage> History::getMessagesForFriend(const ToxPk& friendPk, size_t firstIdx, QList<History::HistMessage> History::getMessagesForFriend(const ToxPk& friendPk, size_t firstIdx,
size_t lastIdx) size_t lastIdx)
{ {
if (historyAccessBlocked()) {
return {};
}
QList<HistMessage> messages; QList<HistMessage> messages;
// Don't forget to update the rowCallback if you change the selected columns! // Don't forget to update the rowCallback if you change the selected columns!
@ -763,6 +779,10 @@ QList<History::HistMessage> History::getMessagesForFriend(const ToxPk& friendPk,
QList<History::HistMessage> History::getUndeliveredMessagesForFriend(const ToxPk& friendPk) QList<History::HistMessage> History::getUndeliveredMessagesForFriend(const ToxPk& friendPk)
{ {
if (historyAccessBlocked()) {
return {};
}
auto queryText = auto queryText =
QString("SELECT history.id, faux_offline_pending.id, timestamp, chat.public_key, " QString("SELECT history.id, faux_offline_pending.id, timestamp, chat.public_key, "
"aliases.display_name, sender.public_key, message, broken_messages.id " "aliases.display_name, sender.public_key, message, broken_messages.id "
@ -809,6 +829,10 @@ QList<History::HistMessage> History::getUndeliveredMessagesForFriend(const ToxPk
QDateTime History::getDateWhereFindPhrase(const QString& friendPk, const QDateTime& from, QDateTime History::getDateWhereFindPhrase(const QString& friendPk, const QDateTime& from,
QString phrase, const ParameterSearch& parameter) QString phrase, const ParameterSearch& parameter)
{ {
if (historyAccessBlocked()) {
return QDateTime();
}
QDateTime result; QDateTime result;
auto rowCallback = [&result](const QVector<QVariant>& row) { auto rowCallback = [&result](const QVector<QVariant>& row) {
result = QDateTime::fromMSecsSinceEpoch(row[0].toLongLong()); result = QDateTime::fromMSecsSinceEpoch(row[0].toLongLong());
@ -903,6 +927,10 @@ QList<History::DateIdx> History::getNumMessagesForFriendBeforeDateBoundaries(con
const QDate& from, const QDate& from,
size_t maxNum) size_t maxNum)
{ {
if (historyAccessBlocked()) {
return {};
}
auto friendPkString = friendPk.toString(); auto friendPkString = friendPk.toString();
// No guarantee that this is the most efficient way to do this... // No guarantee that this is the most efficient way to do this...
@ -954,9 +982,29 @@ QList<History::DateIdx> History::getNumMessagesForFriendBeforeDateBoundaries(con
*/ */
void History::markAsDelivered(RowId messageId) void History::markAsDelivered(RowId messageId)
{ {
if (!isValid()) { if (historyAccessBlocked()) {
return; return;
} }
db->execLater(QString("DELETE FROM faux_offline_pending WHERE id=%1;").arg(messageId.get())); db->execLater(QString("DELETE FROM faux_offline_pending WHERE id=%1;").arg(messageId.get()));
} }
/**
* @brief Determines if history access should be blocked
* @return True if history should not be accessed
*/
bool History::historyAccessBlocked()
{
if (!Settings::getInstance().getEnableLogging()) {
assert(false);
qCritical() << "Blocked history access while history is disabled";
return true;
}
if (!isValid()) {
return true;
}
return false;
}

View File

@ -201,6 +201,7 @@ private slots:
void onFileInserted(RowId dbId, QString fileId); void onFileInserted(RowId dbId, QString fileId);
private: private:
bool historyAccessBlocked();
static RawDatabase::Query generateFileFinished(RowId fileId, bool success, static RawDatabase::Query generateFileFinished(RowId fileId, bool success,
const QString& filePath, const QByteArray& fileHash); const QString& filePath, const QByteArray& fileHash);
std::shared_ptr<RawDatabase> db; std::shared_ptr<RawDatabase> db;

View File

@ -983,6 +983,10 @@ void GenericChatForm::searchInBegin(const QString& phrase, const ParameterSearch
return; return;
} }
if (messages.size() == 0) {
return;
}
if (chatLog.getNextIdx().get() == messages.rbegin()->first.get() + 1) { if (chatLog.getNextIdx().get() == messages.rbegin()->first.get() + 1) {
disableSearchText(); disableSearchText();
} else { } else {