home *** CD-ROM | disk | FTP | other *** search
/ Chip 2008 June / CHIP-2008-06.iso / bonus / +10SecurityTips / files / xB-Browser_2.0.0.12b.exe / App / Browser / firefox / components / nsUpdateService.js < prev    next >
Encoding:
Text File  |  2008-02-02  |  102.9 KB  |  3,124 lines

  1. //@line 42 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-Release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2.  
  3. const PREF_APP_UPDATE_ENABLED             = "app.update.enabled";
  4. const PREF_APP_UPDATE_AUTO                = "app.update.auto";
  5. const PREF_APP_UPDATE_MODE                = "app.update.mode";
  6. const PREF_APP_UPDATE_SILENT              = "app.update.silent";
  7. const PREF_APP_UPDATE_INTERVAL            = "app.update.interval";
  8. const PREF_APP_UPDATE_TIMER               = "app.update.timer";
  9. const PREF_APP_UPDATE_LOG_BRANCH          = "app.update.log.";
  10. const PREF_APP_UPDATE_URL                 = "app.update.url";
  11. const PREF_APP_UPDATE_URL_OVERRIDE        = "app.update.url.override";
  12. const PREF_APP_UPDATE_URL_DETAILS         = "app.update.url.details";
  13. const PREF_APP_UPDATE_CHANNEL             = "app.update.channel";
  14. const PREF_APP_UPDATE_SHOW_INSTALLED_UI   = "app.update.showInstalledUI";
  15. const PREF_APP_UPDATE_LASTUPDATETIME_FMT  = "app.update.lastUpdateTime.%ID%";
  16. const PREF_APP_EXTENSIONS_VERSION         = "app.extensions.version";
  17. const PREF_GENERAL_USERAGENT_LOCALE       = "general.useragent.locale";
  18. const PREF_APP_UPDATE_INCOMPATIBLE_MODE   = "app.update.incompatible.mode";
  19. const PREF_UPDATE_NEVER_BRANCH            = "app.update.never."
  20. const PREF_PARTNER_BRANCH                 = "app.partner.";
  21.  
  22. const URI_UPDATE_PROMPT_DIALOG  = "chrome://mozapps/content/update/updates.xul";
  23. const URI_UPDATE_HISTORY_DIALOG = "chrome://mozapps/content/update/history.xul";
  24. const URI_BRAND_PROPERTIES      = "chrome://branding/locale/brand.properties";
  25. const URI_UPDATES_PROPERTIES    = "chrome://mozapps/locale/update/updates.properties";
  26. const URI_UPDATE_NS             = "http://www.mozilla.org/2005/app-update";
  27.  
  28. const KEY_APPDIR          = "XCurProcD";
  29. //@line 70 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-Release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  30. const KEY_UPDROOT         = "UpdRootD";
  31. const KEY_UAPPDATA        = "UAppData";
  32. //@line 73 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-Release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  33.  
  34. const DIR_UPDATES         = "updates";
  35. const FILE_UPDATE_STATUS  = "update.status";
  36. const FILE_UPDATE_ARCHIVE = "update.mar";
  37. const FILE_UPDATE_LOG     = "update.log"
  38. const FILE_UPDATES_DB     = "updates.xml";
  39. const FILE_UPDATE_ACTIVE  = "active-update.xml";
  40. const FILE_PERMS_TEST     = "update.test";
  41. const FILE_LAST_LOG       = "last-update.log";
  42.  
  43. const MODE_RDONLY   = 0x01;
  44. const MODE_WRONLY   = 0x02;
  45. const MODE_CREATE   = 0x08;
  46. const MODE_APPEND   = 0x10;
  47. const MODE_TRUNCATE = 0x20;
  48.  
  49. const PERMS_FILE      = 0644;
  50. const PERMS_DIRECTORY = 0755;
  51.  
  52. const STATE_NONE            = "null";
  53. const STATE_DOWNLOADING     = "downloading";
  54. const STATE_PENDING         = "pending";
  55. const STATE_APPLYING        = "applying";
  56. const STATE_SUCCEEDED       = "succeeded";
  57. const STATE_DOWNLOAD_FAILED = "download-failed";
  58. const STATE_FAILED          = "failed";
  59.  
  60. // From updater/errors.h:
  61. const WRITE_ERROR = 7;
  62.  
  63. const DOWNLOAD_CHUNK_SIZE           = 300000; // bytes
  64. const DOWNLOAD_BACKGROUND_INTERVAL  = 600;    // seconds
  65. const DOWNLOAD_FOREGROUND_INTERVAL  = 0;
  66.  
  67. // Values for the PREF_APP_UPDATE_INCOMPATIBLE_MODE pref. See documentation in
  68. // code below. 
  69. const INCOMPATIBLE_MODE_NEWVERSIONS   = 0;
  70. const INCOMPATIBLE_MODE_NONEWVERSIONS = 1;
  71.  
  72. const POST_UPDATE_CONTRACTID = "@mozilla.org/updates/post-update;1";
  73.  
  74. const nsILocalFile            = Components.interfaces.nsILocalFile;
  75. const nsIUpdateService        = Components.interfaces.nsIUpdateService;
  76. const nsIUpdateItem           = Components.interfaces.nsIUpdateItem;
  77. const nsIPrefLocalizedString  = Components.interfaces.nsIPrefLocalizedString;
  78. const nsIIncrementalDownload  = Components.interfaces.nsIIncrementalDownload;
  79. const nsIFileInputStream      = Components.interfaces.nsIFileInputStream;
  80. const nsIFileOutputStream     = Components.interfaces.nsIFileOutputStream;
  81. const nsICryptoHash           = Components.interfaces.nsICryptoHash;
  82.  
  83. const Node = Components.interfaces.nsIDOMNode;
  84.  
  85. var gApp        = null;
  86. var gPref       = null;
  87. var gABI        = null;
  88. var gOSVersion  = null;
  89. var gConsole    = null;
  90. var gLogEnabled = { };
  91.  
  92. // shared code for suppressing bad cert dialogs
  93. //@line 40 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-Release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/update/src/../../shared/src/badCertHandler.js"
  94.  
  95. /**
  96.  * Only allow built-in certs for HTTPS connections.  See bug 340198.
  97.  */
  98. function checkCert(channel) {
  99.   if (!channel.originalURI.schemeIs("https"))  // bypass
  100.     return;
  101.  
  102.   const Ci = Components.interfaces;  
  103.   var cert =
  104.       channel.securityInfo.QueryInterface(Ci.nsISSLStatusProvider).
  105.       SSLStatus.QueryInterface(Ci.nsISSLStatus).serverCert;
  106.  
  107.   var issuer = cert.issuer;
  108.   while (issuer && !cert.equals(issuer)) {
  109.     cert = issuer;
  110.     issuer = cert.issuer;
  111.   }
  112.  
  113.   if (!issuer || issuer.tokenName != "Builtin Object Token")
  114.     throw "cert issuer is not built-in";
  115. }
  116.  
  117. /**
  118.  * This class implements nsIBadCertListener.  It's job is to prevent "bad cert"
  119.  * security dialogs from being shown to the user.  It is better to simply fail
  120.  * if the certificate is bad. See bug 304286.
  121.  */
  122. function BadCertHandler() {
  123. }
  124. BadCertHandler.prototype = {
  125.  
  126.   // nsIBadCertListener
  127.   confirmUnknownIssuer: function(socketInfo, cert, certAddType) {
  128.     LOG("EM BadCertHandler: Unknown issuer");
  129.     return false;
  130.   },
  131.  
  132.   confirmMismatchDomain: function(socketInfo, targetURL, cert) {
  133.     LOG("EM BadCertHandler: Mismatched domain");
  134.     return false;
  135.   },
  136.  
  137.   confirmCertExpired: function(socketInfo, cert) {
  138.     LOG("EM BadCertHandler: Expired certificate");
  139.     return false;
  140.   },
  141.  
  142.   notifyCrlNextupdate: function(socketInfo, targetURL, cert) {
  143.   },
  144.  
  145.   // nsIChannelEventSink
  146.   onChannelRedirect: function(oldChannel, newChannel, flags) {
  147.     // make sure the certificate of the old channel checks out before we follow
  148.     // a redirect from it.  See bug 340198.
  149.     checkCert(oldChannel);
  150.   },
  151.  
  152.   // nsIInterfaceRequestor
  153.   getInterface: function(iid) {
  154.     if (iid.equals(Components.interfaces.nsIBadCertListener) ||
  155.         iid.equals(Components.interfaces.nsIChannelEventSink))
  156.       return this;
  157.  
  158.     Components.returnCode = Components.results.NS_ERROR_NO_INTERFACE;
  159.     return null;
  160.   },
  161.  
  162.   // nsISupports
  163.   QueryInterface: function(iid) {
  164.     if (!iid.equals(Components.interfaces.nsIBadCertListener) &&
  165.         !iid.equals(Components.interfaces.nsIChannelEventSink) &&
  166.         !iid.equals(Components.interfaces.nsIInterfaceRequestor) &&
  167.         !iid.equals(Components.interfaces.nsISupports))
  168.       throw Components.results.NS_ERROR_NO_INTERFACE;
  169.     return this;
  170.   }
  171. };
  172. //@line 134 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-Release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  173.  
  174. /**
  175.  * Logs a string to the error console. 
  176.  * @param   string
  177.  *          The string to write to the error console..
  178.  */  
  179. function LOG(module, string) {
  180.   if (module in gLogEnabled) {
  181.     dump("*** " + module + ": " + string + "\n");
  182.     gConsole.logStringMessage(string);
  183.   }
  184. }
  185.  
  186. /**
  187.  * Convert a string containing binary values to hex.
  188.  */
  189. function binaryToHex(input) {
  190.   var result = "";
  191.   for (var i = 0; i < input.length; ++i) {
  192.     var hex = input.charCodeAt(i).toString(16);
  193.     if (hex.length == 1)
  194.       hex = "0" + hex;
  195.     result += hex;
  196.   }
  197.   return result;
  198. }
  199.  
  200. /**
  201.  * Gets a File URL spec for a nsIFile
  202.  * @param   file
  203.  *          The file to get a file URL spec to
  204.  * @returns The file URL spec to the file
  205.  */
  206. function getURLSpecFromFile(file) {
  207.   var ioServ = Components.classes["@mozilla.org/network/io-service;1"]
  208.                          .getService(Components.interfaces.nsIIOService);
  209.   var fph = ioServ.getProtocolHandler("file")
  210.                   .QueryInterface(Components.interfaces.nsIFileProtocolHandler);
  211.   return fph.getURLSpecFromFile(file);
  212. }
  213.  
  214. /**
  215.  * Gets the specified directory at the specified hierarchy under a 
  216.  * Directory Service key. 
  217.  * @param   key
  218.  *          The Directory Service Key to start from
  219.  * @param   pathArray
  220.  *          An array of path components to locate beneath the directory 
  221.  *          specified by |key|
  222.  * @return  nsIFile object for the location specified. If the directory
  223.  *          requested does not exist, it is created, along with any
  224.  *          parent directories that need to be created.
  225.  */
  226. function getDir(key, pathArray) {
  227.   return getDirInternal(key, pathArray, true, false);
  228. }
  229.  
  230. /**
  231.  * Gets the specified directory at the speciifed hierarchy under a 
  232.  * Directory Service key. 
  233.  * @param   key
  234.  *          The Directory Service Key to start from
  235.  * @param   pathArray
  236.  *          An array of path components to locate beneath the directory 
  237.  *          specified by |key|
  238.  * @return  nsIFile object for the location specified. If the directory
  239.  *          requested does not exist, it is NOT created.
  240.  */
  241. function getDirNoCreate(key, pathArray) {
  242.   return getDirInternal(key, pathArray, false, false);
  243. }
  244.  
  245. /**
  246.  * Gets the specified directory at the specified hierarchy under the 
  247.  * update root directory.
  248.  * @param   pathArray
  249.  *          An array of path components to locate beneath the directory 
  250.  *          specified by |key|
  251.  * @return  nsIFile object for the location specified. If the directory
  252.  *          requested does not exist, it is created, along with any
  253.  *          parent directories that need to be created.
  254.  */
  255. function getUpdateDir(pathArray) {
  256.   return getDirInternal(KEY_APPDIR, pathArray, true, true);
  257. }
  258.  
  259. /**
  260.  * Gets the specified directory at the speciifed hierarchy under a 
  261.  * Directory Service key. 
  262.  * @param   key
  263.  *          The Directory Service Key to start from
  264.  * @param   pathArray
  265.  *          An array of path components to locate beneath the directory 
  266.  *          specified by |key|
  267.  * @param   shouldCreate
  268.  *          true if the directory hierarchy specified in |pathArray|
  269.  *          should be created if it does not exist,
  270.  *          false otherwise.
  271.  * @param   update
  272.  *          true if finding the update directory,
  273.  *          false otherwise.
  274.  * @return  nsIFile object for the location specified. 
  275.  */
  276. function getDirInternal(key, pathArray, shouldCreate, update) {
  277.   var fileLocator = Components.classes["@mozilla.org/file/directory_service;1"]
  278.                               .getService(Components.interfaces.nsIProperties);
  279.   var dir = fileLocator.get(key, Components.interfaces.nsIFile);
  280. //@line 242 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-Release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  281.   if (update) {
  282.     try {
  283.       dir = fileLocator.get(KEY_UPDROOT, Components.interfaces.nsIFile);
  284.     } catch (e) {
  285.     }
  286.   }
  287. //@line 249 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-Release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  288.   for (var i = 0; i < pathArray.length; ++i) {
  289.     dir.append(pathArray[i]);
  290.     if (shouldCreate && !dir.exists())
  291.       dir.create(nsILocalFile.DIRECTORY_TYPE, PERMS_DIRECTORY);
  292.   }
  293.   return dir;
  294. }
  295.  
  296. /**
  297.  * Gets the file at the speciifed hierarchy under a Directory Service key.
  298.  * @param   key
  299.  *          The Directory Service Key to start from
  300.  * @param   pathArray
  301.  *          An array of path components to locate beneath the directory 
  302.  *          specified by |key|. The last item in this array must be the
  303.  *          leaf name of a file.
  304.  * @return  nsIFile object for the file specified. The file is NOT created
  305.  *          if it does not exist, however all required directories along 
  306.  *          the way are.
  307.  */
  308. function getFile(key, pathArray) {
  309.   var file = getDir(key, pathArray.slice(0, -1));
  310.   file.append(pathArray[pathArray.length - 1]);
  311.   return file;
  312. }
  313.  
  314. /**
  315.  * Gets the file at the specified hierarchy under the update root directory.
  316.  * @param   pathArray
  317.  *          An array of path components to locate beneath the directory 
  318.  *          specified by |key|. The last item in this array must be the
  319.  *          leaf name of a file.
  320.  * @return  nsIFile object for the file specified. The file is NOT created
  321.  *          if it does not exist, however all required directories along 
  322.  *          the way are.
  323.  */
  324. function getUpdateFile(pathArray) {
  325.   var file = getUpdateDir(pathArray.slice(0, -1));
  326.   file.append(pathArray[pathArray.length - 1]);
  327.   return file;
  328. }
  329.  
  330. /**
  331.  * Closes a Safe Output Stream
  332.  * @param   fos
  333.  *          The Safe Output Stream to close
  334.  */
  335. function closeSafeOutputStream(fos) {
  336.   if (fos instanceof Components.interfaces.nsISafeOutputStream) {
  337.     try {
  338.       fos.finish();
  339.     }
  340.     catch (e) {
  341.       fos.close();
  342.     }
  343.   }
  344.   else
  345.     fos.close();
  346. }
  347.  
  348. /**
  349.  * Returns human readable status text from the updates.properties bundle
  350.  * based on an error code
  351.  * @param   code
  352.  *          The error code to look up human readable status text for
  353.  * @param   defaultCode
  354.  *          The default code to look up should human readable status text
  355.  *          not exist for |code|
  356.  * @returns A human readable status text string
  357.  */
  358. function getStatusTextFromCode(code, defaultCode) {
  359.   var sbs = 
  360.       Components.classes["@mozilla.org/intl/stringbundle;1"].
  361.       getService(Components.interfaces.nsIStringBundleService);
  362.   var updateBundle = sbs.createBundle(URI_UPDATES_PROPERTIES);
  363.   var reason = updateBundle.GetStringFromName("checker_error-" + defaultCode);
  364.   try {
  365.     reason = updateBundle.GetStringFromName("checker_error-" + code);
  366.     LOG("General", "Transfer Error: " + reason + ", code: " + code);
  367.   }
  368.   catch (e) {
  369.     // Use the default reason
  370.     LOG("General", "Transfer Error: " + reason + ", code: " + defaultCode);
  371.   }
  372.   return reason;
  373. }
  374.  
  375. /**
  376.  * Get the Active Updates directory
  377.  * @param   key
  378.  *          The Directory Service Key (optional).
  379.  *          If used, don't search local appdata on Win32 and don't create dir.
  380.  * @returns The active updates directory, as a nsIFile object
  381.  */
  382. function getUpdatesDir(key) {
  383.   // Right now, we only support downloading one patch at a time, so we always
  384.   // use the same target directory.
  385.   var fileLocator =
  386.       Components.classes["@mozilla.org/file/directory_service;1"].
  387.       getService(Components.interfaces.nsIProperties);
  388.   var appDir;
  389.   if (key)
  390.     appDir = fileLocator.get(key, Components.interfaces.nsIFile);
  391.   else {
  392.     appDir = fileLocator.get(KEY_APPDIR, Components.interfaces.nsIFile);
  393. //@line 355 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-Release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  394.     try {
  395.       appDir = fileLocator.get(KEY_UPDROOT, Components.interfaces.nsIFile);
  396.     } catch (e) {
  397.     }
  398. //@line 360 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-Release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  399.   }
  400.   appDir.append(DIR_UPDATES);
  401.   appDir.append("0");
  402.   if (!appDir.exists() && !key)
  403.     appDir.create(nsILocalFile.DIRECTORY_TYPE, PERMS_DIRECTORY);
  404.   return appDir;
  405. }
  406.  
  407. /**
  408.  * Reads the update state from the update.status file in the specified
  409.  * directory.
  410.  * @param   dir
  411.  *          The dir to look for an update.status file in
  412.  * @returns The status value of the update.
  413.  */
  414. function readStatusFile(dir) {
  415.   var statusFile = dir.clone();
  416.   statusFile.append(FILE_UPDATE_STATUS);
  417.   LOG("General", "Reading Status File: " + statusFile.path);
  418.   return readStringFromFile(statusFile) || STATE_NONE;
  419. }
  420.  
  421. /**
  422.  * Writes the current update operation/state to a file in the patch 
  423.  * directory, indicating to the patching system that operations need
  424.  * to be performed.
  425.  * @param   dir
  426.  *          The patch directory where the update.status file should be 
  427.  *          written.
  428.  * @param   state
  429.  *          The state value to write.
  430.  */
  431. function writeStatusFile(dir, state) {
  432.   var statusFile = dir.clone();
  433.   statusFile.append(FILE_UPDATE_STATUS);
  434.   writeStringToFile(statusFile, state);
  435. }
  436.  
  437. /**
  438.  * Removes the Updates Directory
  439.  * @param   key
  440.  *          The Directory Service Key under which update directory resides
  441.  *          (optional).
  442.  */
  443. function cleanUpUpdatesDir(key) {
  444.   // Bail out if we don't have appropriate permissions
  445.   var updateDir;
  446.   try {
  447.     updateDir = getUpdatesDir(key);
  448.   }
  449.   catch (e) {
  450.     return;
  451.   }
  452.  
  453.   var e = updateDir.directoryEntries;
  454.   while (e.hasMoreElements()) {
  455.     var f = e.getNext().QueryInterface(Components.interfaces.nsIFile);
  456.     // Preserve the last update log file for debugging purposes
  457.     if (f.leafName == FILE_UPDATE_LOG) {
  458.       try {
  459.         var dir = f.parent.parent;
  460.         var logFile = dir.clone();
  461.         logFile.append(FILE_LAST_LOG);
  462.         if (logFile.exists())
  463.           logFile.remove(false);
  464.         f.copyTo(dir, FILE_LAST_LOG);
  465.       }
  466.       catch (e) {
  467.         LOG("General", "Failed to copy file: " + f.path);
  468.       }
  469.     }
  470.     // Now, recursively remove this file.  The recusive removal is really
  471.     // only needed on Mac OSX because this directory will contain a copy of
  472.     // updater.app, which is itself a directory.
  473.     try {
  474.       f.remove(true);
  475.     }
  476.     catch (e) {
  477.       LOG("General", "Failed to remove file: " + f.path);
  478.     }
  479.   }
  480.   try {
  481.     updateDir.remove(false);
  482.   } catch (e) {
  483.     LOG("General", "Failed to remove update directory: " + updateDir.path + 
  484.         " - This is almost always bad. Exception = " + e);
  485.     throw e;
  486.   }
  487. }
  488.  
  489. /**
  490.  * Clean up updates list and the updates directory.
  491.  * @param   key
  492.  *          The Directory Service Key under which update directory resides
  493.  *          (optional).
  494.  */
  495. function cleanupActiveUpdate(key) {
  496.   // Move the update from the Active Update list into the Past Updates list.
  497.   var um = 
  498.       Components.classes["@mozilla.org/updates/update-manager;1"].
  499.       getService(Components.interfaces.nsIUpdateManager);
  500.   um.activeUpdate = null;
  501.   um.saveUpdates();
  502.  
  503.   // Now trash the updates directory, since we're done with it
  504.   cleanUpUpdatesDir(key);
  505. }
  506.  
  507. /**
  508.  * Gets a preference value, handling the case where there is no default.
  509.  * @param   func
  510.  *          The name of the preference function to call, on nsIPrefBranch
  511.  * @param   preference
  512.  *          The name of the preference
  513.  * @param   defaultValue
  514.  *          The default value to return in the event the preference has 
  515.  *          no setting
  516.  * @returns The value of the preference, or undefined if there was no
  517.  *          user or default value.
  518.  */
  519. function getPref(func, preference, defaultValue) {
  520.   try {
  521.     return gPref[func](preference);
  522.   }
  523.   catch (e) {
  524.   }
  525.   return defaultValue;
  526. }
  527.  
  528. /**
  529.  * Gets the current value of the locale.  It's possible for this preference to
  530.  * be localized, so we have to do a little extra work here.  Similar code
  531.  * exists in nsHttpHandler.cpp when building the UA string.
  532.  */
  533. function getLocale() {
  534.   try {
  535.       // Get the default branch
  536.       var prefs = Components.classes["@mozilla.org/preferences-service;1"]
  537.           .getService(Components.interfaces.nsIPrefService);
  538.       var defaultPrefs = prefs.getDefaultBranch(null);
  539.       return defaultPrefs.getCharPref(PREF_GENERAL_USERAGENT_LOCALE);
  540.   } catch (e) {}
  541.  
  542.   return gPref.getCharPref(PREF_GENERAL_USERAGENT_LOCALE);
  543. }
  544.  
  545. /**
  546.  * Read the update channel from defaults only.  We do this to ensure that
  547.  * the channel is tightly coupled with the application and does not apply
  548.  * to other instances of the application that may use the same profile.
  549.  */
  550. function getUpdateChannel() {
  551.   var channel = "default";
  552.   var prefName;
  553.   var prefValue;
  554.  
  555.   var defaults =
  556.       gPref.QueryInterface(Components.interfaces.nsIPrefService).
  557.       getDefaultBranch(null);
  558.   try {
  559.     channel = defaults.getCharPref(PREF_APP_UPDATE_CHANNEL);
  560.   } catch (e) {
  561.     // use default when pref not found
  562.   }
  563.  
  564.   try {
  565.     var partners = gPref.getChildList(PREF_PARTNER_BRANCH, { });
  566.     if (partners.length) {
  567.       channel += "-cck";
  568.       partners.sort();
  569.  
  570.       for each (prefName in partners) {
  571.         prefValue = gPref.getCharPref(prefName);
  572.         channel += "-" + prefValue;
  573.       }
  574.     }
  575.   }
  576.   catch (e) {
  577.     Components.utils.reportError(e);
  578.   }
  579.  
  580.   return channel;
  581. }
  582.  
  583. /**
  584.  * An enumeration of items in a JS array.
  585.  * @constructor
  586.  */
  587. function ArrayEnumerator(aItems) {
  588.   this._index = 0;
  589.   if (aItems) {
  590.     for (var i = 0; i < aItems.length; ++i) {
  591.       if (!aItems[i])
  592.         aItems.splice(i, 1);      
  593.     }
  594.   }
  595.   this._contents = aItems;
  596. }
  597.  
  598. ArrayEnumerator.prototype = {
  599.   _index: 0,
  600.   _contents: [],
  601.   
  602.   hasMoreElements: function() {
  603.     return this._index < this._contents.length;
  604.   },
  605.   
  606.   getNext: function() {
  607.     return this._contents[this._index++];      
  608.   }
  609. };
  610.  
  611. /**
  612.  * Trims a prefix from a string.
  613.  * @param   string
  614.  *          The source string
  615.  * @param   prefix
  616.  *          The prefix to remove.
  617.  * @returns The suffix (string - prefix)
  618.  */
  619. function stripPrefix(string, prefix) {
  620.   return string.substr(prefix.length);
  621. }
  622.  
  623. /**
  624.  * Writes a string of text to a file.  A newline will be appended to the data
  625.  * written to the file.  This function only works with ASCII text.
  626.  */
  627. function writeStringToFile(file, text) {
  628.   var fos =
  629.       Components.classes["@mozilla.org/network/safe-file-output-stream;1"].
  630.       createInstance(nsIFileOutputStream);
  631.   var modeFlags = MODE_WRONLY | MODE_CREATE | MODE_TRUNCATE;
  632.   if (!file.exists()) 
  633.     file.create(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  634.   fos.init(file, modeFlags, PERMS_FILE, 0);
  635.   text += "\n";
  636.   fos.write(text, text.length);    
  637.   closeSafeOutputStream(fos);
  638. }
  639.  
  640. /**
  641.  * Reads a string of text from a file.  A trailing newline will be removed
  642.  * before the result is returned.  This function only works with ASCII text.
  643.  */
  644. function readStringFromFile(file) {
  645.   var fis =
  646.       Components.classes["@mozilla.org/network/file-input-stream;1"].
  647.       createInstance(nsIFileInputStream);
  648.   var modeFlags = MODE_RDONLY;
  649.   if (!file.exists())
  650.     return null;
  651.   fis.init(file, modeFlags, PERMS_FILE, 0);
  652.   var sis =
  653.       Components.classes["@mozilla.org/scriptableinputstream;1"].
  654.       createInstance(Components.interfaces.nsIScriptableInputStream);
  655.   sis.init(fis);
  656.   var text = sis.read(sis.available());
  657.   sis.close();
  658.   if (text[text.length - 1] == "\n")
  659.     text = text.slice(0, -1);
  660.   return text;
  661. }
  662.  
  663. function getObserverService()
  664. {
  665.   return Components.classes["@mozilla.org/observer-service;1"]
  666.                    .getService(Components.interfaces.nsIObserverService);
  667. }
  668.  
  669. /**
  670.  * Update Patch
  671.  * @param   patch
  672.  *          A <patch> element to initialize this object with
  673.  * @throws if patch has a size of 0
  674.  * @constructor
  675.  */
  676. function UpdatePatch(patch) {
  677.   this._properties = {};
  678.   for (var i = 0; i < patch.attributes.length; ++i) {
  679.     var attr = patch.attributes.item(i);
  680.     attr.QueryInterface(Components.interfaces.nsIDOMAttr);
  681.     switch (attr.name) {
  682.     case "selected":
  683.       this.selected = attr.value == "true";
  684.       break;
  685.     case "size":
  686.       if (0 == parseInt(attr.value)) {
  687.         LOG("UpdatePatch", "0-sized patch!");
  688.         throw Components.results.NS_ERROR_ILLEGAL_VALUE;
  689.       }
  690.     default:
  691.       this[attr.name] = attr.value;
  692.       break;
  693.     };
  694.   }
  695. }
  696. UpdatePatch.prototype = {
  697.   /**
  698.    * See nsIUpdateService.idl
  699.    */
  700.   serialize: function(updates) {
  701.     var patch = updates.createElementNS(URI_UPDATE_NS, "patch");
  702.     patch.setAttribute("type", this.type);
  703.     patch.setAttribute("URL", this.URL);
  704.     patch.setAttribute("hashFunction", this.hashFunction);
  705.     patch.setAttribute("hashValue", this.hashValue);
  706.     patch.setAttribute("size", this.size);
  707.     patch.setAttribute("selected", this.selected);
  708.     patch.setAttribute("state", this.state);
  709.     
  710.     for (var p in this._properties) {
  711.       if (this._properties[p].present)
  712.         patch.setAttribute(p, this._properties[p].data);
  713.     }
  714.     
  715.     return patch; 
  716.   },
  717.   
  718.   /**
  719.    * A hash of custom properties
  720.    */
  721.   _properties: null,
  722.   
  723.   /**
  724.    * See nsIWritablePropertyBag.idl
  725.    */
  726.   setProperty: function(name, value) {
  727.     this._properties[name] = { data: value, present: true };
  728.   },
  729.   
  730.   /**
  731.    * See nsIWritablePropertyBag.idl
  732.    */
  733.   deleteProperty: function(name) {
  734.     if (name in this._properties)
  735.       this._properties[name].present = false;
  736.     else
  737.       throw Components.results.NS_ERROR_FAILURE;
  738.   },
  739.   
  740.   /**
  741.    * See nsIPropertyBag.idl
  742.    */
  743.   get enumerator() {
  744.     var properties = [];
  745.     for (var p in this._properties)
  746.       properties.push(this._properties[p].data);
  747.     return new ArrayEnumerator(properties);
  748.   },
  749.   
  750.   /**
  751.    * See nsIPropertyBag.idl
  752.    */
  753.   getProperty: function(name) {
  754.     if (name in this._properties &&
  755.         this._properties[name].present)
  756.       return this._properties[name].data;
  757.     throw Components.results.NS_ERROR_FAILURE;
  758.   },
  759.   
  760.   /**
  761.    * Returns whether or not the update.status file for this patch exists at the 
  762.    * appropriate location. 
  763.    */
  764.   get statusFileExists() {
  765.     var statusFile = getUpdatesDir();
  766.     statusFile.append(FILE_UPDATE_STATUS);
  767.     return statusFile.exists();
  768.   },
  769.   
  770.   /**
  771.    * See nsIUpdateService.idl
  772.    */
  773.   get state() {
  774.     if (!this.statusFileExists)
  775.       return STATE_NONE;
  776.     return this._properties.state;
  777.   },
  778.   set state(val) {
  779.     this._properties.state = val;
  780.   },
  781.   
  782.   /**
  783.    * See nsISupports.idl
  784.    */
  785.   QueryInterface: function(iid) {
  786.     if (!iid.equals(Components.interfaces.nsIUpdatePatch) &&
  787.         !iid.equals(Components.interfaces.nsIPropertyBag) && 
  788.         !iid.equals(Components.interfaces.nsIWritablePropertyBag) && 
  789.         !iid.equals(Components.interfaces.nsISupports))
  790.       throw Components.results.NS_ERROR_NO_INTERFACE;
  791.     return this;
  792.   }
  793. };
  794.  
  795. /**
  796.  * Update
  797.  * Implements nsIUpdate
  798.  * @param   update
  799.  *          An <update> element to initialize this object with
  800.  * @throws if the update contains no patches
  801.  * @constructor
  802.  */
  803. function Update(update) {
  804.   this._properties = {};
  805.   this._patches = [];
  806.   this.installDate = 0;
  807.   this.isCompleteUpdate = false;
  808.   this.channel = "default";
  809.  
  810.   // Null <update>, assume this is a message container and do no 
  811.   // further initialization
  812.   if (!update)
  813.     return;
  814.     
  815.   for (var i = 0; i < update.childNodes.length; ++i) {
  816.     var patchElement = update.childNodes.item(i);
  817.     if (patchElement.nodeType != Node.ELEMENT_NODE ||
  818.         patchElement.localName != "patch")
  819.       continue;
  820.  
  821.     patchElement.QueryInterface(Components.interfaces.nsIDOMElement);
  822.     try {
  823.       var patch = new UpdatePatch(patchElement);
  824.     } catch (e) {
  825.       continue;
  826.     }
  827.     this._patches.push(patch);
  828.   }
  829.   
  830.   if (0 == this._patches.length)
  831.     throw Components.results.NS_ERROR_ILLEGAL_VALUE;
  832.  
  833.   for (var i = 0; i < update.attributes.length; ++i) {
  834.     var attr = update.attributes.item(i);
  835.     attr.QueryInterface(Components.interfaces.nsIDOMAttr);
  836.     if (attr.name == "installDate" && attr.value) 
  837.       this.installDate = parseInt(attr.value);
  838.     else if (attr.name == "isCompleteUpdate")
  839.       this.isCompleteUpdate = attr.value == "true";
  840.     else if (attr.name == "isSecurityUpdate")
  841.       this.isSecurityUpdate = attr.value == "true";
  842.     else if (attr.name == "detailsURL")
  843.       this._detailsURL = attr.value;
  844.     else if (attr.name == "channel")
  845.       this.channel = attr.value;
  846.     else
  847.       this[attr.name] = attr.value;
  848.   }
  849.   
  850.   // The Update Name is either the string provided by the <update> element, or
  851.   // the string: "<App Name> <Update App Version>"
  852.   var name = "";
  853.   if (update.hasAttribute("name"))
  854.     name = update.getAttribute("name");
  855.   else {
  856.     var sbs = Components.classes["@mozilla.org/intl/stringbundle;1"]
  857.                         .getService(Components.interfaces.nsIStringBundleService);
  858.     var brandBundle = sbs.createBundle(URI_BRAND_PROPERTIES);
  859.     var updateBundle = sbs.createBundle(URI_UPDATES_PROPERTIES);
  860.     var appName = brandBundle.GetStringFromName("brandShortName");
  861.     name = updateBundle.formatStringFromName("updateName", 
  862.                                              [appName, this.version], 2);
  863.   }
  864.   this.name = name;
  865. }
  866. Update.prototype = {
  867.   /**
  868.    * See nsIUpdateService.idl
  869.    */
  870.   get patchCount() {
  871.     return this._patches.length;
  872.   },
  873.   
  874.   /**
  875.    * See nsIUpdateService.idl
  876.    */
  877.   getPatchAt: function(index) {
  878.     return this._patches[index];
  879.   },
  880.  
  881.   /**
  882.    * See nsIUpdateService.idl
  883.    * 
  884.    * We use a copy of the state cached on this object in |_state| only when 
  885.    * there is no selected patch, i.e. in the case when we could not load 
  886.    * |.activeUpdate| from the update manager for some reason but still have
  887.    * the update.status file to work with. 
  888.    */
  889.   _state: "",
  890.   set state(state) {
  891.     if (this.selectedPatch)
  892.       this.selectedPatch.state = state;
  893.     this._state = state;
  894.     return state;
  895.   },
  896.   get state() {
  897.     if (this.selectedPatch)
  898.       return this.selectedPatch.state;
  899.     return this._state;
  900.   },
  901.  
  902.   /**
  903.    * See nsIUpdateService.idl
  904.    */
  905.   errorCode: 0,
  906.     
  907.   /**
  908.    * See nsIUpdateService.idl
  909.    */
  910.   get selectedPatch() {
  911.     for (var i = 0; i < this.patchCount; ++i) {
  912.       if (this._patches[i].selected)
  913.         return this._patches[i];
  914.     }
  915.     return null;
  916.   },
  917.   
  918.   /**
  919.    * See nsIUpdateService.idl
  920.    */
  921.   get detailsURL() {
  922.     if (!this._detailsURL) {
  923.       try {
  924.         // Try using a default details URL supplied by the distribution
  925.         // if the update XML does not supply one.
  926.         var formatter = Components.classes["@mozilla.org/toolkit/URLFormatterService;1"]
  927.                                   .getService(Components.interfaces.nsIURLFormatter);
  928.         return formatter.formatURLPref(PREF_APP_UPDATE_URL_DETAILS);
  929.       }
  930.       catch (e) {
  931.       }
  932.     }
  933.     return this._detailsURL || "";
  934.   },
  935.   
  936.   /**
  937.    * See nsIUpdateService.idl
  938.    */
  939.   serialize: function(updates) {
  940.     var update = updates.createElementNS(URI_UPDATE_NS, "update");
  941.     update.setAttribute("type", this.type);
  942.     update.setAttribute("name", this.name);
  943.     update.setAttribute("version", this.version);
  944.     update.setAttribute("extensionVersion", this.extensionVersion);
  945.     update.setAttribute("detailsURL", this.detailsURL);
  946.     update.setAttribute("licenseURL", this.licenseURL);
  947.     update.setAttribute("serviceURL", this.serviceURL);
  948.     update.setAttribute("installDate", this.installDate);
  949.     update.setAttribute("statusText", this.statusText);
  950.     update.setAttribute("buildID", this.buildID);
  951.     update.setAttribute("isCompleteUpdate", this.isCompleteUpdate);
  952.     update.setAttribute("channel", this.channel);
  953.     updates.documentElement.appendChild(update);
  954.     
  955.     for (var p in this._properties) {
  956.       if (this._properties[p].present)
  957.         update.setAttribute(p, this._properties[p].data);
  958.     }
  959.     
  960.     for (var i = 0; i < this.patchCount; ++i)
  961.       update.appendChild(this.getPatchAt(i).serialize(updates));
  962.     
  963.     return update;
  964.   },
  965.    
  966.   /**
  967.    * A hash of custom properties
  968.    */
  969.   _properties: null,
  970.   
  971.   /**
  972.    * See nsIWritablePropertyBag.idl
  973.    */
  974.   setProperty: function(name, value) {
  975.     this._properties[name] = { data: value, present: true };
  976.   },
  977.   
  978.   /**
  979.    * See nsIWritablePropertyBag.idl
  980.    */
  981.   deleteProperty: function(name) {
  982.     if (name in this._properties)
  983.       this._properties[name].present = false;
  984.     else
  985.       throw Components.results.NS_ERROR_FAILURE;
  986.   },
  987.   
  988.   /**
  989.    * See nsIPropertyBag.idl
  990.    */
  991.   get enumerator() {
  992.     var properties = [];
  993.     for (var p in this._properties)
  994.       properties.push(this._properties[p].data);
  995.     return new ArrayEnumerator(properties);
  996.   },
  997.   
  998.   /**
  999.    * See nsIPropertyBag.idl
  1000.    */
  1001.   getProperty: function(name) {
  1002.     if (name in this._properties &&
  1003.         this._properties[name].present)
  1004.       return this._properties[name].data;
  1005.     throw Components.results.NS_ERROR_FAILURE;
  1006.   },
  1007.   
  1008.   /**
  1009.    * See nsISupports.idl
  1010.    */
  1011.   QueryInterface: function(iid) {
  1012.     if (!iid.equals(Components.interfaces.nsIUpdate_MOZILLA_1_8_BRANCH) &&
  1013.         !iid.equals(Components.interfaces.nsIUpdate) &&
  1014.         !iid.equals(Components.interfaces.nsIPropertyBag) &&
  1015.         !iid.equals(Components.interfaces.nsIWritablePropertyBag) &&
  1016.         !iid.equals(Components.interfaces.nsISupports))
  1017.       throw Components.results.NS_ERROR_NO_INTERFACE;
  1018.     return this;
  1019.   }
  1020. }; 
  1021.  
  1022. /**
  1023.  * UpdateService
  1024.  * A Service for managing the discovery and installation of software updates.
  1025.  * @constructor
  1026.  */
  1027. function UpdateService() {
  1028.   gApp  = Components.classes["@mozilla.org/xre/app-info;1"]
  1029.                     .getService(Components.interfaces.nsIXULAppInfo)
  1030.                     .QueryInterface(Components.interfaces.nsIXULRuntime);
  1031.   gPref = Components.classes["@mozilla.org/preferences-service;1"]
  1032.                     .getService(Components.interfaces.nsIPrefBranch2);
  1033.   gConsole = Components.classes["@mozilla.org/consoleservice;1"]
  1034.                        .getService(Components.interfaces.nsIConsoleService);  
  1035.  
  1036.   // Not all builds have a known ABI
  1037.   try {
  1038.     gABI = gApp.XPCOMABI;
  1039.   }
  1040.   catch (e) {
  1041.     LOG("UpdateService", "XPCOM ABI unknown: updates are not possible.");
  1042.   }
  1043.  
  1044.   try {
  1045.     var sysInfo = 
  1046.       Components.classes["@mozilla.org/system-info;1"]
  1047.                 .getService(Components.interfaces.nsIPropertyBag2);
  1048.  
  1049.     gOSVersion = encodeURIComponent(sysInfo.getProperty("name") + " " +  
  1050.                                     sysInfo.getProperty("version"));
  1051.   }
  1052.   catch (e) {
  1053.     LOG("UpdateService", "OS Version unknown: updates are not possible.");
  1054.   }
  1055.  
  1056. //@line 1026 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-Release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  1057.  
  1058.   // Start the update timer only after a profile has been selected so that the
  1059.   // appropriate values for the update check are read from the user's profile.  
  1060.   var os = getObserverService();
  1061.  
  1062.   os.addObserver(this, "profile-after-change", false);
  1063.  
  1064.   // Observe xpcom-shutdown to unhook pref branch observers above to avoid 
  1065.   // shutdown leaks.
  1066.   os.addObserver(this, "xpcom-shutdown", false);
  1067. }
  1068.  
  1069. UpdateService.prototype = {
  1070.   /**
  1071.    * The downloader we are using to download updates. There is only ever one of
  1072.    * these.
  1073.    */
  1074.   _downloader: null,
  1075.  
  1076.   /**
  1077.    * Handle Observer Service notifications
  1078.    * @param   subject
  1079.    *          The subject of the notification
  1080.    * @param   topic
  1081.    *          The notification name
  1082.    * @param   data
  1083.    *          Additional data
  1084.    */
  1085.   observe: function(subject, topic, data) {
  1086.     var os = getObserverService();
  1087.  
  1088.     switch (topic) {
  1089.     case "profile-after-change":
  1090.       os.removeObserver(this, "profile-after-change");
  1091.       this._start();
  1092.       break;
  1093.     case "xpcom-shutdown":
  1094.       os.removeObserver(this, "xpcom-shutdown");
  1095.       
  1096.       // Release Services
  1097.       gApp      = null;
  1098.       gPref     = null;
  1099.       gConsole  = null;
  1100.       break;
  1101.     }
  1102.   },
  1103.   
  1104.   /**
  1105.    * Start the Update Service
  1106.    */
  1107.   _start: function() {
  1108.     // Start logging
  1109.     this._initLoggingPrefs();
  1110.     
  1111.     // Clean up any extant updates
  1112.     this._postUpdateProcessing();
  1113.  
  1114.     // Register a background update check timer
  1115.     var tm = 
  1116.         Components.classes["@mozilla.org/updates/timer-manager;1"]
  1117.                   .getService(Components.interfaces.nsIUpdateTimerManager);
  1118.     var interval = getPref("getIntPref", PREF_APP_UPDATE_INTERVAL, 86400);
  1119.     tm.registerTimer("background-update-timer", this, interval);
  1120.  
  1121.     // Resume fetching...
  1122.     var um = Components.classes["@mozilla.org/updates/update-manager;1"]
  1123.                         .getService(Components.interfaces.nsIUpdateManager);
  1124.     var activeUpdate = um.activeUpdate;
  1125.     if (activeUpdate) {
  1126.       var status = this.downloadUpdate(activeUpdate, true);
  1127.       if (status == STATE_NONE)
  1128.         cleanupActiveUpdate();
  1129.     }
  1130.   },
  1131.   
  1132.   /**
  1133.    * Perform post-processing on updates lingering in the updates directory
  1134.    * from a previous browser session - either report install failures (and
  1135.    * optionally attempt to fetch a different version if appropriate) or 
  1136.    * notify the user of install success.
  1137.    */
  1138.   _postUpdateProcessing: function() {
  1139.     // Detect installation failures and notify
  1140.     
  1141.     // Bail out if we don't have appropriate permissions
  1142.     if (!this.canUpdate)
  1143.       return;
  1144.       
  1145.     var status = readStatusFile(getUpdatesDir()); 
  1146.  
  1147.     // Make sure to cleanup after an update that failed for an unknown reason
  1148.     if (status == "null")
  1149.       status = null;
  1150.  
  1151.     var updRootKey = null;
  1152. //@line 1122 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-Release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  1153.     function findPreviousUpdate(key) {
  1154.       var updateDir = getUpdatesDir(key);
  1155.       if (updateDir.exists()) {
  1156.         status = readStatusFile(updateDir);
  1157.         // Previous download should succeed. Otherwise, we will not be here!
  1158.         if (status == STATE_SUCCEEDED)
  1159.           updRootKey = key;
  1160.         else
  1161.           status = null;
  1162.       }
  1163.     }
  1164.  
  1165.     // required when updating from Fx 2.0.0.1 to 2.0.0.3 (or later)
  1166.     // on Windows Vista.
  1167.     if (status == null)
  1168.       findPreviousUpdate(KEY_UAPPDATA);
  1169.  
  1170.     // required to migrate from older versions.
  1171.     if (status == null)
  1172.       findPreviousUpdate(KEY_APPDIR);
  1173. //@line 1143 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-Release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  1174.  
  1175.     if (status == STATE_DOWNLOADING) {
  1176.       LOG("UpdateService", "_postUpdateProcessing: Downloading patch, resuming...");
  1177.     }
  1178.     else if (status != null) {
  1179.       // null status means the update.status file is not present, because either:
  1180.       // 1) no update was performed, and so there's no UI to show
  1181.       // 2) an update was attempted but failed during checking, transfer or 
  1182.       //    verification, and was cleaned up at that point, and UI notifying of
  1183.       //    that error was shown at that stage. 
  1184.       var um = 
  1185.           Components.classes["@mozilla.org/updates/update-manager;1"].
  1186.           getService(Components.interfaces.nsIUpdateManager);
  1187.       var prompter = 
  1188.           Components.classes["@mozilla.org/updates/update-prompt;1"].
  1189.           createInstance(Components.interfaces.nsIUpdatePrompt);
  1190.  
  1191.       var shouldCleanup = true;
  1192.       var update = um.activeUpdate;
  1193.       if (!update) {
  1194.         update = new Update(null);
  1195.       }
  1196.       update.state = status;
  1197.       var sbs = 
  1198.           Components.classes["@mozilla.org/intl/stringbundle;1"].
  1199.           getService(Components.interfaces.nsIStringBundleService);
  1200.       var bundle = sbs.createBundle(URI_UPDATES_PROPERTIES);
  1201.       if (status == STATE_SUCCEEDED) {
  1202.         update.statusText = bundle.GetStringFromName("installSuccess");
  1203.         
  1204.         // Dig through the update history to find the patch that was just
  1205.         // installed and update its metadata.
  1206.         for (var i = 0; i < um.updateCount; ++i) {
  1207.           var umUpdate = um.getUpdateAt(i);
  1208.           if (umUpdate && umUpdate.version == update.version &&
  1209.                           umUpdate.buildID == update.buildID) {
  1210.             umUpdate.statusText = update.statusText;
  1211.             break;
  1212.           }
  1213.         }
  1214.  
  1215.         LOG("UpdateService", "_postUpdateProcessing: Install Succeeded, Showing UI");
  1216.         prompter.showUpdateInstalled(update);
  1217. //@line 1190 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-Release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  1218.         // Perform platform-specific post-update processing.
  1219.         if (POST_UPDATE_CONTRACTID in Components.classes) {
  1220.           Components.classes[POST_UPDATE_CONTRACTID].
  1221.               createInstance(Components.interfaces.nsIRunnable).run();
  1222.         }
  1223. //@line 1196 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-Release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  1224.  
  1225.         // Done with this update. Clean it up.
  1226.         cleanupActiveUpdate(updRootKey);
  1227.       }
  1228.       else {
  1229.         // If we hit an error, then the error code will be included in the
  1230.         // status string following a colon.  If we had an I/O error, then we
  1231.         // assume that the patch is not invalid, and we restage the patch so
  1232.         // that it can be attempted again the next time we restart.
  1233.         var ary = status.split(": ");
  1234.         update.state = ary[0];
  1235.         if (update.state == STATE_FAILED && ary[1]) {
  1236.           update.errorCode = ary[1];
  1237.           if (update.errorCode == WRITE_ERROR) {
  1238.             prompter.showUpdateError(update);
  1239.             writeStatusFile(getUpdatesDir(), update.state = STATE_PENDING);
  1240.             return;
  1241.           }
  1242.         }
  1243.  
  1244.         // Something went wrong with the patch application process.
  1245.         cleanupActiveUpdate();
  1246.  
  1247.         update.statusText = bundle.GetStringFromName("patchApplyFailure");
  1248.         var oldType = update.selectedPatch ? update.selectedPatch.type 
  1249.                                            : "complete";
  1250.         if (update.selectedPatch && oldType == "partial") {
  1251.           // Partial patch application failed, try downloading the complete
  1252.           // update in the background instead.
  1253.           LOG("UpdateService", "_postUpdateProcessing: Install of Partial Patch " + 
  1254.               "failed, downloading Complete Patch and maybe showing UI");
  1255.           var status = this.downloadUpdate(update, true);
  1256.           if (status == STATE_NONE)
  1257.             cleanupActiveUpdate();
  1258.         }
  1259.         else {
  1260.           LOG("UpdateService", "_postUpdateProcessing: Install of Complete or " + 
  1261.               "only patch failed. Showing error.");
  1262.         }
  1263.         update.QueryInterface(Components.interfaces.nsIWritablePropertyBag);
  1264.         update.setProperty("patchingFailed", oldType);
  1265.         prompter.showUpdateError(update);
  1266.       }
  1267.     }
  1268.     else {
  1269.       LOG("UpdateService", "_postUpdateProcessing: No Status, No Update");
  1270.     }
  1271.   },
  1272.  
  1273.   /**
  1274.    * Initialize Logging preferences, formatted like so:
  1275.    *  app.update.log.<moduleName> = <true|false>
  1276.    */
  1277.   _initLoggingPrefs: function() {
  1278.     try {
  1279.       var ps = Components.classes["@mozilla.org/preferences-service;1"]
  1280.                         .getService(Components.interfaces.nsIPrefService);
  1281.       var logBranch = ps.getBranch(PREF_APP_UPDATE_LOG_BRANCH);
  1282.       var modules = logBranch.getChildList("", { value: 0 });
  1283.  
  1284.       for (var i = 0; i < modules.length; ++i) {
  1285.         if (logBranch.prefHasUserValue(modules[i]))
  1286.           gLogEnabled[modules[i]] = logBranch.getBoolPref(modules[i]);
  1287.       }
  1288.     }
  1289.     catch (e) {
  1290.     }
  1291.   },
  1292.   
  1293.   /**
  1294.    *
  1295.    */
  1296.   _needsToPromptForUpdate: function(updates) {
  1297.     // First, check for Extension incompatibilities. These trump any preference
  1298.     // settings.
  1299.     var em = Components.classes["@mozilla.org/extensions/manager;1"]
  1300.                        .getService(Components.interfaces.nsIExtensionManager);
  1301.     var incompatibleList = { };
  1302.     for (var i = 0; i < updates.length; ++i) {
  1303.       var count = {};
  1304.       em.getIncompatibleItemList(gApp.ID, updates[i].extensionVersion,
  1305.                                  nsIUpdateItem.TYPE_ADDON, false, count);
  1306.       if (count.value > 0)
  1307.         return true;
  1308.     }
  1309.  
  1310.     // Now, inspect user preferences.
  1311.     
  1312.     // No prompt necessary, silently update...
  1313.     return false;
  1314.   },
  1315.   
  1316.   /**
  1317.    * Notified when a timer fires
  1318.    * @param   timer
  1319.    *          The timer that fired
  1320.    */
  1321.   notify: function(timer) {
  1322.     // If a download is in progress, then do nothing.
  1323.     if (this.isDownloading || this._downloader && this._downloader.patchIsStaged)
  1324.       return;
  1325.  
  1326.     var self = this;
  1327.     var listener = {
  1328.       /**
  1329.        * See nsIUpdateService.idl
  1330.        */
  1331.       onProgress: function(request, position, totalSize) { 
  1332.       },
  1333.       
  1334.       /**
  1335.        * See nsIUpdateService.idl
  1336.        */
  1337.       onCheckComplete: function(request, updates, updateCount) {
  1338.         self._selectAndInstallUpdate(updates);
  1339.       },
  1340.  
  1341.       /**
  1342.        * See nsIUpdateService.idl
  1343.        */
  1344.       onError: function(request, update) { 
  1345.         LOG("Checker", "Error during background update: " + update.statusText);
  1346.       },
  1347.     }
  1348.     this.backgroundChecker.checkForUpdates(listener, false);
  1349.   },
  1350.   
  1351.   /**
  1352.    * Determine whether or not an update requires user confirmation before it
  1353.    * can be installed.
  1354.    * @param   update
  1355.    *          The update to be installed
  1356.    * @returns true if a prompt UI should be shown asking the user if they want
  1357.    *          to install the update, false if the update should just be 
  1358.    *          silently downloaded and installed.
  1359.    */
  1360.   _shouldPrompt: function(update) {
  1361.     // There are two possible outcomes here:
  1362.     // 1. download and install the update automatically
  1363.     // 2. alert the user about the presence of an update before doing anything
  1364.     //
  1365.     // The outcome we follow is determined as follows:
  1366.     // 
  1367.     // Note:  all Major updates require notification and confirmation
  1368.     // 
  1369.     // Update Type      Mode      Incompatible    Outcome
  1370.     // Major            0         Yes or No       Notify and Confirm
  1371.     // Major            1         No              Notify and Confirm
  1372.     // Major            1         Yes             Notify and Confirm
  1373.     // Major            2         Yes or No       Notify and Confirm
  1374.     // Minor            0         Yes or No       Auto Install
  1375.     // Minor            1         No              Auto Install
  1376.     // Minor            1         Yes             Notify and Confirm
  1377.     // Minor            2         No              Auto Install
  1378.     // Minor            2         Yes             Notify and Confirm
  1379.     //
  1380.     // In addition, if there is a license associated with an update, regardless
  1381.     // of type it must be agreed to. 
  1382.     //
  1383.     // If app.update.enabled is set to false, an update check is not performed
  1384.     // at all, and so none of the decision making above is entered into.
  1385.     //
  1386.     if (update.type == "major") {
  1387.       LOG("Checker", "_shouldPrompt: Prompting because it is a major update");
  1388.       return true;
  1389.     }
  1390.  
  1391.     update.QueryInterface(Components.interfaces.nsIPropertyBag);
  1392.     try {
  1393.       var licenseAccepted = update.getProperty("licenseAccepted") == "true";
  1394.     }
  1395.     catch (e) {
  1396.       licenseAccepted = false;
  1397.     }
  1398.  
  1399.     var updateEnabled = getPref("getBoolPref", PREF_APP_UPDATE_ENABLED, true);
  1400.     if (!updateEnabled) {
  1401.       LOG("Checker", "_shouldPrompt: Not prompting because update is " + 
  1402.           "disabled");
  1403.       return false;
  1404.     }
  1405.     
  1406.     // User has turned off automatic download and install
  1407.     var autoEnabled = getPref("getBoolPref", PREF_APP_UPDATE_AUTO, true);
  1408.     if (!autoEnabled) {
  1409.       LOG("Checker", "_shouldPrompt: Prompting because auto install is disabled");
  1410.       return true;
  1411.     }
  1412.     
  1413.     switch (getPref("getIntPref", PREF_APP_UPDATE_MODE, 1)) {
  1414.     case 1:
  1415.       // Mode 1 is do not prompt only if there are no incompatibilities
  1416.       // releases
  1417.       LOG("Checker", "_shouldPrompt: Prompting if there are incompatibilities");
  1418.       return !isCompatible(update);
  1419.     case 2:
  1420.       // Mode 2 is do not prompt only if there are no incompatibilities
  1421.       LOG("Checker", "_shouldPrompt: Prompting if there are incompatibilities");
  1422.       return !isCompatible(update);
  1423.     }
  1424.     // Mode 0 is do not prompt regardless of incompatibilities
  1425.     LOG("Checker", "_shouldPrompt: Not prompting the user - they choose to " +
  1426.         "ignore incompatibilities");
  1427.     return false;
  1428.   },
  1429.   
  1430.   /**
  1431.    * Determine which of the specified updates should be installed.
  1432.    * @param   updates
  1433.    *          An array of available updates
  1434.    */
  1435.   selectUpdate: function(updates) {
  1436.     if (updates.length == 0)
  1437.       return null;
  1438.     
  1439.     // Choose the newest of the available minor and major updates. 
  1440.     var majorUpdate = null, minorUpdate = null;
  1441.     var newestMinor = updates[0], newestMajor = updates[0];
  1442.  
  1443.     var vc = Components.classes["@mozilla.org/xpcom/version-comparator;1"]
  1444.                        .getService(Components.interfaces.nsIVersionComparator);
  1445.     for (var i = 0; i < updates.length; ++i) {
  1446.       if (updates[i].type == "major" && 
  1447.           vc.compare(newestMajor.version, updates[i].version) <= 0)
  1448.         majorUpdate = newestMajor = updates[i];
  1449.       if (updates[i].type == "minor" && 
  1450.           vc.compare(newestMinor.version, updates[i].version) <= 0)
  1451.         minorUpdate = newestMinor = updates[i];
  1452.     }
  1453.  
  1454.     // IMPORTANT
  1455.     // If there's a minor update, always try and fetch that one first, 
  1456.     // otherwise use the newest major update.
  1457.     // selectUpdate() only returns one update.
  1458.     // if major were to trump minor, and we said "never" to the major
  1459.     // we'd never get the minor update, since selectUpdate()
  1460.     // would return the major update that the user said "never" to
  1461.     // (shadowing the important minor update with security fixes)
  1462.     return minorUpdate || majorUpdate;
  1463.   },
  1464.   
  1465.   /**
  1466.    * Determine which of the specified updates should be installed and
  1467.    * begin the download/installation process, optionally prompting the
  1468.    * user for permission if required.
  1469.    * @param   updates
  1470.    *          An array of available updates
  1471.    */
  1472.   _selectAndInstallUpdate: function(updates) {
  1473.     // Don't prompt if there's an active update - the user is already 
  1474.     // aware and is downloading, or performed some user action to prevent
  1475.     // notification.
  1476.     var um = Components.classes["@mozilla.org/updates/update-manager;1"]
  1477.                        .getService(Components.interfaces.nsIUpdateManager);
  1478.     if (um.activeUpdate)
  1479.       return;
  1480.     
  1481.     var update = this.selectUpdate(updates, updates.length);
  1482.     if (!update)
  1483.       return;
  1484.  
  1485.     // check if the user said "never" to this version
  1486.     // this check is done here, and not in selectUpdate() so that
  1487.     // the user can get an upgrade they said "never" to if they
  1488.     // manually do "Check for Updates..."
  1489.     // note, selectUpdate() only returns one update.
  1490.     // but in selectUpdate(), minor updates trump major updates
  1491.     // if major trumps minor, and we said "never" to the major
  1492.     // we'd never see the minor update.
  1493.     // 
  1494.     // note, the never decision should only apply to major updates
  1495.     // see bug #350636 for a scenario where this could potentially
  1496.     // be an issue
  1497.     var neverPrefName = PREF_UPDATE_NEVER_BRANCH + update.version;
  1498.     var never = getPref("getBoolPref", neverPrefName, false);
  1499.     if (never && update.type == "major")
  1500.       return;
  1501.  
  1502.     if (this._shouldPrompt(update))
  1503.       showPromptIfNoIncompatibilities(update);
  1504.     else {
  1505.       LOG("UpdateService", "_selectAndInstallUpdate: No need to show prompt, just download update");
  1506.       var status = this.downloadUpdate(update, true);
  1507.       if (status == STATE_NONE)
  1508.         cleanupActiveUpdate();
  1509.     }
  1510.   },
  1511.  
  1512.   /**
  1513.    * The Checker used for background update checks.
  1514.    */
  1515.   _backgroundChecker: null,
  1516.   
  1517.   /**
  1518.    * See nsIUpdateService.idl
  1519.    */
  1520.   get backgroundChecker() {
  1521.     if (!this._backgroundChecker) 
  1522.       this._backgroundChecker = new Checker();
  1523.     return this._backgroundChecker;
  1524.   },
  1525.   
  1526.   /**
  1527.    * See nsIUpdateService.idl
  1528.    */
  1529.   get canUpdate() {
  1530.     try {
  1531.       var appDirFile = getUpdateFile([FILE_PERMS_TEST]);
  1532.       LOG("UpdateService", "canUpdate?  testing " + appDirFile.path);
  1533.       if (!appDirFile.exists()) {
  1534.         appDirFile.create(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1535.         appDirFile.remove(false);
  1536.       }
  1537.       var updateDir = getUpdatesDir();
  1538.       var upDirFile = updateDir.clone();
  1539.       upDirFile.append(FILE_PERMS_TEST);
  1540.       LOG("UpdateService", "canUpdate?  testing " + upDirFile.path);
  1541.       if (!upDirFile.exists()) {
  1542.         upDirFile.create(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1543.         upDirFile.remove(false);
  1544.       }
  1545. //@line 1518 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-Release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  1546.       var sysInfo = 
  1547.         Components.classes["@mozilla.org/system-info;1"]
  1548.                   .getService(Components.interfaces.nsIPropertyBag2);
  1549.   
  1550.       // On Windows, we no longer store the update under the app dir
  1551.       // if the app dir is under C:\Program Files. 
  1552.       //
  1553.       // If we are on Windows, but not Vista, we need to check that
  1554.       // we can create and remove files from the actual app directory
  1555.       // (like C:\Program Files\Mozilla Firefox).  If we can't,
  1556.       // because this user is not an adminstrator, for example
  1557.       // canUpdate() should return false (like it used to).
  1558.       // 
  1559.       // For Vista, don't perform this check because non-admin users
  1560.       // can update firefox (by granting the updater access via the 
  1561.       // UAC prompt)
  1562.       var windowsVersion = sysInfo.getProperty("version");
  1563.       LOG("UpdateService", "canUpdate?  version = " + windowsVersion);
  1564.       // Example windowsVersion:  Windows XP == 5.1
  1565.       if (parseFloat(windowsVersion) < 6) {
  1566.         var actualAppDir = getDir(KEY_APPDIR, []);
  1567.         var actualAppDirFile = actualAppDir.clone();
  1568.         actualAppDirFile.append(FILE_PERMS_TEST);
  1569.         LOG("UpdateService", "canUpdate?  testing " + actualAppDirFile.path);
  1570.         if (!actualAppDirFile.exists()) {
  1571.           actualAppDirFile.create(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1572.           actualAppDirFile.remove(false);
  1573.         }
  1574.       }
  1575. //@line 1548 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-Release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  1576.     }
  1577.     catch (e) {
  1578.        LOG("UpdateService", "can't update, no privileges: " + e);
  1579.       // No write privileges to install directory
  1580.       return false;
  1581.     }
  1582.     // If the administrator has locked the app update functionality 
  1583.     // OFF - this is not just a user setting, so disable the manual
  1584.     // UI too.
  1585.     var enabled = getPref("getBoolPref", PREF_APP_UPDATE_ENABLED, true);
  1586.     if (!enabled && gPref.prefIsLocked(PREF_APP_UPDATE_ENABLED)) {
  1587.       LOG("UpdateService", "can't update, disabled by pref");
  1588.       return false;
  1589.     }
  1590.  
  1591.     // If we don't know the binary platform we're updating, we can't update.
  1592.     if (!gABI) {
  1593.       LOG("UpdateService", "can't update, unknown ABI");
  1594.       return false;
  1595.     }
  1596.  
  1597.     // If we don't know the OS version we're updating, we can't update.
  1598.     if (!gOSVersion) {
  1599.       LOG("UpdateService", "can't update, unknown OS version");
  1600.       return false;
  1601.     }
  1602.  
  1603.     LOG("UpdateService", "can update");
  1604.     return true;
  1605.   },
  1606.   
  1607.   /**
  1608.    * See nsIUpdateService.idl
  1609.    */
  1610.   addDownloadListener: function(listener) {
  1611.     if (!this._downloader) {
  1612.       LOG("UpdateService", "addDownloadListener: no downloader!\n");
  1613.       return;
  1614.     }
  1615.     this._downloader.addDownloadListener(listener);
  1616.   },
  1617.   
  1618.   /**
  1619.    * See nsIUpdateService.idl
  1620.    */
  1621.   removeDownloadListener: function(listener) {
  1622.     if (!this._downloader) {
  1623.       LOG("UpdateService", "removeDownloadListener: no downloader!\n");
  1624.       return;
  1625.     }
  1626.     this._downloader.removeDownloadListener(listener);
  1627.   },
  1628.   
  1629.   /**
  1630.    * See nsIUpdateService.idl
  1631.    */
  1632.   downloadUpdate: function(update, background) {
  1633.     if (!update)
  1634.       throw Components.results.NS_ERROR_NULL_POINTER;
  1635.     if (this.isDownloading) {
  1636.       if (update.isCompleteUpdate == this._downloader.isCompleteUpdate &&
  1637.           background == this._downloader.background) {
  1638.         LOG("UpdateService", "no support for downloading more than one update at a time");
  1639.         return readStatusFile(getUpdatesDir());
  1640.       }
  1641.       this._downloader.cancel();
  1642.     }
  1643.     this._downloader = new Downloader(background);
  1644.     return this._downloader.downloadUpdate(update);
  1645.   },
  1646.   
  1647.   /**
  1648.    * See nsIUpdateService.idl
  1649.    */
  1650.   pauseDownload: function() {
  1651.     if (this.isDownloading)
  1652.       this._downloader.cancel();
  1653.   },
  1654.   
  1655.   /**
  1656.    * See nsIUpdateService.idl
  1657.    */
  1658.   get isDownloading() {
  1659.     return this._downloader && this._downloader.isBusy;
  1660.   },
  1661.   
  1662.   /**
  1663.    * See nsISupports.idl
  1664.    */
  1665.   QueryInterface: function(iid) {
  1666.     if (!iid.equals(Components.interfaces.nsIApplicationUpdateService) &&
  1667.         !iid.equals(Components.interfaces.nsITimerCallback) && 
  1668.         !iid.equals(Components.interfaces.nsIObserver) && 
  1669.         !iid.equals(Components.interfaces.nsISupports))
  1670.       throw Components.results.NS_ERROR_NO_INTERFACE;
  1671.     return this;
  1672.   }
  1673. };
  1674.  
  1675. /**
  1676.  * A service to manage active and past updates.
  1677.  * @constructor
  1678.  */
  1679. function UpdateManager() {
  1680.   // Ensure the Active Update file is loaded
  1681.   var updates = this._loadXMLFileIntoArray(getUpdateFile([FILE_UPDATE_ACTIVE]));
  1682.   if (updates.length > 0)
  1683.     this._activeUpdate = updates[0];
  1684. }
  1685. UpdateManager.prototype = {
  1686.   /**
  1687.    * All previously downloaded and installed updates, as an array of nsIUpdate
  1688.    * objects.
  1689.    */
  1690.   _updates: null,
  1691.   
  1692.   /**
  1693.    * The current actively downloading/installing update, as a nsIUpdate object.
  1694.    */
  1695.   _activeUpdate: null,
  1696.   
  1697.   /**
  1698.    * Loads an updates.xml formatted file into an array of nsIUpdate items.
  1699.    * @param   file
  1700.    *          A nsIFile for the updates.xml file
  1701.    * @returns The array of nsIUpdate items held in the file.
  1702.    */
  1703.   _loadXMLFileIntoArray: function(file) {
  1704.     if (!file.exists()) {
  1705.       LOG("UpdateManager", "_loadXMLFileIntoArray: XML File does not exist");
  1706.       return [];
  1707.     }
  1708.  
  1709.     var result = [];
  1710.     var fileStream = Components.classes["@mozilla.org/network/file-input-stream;1"]
  1711.                                .createInstance(Components.interfaces.nsIFileInputStream);
  1712.     fileStream.init(file, MODE_RDONLY, PERMS_FILE, 0);
  1713.     try {
  1714.       var parser = Components.classes["@mozilla.org/xmlextras/domparser;1"]
  1715.                             .createInstance(Components.interfaces.nsIDOMParser);
  1716.       var doc = parser.parseFromStream(fileStream, "UTF-8", fileStream.available(), "text/xml");
  1717.       
  1718.       var updateCount = doc.documentElement.childNodes.length;
  1719.       for (var i = 0; i < updateCount; ++i) {
  1720.         var updateElement = doc.documentElement.childNodes.item(i);
  1721.         if (updateElement.nodeType != Node.ELEMENT_NODE ||
  1722.             updateElement.localName != "update")
  1723.           continue;
  1724.  
  1725.         updateElement.QueryInterface(Components.interfaces.nsIDOMElement);
  1726.         try {
  1727.           var update = new Update(updateElement);
  1728.         } catch (e) {
  1729.           LOG("UpdateManager", "_loadXMLFileIntoArray: invalid update");
  1730.           continue;
  1731.         }
  1732.         result.push(new Update(updateElement));
  1733.       }
  1734.     }
  1735.     catch (e) {
  1736.       LOG("UpdateManager", "_loadXMLFileIntoArray: Error constructing update list " + 
  1737.           e);
  1738.     }
  1739.     fileStream.close();
  1740.     return result;
  1741.   },
  1742.   
  1743.   /**
  1744.    * Load the update manager, initializing state from state files.
  1745.    */
  1746.   _ensureUpdates: function() {
  1747.     if (!this._updates) {
  1748.       this._updates = this._loadXMLFileIntoArray(getUpdateFile(
  1749.                         [FILE_UPDATES_DB]));
  1750.  
  1751.       // Make sure that any active update is part of our updates list
  1752.       var active = this.activeUpdate;
  1753.       if (active)
  1754.         this._addUpdate(active);
  1755.     }
  1756.   },
  1757.  
  1758.   /**
  1759.    * See nsIUpdateService.idl
  1760.    */
  1761.   getUpdateAt: function(index) {
  1762.     this._ensureUpdates();
  1763.     return this._updates[index];
  1764.   },
  1765.   
  1766.   /**
  1767.    * See nsIUpdateService.idl
  1768.    */
  1769.   get updateCount() {
  1770.     this._ensureUpdates();
  1771.     return this._updates.length;
  1772.   },
  1773.   
  1774.   /**
  1775.    * See nsIUpdateService.idl
  1776.    */
  1777.   get activeUpdate() {
  1778.     if (this._activeUpdate) {
  1779.       this._activeUpdate.QueryInterface(Components.interfaces.nsIUpdate_MOZILLA_1_8_BRANCH);
  1780.       if (this._activeUpdate.channel != getUpdateChannel()) {
  1781.         // User switched channels, clear out any old active updates and remove
  1782.         // partial downloads
  1783.         this._activeUpdate = null;
  1784.       
  1785.         // Destroy the updates directory, since we're done with it.
  1786.         cleanUpUpdatesDir();
  1787.       }
  1788.     }
  1789.     return this._activeUpdate;
  1790.   },
  1791.   set activeUpdate(activeUpdate) {
  1792.     this._addUpdate(activeUpdate);
  1793.     this._activeUpdate = activeUpdate;
  1794.     if (!activeUpdate) {
  1795.       // If |activeUpdate| is null, we have updated both lists - the active list
  1796.       // and the history list, so we want to write both files.
  1797.       this.saveUpdates();
  1798.     }
  1799.     else
  1800.       this._writeUpdatesToXMLFile([this._activeUpdate], 
  1801.                                   getUpdateFile([FILE_UPDATE_ACTIVE]));
  1802.     return activeUpdate;
  1803.   },
  1804.   
  1805.   /**
  1806.    * Add an update to the Updates list. If the item already exists in the list,
  1807.    * replace the existing value with the new value.
  1808.    * @param   update
  1809.    *          The nsIUpdate object to add.
  1810.    */
  1811.   _addUpdate: function(update) {
  1812.     if (!update)
  1813.       return;
  1814.     this._ensureUpdates();
  1815.     if (this._updates) {
  1816.       for (var i = 0; i < this._updates.length; ++i) {
  1817.         if (this._updates[i] &&
  1818.             this._updates[i].version == update.version &&
  1819.             this._updates[i].buildID == update.buildID) {
  1820.           // Replace the existing entry with the new value, updating
  1821.           // all metadata.
  1822.           this._updates[i] = update;
  1823.           return;
  1824.         }
  1825.       }
  1826.     }
  1827.     // Otherwise add it to the front of the list.
  1828.     if (update) 
  1829.       this._updates = [update].concat(this._updates);
  1830.   },
  1831.   
  1832.   /**
  1833.    * Serializes an array of updates to an XML file
  1834.    * @param   updates
  1835.    *          An array of nsIUpdate objects
  1836.    * @param   file
  1837.    *          The nsIFile object to serialize to
  1838.    */
  1839.   _writeUpdatesToXMLFile: function(updates, file) {
  1840.     var fos = Components.classes["@mozilla.org/network/safe-file-output-stream;1"]
  1841.                         .createInstance(Components.interfaces.nsIFileOutputStream);
  1842.     var modeFlags = MODE_WRONLY | MODE_CREATE | MODE_TRUNCATE;
  1843.     if (!file.exists()) 
  1844.       file.create(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1845.     fos.init(file, modeFlags, PERMS_FILE, 0);
  1846.     
  1847.     try {
  1848.       var parser = Components.classes["@mozilla.org/xmlextras/domparser;1"]
  1849.                             .createInstance(Components.interfaces.nsIDOMParser);
  1850.       const EMPTY_UPDATES_DOCUMENT = "<?xml version=\"1.0\"?><updates xmlns=\"http://www.mozilla.org/2005/app-update\"></updates>";
  1851.       var doc = parser.parseFromString(EMPTY_UPDATES_DOCUMENT, "text/xml");
  1852.  
  1853.       for (var i = 0; i < updates.length; ++i) {
  1854.         if (updates[i])
  1855.           doc.documentElement.appendChild(updates[i].serialize(doc));
  1856.       }
  1857.  
  1858.       var serializer = Components.classes["@mozilla.org/xmlextras/xmlserializer;1"]
  1859.                                 .createInstance(Components.interfaces.nsIDOMSerializer);
  1860.       serializer.serializeToStream(doc.documentElement, fos, null);
  1861.     }
  1862.     catch (e) {
  1863.     }
  1864.     
  1865.     closeSafeOutputStream(fos);
  1866.   },
  1867.  
  1868.   /**
  1869.    * See nsIUpdateService.idl
  1870.    */
  1871.   saveUpdates: function() {
  1872.     this._writeUpdatesToXMLFile([this._activeUpdate], 
  1873.                                 getUpdateFile([FILE_UPDATE_ACTIVE]));
  1874.     if (this._updates) {
  1875.       this._writeUpdatesToXMLFile(this._updates, 
  1876.                                   getUpdateFile([FILE_UPDATES_DB]));
  1877.     }
  1878.   },
  1879.   
  1880.   /**
  1881.    * See nsISupports.idl
  1882.    */
  1883.   QueryInterface: function(iid) {
  1884.     if (!iid.equals(Components.interfaces.nsIUpdateManager) &&
  1885.         !iid.equals(Components.interfaces.nsISupports))
  1886.       throw Components.results.NS_ERROR_NO_INTERFACE;
  1887.     return this;
  1888.   }
  1889. };
  1890.  
  1891.  
  1892. /**
  1893.  * Checker
  1894.  * Checks for new Updates
  1895.  * @constructor
  1896.  */
  1897. function Checker() {
  1898. }
  1899. Checker.prototype = {
  1900.   /**
  1901.    * The XMLHttpRequest object that performs the connection.
  1902.    */
  1903.   _request  : null,
  1904.   
  1905.   /**
  1906.    * The nsIUpdateCheckListener callback
  1907.    */
  1908.   _callback : null,
  1909.  
  1910.   /**
  1911.    * The URL of the update service XML file to connect to that contains details
  1912.    * about available updates.
  1913.    */
  1914.   getUpdateURL: function(force) {
  1915.     this._forced = force;
  1916.  
  1917.     var defaults =
  1918.         gPref.QueryInterface(Components.interfaces.nsIPrefService).
  1919.         getDefaultBranch(null);
  1920.  
  1921.     // Use the override URL if specified.
  1922.     var url = getPref("getCharPref", PREF_APP_UPDATE_URL_OVERRIDE, null);
  1923.  
  1924.     // Otherwise, construct the update URL from component parts.
  1925.     if (!url) {
  1926.       try {
  1927.         url = defaults.getCharPref(PREF_APP_UPDATE_URL);
  1928.       } catch (e) {
  1929.       }
  1930.     }
  1931.  
  1932.     if (!url || url == "") {
  1933.       LOG("Checker", "Update URL not defined");
  1934.       return null;
  1935.     }
  1936.  
  1937.     url = url.replace(/%PRODUCT%/g, gApp.name);
  1938.     url = url.replace(/%VERSION%/g, gApp.version);
  1939.     url = url.replace(/%BUILD_ID%/g, gApp.appBuildID);
  1940.     url = url.replace(/%BUILD_TARGET%/g, gApp.OS + "_" + gABI);
  1941.     url = url.replace(/%OS_VERSION%/g, gOSVersion);
  1942.     url = url.replace(/%LOCALE%/g, getLocale());
  1943.     url = url.replace(/%CHANNEL%/g, getUpdateChannel());
  1944.     url = url.replace(/\+/g, "%2B");
  1945.  
  1946.     if (force)
  1947.     url += "?force=1"
  1948.  
  1949.     LOG("Checker", "update url: " + url);
  1950.     return url;
  1951.   },
  1952.   
  1953.   /**
  1954.    * See nsIUpdateService.idl
  1955.    */
  1956.   checkForUpdates: function(listener, force) {
  1957.     if (!listener)
  1958.       throw Components.results.NS_ERROR_NULL_POINTER;
  1959.     
  1960.     if (!this.getUpdateURL(force) || (!this.enabled && !force))
  1961.       return;
  1962.       
  1963.     this._request = 
  1964.       Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"].
  1965.       createInstance(Components.interfaces.nsIXMLHttpRequest);
  1966.     this._request.open("GET", this.getUpdateURL(force), true);
  1967.     this._request.channel.notificationCallbacks = new BadCertHandler();
  1968.     this._request.overrideMimeType("text/xml");
  1969.     this._request.setRequestHeader("Cache-Control", "no-cache");
  1970.     
  1971.     var self = this;
  1972.     this._request.onerror     = function(event) { self.onError(event);    };
  1973.     this._request.onload      = function(event) { self.onLoad(event);     };
  1974.     this._request.onprogress  = function(event) { self.onProgress(event); };
  1975.  
  1976.     LOG("Checker", "checkForUpdates: sending request to " + this.getUpdateURL(force));
  1977.     this._request.send(null);
  1978.     
  1979.     this._callback = listener;
  1980.   },
  1981.   
  1982.   /**
  1983.    * When progress associated with the XMLHttpRequest is received.
  1984.    * @param   event
  1985.    *          The nsIDOMLSProgressEvent for the load.
  1986.    */
  1987.   onProgress: function(event) {
  1988.     LOG("Checker", "onProgress: " + event.position + "/" + event.totalSize);
  1989.     this._callback.onProgress(event.target, event.position, event.totalSize);
  1990.   },
  1991.   
  1992.   /**
  1993.    * Returns an array of nsIUpdate objects discovered by the update check.
  1994.    */
  1995.   get _updates() {
  1996.     var updatesElement = this._request.responseXML.documentElement;
  1997.     if (!updatesElement) {
  1998.       LOG("Checker", "get_updates: empty updates document?!");
  1999.       return [];
  2000.     }
  2001.  
  2002.     if (updatesElement.nodeName != "updates") {
  2003.       LOG("Checker", "get_updates: unexpected node name!");
  2004.       throw "";
  2005.     }
  2006.     
  2007.     var updates = [];
  2008.     for (var i = 0; i < updatesElement.childNodes.length; ++i) {
  2009.       var updateElement = updatesElement.childNodes.item(i);
  2010.       if (updateElement.nodeType != Node.ELEMENT_NODE ||
  2011.           updateElement.localName != "update")
  2012.         continue;
  2013.  
  2014.       updateElement.QueryInterface(Components.interfaces.nsIDOMElement);
  2015.       try {
  2016.         var update = new Update(updateElement);
  2017.       } catch (e) {
  2018.         LOG("Checker", "Invalid <update/>, ignoring...");
  2019.         continue;
  2020.       }
  2021.       update.serviceURL = this.getUpdateURL(this._forced);
  2022.       update.channel = getUpdateChannel();
  2023.       updates.push(update);
  2024.     }
  2025.  
  2026.     return updates;
  2027.   },
  2028.   
  2029.   /**
  2030.    * The XMLHttpRequest succeeded and the document was loaded.
  2031.    * @param   event
  2032.    *          The nsIDOMLSEvent for the load
  2033.    */
  2034.   onLoad: function(event) {
  2035.     LOG("Checker", "onLoad: request completed downloading document");
  2036.     
  2037.     try {
  2038.       checkCert(this._request.channel);
  2039.  
  2040.       // Analyze the resulting DOM and determine the set of updates to install
  2041.       var updates = this._updates;
  2042.       
  2043.       LOG("Checker", "Updates available: " + updates.length);
  2044.       
  2045.       // ... and tell the Update Service about what we discovered.
  2046.       this._callback.onCheckComplete(event.target, updates, updates.length);
  2047.     }
  2048.     catch (e) {
  2049.       LOG("Checker", "There was a problem with the update service URL specified, " + 
  2050.           "either the XML file was malformed or it does not exist at the location " + 
  2051.           "specified. Exception: " + e);
  2052.       var update = new Update(null);
  2053.       update.statusText = getStatusTextFromCode(404, 404);
  2054.       this._callback.onError(event.target, update);
  2055.     }
  2056.  
  2057.     this._request = null;
  2058.   },
  2059.   
  2060.   /**
  2061.    * There was an error of some kind during the XMLHttpRequest
  2062.    * @param   event
  2063.    *          The nsIDOMLSEvent for the load
  2064.    */
  2065.   onError: function(event) {
  2066.     LOG("Checker", "onError: error during load");
  2067.     
  2068.     var request = event.target;
  2069.     try {
  2070.       var status = request.status;
  2071.     }
  2072.     catch (e) {
  2073.       var req = request.channel.QueryInterface(Components.interfaces.nsIRequest);
  2074.       status = req.status;
  2075.     }
  2076.     
  2077.     // If we can't find an error string specific to this status code, 
  2078.     // just use the 200 message from above, which means everything 
  2079.     // "looks" fine but there was probably an XML error or a bogus file.
  2080.     var update = new Update(null);
  2081.     update.statusText = getStatusTextFromCode(status, 200);
  2082.     this._callback.onError(request, update);
  2083.  
  2084.     this._request = null;
  2085.   },
  2086.   
  2087.   /**
  2088.    * Whether or not we are allowed to do update checking.
  2089.    */
  2090.   _enabled: true,
  2091.   
  2092.   /**
  2093.    * See nsIUpdateService.idl
  2094.    */
  2095.   get enabled() {
  2096.     var aus = 
  2097.         Components.classes["@mozilla.org/updates/update-service;1"].
  2098.         getService(Components.interfaces.nsIApplicationUpdateService);
  2099.     var enabled = getPref("getBoolPref", PREF_APP_UPDATE_ENABLED, true) && 
  2100.                   aus.canUpdate && this._enabled;
  2101.     return enabled;
  2102.   },
  2103.   
  2104.   /**
  2105.    * See nsIUpdateService.idl
  2106.    */
  2107.   stopChecking: function(duration) {
  2108.     // Always stop the current check
  2109.     if (this._request)
  2110.       this._request.abort();
  2111.     
  2112.     const nsIUpdateChecker = Components.interfaces.nsIUpdateChecker;
  2113.     switch (duration) {
  2114.     case nsIUpdateChecker.CURRENT_SESSION:
  2115.       this._enabled = false;
  2116.       break;
  2117.     case nsIUpdateChecker.ANY_CHECKS:
  2118.       this._enabled = false;
  2119.       gPref.setBoolPref(PREF_APP_UPDATE_ENABLED, this._enabled);
  2120.       break;
  2121.     }
  2122.   },
  2123.   
  2124.   /**
  2125.    * See nsISupports.idl
  2126.    */
  2127.   QueryInterface: function(iid) {
  2128.     if (!iid.equals(Components.interfaces.nsIUpdateChecker) &&
  2129.         !iid.equals(Components.interfaces.nsISupports))
  2130.       throw Components.results.NS_ERROR_NO_INTERFACE;
  2131.     return this;
  2132.   }
  2133. };
  2134.  
  2135. /**
  2136.  * Manages the download of updates
  2137.  * @param   background
  2138.  *          Whether or not this downloader is operating in background
  2139.  *          update mode. 
  2140.  * @constructor
  2141.  */
  2142. function Downloader(background) {
  2143.   this.background = background;
  2144. }
  2145. Downloader.prototype = {
  2146.   /**
  2147.    * The nsIUpdatePatch that we are downloading
  2148.    */
  2149.   _patch: null,
  2150.   
  2151.   /**
  2152.    * The nsIUpdate that we are downloading
  2153.    */
  2154.   _update: null,
  2155.   
  2156.   /**
  2157.    * The nsIIncrementalDownload object handling the download
  2158.    */
  2159.   _request: null,
  2160.  
  2161.   /**
  2162.    * Whether or not the update being downloaded is a complete replacement of
  2163.    * the user's existing installation or a patch representing the difference
  2164.    * between the new version and the previous version.
  2165.    */
  2166.   isCompleteUpdate: null,
  2167.  
  2168.   /**
  2169.    * Cancels the active download.
  2170.    */  
  2171.   cancel: function() {
  2172.     if (this._request && 
  2173.         this._request instanceof Components.interfaces.nsIRequest) {
  2174.       const NS_BINDING_ABORTED = 0x804b0002;
  2175.       this._request.cancel(NS_BINDING_ABORTED);
  2176.     }
  2177.   },
  2178.  
  2179.   /**
  2180.    * Whether or not a patch has been downloaded and staged for installation.
  2181.    */
  2182.   get patchIsStaged() {
  2183.     return readStatusFile(getUpdatesDir()) == STATE_PENDING;
  2184.   },
  2185.  
  2186.   /**
  2187.    * Verify the downloaded file.  We assume that the download is complete at
  2188.    * this point.
  2189.    */
  2190.   _verifyDownload: function() {
  2191.     if (!this._request)
  2192.       return false;
  2193.  
  2194.     var destination = this._request.destination;
  2195.  
  2196.     // Ensure that the file size matches the expected file size.
  2197.     if (destination.fileSize != this._patch.size)
  2198.       return false;
  2199.  
  2200.     var fileStream = Components.classes["@mozilla.org/network/file-input-stream;1"].
  2201.         createInstance(nsIFileInputStream);
  2202.     fileStream.init(destination, MODE_RDONLY, PERMS_FILE, 0);
  2203.  
  2204.     try {
  2205.       var hash = Components.classes["@mozilla.org/security/hash;1"].
  2206.           createInstance(nsICryptoHash);
  2207.       var hashFunction = nsICryptoHash[this._patch.hashFunction.toUpperCase()];
  2208.       if (hashFunction == undefined)
  2209.         throw Components.results.NS_ERROR_UNEXPECTED;
  2210.       hash.init(hashFunction);
  2211.       hash.updateFromStream(fileStream, -1);
  2212.       // NOTE: For now, we assume that the format of _patch.hashValue is hex
  2213.       // encoded binary (such as what is typically output by programs like
  2214.       // sha1sum).  In the future, this may change to base64 depending on how
  2215.       // we choose to compute these hashes.
  2216.       digest = binaryToHex(hash.finish(false));
  2217.     } catch (e) {
  2218.       LOG("Downloader", "failed to compute hash of downloaded update archive");
  2219.       digest = "";
  2220.     }
  2221.  
  2222.     fileStream.close();
  2223.  
  2224.     return digest == this._patch.hashValue.toLowerCase();
  2225.   },
  2226.  
  2227.   /**
  2228.    * Select the patch to use given the current state of updateDir and the given
  2229.    * set of update patches.
  2230.    * @param   update
  2231.    *          A nsIUpdate object to select a patch from
  2232.    * @param   updateDir
  2233.    *          A nsIFile representing the update directory
  2234.    * @returns A nsIUpdatePatch object to download
  2235.    */
  2236.   _selectPatch: function(update, updateDir) {
  2237.     // Given an update to download, we will always try to download the patch
  2238.     // for a partial update over the patch for a full update.
  2239.  
  2240.     /**
  2241.      * Return the first UpdatePatch with the given type.
  2242.      * @param   type
  2243.      *          The type of the patch ("complete" or "partial")
  2244.      * @returns A nsIUpdatePatch object matching the type specified
  2245.      */
  2246.     function getPatchOfType(type) {
  2247.       for (var i = 0; i < update.patchCount; ++i) {
  2248.         var patch = update.getPatchAt(i);
  2249.         if (patch && patch.type == type)
  2250.           return patch;
  2251.       }
  2252.       return null;
  2253.     }
  2254.  
  2255.     // Look to see if any of the patches in the Update object has been
  2256.     // pre-selected for download, otherwise we must figure out which one
  2257.     // to select ourselves. 
  2258.     var selectedPatch = update.selectedPatch;
  2259.     
  2260.     var state = readStatusFile(updateDir)
  2261.  
  2262.     // If this is a patch that we know about, then select it.  If it is a patch
  2263.     // that we do not know about, then remove it and use our default logic.
  2264.     var useComplete = false;
  2265.     if (selectedPatch) {
  2266.       LOG("Downloader", "found existing patch [state="+state+"]");
  2267.       switch (state) {
  2268.       case STATE_DOWNLOADING: 
  2269.         LOG("Downloader", "resuming download");
  2270.         return selectedPatch;
  2271.       case STATE_PENDING:
  2272.         LOG("Downloader", "already downloaded and staged");
  2273.         return null;
  2274.       default:
  2275.         // Something went wrong when we tried to apply the previous patch.
  2276.         // Try the complete patch next time.
  2277.         if (update && selectedPatch.type == "partial") {
  2278.           useComplete = true;
  2279.         } else {
  2280.           // This is a pretty fatal error.  Just bail.
  2281.           LOG("Downloader", "failed to apply complete patch!");
  2282.           writeStatusFile(updateDir, STATE_NONE);
  2283.           return null;
  2284.         }
  2285.       }
  2286.  
  2287.       selectedPatch = null;
  2288.     }
  2289.     
  2290.     // If we were not able to discover an update from a previous download, we 
  2291.     // select the best patch from the given set.
  2292.     var partialPatch = getPatchOfType("partial");
  2293.     if (!useComplete)
  2294.       selectedPatch = partialPatch;
  2295.     if (!selectedPatch) {
  2296.       if (partialPatch)
  2297.         partialPatch.selected = false;
  2298.       selectedPatch = getPatchOfType("complete");
  2299.     }
  2300.  
  2301.     // Restore the updateDir since we may have deleted it.
  2302.     updateDir = getUpdatesDir();
  2303.  
  2304.     // if update only contains a partial patch, selectedPatch == null here if
  2305.     // the partial patch has been attempted and fails and we're trying to get a
  2306.     // complete patch
  2307.     if (selectedPatch)    
  2308.       selectedPatch.selected = true;
  2309.  
  2310.     update.isCompleteUpdate = useComplete;
  2311.     
  2312.     // Reset the Active Update object on the Update Manager and flush the
  2313.     // Active Update DB. 
  2314.     var um = Components.classes["@mozilla.org/updates/update-manager;1"]
  2315.                        .getService(Components.interfaces.nsIUpdateManager);
  2316.     um.activeUpdate = update;
  2317.  
  2318.     return selectedPatch;
  2319.   },
  2320.  
  2321.   /**
  2322.    * Whether or not we are currently downloading something.
  2323.    */
  2324.   get isBusy() {
  2325.     return this._request != null;
  2326.   },
  2327.   
  2328.   /**
  2329.    * Download and stage the given update.
  2330.    * @param   update
  2331.    *          A nsIUpdate object to download a patch for. Cannot be null.
  2332.    */
  2333.   downloadUpdate: function(update) {
  2334.     if (!update)
  2335.       throw Components.results.NS_ERROR_NULL_POINTER;
  2336.     
  2337.     var updateDir = getUpdatesDir();
  2338.  
  2339.     this._update = update;
  2340.  
  2341.     // This function may return null, which indicates that there are no patches
  2342.     // to download.
  2343.     this._patch = this._selectPatch(update, updateDir);
  2344.     if (!this._patch) {
  2345.       LOG("Downloader", "no patch to download");
  2346.       return readStatusFile(updateDir);
  2347.     }
  2348.     this.isCompleteUpdate = this._patch.type == "complete";
  2349.  
  2350.     var patchFile = updateDir.clone();
  2351.     patchFile.append(FILE_UPDATE_ARCHIVE);
  2352.  
  2353.     var ios = Components.classes["@mozilla.org/network/io-service;1"].
  2354.         getService(Components.interfaces.nsIIOService);
  2355.     var uri = ios.newURI(this._patch.URL, null, null);
  2356.  
  2357.     this._request =
  2358.         Components.classes["@mozilla.org/network/incremental-download;1"].
  2359.         createInstance(nsIIncrementalDownload);
  2360.  
  2361.     LOG("Downloader", "downloadUpdate: Downloading from " + uri.spec + " to " + 
  2362.         patchFile.path);
  2363.  
  2364.     var interval = this.background ? DOWNLOAD_BACKGROUND_INTERVAL
  2365.                                    : DOWNLOAD_FOREGROUND_INTERVAL;
  2366.     this._request.init(uri, patchFile, DOWNLOAD_CHUNK_SIZE, interval);
  2367.     this._request.start(this, null);
  2368.  
  2369.     writeStatusFile(updateDir, STATE_DOWNLOADING);
  2370.     this._patch.QueryInterface(Components.interfaces.nsIWritablePropertyBag);
  2371.     this._patch.state = STATE_DOWNLOADING;
  2372.     var um = Components.classes["@mozilla.org/updates/update-manager;1"]
  2373.                        .getService(Components.interfaces.nsIUpdateManager);
  2374.     um.saveUpdates();
  2375.     return STATE_DOWNLOADING;
  2376.   },
  2377.   
  2378.   /**
  2379.    * An array of download listeners to notify when we receive 
  2380.    * nsIRequestObserver or nsIProgressEventSink method calls.
  2381.    */
  2382.   _listeners: [],
  2383.  
  2384.   /** 
  2385.    * Adds a listener to the download process
  2386.    * @param   listener
  2387.    *          A download listener, implementing nsIRequestObserver and
  2388.    *          nsIProgressEventSink
  2389.    */
  2390.   addDownloadListener: function(listener) {
  2391.     for (var i = 0; i < this._listeners.length; ++i) {
  2392.       if (this._listeners[i] == listener)
  2393.         return;
  2394.     }
  2395.     this._listeners.push(listener);
  2396.   },
  2397.   
  2398.   /** 
  2399.    * Removes a download listener
  2400.    * @param   listener
  2401.    *          The listener to remove.
  2402.    */
  2403.   removeDownloadListener: function(listener) {
  2404.     for (var i = 0; i < this._listeners.length; ++i) {
  2405.       if (this._listeners[i] == listener) {
  2406.         this._listeners.splice(i, 1);
  2407.         return;
  2408.       }
  2409.     }
  2410.   },
  2411.   
  2412.   /**
  2413.    * When the async request begins
  2414.    * @param   request
  2415.    *          The nsIRequest object for the transfer
  2416.    * @param   context
  2417.    *          Additional data
  2418.    */
  2419.   onStartRequest: function(request, context) {
  2420.     request.QueryInterface(nsIIncrementalDownload);
  2421.     LOG("Downloader", "onStartRequest: " + request.URI.spec);
  2422.     
  2423.     var listenerCount = this._listeners.length;
  2424.     for (var i = 0; i < listenerCount; ++i)
  2425.       this._listeners[i].onStartRequest(request, context);
  2426.   },
  2427.   
  2428.   /** 
  2429.    * When new data has been downloaded
  2430.    * @param   request
  2431.    *          The nsIRequest object for the transfer
  2432.    * @param   context
  2433.    *          Additional data
  2434.    * @param   progress
  2435.    *          The current number of bytes transferred
  2436.    * @param   maxProgress
  2437.    *          The total number of bytes that must be transferred
  2438.    */
  2439.   onProgress: function(request, context, progress, maxProgress) {
  2440.     request.QueryInterface(nsIIncrementalDownload);
  2441.     LOG("Downloader.onProgress", "onProgress: " + request.URI.spec + ", " + progress + "/" + maxProgress);
  2442.     
  2443.     var listenerCount = this._listeners.length;
  2444.     for (var i = 0; i < listenerCount; ++i) {
  2445.       var listener = this._listeners[i];
  2446.       if (listener instanceof Components.interfaces.nsIProgressEventSink)
  2447.         listener.onProgress(request, context, progress, maxProgress);
  2448.     }
  2449.   },
  2450.   
  2451.   /** 
  2452.    * When we have new status text
  2453.    * @param   request
  2454.    *          The nsIRequest object for the transfer
  2455.    * @param   context
  2456.    *          Additional data
  2457.    * @param   status
  2458.    *          A status code
  2459.    * @param   statusText
  2460.    *          Human readable version of |status|
  2461.    */
  2462.   onStatus: function(request, context, status, statusText) {
  2463.     request.QueryInterface(nsIIncrementalDownload);
  2464.     LOG("Downloader", "onStatus: " + request.URI.spec + " status = " + status + ", text = " + statusText);
  2465.     var listenerCount = this._listeners.length;
  2466.     for (var i = 0; i < listenerCount; ++i) {
  2467.       var listener = this._listeners[i];
  2468.       if (listener instanceof Components.interfaces.nsIProgressEventSink)
  2469.         listener.onStatus(request, context, status, statusText);
  2470.     }
  2471.   },
  2472.   
  2473.   /** 
  2474.    * When data transfer ceases
  2475.    * @param   request
  2476.    *          The nsIRequest object for the transfer
  2477.    * @param   context
  2478.    *          Additional data
  2479.    * @param   status
  2480.    *          Status code containing the reason for the cessation.
  2481.    */
  2482.   onStopRequest: function(request, context, status) {
  2483.     request.QueryInterface(nsIIncrementalDownload);
  2484.     LOG("Downloader", "onStopRequest: " + request.URI.spec + ", status = " + status);
  2485.  
  2486.     var state = this._patch.state;
  2487.     var shouldShowPrompt = false;
  2488.     var deleteActiveUpdate = false;
  2489.     const NS_BINDING_ABORTED = 0x804b0002;
  2490.     const NS_ERROR_ABORT = 0x80004004;
  2491.     if (Components.isSuccessCode(status)) {
  2492.       var sbs = 
  2493.           Components.classes["@mozilla.org/intl/stringbundle;1"].
  2494.           getService(Components.interfaces.nsIStringBundleService);
  2495.       var updateStrings = sbs.createBundle(URI_UPDATES_PROPERTIES);
  2496.       if (this._verifyDownload()) {
  2497.         state = STATE_PENDING;
  2498.         
  2499.         // We only need to explicitly show the prompt if this is a backround
  2500.         // download, since otherwise some kind of UI is already visible and 
  2501.         // that UI will notify. 
  2502.         if (this.background)
  2503.           shouldShowPrompt = true;
  2504.         
  2505.         // Tell the updater.exe we're ready to apply.
  2506.         writeStatusFile(getUpdatesDir(), state);
  2507.         this._update.installDate = (new Date()).getTime();
  2508.         this._update.statusText = updateStrings.
  2509.           GetStringFromName("installPending");
  2510.       } else {
  2511.         LOG("Downloader", "onStopRequest: download verification failed");
  2512.         state = STATE_DOWNLOAD_FAILED;
  2513.         
  2514.         var brandStrings = sbs.createBundle(URI_BRAND_PROPERTIES);
  2515.         var brandShortName = brandStrings.GetStringFromName("brandShortName");
  2516.         this._update.statusText = updateStrings.
  2517.           formatStringFromName("verificationError", [brandShortName], 1);
  2518.         
  2519.         // TODO: use more informative error code here
  2520.         status = Components.results.NS_ERROR_UNEXPECTED;
  2521.         
  2522.         var message = getStatusTextFromCode("verification_failed", 
  2523.           "verification_failed");
  2524.         this._update.statusText = message;
  2525.         
  2526.         if (this._update.isCompleteUpdate)
  2527.           deleteActiveUpdate = true;
  2528.  
  2529.         // Destroy the updates directory, since we're done with it.
  2530.         cleanUpUpdatesDir();
  2531.       }
  2532.     }
  2533.     else if (status != NS_BINDING_ABORTED &&
  2534.              status != NS_ERROR_ABORT) {
  2535.       LOG("Downloader", "onStopRequest: Non-verification failure");
  2536.       // Some sort of other failure, log this in the |statusText| property
  2537.       state = STATE_DOWNLOAD_FAILED;
  2538.       
  2539.       // XXXben - if |request| (The Incremental Download) provided a means
  2540.       // for accessing the http channel we could do more here.
  2541.       
  2542.       const NS_BINDING_FAILED = 2152398849;
  2543.       this._update.statusText = getStatusTextFromCode(status, 
  2544.         NS_BINDING_FAILED);
  2545.       
  2546.       // Destroy the updates directory, since we're done with it.
  2547.       cleanUpUpdatesDir();
  2548.       
  2549.       deleteActiveUpdate = true;
  2550.     }
  2551.     LOG("Downloader", "Setting state to: " + state);
  2552.     this._patch.state = state;
  2553.     var um = 
  2554.         Components.classes["@mozilla.org/updates/update-manager;1"].
  2555.         getService(Components.interfaces.nsIUpdateManager);
  2556.     if (deleteActiveUpdate) {
  2557.       this._update.installDate = (new Date()).getTime();
  2558.       um.activeUpdate = null;
  2559.     }
  2560.     um.saveUpdates();
  2561.     
  2562.     var listenerCount = this._listeners.length;
  2563.     for (var i = 0; i < listenerCount; ++i)
  2564.       this._listeners[i].onStopRequest(request, context, status);
  2565.  
  2566.     this._request = null;
  2567.     
  2568.     if (state == STATE_DOWNLOAD_FAILED) {
  2569.       if (!this._update.isCompleteUpdate) {
  2570.         var allFailed = true;
  2571.   
  2572.         // If we were downloading a patch and the patch verification phase 
  2573.         // failed, log this and then commence downloading the complete update.
  2574.         LOG("Downloader", "onStopRequest: Verification of patch failed, downloading complete update");
  2575.         this._update.isCompleteUpdate = true;
  2576.         var status = this.downloadUpdate(this._update);
  2577.  
  2578.         if (status == STATE_NONE) {
  2579.           cleanupActiveUpdate();
  2580.         } else {
  2581.           allFailed = false;
  2582.         }
  2583.         // This will reset the |.state| property on this._update if a new 
  2584.         // download initiates.
  2585.       }
  2586.     
  2587.       // if we still fail after trying a complete download, give up completely
  2588.       if (allFailed) {
  2589.         // In all other failure cases, i.e. we're S.O.L. - no more failing over
  2590.         // ...
  2591.         
  2592.         // If this was ever a foreground download, and now there is no UI active
  2593.         // (e.g. because the user closed the download window) and there was an
  2594.         // error, we must notify now. Otherwise we can keep the failure to 
  2595.         // ourselves since the user won't be expecting it. 
  2596.         try {
  2597.           this._update.QueryInterface(Components.interfaces.nsIWritablePropertyBag);
  2598.           var fgdl = this._update.getProperty("foregroundDownload");
  2599.         }
  2600.         catch (e) {
  2601.         }
  2602.       
  2603.         if (fgdl == "true") {
  2604.           var prompter = 
  2605.               Components.classes["@mozilla.org/updates/update-prompt;1"].
  2606.               createInstance(Components.interfaces.nsIUpdatePrompt);
  2607.           this._update.QueryInterface(Components.interfaces.nsIWritablePropertyBag);
  2608.           this._update.setProperty("downloadFailed", "true");
  2609.           prompter.showUpdateError(this._update);
  2610.         }
  2611.       }
  2612.  
  2613.       // the complete download succeeded or total failure was handled, so exit
  2614.       return;
  2615.     }
  2616.  
  2617.     // Do this after *everything* else, since it will likely cause the app 
  2618.     // to shut down. 
  2619.     if (shouldShowPrompt) {
  2620.       // Notify the user that an update has been downloaded and is ready for 
  2621.       // installation (i.e. that they should restart the application). We do
  2622.       // not notify on failed update attempts.
  2623.       var prompter = 
  2624.           Components.classes["@mozilla.org/updates/update-prompt;1"].
  2625.           createInstance(Components.interfaces.nsIUpdatePrompt);
  2626.       prompter.showUpdateDownloaded(this._update);
  2627.     }
  2628.   },
  2629.  
  2630.   /**
  2631.    * See nsIInterfaceRequestor.idl
  2632.    */
  2633.   getInterface: function(iid) {
  2634.     // The network request may require proxy authentication, so provide the
  2635.     // default nsIAuthPrompt if requested.
  2636.     if (iid.equals(Components.interfaces.nsIAuthPrompt)) {
  2637.       var prompt =
  2638.           Components.classes["@mozilla.org/network/default-auth-prompt;1"].
  2639.           createInstance();
  2640.       return prompt.QueryInterface(iid);
  2641.     }
  2642.     Components.returnCode = Components.results.NS_ERROR_NO_INTERFACE;
  2643.     return null;
  2644.   },
  2645.    
  2646.   /**
  2647.    * See nsISupports.idl
  2648.    */
  2649.   QueryInterface: function(iid) {
  2650.     if (!iid.equals(Components.interfaces.nsIRequestObserver) &&
  2651.         !iid.equals(Components.interfaces.nsIProgressEventSink) &&
  2652.         !iid.equals(Components.interfaces.nsIInterfaceRequestor) &&
  2653.         !iid.equals(Components.interfaces.nsISupports))
  2654.       throw Components.results.NS_ERROR_NO_INTERFACE;
  2655.     return this;
  2656.   }
  2657. };
  2658.  
  2659. /**
  2660.  * A manager for update check timers. Manages timers that fire over long 
  2661.  * periods of time (e.g. days, weeks).
  2662.  * @constructor
  2663.  */
  2664. function TimerManager() {
  2665.   getObserverService().addObserver(this, "xpcom-shutdown", false);
  2666.  
  2667.   const nsITimer = Components.interfaces.nsITimer;
  2668.   this._timer = Components.classes["@mozilla.org/timer;1"]
  2669.                           .createInstance(nsITimer);
  2670.   var timerInterval = getPref("getIntPref", PREF_APP_UPDATE_TIMER, 600000);
  2671.   this._timer.initWithCallback(this, timerInterval, 
  2672.                                nsITimer.TYPE_REPEATING_SLACK);
  2673. }
  2674. TimerManager.prototype = {
  2675.   /**
  2676.    * See nsIObserver.idl
  2677.    */
  2678.   observe: function(subject, topic, data) {
  2679.     if (topic == "xpcom-shutdown") {
  2680.      getObserverService().removeObserver(this, "xpcom-shutdown");
  2681.  
  2682.       // Release everything we hold onto. 
  2683.       for (var timerID in this._timers)
  2684.         delete this._timers[timerID];
  2685.       this._timer = null;
  2686.       this._timers = null;
  2687.     }
  2688.   },
  2689.  
  2690.   /**
  2691.    * The Checker Timer
  2692.    */
  2693.   _timer: null,
  2694.   
  2695.   /**
  2696.    * The set of registered timers.
  2697.    */
  2698.   _timers: { },
  2699.   
  2700.   /**
  2701.    * Called when the checking timer fires.
  2702.    * @param   timer
  2703.    *          The checking timer that fired. 
  2704.    */
  2705.   notify: function(timer) {
  2706.     for (var timerID in this._timers) {
  2707.       var timerData = this._timers[timerID];
  2708.       var lastUpdateTime = timerData.lastUpdateTime;
  2709.       var now = Math.round(Date.now() / 1000);
  2710.     
  2711.       // Fudge the lastUpdateTime by some random increment of the update 
  2712.       // check interval (e.g. some random slice of 10 minutes) so that when
  2713.       // the time comes to check, we offset each client request by a random
  2714.       // amount so they don't all hit at once. app.update.timer is in milliseconds,
  2715.       // whereas app.update.lastUpdateTime is in seconds
  2716.       var timerInterval = getPref("getIntPref", PREF_APP_UPDATE_TIMER, 600000);
  2717.       lastUpdateTime += Math.round(Math.random() * timerInterval / 1000);
  2718.  
  2719.       if ((now - lastUpdateTime) > timerData.interval &&
  2720.           timerData.callback instanceof Components.interfaces.nsITimerCallback) {
  2721.         timerData.callback.notify(timer);
  2722.         timerData.lastUpdateTime = now;
  2723.         var preference = PREF_APP_UPDATE_LASTUPDATETIME_FMT.replace(/%ID%/, timerID);
  2724.         gPref.setIntPref(preference, now);
  2725.       }
  2726.     }
  2727.   },
  2728.   
  2729.   /**
  2730.    * See nsIUpdateService.idl
  2731.    */
  2732.   registerTimer: function(id, callback, interval) {
  2733.     var preference = PREF_APP_UPDATE_LASTUPDATETIME_FMT.replace(/%ID%/, id);
  2734.     var now = Math.round(Date.now() / 1000);
  2735.     var lastUpdateTime = null;
  2736.     if (gPref.prefHasUserValue(preference)) {
  2737.       lastUpdateTime = gPref.getIntPref(preference);
  2738.     } else {
  2739.       gPref.setIntPref(preference, now);
  2740.       lastUpdateTime = now;
  2741.     }
  2742.     this._timers[id] = { callback       : callback, 
  2743.                          interval       : interval,
  2744.                          lastUpdateTime : lastUpdateTime }; 
  2745.   },
  2746.  
  2747.   /**
  2748.    * See nsISupports.idl
  2749.    */
  2750.   QueryInterface: function(iid) {
  2751.     if (!iid.equals(Components.interfaces.nsIUpdateTimerManager) &&
  2752.         !iid.equals(Components.interfaces.nsITimerCallback) &&
  2753.         !iid.equals(Components.interfaces.nsIObserver) &&
  2754.         !iid.equals(Components.interfaces.nsISupports))
  2755.       throw Components.results.NS_ERROR_NO_INTERFACE;
  2756.     return this;
  2757.   }
  2758. };
  2759.  
  2760. //@line 2733 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-Release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2761. /**
  2762.  * UpdatePrompt
  2763.  * An object which can prompt the user with information about updates, request
  2764.  * action, etc. Embedding clients can override this component with one that 
  2765.  * invokes a native front end. 
  2766.  * @constructor
  2767.  */
  2768. function UpdatePrompt() {
  2769. }
  2770. UpdatePrompt.prototype = {
  2771.   /**
  2772.    * See nsIUpdateService.idl
  2773.    */
  2774.   checkForUpdates: function() {
  2775.     this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null, "Update:Wizard", 
  2776.                  null, null);
  2777.   },
  2778.     
  2779.   /**
  2780.    * See nsIUpdateService.idl
  2781.    */
  2782.   showUpdateAvailable: function(update) {
  2783.     if (this._enabled) {
  2784.       this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null, "Update:Wizard", 
  2785.                    "updatesavailable", update);
  2786.     }
  2787.   },
  2788.   
  2789.   /**
  2790.    * See nsIUpdateService.idl
  2791.    */
  2792.   showUpdateDownloaded: function(update) {
  2793.     if (this._enabled) {
  2794.       this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null, "Update:Wizard", 
  2795.                    "finishedBackground", update);
  2796.     }
  2797.   },
  2798.   
  2799.   /**
  2800.    * See nsIUpdateService.idl
  2801.    */
  2802.   showUpdateInstalled: function(update) {
  2803.     var showUpdateInstalledUI = getPref("getBoolPref", 
  2804.       PREF_APP_UPDATE_SHOW_INSTALLED_UI, true);
  2805.     if (this._enabled && showUpdateInstalledUI) {
  2806.       this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null, "Update:Wizard", 
  2807.                    "installed", update);
  2808.     }
  2809.   },
  2810.   
  2811.   /**
  2812.    * See nsIUpdateService.idl
  2813.    */
  2814.   showUpdateError: function(update) {
  2815.     if (this._enabled) {
  2816.       // In some cases, we want to just show a simple alert dialog:
  2817.       if (update.state == STATE_FAILED && update.errorCode == WRITE_ERROR) {
  2818.         var sbs = 
  2819.             Components.classes["@mozilla.org/intl/stringbundle;1"].
  2820.             getService(Components.interfaces.nsIStringBundleService);
  2821.         var updateBundle = sbs.createBundle(URI_UPDATES_PROPERTIES);
  2822.         var title = updateBundle.GetStringFromName("updaterIOErrorTitle");
  2823.         var text = updateBundle.formatStringFromName("updaterIOErrorText",
  2824.                                                      [gApp.name], 1);
  2825.         var ww =
  2826.             Components.classes["@mozilla.org/embedcomp/window-watcher;1"].
  2827.             getService(Components.interfaces.nsIWindowWatcher);
  2828.         ww.getNewPrompter(null).alert(title, text);
  2829.       } else {
  2830.         this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null, "Update:Wizard", 
  2831.                      "errors", update);
  2832.       }
  2833.     }
  2834.   },
  2835.   
  2836.   /**
  2837.    * See nsIUpdateService.idl
  2838.    */
  2839.   showUpdateHistory: function(parent) {
  2840.     this._showUI(parent, URI_UPDATE_HISTORY_DIALOG, "modal,dialog=yes", "Update:History", 
  2841.                  null, null);
  2842.   },
  2843.   
  2844.   /**
  2845.    * Whether or not we are enabled (i.e. not in Silent mode)
  2846.    */
  2847.   get _enabled() {
  2848.     return !getPref("getBoolPref", PREF_APP_UPDATE_SILENT, false);
  2849.   },
  2850.   
  2851.   /**
  2852.    * Show the Update Checking UI
  2853.    * @param   parent
  2854.    *          A parent window, can be null
  2855.    * @param   uri
  2856.    *          The URI string of the dialog to show
  2857.    * @param   name
  2858.    *          The Window Name of the dialog to show, in case it is already open
  2859.    *          and can merely be focused
  2860.    * @param   page
  2861.    *          The page of the wizard to be displayed, if one is already open.
  2862.    * @param   update
  2863.    *          An update to pass to the UI in the window arguments. 
  2864.    *          Can be null
  2865.    */
  2866.   _showUI: function(parent, uri, features, name, page, update) {
  2867.     var ary = null;
  2868.     if (update) {
  2869.       ary = Components.classes["@mozilla.org/supports-array;1"]
  2870.                       .createInstance(Components.interfaces.nsISupportsArray);
  2871.       ary.AppendElement(update);
  2872.     }
  2873.       
  2874.     var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
  2875.                        .getService(Components.interfaces.nsIWindowMediator);
  2876.     var win = wm.getMostRecentWindow(name);
  2877.     if (win) {
  2878.       if (page && "setCurrentPage" in win)
  2879.         win.setCurrentPage(page);
  2880.       win.focus();
  2881.     }
  2882.     else {
  2883.       var openFeatures = "chrome,centerscreen,dialog=no,resizable=no,titlebar,toolbar=no";
  2884.       if (features)
  2885.         openFeatures += "," + features;
  2886.       var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"]
  2887.                          .getService(Components.interfaces.nsIWindowWatcher);
  2888.       ww.openWindow(parent, uri, "", openFeatures, ary);
  2889.     }
  2890.   },
  2891.   
  2892.   /**
  2893.    * See nsISupports.idl
  2894.    */
  2895.   QueryInterface: function(iid) {
  2896.     if (!iid.equals(Components.interfaces.nsIUpdatePrompt) &&
  2897.         !iid.equals(Components.interfaces.nsISupports))
  2898.       throw Components.results.NS_ERROR_NO_INTERFACE;
  2899.     return this;
  2900.   }
  2901. };
  2902. //@line 2875 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-Release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2903.  
  2904. var gModule = {
  2905.   registerSelf: function(componentManager, fileSpec, location, type) {
  2906.     componentManager = componentManager.QueryInterface(Components.interfaces.nsIComponentRegistrar);
  2907.     
  2908.     for (var key in this._objects) {
  2909.       var obj = this._objects[key];
  2910.       componentManager.registerFactoryLocation(obj.CID, obj.className, obj.contractID,
  2911.                                                fileSpec, location, type);
  2912.     }
  2913.  
  2914.     // Make the Update Service a startup observer
  2915.     var categoryManager = Components.classes["@mozilla.org/categorymanager;1"]
  2916.                                     .getService(Components.interfaces.nsICategoryManager);
  2917.     categoryManager.addCategoryEntry("app-startup", this._objects.service.className,
  2918.                                      "service," + this._objects.service.contractID, 
  2919.                                      true, true, null);
  2920.   },
  2921.   
  2922.   getClassObject: function(componentManager, cid, iid) {
  2923.     if (!iid.equals(Components.interfaces.nsIFactory))
  2924.       throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
  2925.  
  2926.     for (var key in this._objects) {
  2927.       if (cid.equals(this._objects[key].CID))
  2928.         return this._objects[key].factory;
  2929.     }
  2930.     
  2931.     throw Components.results.NS_ERROR_NO_INTERFACE;
  2932.   },
  2933.   
  2934.   _objects: {
  2935.     service: { CID        : Components.ID("{B3C290A6-3943-4B89-8BBE-C01EB7B3B311}"),
  2936.                contractID : "@mozilla.org/updates/update-service;1",
  2937.                className  : "Update Service",
  2938.                factory    : makeFactory(UpdateService)
  2939.              },
  2940.     checker: { CID        : Components.ID("{898CDC9B-E43F-422F-9CC4-2F6291B415A3}"),
  2941.                contractID : "@mozilla.org/updates/update-checker;1",
  2942.                className  : "Update Checker",
  2943.                factory    : makeFactory(Checker)
  2944.              },
  2945. //@line 2918 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-Release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2946.     prompt:  { CID        : Components.ID("{27ABA825-35B5-4018-9FDD-F99250A0E722}"),
  2947.                contractID : "@mozilla.org/updates/update-prompt;1",
  2948.                className  : "Update Prompt",
  2949.                factory    : makeFactory(UpdatePrompt)
  2950.              },
  2951. //@line 2924 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-Release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2952.     timers:  { CID        : Components.ID("{B322A5C0-A419-484E-96BA-D7182163899F}"),
  2953.                contractID : "@mozilla.org/updates/timer-manager;1",
  2954.                className  : "Timer Manager",
  2955.                factory    : makeFactory(TimerManager)
  2956.              },
  2957.     manager: { CID        : Components.ID("{093C2356-4843-4C65-8709-D7DBCBBE7DFB}"),
  2958.                contractID : "@mozilla.org/updates/update-manager;1",
  2959.                className  : "Update Manager",
  2960.                factory    : makeFactory(UpdateManager)
  2961.              },
  2962.   },
  2963.   
  2964.   canUnload: function(componentManager) {
  2965.     return true;
  2966.   }
  2967. };
  2968.  
  2969. /**
  2970.  * Creates a factory for instances of an object created using the passed-in
  2971.  * constructor.
  2972.  */
  2973. function makeFactory(ctor) {
  2974.   function ci(outer, iid) {
  2975.     if (outer != null)
  2976.       throw Components.results.NS_ERROR_NO_AGGREGATION;
  2977.     return (new ctor()).QueryInterface(iid);
  2978.   } 
  2979.   return { createInstance: ci };
  2980. }
  2981.   
  2982. function NSGetModule(compMgr, fileSpec) {
  2983.   return gModule;
  2984. }
  2985.  
  2986. /**
  2987.  * Determines whether or there are installed addons which are incompatible 
  2988.  * with this update.
  2989.  * @param   update
  2990.  *          The update to check compatibility against
  2991.  * @returns true if there are no addons installed that are incompatible with
  2992.  *          the specified update, false otherwise.
  2993.  */
  2994. function isCompatible(update) {
  2995. //@line 2968 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-Release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2996.   var em = 
  2997.       Components.classes["@mozilla.org/extensions/manager;1"].
  2998.       getService(Components.interfaces.nsIExtensionManager);
  2999.   var items = em.getIncompatibleItemList("", update.extensionVersion,
  3000.     nsIUpdateItem.TYPE_ADDON, false, { });
  3001.   return items.length == 0;
  3002. //@line 2977 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-Release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  3003. }
  3004.  
  3005. /**
  3006.  * Shows a prompt for an update, provided there are no incompatible addons.
  3007.  * If there are, kick off an update check and see if updates are available
  3008.  * that will resolve the incompatibilities.
  3009.  * @param   update
  3010.  *          The available update to show
  3011.  */
  3012. function showPromptIfNoIncompatibilities(update) {
  3013.   function showPrompt(update) {
  3014.     LOG("UpdateService", "_selectAndInstallUpdate: need to prompt user before continuing...");
  3015.     var prompter = 
  3016.         Components.classes["@mozilla.org/updates/update-prompt;1"].
  3017.         createInstance(Components.interfaces.nsIUpdatePrompt);
  3018.     prompter.showUpdateAvailable(update);
  3019.   }
  3020.  
  3021. //@line 2996 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-Release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  3022.   /**
  3023.    * Determines if an addon is compatible with a particular update.
  3024.    * @param   addon
  3025.    *          The addon to check
  3026.    * @param   version
  3027.    *          The extensionVersion of the update to check for compatibility 
  3028.    *          against.
  3029.    * @returns true if the addon is compatible, false otherwise
  3030.    */
  3031.   function addonIsCompatible(addon, version) {
  3032.     var vc = 
  3033.         Components.classes["@mozilla.org/xpcom/version-comparator;1"].
  3034.         getService(Components.interfaces.nsIVersionComparator);
  3035.     return (vc.compare(version, addon.minAppVersion) >= 0) &&
  3036.           (vc.compare(version, addon.maxAppVersion) <= 0);
  3037.   }
  3038.  
  3039.   /**
  3040.    * An object implementing nsIAddonUpdateCheckListener that looks for 
  3041.    * available updates to addons and if updates are found that will make the 
  3042.    * user's installed addon set compatible with the update, suppresses the
  3043.    * prompt that would otherwise be shown.
  3044.    * @param   addons
  3045.    *          An array of incompatible addons that are installed.
  3046.    * @constructor
  3047.    */
  3048.   function Listener(addons) {
  3049.     this._addons = addons;
  3050.   }
  3051.   Listener.prototype = {
  3052.     _addons: null,
  3053.     
  3054.     /**
  3055.      * See nsIUpdateService.idl
  3056.      */
  3057.     onUpdateStarted: function() { 
  3058.     },
  3059.     onUpdateEnded: function() {
  3060.       // There are still incompatibilities, even after an extension update 
  3061.       // check to see if there were newer, compatible versions available, so
  3062.       // we have to prompt. 
  3063.       // 
  3064.       // PREF_APP_UPDATE_INCOMPATIBLE_MODE controls the mode in which we 
  3065.       // handle incompatibilities:
  3066.       // 0    We count both VersionInfo updates _and_ NewerVersion updates
  3067.       //      against the list of incompatible addons installed - i.e. if
  3068.       //      Foo 1.2 is installed and it is incompatible with the update, and
  3069.       //      we find Foo 2.0 which is but which is not yet downloaded or 
  3070.       //      installed, then we do NOT prompt because the user can download
  3071.       //      Foo 2.0 when they restart after the update during the mismatch
  3072.       //      checking UI. This is the default, since it suppresses most 
  3073.       //      prompt dialogs. 
  3074.       // 1    We count only VersionInfo updates against the list of 
  3075.       //      incompatible addons installed - i.e. if the situation above
  3076.       //      with Foo 1.2 and available update to 2.0 applies, we DO show
  3077.       //      the prompt since a download operation will be required after
  3078.       //      the update. This is not the default and is supplied only as
  3079.       //      a hidden option for those that want it. 
  3080.       var mode = getPref("getIntPref", PREF_APP_UPDATE_INCOMPATIBLE_MODE, 
  3081.                          INCOMPATIBLE_MODE_NEWVERSIONS);
  3082.       if ((mode == 0 && this._addons.length) || !isCompatible(update))
  3083.         showPrompt(update);
  3084.     },
  3085.     onAddonUpdateStarted: function(addon) {
  3086.     },
  3087.     onAddonUpdateEnded: function(addon, status) {
  3088.       if (status == Components.interfaces.nsIAddonUpdateCheckListener.STATUS_UPDATE &&
  3089.           addonIsCompatible(addon, update.extensionVersion)) {
  3090.         for (var i = 0; i < this._addons.length; ++i) {
  3091.           if (this._addons[i] == addon) {
  3092.             this._addons.splice(i, 1);
  3093.             break;
  3094.           }
  3095.         }
  3096.       }
  3097.     },
  3098.     /**
  3099.      * See nsISupports.idl
  3100.      */
  3101.     QueryInterface: function(iid) {
  3102.       if (!iid.equals(Components.interfaces.nsIAddonUpdateCheckListener) &&
  3103.           !iid.equals(Components.interfaces.nsISupports))
  3104.         throw Components.results.NS_ERROR_NO_INTERFACE;
  3105.       return this;
  3106.     }
  3107.   };
  3108.   
  3109.   if (!isCompatible(update)) {
  3110.     var em = 
  3111.         Components.classes["@mozilla.org/extensions/manager;1"].
  3112.         getService(Components.interfaces.nsIExtensionManager);
  3113.     var listener = new Listener(em.getIncompatibleItemList("", 
  3114.       update.extensionVersion, nsIUpdateItem.TYPE_ADDON, false, { }));
  3115.     // See documentation on |mode| above. 
  3116.     var mode = getPref("getIntPref", PREF_APP_UPDATE_INCOMPATIBLE_MODE, 
  3117.                        INCOMPATIBLE_MODE_NEWVERSIONS);
  3118.     em.update([], 0, mode != 0, listener);
  3119.   }
  3120.   else
  3121. //@line 3096 "/cygdrive/c/builds/tinderbox/Fx-Mozilla1.8-Release/WINNT_5.2_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  3122.     showPrompt(update);
  3123. }
  3124.