home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2011 February / maximum-cd-2011-02.iso / DiscContents / Miro_Installer.exe / xulrunner / components / nsUpdateService.js < prev    next >
Encoding:
Text File  |  2010-08-30  |  112.3 KB  |  3,393 lines

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