summaryrefslogtreecommitdiffstats
path: root/dom/storage/StorageDBUpdater.cpp
blob: 255deddb4d465a52dfd289a6330fb1697f586969 (plain)
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "LocalStorageManager.h"
#include "StorageUtils.h"

#include "mozIStorageBindingParams.h"
#include "mozIStorageValueArray.h"
#include "mozIStorageFunction.h"
#include "mozilla/BasePrincipal.h"
#include "nsVariant.h"
#include "mozilla/Tokenizer.h"
#include "mozIStorageConnection.h"
#include "mozStorageHelper.h"
#include "mozilla/StorageOriginAttributes.h"

// Current version of the database schema
#define CURRENT_SCHEMA_VERSION 2

namespace mozilla::dom {

using namespace StorageUtils;

namespace {

class nsReverseStringSQLFunction final : public mozIStorageFunction {
  ~nsReverseStringSQLFunction() = default;

  NS_DECL_ISUPPORTS
  NS_DECL_MOZISTORAGEFUNCTION
};

NS_IMPL_ISUPPORTS(nsReverseStringSQLFunction, mozIStorageFunction)

NS_IMETHODIMP
nsReverseStringSQLFunction::OnFunctionCall(
    mozIStorageValueArray* aFunctionArguments, nsIVariant** aResult) {
  nsresult rv;

  nsAutoCString stringToReverse;
  rv = aFunctionArguments->GetUTF8String(0, stringToReverse);
  NS_ENSURE_SUCCESS(rv, rv);

  nsAutoCString result;
  ReverseString(stringToReverse, result);

  RefPtr<nsVariant> outVar(new nsVariant());
  rv = outVar->SetAsAUTF8String(result);
  NS_ENSURE_SUCCESS(rv, rv);

  outVar.forget(aResult);
  return NS_OK;
}

// "scope" to "origin attributes suffix" and "origin key" convertor

class ExtractOriginData : protected mozilla::Tokenizer {
 public:
  ExtractOriginData(const nsACString& scope, nsACString& suffix,
                    nsACString& origin)
      : mozilla::Tokenizer(scope) {
    using mozilla::OriginAttributes;

    // Parse optional appId:isInIsolatedMozBrowserElement: string, in case
    // we don't find it, the scope is our new origin key and suffix
    // is empty.
    suffix.Truncate();
    origin.Assign(scope);

    // Bail out if it isn't appId.
    // AppId doesn't exist any more but we could have old storage data...
    uint32_t appId;
    if (!ReadInteger(&appId)) {
      return;
    }

    // Should be followed by a colon.
    if (!CheckChar(':')) {
      return;
    }

    // Bail out if it isn't 'isolatedBrowserFlag'.
    nsDependentCSubstring isolatedBrowserFlag;
    if (!ReadWord(isolatedBrowserFlag)) {
      return;
    }

    bool inIsolatedMozBrowser = isolatedBrowserFlag == "t";
    bool notInIsolatedBrowser = isolatedBrowserFlag == "f";
    if (!inIsolatedMozBrowser && !notInIsolatedBrowser) {
      return;
    }

    // Should be followed by a colon.
    if (!CheckChar(':')) {
      return;
    }

    // OK, we have found appId and inIsolatedMozBrowser flag, create the suffix
    // from it and take the rest as the origin key.

    // If the profile went through schema 1 -> schema 0 -> schema 1 switching
    // we may have stored the full attributes origin suffix when there were
    // more than just appId and inIsolatedMozBrowser set on storage principal's
    // OriginAttributes.
    //
    // To preserve full uniqueness we store this suffix to the scope key.
    // Schema 0 code will just ignore it while keeping the scoping unique.
    //
    // The whole scope string is in one of the following forms (when we are
    // here):
    //
    // "1001:f:^appId=1001&inBrowser=false&addonId=101:gro.allizom.rxd.:https:443"
    // "1001:f:gro.allizom.rxd.:https:443"
    //         |
    //         +- the parser cursor position.
    //
    // If there is '^', the full origin attributes suffix follows.  We search
    // for ':' since it is the delimiter used in the scope string and is never
    // contained in the origin attributes suffix.  Remaining string after
    // the comma is the reversed-domain+schema+port tuple.
    Record();
    if (CheckChar('^')) {
      Token t;
      while (Next(t)) {
        if (t.Equals(Token::Char(':'))) {
          Claim(suffix);
          break;
        }
      }
    } else {
      StorageOriginAttributes originAttributes(inIsolatedMozBrowser);
      originAttributes.CreateSuffix(suffix);
    }

    // Consume the rest of the input as "origin".
    origin.Assign(Substring(mCursor, mEnd));
  }
};

class GetOriginParticular final : public mozIStorageFunction {
 public:
  enum EParticular { ORIGIN_ATTRIBUTES_SUFFIX, ORIGIN_KEY };

  explicit GetOriginParticular(EParticular aParticular)
      : mParticular(aParticular) {}

 private:
  GetOriginParticular() = delete;
  ~GetOriginParticular() = default;

  EParticular mParticular;

  NS_DECL_ISUPPORTS
  NS_DECL_MOZISTORAGEFUNCTION
};

NS_IMPL_ISUPPORTS(GetOriginParticular, mozIStorageFunction)

NS_IMETHODIMP
GetOriginParticular::OnFunctionCall(mozIStorageValueArray* aFunctionArguments,
                                    nsIVariant** aResult) {
  nsresult rv;

  nsAutoCString scope;
  rv = aFunctionArguments->GetUTF8String(0, scope);
  NS_ENSURE_SUCCESS(rv, rv);

  nsAutoCString suffix, origin;
  ExtractOriginData extractor(scope, suffix, origin);

  nsCOMPtr<nsIWritableVariant> outVar(new nsVariant());

  switch (mParticular) {
    case EParticular::ORIGIN_ATTRIBUTES_SUFFIX:
      rv = outVar->SetAsAUTF8String(suffix);
      break;
    case EParticular::ORIGIN_KEY:
      rv = outVar->SetAsAUTF8String(origin);
      break;
  }

  NS_ENSURE_SUCCESS(rv, rv);

  outVar.forget(aResult);
  return NS_OK;
}

class StripOriginAddonId final : public mozIStorageFunction {
 public:
  explicit StripOriginAddonId() = default;

 private:
  ~StripOriginAddonId() = default;

  NS_DECL_ISUPPORTS
  NS_DECL_MOZISTORAGEFUNCTION
};

NS_IMPL_ISUPPORTS(StripOriginAddonId, mozIStorageFunction)

NS_IMETHODIMP
StripOriginAddonId::OnFunctionCall(mozIStorageValueArray* aFunctionArguments,
                                   nsIVariant** aResult) {
  nsresult rv;

  nsAutoCString suffix;
  rv = aFunctionArguments->GetUTF8String(0, suffix);
  NS_ENSURE_SUCCESS(rv, rv);

  // Deserialize and re-serialize to automatically drop any obsolete origin
  // attributes.
  OriginAttributes oa;
  bool ok = oa.PopulateFromSuffix(suffix);
  NS_ENSURE_TRUE(ok, NS_ERROR_FAILURE);

  nsAutoCString newSuffix;
  oa.CreateSuffix(newSuffix);

  nsCOMPtr<nsIWritableVariant> outVar = new nsVariant();
  rv = outVar->SetAsAUTF8String(newSuffix);
  NS_ENSURE_SUCCESS(rv, rv);

  outVar.forget(aResult);
  return NS_OK;
}

nsresult CreateSchema1Tables(mozIStorageConnection* aWorkerConnection) {
  nsresult rv;

  rv = aWorkerConnection->ExecuteSimpleSQL(nsLiteralCString(
      "CREATE TABLE IF NOT EXISTS webappsstore2 ("
      "originAttributes TEXT, "
      "originKey TEXT, "
      "scope TEXT, "  // Only for schema0 downgrade compatibility
      "key TEXT, "
      "value TEXT)"));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = aWorkerConnection->ExecuteSimpleSQL(
      nsLiteralCString("CREATE UNIQUE INDEX IF NOT EXISTS origin_key_index"
                       " ON webappsstore2(originAttributes, originKey, key)"));
  NS_ENSURE_SUCCESS(rv, rv);

  return NS_OK;
}

nsresult TablesExist(mozIStorageConnection* aWorkerConnection,
                     bool* aWebappsstore2Exists, bool* aWebappsstoreExists,
                     bool* aMoz_webappsstoreExists) {
  nsresult rv =
      aWorkerConnection->TableExists("webappsstore2"_ns, aWebappsstore2Exists);
  NS_ENSURE_SUCCESS(rv, rv);
  rv = aWorkerConnection->TableExists("webappsstore"_ns, aWebappsstoreExists);
  NS_ENSURE_SUCCESS(rv, rv);
  rv = aWorkerConnection->TableExists("moz_webappsstore"_ns,
                                      aMoz_webappsstoreExists);
  NS_ENSURE_SUCCESS(rv, rv);

  return NS_OK;
}

nsresult CreateCurrentSchemaOnEmptyTableInternal(
    mozIStorageConnection* aWorkerConnection) {
  nsresult rv = CreateSchema1Tables(aWorkerConnection);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = aWorkerConnection->SetSchemaVersion(CURRENT_SCHEMA_VERSION);
  NS_ENSURE_SUCCESS(rv, rv);

  return NS_OK;
}

}  // namespace

namespace StorageDBUpdater {

nsresult CreateCurrentSchema(mozIStorageConnection* aConnection) {
  mozStorageTransaction transaction(aConnection, false);

  nsresult rv = transaction.Start();
  NS_ENSURE_SUCCESS(rv, rv);

#ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
  {
    int32_t schemaVer;
    nsresult rv = aConnection->GetSchemaVersion(&schemaVer);
    NS_ENSURE_SUCCESS(rv, rv);

    MOZ_DIAGNOSTIC_ASSERT(0 == schemaVer);

    bool webappsstore2Exists, webappsstoreExists, moz_webappsstoreExists;
    rv = TablesExist(aConnection, &webappsstore2Exists, &webappsstoreExists,
                     &moz_webappsstoreExists);
    NS_ENSURE_SUCCESS(rv, rv);

    MOZ_DIAGNOSTIC_ASSERT(!webappsstore2Exists && !webappsstoreExists &&
                          !moz_webappsstoreExists);
  }
#endif

  rv = CreateCurrentSchemaOnEmptyTableInternal(aConnection);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = transaction.Commit();
  NS_ENSURE_SUCCESS(rv, rv);

  return NS_OK;
}

nsresult Update(mozIStorageConnection* aWorkerConnection) {
  mozStorageTransaction transaction(aWorkerConnection, false);

  nsresult rv = transaction.Start();
  NS_ENSURE_SUCCESS(rv, rv);

  bool doVacuum = false;

  int32_t schemaVer;
  rv = aWorkerConnection->GetSchemaVersion(&schemaVer);
  NS_ENSURE_SUCCESS(rv, rv);

  // downgrade (v0) -> upgrade (v1+) specific code
  if (schemaVer >= 1) {
    bool schema0IndexExists;
    rv = aWorkerConnection->IndexExists("scope_key_index"_ns,
                                        &schema0IndexExists);
    NS_ENSURE_SUCCESS(rv, rv);

    if (schema0IndexExists) {
      // If this index exists, the database (already updated to schema >1)
      // has been run again on schema 0 code.  That recreated that index
      // and might store some new rows while updating only the 'scope' column.
      // For such added rows we must fill the new 'origin*' columns correctly
      // otherwise there would be a data loss.  The safest way to do it is to
      // simply run the whole update to schema 1 again.
      schemaVer = 0;
    }
  }

  switch (schemaVer) {
    case 0: {
      bool webappsstore2Exists, webappsstoreExists, moz_webappsstoreExists;
      rv = TablesExist(aWorkerConnection, &webappsstore2Exists,
                       &webappsstoreExists, &moz_webappsstoreExists);
      NS_ENSURE_SUCCESS(rv, rv);

      if (!webappsstore2Exists && !webappsstoreExists &&
          !moz_webappsstoreExists) {
        // The database is empty, this is the first start.  Just create the
        // schema table and break to the next version to update to, i.e. bypass
        // update from the old version.

        // XXX What does "break to the next version to update to" mean here? It
        // seems to refer to the 'break' statement below, but that breaks out of
        // the 'switch' statement and continues with committing the transaction.
        // Either this is wrong, or the comment above is misleading.

        rv = CreateCurrentSchemaOnEmptyTableInternal(aWorkerConnection);
        NS_ENSURE_SUCCESS(rv, rv);

        break;
      }

      doVacuum = true;

      // Ensure Gecko 1.9.1 storage table
      rv = aWorkerConnection->ExecuteSimpleSQL(
          nsLiteralCString("CREATE TABLE IF NOT EXISTS webappsstore2 ("
                           "scope TEXT, "
                           "key TEXT, "
                           "value TEXT, "
                           "secure INTEGER, "
                           "owner TEXT)"));
      NS_ENSURE_SUCCESS(rv, rv);

      rv = aWorkerConnection->ExecuteSimpleSQL(
          nsLiteralCString("CREATE UNIQUE INDEX IF NOT EXISTS scope_key_index"
                           " ON webappsstore2(scope, key)"));
      NS_ENSURE_SUCCESS(rv, rv);

      nsCOMPtr<mozIStorageFunction> function1(new nsReverseStringSQLFunction());
      NS_ENSURE_TRUE(function1, NS_ERROR_OUT_OF_MEMORY);

      rv = aWorkerConnection->CreateFunction("REVERSESTRING"_ns, 1, function1);
      NS_ENSURE_SUCCESS(rv, rv);

      // Check if there is storage of Gecko 1.9.0 and if so, upgrade that
      // storage to actual webappsstore2 table and drop the obsolete table.
      // First process this newer table upgrade to priority potential duplicates
      // from older storage table.
      if (webappsstoreExists) {
        rv = aWorkerConnection->ExecuteSimpleSQL(nsLiteralCString(
            "INSERT OR IGNORE INTO "
            "webappsstore2(scope, key, value, secure, owner) "
            "SELECT REVERSESTRING(domain) || '.:', key, value, secure, owner "
            "FROM webappsstore"));
        NS_ENSURE_SUCCESS(rv, rv);

        rv = aWorkerConnection->ExecuteSimpleSQL("DROP TABLE webappsstore"_ns);
        NS_ENSURE_SUCCESS(rv, rv);
      }

      // Check if there is storage of Gecko 1.8 and if so, upgrade that storage
      // to actual webappsstore2 table and drop the obsolete table. Potential
      // duplicates will be ignored.
      if (moz_webappsstoreExists) {
        rv = aWorkerConnection->ExecuteSimpleSQL(nsLiteralCString(
            "INSERT OR IGNORE INTO "
            "webappsstore2(scope, key, value, secure, owner) "
            "SELECT REVERSESTRING(domain) || '.:', key, value, secure, domain "
            "FROM moz_webappsstore"));
        NS_ENSURE_SUCCESS(rv, rv);

        rv = aWorkerConnection->ExecuteSimpleSQL(
            "DROP TABLE moz_webappsstore"_ns);
        NS_ENSURE_SUCCESS(rv, rv);
      }

      aWorkerConnection->RemoveFunction("REVERSESTRING"_ns);

      // Update the scoping to match the new implememntation: split to oa suffix
      // and origin key First rename the old table, we want to remove some
      // columns no longer needed, but even before that drop all indexes from it
      // (CREATE IF NOT EXISTS for index on the new table would falsely find the
      // index!)
      rv = aWorkerConnection->ExecuteSimpleSQL(nsLiteralCString(
          "DROP INDEX IF EXISTS webappsstore2.origin_key_index"));
      NS_ENSURE_SUCCESS(rv, rv);

      rv = aWorkerConnection->ExecuteSimpleSQL(nsLiteralCString(
          "DROP INDEX IF EXISTS webappsstore2.scope_key_index"));
      NS_ENSURE_SUCCESS(rv, rv);

      rv = aWorkerConnection->ExecuteSimpleSQL(nsLiteralCString(
          "ALTER TABLE webappsstore2 RENAME TO webappsstore2_old"));
      NS_ENSURE_SUCCESS(rv, rv);

      nsCOMPtr<mozIStorageFunction> oaSuffixFunc(new GetOriginParticular(
          GetOriginParticular::ORIGIN_ATTRIBUTES_SUFFIX));
      rv = aWorkerConnection->CreateFunction("GET_ORIGIN_SUFFIX"_ns, 1,
                                             oaSuffixFunc);
      NS_ENSURE_SUCCESS(rv, rv);

      nsCOMPtr<mozIStorageFunction> originKeyFunc(
          new GetOriginParticular(GetOriginParticular::ORIGIN_KEY));
      rv = aWorkerConnection->CreateFunction("GET_ORIGIN_KEY"_ns, 1,
                                             originKeyFunc);
      NS_ENSURE_SUCCESS(rv, rv);

      // Here we ensure this schema tables when we are updating.
      rv = CreateSchema1Tables(aWorkerConnection);
      NS_ENSURE_SUCCESS(rv, rv);

      rv = aWorkerConnection->ExecuteSimpleSQL(nsLiteralCString(
          "INSERT OR IGNORE INTO "
          "webappsstore2 (originAttributes, originKey, scope, key, value) "
          "SELECT GET_ORIGIN_SUFFIX(scope), GET_ORIGIN_KEY(scope), scope, key, "
          "value "
          "FROM webappsstore2_old"));
      NS_ENSURE_SUCCESS(rv, rv);

      rv = aWorkerConnection->ExecuteSimpleSQL(
          "DROP TABLE webappsstore2_old"_ns);
      NS_ENSURE_SUCCESS(rv, rv);

      aWorkerConnection->RemoveFunction("GET_ORIGIN_SUFFIX"_ns);
      aWorkerConnection->RemoveFunction("GET_ORIGIN_KEY"_ns);

      rv = aWorkerConnection->SetSchemaVersion(1);
      NS_ENSURE_SUCCESS(rv, rv);

      [[fallthrough]];
    }
    case 1: {
      nsCOMPtr<mozIStorageFunction> oaStripAddonId(new StripOriginAddonId());
      rv = aWorkerConnection->CreateFunction("STRIP_ADDON_ID"_ns, 1,
                                             oaStripAddonId);
      NS_ENSURE_SUCCESS(rv, rv);

      rv = aWorkerConnection->ExecuteSimpleSQL(nsLiteralCString(
          "UPDATE webappsstore2 "
          "SET originAttributes = STRIP_ADDON_ID(originAttributes) "
          "WHERE originAttributes LIKE '^%'"));
      NS_ENSURE_SUCCESS(rv, rv);

      aWorkerConnection->RemoveFunction("STRIP_ADDON_ID"_ns);

      rv = aWorkerConnection->SetSchemaVersion(2);
      NS_ENSURE_SUCCESS(rv, rv);

      [[fallthrough]];
    }
    case CURRENT_SCHEMA_VERSION:
      // Ensure the tables and indexes are up.  This is mostly a no-op
      // in common scenarios.
      rv = CreateSchema1Tables(aWorkerConnection);
      NS_ENSURE_SUCCESS(rv, rv);

      // Nothing more to do here, this is the current schema version
      break;

    default:
      MOZ_ASSERT(false);
      break;
  }  // switch

  rv = transaction.Commit();
  NS_ENSURE_SUCCESS(rv, rv);

  if (doVacuum) {
    // In some cases this can make the disk file of the database significantly
    // smaller.  VACUUM cannot be executed inside a transaction.
    rv = aWorkerConnection->ExecuteSimpleSQL("VACUUM"_ns);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  return NS_OK;
}

}  // namespace StorageDBUpdater
}  // namespace mozilla::dom