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