summaryrefslogtreecommitdiffstats
path: root/dom/fs/parent/datamodel/FileSystemFileManager.cpp
blob: c43ee67ae5ef247e3ea1bb36fa7fa79f53ccaba4 (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
/* -*- 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 "FileSystemFileManager.h"

#include "FileSystemDataManager.h"
#include "FileSystemHashSource.h"
#include "mozilla/Assertions.h"
#include "mozilla/NotNull.h"
#include "mozilla/Result.h"
#include "mozilla/ResultVariant.h"
#include "mozilla/Unused.h"
#include "mozilla/dom/quota/QuotaManager.h"
#include "mozilla/dom/quota/ResultExtensions.h"
#include "nsCOMPtr.h"
#include "nsHashKeys.h"
#include "nsIFile.h"
#include "nsIFileProtocolHandler.h"
#include "nsIFileURL.h"
#include "nsIURIMutator.h"
#include "nsTHashMap.h"
#include "nsXPCOM.h"

namespace mozilla::dom::fs::data {

namespace {

constexpr nsLiteralString kDatabaseFileName = u"metadata.sqlite"_ns;

Result<nsCOMPtr<nsIFile>, QMResult> GetFileDestination(
    const nsCOMPtr<nsIFile>& aTopDirectory, const EntryId& aEntryId) {
  MOZ_ASSERT(32u == aEntryId.Length());

  nsCOMPtr<nsIFile> destination;

  // nsIFile Clone is not a constant method
  QM_TRY(QM_TO_RESULT(aTopDirectory->Clone(getter_AddRefs(destination))));

  QM_TRY_UNWRAP(Name encoded, FileSystemHashSource::EncodeHash(aEntryId));

  MOZ_ALWAYS_TRUE(IsAscii(encoded));

  nsString relativePath;
  relativePath.Append(Substring(encoded, 0, 2));

  QM_TRY(QM_TO_RESULT(destination->AppendRelativePath(relativePath)));

  QM_TRY(QM_TO_RESULT(destination->AppendRelativePath(encoded)));

  return destination;
}

Result<nsCOMPtr<nsIFile>, QMResult> GetOrCreateFileImpl(
    const nsAString& aFilePath) {
  MOZ_ASSERT(!aFilePath.IsEmpty());

  nsCOMPtr<nsIFile> result;
  QM_TRY(QM_TO_RESULT(NS_NewLocalFile(aFilePath,
                                      /* aFollowLinks */ false,
                                      getter_AddRefs(result))));

  bool exists = true;
  QM_TRY(QM_TO_RESULT(result->Exists(&exists)));

  if (!exists) {
    QM_TRY(QM_TO_RESULT(result->Create(nsIFile::NORMAL_FILE_TYPE, 0644)));

    return result;
  }

  bool isDirectory = true;
  QM_TRY(QM_TO_RESULT(result->IsDirectory(&isDirectory)));
  QM_TRY(OkIf(!isDirectory), Err(QMResult(NS_ERROR_FILE_IS_DIRECTORY)));

  return result;
}

Result<nsCOMPtr<nsIFile>, QMResult> GetFile(
    const nsCOMPtr<nsIFile>& aTopDirectory, const EntryId& aEntryId) {
  MOZ_ASSERT(!aEntryId.IsEmpty());

  QM_TRY_UNWRAP(nsCOMPtr<nsIFile> pathObject,
                GetFileDestination(aTopDirectory, aEntryId));

  nsString desiredPath;
  QM_TRY(QM_TO_RESULT(pathObject->GetPath(desiredPath)));

  nsCOMPtr<nsIFile> result;
  QM_TRY(QM_TO_RESULT(NS_NewLocalFile(desiredPath,
                                      /* aFollowLinks */ false,
                                      getter_AddRefs(result))));

  return result;
}

Result<nsCOMPtr<nsIFile>, QMResult> GetOrCreateFile(
    const nsCOMPtr<nsIFile>& aTopDirectory, const EntryId& aEntryId) {
  MOZ_ASSERT(!aEntryId.IsEmpty());

  QM_TRY_UNWRAP(nsCOMPtr<nsIFile> pathObject,
                GetFileDestination(aTopDirectory, aEntryId));

  nsString desiredPath;
  QM_TRY(QM_TO_RESULT(pathObject->GetPath(desiredPath)));

  QM_TRY_UNWRAP(nsCOMPtr<nsIFile> result, GetOrCreateFileImpl(desiredPath));

  return result;
}

nsresult RemoveFileObject(const nsCOMPtr<nsIFile>& aFilePtr) {
  // If we cannot tell whether the object is file or directory, or it is a
  // directory, it is abandoned as an unknown object. If an attempt is made to
  // create a new object with the same path on disk, we regenerate the entryId
  // until the collision is resolved.

  bool isFile = false;
  QM_TRY(MOZ_TO_RESULT(aFilePtr->IsFile(&isFile)));

  QM_TRY(OkIf(isFile), NS_ERROR_FILE_IS_DIRECTORY);

  QM_TRY(QM_TO_RESULT(aFilePtr->Remove(/* recursive */ false)));

  return NS_OK;
}

#ifdef DEBUG
// Unused in release builds
Result<Usage, QMResult> GetFileSize(const nsCOMPtr<nsIFile>& aFileObject) {
  bool exists = false;
  QM_TRY(QM_TO_RESULT(aFileObject->Exists(&exists)));

  if (!exists) {
    return 0;
  }

  bool isFile = false;
  QM_TRY(QM_TO_RESULT(aFileObject->IsFile(&isFile)));

  // We never create directories with this path: this is an unknown object
  // and the file does not exist
  QM_TRY(OkIf(isFile), 0);

  QM_TRY_UNWRAP(Usage fileSize,
                QM_TO_RESULT_INVOKE_MEMBER(aFileObject, GetFileSize));

  return fileSize;
}
#endif

}  // namespace

Result<nsCOMPtr<nsIFile>, QMResult> GetFileSystemDirectory(
    const quota::OriginMetadata& aOriginMetadata) {
  MOZ_ASSERT(aOriginMetadata.mPersistenceType ==
             quota::PERSISTENCE_TYPE_DEFAULT);

  quota::QuotaManager* quotaManager = quota::QuotaManager::Get();
  MOZ_ASSERT(quotaManager);

  QM_TRY_UNWRAP(nsCOMPtr<nsIFile> fileSystemDirectory,
                QM_TO_RESULT_TRANSFORM(
                    quotaManager->GetOriginDirectory(aOriginMetadata)));

  QM_TRY(QM_TO_RESULT(fileSystemDirectory->AppendRelativePath(
      NS_LITERAL_STRING_FROM_CSTRING(FILESYSTEM_DIRECTORY_NAME))));

  return fileSystemDirectory;
}

nsresult EnsureFileSystemDirectory(
    const quota::OriginMetadata& aOriginMetadata) {
  quota::QuotaManager* quotaManager = quota::QuotaManager::Get();
  MOZ_ASSERT(quotaManager);

  QM_TRY(MOZ_TO_RESULT(quotaManager->EnsureStorageIsInitialized()));

  QM_TRY(MOZ_TO_RESULT(quotaManager->EnsureTemporaryStorageIsInitialized()));

  QM_TRY_INSPECT(const auto& fileSystemDirectory,
                 quotaManager
                     ->EnsureTemporaryOriginIsInitialized(
                         quota::PERSISTENCE_TYPE_DEFAULT, aOriginMetadata)
                     .map([](const auto& aPair) { return aPair.first; }));

  QM_TRY(QM_TO_RESULT(fileSystemDirectory->AppendRelativePath(
      NS_LITERAL_STRING_FROM_CSTRING(FILESYSTEM_DIRECTORY_NAME))));

  bool exists = true;
  QM_TRY(QM_TO_RESULT(fileSystemDirectory->Exists(&exists)));

  if (!exists) {
    QM_TRY(QM_TO_RESULT(
        fileSystemDirectory->Create(nsIFile::DIRECTORY_TYPE, 0755)));

    return NS_OK;
  }

  bool isDirectory = true;
  QM_TRY(QM_TO_RESULT(fileSystemDirectory->IsDirectory(&isDirectory)));
  QM_TRY(OkIf(isDirectory), NS_ERROR_FILE_NOT_DIRECTORY);

  return NS_OK;
}

Result<nsCOMPtr<nsIFile>, QMResult> GetDatabaseFile(
    const quota::OriginMetadata& aOriginMetadata) {
  MOZ_ASSERT(!aOriginMetadata.mOrigin.IsEmpty());

  QM_TRY_UNWRAP(nsCOMPtr<nsIFile> databaseFile,
                GetFileSystemDirectory(aOriginMetadata));

  QM_TRY(QM_TO_RESULT(databaseFile->AppendRelativePath(kDatabaseFileName)));

  return databaseFile;
}

/**
 * TODO: This is almost identical to the corresponding function of IndexedDB
 */
Result<nsCOMPtr<nsIFileURL>, QMResult> GetDatabaseFileURL(
    const quota::OriginMetadata& aOriginMetadata,
    const int64_t aDirectoryLockId) {
  MOZ_ASSERT(aDirectoryLockId >= 0);

  QM_TRY_UNWRAP(nsCOMPtr<nsIFile> databaseFile,
                GetDatabaseFile(aOriginMetadata));

  QM_TRY_INSPECT(
      const auto& protocolHandler,
      QM_TO_RESULT_TRANSFORM(MOZ_TO_RESULT_GET_TYPED(
          nsCOMPtr<nsIProtocolHandler>, MOZ_SELECT_OVERLOAD(do_GetService),
          NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX "file")));

  QM_TRY_INSPECT(const auto& fileHandler,
                 QM_TO_RESULT_TRANSFORM(MOZ_TO_RESULT_GET_TYPED(
                     nsCOMPtr<nsIFileProtocolHandler>,
                     MOZ_SELECT_OVERLOAD(do_QueryInterface), protocolHandler)));

  QM_TRY_INSPECT(const auto& mutator,
                 QM_TO_RESULT_TRANSFORM(MOZ_TO_RESULT_INVOKE_MEMBER_TYPED(
                     nsCOMPtr<nsIURIMutator>, fileHandler, NewFileURIMutator,
                     databaseFile)));

  nsCString directoryLockIdClause = "&directoryLockId="_ns;
  directoryLockIdClause.AppendInt(aDirectoryLockId);

  nsCOMPtr<nsIFileURL> result;
  QM_TRY(QM_TO_RESULT(
      NS_MutateURI(mutator).SetQuery(directoryLockIdClause).Finalize(result)));

  return result;
}

/* static */
Result<FileSystemFileManager, QMResult>
FileSystemFileManager::CreateFileSystemFileManager(
    nsCOMPtr<nsIFile>&& topDirectory) {
  return FileSystemFileManager(std::move(topDirectory));
}

/* static */
Result<FileSystemFileManager, QMResult>
FileSystemFileManager::CreateFileSystemFileManager(
    const quota::OriginMetadata& aOriginMetadata) {
  QM_TRY_UNWRAP(nsCOMPtr<nsIFile> topDirectory,
                GetFileSystemDirectory(aOriginMetadata));

  return FileSystemFileManager(std::move(topDirectory));
}

FileSystemFileManager::FileSystemFileManager(nsCOMPtr<nsIFile>&& aTopDirectory)
    : mTopDirectory(std::move(aTopDirectory)) {}

Result<nsCOMPtr<nsIFile>, QMResult> FileSystemFileManager::GetFile(
    const EntryId& aEntryId) const {
  return data::GetFile(mTopDirectory, aEntryId);
}

Result<nsCOMPtr<nsIFile>, QMResult> FileSystemFileManager::GetOrCreateFile(
    const EntryId& aEntryId) {
  return data::GetOrCreateFile(mTopDirectory, aEntryId);
}

Result<Usage, QMResult> FileSystemFileManager::RemoveFile(
    const EntryId& aEntryId) {
  MOZ_ASSERT(!aEntryId.IsEmpty());
  QM_TRY_UNWRAP(nsCOMPtr<nsIFile> pathObject,
                GetFileDestination(mTopDirectory, aEntryId));

  bool exists = false;
  QM_TRY(QM_TO_RESULT(pathObject->Exists(&exists)));

  if (!exists) {
    return 0;
  }

  bool isFile = false;
  QM_TRY(QM_TO_RESULT(pathObject->IsFile(&isFile)));

  // We could handle this also as a nonexistent file.
  if (!isFile) {
    return Err(QMResult(NS_ERROR_FILE_IS_DIRECTORY));
  }

  Usage totalUsage = 0;
#ifdef DEBUG
  QM_TRY_UNWRAP(totalUsage,
                QM_TO_RESULT_INVOKE_MEMBER(pathObject, GetFileSize));
#endif

  QM_TRY(QM_TO_RESULT(pathObject->Remove(/* recursive */ false)));

  return totalUsage;
}

Result<DebugOnly<Usage>, QMResult> FileSystemFileManager::RemoveFiles(
    const nsTArray<EntryId>& aEntryIds, nsTArray<EntryId>& aRemoveFails) {
  if (aEntryIds.IsEmpty()) {
    return DebugOnly<Usage>(0);
  }

  CheckedInt64 totalUsage = 0;
  for (const auto& entryId : aEntryIds) {
    QM_WARNONLY_TRY_UNWRAP(Maybe<nsCOMPtr<nsIFile>> maybeFile,
                           GetFileDestination(mTopDirectory, entryId));
    if (!maybeFile) {
      aRemoveFails.AppendElement(entryId);
      continue;
    }
    nsCOMPtr<nsIFile> fileObject = maybeFile.value();

// Size recorded at close is checked to be equal to the sum of sizes on disk
#ifdef DEBUG
    QM_WARNONLY_TRY_UNWRAP(Maybe<Usage> fileSize, GetFileSize(fileObject));
    if (!fileSize) {
      aRemoveFails.AppendElement(entryId);
      continue;
    }
    totalUsage += fileSize.value();
#endif

    QM_WARNONLY_TRY_UNWRAP(Maybe<Ok> ok,
                           MOZ_TO_RESULT(RemoveFileObject(fileObject)));
    if (!ok) {
      aRemoveFails.AppendElement(entryId);
    }
  }

  MOZ_ASSERT(totalUsage.isValid());

  return DebugOnly<Usage>(totalUsage.value());
}

}  // namespace mozilla::dom::fs::data