home *** CD-ROM | disk | FTP | other *** search
/ PC Welt 2006 November (DVD) / PCWELT_11_2006.ISO / casper / filesystem.squashfs / usr / lib / firefox / components / nsUpdateService.js < prev    next >
Encoding:
Text File  |  2006-08-18  |  93.0 KB  |  2,899 lines

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