summaryrefslogtreecommitdiffstats
path: root/toolkit/mozapps/update/UpdateServiceStub.sys.mjs
blob: 415c6bbe80533aad9a3a987bec44e9f353eca71f (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
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* 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/. */

import { FileUtils } from "resource://gre/modules/FileUtils.sys.mjs";
import { AppConstants } from "resource://gre/modules/AppConstants.sys.mjs";

const lazy = {};

ChromeUtils.defineESModuleGetters(lazy, {
  UpdateLog: "resource://gre/modules/UpdateLog.sys.mjs",
});

const DIR_UPDATES = "updates";
const FILE_UPDATE_STATUS = "update.status";

const KEY_UPDROOT = "UpdRootD";
const KEY_OLD_UPDROOT = "OldUpdRootD";

// The pref prefix below should have the hash of the install path appended to
// ensure that this is a per-installation pref (i.e. to ensure that migration
// happens for every install rather than once per profile)
const PREF_PREFIX_UPDATE_DIR_MIGRATED = "app.update.migrated.updateDir3.";
const PREF_APP_UPDATE_ALTUPDATEDIRPATH = "app.update.altUpdateDirPath";

function getUpdateBaseDirNoCreate() {
  if (Cu.isInAutomation) {
    // This allows tests to use an alternate updates directory so they can test
    // startup behavior.
    const MAGIC_TEST_ROOT_PREFIX = "<test-root>";
    const PREF_TEST_ROOT = "mochitest.testRoot";
    let alternatePath = Services.prefs.getCharPref(
      PREF_APP_UPDATE_ALTUPDATEDIRPATH,
      null
    );
    if (alternatePath && alternatePath.startsWith(MAGIC_TEST_ROOT_PREFIX)) {
      let testRoot = Services.prefs.getCharPref(PREF_TEST_ROOT);
      let relativePath = alternatePath.substring(MAGIC_TEST_ROOT_PREFIX.length);
      if (AppConstants.platform == "win") {
        relativePath = relativePath.replace(/\//g, "\\");
      }
      alternatePath = testRoot + relativePath;
      let updateDir = Cc["@mozilla.org/file/local;1"].createInstance(
        Ci.nsIFile
      );
      updateDir.initWithPath(alternatePath);
      LOG(
        "getUpdateBaseDirNoCreate returning test directory, path: " +
          updateDir.path
      );
      return updateDir;
    }
  }

  return FileUtils.getDir(KEY_UPDROOT, []);
}

export function UpdateServiceStub() {
  LOG("UpdateServiceStub - Begin.");

  let updateDir = getUpdateBaseDirNoCreate();
  let prefUpdateDirMigrated =
    PREF_PREFIX_UPDATE_DIR_MIGRATED + updateDir.leafName;

  let statusFile = updateDir;
  statusFile.append(DIR_UPDATES);
  statusFile.append("0");
  statusFile.append(FILE_UPDATE_STATUS);
  updateDir = null; // We don't need updateDir anymore, plus now its nsIFile
  // contains the status file's path

  // We may need to migrate update data
  if (
    AppConstants.platform == "win" &&
    !Services.prefs.getBoolPref(prefUpdateDirMigrated, false)
  ) {
    Services.prefs.setBoolPref(prefUpdateDirMigrated, true);
    try {
      migrateUpdateDirectory();
    } catch (ex) {
      // For the most part, migrateUpdateDirectory() catches its own errors.
      // But there are technically things that could happen that might not be
      // caught, like nsIFile.parent or nsIFile.append could unexpectedly fail.
      // So we will catch any errors here, just in case.
      LOG(
        `UpdateServiceStub:UpdateServiceStub Failed to migrate update ` +
          `directory. Exception: ${ex}`
      );
    }
  }

  // If the update.status file exists then initiate post update processing.
  if (statusFile.exists()) {
    let aus = Cc["@mozilla.org/updates/update-service;1"]
      .getService(Ci.nsIApplicationUpdateService)
      .QueryInterface(Ci.nsIObserver);
    aus.observe(null, "post-update-processing", "");
  }
}

UpdateServiceStub.prototype = {
  observe() {},
  classID: Components.ID("{e43b0010-04ba-4da6-b523-1f92580bc150}"),
  QueryInterface: ChromeUtils.generateQI(["nsIObserver"]),
};

/**
 * This function should be called when there are files in the old update
 * directory that may need to be migrated to the new update directory.
 */
function migrateUpdateDirectory() {
  LOG("UpdateServiceStub:migrateUpdateDirectory Performing migration");

  let sourceRootDir = FileUtils.getDir(KEY_OLD_UPDROOT, []);
  let destRootDir = FileUtils.getDir(KEY_UPDROOT, []);
  let hash = destRootDir.leafName;

  if (!sourceRootDir.exists()) {
    // Nothing to migrate.
    return;
  }

  // List of files to migrate. Each is specified as a list of path components.
  const toMigrate = [
    ["updates.xml"],
    ["active-update.xml"],
    ["update-config.json"],
    ["updates", "last-update.log"],
    ["updates", "backup-update.log"],
    ["updates", "downloading", FILE_UPDATE_STATUS],
    ["updates", "downloading", "update.mar"],
    ["updates", "0", FILE_UPDATE_STATUS],
    ["updates", "0", "update.mar"],
    ["updates", "0", "update.version"],
    ["updates", "0", "update.log"],
    ["backgroundupdate", "datareporting", "glean", "db", "data.safe.bin"],
  ];

  // Before we copy anything, double check that a different profile hasn't
  // already performed migration. If we don't have the necessary permissions to
  // remove the pre-migration files, we don't want to copy any old files and
  // potentially make the current update state inconsistent.
  for (let pathComponents of toMigrate) {
    // Assemble the destination nsIFile.
    let destFile = destRootDir.clone();
    for (let pathComponent of pathComponents) {
      destFile.append(pathComponent);
    }

    if (destFile.exists()) {
      LOG(
        `UpdateServiceStub:migrateUpdateDirectory Aborting migration because ` +
          `"${destFile.path}" already exists.`
      );
      return;
    }
  }

  // Before we migrate everything in toMigrate, there are a few things that
  // need special handling.
  let sourceRootParent = sourceRootDir.parent.parent;
  let destRootParent = destRootDir.parent.parent;

  let profileCountFile = sourceRootParent.clone();
  profileCountFile.append(`profile_count_${hash}.json`);
  migrateFile(profileCountFile, destRootParent);

  const updatePingPrefix = `uninstall_ping_${hash}_`;
  const updatePingSuffix = ".json";
  try {
    for (let file of sourceRootParent.directoryEntries) {
      if (
        file.leafName.startsWith(updatePingPrefix) &&
        file.leafName.endsWith(updatePingSuffix)
      ) {
        migrateFile(file, destRootParent);
      }
    }
  } catch (ex) {
    // migrateFile should catch its own errors, but it is possible that
    // sourceRootParent.directoryEntries could throw.
    LOG(
      `UpdateServiceStub:migrateUpdateDirectory Failed to migrate uninstall ` +
        `ping. Exception: ${ex}`
    );
  }

  // Migrate "backgroundupdate.moz_log" and child process logs like
  // "backgroundupdate.child-1.moz_log".
  const backgroundLogPrefix = `backgroundupdate`;
  const backgroundLogSuffix = ".moz_log";
  try {
    for (let file of sourceRootDir.directoryEntries) {
      if (
        file.leafName.startsWith(backgroundLogPrefix) &&
        file.leafName.endsWith(backgroundLogSuffix)
      ) {
        migrateFile(file, destRootDir);
      }
    }
  } catch (ex) {
    LOG(
      `UpdateServiceStub:migrateUpdateDirectory Failed to migrate background ` +
        `log file. Exception: ${ex}`
    );
  }

  const pendingPingRelDir =
    "backgroundupdate\\datareporting\\glean\\pending_pings";
  let pendingPingSourceDir = sourceRootDir.clone();
  pendingPingSourceDir.appendRelativePath(pendingPingRelDir);
  let pendingPingDestDir = destRootDir.clone();
  pendingPingDestDir.appendRelativePath(pendingPingRelDir);
  // Pending ping filenames are UUIDs.
  const pendingPingFilenameRegex =
    /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
  if (pendingPingSourceDir.exists()) {
    try {
      for (let file of pendingPingSourceDir.directoryEntries) {
        if (pendingPingFilenameRegex.test(file.leafName)) {
          migrateFile(file, pendingPingDestDir);
        }
      }
    } catch (ex) {
      // migrateFile should catch its own errors, but it is possible that
      // pendingPingSourceDir.directoryEntries could throw.
      LOG(
        `UpdateServiceStub:migrateUpdateDirectory Failed to migrate ` +
          `pending pings. Exception: ${ex}`
      );
    }
  }

  // Migrate everything in toMigrate.
  for (let pathComponents of toMigrate) {
    let filename = pathComponents.pop();

    // Assemble the source and destination nsIFile's.
    let sourceFile = sourceRootDir.clone();
    let destDir = destRootDir.clone();
    for (let pathComponent of pathComponents) {
      sourceFile.append(pathComponent);
      destDir.append(pathComponent);
    }
    sourceFile.append(filename);

    migrateFile(sourceFile, destDir);
  }

  // There is no reason to keep this file, and it often hangs around and could
  // interfere with cleanup.
  let updateLockFile = sourceRootParent.clone();
  updateLockFile.append(`UpdateLock-${hash}`);
  try {
    updateLockFile.remove(false);
  } catch (ex) {}

  // We want to recursively remove empty directories out of the sourceRootDir.
  // And if that was the only remaining update directory in sourceRootParent,
  // we want to remove that too. But we don't want to recurse into other update
  // directories in sourceRootParent.
  //
  // Potentially removes "C:\ProgramData\Mozilla\updates\<hash>" and
  // subdirectories.
  cleanupDir(sourceRootDir, true);
  // Potentially removes "C:\ProgramData\Mozilla\updates"
  cleanupDir(sourceRootDir.parent, false);
  // Potentially removes "C:\ProgramData\Mozilla"
  cleanupDir(sourceRootParent, false);
}

/**
 * Attempts to move the source file to the destination directory. If the file
 * cannot be moved, we attempt to copy it and remove the original. All errors
 * are logged, but no exceptions are thrown. Both arguments must be of type
 * nsIFile and are expected to be regular files.
 *
 * Non-existent files are silently ignored.
 *
 * The reason that we are migrating is to deal with problematic inherited
 * permissions. But, luckily, neither nsIFile.moveTo nor nsIFile.copyTo preserve
 * inherited permissions.
 */
function migrateFile(sourceFile, destDir) {
  if (!sourceFile.exists()) {
    return;
  }

  if (sourceFile.isDirectory()) {
    LOG(
      `UpdateServiceStub:migrateFile Aborting attempt to migrate ` +
        `"${sourceFile.path}" because it is a directory.`
    );
    return;
  }

  // Create destination directory.
  try {
    // Pass an arbitrary value for permissions. Windows doesn't use octal
    // permissions, so that value doesn't really do anything.
    destDir.create(Ci.nsIFile.DIRECTORY_TYPE, 0);
  } catch (ex) {
    if (ex.result != Cr.NS_ERROR_FILE_ALREADY_EXISTS) {
      LOG(
        `UpdateServiceStub:migrateFile Unable to create destination ` +
          `directory "${destDir.path}": ${ex}`
      );
    }
  }

  try {
    sourceFile.moveTo(destDir, null);
    return;
  } catch (ex) {}

  try {
    sourceFile.copyTo(destDir, null);
  } catch (ex) {
    LOG(
      `UpdateServiceStub:migrateFile Failed to migrate file from ` +
        `"${sourceFile.path}" to "${destDir.path}". Exception: ${ex}`
    );
    return;
  }

  try {
    sourceFile.remove(false);
  } catch (ex) {
    LOG(
      `UpdateServiceStub:migrateFile Successfully migrated file from ` +
        `"${sourceFile.path}" to "${destDir.path}", but was unable to remove ` +
        `the original. Exception: ${ex}`
    );
  }
}

/**
 * If recurse is true, recurses through the directory's contents. Any empty
 * directories are removed. Directories with remaining files are left behind.
 *
 * If recurse if false, we delete the directory passed as long as it is empty.
 *
 * All errors are silenced and not thrown.
 *
 * Returns true if the directory passed in was removed. Otherwise false.
 */
function cleanupDir(dir, recurse) {
  let directoryEmpty = true;
  try {
    for (let file of dir.directoryEntries) {
      if (!recurse) {
        // If we aren't recursing, bail out after we find a single file. The
        // directory isn't empty so we can't delete it, and we aren't going to
        // clean out and remove any other directories.
        return false;
      }
      if (file.isDirectory()) {
        if (!cleanupDir(file, recurse)) {
          directoryEmpty = false;
        }
      } else {
        directoryEmpty = false;
      }
    }
  } catch (ex) {
    // If any of our nsIFile calls fail, just err on the side of caution and
    // don't delete anything.
    return false;
  }

  if (directoryEmpty) {
    try {
      dir.remove(false);
      return true;
    } catch (ex) {}
  }
  return false;
}

/**
 * Logs a string to the error console.
 * @param   string
 *          The string to write to the error console.
 */
function LOG(string) {
  lazy.UpdateLog.logPrefixedString("AUS:STB", string);
}