summaryrefslogtreecommitdiffstats
path: root/dom/storage/DOMStorageDBUpdater.cpp
blob: 8e3f07d7ced8267d6acc5d0e8d9962fd3fcd1324 (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
/* -*- 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 "DOMStorageManager.h"

#include "mozIStorageBindingParamsArray.h"
#include "mozIStorageBindingParams.h"
#include "mozIStorageValueArray.h"
#include "mozIStorageFunction.h"
#include "mozilla/BasePrincipal.h"
#include "nsVariant.h"
#include "mozilla/Services.h"
#include "mozilla/Tokenizer.h"

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

namespace mozilla {
namespace dom {

extern void
ReverseString(const nsCSubstring& aSource, nsCSubstring& aResult);

namespace {

class nsReverseStringSQLFunction final : public mozIStorageFunction
{
  ~nsReverseStringSQLFunction() {}

  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.
    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 {
      PrincipalOriginAttributes attrs(appId, inIsolatedMozBrowser);
      attrs.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() {}

  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(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;
}

} // namespace

namespace DOMStorageDBUpdater {

nsresult CreateSchema1Tables(mozIStorageConnection *aWorkerConnection)
{
  nsresult rv;

  rv = aWorkerConnection->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
          "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(NS_LITERAL_CSTRING(
        "CREATE UNIQUE INDEX IF NOT EXISTS origin_key_index"
        " ON webappsstore2(originAttributes, originKey, key)"));
  NS_ENSURE_SUCCESS(rv, rv);

  return NS_OK;
}

nsresult Update(mozIStorageConnection *aWorkerConnection)
{
  nsresult rv;

  mozStorageTransaction transaction(aWorkerConnection, false);

  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(NS_LITERAL_CSTRING("scope_key_index"),
                                        &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 = aWorkerConnection->TableExists(NS_LITERAL_CSTRING("webappsstore2"),
                                        &webappsstore2Exists);
    NS_ENSURE_SUCCESS(rv, rv);
    rv = aWorkerConnection->TableExists(NS_LITERAL_CSTRING("webappsstore"),
                                        &webappsstoreExists);
    NS_ENSURE_SUCCESS(rv, rv);
    rv = aWorkerConnection->TableExists(NS_LITERAL_CSTRING("moz_webappsstore"),
                                        &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.

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

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

      break;
    }

    doVacuum = true;

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

    rv = aWorkerConnection->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
          "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(NS_LITERAL_CSTRING("REVERSESTRING"), 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(
        NS_LITERAL_CSTRING("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(
        NS_LITERAL_CSTRING("DROP TABLE webappsstore"));
      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(
        NS_LITERAL_CSTRING("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(
        NS_LITERAL_CSTRING("DROP TABLE moz_webappsstore"));
      NS_ENSURE_SUCCESS(rv, rv);
    }

    aWorkerConnection->RemoveFunction(NS_LITERAL_CSTRING("REVERSESTRING"));

    // 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(NS_LITERAL_CSTRING(
          "DROP INDEX IF EXISTS webappsstore2.origin_key_index"));
    NS_ENSURE_SUCCESS(rv, rv);

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

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

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

    nsCOMPtr<mozIStorageFunction> originKeyFunc(
      new GetOriginParticular(GetOriginParticular::ORIGIN_KEY));
    rv = aWorkerConnection->CreateFunction(NS_LITERAL_CSTRING("GET_ORIGIN_KEY"), 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(NS_LITERAL_CSTRING(
          "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(
      NS_LITERAL_CSTRING("DROP TABLE webappsstore2_old"));
    NS_ENSURE_SUCCESS(rv, rv);

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

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

    MOZ_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(
      NS_LITERAL_CSTRING("VACUUM"));
    NS_ENSURE_SUCCESS(rv, rv);
  }

  return NS_OK;
}

} // namespace DOMStorageDBUpdater
} // namespace dom
} // namespace mozilla