File: DatabaseUtilities.cpp

package info (click to toggle)
webkit2gtk 2.42.2-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 362,452 kB
  • sloc: cpp: 2,881,971; javascript: 282,447; ansic: 134,088; python: 43,789; ruby: 18,308; perl: 15,872; asm: 14,389; xml: 4,395; yacc: 2,350; sh: 2,074; java: 1,734; lex: 1,323; makefile: 288; pascal: 60
file content (347 lines) | stat: -rw-r--r-- 17,472 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
/*
 * Copyright (C) 2021 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "DatabaseUtilities.h"

#include "Logging.h"
#include "PrivateClickMeasurementManager.h"
#include <WebCore/PrivateClickMeasurement.h>
#include <WebCore/SQLiteStatement.h>
#include <WebCore/SQLiteStatementAutoResetScope.h>
#include <wtf/FileSystem.h>
#include <wtf/RunLoop.h>

namespace WebKit {

DatabaseUtilities::DatabaseUtilities(String&& storageFilePath)
    : m_storageFilePath(WTFMove(storageFilePath))
    , m_transaction(m_database)
{
    ASSERT(!RunLoop::isMain());
}

DatabaseUtilities::~DatabaseUtilities()
{
    ASSERT(!RunLoop::isMain());
}

WebCore::SQLiteStatementAutoResetScope DatabaseUtilities::scopedStatement(std::unique_ptr<WebCore::SQLiteStatement>& statement, ASCIILiteral query, ASCIILiteral logString) const
{
    ASSERT(!RunLoop::isMain());
    if (!statement) {
        auto statementOrError = m_database.prepareHeapStatement(query);
        if (!statementOrError) {
            RELEASE_LOG_ERROR(PrivateClickMeasurement, "%p - DatabaseUtilities::%s failed to prepare statement, error message: %" PUBLIC_LOG_STRING, this, logString.characters(), m_database.lastErrorMsg());
            return WebCore::SQLiteStatementAutoResetScope { };
        }
        statement = statementOrError.value().moveToUniquePtr();
        ASSERT(m_database.isOpen());
    }
    return WebCore::SQLiteStatementAutoResetScope { statement.get() };
}

ScopeExit<Function<void()>> DatabaseUtilities::beginTransactionIfNecessary()
{
    ASSERT(!RunLoop::isMain());
    if (m_transaction.inProgress())
        return makeScopeExit(Function<void()> { [] { } });

    m_transaction.begin();
    return makeScopeExit(Function<void()> { [this] {
        m_transaction.commit();
    } });
}

auto DatabaseUtilities::openDatabaseAndCreateSchemaIfNecessary() -> CreatedNewFile
{
    ASSERT(!RunLoop::isMain());
    CreatedNewFile createdNewFile = CreatedNewFile::No;
    if (!FileSystem::fileExists(m_storageFilePath)) {
        if (!FileSystem::makeAllDirectories(FileSystem::parentPath(m_storageFilePath))) {
            RELEASE_LOG_ERROR(PrivateClickMeasurement, "%p - DatabaseUtilities::open failed, error message: Failed to create directory database path: %" PUBLIC_LOG_STRING, this, m_storageFilePath.utf8().data());
            return createdNewFile;
        }
        createdNewFile = CreatedNewFile::Yes;
    }

    if (!m_database.open(m_storageFilePath, WebCore::SQLiteDatabase::OpenMode::ReadWriteCreate, WebCore::SQLiteDatabase::OpenOptions::CanSuspendWhileLocked)) {
        RELEASE_LOG_ERROR(PrivateClickMeasurement, "%p - DatabaseUtilities::open failed, error message: %" PUBLIC_LOG_STRING ", database path: %" PUBLIC_LOG_STRING, this, m_database.lastErrorMsg(), m_storageFilePath.utf8().data());
        return createdNewFile;
    }
    
    // Since we are using a workerQueue, the sequential dispatch blocks may be called by different threads.
    m_database.disableThreadingChecks();

    auto setBusyTimeout = m_database.prepareStatement("PRAGMA busy_timeout = 5000"_s);
    if (!setBusyTimeout || setBusyTimeout->step() != SQLITE_ROW) {
        RELEASE_LOG_ERROR(PrivateClickMeasurement, "%p - DatabaseUtilities::setBusyTimeout failed, error message: %" PRIVATE_LOG_STRING, this, m_database.lastErrorMsg());
    }

    if (createdNewFile == CreatedNewFile::Yes) {
        if (!createSchema()) {
            RELEASE_LOG_ERROR(PrivateClickMeasurement, "%p - DatabaseUtilities::createSchema failed, error message: %" PUBLIC_LOG_STRING ", database path: %" PUBLIC_LOG_STRING, this, m_database.lastErrorMsg(), m_storageFilePath.utf8().data());
        }
    }
    return createdNewFile;
}

void DatabaseUtilities::enableForeignKeys()
{
    auto enableForeignKeys = m_database.prepareStatement("PRAGMA foreign_keys = ON"_s);
    if (!enableForeignKeys || enableForeignKeys->step() != SQLITE_DONE) {
        RELEASE_LOG_ERROR(PrivateClickMeasurement, "%p - DatabaseUtilities::enableForeignKeys failed, error message: %" PRIVATE_LOG_STRING, this, m_database.lastErrorMsg());
    }
}

void DatabaseUtilities::close()
{
    ASSERT(!RunLoop::isMain());
    destroyStatements();
    if (m_database.isOpen())
        m_database.close();
}

void DatabaseUtilities::interrupt()
{
    ASSERT(!RunLoop::isMain());
    if (m_database.isOpen())
        m_database.interrupt();
}

WebCore::PrivateClickMeasurement DatabaseUtilities::buildPrivateClickMeasurementFromDatabase(WebCore::SQLiteStatement& statement, PrivateClickMeasurementAttributionType attributionType) const
{
    ASSERT(!RunLoop::isMain());
    auto sourceSiteDomain = getDomainStringFromDomainID(statement.columnInt(0));
    auto destinationSiteDomain = getDomainStringFromDomainID(statement.columnInt(1));
    auto sourceID = statement.columnInt(2);
    auto timeOfAdClick = attributionType == PrivateClickMeasurementAttributionType::Attributed ? statement.columnDouble(5) : statement.columnDouble(3);
    auto token = attributionType == PrivateClickMeasurementAttributionType::Attributed ? statement.columnText(7) : statement.columnText(4);
    auto signature = attributionType == PrivateClickMeasurementAttributionType::Attributed ? statement.columnText(8) : statement.columnText(5);
    auto keyID = attributionType == PrivateClickMeasurementAttributionType::Attributed ? statement.columnText(9) : statement.columnText(6);
    auto bundleID = attributionType == PrivateClickMeasurementAttributionType::Attributed ? statement.columnText(11) : statement.columnText(7);

    // Safari was the only application that used PCM when it was stored with ResourceLoadStatistics.
#if PLATFORM(MAC)
    constexpr auto safariBundleID = "com.apple.Safari"_s;
#else
    constexpr auto safariBundleID = "com.apple.mobilesafari"_s;
#endif
    if (bundleID.isEmpty())
        bundleID = safariBundleID;

    WebCore::PrivateClickMeasurement attribution(WebCore::PrivateClickMeasurement::SourceID(sourceID), WebCore::PCM::SourceSite(WebCore::RegistrableDomain::uncheckedCreateFromRegistrableDomainString(sourceSiteDomain)), WebCore::PCM::AttributionDestinationSite(WebCore::RegistrableDomain::uncheckedCreateFromRegistrableDomainString(destinationSiteDomain)), bundleID, WallTime::fromRawSeconds(timeOfAdClick), WebCore::PCM::AttributionEphemeral::No);

    // These indices are zero-based: https://www.sqlite.org/c3ref/column_blob.html "The leftmost column of the result set has the index 0".
    if (attributionType == PrivateClickMeasurementAttributionType::Attributed) {
        auto attributionTriggerData = statement.columnInt(3);
        auto priority = statement.columnInt(4);
        auto sourceEarliestTimeToSendValue = statement.columnDouble(6);
        auto destinationEarliestTimeToSendValue = statement.columnDouble(10);
        auto destinationToken = statement.columnText(12);
        auto destinationSignature = statement.columnText(13);
        auto destinationKeyID = statement.columnText(14);

        if (attributionTriggerData != -1)
            attribution.setAttribution(WebCore::PCM::AttributionTriggerData { static_cast<uint8_t>(attributionTriggerData), WebCore::PCM::AttributionTriggerData::Priority::PriorityValue(priority), { }, { }, { }, { }, { }, { } });

        WebCore::PCM::DestinationSecretToken destinationSecretToken;
        destinationSecretToken.tokenBase64URL = destinationToken;
        destinationSecretToken.signatureBase64URL = destinationSignature;
        destinationSecretToken.keyIDBase64URL = destinationKeyID;

        attribution.setDestinationSecretToken(WTFMove(destinationSecretToken));

        std::optional<WallTime> sourceEarliestTimeToSend;
        std::optional<WallTime> destinationEarliestTimeToSend;

        // A value of 0.0 indicates that the report has been sent to the respective site.
        if (sourceEarliestTimeToSendValue > 0.0)
            sourceEarliestTimeToSend = WallTime::fromRawSeconds(sourceEarliestTimeToSendValue);

        if (destinationEarliestTimeToSendValue > 0.0)
            destinationEarliestTimeToSend = WallTime::fromRawSeconds(destinationEarliestTimeToSendValue);

        attribution.setTimesToSend({ sourceEarliestTimeToSend, destinationEarliestTimeToSend });
    }

    WebCore::PCM::SourceSecretToken sourceSecretToken;
    sourceSecretToken.tokenBase64URL = token;
    sourceSecretToken.signatureBase64URL = signature;
    sourceSecretToken.keyIDBase64URL = keyID;

    attribution.setSourceSecretToken(WTFMove(sourceSecretToken));

    return attribution;
}

String DatabaseUtilities::stripIndexQueryToMatchStoredValue(const char* originalQuery)
{
    return makeStringByReplacingAll(String::fromLatin1(originalQuery), "CREATE UNIQUE INDEX IF NOT EXISTS"_s, "CREATE UNIQUE INDEX"_s);
}

TableAndIndexPair DatabaseUtilities::currentTableAndIndexQueries(const String& tableName)
{
    auto getTableStatement = m_database.prepareStatement("SELECT sql FROM sqlite_master WHERE tbl_name=? AND type = 'table'"_s);
    if (!getTableStatement) {
        RELEASE_LOG_ERROR(PrivateClickMeasurement, "%p - DatabaseUtilities::currentTableAndIndexQueries Unable to prepare statement to fetch schema for the table, error message: %" PRIVATE_LOG_STRING, this, m_database.lastErrorMsg());
        return { };
    }

    if (getTableStatement->bindText(1, tableName) != SQLITE_OK) {
        RELEASE_LOG_ERROR(PrivateClickMeasurement, "%p - DatabaseUtilities::currentTableAndIndexQueries Unable to bind statement to fetch schema for the table, error message: %" PRIVATE_LOG_STRING, this, m_database.lastErrorMsg());
        return { };
    }

    if (getTableStatement->step() != SQLITE_ROW) {
        RELEASE_LOG_ERROR(PrivateClickMeasurement, "%p - DatabaseUtilities::currentTableAndIndexQueries error executing statement to fetch table schema, error message: %" PRIVATE_LOG_STRING, this, m_database.lastErrorMsg());
        return { };
    }

    String createTableQuery = getTableStatement->columnText(0);

    auto getIndexStatement = m_database.prepareStatement("SELECT sql FROM sqlite_master WHERE tbl_name=? AND type = 'index'"_s);
    if (!getIndexStatement) {
        RELEASE_LOG_ERROR(PrivateClickMeasurement, "%p - DatabaseUtilities::currentTableAndIndexQueries Unable to prepare statement to fetch index for the table, error message: %" PRIVATE_LOG_STRING, this, m_database.lastErrorMsg());
        return { };
    }

    if (getIndexStatement->bindText(1, tableName) != SQLITE_OK) {
        RELEASE_LOG_ERROR(PrivateClickMeasurement, "%p - DatabaseUtilities::currentTableAndIndexQueries Unable to bind statement to fetch index for the table, error message: %" PRIVATE_LOG_STRING, this, m_database.lastErrorMsg());
        return { };
    }

    std::optional<String> index;
    if (getIndexStatement->step() == SQLITE_ROW) {
        auto rawIndex = String(getIndexStatement->columnText(0));
        if (!rawIndex.isEmpty())
            index = rawIndex;
    }

    return std::make_pair<String, std::optional<String>>(WTFMove(createTableQuery), WTFMove(index));
}

static Expected<WebCore::SQLiteStatement, int> insertDistinctValuesInTableStatement(WebCore::SQLiteDatabase& database, const String& table)
{
    if (table == "SubframeUnderTopFrameDomains"_s)
        return database.prepareStatement("INSERT INTO SubframeUnderTopFrameDomains SELECT subFrameDomainID, MAX(lastUpdated), topFrameDomainID FROM _SubframeUnderTopFrameDomains GROUP BY subFrameDomainID, topFrameDomainID"_s);

    if (table == "SubresourceUnderTopFrameDomains"_s)
        return database.prepareStatement("INSERT INTO SubresourceUnderTopFrameDomains SELECT subresourceDomainID, MAX(lastUpdated), topFrameDomainID FROM _SubresourceUnderTopFrameDomains GROUP BY subresourceDomainID, topFrameDomainID"_s);

    if (table == "SubresourceUniqueRedirectsTo"_s)
        return database.prepareStatement("INSERT INTO SubresourceUniqueRedirectsTo SELECT subresourceDomainID, MAX(lastUpdated), toDomainID FROM _SubresourceUniqueRedirectsTo GROUP BY subresourceDomainID, toDomainID"_s);

    if (table == "TopFrameLinkDecorationsFrom"_s)
        return database.prepareStatement("INSERT INTO TopFrameLinkDecorationsFrom SELECT toDomainID, MAX(lastUpdated), fromDomainID FROM _TopFrameLinkDecorationsFrom GROUP BY toDomainID, fromDomainID"_s);

    return database.prepareStatementSlow(makeString("INSERT INTO ", table, " SELECT DISTINCT * FROM _", table));
}

void DatabaseUtilities::migrateDataToNewTablesIfNecessary()
{
    ASSERT(!RunLoop::isMain());
    if (!needsUpdatedSchema())
        return;

    WebCore::SQLiteTransaction transaction(m_database);
    transaction.begin();

    for (auto& table : expectedTableAndIndexQueries().keys()) {
        auto alterTable = m_database.prepareStatementSlow(makeString("ALTER TABLE ", table, " RENAME TO _", table));
        if (!alterTable || alterTable->step() != SQLITE_DONE) {
            RELEASE_LOG_ERROR(PrivateClickMeasurement, "%p - DatabaseUtilities::migrateDataToNewTablesIfNecessary failed to rename table, error message: %s", this, m_database.lastErrorMsg());
            transaction.rollback();
            return;
        }
    }

    if (!createSchema()) {
        transaction.rollback();
        return;
    }

    // Maintain the order of tables to make sure the ObservedDomains table is created first. Other tables have foreign key constraints referencing it.
    for (auto& table : sortedTables()) {
        auto migrateTableData = insertDistinctValuesInTableStatement(m_database, table);
        if (!migrateTableData || migrateTableData->step() != SQLITE_DONE) {
            transaction.rollback();
            RELEASE_LOG_ERROR(PrivateClickMeasurement, "%p - DatabaseUtilities::migrateDataToNewTablesIfNecessary (table %s) failed to migrate schema, error message: %s", this, table.characters(), m_database.lastErrorMsg());
            return;
        }
    }

    // Drop all tables at the end to avoid trashing data that references data in other tables.
    for (auto& table : sortedTables()) {
        auto dropTableQuery = m_database.prepareStatementSlow(makeString("DROP TABLE _", table));
        if (!dropTableQuery || dropTableQuery->step() != SQLITE_DONE) {
            transaction.rollback();
            RELEASE_LOG_ERROR(PrivateClickMeasurement, "%p - DatabaseUtilities::migrateDataToNewTablesIfNecessary failed to drop temporary tables, error message: %s", this, m_database.lastErrorMsg());
            return;
        }
    }

    if (!createUniqueIndices()) {
        RELEASE_LOG_ERROR(PrivateClickMeasurement, "%p - DatabaseUtilities::migrateDataToNewTablesIfNecessary failed to create unique indices, error message: %s", this, m_database.lastErrorMsg());
        transaction.rollback();
        return;
    }

    transaction.commit();
}

Vector<String> DatabaseUtilities::columnsForTable(ASCIILiteral tableName)
{
    auto statement = m_database.prepareStatementSlow(makeString("PRAGMA table_info(", tableName, ")"));

    if (!statement) {
        RELEASE_LOG_ERROR(PrivateClickMeasurement, "%p - Database::columnsForTable Unable to prepare statement to fetch schema for table, error message: %" PRIVATE_LOG_STRING, this, m_database.lastErrorMsg());
        return { };
    }

    Vector<String> columns;
    while (statement->step() == SQLITE_ROW) {
        auto name = statement->columnText(1);
        columns.append(name);
    }

    return columns;
}

bool DatabaseUtilities::addMissingColumnToTable(ASCIILiteral tableName, ASCIILiteral columnName)
{
    auto statement = m_database.prepareStatementSlow(makeString("ALTER TABLE ", tableName, " ADD COLUMN ", columnName));
    if (!statement) {
        RELEASE_LOG_ERROR(PrivateClickMeasurement, "%p - Database::addMissingColumnToTable Unable to prepare statement to add missing columns to table, error message: %" PRIVATE_LOG_STRING, this, m_database.lastErrorMsg());
        return false;
    }
    if (statement->step() != SQLITE_DONE) {
        RELEASE_LOG_ERROR(PrivateClickMeasurement, "%p - Database::addMissingColumnToTable error executing statement to add missing columns to table, error message: %" PRIVATE_LOG_STRING, this, m_database.lastErrorMsg());
        return false;
    }
    return true;
}

} // namespace WebKit