home *** CD-ROM | disk | FTP | other *** search
/ PC go! 2008 October / PCgo 2008-10 (DVD).iso / interface / contents / vollversionen_6617 / 21733 / files / xulrunner / components / nsUpdateService.js < prev    next >
Encoding:
Text File  |  2008-08-20  |  109.6 KB  |  3,313 lines

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