home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2007 September / PCWSEP07.iso / Software / Linux / Linux Mint 3.0 Light / LinuxMint-3.0-Light.iso / casper / filesystem.squashfs / usr / lib / firefox / components / nsUpdateService.js < prev    next >
Encoding:
Text File  |  2007-04-03  |  98.5 KB  |  3,044 lines

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